From 255977e304b59b4a1e8ede9e490ca78fefd6ef31 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 20 Nov 2026 04:12:39 -0500 Subject: [PATCH 001/153] Align menus and default UI with the context-menu plan Match menu labels, defaults, checkmarks, toolbar visibility and Help links. Add recent-project limits, per-mode layouts and session log actions. Make dialogs movable and resizable with consistent titles and scrollbar clearance. Validation: release app build succeeded and preview opened. Full tests and screenshots were not rerun at the user's request. --- ATTRIBUTION.md | 10 + Cargo.lock | 59 ++++ NOTICE | 7 + apps/texturecraft/Cargo.toml | 2 +- crates/ui-egui/src/color_selection_editor.rs | 2 +- crates/ui-egui/src/control.rs | 3 + crates/ui-egui/src/docking.rs | 18 +- crates/ui-egui/src/export_templates.rs | 27 +- crates/ui-egui/src/export_window.rs | 198 +++++++------- crates/ui-egui/src/generator_panel.rs | 3 +- crates/ui-egui/src/import_resources.rs | 215 ++++++++------- crates/ui-egui/src/keymap.rs | 9 +- crates/ui-egui/src/lib.rs | 31 ++- crates/ui-egui/src/menus.rs | 200 +++++++------- crates/ui-egui/src/mesh_export_options.rs | 2 +- crates/ui-egui/src/mode_layout.rs | 59 ++++ crates/ui-egui/src/named_layouts.rs | 29 +- crates/ui-egui/src/new_project_advanced.rs | 53 ++-- crates/ui-egui/src/pbr_import.rs | 2 +- crates/ui-egui/src/project_config.rs | 252 +++++++++--------- crates/ui-egui/src/session_log_file.rs | 98 +++++++ crates/ui-egui/src/settings_window.rs | 142 +++++----- crates/ui-egui/src/state.rs | 28 ++ crates/ui-egui/src/toolbar.rs | 37 +-- crates/ui-egui/src/ui_state_store.rs | 3 +- crates/ui-egui/src/updates_ui.rs | 4 +- crates/ui-egui/src/windows.rs | 96 +++++-- crates/ui-egui/tests/it/camera_views.rs | 10 +- .../tests/it/color_selection_editor.rs | 2 +- crates/ui-egui/tests/it/empty_menus.rs | 139 ++++++++++ crates/ui-egui/tests/it/empty_start.rs | 17 +- crates/ui-egui/tests/it/help_menu_664.rs | 12 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/named_layouts.rs | 29 +- crates/ui-egui/tests/it/new_project_window.rs | 2 +- crates/ui-egui/tests/it/reference_order.rs | 14 +- crates/ui-egui/tests/it/settings_window.rs | 28 ++ crates/ui-egui/tests/it/shortcut_list.rs | 30 +-- crates/ui-egui/tests/it/templates_681.rs | 12 +- crates/ui-egui/tests/it/toolbar.rs | 8 +- crates/ui-egui/tests/it/window_menu_684.rs | 40 ++- crates/ui-egui/tests/ui_snapshots.rs | 34 ++- docs/control-protocol.md | 26 +- docs/parity.md | 105 +++----- 44 files changed, 1346 insertions(+), 752 deletions(-) create mode 100644 crates/ui-egui/src/mode_layout.rs create mode 100644 crates/ui-egui/src/session_log_file.rs create mode 100644 crates/ui-egui/tests/it/empty_menus.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 5d607a5c..6d8f3963 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -46,3 +46,13 @@ Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedur (`crates/paint/src/brush.rs`), meshes (`crates/geom/src/primitives.rs`) and shelf thumbnails (`crates/ui-egui/src/thumbs.rs`) are generated in code by TextureCraft contributors (MIT OR Apache-2.0). None of them is derived from another product's presets, shaders, materials or images. + +## Default-browser integration dependencies + +The desktop app enables eframe's `links` feature. These unmodified Rust dependencies open links in the system browser and parse their URLs; their upstream MIT and Apache-2.0 licence files remain in the published crates. + +| Dependency | Source | License | +|---|---|---| +| `webbrowser` 1.2.7 | https://github.com/amodm/webbrowser-rs | MIT OR Apache-2.0 | +| `url` 2.5.8, `idna` 1.1.0, `form_urlencoded` 1.2.2 | https://github.com/servo/rust-url | MIT OR Apache-2.0 | +| `idna_adapter` 1.2.2 | https://github.com/hsivonen/idna_adapter | Apache-2.0 OR MIT | diff --git a/Cargo.lock b/Cargo.lock index 4faf24bb..8d3b7afc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1423,6 +1423,7 @@ dependencies = [ "raw-window-handle", "serde", "web-time", + "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -1744,6 +1745,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "fs-set-times" version = "0.20.3" @@ -2400,6 +2410,27 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "image" version = "0.25.10" @@ -5184,6 +5215,18 @@ dependencies = [ "log", ] +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "urlencoding" version = "2.1.3" @@ -5485,6 +5528,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + [[package]] name = "webpki-root-certs" version = "1.0.11" diff --git a/NOTICE b/NOTICE index a6c9da4b..39ead11d 100644 --- a/NOTICE +++ b/NOTICE @@ -25,3 +25,10 @@ in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (Inter and BIZ UDPGothic on desktop and web, Noto Sans CJK SC on desktop), under the SIL Open Font License 1.1. Their licence texts ship with the package as OFL-.txt. + +Default-browser integration (eframe's links feature): +webbrowser 1.2.7 — MIT OR Apache-2.0, https://github.com/amodm/webbrowser-rs. +url 2.5.8, idna 1.1.0 and form_urlencoded 1.2.2 — MIT OR Apache-2.0, +https://github.com/servo/rust-url. +idna_adapter 1.2.2 — Apache-2.0 OR MIT, https://github.com/hsivonen/idna_adapter. +These dependencies are used unmodified; their published crates retain the upstream licence files. diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index e3fb936a..3043fb11 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -15,7 +15,7 @@ texturecraft-engine = { workspace = true } texturecraft-ui-egui = { workspace = true } # The control channel's token, framing and connection limits (shared with `texturecraft-cli serve`). texturecraft-automation = { workspace = true } -eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] } +eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence", "links"] } egui = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } diff --git a/crates/ui-egui/src/color_selection_editor.rs b/crates/ui-egui/src/color_selection_editor.rs index 6bb0e6e6..482bc227 100644 --- a/crates/ui-egui/src/color_selection_editor.rs +++ b/crates/ui-egui/src/color_selection_editor.rs @@ -32,7 +32,7 @@ pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index); let has_id_map = app.session.baked(set_index).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Id)); if !has_id_map { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (Ctrl+Shift+B) to pick colors from the mesh."))).color(tokens.warning)); + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (F8) to pick colors from the mesh."))).color(tokens.warning)); } let picking = app.picking_id_color.filter(|pick| pick.effect == effect); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6b471ff5..79050e12 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -92,6 +92,7 @@ fn refresh_draft_preferences(draft: &mut Prefs, previous: &Prefs, current: &Pref refresh_fields!( ui_scale, autosave_minutes, + recent_projects_limit, language, viewport_texture, brightness, @@ -227,6 +228,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para .map(|item| json!({ "menu": item.menu, "submenu": item.sub, "label": item.label, "id": item.id, "shortcut": crate::keymap::shortcut_of(&app.ui.keymap, item.id), "implemented": crate::menus::implemented(item.id), "enabled": crate::menus::enabled(app, item.id), + "checked": crate::menus::checked(app, item.id), })) .collect::>() )), @@ -283,6 +285,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para refresh_draft_preferences(&mut draft.prefs, &app.ui.prefs, &ui.prefs); } + ui.trim_recent(); app.ui = ui; app.reschedule_autosave_if_changed(previous_autosave_minutes); app.ui.prefs.apply_resource_limits(); diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index d779bf77..296c1830 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -38,14 +38,16 @@ pub enum Panel { Shader, History, Log, + BakingLog, Export, /// The path tracer's settings (Window ▸ Views ▸ Renderer Settings, Rendering mode only) Renderer, } /// Window ▸ Views items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 14] = [ +pub const VIEWS: [(&str, Panel); 15] = [ ("ui.view.assets", Panel::Assets), + ("ui.view.bakingLog", Panel::BakingLog), ("ui.view.bakeMaps", Panel::MeshMapSettings), ("ui.view.bakeSettings", Panel::CommonSettings), ("ui.view.display", Panel::Display), @@ -74,7 +76,7 @@ impl Panel { pub(crate) fn available_in(self, mode: crate::state::Mode) -> bool { use crate::state::Mode; match self { - Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers => mode == Mode::Baking, + Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers | Self::BakingLog => mode == Mode::Baking, Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings | Self::Export => mode == Mode::Painting, Self::History => mode != Mode::Rendering, Self::Shader => mode != Mode::Baking, @@ -83,7 +85,7 @@ impl Panel { } } - pub const ALL: [Panel; 15] = [ + pub const ALL: [Panel; 16] = [ Panel::Viewport, Panel::Assets, Panel::MeshMapSettings, @@ -97,6 +99,7 @@ impl Panel { Panel::Shader, Panel::History, Panel::Log, + Panel::BakingLog, Panel::Export, Panel::Renderer, ]; @@ -116,6 +119,7 @@ impl Panel { Panel::Shader => "Shader Settings", Panel::History => "History", Panel::Log => "Log", + Panel::BakingLog => "Baking Log", Panel::Export => "Export", Panel::Renderer => "Renderer Settings", } @@ -130,6 +134,7 @@ impl Panel { Panel::Log => 3.0, Panel::Export => 4.0, Panel::Renderer => 5.0, + Panel::BakingLog => 6.0, _ => return None, }; Some([960.0, 90.0 + 50.0 * slot, 300.0, 380.0]) @@ -524,6 +529,13 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::Shader => crate::shader_settings::body(app, ui), Panel::History => crate::windows::history(app, ui), Panel::Log => crate::log_panel::body(app, ui), + Panel::BakingLog => { + egui::ScrollArea::vertical().show(ui, |ui| { + for entry in app.session.log.entries().iter().filter(|entry| entry.source == "Baker") { + ui.label(entry.line()); + } + }); + } Panel::Export => crate::export_panel::body(app, ui), Panel::Renderer => crate::render_mode::settings_body(app, ui), Panel::Viewport => {} diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index c1c0eddc..061c31cf 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -423,13 +423,13 @@ pub(crate) fn ask(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut yes = false; let (title, text, yes_label, no_label) = match &question { Ask::Delete(name) => ( - tr("Delete template"), + tr("Delete Template"), trf("Delete the template \"{name}\"? Its file is removed and this cannot be undone.", &[("name", name)]), tr("Delete"), tr("Cancel"), ), Ask::Leave(_) => ( - tr("Unfinished template edit"), + tr("Unfinished Template Edit"), trf( "The last edit of the template \"{name}\" is not saved: {error}. Switching away drops it.", &[("name", &app.ui.export.preset), ("error", &unfinished(app).unwrap_or_default())], @@ -438,27 +438,22 @@ pub(crate) fn ask(app: &mut TextureCraftApp, ctx: &egui::Context) { tr("Keep editing"), ), }; - egui::Window::new(title) - .id(egui::Id::unique("export_template_ask")) - .collapsible(false) - .resizable(false) - .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) - .show(ctx, |ui| { - ui.set_max_width(360.0); - ui.label(text); - ui.add_space(8.0); - ui.horizontal(|ui| { - yes = ui.button(yes_label).clicked(); - cancel |= ui.button(no_label).clicked(); - }); + let mut open = true; + crate::windows::dialog(ctx, "export_template_ask", title, &mut open).default_width(360.0).show(ctx, |ui| { + ui.label(text); + ui.add_space(8.0); + ui.horizontal(|ui| { + yes = ui.button(yes_label).clicked(); + cancel |= ui.button(no_label).clicked(); }); + }); if yes { app.ui.export.ask = None; match question { Ask::Delete(name) => remove(app, name), Ask::Leave(act) => perform(app, ctx, act), } - } else if cancel { + } else if cancel || !open { app.ui.export.ask = None; } } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 37590454..94be39c0 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -717,7 +717,7 @@ fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { } // Many texture sets scroll inside the list; the footer stays in view - let list_height = BODY_HEIGHT - header.rect.height() - ui.spacing().item_spacing.y; + let list_height = ui.available_height(); egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); } @@ -1204,107 +1204,121 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(900.0, 520.0)).show(ctx, |ui| { + crate::windows::dialog(ctx, "export_textures", tr("Export Textures"), &mut open).default_size(vec2(900.0, BODY_HEIGHT + 80.0)).show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { ui.label(tr("No project is open")); return; } - ui.horizontal(|ui| { - for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if ui.selectable_label(app.ui.export.tab == i as u8, caption(&t.to_uppercase())).clicked() { - app.ui.export.tab = i as u8; - } - } - - // The file list opens the destination folder - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if app.ui.export.tab == 2 { - // The browser downloads the files instead - #[cfg(target_arch = "wasm32")] - crate::unavailable::greyed(ui, |ui| ui.button(tr("Open output directory"))); - #[cfg(not(target_arch = "wasm32"))] - if ui.button(tr("Open output directory")).clicked() { - open_output_directory(app); - } - } else if ui.button(tr("Include all")).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { - app.ui.export.skip.clear(); - for o in app.ui.export.sets.values_mut() { - o.maps.values_mut().for_each(|m| m.enabled = true); - } - app.ui.export.sets.retain(|_, o| !o.is_default()); - } - }); - }); - ui.separator(); - ui.allocate_ui_with_layout(vec2(ui.available_width(), BODY_HEIGHT), egui::Layout::left_to_right(egui::Align::Min), |ui| { - ui.set_height(BODY_HEIGHT); - match app.ui.export.tab { - 1 => { - crate::export_templates::tab(app, ui, &presets); - return; - } - 2 => { - list_tab(app, ui); - return; - } - _ => {} - } - - ui.vertical(|ui| { - ui.set_width(LIST_WIDTH); - set_list(app, ui); - }); - ui.separator(); - ui.vertical(|ui| match app.ui.export.page { - Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), - _ => global_page(app, ui, &presets), - }); - }); - ui.add_space(8.0); - ui.separator(); - - // While exporting: the progress and Cancel Export - if let Some(job) = &app.ui.export.job { - let done = job.total - job.pending.len(); - let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Cancel Export")).clicked() { - app.ui.export.job = None; - } - let percent = format!("{:.0}%", progress * 100.0); - ui.add(egui::ProgressBar::new(progress).text(percent)); + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + // While exporting: the progress and Cancel Export + if let Some(job) = &app.ui.export.job { + let done = job.total - job.pending.len(); + let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Cancel Export")).clicked() { + app.ui.export.job = None; + } + let percent = format!("{:.0}%", progress * 100.0); + ui.add(egui::ProgressBar::new(progress).text(percent)); + }); }); - }); - return; - } + } else { + let selected = selected_texture_count(app); + ui.horizontal(|ui| { + // Not on LIST OF EXPORTS + if app.ui.export.tab != 2 && ui.button(tr("Reset all")).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() + { + // Keep ownership so Cancel can restore the opening settings + let e = &mut app.ui.export; + let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); + app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // Nothing to write without a ticked texture set + let any = !export_selection(app).is_empty(); + if ui + .add_enabled(any, primary_button(ui, tr("Export"))) + .on_hover_text(tr("Write the selected textures using the settings above")) + .clicked() + { + do_export = true; + } - let selected = selected_texture_count(app); - ui.horizontal(|ui| { - // Not on LIST OF EXPORTS - if app.ui.export.tab != 2 && ui.button(tr("Reset all")).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() { - // Keep ownership so Cancel can restore the opening settings - let e = &mut app.ui.export; - let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); - app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; + // Saving closes the window without starting an export + if ui.button(tr("Save settings")).on_hover_text(tr("Keep these settings for the next export")).clicked() { + app.ui.windows.export = false; + } + if ui.button(tr("Cancel")).on_hover_text(tr("Restore the settings from when you opened this window")).clicked() { + canceled = true; + } + ui.label(trf("{n} textures selected for export", &[("n", &selected)])); + }); + }); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Nothing to write without a ticked texture set - let any = !export_selection(app).is_empty(); - if ui.add_enabled(any, primary_button(ui, tr("Export"))).on_hover_text(tr("Write the selected textures using the settings above")).clicked() { - do_export = true; - } + ui.separator(); + ui.add_space(8.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { + if ui.selectable_label(app.ui.export.tab == i as u8, caption(&t.to_uppercase())).clicked() { + app.ui.export.tab = i as u8; + } + } - // Saving closes the window without starting an export - if ui.button(tr("Save settings")).on_hover_text(tr("Keep these settings for the next export")).clicked() { - app.ui.windows.export = false; - } - if ui.button(tr("Cancel")).on_hover_text(tr("Restore the settings from when you opened this window")).clicked() { - canceled = true; - } - ui.label(trf("{n} textures selected for export", &[("n", &selected)])); + // The file list opens the destination folder + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if app.ui.export.tab == 2 { + // The browser downloads the files instead + #[cfg(target_arch = "wasm32")] + crate::unavailable::greyed(ui, |ui| ui.button(tr("Open output directory"))); + #[cfg(not(target_arch = "wasm32"))] + if ui.button(tr("Open output directory")).clicked() { + open_output_directory(app); + } + } else if ui.button(tr("Include all")).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { + app.ui.export.skip.clear(); + for o in app.ui.export.sets.values_mut() { + o.maps.values_mut().for_each(|m| m.enabled = true); + } + app.ui.export.sets.retain(|_, o| !o.is_default()); + } + }); + }); + ui.separator(); + let body_height = ui.available_height().max(0.0); + ui.allocate_ui_with_layout(vec2(ui.available_width(), body_height), egui::Layout::left_to_right(egui::Align::Min), |ui| { + ui.set_height(body_height); + match app.ui.export.tab { + 1 => { + crate::export_templates::tab(app, ui, &presets); + return; + } + 2 => { + list_tab(app, ui); + return; + } + _ => {} + } + + ui.vertical(|ui| { + ui.set_width(LIST_WIDTH); + set_list(app, ui); + }); + ui.separator(); + ui.vertical(|ui| { + egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false, false]).min_scrolled_height(0.0).show(ui, |ui| match app + .ui + .export + .page + { + Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), + _ => global_page(app, ui, &presets), + }); + }); + }); }); }); }); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 9a6dfae1..d15be0e4 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -59,8 +59,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer } if !app.session.doc.baked.contains_key(&app.session.ts()) { ui.label( - RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (Ctrl+Shift+B) for curvature, AO and thickness based generators."))) - .color(tokens.warning), + RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tokens.warning), ); } } diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs index 629bc90a..b4e1c7b1 100644 --- a/crates/ui-egui/src/import_resources.rs +++ b/crates/ui-egui/src/import_resources.rs @@ -114,113 +114,132 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let (mut import, mut cancel, mut add) = (std::mem::take(&mut window.confirm), false, false); let mut remove = false; - crate::windows::dialog("import_resources", tr("Import resources"), &mut open).default_width(WINDOW_WIDTH_POINTS).show(ctx, |ui| { - ui.set_min_width(WINDOW_WIDTH_POINTS); - ui.horizontal(|ui| { - ui.label(tr("Choose files and assign their roles")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add_enabled_ui(!window.selected.is_empty(), |ui| { - remove = ui.button(tr("Remove selected resources")).clicked(); - }); - add = ui.button(tr("Add resources")).clicked(); - }); - }); - ui.add_space(4.0); - - let all_label = trf("All files ({count})", &[("count", &window.rows.len())]); - let filter_text = match window.filter { - None => all_label.clone(), - Some(usage) => trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|row| row.usage == usage).count())]), - }; - egui::ComboBox::from_id_salt("import_filter").width(ui.available_width()).selected_text(filter_text).show_ui(ui, |ui| { - if ui.selectable_label(window.filter.is_none(), &all_label).clicked() { - window.filter = None; - } - - // Only usages some row has, so the list is never empty by filter - for usage in ResourceUsage::ALL { - let count = window.rows.iter().filter(|row| row.usage == usage).count(); - if count > 0 && ui.selectable_label(window.filter == Some(usage), format!("{} ({count})", usage.name())).clicked() { - window.filter = Some(usage); - } - } - }); - ui.add_space(4.0); - - let filter = window.filter; - let visible = |row: &ImportRow| filter.is_none_or(|usage| row.usage == usage); - let modifiers = ui.input(|i| i.modifiers); - let mut clicked = None; - - egui::ScrollArea::vertical().min_scrolled_height(LIST_HEIGHT_POINTS).max_height(LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| { - for row in window.rows.iter_mut().filter(|row| visible(row)) { - let material = is_material(row); - let selected = window.selected.contains(&row.id); + crate::windows::dialog(ctx, "import_resources", tr("Import Resources"), &mut open) + .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + 200.0)) + .show(ctx, |ui| { + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { ui.horizontal(|ui| { - let name_width = - (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x).max(MIN_NAME_WIDTH_POINTS); - let name = ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate()); - if name.on_hover_text(row.path.display().to_string()).clicked() { - clicked = Some(row.id); - } - - let prefix = ui.add_enabled( - !material, - egui::TextEdit::singleline(&mut row.prefix).hint_text(tr("Optional prefix/path...")).desired_width(PREFIX_WIDTH_POINTS), - ); - if material { - prefix.on_disabled_hover_text(tr("Materials keep their own name")); - } else { - prefix.on_hover_text(tr("Put in front of the resource's name. Characters other than letters, digits and _ . - become _")); - } - - ui.add_enabled_ui(!material, |ui| { - egui::ComboBox::from_id_salt(("import_usage", row.id)).width(USAGE_WIDTH_POINTS).selected_text(row.usage.name()).show_ui(ui, |ui| { - for usage in ResourceUsage::ALL { - let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name())); - if usage.available() { - if item.clicked() { - row.usage = usage; - ui.close(); - } - } else { - item.on_disabled_hover_text(tr("Not available yet")); - } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel = ui.button(tr("Cancel")).clicked(); + import |= ui.add_enabled(app.session.project_open && !window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); + }); + }); + ui.add_space(4.0); + if !app.session.project_open { + ui.label(tr("Open a project to import resources. Importing into the asset library is not available yet.")); + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + egui::ComboBox::from_id_salt("import_target").width(TARGET_WIDTH_POINTS).selected_text(tr("Open project")).show_ui(ui, |ui| { + if ui.selectable_label(true, tr("Open project")).clicked() { + ui.close(); } + + ui.add_enabled(false, egui::Button::selectable(false, tr("Asset library"))).on_disabled_hover_text(tr("Not available yet")); }); - }) - .response - .on_disabled_hover_text(tr("Materials need no usage")); + ui.label(tr("Destination")); + }); }); - } - }); + ui.add_space(8.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + ui.label(tr("Choose files and assign their roles")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(!window.selected.is_empty(), |ui| { + remove = ui.button(tr("Remove selected resources")).clicked(); + }); + add = ui.button(tr("Add resources")).clicked(); + }); + }); + ui.add_space(4.0); - if let Some(id) = clicked { - let visible: Vec = if modifiers.shift { window.rows.iter().filter(|row| visible(row)).map(|row| row.id).collect() } else { Vec::new() }; - click_row(&mut window, &visible, id, modifiers); - } + let all_label = trf("All files ({count})", &[("count", &window.rows.len())]); + let filter_text = match window.filter { + None => all_label.clone(), + Some(usage) => { + trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|row| row.usage == usage).count())]) + } + }; + egui::ComboBox::from_id_salt("import_filter").width(ui.available_width()).selected_text(filter_text).show_ui(ui, |ui| { + if ui.selectable_label(window.filter.is_none(), &all_label).clicked() { + window.filter = None; + } - ui.add_space(8.0); - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - egui::ComboBox::from_id_salt("import_target").width(TARGET_WIDTH_POINTS).selected_text(tr("Open project")).show_ui(ui, |ui| { - if ui.selectable_label(true, tr("Open project")).clicked() { - ui.close(); + // Only usages some row has, so the list is never empty by filter + for usage in ResourceUsage::ALL { + let count = window.rows.iter().filter(|row| row.usage == usage).count(); + if count > 0 && ui.selectable_label(window.filter == Some(usage), format!("{} ({count})", usage.name())).clicked() { + window.filter = Some(usage); + } + } + }); + ui.add_space(4.0); + + let filter = window.filter; + let visible = |row: &ImportRow| filter.is_none_or(|usage| row.usage == usage); + let modifiers = ui.input(|i| i.modifiers); + let mut clicked = None; + + let list_height = ui.available_height().max(0.0); + egui::ScrollArea::both().min_scrolled_width(0.0).min_scrolled_height(0.0).max_height(list_height).auto_shrink([false, false]).show( + ui, + |ui| { + for row in window.rows.iter_mut().filter(|row| visible(row)) { + let material = is_material(row); + let selected = window.selected.contains(&row.id); + ui.horizontal(|ui| { + let name_width = (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x) + .max(MIN_NAME_WIDTH_POINTS); + let name = + ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate()); + if name.on_hover_text(row.path.display().to_string()).clicked() { + clicked = Some(row.id); + } + + let prefix = ui.add_enabled( + !material, + egui::TextEdit::singleline(&mut row.prefix).hint_text(tr("Optional prefix/path...")).desired_width(PREFIX_WIDTH_POINTS), + ); + if material { + prefix.on_disabled_hover_text(tr("Materials keep their own name")); + } else { + prefix + .on_hover_text(tr("Put in front of the resource's name. Characters other than letters, digits and _ . - become _")); + } + + ui.add_enabled_ui(!material, |ui| { + egui::ComboBox::from_id_salt(("import_usage", row.id)) + .width(USAGE_WIDTH_POINTS) + .selected_text(row.usage.name()) + .show_ui(ui, |ui| { + for usage in ResourceUsage::ALL { + let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name())); + if usage.available() { + if item.clicked() { + row.usage = usage; + ui.close(); + } + } else { + item.on_disabled_hover_text(tr("Not available yet")); + } + } + }); + }) + .response + .on_disabled_hover_text(tr("Materials need no usage")); + }); + } + }, + ); + + if let Some(id) = clicked { + let visible: Vec = + if modifiers.shift { window.rows.iter().filter(|row| visible(row)).map(|row| row.id).collect() } else { Vec::new() }; + click_row(&mut window, &visible, id, modifiers); } - - ui.add_enabled(false, egui::Button::selectable(false, tr("Asset library"))).on_disabled_hover_text(tr("Not available yet")); }); - ui.label(tr("Destination")); }); }); - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - cancel = ui.button(tr("Cancel")).clicked(); - import |= ui.add_enabled(!window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); - }); - }); - }); if cancel || !open { return; @@ -250,7 +269,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); } - if import && !window.rows.is_empty() { + if import && app.session.project_open && !window.rows.is_empty() { window.rows.retain(|row| !import_row(app, row)); if window.rows.is_empty() { app.ui.dock.focus(crate::docking::Panel::Assets); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 0a664136..ee29ac48 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -55,7 +55,7 @@ const LISTED_SHORTCUTS: &[ShortcutListEntry] = &[ ShortcutListEntry::new("ui.quit", "Quit application", Some("Ctrl+Q")), ShortcutListEntry::new("ui.export", "Export Textures...", Some("Ctrl+Shift+E")), ShortcutListEntry::new("file.reimportMesh", "Reimport mesh", Some("Ctrl+Shift+R")), - ShortcutListEntry::new("ui.mode.bake", "Switch to baking mode", Some("Ctrl+Shift+B")), + ShortcutListEntry::new("ui.mode.bake", "Switch to baking mode", Some("F8")), ShortcutListEntry::new("ui.mode.paint", "Switch to edition mode", Some("F9")), ShortcutListEntry::new("ui.mode.render", "Switch to rendering mode (path traced)", Some("F10")), ShortcutListEntry::new("ui.wireframe", "Show mesh wireframe", None), @@ -76,6 +76,11 @@ const LISTED_SHORTCUTS: &[ShortcutListEntry] = &[ ShortcutListEntry::new("ui.layout.3d", "Viewers layout: 3D only", Some("F2")), ShortcutListEntry::new("ui.layout.2d", "Viewers layout: 2D only", Some("F3")), ShortcutListEntry::new("ui.layout.swap", "Viewers layout: Swap 3D/2D", Some("F4")), + ShortcutListEntry::new("ui.layout.saveAs", "Save current layout as...", None), + ShortcutListEntry::new("ui.layout.manage", "Manage layouts...", None), + ShortcutListEntry::new("ui.resetPanelLayout", "Reset panel layout", None), + ShortcutListEntry::new("ui.navButtons", "Navigation buttons", None), + ShortcutListEntry::new("ui.uvChecker", "UV checker", None), ]; /// The menu a command without a menu entry is listed under, from its id. @@ -515,7 +520,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { app.bindings.sync(&app.ui.keymap, craft_keymap::egui::platform(ctx)); let mut filter: String = ctx.data(|d| d.get_temp(filter_id)).unwrap_or_default(); let mut open = true; - crate::windows::window("keyboard_shortcuts", tr("Keyboard shortcuts"), &mut open).default_width(480.0).show(ctx, |ui| { + crate::windows::window("keyboard_shortcuts", tr("Keyboard Shortcuts"), &mut open).default_width(480.0).show(ctx, |ui| { ui.horizontal(|ui| { ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); ui.add(egui::TextEdit::singleline(&mut filter).hint_text(tr("Search commands or keys")).desired_width(300.0)); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3df3eb31..4492be15 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -54,6 +54,8 @@ mod mask_preview_image; mod material_preview_image; pub mod menus; mod mesh_export_options; +#[cfg(not(target_arch = "wasm32"))] +mod mode_layout; mod name_error; mod named_layout; pub mod named_layouts; @@ -90,6 +92,8 @@ mod running_bake; pub mod saved_search; mod screen_color_pick; mod section_page; +#[cfg(not(target_arch = "wasm32"))] +mod session_log_file; pub mod settings_window; pub mod shader_settings; pub mod shelf; @@ -191,6 +195,8 @@ pub struct Toast { pub struct TextureCraftApp { pub session: Session, + #[cfg(not(target_arch = "wasm32"))] + pub(crate) session_log_file: Option, /// A smooth move to a saved camera in progress. camera_glide: Option, /// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`). @@ -304,6 +310,7 @@ impl TextureCraftApp { // 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 mut ui = start_ui(ui_store.load(cc.storage), &mut session); + ui.trim_recent(); // No window opens by itself with no project (a saved layout may have left Export open) if !session.project_open { @@ -319,6 +326,8 @@ impl TextureCraftApp { uv_rotation_snap: None, uv_view_reset: false, session, + #[cfg(not(target_arch = "wasm32"))] + session_log_file: None, ui, ui_store, gpu, @@ -371,6 +380,17 @@ impl TextureCraftApp { if cc.winit_window().is_none() { app.file_dialogs.without_window(); } + #[cfg(not(target_arch = "wasm32"))] + if cc.winit_window().is_some() { + let path = crate::data_dir() + .join("logs") + .join(format!("session-{}-{}", chrono::Utc::now().format("%Y%m%dT%H%M%S%.6fZ"), std::process::id())) + .join("log.txt"); + match session_log_file::SessionLogFile::new(path) { + Ok(file) => app.session_log_file = Some(file), + Err(error) => app.toast(format!("{}: {error}", i18n::tr("Could not create the session log")), true), + } + } app.ui.rename = None; app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); @@ -1037,6 +1057,13 @@ impl eframe::App for TextureCraftApp { } profile::drive(self, ctx); self.toasts.retain(|t| t.until > now); + #[cfg(not(target_arch = "wasm32"))] + if let Some(file) = &mut self.session_log_file + && let Err(error) = file.sync(self.session.log_id, self.session.log.entries()) + { + self.session_log_file = None; + self.toast(format!("{}: {error}", i18n::tr("Could not update the session log")), true); + } self.profiler.logic_ms = (now_ms() - t0) as f32; // Last, so it sees every close request this frame's work made @@ -1057,9 +1084,7 @@ impl eframe::App for TextureCraftApp { titlebar::show(self, ui); banner(self, ui); toolbar::status_bar(self, ui); - if self.ui.toolbar_tools { - toolbar::tool_shelf(self, ui); - } + toolbar::tool_shelf(self, ui); self.ui.sync_mode_dock(); if self.ui.mode != state::Mode::Baking && self.ui.toolbar_docks { toolbar::rail(self, ui); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7ec42c75..8ea0035f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -2,7 +2,7 @@ //! texture-painting workflow, with stable ids; an item is live when the engine (or the shell, for `ui.*` ids) implements //! its id. The same catalog drives `docs/parity.md`. -use egui::{Key, Modifiers}; +use egui::{Key, Modifiers, class::HasClasses as _}; use serde_json::{Value, json}; use texturecraft_engine::Tool; @@ -36,38 +36,36 @@ pub const TOP: [&str; 6] = ["File", "Edit", "Mode", "Window", "Viewport", "Help" /// The menu catalog (the target menu tree with our ids). pub const CATALOG: &[Item] = &[ - it("File", "New project...", "ui.newProject", Some("Ctrl+N")), - it("File", "Open...", "file.open", Some("Ctrl+O")), + it("File", "New Project", "ui.newProject", Some("Ctrl+N")), + it("File", "Open", "file.open", Some("Ctrl+O")), + sub("File", "Recent Projects", "Clear", "ui.recent.clear", None), sep("File"), - it("File", "Open sample project...", "project.sample", None), + it("File", "Open Sample Project", "project.sample", None), sep("File"), it("File", "Close", "file.close", Some("Ctrl+F4")), sep("File"), it("File", "Save", "file.save", Some("Ctrl+S")), - it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")), - sub("File", "More save options", "Save as template...", "ui.saveAsTemplate", None), - sub("File", "More save options", "Save and reduce file size", "ui.saveReduced", None), - sub("File", "More save options", "Save as copy...", "file.saveCopy", None), - it("File", "Remove unused resources...", "file.removeUnused", None), + it("File", "Save As", "file.saveAs", Some("Ctrl+Shift+S")), + sub("File", "More Save Options", "Save As Template", "ui.saveAsTemplate", None), + sub("File", "More Save Options", "Save and Reduce File Size", "ui.saveReduced", None), + sub("File", "More Save Options", "Save As Copy", "file.saveCopy", None), + it("File", "Remove Unused Resources", "file.removeUnused", None), sep("File"), - it("File", "Import resources...", "resource.import", None), - it("File", "Import MaterialX material...", "file.importMaterialX", None), - #[cfg(not(target_arch = "wasm32"))] - it("File", "Import PBR texture folder...", "file.importPbrFolder", None), - it("File", "Import material...", "material.load", None), - it("File", "Export Textures...", "ui.export", Some("Ctrl+Shift+E")), - it("File", "Export Mesh...", "file.exportMesh", None), + it("File", "Import Resources", "resource.import", None), + it("File", "Export Textures", "ui.export", Some("Ctrl+Shift+E")), + it("File", "Export Mesh", "file.exportMesh", None), sep("File"), it("File", "Quit", "ui.quit", Some("Ctrl+Q")), it("Edit", "Undo", "edit.undo", Some("Ctrl+Z")), it("Edit", "Redo", "edit.redo", Some("Ctrl+Y")), - it("Edit", "Project Configuration...", "ui.projectConfig", None), - it("Edit", "Reimport mesh", "file.reimportMesh", Some("Ctrl+Shift+R")), - it("Edit", "Settings...", "ui.settings", None), - it("Mode", "Bake Mesh Maps", "ui.mode.bake", Some("Ctrl+Shift+B")), + it("Edit", "Project Configuration", "ui.projectConfig", None), + it("Edit", "Reimport Mesh", "file.reimportMesh", Some("Ctrl+Shift+R")), + it("Edit", "Settings", "ui.settings", None), + it("Mode", "Bake Mesh Maps", "ui.mode.bake", Some("F8")), it("Mode", "Painting", "ui.mode.paint", Some("F9")), - it("Mode", "Rendering (path traced)", "ui.mode.render", Some("F10")), + it("Mode", "Rendering", "ui.mode.render", Some("F10")), sub("Window", "Views", "Assets", "ui.view.assets", None), + sub("Window", "Views", "Baking Log", "ui.view.bakingLog", None), sub("Window", "Views", "Common Settings", "ui.view.bakeSettings", None), sub("Window", "Views", "Display Settings", "ui.view.display", None), sub("Window", "Views", "Export", "ui.view.export", None), @@ -77,68 +75,43 @@ pub const CATALOG: &[Item] = &[ 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", "Python Console", "ui.view.pythonConsole", None), sub("Window", "Views", "Renderer Settings", "ui.view.renderer", None), sub("Window", "Views", "Shader Settings", "ui.view.shader", None), - sub("Window", "Views", "Online assets", "ui.view.onlineAssets", None), - sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), + sub("Window", "Views", "Texture Set List", "ui.view.textureSetList", None), sub("Window", "Views", "Texture Set Settings", "ui.view.textureSetSettings", None), sub("Window", "Toolbars", "Docks", "ui.toolbar.docks", None), - sub("Window", "Toolbars", "Plugins", "ui.toolbar.plugins", None), sub("Window", "Toolbars", "Tools", "ui.toolbar.tools", None), sep("Window"), - sub("Window", "Save UI Layout", "Painting mode", "ui.layout.save.painting", None), - sub("Window", "Save UI Layout", "Rendering mode", "ui.layout.save.rendering", None), - sub("Window", "Save UI Layout", "Baking mode", "ui.layout.save.baking", None), + sub("Window", "Save UI Layout", "Painting Mode", "ui.layout.save.painting", None), + sub("Window", "Save UI Layout", "Rendering Mode", "ui.layout.save.rendering", None), + sub("Window", "Save UI Layout", "Baking Mode", "ui.layout.save.baking", None), it("Window", "Load UI Layout", "ui.layout.load", None), - sub("Window", "Layouts", "Save current layout as...", "ui.layout.saveAs", None), - sub("Window", "Layouts", "Manage layouts...", "ui.layout.manage", None), sep("Window"), it("Window", "Hide UI", "ui.hideUi", Some("Tab")), - it("Window", "Reset panel layout", "ui.resetPanelLayout", None), it("Window", "Reset UI", "ui.resetUi", None), - it("Viewport", "Display material", "viewport.displayMaterial", Some("M")), - it("Viewport", "Display next channel", "viewport.nextChannel", Some("C")), - it("Viewport", "Display previous channel", "viewport.previousChannel", Some("Shift+C")), - it("Viewport", "Display next mesh map", "viewport.nextMeshMap", Some("B")), - it("Viewport", "Display previous mesh map", "viewport.previousMeshMap", Some("Shift+B")), - it("Viewport", "UV checker", "ui.uvChecker", None), + it("Viewport", "Display Material", "viewport.displayMaterial", Some("M")), + it("Viewport", "Display Next Channel", "viewport.nextChannel", Some("C")), + it("Viewport", "Display Previous Channel", "viewport.previousChannel", Some("Shift+C")), + it("Viewport", "Display Next Mesh Map", "viewport.nextMeshMap", Some("B")), + it("Viewport", "Display Previous Mesh Map", "viewport.previousMeshMap", Some("Shift+B")), sep("Viewport"), - it("Viewport", "Frame texture set", "viewport.frameSelection", Some("Shift+F")), - it("Viewport", "Show entire mesh", "viewport.frame", Some("F")), - it("Viewport", "Front view", "camera.view.front", None), - it("Viewport", "Back view", "camera.view.back", None), - it("Viewport", "Left view", "camera.view.left", None), - it("Viewport", "Right view", "camera.view.right", None), - it("Viewport", "Top view", "camera.view.top", None), - it("Viewport", "Bottom view", "camera.view.bottom", None), + it("Viewport", "Show Entire Mesh/Path", "viewport.frame", Some("F")), sep("Viewport"), - it("Viewport", "Perspective", "camera.perspective", Some("F5")), - it("Viewport", "Orthographic", "camera.orthographic", Some("F6")), - sep("Viewport"), - it("Viewport", "3D/2D views", "ui.layout.split", Some("F1")), - it("Viewport", "3D view only", "ui.layout.3d", Some("F2")), - it("Viewport", "2D view only", "ui.layout.2d", Some("F3")), - it("Viewport", "Swap 3D/2D", "ui.layout.swap", Some("F4")), - sep("Viewport"), - it("Viewport", "Navigation buttons", "ui.navButtons", None), - sep("Viewport"), - it("Viewport", "Enable quick mask", "viewport.quickMask", Some("Y")), - it("Viewport", "Edit quick mask", "viewport.quickMask.edit", Some("U")), - it("Viewport", "Invert quick mask", "viewport.quickMask.invert", Some("Ctrl+Shift+I")), - it("Help", "Release notes...", "ui.help.releaseNotes", None), - it("Help", "Documentation...", "ui.help.docs", None), - it("Help", "Shortcuts list...", "ui.help.shortcuts", None), + it("Viewport", "Enable Quick Mask", "viewport.quickMask", Some("Y")), + it("Viewport", "Edit Quick Mask", "viewport.quickMask.edit", Some("U")), + it("Viewport", "Invert Quick Mask", "viewport.quickMask.invert", Some("Ctrl+Shift+I")), + it("Help", "Release Notes", "ui.help.releaseNotes", None), + it("Help", "Documentation", "ui.help.docs", None), + it("Help", "Shortcuts List", "ui.help.shortcuts", None), sep("Help"), - it("Help", "Join the community (Discord)...", "ui.help.discord", None), - it("Help", "ArtCraft website...", "ui.help.website", None), - it("Help", "Report a bug...", "ui.help.bug", None), - it("Help", "Show log...", "ui.view.log", None), - it("Help", "Export log...", "ui.help.exportLog", None), + it("Help", "Discord", "ui.help.discord", None), + it("Help", "Report a Bug", "ui.help.bug", None), + it("Help", "Show Log", "ui.help.showLog", None), + it("Help", "Export Log", "ui.help.exportLog", None), sep("Help"), #[cfg(not(target_arch = "wasm32"))] - it("Help", "Check for Updates...", "ui.help.checkForUpdates", None), - it("Help", "About TextureCraft...", "ui.about", None), + it("Help", "Check for Updates", "ui.help.checkForUpdates", None), + it("Help", "About TextureCraft", "ui.about", None), ]; /// Ids the shell handles itself. @@ -179,8 +152,17 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { return false; } + if id == "ui.recent.clear" { + return !app.ui.recent.is_empty(); + } + // Opening the import dialog is independent of importing into a project. + #[cfg(not(target_arch = "wasm32"))] + if id == "resource.import" { + return true; + } if let Some(panel) = crate::docking::view_panel(id) { - return panel.available_in(app.ui.mode); + let mode = if app.session.project_open { app.ui.mode } else { Mode::Painting }; + return panel.available_in(mode); } if app.ui.mode != Mode::Painting && (id.starts_with("tool.") || id.starts_with("viewport.quickMask")) { @@ -233,6 +215,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { } match id { + "ui.recent.clear" => app.ui.recent.clear(), "ui.newProject" => crate::new_project_advanced::open(app), "ui.export" => app.ui.windows.export = true, @@ -274,7 +257,14 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.layout.3d" => app.ui.layout = ViewLayout::Only3D, "ui.layout.2d" => app.ui.layout = ViewLayout::Only2D, "ui.layout.swap" => app.ui.swap_views = !app.ui.swap_views, - "ui.help.shortcuts" => app.ui.windows.shortcuts = true, + "ui.help.shortcuts" => { + app.ui.windows.shortcuts = false; + app.ui.windows.settings = true; + app.ui.windows.settings_page = crate::settings_window::SettingsPage::Shortcuts; + if let Some(draft) = &mut app.ui.windows.settings_draft { + draft.page = crate::settings_window::SettingsPage::Shortcuts; + } + } "ui.about" => app.ui.windows.about = true, #[cfg(not(target_arch = "wasm32"))] "ui.help.checkForUpdates" => crate::updates_ui::request_check(app, ctx), @@ -282,6 +272,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.help.website" => ctx.open_url(egui::OpenUrl::new_tab("https://getartcraft.com/apps/texturecraft")), "ui.help.docs" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft#readme")), "ui.help.releaseNotes" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft/releases")), + "ui.help.showLog" => crate::windows::show_log(app, ctx), "ui.help.exportLog" => crate::windows::export_log(app), "ui.help.bug" => ctx.open_url(egui::OpenUrl::new_tab("https://github.com/storytold/texturecraft/issues")), _ => { @@ -311,13 +302,23 @@ pub fn menu_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } current_sub = Some(s); - ui.menu_button(tr(s), |ui| { - for x in items.iter().filter(|x| x.sub == Some(s)) { - menu_item(app, &ctx, ui, x); - } - if s == "Layouts" { - crate::named_layouts::entries(app, ui); - } + let submenu_enabled = s != "More Save Options" || app.session.project_open; + ui.add_enabled_ui(submenu_enabled, |ui| { + ui.menu_button((menu_mark(ui, None), tr(s)), |ui| { + if s == "Recent Projects" { + for path in app.ui.recent.clone() { + if ui.button((menu_mark(ui, None), path.as_str())).clicked() { + #[cfg(not(target_arch = "wasm32"))] + crate::windows::open_path(app, &path); + ui.close(); + } + } + ui.separator(); + } + for x in items.iter().filter(|x| x.sub == Some(s)) { + menu_item(app, &ctx, ui, x); + } + }) }); continue; } @@ -342,12 +343,10 @@ pub fn menu_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } -/// The check mark an item shows: the mode and view items, the toolbars and Hide UI (None: not checkable) +/// The check mark an item shows: view items, toolbars and Hide UI (None: not checkable) pub fn checked(app: &TextureCraftApp, id: &str) -> Option { match id { - "ui.mode.paint" => Some(app.ui.mode == Mode::Painting), - "ui.mode.bake" => Some(app.ui.mode == Mode::Baking), - "ui.mode.render" => Some(app.ui.mode == Mode::Rendering), + "viewport.quickMask" => Some(!app.session.project_open || app.session.quick_mask.enabled), "ui.navButtons" => Some(app.ui.nav_buttons), "ui.hideUi" => Some(app.ui.hide_ui), "ui.toolbar.docks" => Some(app.ui.toolbar_docks), @@ -358,15 +357,32 @@ pub fn checked(app: &TextureCraftApp, id: &str) -> Option { } } +/// Reserve the same checkmark column for actions, submenu headings and recent paths. +fn menu_mark(ui: &egui::Ui, checked: Option) -> egui::Atom<'static> { + egui::Atom::paint(egui::Vec2::splat(ui.spacing().icon_width), move |ui, args| { + if checked == Some(true) { + ui.painter().text( + args.rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::CHECK, + egui::TextStyle::Button.resolve(ui.style()), + args.fallback_text_color, + ); + } + }) +} + fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, item: &Item) { let on = enabled(app, item.id); - let mut b = egui::Button::new(item_label(app, item)); + let checked = checked(app, item.id); + let mut b = egui::Button::new((menu_mark(ui, checked), item_label(app, item))); if let Some(sc) = crate::keymap::shortcut_of(&app.ui.keymap, item.id) { b = b.shortcut_text(sc); } - let checked = checked(app, item.id); if let Some(c) = checked { + // Keep the accessible checked state; the checkmark supplies the visual state. b = b.selected(c); + b.set_class(egui::Button::CLASS_SELECTED, false); } let mut response = ui.add_enabled(on, b); if let Some(tip) = tooltip_of(item.id) { @@ -379,24 +395,6 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, invoke(app, ctx, item.id); ui.close(); } - #[cfg(not(target_arch = "wasm32"))] - if item.id == "file.open" { - ui.add_enabled_ui(!app.ui.recent.is_empty(), |ui| { - ui.menu_button(tr("Recent projects"), |ui| { - for path in app.ui.recent.clone() { - if ui.button(&path).clicked() { - crate::windows::open_path(app, &path); - ui.close(); - } - } - ui.separator(); - if ui.button(tr("Clear recent projects")).clicked() { - app.ui.recent.clear(); - ui.close(); - } - }); - }); - } } /// Global shortcuts: the catalog's and every engine command's (defaults or the user's keymap), diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 3c8a4ef4..1651120a 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -22,7 +22,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut export, mut cancel) = (false, false); - crate::windows::dialog("mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { + crate::windows::dialog(ctx, "mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { // TextureCraft exports the mesh as it is: triangulated, without displacement ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); option(ui, true, tr("Apply triangulation")); diff --git a/crates/ui-egui/src/mode_layout.rs b/crates/ui-egui/src/mode_layout.rs new file mode 100644 index 00000000..5bd7e85d --- /dev/null +++ b/crates/ui-egui/src/mode_layout.rs @@ -0,0 +1,59 @@ +//! A layout file contains one mode's panels and view arrangement, never preferences or recent files. +use crate::{ + docking::Dock, + state::{Mode, UiState, ViewLayout}, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub(crate) struct ModeLayout { + pub mode: Mode, + dock: Dock, + layout: ViewLayout, + swap_views: bool, + split_ratio: f32, + toolbar_docks: bool, + toolbar_tools: bool, +} + +impl ModeLayout { + pub fn of(ui: &UiState, mode: Mode) -> Self { + let mut state = ui.clone(); + state.mode = mode; + state.sync_mode_dock(); + Self { + mode, + dock: state.dock, + layout: state.layout, + swap_views: state.swap_views, + split_ratio: state.split_ratio, + toolbar_docks: state.toolbar_docks, + toolbar_tools: state.toolbar_tools, + } + } + + pub fn apply(self, ui: &mut UiState) { + ui.mode = self.mode; + ui.sync_mode_dock(); + ui.dock = self.dock; + ui.layout = self.layout; + ui.swap_views = self.swap_views; + ui.split_ratio = self.split_ratio; + ui.toolbar_docks = self.toolbar_docks; + ui.toolbar_tools = self.toolbar_tools; + ui.rail_panel = None; + } + + pub fn read(bytes: &[u8]) -> Result { + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?; + if value.get("windows").is_some() { + let state: UiState = serde_json::from_value(value).map_err(|e| e.to_string())?; + return Ok(Self::of(&state, state.mode)); + } + let layout: Self = serde_json::from_value(value).map_err(|e| e.to_string())?; + if !layout.split_ratio.is_finite() || !(0.0..=1.0).contains(&layout.split_ratio) || layout.dock.replaced_unreadable() { + return Err("Invalid UI layout".into()); + } + Ok(layout) + } +} diff --git a/crates/ui-egui/src/named_layouts.rs b/crates/ui-egui/src/named_layouts.rs index 893c8020..ba79e24a 100644 --- a/crates/ui-egui/src/named_layouts.rs +++ b/crates/ui-egui/src/named_layouts.rs @@ -30,7 +30,13 @@ impl UiState { return false; } - let (painting, baking) = if self.dock_is_baking { (&self.inactive_mode_dock, &self.dock) } else { (&self.dock, &self.inactive_mode_dock) }; + let (painting, baking) = if self.dock_is_baking { + (&self.inactive_mode_dock, &self.dock) + } else if self.dock_is_rendering { + (self.inactive_render_dock.as_ref().unwrap_or(&self.dock), &self.inactive_mode_dock) + } else { + (&self.dock, &self.inactive_mode_dock) + }; let layout = NamedLayout { name: name.to_string(), painting: painting.clone(), baking: baking.clone() }; match self.named_layout_index(name) { Some(index) => self.named_layouts[index] = layout, @@ -74,21 +80,6 @@ impl UiState { } } -/// One entry per saved layout, under the catalog's items of the Layouts submenu -pub(crate) fn entries(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - if app.ui.named_layouts.is_empty() { - return; - } - - ui.separator(); - for name in app.ui.named_layouts.iter().map(|layout| layout.name.clone()).collect::>() { - if ui.button(&name).clicked() { - app.ui.apply_named_layout(&name); - ui.close(); - } - } -} - /// The save, overwrite and manage dialogs pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { forget_finished_focus(app, ctx); @@ -136,7 +127,7 @@ fn focus_once(ui: &egui::Ui, edit: &egui::Response, key: &'static str, what: Str fn save_dialog(app: &mut TextureCraftApp, ctx: &egui::Context, open: &mut bool, mut name: String) -> Option { let mut done = None; - dialog("save_layout", tr("Save layout"), open).show(ctx, |ui| { + dialog(ctx, "save_layout", tr("Save Layout"), open).show(ctx, |ui| { ui.label(tr("Name of the layout")); let edit = ui.add(egui::TextEdit::singleline(&mut name).desired_width(240.0)); focus_once(ui, &edit, SAVE_FOCUS, String::new()); @@ -167,7 +158,7 @@ fn save_dialog(app: &mut TextureCraftApp, ctx: &egui::Context, open: &mut bool, fn overwrite_dialog(app: &mut TextureCraftApp, ctx: &egui::Context, open: &mut bool, name: String) -> Option { let mut answer = None; - dialog("overwrite_layout", tr("Replace layout"), open).show(ctx, |ui| { + dialog(ctx, "overwrite_layout", tr("Replace Layout"), open).show(ctx, |ui| { ui.label(trf("A layout named {name} already exists. Replace it?", &[("name", &name)])); ui.add_space(8.0); ui.horizontal(|ui| { @@ -199,7 +190,7 @@ fn manage_dialog( mut deleting: Option, ) -> Option { let mut finished = false; - dialog("manage_layouts", tr("Manage layouts"), open).show(ctx, |ui| { + dialog(ctx, "manage_layouts", tr("Manage Layouts"), open).show(ctx, |ui| { ui.set_min_width(320.0); if let Some(name) = deleting.clone() { ui.label(trf("Delete the layout {name}?", &[("name", &name)])); diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 2d079b67..caf7bb8c 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -80,28 +80,43 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut create, mut cancel) = (false, false); - // A fixed height keeps the centered window still while its sections lay out + // Start with a form that fits the viewport; subsequent sizes follow the user's resize. let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); - dialog("new_project", tr("New project"), &mut open).default_width(DIALOG_WIDTH_POINTS).show(ctx, |ui| { - ui.set_width(DIALOG_WIDTH_POINTS); - egui::ScrollArea::vertical().id_salt("np_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| { - basic_settings(app, ui); - ui.add_space(8.0); - advanced_settings(app, ui); - }); - ui.separator(); - let can_create = app.ui.new_project.file.is_some(); - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - create = ui - .add_enabled(can_create, primary_button(ui, tr("Create")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))) - .on_disabled_hover_text(tr("Select a 3D mesh first")) - .clicked(); - cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); + dialog(ctx, "new_project", tr("New Project"), &mut open).default_size(vec2(DIALOG_WIDTH_POINTS, form_height + DIALOG_CHROME_HEIGHT_POINTS)).show( + ctx, + |ui| { + // Lay out the actual footer first so it cannot make the window grow each frame. + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + let can_create = app.ui.new_project.file.is_some(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + create = ui + .add_enabled(can_create, primary_button(ui, tr("Create")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))) + .on_disabled_hover_text(tr("Select a 3D mesh first")) + .clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); + }); + }); + ui.separator(); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + let form_height = ui.available_height().max(0.0); + egui::ScrollArea::both() + .id_salt("np_form") + .content_margin(crate::windows::dialog_scroll_margin(ui)) + .min_scrolled_width(0.0) + .min_scrolled_height(0.0) + .max_height(form_height) + .auto_shrink([false, false]) + .show(ui, |ui| { + basic_settings(app, ui); + ui.add_space(8.0); + advanced_settings(app, ui); + }); + }); }); - }); - }); + }, + ); if cancel || !open { app.ui.new_project.baked_maps = Vec::new(); diff --git a/crates/ui-egui/src/pbr_import.rs b/crates/ui-egui/src/pbr_import.rs index c7a13e29..dc1d1880 100644 --- a/crates/ui-egui/src/pbr_import.rs +++ b/crates/ui-egui/src/pbr_import.rs @@ -100,7 +100,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut import_clicked, mut cancel_clicked) = (false, false); - crate::windows::dialog("pbrImport", tr("Import PBR textures"), &mut open).show(ctx, |ui| { + crate::windows::dialog(ctx, "pbrImport", tr("Import PBR Textures"), &mut open).show(ctx, |ui| { ui.set_min_width(380.0); ui.horizontal(|ui| { ui.label(tr("Layer name")); diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index b6ae5bb1..b5486128 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -137,142 +137,154 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - // A fixed height keeps the centered window still while its sections lay out + // Start with a form that fits the viewport; subsequent sizes follow the user's resize. let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); - let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(DEFAULT_DIALOG_WIDTH_POINTS); + let dialog = crate::windows::dialog(ctx, "project_config", tr("Project Configuration"), &mut open) + .default_size(egui::vec2(DEFAULT_DIALOG_WIDTH_POINTS, form_height + DIALOG_CHROME_HEIGHT_POINTS)); dialog.show(ctx, |ui| { - ui.set_width(DEFAULT_DIALOG_WIDTH_POINTS); - egui::ScrollArea::vertical().id_salt("project_config_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| { - // Keep the project sections in the order users expect - ui.label(caption(tr("3D MESH"))); - ui.add_space(4.0); + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { ui.horizontal(|ui| { - ui.add_space(ROW_INDENT_POINTS); - ui.label(tr("3D mesh")); - - let display_path = chosen_mesh.unwrap_or(mesh_label); - let font = egui::TextStyle::Body.resolve(ui.style()); - let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); - let painter = ui.painter().clone(); - let measure = |text: &str| painter.layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - info_icon(ui, tr("The mesh file the project is built on. Select... chooses another one, read when you press OK.")); - select = ui.button(tr("Select...")).clicked(); - if display_path.is_empty() { - ui.weak(tr("Built-in mesh")); - } else { - ui.label(elide_start(display_path, measure)).on_hover_text(display_path); - } + ok |= ui.add(primary_button(ui, tr("OK")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); }); }); - if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available { - ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); - } - - // A selected replacement always reads the mesh again - // A missing source file cannot be reimported - let mut reimport = config.reimport || chosen_mesh.is_some(); - let can_reimport_source = chosen_mesh.is_none() && source_file_available; - let reimport_checkbox = check_row( - ui, - Some(tr("Read the mesh file again, keeping the layers and painted strokes")), - |ui| ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))), - |_| {}, - ); - - if can_reimport_source { - config.reimport = reimport; - } else if chosen_mesh.is_none() { - reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); - } - - ui.add_space(12.0); - ui.label(caption(tr("PROJECT SETTINGS"))); ui.add_space(4.0); - let shown_format = config.normal_format.unwrap_or(current_normal_format); - row( - ui, - tr("Normal map format"), - Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")), - |ui| { - egui::ComboBox::from_id_salt(tr("Normal map format")) - .width(FIELD_WIDTH_POINTS) - .wrap_mode(egui::TextWrapMode::Truncate) - .selected_text(format_name(shown_format)) - .show_ui(ui, |ui| { - for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { - if ui.selectable_label(format == shown_format, format_name(format)).clicked() { - config.normal_format = (format != current_normal_format).then_some(format); + ui.label(egui::RichText::new(tr("Changing the mesh or normal format can recalculate texture channels.")).color(Tokens::get(ui.ctx()).warning)); + ui.add_space(8.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + let form_height = ui.available_height().max(0.0); + let scroll = egui::ScrollArea::both() + .id_salt("project_config_form") + .content_margin(crate::windows::dialog_scroll_margin(ui)) + .min_scrolled_width(0.0) + .min_scrolled_height(0.0) + .max_height(form_height) + .auto_shrink([false, false]); + scroll.show(ui, |ui| { + // Keep the project sections in the order users expect + ui.label(caption(tr("3D MESH"))); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + ui.label(tr("3D mesh")); + + let display_path = chosen_mesh.unwrap_or(mesh_label); + let font = egui::TextStyle::Body.resolve(ui.style()); + let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); + let painter = ui.painter().clone(); + let measure = |text: &str| painter.layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points; + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("The mesh file the project is built on. Select... chooses another one, read when you press OK.")); + select = ui.button(tr("Select...")).clicked(); + if display_path.is_empty() { + ui.weak(tr("Built-in mesh")); + } else { + ui.label(elide_start(display_path, measure)).on_hover_text(display_path); + } + }); + }); + if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available { + ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); + } + + // A selected replacement always reads the mesh again + // A missing source file cannot be reimported + let mut reimport = config.reimport || chosen_mesh.is_some(); + let can_reimport_source = chosen_mesh.is_none() && source_file_available; + let reimport_checkbox = check_row( + ui, + Some(tr("Read the mesh file again, keeping the layers and painted strokes")), + |ui| ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))), + |_| {}, + ); + + if can_reimport_source { + config.reimport = reimport; + } else if chosen_mesh.is_none() { + reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); + } + + ui.add_space(12.0); + ui.label(caption(tr("PROJECT SETTINGS"))); + ui.add_space(4.0); + let shown_format = config.normal_format.unwrap_or(current_normal_format); + row( + ui, + tr("Normal map format"), + Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")), + |ui| { + egui::ComboBox::from_id_salt(tr("Normal map format")) + .width(FIELD_WIDTH_POINTS) + .wrap_mode(egui::TextWrapMode::Truncate) + .selected_text(format_name(shown_format)) + .show_ui(ui, |ui| { + for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { + if ui.selectable_label(format == shown_format, format_name(format)).clicked() { + config.normal_format = (format != current_normal_format).then_some(format); + } + } + }) + .response + .on_hover_text(tr( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + )); + }, + ); + tangent_space_row(ui); + + // Texture Set Settings owns UV tile changes + ui.add_space(4.0); + sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("View the UV tiles assigned to each texture set"))); + let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings"); + note(ui, tiles_hint); + let mut has_tiles = project.texture_sets.iter().any(|set| !set.uv_tiles.is_empty()); + + check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles, tr("Use UV Tile workflow"))), |_| {}) + .on_disabled_hover_ui(|ui| { + ui.set_max_width(ui.spacing().tooltip_width); + if !has_tiles { + ui.label(tr("No UV tiles")); + } + + for set in project.texture_sets.iter().filter(|set| !set.uv_tiles.is_empty()) { + let tiles = set.uv_tiles.iter().map(u32::to_string).collect::>().join(", "); + if project.texture_sets.len() > 1 { + ui.label(trf("{set}: {tiles}", &[("set", &set.name), ("tiles", &tiles)])); + } else { + ui.label(tiles); } } - }) - .response - .on_hover_text(tr( - "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", - )); - }, - ); - tangent_space_row(ui); + }); + uv_tile_radios(ui, false, tiles_hint); - // Texture Set Settings owns UV tile changes - ui.add_space(4.0); - sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("View the UV tiles assigned to each texture set"))); - let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings"); - note(ui, tiles_hint); - let mut has_tiles = project.texture_sets.iter().any(|set| !set.uv_tiles.is_empty()); + ui.add_space(4.0); + sub_title(ui, tr("Import settings"), None); + check_row( + ui, + Some(tr("Keep the cameras stored in the mesh file")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Import cameras")))), + |_| {}, + ); - check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles, tr("Use UV Tile workflow"))), |_| {}) - .on_disabled_hover_ui(|ui| { - ui.set_max_width(ui.spacing().tooltip_width); - if !has_tiles { - ui.label(tr("No UV tiles")); - } + // Import settings matter only when a mesh will be read + let importing = chosen_mesh.is_some() || (config.reimport && source_file_available); + check_row( + ui, + Some(tr("Painted strokes follow the surface when the new mesh's UVs differ")), + |ui| ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))), + |_| {}, + ); + auto_unwrap_row(ui); - for set in project.texture_sets.iter().filter(|set| !set.uv_tiles.is_empty()) { - let tiles = set.uv_tiles.iter().map(u32::to_string).collect::>().join(", "); - if project.texture_sets.len() > 1 { - ui.label(trf("{set}: {tiles}", &[("set", &set.name), ("tiles", &tiles)])); - } else { - ui.label(tiles); - } - } + ui.add_space(4.0); + physical_size(ui, "project_config_physical_size", false); + color_management(ui, "project_config_color_management", &mut config.color_management); }); - uv_tile_radios(ui, false, tiles_hint); - ui.add_space(4.0); - sub_title(ui, tr("Import settings"), None); - check_row( - ui, - Some(tr("Keep the cameras stored in the mesh file")), - |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Import cameras")))), - |_| {}, - ); - - // Import settings matter only when a mesh will be read - let importing = chosen_mesh.is_some() || (config.reimport && source_file_available); - check_row( - ui, - Some(tr("Painted strokes follow the surface when the new mesh's UVs differ")), - |ui| ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))), - |_| {}, - ); - auto_unwrap_row(ui); - - ui.add_space(4.0); - physical_size(ui, "project_config_physical_size", false); - color_management(ui, "project_config_color_management", &mut config.color_management); - }); - - ui.add_space(8.0); - ui.label(egui::RichText::new(tr("Changing the mesh or normal format can recalculate texture channels.")).color(Tokens::get(ui.ctx()).warning)); - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ok |= ui.add(primary_button(ui, tr("OK")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); - cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); }); }); }); diff --git a/crates/ui-egui/src/session_log_file.rs b/crates/ui-egui/src/session_log_file.rs new file mode 100644 index 00000000..96e0202f --- /dev/null +++ b/crates/ui-egui/src/session_log_file.rs @@ -0,0 +1,98 @@ +//! The current desktop run's rolling log, separate from the clearable Log panel. +use std::{ + fs::{File, OpenOptions}, + io::{self, Write}, + path::PathBuf, +}; +use texturecraft_engine::LogEntry; + +pub(crate) struct SessionLogFile { + pub path: PathBuf, + file: File, + bytes: u64, + log_id: u64, + cursor: usize, + last: Option, +} + +impl SessionLogFile { + pub fn new(path: PathBuf) -> io::Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let file = OpenOptions::new().create_new(true).append(true).open(&path)?; + Ok(Self { path, file, bytes: 0, log_id: 0, cursor: 0, last: None }) + } + + pub fn text(&mut self) -> io::Result { + self.file.flush()?; + let previous = self.path.with_file_name("log.previous.txt"); + let mut text = match std::fs::read_to_string(previous) { + Ok(text) => text, + Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(), + Err(error) => return Err(error), + }; + text.push_str(&std::fs::read_to_string(&self.path)?); + Ok(text) + } + + pub fn sync(&mut self, log_id: u64, entries: &[LogEntry]) -> io::Result<()> { + let same_tail = self.log_id == log_id && self.cursor.checked_sub(1).and_then(|i| entries.get(i)) == self.last.as_ref(); + if same_tail && self.cursor == entries.len() { + return Ok(()); + } + let start = if same_tail { self.cursor } else { 0 }; + for entry in entries.get(start..).unwrap_or_default() { + // Clearing lines in the panel must not append the remaining old lines twice. + if self.log_id == log_id && self.last.as_ref().is_some_and(|last| entry.time <= last.time) { + continue; + } + let text = crate::windows::log_text(std::slice::from_ref(entry)); + let line = text.split_once('\n').map(|(_, line)| line).unwrap_or_default(); + // Bound each run's disk use. Keep one previous segment when the active log rolls. + if self.bytes.saturating_add(line.len() as u64) > 8 * 1024 * 1024 { + self.file.flush()?; + std::fs::copy(&self.path, self.path.with_file_name("log.previous.txt"))?; + self.file.set_len(0)?; + self.bytes = 0; + } + self.file.write_all(line.as_bytes())?; + self.bytes = self.bytes.saturating_add(line.len() as u64); + } + self.file.flush()?; + self.log_id = log_id; + self.cursor = entries.len(); + if let Some(last) = entries.last() { + self.last = Some(last.clone()); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::{LogLevel, SessionLog}; + + #[test] + fn log_file_keeps_messages_after_panel_clear_and_across_projects() { + let dir = std::env::temp_dir().join(format!("texturecraft-session-log-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(format!("{}.txt", chrono::Utc::now().timestamp_nanos_opt().unwrap())); + let mut file = SessionLogFile::new(path.clone()).unwrap(); + let mut log = SessionLog::new(); + log.push("first".into()); + file.sync(1, log.entries()).unwrap(); + file.sync(1, log.entries()).unwrap(); + log.clear(); + file.sync(1, log.entries()).unwrap(); + log.error("UI", "second"); + file.sync(1, log.entries()).unwrap(); + file.sync(2, &[LogEntry::new(LogLevel::Info, "UI", "new project")]).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(text.matches("first").count(), 1); + assert!(text.contains("second") && text.contains("new project")); + drop(file); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index 7a0b38ce..a933bfd9 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -75,77 +75,84 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::keymap::follow(&mut app.settings_bindings, &draft.keymap, ctx); let shortcut_conflict = crate::keymap::has_conflict(&app.settings_bindings); - crate::windows::window("settings", tr("Settings"), &mut open).resizable(false).show(ctx, |ui| { - // Keep the footer inside the viewport when the fixed-width controls need to scroll - ui.set_max_width(content_width); - ui.horizontal_top(|ui| { - egui::ScrollArea::vertical().id_salt("settings_navigation").min_scrolled_height(0.0).max_height(page_height).show(ui, |ui| { - ui.vertical(|ui| { - ui.set_width(PAGE_BUTTON.x); - for page in SettingsPage::ALL { - let warn = page == SettingsPage::Shortcuts && shortcut_conflict; - if page_button(ui, page, draft.page == page, warn).clicked() { - draft.page = page; - } - ui.add_space(6.0); + crate::windows::window("settings", tr("Settings"), &mut open) + .default_size(vec2(content_width + frame_width, page_height + WINDOW_CHROME_HEIGHT_POINTS)) + .show(ctx, |ui| { + // Measure the footer through layout, then let the pages use only what remains. + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + // Recheck after drawing the page as well, before accepting any edits. + let conflict = crate::keymap::has_conflict(&app.settings_bindings); + ui.horizontal(|ui| { + if conflict { + let danger = Tokens::get(ui.ctx()).danger; + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr(SHORTCUT_ERRORS))).color(danger)); } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(100.0, 0.0))).clicked(); + ok = ui.add_enabled(!conflict, egui::Button::new(tr("OK")).min_size(vec2(100.0, 0.0))).clicked(); + }); }); - }); - ui.add_space(8.0); - egui::ScrollArea::both() - .id_salt(("settings_page", draft.page as u8)) - .auto_shrink([false, false]) - .min_scrolled_width(0.0) - .min_scrolled_height(page_height) - .max_height(page_height) - .show(ui, |ui| { - ui.vertical(|ui| { - ui.set_width(PAGE_WIDTH); - match draft.page { - SettingsPage::General => { - general( - ui, - &mut draft.prefs, - &drawable, - gpu.as_deref(), - #[cfg(not(target_arch = "wasm32"))] - resources, - #[cfg(not(target_arch = "wasm32"))] - &mut pick, - ); - } - SettingsPage::Shortcuts => { - crate::keymap::actions_page(ui, &mut draft.keymap, &app.bindings, &mut app.settings_bindings); - } - SettingsPage::Libraries => { - libraries( - ui, - &mut draft, - project_open, - #[cfg(not(target_arch = "wasm32"))] - &mut pick, - ); - } - } + ui.separator(); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + let page_height = ui.available_height().max(0.0); + ui.horizontal_top(|ui| { + egui::ScrollArea::vertical().id_salt("settings_navigation").min_scrolled_height(0.0).max_height(page_height).show(ui, |ui| { + ui.vertical(|ui| { + ui.set_width(PAGE_BUTTON.x); + for page in SettingsPage::ALL { + let warn = page == SettingsPage::Shortcuts && shortcut_conflict; + if page_button(ui, page, draft.page == page, warn).clicked() { + draft.page = page; + } + ui.add_space(6.0); + } + }); + }); + ui.add_space(8.0); + egui::ScrollArea::both() + .id_salt(("settings_page", draft.page as u8)) + .content_margin(crate::windows::dialog_scroll_margin(ui)) + .auto_shrink([false, false]) + .min_scrolled_width(0.0) + .min_scrolled_height(0.0) + .max_height(page_height) + .show(ui, |ui| { + ui.vertical(|ui| { + ui.set_min_width(PAGE_WIDTH); + match draft.page { + SettingsPage::General => { + general( + ui, + &mut draft.prefs, + &drawable, + gpu.as_deref(), + #[cfg(not(target_arch = "wasm32"))] + resources, + #[cfg(not(target_arch = "wasm32"))] + &mut pick, + ); + } + SettingsPage::Shortcuts => { + crate::keymap::actions_page(ui, &mut draft.keymap, &app.bindings, &mut app.settings_bindings); + } + SettingsPage::Libraries => { + libraries( + ui, + &mut draft, + project_open, + #[cfg(not(target_arch = "wasm32"))] + &mut pick, + ); + } + } + }); + }); }); }); - }); - ui.separator(); - - // The page has brought the checker up to date, so OK follows this frame's edits - let conflict = crate::keymap::has_conflict(&app.settings_bindings); - ui.horizontal(|ui| { - if conflict { - let danger = Tokens::get(ui.ctx()).danger; - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr(SHORTCUT_ERRORS))).color(danger)); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(100.0, 0.0))).clicked(); - ok = ui.add_enabled(!conflict, egui::Button::new(tr("OK")).min_size(vec2(100.0, 0.0))).clicked(); }); }); - }); + ok &= !crate::keymap::has_conflict(&app.settings_bindings); app.ui.windows.settings_page = draft.page; if draft.page != SettingsPage::Shortcuts || ok || cancel || !open { crate::keymap::stop_settings_capture(ctx); @@ -169,6 +176,7 @@ fn apply(app: &mut TextureCraftApp, draft: SettingsDraft) { let previous_autosave_minutes = app.ui.prefs.autosave_minutes; app.ui.prefs = draft.prefs; + app.ui.trim_recent(); app.reschedule_autosave_if_changed(previous_autosave_minutes); let ids: std::collections::BTreeSet<&String> = draft.keymap.keys().chain(draft.keymap_at_open.keys()).collect(); @@ -354,6 +362,12 @@ fn general( }); }); + row(ui, tr("Recent projects limit"), |ui, label| { + ui.add(egui::DragValue::new(&mut p.recent_projects_limit).range(0..=100)) + .labelled_by(label) + .on_hover_text(tr("Number of recent projects to remember. 0 disables recent-project history.")); + }); + section(ui, n_("LAYER STACK OPTIONS")); ui.horizontal(|ui| { ui.add_space(12.0); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c5dffbc9..42bdeecd 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -146,6 +146,8 @@ pub struct Prefs { pub ui_scale: f32, /// Minutes between autosaves of a modified project (0: off; desktop). pub autosave_minutes: u32, + /// Maximum recent projects retained (0 disables the history, capped at 100). + pub recent_projects_limit: u16, /// UI language code (`i18n::LANGUAGES`), or `i18n::SYSTEM_LANGUAGE` to follow the system. pub language: String, /// Viewport texture resolution: 0 full, 1 half, 2 quarter of each texture set's size (lighter @@ -197,6 +199,7 @@ impl Default for Prefs { Prefs { ui_scale: 1.0, autosave_minutes: 10, + recent_projects_limit: 10, language: "en".into(), viewport_texture: 0, brightness: crate::theme::Brightness::default(), @@ -502,6 +505,11 @@ pub struct UiState { pub(crate) inactive_mode_dock: Dock, #[serde(default)] pub(crate) dock_is_baking: bool, + /// Rendering's saved dock, or Painting's while Rendering is active. Older states start from Painting. + #[serde(default)] + pub(crate) inactive_render_dock: Option, + #[serde(default)] + pub(crate) dock_is_rendering: bool, /// Window ▸ Toolbars ▸ Docks: the right bar of panel icons #[serde(default = "default_true")] pub toolbar_docks: bool, @@ -615,8 +623,20 @@ pub struct UiState { } impl UiState { + /// Keep recent-file history bounded, including values supplied through automation or old settings. + pub(crate) fn trim_recent(&mut self) { + self.prefs.recent_projects_limit = self.prefs.recent_projects_limit.min(100); + self.recent.truncate(usize::from(self.prefs.recent_projects_limit)); + } + /// 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) { + if self.dock_is_rendering { + if let Some(other) = self.inactive_render_dock.as_mut() { + std::mem::swap(&mut self.dock, other); + } + self.dock_is_rendering = false; + } self.reset_outdated_bake_dock(); let baking = self.mode == Mode::Baking; @@ -624,6 +644,11 @@ impl UiState { std::mem::swap(&mut self.dock, &mut self.inactive_mode_dock); self.dock_is_baking = baking; } + if self.mode == Mode::Rendering { + let other = self.inactive_render_dock.get_or_insert_with(|| self.dock.clone()); + std::mem::swap(&mut self.dock, other); + self.dock_is_rendering = true; + } } /// Replace a bake dock saved with an older bake layout, or one that could not be read, by the bake default @@ -642,6 +667,7 @@ impl UiState { pub fn reset_panel_layout(&mut self) { let (painting, baking) = (Dock::default(), Dock::for_baking()); (self.dock, self.inactive_mode_dock) = if self.dock_is_baking { (baking, painting) } else { (painting, baking) }; + self.inactive_render_dock = self.dock_is_rendering.then(Dock::default); self.bake_layout_version = BAKE_LAYOUT_VERSION; self.rail_panel = None; } @@ -690,6 +716,8 @@ impl Default for UiState { rail_panel: None, inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, + inactive_render_dock: None, + dock_is_rendering: false, toolbar_docks: true, toolbar_tools: true, bake_layout_version: BAKE_LAYOUT_VERSION, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index dc2f3453..0a90340a 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -6,7 +6,6 @@ use serde_json::json; use texturecraft_engine::Tool; use crate::TextureCraftApp; -use crate::docking::Panel; use crate::i18n::{tr, trf}; use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; @@ -435,10 +434,14 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing.y = SHELF_BUTTON_SPACING; // Rendering has nothing to paint, so its shelf keeps only the buttons below the tools - let tools: &[Tool] = match app.ui.mode { - Mode::Painting => &SHELF_TOOLS, - Mode::Baking => &BAKING_SHELF_TOOLS, - Mode::Rendering => &[], + let tools: &[Tool] = if !app.ui.toolbar_tools { + &[] + } else { + match app.ui.mode { + Mode::Painting => &SHELF_TOOLS, + Mode::Baking => &BAKING_SHELF_TOOLS, + Mode::Rendering => &[], + } }; if !tools.is_empty() { for &tool in tools { @@ -467,26 +470,10 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add_space(SHELF_GROUP_GAP); } - let quick_mask = &app.session.quick_mask; - for (command, icon, label, selected) in [ - ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled), - ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing), - ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted), - ] { - let hint = tip(&app.ui.keymap, label, command); - let button = ui.add_enabled_ui(crate::menus::enabled(app, command), |ui| icon_button(ui, icon, &hint, selected, SHELF_BUTTON_SIZE)).inner; - if button.on_disabled_hover_text(label).clicked() { - app.run(command, json!({})); - } - } - - ui.add_space(SHELF_GROUP_GAP); - ui.separator(); - ui.add_space(SHELF_GROUP_GAP); - let painting = app.ui.mode == Mode::Painting; - if ui.add_enabled_ui(painting, |ui| icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, SHELF_BUTTON_SIZE)).inner.clicked() - { - app.ui.dock.focus(Panel::Assets); + for (icon, label) in [(ic::HOURGLASS, "Snooze Autosave"), (ic::ARROWS_CLOCKWISE, "Resources Updater")] { + ui.add_enabled_ui(false, |ui| icon_button(ui, icon, tr(label), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); } }); }); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index 866f3e50..80bad1c7 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -245,7 +245,8 @@ fn read_bytes(_file: &Path) -> std::io::Result> { /// Whether every dock, the two in use and those of the named layouts, was read rather than replaced by a default fn fully_read(ui: &UiState) -> bool { - !ui.dock.replaced_unreadable() + ui.inactive_render_dock.as_ref().is_none_or(|dock| !dock.replaced_unreadable()) + && !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() && ui.named_layouts.iter().all(|layout| !layout.painting.replaced_unreadable() && !layout.baking.replaced_unreadable()) } diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index da935fbe..072977e2 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -199,13 +199,13 @@ mod tests { assert_eq!(h.state().ui.mode, Mode::Painting); offer(&mut h); assert!(crate::docking::input_blocked(h.state(), &h.ctx), "floating panels stop taking input"); - h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::B); + h.key_press(egui::Key::F8); h.step(); assert_eq!(h.state().ui.mode, Mode::Painting, "the prompt holds the keyboard"); h.get_by_label("LATER").click(); h.run_steps(2); assert!(!crate::docking::input_blocked(h.state(), &h.ctx)); - h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::B); + h.key_press(egui::Key::F8); h.step(); assert_eq!(h.state().ui.mode, Mode::Baking, "the key works once the prompt is closed"); } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0624e1be..e8a3ef80 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,6 +1,8 @@ //! Floating windows and the dockable History panel -use egui::{RichText, Ui, vec2}; +#[cfg(any(target_arch = "wasm32", test))] +use egui::vec2; +use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::json; @@ -50,8 +52,8 @@ fn reset_ui(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut reset, mut cancel) = (false, false); - dialog("reset_ui", tr("Reset UI"), &mut open).show(ctx, |ui| { - ui.label(tr("Reset the panels, view layout, zoom and every other view setting to their defaults? Settings and shortcuts stay. To reset only the panels, use Reset panel layout.")); + dialog(ctx, "reset_ui", tr("Reset UI"), &mut open).show(ctx, |ui| { + ui.label(tr("Reset the panels, view layout, zoom and every other view setting to their defaults? Settings and shortcuts stay.")); ui.add_space(8.0); // One row keeps the window to its contents; a bare right-to-left layout fills the screen height @@ -123,7 +125,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { } else { trf("Save the changes to {name} first?", &question_args) }; - dialog("unsaved", tr("Unsaved changes"), &mut open).show(ctx, |ui| { + dialog(ctx, "unsaved", tr("Unsaved Changes"), &mut open).show(ctx, |ui| { ui.label(question); ui.add_space(8.0); @@ -199,14 +201,29 @@ pub(crate) fn window<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Win .default_width(300.0) } -/// A centered dialog; `id` keeps its place across UI languages. -pub(crate) fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { +/// A movable, resizable dialog, initially centered; `id` keeps its place across UI languages. +pub(crate) fn dialog<'a>(ctx: &egui::Context, id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { egui::Window::new(title.to_owned()) .id(egui::Id::unique(id)) .open(open) .collapsible(false) - .resizable(false) - .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .resizable(true) + .default_height(0.0) + .default_pos(ctx.content_rect().center()) + .pivot(egui::Align2::CENTER_CENTER) +} + +/// Keep form controls clear of the scrollbar even when its floating handle expands. +pub(crate) fn dialog_scroll_margin(ui: &egui::Ui) -> egui::Margin { + let scroll = &ui.spacing().scroll; + let mut margin = scroll.content_margin; + let clearance = (scroll.bar_width + ui.spacing().item_spacing.x).ceil() as i8; + if ui.style().right_to_left { + margin.left = margin.left.max(clearance); + } else { + margin.right = margin.right.max(clearance); + } + margin } /// The History panel body (a dock tab) @@ -271,7 +288,7 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let mut picked = None; - dialog("export_mesh", tr("Export mesh"), &mut open).show(ctx, |ui| { + dialog(ctx, "export_mesh", tr("Export Mesh"), &mut open).show(ctx, |ui| { ui.label(crate::theme::caption(tr("Download as"))); 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() { @@ -290,7 +307,7 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); let mut open = app.ui.windows.about; - dialog("about", tr("About TextureCraft"), &mut open).show(ctx, |ui| { + dialog(ctx, "about", tr("About TextureCraft"), &mut open).show(ctx, |ui| { ui.vertical_centered(|ui| { ui.label(RichText::new("TextureCraft").size(22.0).strong().color(tk.text_strong)); ui.label(trf("Version {version}", &[("version", &texturecraft_engine::VERSION)])); @@ -308,7 +325,7 @@ fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { } /// Render the session log as text, preserving each entry's occurrence time, severity and source. -fn log_text(entries: &[texturecraft_engine::LogEntry]) -> String { +pub(crate) fn log_text(entries: &[texturecraft_engine::LogEntry]) -> String { use std::fmt::Write as _; const UTC_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.6fZ"; @@ -328,11 +345,43 @@ fn log_text(entries: &[texturecraft_engine::LogEntry]) -> String { text } +/// Open the current run's log in the desktop's text-file handler. +pub(crate) fn show_log(app: &mut TextureCraftApp, _ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + { + let result = match app.session_log_file.as_mut() { + Some(file) => file.sync(app.session.log_id, app.session.log.entries()).map(|()| file.path.clone()), + None => Err(std::io::Error::other(tr("No session log file is available"))), + }; + match result.and_then(|path| app.file_dialogs.show_folder(&path)) { + Ok(()) => {} + Err(error) => app.toast(trf("Could not open the log: {error}", &[("error", &error)]), true), + } + } + #[cfg(target_arch = "wasm32")] + export_log(app); +} + /// Help ▸ Export log...: saves the whole log to a text file chosen in a save dialog. pub(crate) fn export_log(app: &mut TextureCraftApp) { let text = log_text(app.session.log.entries()); #[cfg(not(target_arch = "wasm32"))] - app.ask_file(FileDialog::save().filter(tr("Text file"), &["txt"]).file_name("texturecraft-log.txt"), Bound::App, move |app, paths| { + let text = if let Some(file) = &mut app.session_log_file { + match file.sync(app.session.log_id, app.session.log.entries()).and_then(|()| file.text()) { + Ok(lines) => format!("{}{lines}", log_text(&[])), + Err(error) => { + app.toast(trf("Could not export the log: {error}", &[("error", &error)]), true); + return; + } + } + } else { + text + }; + let backend = app.render_state.as_ref().map(|state| format!("{:?}", state.adapter.get_info().backend)).unwrap_or_else(|| "CPU".into()); + let name = + format!("Log_TextureCraft_{}_{}_{}_{}.txt", env!("CARGO_PKG_VERSION"), chrono::Utc::now().format("%Y-%m-%d_%H-%M-%S"), std::env::consts::OS, backend); + #[cfg(not(target_arch = "wasm32"))] + app.ask_file(FileDialog::save().filter(tr("Text file"), &["txt"]).file_name(&name), Bound::App, move |app, paths| { let Some(path) = paths.first() else { return }; match std::fs::write(path, &text) { Ok(()) => app.toast(trf("Exported the log to {path}", &[("path", &path.display().to_string())]), false), @@ -340,7 +389,7 @@ pub(crate) fn export_log(app: &mut TextureCraftApp) { } }); #[cfg(target_arch = "wasm32")] - match crate::web_files::download("texturecraft-log.txt", text.as_bytes()) { + match crate::web_files::download(&name, text.as_bytes()) { Ok(()) => app.toast(tr("Exported the log"), false), Err(e) => app.toast(trf("Could not export the log: {error}", &[("error", &e)]), true), } @@ -357,7 +406,7 @@ pub fn file_dialogs_available() -> bool { pub fn remember(app: &mut TextureCraftApp, path: &str) { app.ui.recent.retain(|p| p != path); app.ui.recent.insert(0, path.to_string()); - app.ui.recent.truncate(10); + app.ui.trim_recent(); } /// Start a save picker in its library folder when available. @@ -387,9 +436,7 @@ pub fn save_layout(app: &mut TextureCraftApp, mode: crate::state::Mode) { app.ask_file(dialog, Bound::App, move |app, paths| { let Some(path) = paths.first() else { return }; - // The file carries both docks; the mode's own is the one in use when it is loaded - let mut layout = crate::UiState { recent: Vec::new(), named_layouts: Vec::new(), mode, ..app.ui.clone() }; - layout.sync_mode_dock(); + let layout = crate::mode_layout::ModeLayout::of(&app.ui, mode); let result = serde_json::to_vec_pretty(&layout) .map_err(|error| error.to_string()) .and_then(|bytes| texturecraft_engine::formats::write_atomic(path, &bytes).map_err(|error| error.to_string())) @@ -405,16 +452,13 @@ pub fn save_layout(app: &mut TextureCraftApp, mode: crate::state::Mode) { #[cfg(not(target_arch = "wasm32"))] pub fn load_layout(app: &mut TextureCraftApp) { let dir = crate::user_dir("layouts"); - let dialog = FileDialog::open().title(tr("Select a UI layout file.")).filter(tr("UI layout"), &["json"]).directory(dir); + let dialog = FileDialog::open().title(tr("Load UI Layout")).filter(tr("UI layout"), &["json"]).directory(dir); app.ask_file(dialog, Bound::App, move |app, paths| { let Some(path) = paths.first() else { return }; - let result = std::fs::read(path) - .map_err(|e| e.to_string()) - .and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| e.to_string())) - .map(|layout| { - app.ui.adopt_layout(layout); - trf("Loaded UI layout {path}", &[("path", &path.display())]) - }); + let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| crate::mode_layout::ModeLayout::read(&bytes)).map(|layout| { + layout.apply(&mut app.ui); + trf("Loaded UI layout {path}", &[("path", &path.display())]) + }); match result { Ok(msg) => app.toast(msg, false), Err(e) => app.toast(trf("UI layout: {error}", &[("error", &e)]), true), @@ -437,7 +481,7 @@ pub(crate) fn template_name_of(file_name: &str) -> &str { #[cfg(not(target_arch = "wasm32"))] pub fn save_as_template(app: &mut TextureCraftApp) { let dir = app.session.templates.dir.clone().unwrap_or_else(|| crate::user_dir("templates")); - let dialog = in_save_folder(app, FileDialog::save().title(tr("Save template")).filter(tr("Project template"), &["json"]), dir); + let dialog = in_save_folder(app, FileDialog::save().title(tr("Save As Template")).filter(tr("Project template"), &["json"]), dir); app.ask_file(dialog, Bound::Project, |app, paths| { let Some(path) = paths.first() else { return }; diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs index 83e05d2c..4e235e2a 100644 --- a/crates/ui-egui/tests/it/camera_views.rs +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -1,4 +1,4 @@ -//! F5 and F6 switch the projection, the Viewport menu goes to fixed views, and Alt+Shift+drag orbits +//! F5 and F6 switch the projection, bound shortcuts go to fixed views, and Alt+Shift+drag orbits //! in 90° steps. use std::f32::consts::FRAC_PI_2; @@ -54,7 +54,7 @@ fn f6_switches_to_orthographic_and_f5_back_to_perspective_keeping_the_view() { } #[test] -fn the_viewport_menu_goes_to_the_front_view_and_orbit_works_afterwards() { +fn a_bound_front_view_shortcut_keeps_orbit_working_afterwards() { let mut h = harness(); h.state_mut().run("camera.set", json!({"yaw": 70, "pitch": 30, "ortho": true})); h.run_steps(2); @@ -62,7 +62,11 @@ fn the_viewport_menu_goes_to_the_front_view_and_orbit_works_afterwards() { // The menu bar's "Viewport", above the dock's tab of the same name h.get_all_by_label("Viewport").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); h.run_steps(2); - h.get_by_label_contains("Front view").click(); + assert!(h.query_by_label_contains("Front view").is_none(), "fixed views are absent from the menu"); + h.key_press(Key::Escape); + h.run_steps(2); + h.state_mut().ui.keymap.insert("camera.view.front".into(), "F12".into()); + h.key_press(Key::F12); // The UI glides there over about a third of a second h.run_steps(6); diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 4278b0b3..34a32c0c 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -120,7 +120,7 @@ fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { #[test] fn without_an_id_map_picking_is_off_and_a_warning_says_why() { let (mut harness, _) = app_with_color_selection(false); - let warning = format!("{} Bake an ID map (Ctrl+Shift+B) to pick colors from the mesh.", egui_phosphor::regular::WARNING); + let warning = format!("{} Bake an ID map (F8) to pick colors from the mesh.", egui_phosphor::regular::WARNING); assert!(harness.query_by_label(&warning).is_some()); harness.get_by_label(&pick_color_label()).click(); diff --git a/crates/ui-egui/tests/it/empty_menus.rs b/crates/ui-egui/tests/it/empty_menus.rs new file mode 100644 index 00000000..4092a8d7 --- /dev/null +++ b/crates/ui-egui/tests/it/empty_menus.rs @@ -0,0 +1,139 @@ +//! Empty-project menu behavior and the layout restored by Reset UI. +use egui::accesskit::Toggled; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; +use texturecraft_engine::Session; +use texturecraft_ui_egui::{TextureCraftApp, docking::Panel, menus}; + +fn app() -> Harness<'static, TextureCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|cc| TextureCraftApp::new(cc, Session::closed().unwrap())); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h +} + +#[test] +fn recent_projects_stays_openable_and_clear_tracks_the_list() { + let mut h = app(); + h.get_by_label("File").click(); + h.run_steps(3); + let recent = h.get_by_label("Recent Projects"); + assert!(!recent.accesskit_node().is_disabled()); + recent.click(); + h.run_steps(3); + assert!(h.get_by_label("Clear").accesskit_node().is_disabled()); + h.state_mut().ui.recent.push("/projects/painted-crate.tcraft".into()); + h.run_steps(3); + assert!(h.query_by_label("/projects/painted-crate.tcraft").is_some()); + assert!(!h.get_by_label("Clear").accesskit_node().is_disabled()); + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(h.state().ui.recent.is_empty()); +} + +#[test] +fn shortcuts_list_opens_settings_on_the_shortcuts_page() { + let mut h = app(); + h.get_by_label("Help").click(); + h.run_steps(3); + h.get_by_label("Shortcuts List").click(); + h.run_steps(4); + assert!(h.state().ui.windows.settings); + assert!(!h.state().ui.windows.shortcuts); + assert!(h.query_by_label("Mouse shortcuts").is_some()); + assert!(h.query_by_label("General").is_some()); +} + +#[test] +fn empty_file_menu_disables_the_save_group_and_opens_import() { + let mut h = app(); + h.get_by_label("File").click(); + h.run_steps(3); + assert!(h.get_by_label("More Save Options").accesskit_node().is_disabled()); + let import = h.get_all_by_label("Import Resources").find(|node| node.accesskit_node().toggled().is_none()).unwrap(); + assert!(!import.accesskit_node().is_disabled()); + import.click(); + h.run_steps(4); + assert!(h.state().ui.windows.import_resources.is_some()); + assert!(h.get_by_label("Import").accesskit_node().is_disabled()); +} + +#[test] +fn reset_restores_the_empty_workspace_and_checked_disabled_quick_mask() { + let mut h = app(); + h.state_mut().ui.dock.close(Panel::Assets); + h.state_mut().ui.dock.focus(Panel::History); + h.state_mut().ui.toolbar_tools = false; + h.state_mut().ui.toolbar_docks = false; + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, "ui.resetUi"); + h.run_steps(3); + h.get_by_label("Reset").click(); + h.run_steps(4); + for panel in [Panel::Assets, Panel::Layers, Panel::Properties, Panel::TextureSetList, Panel::TextureSetSettings] { + assert!(h.state().ui.dock.is_open(panel)); + } + for panel in [Panel::History, Panel::Display, Panel::Shader, Panel::Log, Panel::Export] { + assert!(!h.state().ui.dock.is_open(panel)); + } + assert!(h.state().ui.toolbar_tools && h.state().ui.toolbar_docks); + h.get_by_label("Viewport").click(); + h.run_steps(3); + let quick = h.get_by_label_contains("Enable Quick Mask"); + assert!(quick.accesskit_node().is_disabled()); + assert_eq!(quick.accesskit_node().toggled(), Some(Toggled::True)); +} + +#[test] +fn tools_hides_painting_controls_but_keeps_disabled_utilities() { + let mut h = app(); + let ctx = h.ctx.clone(); + for visible in [true, false, true] { + if h.state().ui.toolbar_tools != visible { + menus::invoke(h.state_mut(), &ctx, "ui.toolbar.tools"); + } + h.run_steps(3); + assert_eq!(h.query_by_label_contains("Eraser").is_some(), visible); + for label in ["Snooze Autosave", "Resources Updater"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label}"); + } + assert!(h.query_by_label_contains("Online assets").is_none()); + } +} + +#[test] +fn loading_a_mode_layout_preserves_the_other_modes_and_preferences() { + use texturecraft_ui_egui::{file_dialogs::Answer, state::Mode}; + let dir = super::temp_dir::TempDir::new("mode-layout-isolation"); + let file = dir.join("rendering.json"); + let mut h = app(); + h.state_mut().run("project.new", serde_json::json!({"mesh":"cube", "resolution":128})).unwrap(); + h.state_mut().ui.mode = Mode::Rendering; + h.run_steps(3); + h.state_mut().ui.dock.focus(Panel::Renderer); + let target = file.clone(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![target.clone()])))); + let ctx = h.ctx.clone(); + menus::invoke(h.state_mut(), &ctx, "ui.layout.save.rendering"); + h.run_steps(4); + h.state_mut().ui.mode = Mode::Painting; + h.run_steps(3); + h.state_mut().ui.dock.close(Panel::Assets); + h.state_mut().ui.prefs.autosave_minutes = 17; + h.state_mut().ui.mode = Mode::Baking; + h.run_steps(3); + h.state_mut().ui.dock.close(Panel::MeshMapBakers); + menus::invoke(h.state_mut(), &ctx, "ui.layout.load"); + h.run_steps(4); + assert_eq!(h.state().ui.mode, Mode::Rendering); + assert!(h.state().ui.dock.is_open(Panel::Renderer)); + assert_eq!(h.state().ui.prefs.autosave_minutes, 17); + h.state_mut().ui.mode = Mode::Painting; + h.run_steps(3); + assert!(!h.state().ui.dock.is_open(Panel::Assets)); + h.state_mut().ui.mode = Mode::Baking; + h.run_steps(3); + assert!(!h.state().ui.dock.is_open(Panel::MeshMapBakers)); +} diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 54f4e925..80bbfacf 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -83,14 +83,23 @@ fn project_items_are_disabled_without_a_project() { "layer.add.fill", "layer.remove", "bake.run", - "resource.import", "material.load", ] { assert!(!menus::enabled(app, id), "{id} needs a project"); } - for id in - ["ui.newProject", "file.open", "project.sample", "ui.settings", "ui.about", "ui.quit", "ui.hideUi", "ui.resetUi", "viewport.frame", "ui.layout.split"] - { + for id in [ + "resource.import", + "ui.newProject", + "file.open", + "project.sample", + "ui.settings", + "ui.about", + "ui.quit", + "ui.hideUi", + "ui.resetUi", + "viewport.frame", + "ui.layout.split", + ] { assert!(menus::enabled(app, id), "{id} works without a project"); } let open = open_project(); diff --git a/crates/ui-egui/tests/it/help_menu_664.rs b/crates/ui-egui/tests/it/help_menu_664.rs index 96f5ea43..d412511f 100644 --- a/crates/ui-egui/tests/it/help_menu_664.rs +++ b/crates/ui-egui/tests/it/help_menu_664.rs @@ -1,5 +1,5 @@ -//! Help ▸ Release notes... opens the releases page; Help ▸ Export log... saves the log to a text file; -//! Help ▸ Join the community (Discord)... opens the community Discord. +//! Help ▸ Release Notes opens the releases page; Help ▸ Export Log saves the log to a text file; +//! Help ▸ Discord opens the community Discord. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -34,7 +34,7 @@ fn release_notes_opens_the_releases_page() { let mut h = harness(); h.get_by_label("Help").click(); h.run_steps(3); - h.get_by_label("Release notes...").click(); + h.get_by_label("Release Notes").click(); // The open-url command is in the output of the frame that handled the click only h.step(); @@ -58,7 +58,7 @@ fn join_the_community_opens_the_discord() { let mut h = harness(); h.get_by_label("Help").click(); h.run_steps(3); - h.get_by_label("Join the community (Discord)...").click(); + h.get_by_label("Discord").click(); h.step(); assert!(opened(&h, DISCORD), "the community Discord was opened"); } @@ -82,7 +82,7 @@ fn export_log_writes_every_line_with_time_and_level() { let file = dir.join("log.txt"); let answer = file.clone(); h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); - click_help_item(&mut h, "Export log..."); + click_help_item(&mut h, "Export Log"); let text = std::fs::read_to_string(&file).expect("the log file was written"); let lines: Vec<&str> = text.lines().collect(); @@ -102,6 +102,6 @@ fn export_log_writes_every_line_with_time_and_level() { fn a_canceled_export_log_dialog_writes_nothing() { let mut h = harness(); h.state_mut().file_dialogs.set_override(Some(Box::new(|_| Answer::Cancelled))); - click_help_item(&mut h, "Export log..."); + click_help_item(&mut h, "Export Log"); assert!(h.state().toasts.is_empty()); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 914bb830..ca01a381 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -20,6 +20,7 @@ mod display_post_effects; mod effect_decal; mod effect_rows; mod effect_sliders; +mod empty_menus; mod empty_start; mod export_file_types; mod export_map_overrides; diff --git a/crates/ui-egui/tests/it/named_layouts.rs b/crates/ui-egui/tests/it/named_layouts.rs index 18264949..31c36609 100644 --- a/crates/ui-egui/tests/it/named_layouts.rs +++ b/crates/ui-egui/tests/it/named_layouts.rs @@ -1,4 +1,4 @@ -//! Window > Layouts: save the panel arrangement under a name and switch to it from the menu. +//! Saved named-layout commands remain available to shortcuts and automation after their menu is removed. use egui::Role; use egui_kittest::Harness; @@ -15,14 +15,23 @@ fn app() -> Harness<'static, TextureCraftApp> { harness } -/// Open Window > Layouts, click `entry`, and let the app answer +/// Exercise the existing dialog through a bound shortcut; named layouts are no longer in the menu. fn layouts_menu(harness: &mut Harness<'_, TextureCraftApp>, entry: &str) { - harness.get_by_role_and_label(Role::Button, "Window").click(); - harness.run_steps(3); - harness.get_by_role_and_label(Role::Button, "Layouts").click(); - harness.run_steps(3); - harness.get_by_role_and_label(Role::Button, entry).click(); + let id = match entry { + "Save current layout as..." => "ui.layout.saveAs", + "Manage layouts..." => "ui.layout.manage", + name => { + let reply = invoke(harness, serde_json::json!({"id": "ui.layout.apply", "name": name})); + assert_eq!(reply["ok"], true); + harness.run_steps(3); + return; + } + }; + harness.state_mut().ui.keymap.insert(id.into(), "F12".into()); + harness.run_steps(2); + harness.key_press(egui::Key::F12); harness.run_steps(3); + harness.state_mut().ui.keymap.remove(id); } /// The dialog's text field: the one nearest the window center, where dialogs open (the shelf search is another) @@ -43,7 +52,7 @@ fn save_as(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { } #[test] -fn a_layout_saved_from_the_menu_comes_back_from_the_menu() { +fn a_layout_saved_from_a_shortcut_comes_back_through_automation() { let mut harness = app(); harness.state_mut().ui.dock.close(Panel::Assets); save_as(&mut harness, "No shelf"); @@ -110,12 +119,12 @@ fn invoke(harness: &mut Harness<'_, TextureCraftApp>, params: serde_json::Value) } #[test] -fn the_layout_items_are_in_the_menu_catalog_and_open_their_dialogs() { +fn legacy_layout_commands_stay_out_of_the_menu_and_open_their_dialogs() { use texturecraft_ui_egui::menus::CATALOG; use texturecraft_ui_egui::named_layouts::LayoutDialog; for id in ["ui.layout.saveAs", "ui.layout.manage"] { - assert!(CATALOG.iter().any(|item| item.id == id && item.menu == "Window" && item.sub == Some("Layouts")), "{id}"); + assert!(!CATALOG.iter().any(|item| item.id == id), "{id} is no longer a menu entry"); } let mut harness = app(); assert!(!texturecraft_ui_egui::menus::enabled(harness.state(), "ui.layout.manage"), "nothing to manage yet"); diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index 7d95b501..635deec3 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -393,7 +393,7 @@ fn create_asks_before_discarding_edits_made_after_the_form_opened() { h.get_by_role_and_label(Role::Button, "Create").click(); h.run_steps(3); - assert!(h.query_by_label("Unsaved changes").is_some()); + assert!(h.query_by_label("Unsaved Changes").is_some()); assert_eq!(h.state().session.doc.project.name, "Open"); h.get_by_role_and_label(Role::Button, "Don't save").click(); diff --git a/crates/ui-egui/tests/it/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs index f3943aee..092f7df3 100644 --- a/crates/ui-egui/tests/it/reference_order.rs +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -35,12 +35,12 @@ fn named<'a>(found: &'a [(f32, String, bool)], name: &str) -> Option<&'a (f32, S fn every_menu_lists_its_items_in_the_reference_order() { // Items the reference has and TextureCraft lacks are absent; TextureCraft's own sit where they fit let expected = [ - "File: New project... | Open... | - | Open sample project... | - | Close | - | Save | Save as... | More save options > Save as template... | More save options > Save and reduce file size | More save options > Save as copy... | Remove unused resources... | - | Import resources... | Import MaterialX material... | Import PBR texture folder... | Import material... | Export Textures... | Export Mesh... | - | Quit", - "Edit: Undo | Redo | Project Configuration... | Reimport mesh | Settings...", - "Mode: Bake Mesh Maps | Painting | Rendering (path traced)", - "Window: Views > Assets | Views > Common Settings | Views > Display Settings | Views > Export | Views > History | Views > Layers | Views > Log | Views > Mesh Map Bakers | Views > Mesh Map Settings | Views > Properties | Views > Python Console | Views > Renderer Settings | Views > Shader Settings | Views > Online assets | Views > Texture Sets | Views > Texture Set Settings | Toolbars > Docks | Toolbars > Plugins | Toolbars > Tools | - | Save UI Layout > Painting mode | Save UI Layout > Rendering mode | Save UI Layout > Baking mode | Load UI Layout | Layouts > Save current layout as... | Layouts > Manage layouts... | - | Hide UI | Reset panel layout | Reset UI", - "Viewport: Display material | Display next channel | Display previous channel | Display next mesh map | Display previous mesh map | UV checker | - | Frame texture set | Show entire mesh | Front view | Back view | Left view | Right view | Top view | Bottom view | - | Perspective | Orthographic | - | 3D/2D views | 3D view only | 2D view only | Swap 3D/2D | - | Navigation buttons | - | Enable quick mask | Edit quick mask | Invert quick mask", - "Help: Release notes... | Documentation... | Shortcuts list... | - | Join the community (Discord)... | ArtCraft website... | Report a bug... | Show log... | Export log... | - | Check for Updates... | About TextureCraft...", + "File: New Project | Open | Recent Projects > Clear | - | Open Sample Project | - | Close | - | Save | Save As | More Save Options > Save As Template | More Save Options > Save and Reduce File Size | More Save Options > Save As Copy | Remove Unused Resources | - | Import Resources | Export Textures | Export Mesh | - | Quit", + "Edit: Undo | Redo | Project Configuration | Reimport Mesh | Settings", + "Mode: Bake Mesh Maps | Painting | Rendering", + "Window: Views > Assets | Views > Baking Log | Views > Common Settings | Views > Display Settings | Views > Export | Views > History | Views > Layers | Views > Log | Views > Mesh Map Bakers | Views > Mesh Map Settings | Views > Properties | Views > Renderer Settings | Views > Shader Settings | Views > Texture Set List | Views > Texture Set Settings | Toolbars > Docks | Toolbars > Tools | - | Save UI Layout > Painting Mode | Save UI Layout > Rendering Mode | Save UI Layout > Baking Mode | Load UI Layout | - | Hide UI | Reset UI", + "Viewport: Display Material | Display Next Channel | Display Previous Channel | Display Next Mesh Map | Display Previous Mesh Map | - | Show Entire Mesh/Path | - | Enable Quick Mask | Edit Quick Mask | Invert Quick Mask", + "Help: Release Notes | Documentation | Shortcuts List | - | Discord | Report a Bug | Show Log | Export Log | - | Check for Updates | About TextureCraft", ]; let actual: Vec = menus::TOP .iter() @@ -168,7 +168,7 @@ fn the_blank_screen_menus_match_the_measured_enabled_states() { assert!(menus::enabled(app, id), "{id} is enabled on the blank screen"); } for id in ["ui.view.bakeSettings", "ui.view.bakeMaps", "ui.view.meshMapBakers"] { - assert!(!menus::enabled(app, id), "{id} belongs to Baking mode"); + assert!(!menus::enabled(app, id), "{id} belongs to Baking Mode"); } } diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index c2e31b66..dc5ef506 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -482,3 +482,31 @@ fn the_baking_options_say_when_there_is_no_gpu_to_trace_on() { let no_gpu = h.query_by_label("no GPU").is_some(); assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), no_gpu, "the note shows with no GPU and only then"); } + +#[test] +fn recent_project_limit_applies_on_ok_and_persists() { + let mut h = harness(Session::closed().unwrap()); + h.state_mut().ui.recent = (0..8).map(|i| format!("/projects/{i}.tcraft")).collect(); + open_settings(&mut h); + h.get_by_label("Recent projects limit").scroll_to_me(); + h.run_steps(3); + assert!(!h.get_by_label("Recent projects limit").accesskit_node().is_disabled()); + h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs.recent_projects_limit = 3; + click(&mut h, "Cancel"); + assert_eq!(h.state().ui.recent.len(), 8); + open_settings(&mut h); + h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs.recent_projects_limit = 3; + click(&mut h, "OK"); + assert_eq!(h.state().ui.recent, ["/projects/0.tcraft", "/projects/1.tcraft", "/projects/2.tcraft"]); + texturecraft_ui_egui::windows::remember(h.state_mut(), "/projects/new.tcraft"); + assert_eq!(h.state().ui.recent, ["/projects/new.tcraft", "/projects/0.tcraft", "/projects/1.tcraft"]); + let mut storage = MemoryStorage::default(); + eframe::App::save(h.state_mut(), &mut storage); + let restored: UiState = serde_json::from_str(&storage.values["ui.json"]).unwrap(); + assert_eq!(restored.prefs.recent_projects_limit, 3); + let ctx = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &ctx, "ui.set", &serde_json::json!({"prefs":{"recent_projects_limit":0}})); + assert_eq!(reply["ok"], true); + texturecraft_ui_egui::windows::remember(h.state_mut(), "/projects/another.tcraft"); + assert!(h.state().ui.recent.is_empty()); +} diff --git a/crates/ui-egui/tests/it/shortcut_list.rs b/crates/ui-egui/tests/it/shortcut_list.rs index f99db223..7d54c2a9 100644 --- a/crates/ui-egui/tests/it/shortcut_list.rs +++ b/crates/ui-egui/tests/it/shortcut_list.rs @@ -35,23 +35,23 @@ fn the_list_starts_with_the_reference_names_and_keys_in_the_reference_order() { ("Quit application", "Ctrl+Q"), ("Export Textures...", "Ctrl+Shift+E"), ("Reimport mesh", "Ctrl+Shift+R"), - ("Switch to baking mode", "Ctrl+Shift+B"), + ("Switch to baking mode", "F8"), ("Switch to edition mode", "F9"), ("Switch to rendering mode (path traced)", "F10"), ("Show mesh wireframe", ""), ("Camera projection: Perspective view", "F5"), ("Camera projection: Orthographic view", "F6"), - ("Display next channel", "C"), - ("Display previous channel", "Shift+C"), - ("Display material", "M"), - ("Display next mesh map", "B"), - ("Display previous mesh map", "Shift+B"), - ("Show entire mesh/path", "F"), + ("Display Next Channel", "C"), + ("Display Previous Channel", "Shift+C"), + ("Display Material", "M"), + ("Display Next Mesh Map", "B"), + ("Display Previous Mesh Map", "Shift+B"), + ("Show Entire Mesh/Path", "F"), ("Select next camera", ">"), ("Select previous camera", "<"), - ("Enable quick mask", "Y"), - ("Edit quick mask", "U"), - ("Invert quick mask", "Ctrl+Shift+I"), + ("Enable Quick Mask", "Y"), + ("Edit Quick Mask", "U"), + ("Invert Quick Mask", "Ctrl+Shift+I"), ("Viewers layout: 3D/2D", "F1"), ("Viewers layout: 3D only", "F2"), ("Viewers layout: 2D only", "F3"), @@ -82,9 +82,9 @@ fn the_menus_keep_their_texts_and_quit_keeps_ctrl_q() { assert_eq!(label("file.saveAs"), Some("Save as...")); assert_eq!(label("ui.quit"), Some("Quit")); assert_eq!(label("ui.mode.bake"), Some("Bake Mesh Maps")); - assert_eq!(label("viewport.frame"), Some("Show entire mesh")); + assert_eq!(label("viewport.frame"), Some("Show Entire Mesh/Path")); assert_eq!(shortcut_of(&keymap::Keymap::new(), "ui.quit"), Some("Ctrl+Q")); - assert_eq!(shortcut_of(&keymap::Keymap::new(), "ui.mode.bake"), Some("Ctrl+Shift+B")); + assert_eq!(shortcut_of(&keymap::Keymap::new(), "ui.mode.bake"), Some("F8")); } #[test] @@ -95,7 +95,7 @@ fn the_settings_page_lists_the_reference_names_and_shows_the_missing_functions_d h.run_steps(4); h.get_by_role_and_label(Role::Tab, "Shortcuts").click(); h.run_steps(4); - for name in ["Open project", "Save as project", "Quit application", "Switch to baking mode", "Show entire mesh/path", "Viewers layout: Swap 3D/2D"] { + for name in ["Open project", "Save as project", "Quit application", "Switch to baking mode", "Show Entire Mesh/Path", "Viewers layout: Swap 3D/2D"] { assert!(h.query_by_label(name).is_some(), "{name} is listed"); } assert!(h.query_by_label("Open...").is_none(), "the menu's text is not the list's"); @@ -110,8 +110,8 @@ fn the_settings_page_lists_the_reference_names_and_shows_the_missing_functions_d #[test] fn the_listed_keys_run_their_commands() { let mut h = harness(); - press(&mut h, Key::B, Modifiers::COMMAND | Modifiers::SHIFT); - assert_eq!(h.state().ui.mode, Mode::Baking, "Ctrl+Shift+B switches to baking mode"); + press(&mut h, Key::F8, Modifiers::NONE); + assert_eq!(h.state().ui.mode, Mode::Baking, "F8 switches to baking mode"); press(&mut h, Key::F9, Modifiers::NONE); assert_eq!(h.state().ui.mode, Mode::Painting, "F9 switches to edition mode"); press(&mut h, Key::F10, Modifiers::NONE); diff --git a/crates/ui-egui/tests/it/templates_681.rs b/crates/ui-egui/tests/it/templates_681.rs index c73ebe1d..430086e3 100644 --- a/crates/ui-egui/tests/it/templates_681.rs +++ b/crates/ui-egui/tests/it/templates_681.rs @@ -1,5 +1,5 @@ -//! Project templates: File > More save options (Save as template..., Save and reduce file size, -//! Save as copy...), the New project list's reference names and the remembered template +//! Project templates: File > More Save Options (Save As Template, Save and Reduce File Size, +//! Save As Copy), the New project list's reference names and the remembered template use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -23,7 +23,7 @@ fn app() -> Harness<'static, TextureCraftApp> { fn open_more_save_options(h: &mut Harness<'_, TextureCraftApp>) { h.get_by_label("File").click(); h.run_steps(3); - h.get_by_label("More save options").click(); + h.get_by_label("More Save Options").click(); h.run_steps(3); } @@ -43,7 +43,7 @@ fn save_as_template_asks_in_the_templates_folder_and_saves_without_a_message() { }))); open_more_save_options(&mut h); - h.get_by_label_contains("Save as template...").click(); + h.get_by_label_contains("Save As Template").click(); h.run_steps(4); let asked = asked.borrow(); @@ -83,12 +83,12 @@ fn a_saved_template_appears_in_new_project_with_the_your_assets_suffix() { fn save_and_reduce_file_size_is_greyed_with_the_hint() { let mut h = app(); open_more_save_options(&mut h); - let item = h.get_by_label_contains("Save and reduce file size"); + let item = h.get_by_label_contains("Save and Reduce File Size"); let at = item.rect().center(); h.hover_at(at); h.run_steps(30); assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "the hint shows on hover"); - assert!(h.get_by_label_contains("Save and reduce file size").accesskit_node().is_disabled(), "the item is greyed"); + assert!(h.get_by_label_contains("Save and Reduce File Size").accesskit_node().is_disabled(), "the item is greyed"); assert!(!menus::enabled(h.state(), "ui.saveReduced")); assert!(!menus::implemented("ui.saveReduced")); } diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs index 23fa3e40..7d91e558 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -46,7 +46,7 @@ fn narrow_toolbars_keep_scroll_arrows_and_mode_buttons_separate() { 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 (Ctrl+Shift+B)").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)); @@ -135,10 +135,8 @@ fn compact_view_buttons_can_be_scrolled_into_view_and_clicked() { #[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 (Ctrl+Shift+B)", Mode::Baking), ("Rendering (path traced) (F10)", Mode::Rendering), ("Painting (F9)", Mode::Painting)] - { - let bake = harness.get_by_label("Bake Mesh Maps (Ctrl+Shift+B)").rect(); + 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()); diff --git a/crates/ui-egui/tests/it/window_menu_684.rs b/crates/ui-egui/tests/it/window_menu_684.rs index ecb389c8..2480e326 100644 --- a/crates/ui-egui/tests/it/window_menu_684.rs +++ b/crates/ui-egui/tests/it/window_menu_684.rs @@ -10,7 +10,6 @@ use std::rc::Rc; use texturecraft_engine::Session; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; use texturecraft_ui_egui::state::Mode; -use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; use texturecraft_ui_egui::{TextureCraftApp, menus}; use super::temp_dir::TempDir; @@ -37,25 +36,16 @@ fn open_sub(h: &mut Harness<'_, TextureCraftApp>, name: &str) { h.run_steps(3); } -fn hover_hint(h: &mut Harness<'_, TextureCraftApp>, label: &str) -> bool { - let at = h.get_by_label_contains(label).rect().center(); - h.hover_at(egui::pos2(1.0, 1.0)); - h.run_steps(2); - h.hover_at(at); - h.run_steps(30); - h.query_by_label(NOT_AVAILABLE).is_some() -} - #[test] -fn views_lists_renderer_settings_and_the_greyed_entries_with_a_hint() { - let mut h = app(); +fn views_omit_unrequested_entries_and_disable_mode_specific_panels() { + let mut h = app_with(Session::closed().unwrap()); open_sub(&mut h, "Views"); - assert!(h.query_by_label_contains("Renderer Settings").is_some()); + for label in ["Baking Log", "Common Settings", "Mesh Map Bakers", "Mesh Map Settings", "Renderer Settings"] { + assert!(h.get_by_label_contains(label).accesskit_node().is_disabled(), "{label}"); + } for label in ["Python Console", "Online assets"] { - assert!(h.get_by_label_contains(label).accesskit_node().is_disabled(), "{label} is greyed"); + assert!(h.query_by_label_contains(label).is_none()); } - assert!(hover_hint(&mut h, "Python Console"), "Python Console says it is not available yet"); - assert!(hover_hint(&mut h, "Online assets"), "Online assets says it is not available yet"); } #[test] @@ -71,14 +61,13 @@ fn properties_names_the_tool_while_a_project_is_open() { } #[test] -fn toolbars_lists_docks_plugins_and_tools() { +fn toolbars_lists_only_docks_and_tools() { let mut h = app(); open_sub(&mut h, "Toolbars"); for label in ["Docks", "Tools"] { assert!(!h.get_by_label_contains(label).accesskit_node().is_disabled(), "{label}"); } - assert!(h.get_by_label_contains("Plugins").accesskit_node().is_disabled()); - assert!(hover_hint(&mut h, "Plugins")); + assert!(h.query_by_label_contains("Plugins").is_none()); assert!(h.state().ui.toolbar_docks && h.state().ui.toolbar_tools, "both bars start shown"); h.get_by_label_contains("Docks").click(); @@ -116,9 +105,9 @@ fn hide_ui_shows_its_check_mark() { fn save_ui_layout_has_one_entry_per_mode_and_writes_that_modes_layout() { let dir = TempDir::new("layout-per-mode"); for (item, file, mode, baking) in [ - ("Painting mode", "p.json", Mode::Painting, false), - ("Rendering mode", "r.json", Mode::Rendering, false), - ("Baking mode", "b.json", Mode::Baking, true), + ("Painting Mode", "p.json", Mode::Painting, false), + ("Rendering Mode", "r.json", Mode::Rendering, false), + ("Baking Mode", "b.json", Mode::Baking, true), ] { let mut h = app(); let path = dir.join(file); @@ -130,7 +119,10 @@ fn save_ui_layout_has_one_entry_per_mode_and_writes_that_modes_layout() { let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap_or_else(|e| panic!("{item}: {e}"))).unwrap(); assert_eq!(saved["mode"], serde_json::to_value(mode).unwrap(), "{item}"); - assert_eq!(saved["dock_is_baking"], baking, "{item}: the file's dock is the mode's own"); + assert!(saved.get("inactive_mode_dock").is_none(), "only one mode is saved"); + assert!(saved.get("prefs").is_none(), "preferences are not a layout"); + let dock = texturecraft_ui_egui::docking::Dock::from_value(saved["dock"].clone()); + assert_eq!(dock.is_open(texturecraft_ui_egui::docking::Panel::MeshMapBakers), baking); assert_eq!(h.state().ui.mode, Mode::Painting, "saving does not switch the mode"); } } @@ -152,7 +144,7 @@ fn the_legacy_layout_save_command_saves_the_active_mode() { assert_eq!(reply["ok"], true); let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); assert_eq!(saved["mode"], serde_json::to_value(Mode::Baking).unwrap()); - assert_eq!(saved["dock_is_baking"], true); + assert!(saved.get("inactive_mode_dock").is_none()); } #[test] diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index b29ce0ed..f7ad6880 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::core::{BakeResolution, BakedMap, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -28,6 +28,16 @@ fn save(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { let img = harness.render().unwrap_or_else(|e| panic!("{name}: {e}")); let path = dir.join(format!("{name}.png")); img.save(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let tree = [egui::Role::Button, egui::Role::SpinButton, egui::Role::CheckBox] + .into_iter() + .flat_map(|role| harness.get_all_by_role(role)) + .filter_map(|button| { + let node = button.accesskit_node(); + node.label().map(|label| format!("{label}: disabled={}, checked={:?}", node.is_disabled(), node.toggled())) + }) + .collect::>() + .join("\n"); + std::fs::write(dir.join(format!("{name}.txt")), tree).unwrap(); eprintln!("wrote {}", path.display()); } @@ -41,6 +51,28 @@ fn empty_start_snapshot() { harness.state_mut().ui.prefs.language = "en".into(); save(&mut harness, &output_dir, "empty-start"); + for top in ["File", "Edit", "Mode", "Window", "Viewport", "Help"] { + harness.get_by_label(top).click(); + harness.run_steps(4); + save(&mut harness, &output_dir, &format!("empty-menu-{top}")); + if top == "Window" { + harness.get_by_label("Views").click(); + save(&mut harness, &output_dir, "empty-menu-views"); + } + harness.key_press(egui::Key::Escape); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + } + harness.state_mut().ui.toolbar_tools = false; + save(&mut harness, &output_dir, "empty-tools-off"); + for label in ["Snooze Autosave", "Resources Updater"] { + assert!(harness.get_by_label(label).accesskit_node().is_disabled()); + } + harness.get_by_label("Edit").click(); + harness.run_steps(3); + harness.get_by_label("Settings").click(); + save(&mut harness, &output_dir, "settings-recent-project-limit"); + assert!(!harness.get_by_label("Recent projects limit").accesskit_node().is_disabled()); } /// Closing rejects a same-frame capture, then releases both rendered view targets. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bd11cb2d..0491bce2 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -173,21 +173,31 @@ keeps its state in a throwaway file. | `command.list` | `{filter?}` | `[{id, label, menu, shortcut, params, enabled}]` | | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | | `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | -| `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled}` | -| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a panel layout saved under Window > Layouts (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save that mode's layout as a JSON file, `ui.layout.load` asks for one to load ("Select a UI layout file."); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the tool shelf (`ui.toolbar.plugins`, `ui.view.pythonConsole` and `ui.view.onlineAssets` are listed as not implemented and not enabled); `ui.view.renderer` toggles the Renderer Settings panel (Rendering mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | -| `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More save options > Save as template... opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and reduce file size) is listed as not implemented and not enabled | -| `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.exportLog` | `{id}` | Help > Release notes... opens the releases page in the browser; Help > Export log... exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop, a download on the web) | -| `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (Ctrl+Shift+B) run the same commands as before | +| `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` | +| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Select a UI layout file."); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | +| `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled | +| `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) | +| `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before | | `ui.reset` | | resets the panels, view layout, zoom and every other view setting at once, without the question the Reset UI menu item asks; settings and shortcuts stay | | `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | | `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back | -| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | +| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`, `BakingLog`, `MeshMapBakers`, `MeshMapSettings`, `CommonSettings`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | | `ui.resize` | `{width, height}` | Sets the window's inner size in points (640–7680), leaving maximized state; for recordings and screenshots at a fixed size | | `debug.paintTest` | `{from: [x, y], to: [x, y], frames?: 120}` | Paints a straight stroke through the real frame loop (viewport pixels, one point per frame) for performance work | | `debug.frames` | | Frame timing since the last call (then cleared): `{frames, intervalMs, uiMs, syncMs, logicMs}` each `{avg, p95, max}`; `syncMs` is compositing plus display tile conversion, `logicMs` input, control requests and scripted strokes before the UI is built; `worst` breaks down the slowest frame; `strokeEnd` lists the frame that committed a `debug.paintTest` stroke and the one after it (null without one) | +The empty-project menus keep Recent Projects openable with Clear disabled when the list is empty. +`ui.recent.clear` clears that list. More Save Options is disabled until a project is open. +Help > Shortcuts list opens Settings on its Shortcuts page. Window > Reset UI restores the +Assets, Layers, Properties, Texture Set List and Texture Set Settings panels and both toolbars. +Baking Log and the bake/render settings views are disabled without a project. Import resources +can open its dialog on desktop without a project; importing still requires an open project, +and the dialog explains that asset-library import is not available yet. + +Settings > General > Recent Projects limit controls the retained history (default 10, range 0–100; 0 disables history). Automation uses `ui.set {"prefs":{"recent_projects_limit":10}}`. A lower limit trims the oldest paths immediately. + Example session: ```text @@ -527,13 +537,13 @@ In the app, `viewport.frame` also resets the 2D view (pan, zoom and rotation), a `camera.view {view}` looks at the mesh from one side (`front` from +Z, `back`, `left` from -X, `right`, `top` and `bottom` at the orbit's ±89° pitch limit) and frames it; the projection stays. -`camera.view.front` … `camera.view.bottom` do the same without params (Viewport menu, no default +`camera.view.front` … `camera.view.bottom` do the same without params (no default shortcut, bindable in Settings ▸ Shortcuts). `camera.perspective` (F5) and `camera.orthographic` (F6) change only the projection; position and rotation stay. None of them is an undo step. In the 3D view, Alt+Shift+left drag orbits in 90° steps. `camera.rotation {mode: constrained|free}` (or `camera.rotation.constrained` / `camera.rotation.free`, -Viewport menu and the rotation dropdown of the top bar) picks the orbit: constrained (the default) keeps +the rotation dropdown of the top bar) picks the orbit: constrained (the default) keeps the horizon level and stops at the poles; free is a trackball that turns the camera about its own axes, so the model can be turned over and rolled. `camera.get` shows it as `rotation`; `camera.set` takes `rotation` too. Switching keeps the direction of view; going back to constrained drops the roll. diff --git a/docs/parity.md b/docs/parity.md index 504e685e..a8bc242d 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,28 +2,26 @@ 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). -**83 of 87 menu items live (95%).** +**63 of 64 menu items live (98%).** ## File | Item | Id | Shortcut | Status | |---|---|---|---| -| New project... | `ui.newProject` | Ctrl+N | live | -| Open... | `file.open` | Ctrl+O | live | -| Open sample project... | `project.sample` | | live | +| New Project | `ui.newProject` | Ctrl+N | live | +| Open | `file.open` | Ctrl+O | live | +| Recent Projects ▸ Clear | `ui.recent.clear` | | live | +| Open Sample Project | `project.sample` | | live | | Close | `file.close` | Ctrl+F4 | live | | Save | `file.save` | Ctrl+S | live | -| Save as... | `file.saveAs` | Ctrl+Shift+S | live | -| More save options ▸ Save as template... | `ui.saveAsTemplate` | | live | -| More save options ▸ Save and reduce file size | `ui.saveReduced` | | missing | -| More save options ▸ Save as copy... | `file.saveCopy` | | live | -| Remove unused resources... | `file.removeUnused` | | live | -| Import resources... | `resource.import` | | live | -| Import MaterialX material... | `file.importMaterialX` | | live | -| Import PBR texture folder... | `file.importPbrFolder` | | live | -| Import material... | `material.load` | | live | -| Export Textures... | `ui.export` | Ctrl+Shift+E | live | -| Export Mesh... | `file.exportMesh` | | live | +| Save As | `file.saveAs` | Ctrl+Shift+S | live | +| More Save Options ▸ Save As Template | `ui.saveAsTemplate` | | live | +| More Save Options ▸ Save and Reduce File Size | `ui.saveReduced` | | missing | +| More Save Options ▸ Save As Copy | `file.saveCopy` | | live | +| Remove Unused Resources | `file.removeUnused` | | live | +| Import Resources | `resource.import` | | live | +| Export Textures | `ui.export` | Ctrl+Shift+E | live | +| Export Mesh | `file.exportMesh` | | live | | Quit | `ui.quit` | Ctrl+Q | live | ## Edit @@ -32,23 +30,24 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac |---|---|---|---| | Undo | `edit.undo` | Ctrl+Z | live | | Redo | `edit.redo` | Ctrl+Y | live | -| Project Configuration... | `ui.projectConfig` | | live | -| Reimport mesh | `file.reimportMesh` | Ctrl+Shift+R | live | -| Settings... | `ui.settings` | | live | +| Project Configuration | `ui.projectConfig` | | live | +| Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | +| Settings | `ui.settings` | | live | ## Mode | Item | Id | Shortcut | Status | |---|---|---|---| -| Bake Mesh Maps | `ui.mode.bake` | Ctrl+Shift+B | live | +| Bake Mesh Maps | `ui.mode.bake` | F8 | live | | Painting | `ui.mode.paint` | F9 | live | -| Rendering (path traced) | `ui.mode.render` | F10 | live | +| Rendering | `ui.mode.render` | F10 | live | ## Window | Item | Id | Shortcut | Status | |---|---|---|---| | Views ▸ Assets | `ui.view.assets` | | live | +| Views ▸ Baking Log | `ui.view.bakingLog` | | live | | Views ▸ Common Settings | `ui.view.bakeSettings` | | live | | Views ▸ Display Settings | `ui.view.display` | | live | | Views ▸ Export | `ui.view.export` | | live | @@ -58,66 +57,44 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Views ▸ Mesh Map Bakers | `ui.view.meshMapBakers` | | live | | Views ▸ Mesh Map Settings | `ui.view.bakeMaps` | | live | | Views ▸ Properties | `ui.view.properties` | | live | -| Views ▸ Python Console | `ui.view.pythonConsole` | | missing | | Views ▸ Renderer Settings | `ui.view.renderer` | | live | | Views ▸ Shader Settings | `ui.view.shader` | | live | -| Views ▸ Online assets | `ui.view.onlineAssets` | | missing | -| Views ▸ Texture Sets | `ui.view.textureSetList` | | live | +| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | | Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | | Toolbars ▸ Docks | `ui.toolbar.docks` | | live | -| Toolbars ▸ Plugins | `ui.toolbar.plugins` | | missing | | Toolbars ▸ Tools | `ui.toolbar.tools` | | live | -| Save UI Layout ▸ Painting mode | `ui.layout.save.painting` | | live | -| Save UI Layout ▸ Rendering mode | `ui.layout.save.rendering` | | live | -| Save UI Layout ▸ Baking mode | `ui.layout.save.baking` | | live | +| Save UI Layout ▸ Painting Mode | `ui.layout.save.painting` | | live | +| Save UI Layout ▸ Rendering Mode | `ui.layout.save.rendering` | | live | +| Save UI Layout ▸ Baking Mode | `ui.layout.save.baking` | | live | | Load UI Layout | `ui.layout.load` | | live | -| Layouts ▸ Save current layout as... | `ui.layout.saveAs` | | live | -| Layouts ▸ Manage layouts... | `ui.layout.manage` | | live | | Hide UI | `ui.hideUi` | Tab | live | -| Reset panel layout | `ui.resetPanelLayout` | | live | | Reset UI | `ui.resetUi` | | live | ## Viewport | Item | Id | Shortcut | Status | |---|---|---|---| -| Display material | `viewport.displayMaterial` | M | live | -| Display next channel | `viewport.nextChannel` | C | live | -| Display previous channel | `viewport.previousChannel` | Shift+C | live | -| Display next mesh map | `viewport.nextMeshMap` | B | live | -| Display previous mesh map | `viewport.previousMeshMap` | Shift+B | live | -| UV checker | `ui.uvChecker` | | live | -| Frame texture set | `viewport.frameSelection` | Shift+F | live | -| Show entire mesh | `viewport.frame` | F | live | -| Front view | `camera.view.front` | | live | -| Back view | `camera.view.back` | | live | -| Left view | `camera.view.left` | | live | -| Right view | `camera.view.right` | | live | -| Top view | `camera.view.top` | | live | -| Bottom view | `camera.view.bottom` | | live | -| Perspective | `camera.perspective` | F5 | live | -| Orthographic | `camera.orthographic` | F6 | live | -| 3D/2D views | `ui.layout.split` | F1 | live | -| 3D view only | `ui.layout.3d` | F2 | live | -| 2D view only | `ui.layout.2d` | F3 | live | -| Swap 3D/2D | `ui.layout.swap` | F4 | live | -| Navigation buttons | `ui.navButtons` | | live | -| Enable quick mask | `viewport.quickMask` | Y | live | -| Edit quick mask | `viewport.quickMask.edit` | U | live | -| Invert quick mask | `viewport.quickMask.invert` | Ctrl+Shift+I | live | +| Display Material | `viewport.displayMaterial` | M | live | +| Display Next Channel | `viewport.nextChannel` | C | live | +| Display Previous Channel | `viewport.previousChannel` | Shift+C | live | +| Display Next Mesh Map | `viewport.nextMeshMap` | B | live | +| Display Previous Mesh Map | `viewport.previousMeshMap` | Shift+B | live | +| Show Entire Mesh/Path | `viewport.frame` | F | live | +| Enable Quick Mask | `viewport.quickMask` | Y | live | +| Edit Quick Mask | `viewport.quickMask.edit` | U | live | +| Invert Quick Mask | `viewport.quickMask.invert` | Ctrl+Shift+I | live | ## Help | Item | Id | Shortcut | Status | |---|---|---|---| -| Release notes... | `ui.help.releaseNotes` | | live | -| Documentation... | `ui.help.docs` | | live | -| Shortcuts list... | `ui.help.shortcuts` | | live | -| Join the community (Discord)... | `ui.help.discord` | | live | -| ArtCraft website... | `ui.help.website` | | live | -| Report a bug... | `ui.help.bug` | | live | -| Show log... | `ui.view.log` | | live | -| Export log... | `ui.help.exportLog` | | live | -| Check for Updates... | `ui.help.checkForUpdates` | | live | -| About TextureCraft... | `ui.about` | | live | +| Release Notes | `ui.help.releaseNotes` | | live | +| Documentation | `ui.help.docs` | | live | +| Shortcuts List | `ui.help.shortcuts` | | live | +| Discord | `ui.help.discord` | | live | +| Report a Bug | `ui.help.bug` | | live | +| Show Log | `ui.help.showLog` | | live | +| Export Log | `ui.help.exportLog` | | live | +| Check for Updates | `ui.help.checkForUpdates` | | live | +| About TextureCraft | `ui.about` | | live | From 08df994708d1345daa617ceb9a251fa4aaedf201 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 20 Nov 2026 04:16:10 -0500 Subject: [PATCH 002/153] Remove extra dependency notices and hardcoded shortcut hints --- ATTRIBUTION.md | 10 ---------- NOTICE | 7 ------- crates/ui-egui/src/color_selection_editor.rs | 2 +- crates/ui-egui/src/generator_panel.rs | 4 +--- crates/ui-egui/tests/it/color_selection_editor.rs | 2 +- 5 files changed, 3 insertions(+), 22 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 6d8f3963..5d607a5c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -46,13 +46,3 @@ Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedur (`crates/paint/src/brush.rs`), meshes (`crates/geom/src/primitives.rs`) and shelf thumbnails (`crates/ui-egui/src/thumbs.rs`) are generated in code by TextureCraft contributors (MIT OR Apache-2.0). None of them is derived from another product's presets, shaders, materials or images. - -## Default-browser integration dependencies - -The desktop app enables eframe's `links` feature. These unmodified Rust dependencies open links in the system browser and parse their URLs; their upstream MIT and Apache-2.0 licence files remain in the published crates. - -| Dependency | Source | License | -|---|---|---| -| `webbrowser` 1.2.7 | https://github.com/amodm/webbrowser-rs | MIT OR Apache-2.0 | -| `url` 2.5.8, `idna` 1.1.0, `form_urlencoded` 1.2.2 | https://github.com/servo/rust-url | MIT OR Apache-2.0 | -| `idna_adapter` 1.2.2 | https://github.com/hsivonen/idna_adapter | Apache-2.0 OR MIT | diff --git a/NOTICE b/NOTICE index 39ead11d..a6c9da4b 100644 --- a/NOTICE +++ b/NOTICE @@ -25,10 +25,3 @@ in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (Inter and BIZ UDPGothic on desktop and web, Noto Sans CJK SC on desktop), under the SIL Open Font License 1.1. Their licence texts ship with the package as OFL-.txt. - -Default-browser integration (eframe's links feature): -webbrowser 1.2.7 — MIT OR Apache-2.0, https://github.com/amodm/webbrowser-rs. -url 2.5.8, idna 1.1.0 and form_urlencoded 1.2.2 — MIT OR Apache-2.0, -https://github.com/servo/rust-url. -idna_adapter 1.2.2 — Apache-2.0 OR MIT, https://github.com/hsivonen/idna_adapter. -These dependencies are used unmodified; their published crates retain the upstream licence files. diff --git a/crates/ui-egui/src/color_selection_editor.rs b/crates/ui-egui/src/color_selection_editor.rs index 482bc227..d538c5ca 100644 --- a/crates/ui-egui/src/color_selection_editor.rs +++ b/crates/ui-egui/src/color_selection_editor.rs @@ -32,7 +32,7 @@ pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index); let has_id_map = app.session.baked(set_index).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Id)); if !has_id_map { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (F8) to pick colors from the mesh."))).color(tokens.warning)); + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map to pick colors from the mesh."))).color(tokens.warning)); } let picking = app.picking_id_color.filter(|pick| pick.effect == effect); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index d15be0e4..d635ecf3 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -58,9 +58,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer }); } 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(tokens.warning), - ); + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps for curvature, AO and thickness based generators."))).color(tokens.warning)); } } diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 34a32c0c..1e7bfef6 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -120,7 +120,7 @@ fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { #[test] fn without_an_id_map_picking_is_off_and_a_warning_says_why() { let (mut harness, _) = app_with_color_selection(false); - let warning = format!("{} Bake an ID map (F8) to pick colors from the mesh.", egui_phosphor::regular::WARNING); + let warning = format!("{} Bake an ID map to pick colors from the mesh.", egui_phosphor::regular::WARNING); assert!(harness.query_by_label(&warning).is_some()); harness.get_by_label(&pick_color_label()).click(); From eb126f6f591ff28d237747beb2d4e74337ede4e0 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:00:40 +0800 Subject: [PATCH 003/153] Account for banded PNG memory in MCMAT cooks (#729) --- crates/engine/src/link_cmds/link_job.rs | 2 +- crates/formats/src/mcmat.rs | 32 ++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/link_cmds/link_job.rs b/crates/engine/src/link_cmds/link_job.rs index 2bfb8595..56d57ec1 100644 --- a/crates/engine/src/link_cmds/link_job.rs +++ b/crates/engine/src/link_cmds/link_job.rs @@ -232,7 +232,7 @@ impl LinkJob { continue; }; - let temporary_bytes = texturecraft_formats::mcmat::mesh_map_png_working_bytes(bakes.resolution, map.components()); + let temporary_bytes = texturecraft_formats::mcmat::mesh_map_png_working_bytes(bakes.resolution, bakes.height(map), map.components()); budget.check(temporary_bytes)?; budget.check_available(temporary_bytes)?; if self.canceled.load(Ordering::Relaxed) { diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 319b4666..d542b3a6 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -79,11 +79,23 @@ pub fn mesh_map_png(width: u32, components: usize, data: &[f32]) -> Result u64 { +/// Estimated temporary workspace for `write_mesh_map_png` with a file destination. +pub fn mesh_map_png_working_bytes(width_px: u32, height_px: u32, components: usize) -> u64 { + // PngRows in the pinned codec deflates bands of up to 512 KiB filtered bytes, + // or one scanline for wider images. + const DEFLATE_BAND_BYTES: u64 = 512 << 10; const DEFLATE_WORKSPACE_BYTES: u64 = 1 << 20; - u64::from(width_px).saturating_mul(components as u64).saturating_mul(4 * std::mem::size_of::() as u64).saturating_add(DEFLATE_WORKSPACE_BYTES) + let row_bytes = u64::from(width_px).saturating_mul(components as u64).saturating_mul(std::mem::size_of::() as u64); + let filtered_row_bytes = row_bytes.saturating_add(1); + let band_rows = (DEFLATE_BAND_BYTES / filtered_row_bytes).max(1).min(u64::from(height_px)); + let pending = row_bytes.saturating_mul(band_rows).saturating_mul(2); + let filtered = filtered_row_bytes.saturating_mul(band_rows); + let deflated = filtered.saturating_add(filtered / 8).saturating_add(1_024); + // Include spare row capacity and keep both the deflate output and the + // assembled zlib buffer in the estimate. Input floats are already charged. + let row_buffers = row_bytes.saturating_mul(8); + row_buffers.saturating_add(pending).saturating_add(filtered).saturating_add(deflated.saturating_mul(2)).saturating_add(DEFLATE_WORKSPACE_BYTES) } /// Encode a mesh map directly into its destination using one row of quantized samples. @@ -129,6 +141,20 @@ mod tests { use super::*; use std::io::Cursor; + #[test] + fn mesh_map_png_budget_covers_live_band_allocations() { + // The pinned encoder holds 85 rows for a 1024px RGB16 map. These + // three reserves coexist while deflating, even for compressible data. + const PENDING_BYTES: u64 = 522_240; + const FILTERED_BYTES: u64 = 522_325; + const DEFLATE_OUTPUT_BYTES: u64 = 588_639; + let unavoidable_workspace = PENDING_BYTES + FILTERED_BYTES + DEFLATE_OUTPUT_BYTES; + let estimate = mesh_map_png_working_bytes(1_024, 1_024, 3); + assert!(estimate >= unavoidable_workspace, "estimated {estimate} bytes for at least {unavoidable_workspace} bytes of workspace"); + assert!(mesh_map_png_working_bytes(1_024, 1, 3) < estimate); + assert_eq!(mesh_map_png_working_bytes(u32::MAX, u32::MAX, usize::MAX), u64::MAX); + } + #[test] fn recognizes_v3_and_directs_older_authors_to_republish() { let source = craft_mcmat::write(b"", []).unwrap(); From 391c98afa2805b39d34e6b87a0eb9413d15cb5bc Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 02:34:41 +0800 Subject: [PATCH 004/153] Decode imported PNG resources with the shared codec (#733) * Decode imported PNG resources with the shared codec * Preserve exact luminance and RGB sample conversion * fix(formats): preserve texel limit error message for imported PNGs --------- Co-authored-by: Dylan M. Taylor --- crates/formats/src/image_res.rs | 81 ++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 30be2e61..676b40d0 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -1,6 +1,6 @@ //! Decoding imported image resources (fills, alphas, stencils). -use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, PngCompression, SampleType}; +use craft_image_codecs::{ChannelLayout, CodecError, DecodeOptions, EncodeOptions, Format, Image, Limits, PngCompression, SampleType}; use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result}; @@ -23,7 +23,57 @@ pub fn decode_image(bytes: &[u8]) -> Result { /// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the /// header, before any pixel is decoded or allocated. pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result { - decode_image_with_limits(bytes, max_texels, image::Limits::default()) + let limits = image::Limits::default(); + if craft_image_codecs::detect(bytes) == Some(Format::Png) { + return decode_imported_png(bytes, max_texels, limits.max_alloc.unwrap_or(u64::MAX)); + } + decode_image_with_limits(bytes, max_texels, limits) +} + +fn decode_imported_png(bytes: &[u8], max_texels: u64, max_alloc: u64) -> Result { + if let Ok((width, height, _)) = craft_image_codecs::png_probe::header(bytes) { + if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE { + return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})"))); + } + if u64::from(width) * u64::from(height) > max_texels { + return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels"))); + } + } + let options = DecodeOptions { limits: Limits::new(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, max_texels, max_alloc), keep_orientation: true }; + let png = crate::guard("image", || { + craft_image_codecs::decode_as_with(Format::Png, bytes, &options).map_err(|error| match error { + CodecError::LimitExceeded(message) => FormatError::TooLarge(message), + error => crate::malformed("image", error), + }) + })?; + let layout = png.layout(); + let (green, blue, alpha) = match layout { + ChannelLayout::Gray => (0, 0, None), + ChannelLayout::GrayA => (0, 0, Some(1)), + ChannelLayout::Rgb => (1, 2, None), + ChannelLayout::Rgba => (1, 2, Some(3)), + _ => return Err(crate::malformed("image", "unexpected PNG channel layout")), + }; + let (read_sample, max): (fn(&[u8]) -> f32, f32) = match png.sample_type() { + SampleType::U8 => (|bytes| f32::from(bytes[0]), f32::from(u8::MAX)), + SampleType::U16 => (|bytes| f32::from(u16::from_ne_bytes([bytes[0], bytes[1]])), f32::from(u16::MAX)), + _ => return Err(crate::malformed("image", "unexpected PNG sample type")), + }; + // Match the previous decoder's cast: gray expansion multiplies by the reciprocal, + // and direct RGB and RGBA casts divide. Gray16 cache/reload relies on the exact values. + let reciprocal = 1.0 / max; + let sample_bytes = png.sample_type().bytes(); + let pixels = png.data().chunks_exact(layout.channels() * sample_bytes); + let mut rgba = Vec::new(); + rgba.try_reserve_exact(pixels.len()).map_err(|error| FormatError::TooLarge(error.to_string()))?; + rgba.extend(pixels.map(|pixel| { + let at = |channel: usize| { + let sample = read_sample(&pixel[channel * sample_bytes..]); + if layout.is_gray() { sample * reciprocal } else { sample / max } + }; + [at(0), at(green), at(blue), alpha.map_or(1.0, at)] + })); + Ok(DecodedImage { width: png.width(), height: png.height(), rgba, srgb: true }) } /// Decode a cook output under both its declared dimensions and decoder allocation budget. @@ -286,6 +336,33 @@ mod tests { assert!(decode_image(&png).is_ok()); } + #[test] + fn imported_png_keeps_color_under_alpha_and_gray16_precision() { + let rgba = image::DynamicImage::ImageRgba8( + image::RgbaImage::from_raw(2, 2, vec![61, 113, 173, 0, 37, 103, 237, 81, 34, 99, 5, 193, 89, 211, 239, 255]).unwrap(), + ); + let gray_alpha = image::DynamicImage::ImageLumaA16(image::ImageBuffer::from_raw(2, 2, vec![1234, 0, 1, 27, 0xabcd, 60211, 0xffff, 0xffff]).unwrap()); + for pixels in [rgba, gray_alpha] { + let mut png = Vec::new(); + pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let expected = pixels.into_rgba32f(); + let imported = decode_image_within(&png, 4).unwrap(); + assert_eq!((imported.width, imported.height), (2, 2)); + assert!(imported.srgb); + assert_eq!(imported.rgba, expected.into_raw().as_chunks::<4>().0); + } + } + + #[test] + fn png_import_checks_texels_before_requiring_the_pixel_payload() { + let png = coverage_png(4, 3, &[255; 12], [13, 27, 83]).unwrap(); + // PNG signature followed by a complete IHDR (length, type, 13-byte data and CRC). + let header = &png[..33]; + assert!(matches!(decode_image_within(header, 11), Err(FormatError::TooLarge(_)))); + assert!(matches!(decode_image_within(header, 12), Err(FormatError::Malformed { .. }))); + assert!(decode_image_within(&png, 12).is_ok()); + } + #[test] fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() { // The edge limit permits 16384² but the default resource budget does not From cfb94811ebcea12d9a9558f95be43663a24fd7d1 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 06:47:48 +0800 Subject: [PATCH 005/153] formats: decode cooked linked PNGs through the shared codec --- crates/formats/src/image_res.rs | 53 ++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 676b40d0..903b5b53 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -25,21 +25,21 @@ pub fn decode_image(bytes: &[u8]) -> Result { pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result { let limits = image::Limits::default(); if craft_image_codecs::detect(bytes) == Some(Format::Png) { - return decode_imported_png(bytes, max_texels, limits.max_alloc.unwrap_or(u64::MAX)); + return decode_png(bytes, Limits::new(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, max_texels, limits.max_alloc.unwrap_or(u64::MAX))); } decode_image_with_limits(bytes, max_texels, limits) } -fn decode_imported_png(bytes: &[u8], max_texels: u64, max_alloc: u64) -> Result { +fn decode_png(bytes: &[u8], limits: Limits) -> Result { if let Ok((width, height, _)) = craft_image_codecs::png_probe::header(bytes) { if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE { return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})"))); } - if u64::from(width) * u64::from(height) > max_texels { - return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels"))); + if u64::from(width) * u64::from(height) > limits.max_pixels { + return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {} texels", limits.max_pixels))); } } - let options = DecodeOptions { limits: Limits::new(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, max_texels, max_alloc), keep_orientation: true }; + let options = DecodeOptions { limits, keep_orientation: true }; let png = crate::guard("image", || { craft_image_codecs::decode_as_with(Format::Png, bytes, &options).map_err(|error| match error { CodecError::LimitExceeded(message) => FormatError::TooLarge(message), @@ -78,11 +78,16 @@ fn decode_imported_png(bytes: &[u8], max_texels: u64, max_alloc: u64) -> Result< /// Decode a cook output under both its declared dimensions and decoder allocation budget. pub fn decode_cooked_image(bytes: &[u8], size: [u32; 2], max_decoder_bytes: u64) -> Result { + let [width, height] = size; + let texels = (u64::from(width) * u64::from(height)).min(MAX_RESOURCE_TEXELS); + if craft_image_codecs::detect(bytes) == Some(Format::Png) { + let limits = Limits::new(width.min(MAX_IMAGE_SIZE), height.min(MAX_IMAGE_SIZE), texels, max_decoder_bytes); + return decode_png(bytes, limits); + } let mut limits = image::Limits::default(); limits.max_alloc = Some(max_decoder_bytes); - limits.max_image_width = Some(size[0]); - limits.max_image_height = Some(size[1]); - let texels = (u64::from(size[0]) * u64::from(size[1])).min(MAX_RESOURCE_TEXELS); + limits.max_image_width = Some(width); + limits.max_image_height = Some(height); decode_image_with_limits(bytes, texels, limits) } @@ -337,22 +342,48 @@ mod tests { } #[test] - fn imported_png_keeps_color_under_alpha_and_gray16_precision() { + fn imported_and_cooked_png_keeps_color_under_alpha_and_integer_precision() { + use image::ImageEncoder; + let rgba = image::DynamicImage::ImageRgba8( image::RgbaImage::from_raw(2, 2, vec![61, 113, 173, 0, 37, 103, 237, 81, 34, 99, 5, 193, 89, 211, 239, 255]).unwrap(), ); let gray_alpha = image::DynamicImage::ImageLumaA16(image::ImageBuffer::from_raw(2, 2, vec![1234, 0, 1, 27, 0xabcd, 60211, 0xffff, 0xffff]).unwrap()); - for pixels in [rgba, gray_alpha] { + let rgb = + image::DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(2, 2, vec![0, 19, 256, 17, 1_235, 89, 0xabcd, 1_024, 65_534, 0, 1, 65_535]).unwrap()); + for pixels in [rgba, gray_alpha, rgb] { let mut png = Vec::new(); - pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + // A generated TIFF Orientation=6 tag. Cooked data maps stay in stored row order. + let exif = b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0"; + encoder.set_exif_metadata(exif.to_vec()).unwrap(); + encoder.write_image(pixels.as_bytes(), 2, 2, pixels.color().into()).unwrap(); let expected = pixels.into_rgba32f(); let imported = decode_image_within(&png, 4).unwrap(); assert_eq!((imported.width, imported.height), (2, 2)); assert!(imported.srgb); assert_eq!(imported.rgba, expected.into_raw().as_chunks::<4>().0); + assert_eq!(decode_cooked_image(&png, [2, 2], 1 << 20).unwrap(), imported); } } + #[test] + fn cooked_png_checks_reported_sides_and_decoder_allowance() { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(8, 2, image::Rgba([3, 47, 187, 0])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let header = &png[..33]; + // Each report allows 16 texels but falls short on an individual axis. + for size in [[4, 4], [16, 1]] { + for data in [png.as_slice(), header] { + assert!(matches!(decode_cooked_image(data, size, 1 << 20), Err(FormatError::TooLarge(_)))); + } + } + assert!(matches!(decode_cooked_image(header, [8, 2], 1 << 20), Err(FormatError::Malformed { .. }))); + assert!(matches!(decode_cooked_image(&png, [8, 2], 8 * 2 * 4 - 1), Err(FormatError::TooLarge(_)))); + let valid = decode_cooked_image(&png, [8, 2], 1 << 20).unwrap(); + assert_eq!([valid.width, valid.height], [8, 2]); + } + #[test] fn png_import_checks_texels_before_requiring_the_pixel_payload() { let png = coverage_png(4, 3, &[255; 12], [13, 27, 83]).unwrap(); From b8afd896fa7e9a23fdfbecf977a422a1c3beec20 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Sun, 22 Nov 2026 12:48:52 +0800 Subject: [PATCH 006/153] formats: share PNG inspection for GLB and USD export (#751) --- crates/formats/src/mesh_export.rs | 85 ++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 2e0f2c53..d35156a9 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -7,6 +7,7 @@ pub(crate) mod usd; use std::collections::BTreeSet; use std::fmt::Write as _; +use craft_image_codecs::{DecodeOptions, Format, Limits, SampleType, decode_as_with, png_probe}; use texturecraft_core::{Channel, NormalFormat}; use texturecraft_geom::{Mesh, SubMesh}; @@ -182,12 +183,25 @@ fn png8_options(preset: ExportPreset, normal: NormalFormat) -> ExportOptions { } fn is_black(png: &[u8]) -> bool { - image::load_from_memory_with_format(png, image::ImageFormat::Png).map_or(true, |img| img.to_rgb8().iter().all(|v| *v == 0)) + // Keep the previous PNG decoder's 512 MiB allocation ceiling. + let options = DecodeOptions { limits: Limits { max_alloc: 512 << 20, ..Limits::none() }, keep_orientation: true }; + let Ok(image) = decode_as_with(Format::Png, png, &options) else { return true }; + let sample = image.sample_type(); + let layout = image.layout(); + let pixel_bytes = layout.channels() * sample.bytes(); + let color_bytes = layout.color_channels() * sample.bytes(); + let mut colors = image.data().chunks_exact(pixel_bytes).map(|pixel| &pixel[..color_bytes]); + match sample { + SampleType::U8 => colors.all(|color| color.iter().all(|&value| value == 0)), + // The prior RGB8 conversion rounds 16-bit values through 128 to zero. + SampleType::U16 => colors.all(|color| color.as_chunks::<2>().0.iter().all(|&value| u16::from_ne_bytes(value) <= 128)), + _ => true, + } } /// PNG color type 4 (gray + alpha) or 6 (RGBA), from the IHDR chunk. fn png_has_alpha(png: &[u8]) -> bool { - matches!(png.get(25), Some(4 | 6)) + png_probe::pixel_model(png).is_ok_and(|model| matches!(model.color_type, 4 | 6)) } /// The mesh as binary glTF (GLB) named `name`, with `textures[i]` on material `i` (materials @@ -426,6 +440,73 @@ mod tests { assert_eq!((sampler.mag_filter(), sampler.min_filter()), expected); } + #[test] + fn mesh_png_maps_keep_only_nonblack_color() { + let png = |color, samples: &[u8]| { + let mut out = std::io::Cursor::new(Vec::new()); + image::write_buffer_with_format(&mut out, samples, 1, 1, color, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mesh = texturecraft_geom::primitives::cube(1.0); + for (bytes, keep) in [ + (png(image::ColorType::Rgba8, &[0, 0, 0, 255]), false), + (png(image::ColorType::Rgba8, &[0, 1, 0, 0]), true), + (png(image::ColorType::L16, &128u16.to_ne_bytes()), false), + (png(image::ColorType::L16, &129u16.to_ne_bytes()), true), + (b"PNG without image data".to_vec(), false), + ] { + let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; + let emissive = file("Emissive.png", &bytes); + let textures = GlbTextures::from_files(vec![emissive.clone()]); + assert_eq!(textures.emissive.as_deref(), keep.then_some(bytes.as_slice())); + let glb = glb_bytes(&mesh, "PNG maps", &[textures]).unwrap(); + let glb = gltf::Gltf::from_slice(&glb).unwrap(); + assert_eq!(glb.materials().next().unwrap().emissive_texture().is_some(), keep); + + let roughness = png(image::ColorType::L8, &[64]); + let usd_maps = vec![emissive, file("Clearcoat.png", &bytes), file("ClearcoatRoughness.png", &roughness)]; + let usd = usd_bytes(&mesh, "PNG maps", &[usd_maps], UsdFormat::Usda).unwrap(); + if keep { + assert_eq!(usd.textures.len(), 3); + for (suffix, expected) in [("_Emissive.png", &bytes), ("_Clearcoat.png", &bytes), ("_ClearcoatRoughness.png", &roughness)] { + let (_, written) = usd.textures.iter().find(|(name, _)| name.ends_with(suffix)).unwrap(); + assert_eq!(written, expected); + } + } else { + assert!(usd.textures.is_empty()); + } + } + } + + #[test] + fn mesh_png_alpha_requires_a_png_with_stored_alpha() { + let encode = |color: png::ColorType, samples: &[u8], color_key: bool| { + let mut output = Vec::new(); + let mut encoder = png::Encoder::new(&mut output, 1, 1); + encoder.set_color(color); + if color_key { + encoder.set_trns(vec![0; 6]); + } + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(samples).unwrap(); + writer.finish().unwrap(); + output + }; + let mut impostor = vec![0; 26]; + impostor[25] = 6; + let mesh = texturecraft_geom::primitives::cube(1.0); + for (bytes, expected) in [ + (encode(png::ColorType::Rgba, &[0, 1, 2, 120], false), gltf::material::AlphaMode::Blend), + (encode(png::ColorType::Rgb, &[0, 0, 0], true), gltf::material::AlphaMode::Opaque), + (impostor, gltf::material::AlphaMode::Opaque), + ] { + let textures = GlbTextures { base_color: Some(bytes), ..GlbTextures::default() }; + let glb = glb_bytes(&mesh, "PNG alpha", &[textures]).unwrap(); + let glb = gltf::Gltf::from_slice(&glb).unwrap(); + assert_eq!(glb.materials().next().unwrap().alpha_mode(), expected); + } + } + #[test] fn glb_writes_clearcoat_and_sheen_extensions() { use serde_json::{Value, json}; From eeeb27013dbea08af6fd46182865b3cccceea5c2 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 007/153] Properties: the shared sheet controls (rows, bands, sliders, number fields that hold the pointer, switches, picture dropdowns, section tabs) --- crates/ui-egui/src/pointer_lock/hold.rs | 36 +++ crates/ui-egui/src/pointer_lock/lock.rs | 19 ++ crates/ui-egui/src/pointer_lock/mod.rs | 129 +++++++++ .../src/pointer_lock/system_pointer.rs | 75 +++++ crates/ui-egui/src/pointer_lock/tests.rs | 117 ++++++++ .../ui-egui/src/property_sheet/axis_rows.rs | 135 +++++++++ .../src/property_sheet/band_response.rs | 9 + .../ui-egui/src/property_sheet/button_icon.rs | 14 + crates/ui-egui/src/property_sheet/choice.rs | 256 ++++++++++++++++++ .../ui-egui/src/property_sheet/eye_toggle.rs | 48 ++++ crates/ui-egui/src/property_sheet/group.rs | 134 +++++++++ crates/ui-egui/src/property_sheet/hold_pad.rs | 34 +++ .../ui-egui/src/property_sheet/info_icon.rs | 86 ++++++ crates/ui-egui/src/property_sheet/mod.rs | 208 ++++++++++++++ .../src/property_sheet/number_field.rs | 212 +++++++++++++++ .../ui-egui/src/property_sheet/open_card.rs | 10 + .../src/property_sheet/preview_block.rs | 153 +++++++++++ .../src/property_sheet/preview_edit.rs | 8 + .../src/property_sheet/preview_lower.rs | 10 + .../src/property_sheet/preview_size.rs | 20 ++ crates/ui-egui/src/property_sheet/row.rs | 236 ++++++++++++++++ crates/ui-egui/src/property_sheet/row_lead.rs | 30 ++ .../src/property_sheet/section_tabs.rs | 136 ++++++++++ .../section_tabs/section_scope.rs | 8 + .../section_tabs/section_tops.rs | 21 ++ .../src/property_sheet/sheet_measure.rs | 15 + crates/ui-egui/src/property_sheet/slider.rs | 238 ++++++++++++++++ crates/ui-egui/src/property_sheet/slot.rs | 64 +++++ .../src/property_sheet/stack_slider.rs | 20 ++ .../src/property_sheet/switch_control.rs | 204 ++++++++++++++ crates/ui-egui/src/property_sheet/tests.rs | 243 +++++++++++++++++ .../src/property_sheet/tests/filtering.rs | 19 ++ .../src/property_sheet/tests/gallery.rs | 15 + crates/ui-egui/src/property_sheet/tooltip.rs | 32 +++ crates/ui-egui/src/property_sheet/track.rs | 13 + .../ui-egui/src/property_sheet/value_text.rs | 63 +++++ 36 files changed, 3070 insertions(+) create mode 100644 crates/ui-egui/src/pointer_lock/hold.rs create mode 100644 crates/ui-egui/src/pointer_lock/lock.rs create mode 100644 crates/ui-egui/src/pointer_lock/mod.rs create mode 100644 crates/ui-egui/src/pointer_lock/system_pointer.rs create mode 100644 crates/ui-egui/src/pointer_lock/tests.rs create mode 100644 crates/ui-egui/src/property_sheet/axis_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/band_response.rs create mode 100644 crates/ui-egui/src/property_sheet/button_icon.rs create mode 100644 crates/ui-egui/src/property_sheet/choice.rs create mode 100644 crates/ui-egui/src/property_sheet/eye_toggle.rs create mode 100644 crates/ui-egui/src/property_sheet/group.rs create mode 100644 crates/ui-egui/src/property_sheet/hold_pad.rs create mode 100644 crates/ui-egui/src/property_sheet/info_icon.rs create mode 100644 crates/ui-egui/src/property_sheet/number_field.rs create mode 100644 crates/ui-egui/src/property_sheet/open_card.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_block.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_edit.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_lower.rs create mode 100644 crates/ui-egui/src/property_sheet/preview_size.rs create mode 100644 crates/ui-egui/src/property_sheet/row.rs create mode 100644 crates/ui-egui/src/property_sheet/row_lead.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs create mode 100644 crates/ui-egui/src/property_sheet/sheet_measure.rs create mode 100644 crates/ui-egui/src/property_sheet/slider.rs create mode 100644 crates/ui-egui/src/property_sheet/slot.rs create mode 100644 crates/ui-egui/src/property_sheet/stack_slider.rs create mode 100644 crates/ui-egui/src/property_sheet/switch_control.rs create mode 100644 crates/ui-egui/src/property_sheet/tests.rs create mode 100644 crates/ui-egui/src/property_sheet/tests/filtering.rs create mode 100644 crates/ui-egui/src/property_sheet/tests/gallery.rs create mode 100644 crates/ui-egui/src/property_sheet/tooltip.rs create mode 100644 crates/ui-egui/src/property_sheet/track.rs create mode 100644 crates/ui-egui/src/property_sheet/value_text.rs diff --git a/crates/ui-egui/src/pointer_lock/hold.rs b/crates/ui-egui/src/pointer_lock/hold.rs new file mode 100644 index 00000000..e4d6dc5c --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/hold.rs @@ -0,0 +1,36 @@ +//! How the system lets a drag hold its pointer + +/// How a drag holds the pointer on this platform +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Hold { + /// The pointer moves, and is put back where the press began after every frame; the put-back's own move arrives among the others (X11) + PutBack, + /// Put back the same way, but the system folds its waiting moves into one, read from where it put the pointer (Windows) + PutBackFolded, + /// The system keeps the pointer still and reports raw motion (macOS, Wayland, which cannot move a pointer) + Locked, + /// The pointer cannot be held (the browser): drags read it as it moves + Free, +} + +impl Hold { + /// The way this platform holds a pointer; Wayland is told apart from X11 the way the window system picks it + pub(crate) fn of_platform() -> Hold { + if cfg!(target_arch = "wasm32") { + Hold::Free + } else if cfg!(target_os = "macos") { + Hold::Locked + } else if cfg!(target_os = "windows") { + Hold::PutBackFolded + } else if std::env::var_os("WAYLAND_DISPLAY").is_none() { + Hold::PutBack + } else { + Hold::Locked + } + } + + /// The pointer is held by putting it back after every frame + pub(crate) fn puts_back(self) -> bool { + matches!(self, Hold::PutBack | Hold::PutBackFolded) + } +} diff --git a/crates/ui-egui/src/pointer_lock/lock.rs b/crates/ui-egui/src/pointer_lock/lock.rs new file mode 100644 index 00000000..bb593ce2 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/lock.rs @@ -0,0 +1,19 @@ +use egui::Pos2; + +use super::Hold; + +/// A drag holding the pointer, kept in egui's memory between frames +#[derive(Clone, Copy, Debug)] +pub(super) struct Lock { + pub(super) hold: Hold, + /// Where the press began: the pointer is kept there and comes back there + pub(super) anchor: Pos2, + /// Where the system's pointer is + pub(super) seen: Pos2, + /// Where egui sees the pointer: the anchor plus every move since, as far as it goes + pub(super) at: Pos2, + /// A put-back is on its way: the pointer move that brings it back is no motion + pub(super) putting_back: bool, + /// The drag let go: the next frame shows egui the pointer back at the anchor and forgets the lock + pub(super) let_go: bool, +} diff --git a/crates/ui-egui/src/pointer_lock/mod.rs b/crates/ui-egui/src/pointer_lock/mod.rs new file mode 100644 index 00000000..f3e09661 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/mod.rs @@ -0,0 +1,129 @@ +//! Drags that hold the pointer (Move on model, number fields that scrub): hidden while held, its motion endless so no screen edge stops it, back where the press began when let go. egui sees a pointer that keeps going: the raw input is rewritten to that endless position, so every drag reads its usual positions and deltas + +mod hold; +mod lock; +#[cfg(test)] +pub(crate) mod system_pointer; +#[cfg(test)] +mod tests; + +use egui::{Context, CursorIcon, Event, Id, RawInput, ViewportCommand}; + +pub(crate) use hold::Hold; +use lock::Lock; + +/// Points from where the press began within which a pointer move is the put-back arriving (the system rounds it to whole pixels) +const PUT_BACK_REACH: f32 = 1.0; + +fn lock_id() -> Id { + Id::unique("tc_pointer_lock") +} + +fn asked_id() -> Id { + Id::unique("tc_pointer_lock_asked") +} + +fn hold_override_id() -> Id { + Id::unique("tc_pointer_lock_hold") +} + +/// A drag under way asks for the pointer this frame; it keeps it as long as it asks every frame +pub(crate) fn ask_for_hold(ctx: &Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(asked_id(), pass)); +} + +/// The app's raw input hook: while a drag holds the pointer, its moves become moves of the endless pointer egui sees +pub(crate) fn rewrite(ctx: &Context, raw: &mut RawInput) { + let Some(mut lock) = ctx.data(|data| data.get_temp::(lock_id())) else { + return; + }; + + if lock.let_go { + raw.events.insert(0, Event::PointerMoved(lock.anchor)); + ctx.data_mut(|data| data.remove::(lock_id())); + return; + } + + let zoom = ctx.zoom_factor().max(f32::EPSILON); + let events = std::mem::take(&mut raw.events); + for event in events { + match event { + Event::PointerMoved(to) => { + let put_back = lock.putting_back && to.distance(lock.anchor) <= PUT_BACK_REACH; + lock.putting_back &= !put_back; + if lock.hold.puts_back() && !put_back { + lock.at += to - lock.seen; + raw.events.push(Event::PointerMoved(lock.at)); + } + lock.seen = to; + } + Event::MouseMoved(delta) => { + if lock.hold == Hold::Locked { + lock.at += delta / zoom; + raw.events.push(Event::PointerMoved(lock.at)); + } + raw.events.push(event); + } + Event::PointerButton { button, pressed, modifiers, .. } => raw.events.push(Event::PointerButton { pos: lock.at, button, pressed, modifiers }), + // The pointer never really leaves: the drag goes on + Event::PointerGone => {} + other => raw.events.push(other), + } + } + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); +} + +/// The end of the app's frame: a drag that asked this frame takes or keeps the pointer (hidden, put back), one that stopped asking lets it go +pub(crate) fn settle(ctx: &Context) { + let asked = ctx.data(|data| data.get_temp::(asked_id())) == Some(ctx.cumulative_pass_nr()); + let held = ctx.data(|data| data.get_temp::(lock_id())).filter(|lock| !lock.let_go); + let mut lock = match (asked, held) { + (true, Some(lock)) => lock, + (true, None) => { + let hold = ctx.data(|data| data.get_temp::(hold_override_id())).unwrap_or_else(Hold::of_platform); + let (origin, latest) = ctx.input(|input| (input.pointer.press_origin(), input.pointer.latest_pos())); + let (Some(seen), false) = (latest, hold == Hold::Free) else { + return; + }; + + if hold == Hold::Locked { + ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::Locked)); + } + Lock { hold, anchor: origin.unwrap_or(seen), seen, at: seen, putting_back: false, let_go: false } + } + (false, Some(mut lock)) => { + // Put back before the grab ends: Wayland moves only a locked pointer + if lock.seen.distance(lock.anchor) > PUT_BACK_REACH { + ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor)); + } + if lock.hold == Hold::Locked { + ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::None)); + } + lock.let_go = true; + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); + ctx.request_repaint(); + return; + } + (false, None) => return, + }; + + ctx.set_cursor_icon(CursorIcon::None); + if lock.hold.puts_back() && lock.seen.distance(lock.anchor) > PUT_BACK_REACH { + ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor)); + + // A folding system reads every later move from where it put the pointer, its own move folded in + if lock.hold == Hold::PutBackFolded { + lock.seen = lock.anchor; + } else { + lock.putting_back = true; + } + } + ctx.data_mut(|data| data.insert_temp(lock_id(), lock)); +} + +/// Tests pick how the pointer is held, as a platform would +#[cfg(test)] +pub(crate) fn hold_like(ctx: &Context, hold: Hold) { + ctx.data_mut(|data| data.insert_temp(hold_override_id(), hold)); +} diff --git a/crates/ui-egui/src/pointer_lock/system_pointer.rs b/crates/ui-egui/src/pointer_lock/system_pointer.rs new file mode 100644 index 00000000..156cd8ee --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/system_pointer.rs @@ -0,0 +1,75 @@ +//! The system's pointer in tests: the mouse moves it, and it obeys the app's put-backs, grabs and hidden cursor as a window system does + +use egui::{CursorGrab, CursorIcon, Event, Modifiers, PointerButton, Pos2, Vec2, ViewportCommand, ViewportId}; +use egui_kittest::Harness; + +/// Where the system's pointer is and how the app holds it +#[derive(Clone, Copy, Debug)] +pub(crate) struct SystemPointer { + pub(crate) at: Pos2, + pub(crate) locked: bool, + pub(crate) hidden: bool, + pub(crate) put_backs: usize, + /// The system folds a put-back into the next move, as Windows does, instead of reporting it as a move of its own + pub(crate) folds: bool, +} + +impl SystemPointer { + /// The pointer resting at `at` over the window + pub(crate) fn at(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer { + let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false }; + harness.input_mut().events.push(Event::PointerMoved(at)); + pointer.frame(harness); + pointer + } + + /// One frame in which the mouse moves by `by` with `modifiers` held: a held pointer reports raw motion only, a free one moves + pub(crate) fn moves(&mut self, harness: &mut Harness<'_, S>, by: Vec2, modifiers: Modifiers) { + let input = harness.input_mut(); + input.events.push(Event::ModifiersChanged(modifiers)); + input.events.push(Event::MouseMoved(by)); + if !self.locked { + self.at += by; + input.events.push(Event::PointerMoved(self.at)); + } + self.frame(harness); + } + + /// The mouse moves by `by` over `frames` frames + pub(crate) fn drags(&mut self, harness: &mut Harness<'_, S>, by: Vec2, frames: usize, modifiers: Modifiers) { + for _ in 0..frames { + self.moves(harness, by / frames as f32, modifiers); + } + } + + /// One frame in which `button` goes down or up where the pointer is + pub(crate) fn button(&mut self, harness: &mut Harness<'_, S>, button: PointerButton, pressed: bool, modifiers: Modifiers) { + let input = harness.input_mut(); + input.events.push(Event::ModifiersChanged(modifiers)); + input.events.push(Event::PointerButton { pos: self.at, button, pressed, modifiers }); + self.frame(harness); + } + + /// One frame of everything the system sent since the last: the app's raw input hook rewrites it, the app runs, and the pointer does what the app asked + pub(crate) fn frame(&mut self, harness: &mut Harness<'_, S>) { + let ctx = harness.ctx.clone(); + super::rewrite(&ctx, harness.input_mut()); + harness.step(); + let output = harness.output(); + self.hidden = output.platform_output.cursor_icon == CursorIcon::None; + let commands = output.viewport_output.get(&ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default(); + for command in commands { + match command { + ViewportCommand::CursorPosition(to) => { + self.at = to; + self.put_backs += 1; + if !self.folds { + harness.input_mut().events.push(Event::PointerMoved(to)); + } + } + ViewportCommand::CursorGrab(grab) => self.locked = grab == CursorGrab::Locked, + _ => {} + } + } + } +} diff --git a/crates/ui-egui/src/pointer_lock/tests.rs b/crates/ui-egui/src/pointer_lock/tests.rs new file mode 100644 index 00000000..bbce1297 --- /dev/null +++ b/crates/ui-egui/src/pointer_lock/tests.rs @@ -0,0 +1,117 @@ +use egui::{Modifiers, PointerButton, Pos2, Rect, Sense, Vec2, pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +use super::system_pointer::SystemPointer; +use super::{Hold, ask_for_hold, hold_like, settle}; + +/// A strip that scrubs: dragging it adds the pointer's moves to the state, holding the pointer while it does +fn scrub_strip(hold_as: Hold) -> Harness<'static, Vec2> { + let mut harness = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state( + |ui, moved: &mut Vec2| { + let response = ui.interact(Rect::from_min_size(pos2(10.0, 10.0), vec2(100.0, 24.0)), ui.scope_id().with("scrub"), Sense::drag()); + if response.dragged() { + ask_for_hold(ui.ctx()); + *moved += response.drag_delta(); + } + settle(ui.ctx()); + }, + Vec2::ZERO, + ); + hold_like(&harness.ctx, hold_as); + harness.run_steps(1); + harness +} + +const PRESS: Pos2 = pos2(60.0, 20.0); + +/// Drags the strip 1500 points right (far past the 400-point window) and back up 40, then lets go +fn scrub_past_the_edge(harness: &mut Harness<'static, Vec2>) -> SystemPointer { + let mut pointer = SystemPointer::at(harness, PRESS); + pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden, "the pointer is hidden while the drag holds it"); + assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts, past the window's edge: {:?}", harness.state()); + pointer +} + +#[test] +fn a_put_back_pointer_never_reaches_the_edge_and_comes_back_where_the_press_began() { + let mut harness = scrub_strip(Hold::PutBack); + let mut pointer = scrub_past_the_edge(&mut harness); + assert!(pointer.put_backs >= 30, "the pointer went back after every move: {}", pointer.put_backs); + assert!(pointer.at.distance(PRESS) < 1.0, "it never strayed from the press: {:?}", pointer.at); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden, "let go, the pointer shows again"); + assert_eq!(pointer.at, PRESS, "where the press began"); + assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it there too"); + let moved = *harness.state(); + pointer.moves(&mut harness, vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(pointer.at, PRESS + vec2(30.0, 0.0), "a free pointer moves again"); + assert_eq!(*harness.state(), moved, "and drags nothing"); +} + +/// A system that folds the put-back into the next move (Windows) reads that move from the press point: the drag counts in full and never stalls +#[test] +fn a_folded_put_back_counts_every_move_from_the_press() { + let mut harness = scrub_strip(Hold::PutBackFolded); + let mut pointer = SystemPointer::at(&mut harness, PRESS); + pointer.folds = true; + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden && pointer.put_backs >= 30, "hidden, and put back after every move: {pointer:?}"); + assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts: {:?}", harness.state()); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == PRESS, "let go, it shows again where the press began: {pointer:?}"); +} + +#[test] +fn a_locked_pointer_reads_raw_motion_and_is_let_go_where_the_press_began() { + let mut harness = scrub_strip(Hold::Locked); + let mut pointer = scrub_past_the_edge(&mut harness); + assert!(pointer.locked, "the system holds the pointer"); + assert_eq!(pointer.at, PRESS, "it never moved"); + + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.locked && !pointer.hidden, "let go, the pointer is free and shows"); + assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it where the press began"); +} + +#[test] +fn a_browser_pointer_is_not_held() { + let mut harness = scrub_strip(Hold::Free); + let mut pointer = SystemPointer::at(&mut harness, PRESS); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(100.0, 0.0), 10, Modifiers::NONE); + assert!(!pointer.hidden && pointer.put_backs == 0, "the pointer moves and shows"); + assert_eq!(*harness.state(), vec2(100.0, 0.0), "the drag reads it as it moves"); +} + +/// A number field in the Properties panel scrubs with the pointer held: hidden, kept where the press began, a drag far past the window's edge counted in full +#[test] +fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = crate::frame_gizmo::tests::fill_app("triplanar"); + hold_like(&harness.ctx, Hold::PutBack); + let press = harness.get_by_label("Offset X").rect().center(); + let mut pointer = SystemPointer::at(&mut harness, press); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + let window = harness.ctx.content_rect().width(); + pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE); + assert!(pointer.hidden && pointer.at.distance(press) < 1.0, "the pointer is hidden and kept on the field: {pointer:?}"); + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == press, "let go, it shows again on the field: {pointer:?}"); + + let texturecraft_engine::core::Projection::Triplanar { offset, .. } = crate::frame_gizmo::tests::projection(&harness, layer) else { + panic!("still tri-planar") + }; + + let expected = 2.0 * window * crate::fill_panel::OFFSET_FIELD_SPEED; + assert!((offset[0] - expected).abs() < 0.05 * expected, "the whole drag counts, not only the part inside the window: {offset:?}, {expected}"); +} diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs new file mode 100644 index 00000000..13d65ee9 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -0,0 +1,135 @@ +//! Rows a symmetry needs: a section caption with its own switch, sliders lettered by axis, and a picture beside a stack of sliders + +use std::ops::RangeInclusive; + +use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use super::row::SECTION_CAPTION_CENTER; +use super::slider::KNOB_RADIUS; +use super::switch_control::PILL_SIZE; +use super::track::Track; +use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; +use crate::theme::semibold; + +/// From the right edge to the centre of a caption's switch: the pill ends on the edge +const CAPTION_SWITCH_INSET: f32 = PILL_SIZE.x / 2.0; + +/// The click area around a caption's switch +const CAPTION_SWITCH_HIT: egui::Vec2 = vec2(30.0, 20.0); + +/// Least air between a caption and the reason standing in for its switch +const UNAVAILABLE_AIR: f32 = 12.0; + +/// From the controls column to where a lettered slider's track starts, past its axis letter +const LETTER_TO_TRACK: f32 = 16.0; + +/// From one part of a lettered value to the next +const PART_LINE: f32 = 22.0; + +/// A stacked slider's caption line, its track's line, and the air between stacked sliders +const STACK_CAPTION_LINE: f32 = 18.0; +const STACK_PART_LINE: f32 = 22.0; +const STACK_GAP: f32 = 6.0; + +/// The picture's top below the block's (the first caption's letters), how much shorter it is than the stack, and its air before the controls column +const PICTURE_TOP: f32 = 4.0; +const PICTURE_SHORTER: f32 = 10.0; +const PICTURE_TO_COLUMN: f32 = 6.0; + +impl PropertySheet<'_> { + /// A section caption with its on/off switch at the right edge + pub(crate) fn section_switch(&mut self, title: &str, on: bool) -> Response { + self.section_in(title, false, self.tokens.text); + let top = self.sections.last().map_or(self.cursor_y(), |(_, top)| *top); + let center = pos2(self.right - CAPTION_SWITCH_INSET, top + SECTION_CAPTION_CENTER); + let id = self.next_id(); + let response = self.ui.interact(Rect::from_center_size(center, CAPTION_SWITCH_HIT), id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, title)); + self.pill(center, on, true); + response + } + + /// A dim section caption whose switch can't be used: `reason` stands in its place at the right edge, cut with "…" to fit (then its tooltip reads it whole) + pub(crate) fn section_unavailable(&mut self, title: &str, reason: &str) { + let tokens = self.tokens; + self.section_in(title, false, tokens.text_dim); + let top = self.sections.last().map_or(self.cursor_y(), |(_, top)| *top); + let center_y = top + SECTION_CAPTION_CENTER; + let painter = self.ui.painter().clone(); + let caption = painter.layout_no_wrap(title.to_uppercase(), semibold(SMALL_TEXT_SIZE), tokens.text_dim).size().x; + let room = self.right - self.left - caption - UNAVAILABLE_AIR; + let galley = crate::widgets::elided(&painter, reason, SMALL_TEXT_SIZE, tokens.text_dim, room); + let cut = galley.elided; + let rect = Rect::from_min_size(pos2(self.right - galley.size().x, center_y - galley.size().y / 2.0), galley.size()); + painter.galley(rect.min, galley, tokens.text_dim); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, false, reason)); + if cut { + self.tip(response, reason); + } + } + + /// One value's parts on lettered signed sliders (Axis position X, Y): the label on the first row, each part's axis letter in its colour; returns the part edited and whether it merges + pub(crate) fn lettered_sliders( + &mut self, + label: &str, + parts: &mut [(&str, Color32, f32)], + range: RangeInclusive, + decimals: usize, + ) -> Option<(usize, bool)> { + let (control, first) = self.row(label); + let extra = parts.len().saturating_sub(1) as f32 * PART_LINE; + if extra > 0.0 { + self.take(extra); + } + let mut edit = None; + for (index, (letter, color, value)) in parts.iter_mut().enumerate() { + let center_y = first + index as f32 * PART_LINE; + self.ui.painter().text(pos2(control.left(), center_y), Align2::LEFT_CENTER, *letter, semibold(TEXT_SIZE), *color); + let id = self.next_id(); + let track = Track { start: control.left() + LETTER_TO_TRACK + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; + let name = format_args!("{label} {letter}"); + let dragged = self.track(id, name, &track, value, &range); + let typed = self.value_field(id, name, center_y, *value, &range, decimals, ""); + if let Some(merge) = Self::apply_typed(value, typed, dragged) { + edit = Some((index, merge)); + } + self.drawn(center_y + super::CONTROL_HEIGHT / 2.0); + } + edit + } + + /// A picture at the left edge beside captioned sliders in the controls column, as tall as their stack; returns the slider edited and whether it merges + pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>]) -> Option<(usize, bool)> { + let count = sliders.len().max(1) as f32; + let height = count * (STACK_CAPTION_LINE + STACK_PART_LINE) + (count - 1.0) * STACK_GAP; + self.space(BLOCK_MARGIN); + let block = self.take(height); + let x0 = self.column(); + let side = (height - PICTURE_SHORTER).min(x0 - self.left - PICTURE_TO_COLUMN).max(1.0); + let square = Rect::from_min_size(pos2(self.left, block.top() + PICTURE_TOP), vec2(side, side)); + picture(self.ui.painter(), square); + self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + + let mut edit = None; + let mut y = block.top(); + for (index, slider) in sliders.iter_mut().enumerate() { + let dim = self.tokens.text_dim; + let caption = pos2(x0, y + STACK_CAPTION_LINE / 2.0); + self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); + let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; + let id = self.next_id(); + let track = Track { start: x0 + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); + let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); + if let Some(merge) = Self::apply_typed(slider.value, typed, dragged) { + edit = Some((index, merge)); + } + y += STACK_CAPTION_LINE + STACK_PART_LINE + STACK_GAP; + } + self.drawn(square.bottom().max(block.bottom() - STACK_PART_LINE / 2.0 + KNOB_RADIUS)); + self.space(BLOCK_MARGIN); + edit + } +} diff --git a/crates/ui-egui/src/property_sheet/band_response.rs b/crates/ui-egui/src/property_sheet/band_response.rs new file mode 100644 index 00000000..fb230951 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/band_response.rs @@ -0,0 +1,9 @@ +/// What a band did this frame +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct BandResponse { + /// The band is open: show its rows + pub(crate) open: bool, + + /// Its Restore defaults button was clicked + pub(crate) reset: bool, +} diff --git a/crates/ui-egui/src/property_sheet/button_icon.rs b/crates/ui-egui/src/property_sheet/button_icon.rs new file mode 100644 index 00000000..be97a317 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/button_icon.rs @@ -0,0 +1,14 @@ +//! What a full-width button shows before its words: an icon font glyph or an icon drawn in code + +/// A full-width button's icon +#[derive(Clone, Copy, Debug)] +pub(crate) enum ButtonIcon<'a> { + /// A glyph of the icon font + Glyph(&'a str), +} + +impl<'a> From<&'a str> for ButtonIcon<'a> { + fn from(glyph: &'a str) -> Self { + ButtonIcon::Glyph(glyph) + } +} diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs new file mode 100644 index 00000000..15d3d03f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -0,0 +1,256 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Frame, Margin, Painter, Rect, RectAlign, Response, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, ICON_SIZE, PropertySheet, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::{HARD_SHADOW, semibold}; + +/// Draws an option's picture into its square +pub(super) type ChoicePicture<'a, T> = &'a dyn Fn(&Painter, Rect, T); + +/// Size of a picture in a dropdown button and in its list +const PICTURE_SIZE: f32 = 18.0; + +/// From a picture dropdown's left edge to its picture +const PICTURE_INSET: f32 = 6.0; + +/// From a plain dropdown's left edge to its value +pub(super) const VALUE_INSET: f32 = 8.0; + +/// Air between a picture and the words after it +const PICTURE_TO_TEXT: f32 = 8.0; + +/// From a dropdown's right edge to its caret's centre +pub(super) const CARET_INSET: f32 = 10.0; + +/// Room a dropdown keeps for its caret: its value is cut with "…" before it +pub(super) const CARET_ROOM: f32 = 24.0; + +/// The open list's border, drawn outside its options: the list's outer edge is its button's +pub(super) const LIST_BORDER: f32 = 1.0; + +/// The open list's corner radius and the air above its first option and below its last +const LIST_RADIUS: u8 = 6; +const LIST_PADDING: i8 = 4; + +/// The open list's hard shadow, offset down and right like the other popups' +const LIST_SHADOW: Shadow = Shadow { offset: [2, 3], blur: 0, spread: 0, color: HARD_SHADOW }; + +/// Height of one option in an open list +const OPTION_HEIGHT: f32 = 26.0; + +/// How far an option's words sit above its centre, to look centred beside their capitals +const OPTION_TEXT_LIFT: f32 = 1.0; + +/// Gap under an option's hover fill, so neighbouring fills never touch +const HOVER_BOTTOM_GAP: f32 = 2.0; + +/// How far an option's hover fill sits inside the list's edges +const HOVER_INSET: f32 = 3.0; + +/// From the list's right edge to the hovered option's preview eye +const EYE_INSET: f32 = 16.0; + +/// Lists narrower than this have no room for the preview eye +const EYE_MIN_LIST_WIDTH: f32 = 80.0; + +/// The lettering of a set-once choice, cut with "…" to fit `room` +pub(super) fn truncated(painter: &Painter, text: &str, room: f32, color: Color32) -> std::sync::Arc { + let font = semibold(TEXT_SIZE); + let full = painter.layout_no_wrap(text.to_owned(), font.clone(), color); + if full.size().x <= room { + return full; + } + + let mut cut: String = text.to_owned(); + while cut.pop().is_some() { + let candidate = painter.layout_no_wrap(format!("{}…", cut.trim_end()), font.clone(), color); + if candidate.size().x <= room { + return candidate; + } + } + painter.layout_no_wrap("…".to_owned(), font, color) +} + +/// The chosen option's accent bar, inset from the option's left, top and bottom +const CHOSEN_BAR_LEFT: f32 = 2.0; +const CHOSEN_BAR_RIGHT: f32 = 4.0; +const CHOSEN_BAR_TOP: f32 = 5.0; +const CHOSEN_BAR_BOTTOM: f32 = 7.0; + +/// The chosen option's accent bar is 2 px wide: a 1 px radius rounds its ends fully +const CHOSEN_BAR_RADIUS: u8 = 1; + +/// The hovered option's eye glyph size +const EYE_SIZE: f32 = 13.0; + +impl PropertySheet<'_> { + /// A set-once choice whose list hangs from its button; returns the picked and the hovered option + pub(crate) fn dropdown( + &mut self, + label: &str, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + self.dropdown_led(RowLead::label(label), current, options, name, picture) + } + + /// [`Self::dropdown`] led by `lead` (a label stacked above it, when its values differ only at their end) + pub(crate) fn dropdown_led( + &mut self, + lead: RowLead<'_>, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let response = self.dropdown_row(lead, current, &name, picture); + self.hanging_list(&response, current, options, &name, picture) + } + + /// [`Self::dropdown`] whose `options` are built only while its list is open + pub(crate) fn dropdown_built>( + &mut self, + label: &str, + current: T, + options: impl FnOnce() -> Options, + name: impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let response = self.dropdown_row(RowLead::label(label), current, &name, picture); + self.hanging_groups(&response, current, || [(None, options())], &name, picture) + } + + /// A dropdown's row led by `lead`, its button showing `current` and described by the row's name; returns the button's response + fn dropdown_row(&mut self, lead: RowLead<'_>, current: T, name: &impl Fn(T) -> String, picture: Option>) -> Response { + let x0 = self.lead_with(lead); + let row = self.take(super::ROW_HEIGHT); + let center_y = row.center().y; + self.drawn(center_y + CONTROL_HEIGHT / 2.0); + let button = self.control_box(x0, center_y); + let response = self.dropdown_button(button, &name(current), picture.map(|draw| move |painter: &Painter, rect: Rect| draw(painter, rect, current))); + self.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(lead.text())); + response + } + + /// Paints a dropdown's button in `rect` and returns its response + pub(super) fn dropdown_button(&mut self, rect: Rect, value: &str, picture: Option) -> Response { + self.dropdown_button_led(rect, value, |painter| match picture { + Some(draw) => { + let picture_rect = + Rect::from_min_size(pos2(rect.left() + PICTURE_INSET, rect.center().y - PICTURE_SIZE / 2.0), vec2(PICTURE_SIZE, PICTURE_SIZE)); + draw(painter, picture_rect); + picture_rect.right() + PICTURE_TO_TEXT + } + None => rect.left() + VALUE_INSET, + }) + } + + /// [`Self::dropdown_button`] whose left end `lead` paints on the button's face, returning where the value starts + pub(super) fn dropdown_button_led(&mut self, rect: Rect, value: &str, lead: impl FnOnce(&Painter) -> f32) -> Response { + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, true, value)); + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), if response.hovered() { tokens.row_hover } else { tokens.button }); + + let text_x = lead(painter); + let galley = truncated(painter, value, rect.right() - CARET_ROOM - text_x, tokens.text); + painter.galley(pos2(text_x, rect.center().y - galley.size().y / 2.0), galley, tokens.text); + painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(ICON_SIZE), tokens.text); + response + } + + /// The open list of `button`: 1 px below it, its width, over the rows below; returns the picked and the hovered option + pub(crate) fn hanging_list( + &mut self, + button: &Response, + current: T, + options: &[T], + name: &impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + self.hanging_groups(button, current, || [(None, options.iter().copied())], name, picture) + } + + /// [`Self::hanging_list`] of options in groups, each under its caption (a dim line that can't be picked) when it has one; `groups` runs only while the list is open + fn hanging_groups<'g, T: Copy + PartialEq, Groups: IntoIterator, Options)>, Options: IntoIterator>( + &mut self, + button: &Response, + current: T, + groups: impl FnOnce() -> Groups, + name: &impl Fn(T) -> String, + picture: Option>, + ) -> (Option, Option) { + let tokens = self.tokens; + let width = button.rect.width() - 2.0 * LIST_BORDER; + let frame = Frame::NONE + .fill(tokens.chrome) + .stroke(Stroke::new(LIST_BORDER, tokens.field_border)) + .corner_radius(CornerRadius::same(LIST_RADIUS)) + .inner_margin(Margin::symmetric(0, LIST_PADDING)) + .shadow(LIST_SHADOW); + let shown = egui::Popup::from_toggle_button_response(button).align(RectAlign::BOTTOM_START).gap(1.0).width(width).frame(frame).show(|ui| { + let mut picked = None; + let mut hovered = None; + for (caption, options) in groups() { + if let Some(caption) = caption { + let (rect, response) = ui.allocate_exact_size(vec2(width, OPTION_HEIGHT), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, caption)); + let center_y = rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT; + ui.painter().text( + pos2(rect.left() - LIST_BORDER + VALUE_INSET, center_y), + Align2::LEFT_CENTER, + caption, + FontId::proportional(SMALL_TEXT_SIZE), + tokens.text_dim, + ); + } + for option in options { + let (rect, response) = ui.allocate_exact_size(vec2(width, OPTION_HEIGHT), Sense::click()); + let painter = ui.painter(); + let chosen = option == current; + response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, name(option))); + if response.hovered() { + hovered = Some(option); + let fill = + Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP)); + painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button); + } + if chosen { + let bar = Rect::from_min_max( + pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP), + pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM), + ); + painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent); + } + + // The rows sit inside the list's border: measured from the button's edge, text and picture keep the button's x + let button_left = rect.left() - LIST_BORDER; + let center_y = rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT; + let mut text_x = button_left + VALUE_INSET; + if let Some(draw) = picture { + draw( + painter, + Rect::from_min_size(pos2(button_left + PICTURE_INSET, center_y - PICTURE_SIZE / 2.0), vec2(PICTURE_SIZE, PICTURE_SIZE)), + option, + ); + text_x = button_left + PICTURE_INSET + PICTURE_SIZE + PICTURE_TO_TEXT; + } + let font = if chosen { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) }; + painter.text(pos2(text_x, center_y), Align2::LEFT_CENTER, name(option), font, tokens.text); + if response.hovered() && width >= EYE_MIN_LIST_WIDTH { + painter.text(pos2(rect.right() - EYE_INSET, center_y), Align2::CENTER_CENTER, ic::EYE, FontId::proportional(EYE_SIZE), tokens.accent); + } + if response.clicked() && !chosen { + picked = Some(option); + } + } + } + (picked, hovered) + }); + shown.map(|inner| inner.inner).unwrap_or((None, None)) + } +} diff --git a/crates/ui-egui/src/property_sheet/eye_toggle.rs b/crates/ui-egui/src/property_sheet/eye_toggle.rs new file mode 100644 index 00000000..17fff24e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/eye_toggle.rs @@ -0,0 +1,48 @@ +//! A dropdown row that ends in an eye: shows or hides what the setting draws over the 3D view + +use egui::{Align2, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::choice::ChoicePicture; +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, PropertySheet}; + +/// Air between the dropdown and its eye +const EYE_GAP: f32 = 6.0; + +/// Size of the eye glyph +const EYE_GLYPH_SIZE: f32 = 14.0; + +impl PropertySheet<'_> { + /// [`Self::dropdown`] narrowed by an eye at the row's end (`eye`: open while shown, else slashed and dim; its tip); returns the pick and the eye's click + pub(crate) fn dropdown_with_eye( + &mut self, + label: &str, + current: T, + options: &[T], + name: impl Fn(T) -> String, + picture: Option>, + (shown, tip): (bool, &str), + ) -> (Option, bool) { + let right = self.right; + self.right -= CONTROL_HEIGHT + EYE_GAP; + let (picked, _) = self.dropdown(label, current, options, name, picture); + self.right = right; + + let center_y = self.cursor_y() - super::ROW_HEIGHT / 2.0; + let rect = Rect::from_center_size(pos2(right - CONTROL_HEIGHT / 2.0, center_y), vec2(CONTROL_HEIGHT, CONTROL_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, shown, tip)); + let response = self.tip(response, tip); + paint_eye(self.ui.painter(), rect, shown, response.hovered(), &self.tokens); + (picked, response.clicked()) + } +} + +/// The eye's square: button fill, its edge lit while hovered; the eye open, or slashed and dim +fn paint_eye(painter: &Painter, rect: Rect, shown: bool, hovered: bool, tokens: &crate::theme::Tokens) { + let border = if hovered { tokens.accent } else { tokens.button_border }; + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.button, Stroke::new(1.0, border), StrokeKind::Inside); + let (glyph, color) = if shown { (ic::EYE, tokens.text) } else { (ic::EYE_SLASH, tokens.text_dim) }; + painter.text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(EYE_GLYPH_SIZE), color); +} diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs new file mode 100644 index 00000000..d115e162 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -0,0 +1,134 @@ +use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; +use crate::theme::semibold; + +/// Draws a band's picture in its rect +type BandPicture<'a> = &'a dyn Fn(&egui::Painter, Rect); + +/// Height of a top-level band +const BAND_HEIGHT: f32 = 30.0; + +/// A card's padding above its name and below its last control +const CARD_PADDING: f32 = 10.0; + +/// How far a card's face reaches past its rows on both sides +pub(super) const CARD_BLEED: f32 = 6.0; + +/// Corner radius of a card +pub(super) const CARD_RADIUS: u8 = 6; + +/// From the right edge to the centre of a band's reset button +const BAND_RESET_INSET: f32 = 26.0; + +/// From the right edge to where a band's or folded group's value ends +const BAND_VALUE_INSET: f32 = 22.0; + +/// Side of the picture before a band's value, and the air between them +const BAND_PICTURE_SIZE: f32 = 16.0; +const BAND_PICTURE_AIR: f32 = 8.0; + +/// A band's reset button click square +const BAND_RESET_TARGET: f32 = 20.0; + +impl PropertySheet<'_> { + /// A top-level group across the whole panel with a caret and a reset (`Some(changed)`) or a value; a click folds it + pub(crate) fn band(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>) -> BandResponse { + self.band_drawn(title, default_open, reset, value, None) + } + + fn band_drawn(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>, picture: Option>) -> BandResponse { + if self.card.is_none() { + self.space(GROUP_GAP); + } + + // A band is top-level: it ends a held card too + self.release_card(); + + self.scope = self.id; + let id = self.named_id("band", title); + self.band_scope = id; + self.scope = id; + + let rect = self.take(BAND_HEIGHT); + let band = Rect::from_x_y_ranges(self.ui.max_rect().x_range(), rect.y_range()); + + let mut open = self.ui.data(|data| data.get_temp::(id)).unwrap_or(default_open); + let response = self.ui.interact(band, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title)); + + let reset_rect = Rect::from_center_size(pos2(self.right - BAND_RESET_INSET, rect.center().y), vec2(BAND_RESET_TARGET, BAND_RESET_TARGET)); + let mut reset_clicked = false; + let mut reset_hovered = false; + if let Some(changed) = reset { + // At the defaults it is inert: a click there folds the band like the rest of it + let sense = if changed { Sense::click() } else { Sense::hover() }; + let reset_response = self.ui.interact(reset_rect, id.with("reset"), sense); + if changed { + // Right above the glyph, as far right as it: over the card or toggles above the band, never a value + let mut tooltip = egui::Tooltip::for_enabled(&reset_response); + tooltip.popup = tooltip.popup.anchor(reset_rect).align(egui::RectAlign::TOP_END).align_alternatives(&[egui::RectAlign::LEFT]); + tooltip.show(|ui| ui.label(crate::i18n::tr("Restore defaults"))); + } + reset_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, changed, crate::i18n::tr("Restore defaults"))); + reset_clicked = changed && reset_response.clicked(); + reset_hovered = reset_response.hovered(); + } + if response.clicked() && !reset_clicked { + open = !open; + self.ui.data_mut(|data| data.insert_temp(id, open)); + } + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect_filled(band, CornerRadius::ZERO, self.band_fill()); + painter.line_segment([band.left_top(), band.right_top()], Stroke::new(1.0, tokens.separator)); + painter.line_segment([band.left_bottom(), band.right_bottom()], Stroke::new(1.0, tokens.separator)); + let center_y = rect.center().y; + painter.text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + if let Some(changed) = reset { + // The round section reset, as on a section caption: faint where it does nothing + let color = self.reset_glyph_color(changed, reset_hovered, tokens.text_strong); + painter.text(reset_rect.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_ICON_SIZE), color); + } + if let Some(value) = value { + let shown = + painter.text(pos2(self.right - BAND_VALUE_INSET, center_y), Align2::RIGHT_CENTER, value, FontId::proportional(TEXT_SIZE), tokens.text_dim); + if let Some(draw) = picture { + let left = shown.left() - BAND_PICTURE_AIR - BAND_PICTURE_SIZE; + draw(painter, Rect::from_min_size(pos2(left, center_y - BAND_PICTURE_SIZE / 2.0), vec2(BAND_PICTURE_SIZE, BAND_PICTURE_SIZE))); + } + } + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + + self.drawn(band.bottom()); + self.space(GROUP_GAP); + self.air_at = Some(self.cursor_y()); + BandResponse { open, reset: reset_clicked } + } + + /// Ends [`Self::hold_card`] and closes the held card + pub(crate) fn release_card(&mut self) { + self.held = false; + self.close_card(); + } + + /// Ends the open card (not a held one: [`Self::release_card`] ends that): its face reaches [`CARD_PADDING`] below what its rows painted + pub(crate) fn close_card(&mut self) { + if self.held { + return; + } + + let Some(card) = self.card.take() else { return }; + + self.scope = self.band_scope; + + let bottom = self.drawn_bottom + CARD_PADDING; + let face = Rect::from_min_max(pos2(self.left - CARD_BLEED, card.top), pos2(self.right + CARD_BLEED, bottom)); + self.ui.painter().set(card.face, Shape::rect_filled(face, CornerRadius::same(CARD_RADIUS), self.tokens.row)); + let below = bottom + GROUP_GAP - self.cursor_y(); + self.space(below.max(0.0)); + self.air_at = Some(self.cursor_y()); + } +} diff --git a/crates/ui-egui/src/property_sheet/hold_pad.rs b/crates/ui-egui/src/property_sheet/hold_pad.rs new file mode 100644 index 00000000..24fd7dd7 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/hold_pad.rs @@ -0,0 +1,34 @@ +//! A picture that is also a press-and-hold surface: a badge in its corner says so, and the edge and badge light while hovered or held + +use egui::{Align2, CornerRadius, FontId, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, vec2}; + +use super::PropertySheet; + +/// Side of the badge in the picture's bottom-right corner, and its inset from the picture's edges +const BADGE_SIZE: f32 = 16.0; +const BADGE_INSET: f32 = 4.0; +const BADGE_ROUNDING: u8 = 3; + +/// Size of the badge's glyph +const BADGE_GLYPH_SIZE: f32 = 11.0; + +impl PropertySheet<'_> { + /// Makes the already painted `picture` a press-and-hold surface named `name`, marked by `glyph` in a badge; `held` lights it as hover does. It follows a drag that starts on it, wherever the pointer goes + pub(crate) fn hold_pad(&mut self, picture: Rect, glyph: &str, name: &str, held: bool) -> Response { + let id = self.next_id(); + let response = self.ui.interact(picture, id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, name)); + + let tokens = self.tokens; + let lit = held || response.hovered(); + let painter = self.ui.painter(); + let badge = Rect::from_min_size(picture.right_bottom() - vec2(BADGE_INSET + BADGE_SIZE, BADGE_INSET + BADGE_SIZE), vec2(BADGE_SIZE, BADGE_SIZE)); + let (fill, edge) = if lit { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + painter.rect(badge, CornerRadius::same(BADGE_ROUNDING), fill, Stroke::new(1.0, edge), StrokeKind::Inside); + painter.text(badge.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(BADGE_GLYPH_SIZE), tokens.text); + if lit { + painter.rect_stroke(picture, 0, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } + response + } +} diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs new file mode 100644 index 00000000..b18c0513 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -0,0 +1,86 @@ +use egui::{Align2, CornerRadius, FontId, Frame, Margin, Rect, RectAlign, RichText, Role, Sense, Shadow, Stroke, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE}; +use crate::theme::HARD_SHADOW; + +/// The i's slot at the panel edge; a row with an i at its left starts this much further right +pub(super) const INFO_SLOT: f32 = 16.0; + +/// The i's centre, from the panel's left padding +const INFO_CENTER: f32 = 6.0; + +/// Size of the i glyph +const INFO_ICON_SIZE: f32 = 13.0; + +/// Room the tooltip leaves at the panel's right edge, so it covers no number, dial or switch +const TIP_VALUE_ROOM: f32 = 70.0; + +/// How far the tooltip reaches up into its row +const TIP_OVERLAP: f32 = 2.0; + +/// The tooltip's text padding, line pitch, rounding and shadow +const TIP_MARGIN: Margin = Margin::symmetric(8, 5); +const TIP_LINE_HEIGHT: f32 = 15.0; +const TIP_ROUNDING: u8 = 5; +const TIP_SHADOW: Shadow = Shadow { offset: [2, 3], blur: 0, spread: 0, color: HARD_SHADOW }; + +impl<'u> PropertySheet<'u> { + /// Gives the next row led by a label or picture an i at the panel edge that explains it on hover; its lead and its child rows move right to make room + pub(crate) fn info(&mut self, tip: &'u str) -> &mut Self { + self.info = Some(tip); + self + } + + /// How far the next row's lead moves right: past a pending i + pub(super) fn lead_shift(&self) -> f32 { + if self.info.is_some() { INFO_SLOT } else { 0.0 } + } + + /// Paints the pending i at the panel edge on the row centred at `center_y`, and its tooltip while the pointer rests on it + pub(super) fn paint_info(&mut self, center_y: f32) { + self.paint_info_in(self.left, self.left + INFO_CENTER, center_y); + } + + /// [`Self::paint_info`] at the row's right end, the i's right edge on the values' edge + pub(super) fn paint_info_at_end(&mut self, center_y: f32) { + self.paint_info_in(self.right - INFO_SLOT, self.right - INFO_ICON_SIZE / 2.0, center_y); + } + + /// Paints the pending i at `glyph_x` in its slot from `slot_left` + fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { + let Some(tip) = self.info.take() else { return }; + let row_top = center_y - ROW_HEIGHT / 2.0; + let slot = Rect::from_min_size(pos2(slot_left, row_top), vec2(INFO_SLOT, ROW_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(slot, id, Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tip)); + + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + self.ui.painter().text(pos2(glyph_x, center_y), Align2::CENTER_CENTER, ic::INFO, FontId::proportional(INFO_ICON_SIZE), color); + + // Under the row from the i, ending before the value column; above it where the window ends first + let anchor = Rect::from_min_max(pos2(self.left, row_top), pos2(self.right - TIP_VALUE_ROOM, row_top + ROW_HEIGHT)); + let frame = Frame::NONE + .fill(tokens.chrome) + .stroke(Stroke::new(1.0, tokens.field_border)) + .corner_radius(CornerRadius::same(TIP_ROUNDING)) + .inner_margin(TIP_MARGIN) + .shadow(TIP_SHADOW); + let text_width = anchor.width() - TIP_MARGIN.sum().x; + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip + .popup + .anchor(anchor) + .align(RectAlign::BOTTOM_START) + .align_alternatives(&[RectAlign::TOP_START]) + .gap(-TIP_OVERLAP) + .frame(frame) + .width(text_width); + tooltip.show(|ui| { + ui.set_width(text_width); + ui.label(RichText::new(tip).size(SMALL_TEXT_SIZE).color(tokens.text).line_height(Some(TIP_LINE_HEIGHT))); + }); + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 53afe419..cbd25d6a 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -1,8 +1,216 @@ //! The Properties panel's rows, groups and controls, shared by every panel so they line up +mod axis_rows; +mod band_response; +mod button_icon; +mod choice; +mod eye_toggle; +mod group; +mod hold_pad; +mod info_icon; +mod number_field; +mod open_card; +mod preview_block; +mod preview_edit; +mod preview_lower; +mod preview_size; +mod row; +mod row_lead; mod section_tabs; +mod sheet_measure; +mod slider; +mod slot; +mod stack_slider; +mod switch_control; +mod tooltip; +mod track; +mod value_text; pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; +#[cfg(test)] +mod tests; + +pub(crate) use band_response::BandResponse; +pub(crate) use button_icon::ButtonIcon; +pub(crate) use number_field::NumberField; +pub(crate) use preview_lower::PreviewLower; +pub(crate) use preview_size::PreviewSize; +pub(crate) use row_lead::RowLead; +pub(crate) use stack_slider::StackSlider; + +use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; + +use crate::theme::{Tokens, semibold}; +use open_card::OpenCard; +use sheet_measure::SheetMeasure; /// Side padding: every row starts and ends this far inside the panel pub(crate) const PAD: f32 = 12.0; + +/// Row pitch: every control row is one box this tall with its control centred +pub(crate) const ROW_HEIGHT: f32 = 28.0; + +/// Height of dropdowns, fields, switches and buttons +const CONTROL_HEIGHT: f32 = 24.0; + +/// Air between groups and after loose rows +const GROUP_GAP: f32 = 6.0; + +/// The narrowest label column, from the panel's left padding to the controls +const LABEL_COLUMN_MIN: f32 = 90.0; + +/// Labels wider than this stack above a full-width control and never widen the column +const LABEL_MAX: f32 = 132.0; + +/// Air between the widest label and the controls column +const LABEL_TO_CONTROL: f32 = 12.0; + +/// A label fits beside its control when it leaves at least this much air before the column +const LABEL_MIN_AIR: f32 = 8.0; + +/// The least air a loose label leaves before the controls column +const LOOSE_LABEL_AIR: f32 = 2.0; + +/// The narrowest value column at a slider's right end +const VALUE_MIN_WIDTH: f32 = 26.0; + +/// Air between a slider track's end and the value column, room for the knob and a gap +const TRACK_TO_VALUE: f32 = 14.0; + +/// Size of regular labels and SemiBold values +const TEXT_SIZE: f32 = 12.0; + +/// Size of captions, pill names and the switch's words +const SMALL_TEXT_SIZE: f32 = 11.0; + +/// Size of the caret and small glyphs drawn as icons +const ICON_SIZE: f32 = 12.0; + +/// Size of a picture row's picture, and the air after it +const ROW_PICTURE_SIZE: f32 = 18.0; +const ROW_PICTURE_AIR: f32 = 8.0; + +/// How far above and below a row's centre a slider track or a typed value takes the pointer +const ROW_HIT_HALF_HEIGHT: f32 = 10.0; + +/// Corner radius of dropdowns, fields and buttons +const CONTROL_RADIUS: u8 = 4; + +/// Air above and below a picture block, as a control has in its row +const BLOCK_MARGIN: f32 = 2.0; + +/// The Properties panel being laid out this frame: where the controls column is, which card is open, and what this frame measured for the next one +pub(crate) struct PropertySheet<'u> { + pub(crate) ui: &'u mut Ui, + tokens: Tokens, + id: Id, + scope: Id, + band_scope: Id, + named: Vec, + left: f32, + right: f32, + used: SheetMeasure, + seen: SheetMeasure, + card: Option, + air_at: Option, + drawn_bottom: f32, + empty: bool, + sections: Vec<(String, f32)>, + info: Option<&'u str>, + held: bool, +} + +impl<'u> PropertySheet<'u> { + /// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen + pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let id = ui.make_persistent_id(id_salt); + let used = ui.data(|data| data.get_temp::(id)).unwrap_or_default(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let rect = ui.available_rect_before_wrap(); + let mut sheet = PropertySheet { + tokens: Tokens::get(ui.ctx()), + id, + scope: id, + band_scope: id, + named: Vec::new(), + left: rect.left() + PAD, + right: rect.right() - PAD, + used, + seen: SheetMeasure::default(), + card: None, + air_at: None, + drawn_bottom: rect.top(), + empty: true, + sections: Vec::new(), + info: None, + held: false, + ui, + }; + let result = body(&mut sheet); + sheet.close_card(); + if !sheet.sections.is_empty() { + let view_top = sheet.ui.clip_rect().top(); + section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top }); + } + + let seen = sheet.seen; + if seen != used { + sheet.ui.data_mut(|data| data.insert_temp(id, seen)); + sheet.ui.ctx().request_discard("Properties columns changed"); + } + result + } + + /// The controls column: wide enough for this panel's labels, capped at [`LABEL_MAX`] + fn column(&self) -> f32 { + self.left + LABEL_COLUMN_MIN.max(self.used.label_width + LABEL_TO_CONTROL) + } + + /// Where the knob of a slider's track ends: left of this panel's widest value + fn track_end(&self) -> f32 { + self.right - self.used.value_width.max(VALUE_MIN_WIDTH) - TRACK_TO_VALUE + } + + /// Records a value's width for the panel's value column + fn measure_value(&mut self, text: &str) { + let width = self.text_width(text, semibold(TEXT_SIZE)); + self.seen.value_width = self.seen.value_width.max(width); + } + + fn text_width(&self, text: &str, font: FontId) -> f32 { + self.ui.painter().layout_no_wrap(text.to_owned(), font, Color32::WHITE).size().x + } + + /// Takes the next `height` pixels of the panel, full width; marks what it draws down to + fn take(&mut self, height: f32) -> Rect { + let (rect, _) = self.ui.allocate_exact_size(vec2(self.ui.available_width(), height), egui::Sense::hover()); + self.empty = false; + rect + } + + /// Leaves `height` pixels of air + fn space(&mut self, height: f32) { + self.ui.add_space(height); + } + + fn cursor_y(&self) -> f32 { + self.ui.cursor().top() + } + + /// Notes that something was painted down to `bottom`, so an open card ends its padding below it + fn drawn(&mut self, bottom: f32) { + self.drawn_bottom = self.drawn_bottom.max(bottom); + } + + /// A control's box: [`CONTROL_HEIGHT`] tall, centred in its row, from `x0` to the right edge + fn control_box(&self, x0: f32, center_y: f32) -> Rect { + Rect::from_min_max(pos2(x0, center_y - CONTROL_HEIGHT / 2.0), pos2(self.right, center_y + CONTROL_HEIGHT / 2.0)) + } + + /// The colour of a top-level band: between the window frame and a card + fn band_fill(&self) -> Color32 { + let tokens = &self.tokens; + let mid = |a: u8, b: u8| ((u16::from(a) + u16::from(b)) / 2) as u8; + Color32::from_rgb(mid(tokens.chrome.r(), tokens.row.r()), mid(tokens.chrome.g(), tokens.row.g()), mid(tokens.chrome.b(), tokens.row.b())) + } +} diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs new file mode 100644 index 00000000..22337ebb --- /dev/null +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -0,0 +1,212 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Air between neighbouring fields of one row +const FIELD_GAP: f32 = 4.0; + +/// Room kept at the row's end for the link button, on every row of a group that has one +const LINK_SLOT: f32 = 26.0; + +/// Size of the link button +pub(super) const LINK_SIZE: f32 = 18.0; + +/// From a field's left edge to its axis letter's left edge +const TAG_LETTER_INSET: f32 = 7.0; + +/// From a field's left edge to its glyph's centre +const TAG_GLYPH_CENTER: f32 = 10.0; + +/// From a field's right edge to its value's right end +const VALUE_INSET: f32 = 6.0; + +/// Least air between a field's tag and its value: a value that would come closer drops decimals +const TAG_VALUE_GAP: f32 = 5.0; + +/// One part of a row of number fields: its tag (an axis letter in its colour, or a glyph) and value +pub(crate) struct NumberField<'a> { + pub(crate) tag: &'a str, + + /// The axis letter's colour; `None` draws `tag` as a dim glyph + pub(crate) tag_color: Option, + + pub(crate) value: f32, + + /// Change per pixel dragged + pub(crate) speed: f32, + + pub(crate) decimals: usize, + + /// A unit after the value ("°") + pub(crate) suffix: &'a str, +} + +/// The air between a field's axis tag and its typing box +const TAG_TO_TYPING: f32 = 6.0; + +impl PropertySheet<'_> { + /// A row of number fields (drag or type); returns the edited index and whether it continues a drag + pub(crate) fn number_fields(&mut self, label: &str, fields: &mut [NumberField], link: Option<&mut bool>, keep_link_slot: bool) -> Option<(usize, bool)> { + let (control, center_y) = self.row(label); + let slot = if link.is_some() || keep_link_slot { LINK_SLOT } else { 0.0 }; + let count = fields.len().max(1) as f32; + let width = (control.width() - slot - (count - 1.0) * FIELD_GAP) / count; + + let mut edited = None; + for (index, field) in fields.iter_mut().enumerate() { + let left = control.left() + index as f32 * (width + FIELD_GAP); + let rect = Rect::from_min_size(pos2(left, control.top()), vec2(width, control.height())); + if let Some(merge) = self.number_field(rect, label, field) { + edited = Some((index, merge)); + } + } + + if let Some(linked) = link { + self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); + } + edited + } + + /// The link that keeps two values together; returns whether it was clicked + pub(super) fn link_button(&mut self, center: egui::Pos2, linked: &mut bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *linked, crate::i18n::tr("Link"))); + let response = self.tip(response, crate::i18n::tr("Link")); + if response.clicked() { + *linked = !*linked; + } + + let tokens = self.tokens; + let (fill, border) = if *linked { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + let glyph = if *linked { ic::LINK_SIMPLE_HORIZONTAL } else { ic::LINK_SIMPLE_HORIZONTAL_BREAK }; + painter.text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), tokens.text); + response.clicked() + } + + /// One field: its tag on the left, the value on the right; drag or click to type. Named "`label` `tag`" ("Scale X") + fn number_field(&mut self, rect: Rect, label: &str, field: &mut NumberField) -> Option { + let id = self.next_id(); + let typing_id = id.with("typed"); + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + match field.tag_color { + Some(color) => { + painter.text(pos2(rect.left() + TAG_LETTER_INSET, rect.center().y), Align2::LEFT_CENTER, field.tag, semibold(SMALL_TEXT_SIZE), color); + } + None => { + painter.text( + pos2(rect.left() + TAG_GLYPH_CENTER, rect.center().y), + Align2::CENTER_CENTER, + field.tag, + FontId::proportional(ICON_SIZE), + tokens.text_dim, + ); + } + } + + let decimals = field.decimals; + if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { + let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, edit); + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + if !response.lost_focus() { + self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + return None; + } + + let untouched = self.end_typing(typing_id, &text); + if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + return None; + } + + // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile + if untouched || text.trim() == shown_number(field.value, decimals) { + return None; + } + + let typed: f32 = text.trim().trim_end_matches(field.suffix).trim().parse().ok()?; + if !typed.is_finite() || typed == field.value { + return None; + } + + field.value = typed; + return Some(false); + } + + self.skip_typing_edit(); + let response = self.ui.interact(rect, id, Sense::click_and_drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(field.value), format!("{label} {}", field.tag))); + let tag_right = match field.tag_color { + Some(_) => rect.left() + TAG_LETTER_INSET + painter.layout_no_wrap(field.tag.to_owned(), semibold(SMALL_TEXT_SIZE), tokens.text).size().x, + None => rect.left() + TAG_GLYPH_CENTER + ICON_SIZE / 2.0, + }; + let room = rect.right() - VALUE_INSET - tag_right - TAG_VALUE_GAP; + let shown = fitting_number(field.value, decimals, field.suffix, room, |text| { + painter.layout_no_wrap(text.to_owned(), semibold(TEXT_SIZE), tokens.text).size().x + }); + painter.text(pos2(rect.right() - VALUE_INSET, rect.center().y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); + if response.hovered() || response.dragged() { + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + + if response.clicked() { + self.start_typing(typing_id, shown_number(field.value, decimals)); + return None; + } + + if response.dragged() { + crate::pointer_lock::ask_for_hold(self.ui.ctx()); + } + let delta = response.drag_delta().x; + let moved = response.dragged() && delta != 0.0; + if moved { + field.value += delta * field.speed; + } + crate::widgets::press_edit(self.ui, response.id, moved) + } +} + +/// `value` and `suffix` with up to `decimals` decimals, as many as fit `room` wide (as measured by `width`), at least none +fn fitting_number(value: f32, decimals: usize, suffix: &str, room: f32, width: impl Fn(&str) -> f32) -> String { + let mut decimals = decimals; + loop { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + if decimals == 0 || width(&shown) <= room { + return shown; + } + + decimals -= 1; + } +} + +/// `value` with `decimals` decimals, a value that rounds to zero reading 0 without a minus sign +pub(super) fn shown_number(value: f32, decimals: usize) -> String { + let shown = format!("{value:.decimals$}"); + let zero = shown.trim_start_matches('-').chars().all(|digit| matches!(digit, '0' | '.')); + if zero { shown.trim_start_matches('-').to_owned() } else { shown } +} + +#[cfg(test)] +mod tests { + use super::fitting_number; + + /// Every character is 7 wide + fn width(text: &str) -> f32 { + 7.0 * text.chars().count() as f32 + } + + #[test] + fn a_value_too_wide_for_its_field_drops_decimals_before_it_reaches_the_tag() { + assert_eq!(fitting_number(1.0, 2, "", 28.0, width), "1.00"); + assert_eq!(fitting_number(1.0, 2, "", 27.0, width), "1.0"); + assert_eq!(fitting_number(-12.5, 2, "°", 30.0, width), "-12°"); + assert_eq!(fitting_number(12345.0, 2, "", 1.0, width), "12345"); + } +} diff --git a/crates/ui-egui/src/property_sheet/open_card.rs b/crates/ui-egui/src/property_sheet/open_card.rs new file mode 100644 index 00000000..2063742d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/open_card.rs @@ -0,0 +1,10 @@ +use egui::layers::ShapeIdx; + +/// A card whose rows are being laid out; its face is painted behind them once they end +pub(super) struct OpenCard { + /// Where the card starts + pub(super) top: f32, + + /// The placeholder the card's face is painted into, behind its rows + pub(super) face: ShapeIdx, +} diff --git a/crates/ui-egui/src/property_sheet/preview_block.rs b/crates/ui-egui/src/property_sheet/preview_block.rs new file mode 100644 index 00000000..e76045cf --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_block.rs @@ -0,0 +1,153 @@ +use egui::{Align2, FontId, Painter, Rect, Stroke, StrokeKind, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::number_field::LINK_SIZE; +use super::preview_edit::PreviewEdit; +use super::preview_lower::PreviewLower; +use super::preview_size::PreviewSize; +use super::row::CAPTION_LINE; +use super::track::Track; +use super::{BLOCK_MARGIN, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE}; + +/// One slider line beside the preview square +const PART_LINE: f32 = 22.0; + +/// Air between the size and what follows it +const PART_GAP: f32 = 6.0; + +/// From the block's top to the square's top: the first caption's letters +const SQUARE_TOP: f32 = 4.0; + +/// The square stops this far above the block's bottom: the last knob's bottom +const SQUARE_SHORTER: f32 = 10.0; + +/// Air between the square and the controls beside it +const SQUARE_TO_SIDE: f32 = 12.0; + +/// From the side's left edge to a direction glyph's centre, and to the track after it +const GLYPH_CENTER: f32 = 5.0; +const GLYPH_TRACK: f32 = 18.0; + +/// Room kept at the right edge for the link, on every line, so the tracks end together +pub(super) const LINK_ROOM: f32 = 24.0; + +/// The value column's width beside the square: every track ends this far left of the value's end +const SIDE_VALUE_WIDTH: f32 = 46.0; + +/// The air kept between a side slider's track and its value +const SIDE_VALUE_AIR: f32 = 8.0; + +impl PropertySheet<'_> { + /// A preview square beside its stack (the size, then Offset or one setting), exactly as tall as the stack + pub(crate) fn preview_block(&mut self, picture: &dyn Fn(&Painter, Rect), size: PreviewSize<'_>, lower: PreviewLower<'_>) -> PreviewEdit { + let size_rows = if *size.linked { 1 } else { 2 }; + let lower_rows = match lower { + PreviewLower::Offset { .. } => 2, + PreviewLower::Slider { .. } => 1, + }; + let height = CAPTION_LINE + PART_LINE * size_rows as f32 + PART_GAP + CAPTION_LINE + PART_LINE * lower_rows as f32; + self.space(BLOCK_MARGIN); + let block = self.take(height); + let top = block.top(); + + let side = (height - SQUARE_SHORTER).max(1.0); + let square = Rect::from_min_size(pos2(self.left, top + SQUARE_TOP), vec2(side, side)); + picture(self.ui.painter(), square); + self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + + let x0 = square.right() + SQUARE_TO_SIDE; + let value_right = self.right - LINK_ROOM; + let track_end = value_right - SIDE_VALUE_WIDTH; + let mut edit = PreviewEdit { square, size: None, lower: None }; + let mut y = top; + + self.side_caption(x0, y, size.label); + y += CAPTION_LINE; + let linked = *size.linked; + for part in 0..size_rows { + let center_y = y + PART_LINE / 2.0; + let start = if linked { x0 } else { self.direction_glyph(x0, center_y, part) }; + let mut value = size.values[part]; + let label = format_args!("{}{}", size.label, part_suffix(part)); + if let Some(merge) = self.side_slider(label, start, track_end, value_right, center_y, &mut value, (&size.range, &size.typed), size.decimals, false) + { + size.values[part] = value; + if linked { + size.values[1] = value; + } + edit.size = Some(merge); + } + y += PART_LINE; + } + let link_center = pos2(self.right - LINK_SIZE / 2.0, y - PART_LINE / 2.0); + if self.link_button(link_center, size.linked) && *size.linked && size.values[1] != size.values[0] { + size.values[1] = size.values[0]; + edit.size = Some(false); + } + y += PART_GAP; + + match lower { + PreviewLower::Offset { values, range, typed } => { + let offset = crate::i18n::tr("Offset"); + self.side_caption(x0, y, offset); + y += CAPTION_LINE; + for part in 0..2 { + let center_y = y + PART_LINE / 2.0; + let start = self.direction_glyph(x0, center_y, part); + let label = format_args!("{offset}{}", part_suffix(part)); + if let Some(merge) = self.side_slider(label, start, track_end, value_right, center_y, &mut values[part], (&range, &typed), 2, true) { + edit.lower = Some(merge); + } + y += PART_LINE; + } + } + PreviewLower::Slider { label, value, range, decimals } => { + self.side_caption(x0, y, label); + y += CAPTION_LINE; + if let Some(merge) = self.side_slider(label, x0, track_end, value_right, y + PART_LINE / 2.0, value, (&range, &range), decimals, false) { + edit.lower = Some(merge); + } + } + } + self.drawn(square.bottom()); + self.space(BLOCK_MARGIN); + edit + } + + fn side_caption(&self, x: f32, top: f32, text: &str) { + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(x, top + CAPTION_LINE / 2.0), Align2::LEFT_CENTER, text, FontId::proportional(SMALL_TEXT_SIZE), dim); + } + + /// The ⇄ (across) or ⇅ (down) glyph before a part's track; returns where the track starts + fn direction_glyph(&self, x0: f32, center_y: f32, part: usize) -> f32 { + let glyph = if part == 0 { ic::ARROWS_LEFT_RIGHT } else { ic::ARROWS_DOWN_UP }; + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(x0 + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), dim); + x0 + GLYPH_TRACK + } + + #[allow(clippy::too_many_arguments)] + fn side_slider( + &mut self, + label: impl std::fmt::Display, + start: f32, + end: f32, + value_right: f32, + center_y: f32, + value: &mut f32, + (range, typed_range): (&std::ops::RangeInclusive, &std::ops::RangeInclusive), + decimals: usize, + signed: bool, + ) -> Option { + let id = self.next_id(); + let dragged = self.track(id, &label, &Track { start, end, center_y, zero: signed.then_some(0.0), ramp: false }, value, range); + let typed = self.value_field_at(id, &label, value_right, SIDE_VALUE_WIDTH - SIDE_VALUE_AIR, center_y, *value, typed_range, decimals, ""); + Self::apply_typed(value, typed, dragged) + } +} + +/// What a part's name adds to its caption: nothing for the first, " 2" for the second +fn part_suffix(part: usize) -> &'static str { + if part == 0 { "" } else { " 2" } +} diff --git a/crates/ui-egui/src/property_sheet/preview_edit.rs b/crates/ui-egui/src/property_sheet/preview_edit.rs new file mode 100644 index 00000000..8ba1324f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_edit.rs @@ -0,0 +1,8 @@ +/// What a preview block's controls changed this frame (`Some(merge)` per edited part), and where its square is +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PreviewEdit { + /// Where the preview square sits, for a surface over it + pub(crate) square: egui::Rect, + pub(crate) size: Option, + pub(crate) lower: Option, +} diff --git a/crates/ui-egui/src/property_sheet/preview_lower.rs b/crates/ui-egui/src/property_sheet/preview_lower.rs new file mode 100644 index 00000000..085ff6c5 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_lower.rs @@ -0,0 +1,10 @@ +use std::ops::RangeInclusive; + +/// What sits under the size beside a preview square +pub(crate) enum PreviewLower<'a> { + /// Offset across and down, signed + Offset { values: &'a mut [f32; 2], range: RangeInclusive, typed: RangeInclusive }, + + /// One other setting (tri-planar Hardness) + Slider { label: &'a str, value: &'a mut f32, range: RangeInclusive, decimals: usize }, +} diff --git a/crates/ui-egui/src/property_sheet/preview_size.rs b/crates/ui-egui/src/property_sheet/preview_size.rs new file mode 100644 index 00000000..c2ebc45e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/preview_size.rs @@ -0,0 +1,20 @@ +use std::ops::RangeInclusive; + +/// The size beside a preview square: one slider while linked, one per direction otherwise +pub(crate) struct PreviewSize<'a> { + /// The caption above it (Tiling, Size (cm), Scaling) + pub(crate) label: &'a str, + + /// Across and down; while linked, down follows across + pub(crate) values: &'a mut [f32; 2], + + /// What the track spans + pub(crate) range: RangeInclusive, + + /// What a typed value may be: wider than the track + pub(crate) typed: RangeInclusive, + + pub(crate) decimals: usize, + + pub(crate) linked: &'a mut bool, +} diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs new file mode 100644 index 00000000..28af9dd7 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -0,0 +1,236 @@ +use egui::{Align2, FontId, Id, Rect, Response, Sense, Stroke, pos2}; +use egui_phosphor::regular as ic; + +use super::{ + CONTROL_HEIGHT, ICON_SIZE, LABEL_MAX, LABEL_MIN_AIR, LOOSE_LABEL_AIR, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, + SMALL_TEXT_SIZE, TEXT_SIZE, +}; +use crate::theme::semibold; + +/// Air above a stacked label +const STACK_AIR: f32 = 4.0; + +/// Height of a stacked label's line, from its air to the control row under it +const STACK_LABEL_LINE: f32 = 14.0; + +/// A stacked label's centre below its line's top +const STACK_LABEL_CENTER: f32 = 8.0; + +/// A caption line's height +pub(super) const CAPTION_LINE: f32 = 18.0; + +/// How far small text reaches below its centre line +const SMALL_TEXT_HALF_LINE: f32 = 6.0; + +/// The square a row-end glyph answers the pointer in +const GLYPH_BOX: f32 = 20.0; + +/// Air above a section caption that follows other rows, and the hairline's distance below it +const SECTION_AIR: f32 = 6.0; + +/// The hairline above a later section caption, to the caption's top +pub(super) const SECTION_RULE_TO_CAPTION: f32 = 12.0; + +/// Air above the panel's first section caption +const FIRST_SECTION_AIR: f32 = 12.0; + +/// Height of a section caption's line, including the air under it +const SECTION_CAPTION_LINE: f32 = 24.0; + +/// From a section caption's line top to its text's centre +pub(super) const SECTION_CAPTION_CENTER: f32 = 7.0; + +/// Size of a section's menu glyph +const SECTION_MENU_ICON_SIZE: f32 = 14.0; + +/// Distance from the right edge to the centre of a right-edge glyph (caret, menu) +pub(super) const EDGE_GLYPH_INSET: f32 = 6.0; + +/// Size of the round reset glyph on a section caption or a band +pub(super) const RESET_ICON_SIZE: f32 = 14.0; + +/// Opacity of a reset glyph at the defaults, where it does nothing +const RESET_AT_DEFAULT_OPACITY: f32 = 0.4; + +/// From the right edge to the centre of a section caption's reset: its 14 px glyph ends at the dropdowns' right edge +const SECTION_RESET_INSET: f32 = RESET_ICON_SIZE / 2.0; + +impl PropertySheet<'_> { + /// [`Self::section`] with the round section reset at the caption's right end: faint and inert at the defaults (`changed` false); returns whether it was clicked + pub(crate) fn section_reset(&mut self, title: &str, changed: bool) -> bool { + let text = self.tokens.text; + let center_y = self.section_caption(title, text); + + let glyph = Rect::from_center_size(pos2(self.right - SECTION_RESET_INSET, center_y), egui::Vec2::splat(GLYPH_BOX)); + let id = self.id.with(("section_reset", title)); + let sense = if changed { Sense::click() } else { Sense::hover() }; + let response = self.ui.interact(glyph, id, sense); + + let label = crate::i18n::tr("Reset to defaults"); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, changed, format_args!("{title}: {label}"))); + + if changed { + // Left of the glyph, on the caption's line: it covers no value + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(glyph).align(egui::RectAlign::LEFT).align_alternatives(&[egui::RectAlign::BOTTOM_END]); + tooltip.show(|ui| ui.label(crate::i18n::tr("Restore defaults"))); + } + + let color = self.reset_glyph_color(changed, response.hovered(), self.tokens.text_strong); + self.ui.painter().text(glyph.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_ICON_SIZE), color); + changed && response.clicked() + } + + /// A reset or clear glyph's colour: faint where it does nothing (`live` false), `hover_color` under the pointer, dim otherwise + pub(super) fn reset_glyph_color(&self, live: bool, hovered: bool, hover_color: egui::Color32) -> egui::Color32 { + match (live, hovered) { + (false, _) => self.tokens.text_dim.gamma_multiply(RESET_AT_DEFAULT_OPACITY), + (true, true) => hover_color, + (true, false) => self.tokens.text_dim, + } + } + + /// [`Self::section`] with its caption in `color` + pub(super) fn section_in(&mut self, title: &str, menu: bool, color: egui::Color32) -> Option { + let center_y = self.section_caption(title, color); + if !menu { + return None; + } + + let glyph = Rect::from_center_size(pos2(self.right - EDGE_GLYPH_INSET, center_y), egui::Vec2::splat(GLYPH_BOX)); + let id = self.id.with(("section_menu", title)); + let response = self.ui.interact(glyph, id, Sense::click()); + let color = if response.hovered() { self.tokens.text } else { self.tokens.text_dim }; + self.ui.painter().text(glyph.center(), Align2::CENTER_CENTER, ic::LIST, FontId::proportional(SECTION_MENU_ICON_SIZE), color); + Some(response) + } + + /// A section caption in capitals in `color`, a hairline above a later one; returns the caption's centre line + fn section_caption(&mut self, title: &str, color: egui::Color32) -> f32 { + self.close_card(); + + // Named state before the section's first band is keyed by the section, not by the band above it + if self.card.is_none() { + let section = self.id.with(("section", title)); + self.band_scope = section; + self.scope = section; + } + + if !self.empty { + self.space(SECTION_AIR); + let y = self.cursor_y(); + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.space(SECTION_RULE_TO_CAPTION); + } else { + self.space(FIRST_SECTION_AIR); + } + + let rect = self.take(SECTION_CAPTION_LINE); + self.sections.push((title.to_owned(), rect.top())); + if super::section_tabs::take_jump(self.ui, title) { + // Scroll by the distance itself: a top-aligned scroll_to_rect stops short by the scroll area's item spacing, which the sheet cannot see + let hairline = rect.top() - SECTION_RULE_TO_CAPTION; + let to_top = self.ui.clip_rect().top() - hairline; + self.ui.scroll_with_delta(egui::vec2(0.0, to_top)); + } + + let center_y = rect.top() + SECTION_CAPTION_CENTER; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title.to_uppercase(), semibold(SMALL_TEXT_SIZE), color); + self.drawn(center_y + SMALL_TEXT_HALF_LINE); + self.air_at = None; + center_y + } + + /// One setting's row: label beside the controls column or stacked above; returns the control's box and centre + pub(crate) fn row(&mut self, label: &str) -> (Rect, f32) { + self.row_with(RowLead::label(label)) + } + + /// [`Self::row`] led by `lead` + pub(crate) fn row_with(&mut self, lead: RowLead<'_>) -> (Rect, f32) { + let x0 = self.lead_with(lead); + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + let picture = matches!(lead, RowLead::Picture { .. }); + self.drawn(center_y + if picture { ROW_PICTURE_SIZE } else { CONTROL_HEIGHT } / 2.0); + (self.control_box(x0, center_y), center_y) + } + + /// Paints a row's lead and returns where its control starts; pictures and children never widen the column + pub(crate) fn lead_with(&mut self, lead: RowLead<'_>) -> f32 { + let font = FontId::proportional(TEXT_SIZE); + let center_y = self.cursor_y() + ROW_HEIGHT / 2.0; + let shift = self.lead_shift(); + let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; + let (label, stack, text_color) = match lead { + RowLead::Label { text, stack } => (text, stack, self.tokens.text), + RowLead::Loose(text) if shift + self.text_width(text, font.clone()) <= self.column() - self.left - LOOSE_LABEL_AIR => { + self.paint_info(center_y); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); + return self.column(); + } + RowLead::Loose(text) => return self.stacked_label(text, shift), + RowLead::Picture { picture, text } => { + self.paint_info(center_y); + let square = Rect::from_center_size(pos2(self.left + shift + ROW_PICTURE_SIZE / 2.0, center_y), egui::vec2(ROW_PICTURE_SIZE, ROW_PICTURE_SIZE)); + picture(self.ui.painter(), square); + self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); + return self.column(); + } + RowLead::Child(text) => { + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text_dim); + return self.column(); + } + }; + + // The i's slot counts as part of the label + let width = shift + self.text_width(label, font.clone()); + if width <= LABEL_MAX { + self.seen.label_width = self.seen.label_width.max(width); + } + + if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { + self.paint_info(center_y); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); + return self.column(); + } + + self.stacked_label(label, shift) + } + + /// Paints `label` on its own line above a full-width control, `shift` right of the edge after its i; returns the control's left edge + fn stacked_label(&mut self, label: &str, shift: f32) -> f32 { + self.space(STACK_AIR); + let rect = self.take(STACK_LABEL_LINE); + let center_y = rect.top() + STACK_LABEL_CENTER; + self.paint_info(center_y); + let text = self.tokens.text; + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), text); + self.left + } + + /// A caret pointing down (open) or right (folded), centred on `center` + pub(super) fn caret(&self, center: egui::Pos2, open: bool, color: egui::Color32) { + let glyph = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + self.ui.painter().text(center, Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), color); + } + + /// The next control's id: stable while the panel shows the same rows + pub(super) fn next_id(&mut self) -> Id { + let id = self.ui.next_auto_id(); + self.ui.skip_ahead_auto_ids(1); + id + } + + /// The id of a group or colour bar whose state outlives the frame: keyed by its name inside the open band and card, so rows shown or hidden above it never hand it another's state + pub(super) fn named_id(&mut self, kind: &str, title: &str) -> Id { + let mut id = self.scope.with((kind, title)); + + // A repeated name in one scope (two cards of one effect) takes the next free id + while self.named.contains(&id) { + id = id.with(kind); + } + self.named.push(id); + id + } +} diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs new file mode 100644 index 00000000..5d3b981c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -0,0 +1,30 @@ +use egui::{Painter, Rect}; + +/// What leads a setting's row, left of its control +#[derive(Clone, Copy)] +pub(crate) enum RowLead<'a> { + /// A label beside the controls column; it stacks above a full-width control when it doesn't fit, or always with `stack` + Label { text: &'a str, stack: bool }, + + /// A label beside the controls column that never widens it; it stacks only when it can't fit with [`super::LOOSE_LABEL_AIR`] before the column + Loose(&'a str), + + /// A picture at the left edge with its label after it (culling rows) + Picture { picture: &'a dyn Fn(&Painter, Rect), text: &'a str }, + + /// A setting of the row above, dim, its label on the label column like its parent's + Child(&'a str), +} + +impl<'a> RowLead<'a> { + /// A label beside the controls column + pub(crate) fn label(text: &'a str) -> RowLead<'a> { + RowLead::Label { text, stack: false } + } + + /// The row's name, as assistive tech reads it + pub(crate) fn text(self) -> &'a str { + match self { + } + } +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 5b7d6187..99edf990 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -1,13 +1,116 @@ use egui::{CornerRadius, Painter, Rect, pos2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Painter, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; use crate::theme::Tokens; +use super::row::SECTION_RULE_TO_CAPTION; +use super::{PAD, SMALL_TEXT_SIZE}; +use crate::theme::{Tokens, semibold}; + +mod section_scope; +mod section_tops; + +pub(crate) use section_scope::SectionScope; +pub(super) use section_tops::SectionTops; + +/// Height of the tab strip +const STRIP_HEIGHT: f32 = 30.0; + +/// How far the first tab reaches left of the rows' side padding +const FIRST_TAB_OUTDENT: f32 = 4.0; + +/// From the panel's left edge to the first tab +const FIRST_TAB: f32 = PAD - FIRST_TAB_OUTDENT; + +/// A tab's width beyond its name: icon and air (the resource picker's tabs share these measures) +pub(crate) const TAB_PADDING: f32 = 38.0; + +/// Air between tabs +pub(crate) const TAB_GAP: f32 = 2.0; /// The chosen tab starts this far below the strip's top and reaches this far into the panel +pub(crate) const TAB_TOP: f32 = 4.0; const TAB_BELOW: f32 = 6.0; /// Corner rounding of the chosen tab pub(crate) const TAB_ROUNDING: u8 = 5; +/// From a tab's left edge to its icon's centre, and to its name +pub(crate) const TAB_ICON_CENTER: f32 = 14.0; +pub(crate) const TAB_NAME_LEFT: f32 = 26.0; + +/// Size of a tab's icon and of its name +pub(crate) const TAB_ICON_SIZE: f32 = 13.0; +pub(crate) const TAB_TEXT_SIZE: f32 = SMALL_TEXT_SIZE; + +/// A section counts as in view once its caption is this close to the top of the scrolled area +const IN_VIEW_SLACK: f32 = 30.0; + +/// Where the scope of the sections being drawn is kept while a strip's contents run +fn scope_id() -> Id { + Id::unique("property_sheet_section_scope") +} + +/// Where a strip keeps its section positions and the section one of its tabs asked to jump to +fn sections_id(scope: SectionScope) -> Id { + Id::unique("property_sheet_sections").with(scope) +} + +fn jump_id(scope: SectionScope) -> Id { + Id::unique("property_sheet_jump").with(scope) +} + +/// Runs `body` with its section captions tied to the `scope` strip +pub(crate) fn in_scope(ui: &mut Ui, scope: SectionScope, body: impl FnOnce(&mut Ui) -> R) -> R { + let outer = ui.data(|data| data.get_temp::(scope_id())); + ui.data_mut(|data| data.insert_temp(scope_id(), scope)); + let result = body(ui); + ui.data_mut(|data| data.insert_temp(scope_id(), outer.unwrap_or(SectionScope::Docked))); + result +} + +/// The strip the sections being drawn belong to: the docked panel's unless a caller said otherwise +fn current_scope(ui: &Ui) -> SectionScope { + ui.data(|data| data.get_temp::(scope_id())).unwrap_or(SectionScope::Docked) +} + +/// Stores this frame's section captions for the tabs +pub(super) fn remember(ui: &Ui, tops: SectionTops) { + let scope = current_scope(ui); + ui.data_mut(|data| data.insert_temp(sections_id(scope), tops)); +} + +/// Drops the captions the sheets stored last frame, so a list drawn without sections leaves none behind; call before drawing the list +pub(crate) fn forget_sections(ui: &Ui) { + let scope = current_scope(ui); + ui.data_mut(|data| data.remove::(sections_id(scope))); +} + +/// Room to leave under the sheets just drawn in `ui`'s scroll area so the last section's top can reach the top of the view +pub(crate) fn room_past_end(ui: &Ui) -> f32 { + let scope = current_scope(ui); + let last_top = ui.data(|data| data.get_temp::(sections_id(scope))).and_then(|tops| tops.last_top()); + let Some(last_top) = last_top else { return 0.0 }; + + // Where a jump to the section scrolls to: its hairline at the top + let reach = last_top - SECTION_RULE_TO_CAPTION; + (reach + ui.clip_rect().height() - ui.min_rect().bottom()).max(0.0) +} + +/// Whether a tab asked to show `title`: the caller scrolls to it once +pub(super) fn take_jump(ui: &Ui, title: &str) -> bool { + let jump = jump_id(current_scope(ui)); + let wanted = ui.data(|data| data.get_temp::(jump)).is_some_and(|wanted| wanted == title); + if wanted { + ui.data_mut(|data| data.remove::(jump)); + } + wanted +} + +/// A tab from `left` to `right` on `strip`: from just under the strip's top down into the panel the strip sits on +fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { + Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(right, strip.bottom() + TAB_BELOW)) +} + /// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW)) @@ -17,3 +120,36 @@ pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); } + +/// The tab strip on the `scope` panel's top edge, top corners rounded by `top_corner`: one tab per section; a click scrolls to it +pub(crate) fn section_tabs(ui: &mut Ui, scope: SectionScope, top_corner: u8, tabs: &[(&str, &str)]) { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + let corners = CornerRadius { nw: top_corner, ne: top_corner, sw: 0, se: 0 }; + ui.painter().rect_filled(strip, corners, tokens.chrome); + let seen = ui.data(|data| data.get_temp::(sections_id(scope))).unwrap_or_default(); + let lit = seen.lit(); + + let mut x = strip.left() + FIRST_TAB; + for (index, (icon, title)) in tabs.iter().enumerate() { + let on = lit.map_or(index == 0, |lit| lit == *title); + let width = ui.painter().layout_no_wrap((*title).to_owned(), semibold(TAB_TEXT_SIZE), Color32::WHITE).size().x + TAB_PADDING; + let tab = tab_rect(strip, x, x + width); + let response = ui.interact(tab, ui.scope_id().with(("section_tab", index)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, *title)); + if response.clicked() { + ui.data_mut(|data| data.insert_temp(jump_id(scope), (*title).to_owned())); + } + + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, tab); + } + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(x + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, *icon, FontId::proportional(TAB_ICON_SIZE), color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(x + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, *title, font, color); + x += width + TAB_GAP; + } +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs new file mode 100644 index 00000000..5fe48e1f --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_scope.rs @@ -0,0 +1,8 @@ +/// Which strip the sections belong to: the docked panel and the right-click popup can show the same sections at once +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub(crate) enum SectionScope { + /// The docked Properties panel + Docked, + /// The right-click Properties popup over a view + Popup, +} diff --git a/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs b/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs new file mode 100644 index 00000000..5165c7eb --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs/section_tops.rs @@ -0,0 +1,21 @@ +use super::IN_VIEW_SLACK; + +/// The sections' captions seen last frame, top to bottom, and the top of the area they scroll in +#[derive(Clone, Default)] +pub(crate) struct SectionTops { + pub(crate) tops: Vec<(String, f32)>, + pub(crate) view_top: f32, +} + +impl SectionTops { + /// The section in view: the last caption at the top (the panel scrolls far enough for the last one to get there) + pub(crate) fn lit(&self) -> Option<&str> { + let reached = self.tops.iter().rev().find(|(_, top)| *top <= self.view_top + IN_VIEW_SLACK); + reached.or(self.tops.first()).map(|(title, _)| title.as_str()) + } + + /// The top of the last section's caption + pub(crate) fn last_top(&self) -> Option { + self.tops.last().map(|(_, top)| *top) + } +} diff --git a/crates/ui-egui/src/property_sheet/sheet_measure.rs b/crates/ui-egui/src/property_sheet/sheet_measure.rs new file mode 100644 index 00000000..e4a16d55 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/sheet_measure.rs @@ -0,0 +1,15 @@ +/// What one pass of a Properties panel measured, used to place the next pass's columns +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct SheetMeasure { + /// The widest label that sits beside its control + pub(super) label_width: f32, + + /// Where the widest toggle label ends, from the panel's left padding + pub(super) toggle_label_end: f32, + + /// Where the widest picture row's name ends, from the panel's left padding + pub(super) picture_label_end: f32, + + /// The widest value at a slider's right end + pub(super) value_width: f32, +} diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs new file mode 100644 index 00000000..cfd35af1 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -0,0 +1,238 @@ +use std::ops::RangeInclusive; + + +use super::number_field::shown_number; +use super::track::Track; +use super::value_text::ValueText; +use crate::theme::semibold; + +/// Radius of a slider's knob +pub(super) const KNOB_RADIUS: f32 = 5.0; + +/// Width of a slider's knob outline +const KNOB_STROKE: f32 = 1.5; + +/// Width of a slider's track +const TRACK_WIDTH: f32 = 2.0; + +/// Half the height of a signed slider's zero tick +const ZERO_TICK_HALF: f32 = 4.0; + +/// Radius of an angle row's dial +const DIAL_RADIUS: f32 = 8.0; + +/// The quarter turn back from the screen's 0 rad (pointing right) that points the dial's hand straight up at 0° +const DIAL_ZERO_DEGREES: f32 = 90.0; + +/// Air between the dial and the value, and between the track's end and the dial +const DIAL_AIR: f32 = 6.0; + +impl PropertySheet<'_> { + /// [`Self::slider_with_suffix`] led by `lead` (a picture row, a child setting) + pub(crate) fn slider_led(&mut self, lead: RowLead<'_>, value: &mut f32, range: RangeInclusive, decimals: usize, suffix: &str) -> Option { + let (control, center_y) = self.row_with(lead); + let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, lead.text(), &track, value, &range); + let typed = self.value_field(id, lead.text(), center_y, *value, &range, decimals, suffix); + Self::apply_typed(value, typed, dragged) + } + + /// An angle in degrees: the track, then a small dial just before the value + pub(crate) fn angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_led(RowLead::label(label), degrees, range) + } + + /// [`Self::angle`] led by `lead` + pub(crate) fn angle_led(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_shown(lead, degrees, range, false) + } + + /// [`Self::angle_led`], the value shown with its sign when `plus` + fn angle_shown(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive, plus: bool) -> Option { + let (control, center_y) = self.row_with(lead); + let id = self.next_id(); + let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; + let track = Track { + start: control.left() + KNOB_RADIUS, + end: dial_x - DIAL_RADIUS - DIAL_AIR, + center_y, + zero: (*range.start() < 0.0).then_some(0.0), + ramp: false, + }; + let name = lead.text(); + let dragged = self.track(id, name, &track, degrees, &range); + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.circle_stroke(pos2(dial_x, center_y), DIAL_RADIUS, Stroke::new(KNOB_STROKE, tokens.button_border)); + let turn = (*degrees - DIAL_ZERO_DEGREES).to_radians(); + let hand = pos2(dial_x + DIAL_RADIUS * turn.cos(), center_y + DIAL_RADIUS * turn.sin()); + painter.line_segment([pos2(dial_x, center_y), hand], Stroke::new(TRACK_WIDTH, tokens.text)); + + let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; + let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); + Self::apply_typed(degrees, typed, dragged) + } + + /// A typed value wins over a drag in the same frame and starts its own undo step + pub(super) fn apply_typed(value: &mut f32, typed: Option, dragged: Option) -> Option { + match typed { + Some(typed) => { + *value = typed; + Some(false) + } + None => dragged, + } + } + + /// Paints a track with its knob and moves `value` while it is clicked or dragged + pub(super) fn track(&mut self, id: Id, label: impl std::fmt::Display, track: &Track, value: &mut f32, range: &RangeInclusive) -> Option { + let (minimum, maximum) = (*range.start(), *range.end()); + let span = (maximum - minimum).max(f32::EPSILON); + let length = (track.end - track.start).max(1.0); + let hit = Rect::from_min_max( + pos2(track.start - KNOB_RADIUS, track.center_y - ROW_HIT_HALF_HEIGHT), + pos2(track.end + KNOB_RADIUS, track.center_y + ROW_HIT_HALF_HEIGHT), + ); + let response = self.ui.interact(hit, id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + + let mut moved = false; + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() + { + let picked = kept_in(minimum + (pointer.x - track.start) / length * span, range); + if picked != *value { + *value = picked; + moved = true; + } + } + + // A press's first change starts an undo step, its later changes continue it + let edit = crate::widgets::press_edit(self.ui, response.id, moved); + + let tokens = self.tokens; + let at = |v: f32| track.start + ((v - minimum) / span).clamp(0.0, 1.0) * length; + let knob_x = at(*value); + let zero_x = track.zero.map_or(track.start, |zero| at(kept_in(zero, range))); + let painter = self.ui.painter(); + if !track.ramp { + painter.line_segment([pos2(track.start, track.center_y), pos2(track.end, track.center_y)], Stroke::new(TRACK_WIDTH, tokens.button_border)); + painter.line_segment([pos2(zero_x.min(knob_x), track.center_y), pos2(zero_x.max(knob_x), track.center_y)], Stroke::new(TRACK_WIDTH, tokens.accent)); + } + if track.zero.is_some() { + let tick = [pos2(zero_x, track.center_y - ZERO_TICK_HALF), pos2(zero_x, track.center_y + ZERO_TICK_HALF)]; + painter.line_segment(tick, Stroke::new(1.0, tokens.text_dim)); + } + let outline = if response.hovered() || response.dragged() { tokens.accent } else { tokens.text }; + painter.circle(pos2(knob_x, track.center_y), KNOB_RADIUS, tokens.panel, Stroke::new(KNOB_STROKE, outline)); + edit + } + + /// The value at the row's end, answering as `label`'s value; a click turns it into a field, which returns the typed value when done + #[allow(clippy::too_many_arguments)] + pub(super) fn value_field( + &mut self, + id: Id, + label: impl std::fmt::Display, + center_y: f32, + value: f32, + range: &RangeInclusive, + decimals: usize, + suffix: &str, + ) -> Option { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.column_value_field(id, &label, center_y, &shown, suffix, value, range, decimals) + } + + /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it + #[allow(clippy::too_many_arguments)] + pub(super) fn column_value_field( + &mut self, + id: Id, + label: &dyn std::fmt::Display, + center_y: f32, + shown: &str, + suffix: &str, + value: f32, + range: &RangeInclusive, + decimals: usize, + ) -> Option { + self.measure_value(shown); + let width = self.used.value_width.max(super::VALUE_MIN_WIDTH); + self.value_text_field(id, ValueText { label, right: self.right, width, center_y, shown, suffix }, value, range, decimals) + } + + /// [`Self::value_field`] ending at `right`, `width` wide, outside the panel's value column + #[allow(clippy::too_many_arguments)] + pub(super) fn value_field_at( + &mut self, + id: Id, + label: impl std::fmt::Display, + right: f32, + width: f32, + center_y: f32, + value: f32, + range: &RangeInclusive, + decimals: usize, + suffix: &str, + ) -> Option { + let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.value_text_field(id, ValueText { label: &label, right, width, center_y, shown: &shown, suffix }, value, range, decimals) + } + + /// A value drawn as `text.shown` that turns into a field when clicked; returns the typed value (its `text.suffix` and a leading "×" or "x" allowed), kept in `range` + pub(super) fn value_text_field(&mut self, id: Id, value_text: ValueText<'_>, value: f32, range: &RangeInclusive, decimals: usize) -> Option { + let ValueText { label, right, width, center_y, shown, suffix } = value_text; + let rect = Rect::from_min_max(pos2(right - width, center_y - ROW_HIT_HALF_HEIGHT), pos2(right, center_y + ROW_HIT_HALF_HEIGHT)); + let field_id = id.with("typed"); + let editing = self.ui.data(|data| data.get_temp::(field_id)); + let seeded = || shown_number(value, decimals); + + let tokens = self.tokens; + let Some(mut typed_text) = editing else { + self.skip_typing_edit(); + let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); + self.ui.painter().text(pos2(right, center_y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); + + if response.hovered() { + self.value_line(rect.left(), right, center_y, tokens.field_border); + } + if response.clicked() { + self.start_typing(field_id, seeded()); + } + return None; + }; + + // Typing happens on the value's own line: no box, the line under it goes accent + let edit = egui::TextEdit::singleline(&mut typed_text).id(field_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(rect.left(), right, center_y, edit); + self.value_line(rect.left(), right, center_y, tokens.accent); + if !response.lost_focus() { + self.ui.data_mut(|data| data.insert_temp(field_id, typed_text)); + return None; + } + + let untouched = self.end_typing(field_id, &typed_text); + if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + return None; + } + + // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile + if untouched || typed_text.trim() == seeded() { + return None; + } + + let typed: f32 = typed_text.trim().trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?; + + // A typed value that lands on the current one (a clamp, "0.750" for 0.75) is no edit either + typed.is_finite().then(|| kept_in(typed, range)).filter(|kept| *kept != value) + } +} + +/// `value` kept in `range`; unlike `clamp`, a reversed or NaN range never panics +pub(super) fn kept_in(value: f32, range: &RangeInclusive) -> f32 { + value.max(*range.start()).min(*range.end()) +} diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs new file mode 100644 index 00000000..96e72f7e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -0,0 +1,64 @@ + + +/// Air between a full-width button's icon and its words +const BUTTON_ICON_GAP: f32 = 8.0; + +/// Size of a full-width button's icon +const BUTTON_ICON_SIZE: f32 = 14.0; + +impl PropertySheet<'_> { + /// A full-width button: centred icon and words + pub(crate) fn button<'a>(&mut self, icon: impl Into>, text: &str) -> egui::Response { + self.button_lit(icon, text, false) + } + + /// A full-width button lit in the accent while what it turns on stays on + pub(crate) fn button_lit<'a>(&mut self, icon: impl Into>, text: &str, lit: bool) -> egui::Response { + self.button_enabled(icon, text, lit, true) + } + + /// [`Self::button_lit`] that answers no clicks and dims its words while not `enabled` + pub(crate) fn button_enabled<'a>(&mut self, icon: impl Into>, text: &str, lit: bool, enabled: bool) -> egui::Response { + self.button_sensing(icon.into(), text, lit, if enabled { Sense::click() } else { Sense::hover() }) + } + + fn button_sensing(&mut self, icon: ButtonIcon<'_>, text: &str, lit: bool, sense: Sense) -> egui::Response { + let enabled = sense != Sense::hover(); + let rect = self.take(ROW_HEIGHT); + let button = self.control_box(self.left, rect.center().y); + let id = self.next_id(); + let response = self.ui.interact(button, id, sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, text)); + + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect( + button, + CornerRadius::same(CONTROL_RADIUS), + match (lit, enabled && response.hovered()) { + (true, _) => tokens.accent_dim, + (false, true) => tokens.row_hover, + (false, false) => tokens.button, + }, + Stroke::new(1.0, if lit { tokens.accent } else { tokens.button_border }), + StrokeKind::Inside, + ); + let color = if enabled { tokens.text } else { tokens.text_dim }; + let font = FontId::proportional(TEXT_SIZE); + let (icon_width, icon_galley) = match icon { + ButtonIcon::Glyph(glyph) => { + let galley = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(BUTTON_ICON_SIZE), color); + (galley.size().x, Some(galley)) + } + }; + let text_galley = painter.layout_no_wrap(text.to_owned(), font, color); + let total = icon_width + BUTTON_ICON_GAP + text_galley.size().x; + let x = button.center().x - total / 2.0; + if let Some(galley) = icon_galley { + painter.galley(pos2(x, button.center().y - galley.size().y / 2.0), galley, color); + } + painter.galley(pos2(x + icon_width + BUTTON_ICON_GAP, button.center().y - text_galley.size().y / 2.0), text_galley, color); + self.drawn(button.bottom()); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/stack_slider.rs b/crates/ui-egui/src/property_sheet/stack_slider.rs new file mode 100644 index 00000000..b68c602d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/stack_slider.rs @@ -0,0 +1,20 @@ +use std::ops::RangeInclusive; + +/// One captioned slider in the stack beside a picture +pub(crate) struct StackSlider<'a> { + /// The dim caption above the track (Count, Angle span) + pub(crate) label: &'a str, + + pub(crate) value: &'a mut f32, + + /// What the track spans + pub(crate) range: RangeInclusive, + + /// What a typed value may reach, at least the track's span (a radial Count types past its track's most) + pub(crate) typed: RangeInclusive, + + pub(crate) decimals: usize, + + /// A unit after the value ("°") + pub(crate) suffix: &'a str, +} diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs new file mode 100644 index 00000000..e0107857 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -0,0 +1,204 @@ +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use crate::theme::semibold; + +/// Draws a picture row's picture into its square +type RowPicture<'a> = &'a dyn Fn(&Painter, Rect); + +/// Draws option `index`'s picture into its square +type SegmentPicture<'a> = &'a dyn Fn(&Painter, Rect, usize); + +/// Side of a picture beside a switch's word, and the air between them +const SEGMENT_PICTURE_SIZE: f32 = 14.0; +const SEGMENT_PICTURE_AIR: f32 = 6.0; + +/// Room a switch's word needs in its segment beyond its own width (6 px each side: Bevel Smooth's Out | In | In/Out fits beside the widest label column) +const SEGMENT_AIR: f32 = 12.0; + +/// How far the chosen segment sits inside the switch's box +const SEGMENT_INSET: f32 = 2.0; + +/// Corner radius of a switch's box +const SWITCH_RADIUS: u8 = 6; + +/// Size of a toggle's pill +pub(super) const PILL_SIZE: egui::Vec2 = vec2(22.0, 13.0); + +/// Corner radius of a toggle's pill: about half its height, so its ends are round +const PILL_RADIUS: u8 = 6; + +/// Radius of a toggle's knob, and how far it sits from the pill's middle +const TOGGLE_KNOB_RADIUS: f32 = 4.0; +const TOGGLE_KNOB_TRAVEL: f32 = 4.5; + +/// From one of a pair's toggles to the next, and from its name to its pill's centre +const PAIR_PITCH: f32 = 76.0; +const PAIR_NAME_TO_PILL: f32 = 32.0; + +impl PropertySheet<'_> { + /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index + pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + self.switch_tinted(label, options, selected, &[]) + } + + /// [`Self::switch`] whose chosen word takes its colour from `tints` (axis colours) + pub(crate) fn switch_tinted(&mut self, label: &str, options: &[&str], selected: usize, tints: &[Color32]) -> Option { + let stacks = self.text_width(label, FontId::proportional(TEXT_SIZE)) > self.column() - self.left - super::LABEL_MIN_AIR; + let left = if stacks { self.left } else { self.column() }; + if !self.switch_fits(options, left) { + return self.switch_dropdown(label, options, selected); + } + + let (control, _) = self.row(label); + let runs = |index: usize| tints.get(index).map(std::slice::from_ref).unwrap_or_default(); + self.segments(control, options, selected, runs, None) + } + + /// Whether every option's word fits its share of a switch from `left` to the panel's right edge + fn switch_fits(&self, options: &[&str], left: f32) -> bool { + let segment = (self.right - left) / options.len().max(1) as f32; + options.iter().all(|option| self.text_width(option, semibold(SMALL_TEXT_SIZE)) + SEGMENT_AIR <= segment) + } + + /// The dropdown a switch whose words don't fit becomes; returns the picked index + fn switch_dropdown(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + let name = |index: usize| options.get(index).copied().unwrap_or_default().to_owned(); + self.dropdown_built(label, selected, || 0..options.len(), name, None).0 + } + + /// A boxed switch's box and segments in `control`, the chosen word in the colours `tints` gives its index (none: the text colour); returns the segment clicked when it was not the chosen one + pub(super) fn segments<'t>( + &mut self, + control: Rect, + options: &[&str], + selected: usize, + tints: impl Fn(usize) -> &'t [Color32], + picture: Option>, + ) -> Option { + let segment = control.width() / options.len().max(1) as f32; + let tokens = self.tokens; + self.ui.painter().rect(control, CornerRadius::same(SWITCH_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + let mut picked = None; + for (index, option) in options.iter().enumerate() { + let rect = Rect::from_min_size(pos2(control.left() + index as f32 * segment, control.top()), vec2(segment, control.height())); + let id = self.next_id(); + let response = self.ui.interact(rect, id, Sense::click()); + let on = index == selected; + response.widget_info(|| WidgetInfo::selected(Role::RadioButton, true, on, *option)); + if response.clicked() && !on { + picked = Some(index); + } + + let painter = self.ui.painter(); + if on { + painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.button); + } else if response.hovered() { + painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.row_hover); + } + let runs = tints(index); + let tint = runs.first().copied().unwrap_or(tokens.text); + let (font, color) = if on { (semibold(SMALL_TEXT_SIZE), tint) } else { (FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) }; + let Some(draw) = picture else { + let word = + if on && runs.len() > 1 { split_word(painter, option, runs, &font) } else { painter.layout_no_wrap((*option).to_owned(), font, color) }; + painter.galley(rect.center() - word.size() / 2.0, word, color); + continue; + }; + + // The picture and the word centred together in the segment + let word = painter.layout_no_wrap((*option).to_owned(), font, color); + let left = rect.center().x - (SEGMENT_PICTURE_SIZE + SEGMENT_PICTURE_AIR + word.size().x) / 2.0; + draw( + painter, + Rect::from_min_size(pos2(left, rect.center().y - SEGMENT_PICTURE_SIZE / 2.0), vec2(SEGMENT_PICTURE_SIZE, SEGMENT_PICTURE_SIZE)), + index, + ); + let word_left = left + SEGMENT_PICTURE_SIZE + SEGMENT_PICTURE_AIR; + painter.galley(pos2(word_left, rect.center().y - word.size().y / 2.0), word, color); + } + picked + } + + /// A culling row on the panel's grid: its name on the label column, its picture where the controls start with the switch after it, a pending i at the row's right end + pub(crate) fn picture_toggle(&mut self, picture: RowPicture<'_>, label: &str, on: &mut bool) -> bool { + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + self.paint_info_at_end(center_y); + let font = FontId::proportional(TEXT_SIZE); + + // A name too long for the label column pushes every picture row's picture right instead of running under it + let label_end = self.text_width(label, font.clone()) + super::LABEL_MIN_AIR; + self.seen.picture_label_end = self.seen.picture_label_end.max(label_end); + let picture_x = self.left + (self.column() - self.left).max(self.used.picture_label_end).max(label_end); + let square = Rect::from_min_size(pos2(picture_x, center_y - ROW_PICTURE_SIZE / 2.0), vec2(ROW_PICTURE_SIZE, ROW_PICTURE_SIZE)); + let pill = Rect::from_min_size(pos2(square.right() + ROW_PICTURE_AIR, center_y - PILL_SIZE.y / 2.0), PILL_SIZE); + let clicked = self.toggle_hit(Rect::from_min_max(pos2(self.left, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + + let text = self.tokens.text; + picture(self.ui.painter(), square); + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, label, font, text); + self.pill(pill.center(), *on, true); + self.drawn(square.bottom()); + clicked + } + + /// A toggle's clickable area: a click flips `on`; returns whether it was clicked + fn toggle_hit(&mut self, hit: Rect, label: &str, on: &mut bool) -> bool { + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, label)); + response.clicked() + } + + /// Two named toggles side by side after one label (Flip copy: U, V); returns the index clicked + pub(crate) fn toggle_pair(&mut self, label: &str, names: [&str; 2], on: &mut [bool; 2]) -> Option { + let (control, center_y) = self.row(label); + let font = FontId::proportional(TEXT_SIZE); + let mut clicked = None; + for (index, (name, state)) in names.into_iter().zip(on.iter_mut()).enumerate() { + let x = control.left() + index as f32 * PAIR_PITCH; + let pill = pos2(x + PAIR_NAME_TO_PILL, center_y); + let hit = Rect::from_min_max(pos2(x, control.top()), pos2(pill.x + PILL_SIZE.x / 2.0, control.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}"))); + if response.clicked() { + *state = !*state; + clicked = Some(index); + } + let tokens = self.tokens; + self.ui.painter().text(pos2(x, center_y), Align2::LEFT_CENTER, name, font.clone(), if *state { tokens.text } else { tokens.text_dim }); + self.pill(pill, *state, true); + } + clicked + } + + /// A toggle's pill centred on `center`: on (accent), off, or greyed out when not `enabled` + pub(super) fn pill(&self, center: egui::Pos2, on: bool, enabled: bool) { + let tokens = self.tokens; + let (fill, border, knob, knob_x) = match (enabled, on) { + (false, _) => (tokens.field, tokens.separator, tokens.separator, center.x - TOGGLE_KNOB_TRAVEL), + (true, true) => (tokens.accent_dim, tokens.accent, tokens.text, center.x + TOGGLE_KNOB_TRAVEL), + (true, false) => (tokens.button, tokens.button_border, tokens.text_dim, center.x - TOGGLE_KNOB_TRAVEL), + }; + let painter = self.ui.painter(); + painter.rect(Rect::from_center_size(center, PILL_SIZE), CornerRadius::same(PILL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + painter.circle_filled(pos2(knob_x, center.y), TOGGLE_KNOB_RADIUS, knob); + } +} + +/// `word` laid out with its letters split as evenly as they go between the colours of `runs` +fn split_word(painter: &Painter, word: &str, runs: &[Color32], font: &FontId) -> std::sync::Arc { + let letters: Vec = word.chars().collect(); + let mut job = egui::text::LayoutJob::default(); + let parts = runs.len().max(1); + for (part, color) in runs.iter().enumerate() { + let (start, end) = (letters.len() * part / parts, letters.len() * (part + 1) / parts); + let text: String = letters.get(start..end).unwrap_or_default().iter().collect(); + job.append(&text, 0.0, egui::TextFormat::simple(font.clone(), *color)); + } + painter.layout_job(job) +} diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs new file mode 100644 index 00000000..546bddf2 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -0,0 +1,243 @@ +use egui::{Color32, CornerRadius, Painter, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; + +use super::number_field::shown_number; +use super::{NumberField, PropertySheet}; +use crate::theme::{Accent, Brightness, Tokens}; + +mod filtering; +mod gallery; + +use filtering::Filtering; +use gallery::Gallery; + +/// Width of the Properties panel the mockups are drawn at +const PANEL_WIDTH: f32 = 300.0; + +/// The harness window: the panel plus room on its right for popups and tips, tall enough for the whole gallery unscrolled +const HARNESS_SIZE: egui::Vec2 = egui::vec2(PANEL_WIDTH + 260.0, 1000.0); + +fn swatch(color: Color32) -> impl Fn(&Painter, Rect) { + move |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, color); + } +} + +fn filtering_picture(painter: &Painter, rect: Rect, filtering: Filtering) { + let shade = match filtering { + Filtering::BilinearHq => 200, + Filtering::BilinearSharp => 150, + Filtering::Nearest => 100, + }; + painter.rect_filled(rect.shrink(2.0), CornerRadius::same(2), Color32::from_gray(shade)); +} + +fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "gallery", |sheet| { + if let Some(picked) = sheet + .dropdown( + "Filtering", + state.filtering, + &[Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest], + Filtering::name, + Some(&filtering_picture), + ) + .0 + { + state.filtering = picked; + } + + let reset = sheet.band("3D projection settings", true, Some(state.position != [0.0; 3]), None); + if reset.reset { + state.position = [0.0; 3]; + } + if reset.open { + let mut fields = [("X", 0), ("Y", 1), ("Z", 2)].map(|(tag, axis)| NumberField { + tag, + tag_color: crate::theme::AXIS_COLORS.get(axis).copied(), + value: state.position[axis], + speed: 0.01, + decimals: 2, + suffix: "", + }); + if let Some((axis, merge)) = sheet.number_fields("Position", &mut fields, Some(&mut state.linked), false) + && let Some(slot) = state.position.get_mut(axis) + { + *slot = fields[axis].value; + state.position_merges.push(merge); + } + } + }); + }); +} + +/// A harness in `brightness`, with the app's fonts from the first frame +fn builder(brightness: Brightness) -> egui_kittest::HarnessBuilder { + Harness::builder().with_size(HARNESS_SIZE).with_context_setup(move |ctx| { + crate::theme::install(ctx); + crate::theme::apply(ctx, brightness, Accent::default()); + }) +} + +fn gallery_harness(brightness: Brightness, gallery_state: Gallery) -> Harness<'static, Gallery> { + let mut harness = builder(brightness).build_ui_state(gallery, gallery_state); + harness.run_steps(3); + harness +} + +/// Two culling rows, the second named past the label column +fn culling_rows(ui: &mut egui::Ui, on: &mut [bool; 2]) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "culling", |sheet| { + sheet.picture_toggle(&swatch(Color32::from_gray(160)), "Depth", &mut on[0]); + sheet.picture_toggle(&swatch(Color32::from_gray(100)), "Backface culling past the column", &mut on[1]); + }); + }); +} + +/// A culling name too long for the label column moves every culling row's picture and switch, so the switches stay one column +#[test] +fn culling_rows_keep_their_switches_in_one_column_when_a_name_is_long() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(culling_rows, [false; 2]); + harness.run_steps(3); + + let short = harness.get_by_label("Depth").rect(); + let long = harness.get_by_label("Backface culling past the column").rect(); + + assert_eq!(short.right(), long.right(), "both switches end at one x: {short:?} vs {long:?}"); +} + +/// A gray slider in a panel-wide column; records the column's right edge +fn gray_row(ui: &mut egui::Ui, state: &mut (f32, f32)) { + ui.set_width(PANEL_WIDTH); + state.1 = ui.max_rect().right(); + crate::gray_slider::gray_slider(ui, "Color", &mut state.0); +} + +/// A gray slider's invert button ends on the column's right edge (a plain button was wider than the room kept for it) +#[test] +fn a_gray_sliders_invert_button_ends_on_its_columns_right_edge() { + // the slider's typed value field (upstream's) carries no accessible name + let mut harness = builder(Brightness::MediumDark).with_accessibility_check(false).build_ui_state(gray_row, (0.5, 0.0)); + harness.run_steps(3); + + let invert = harness.get_by_role(egui::accesskit::Role::Button).rect(); + let right = harness.state().1; + assert!(invert.right() <= right + 0.5, "the button ends at {} past the column's {right}", invert.right()); +} + +/// Where `wanted` is painted, first to last +fn painted_at(harness: &Harness<'_, State>, wanted: &str) -> Vec { + let shapes = harness.output().shapes.iter(); + shapes + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == wanted => Some(text.pos), + _ => None, + }) + .collect() +} + +/// An open dropdown's options start their words at the button's own word x (they started 1 px in, inside the list's border) +#[test] +fn an_open_dropdowns_options_start_at_the_buttons_word() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let button = harness.get_by_label("Bilinear | HQ").rect(); + + let at = button.center(); + click_at(&mut harness, at); + harness.run_steps(2); + + let button_word = painted_at(&harness, "Bilinear | HQ").into_iter().find(|at| button.contains(*at)).map(|at| at.x); + let option_word = painted_at(&harness, "Nearest").first().map(|at| at.x); + assert!(button_word.is_some() && option_word == button_word, "the option's word at {option_word:?}, the button's at {button_word:?}"); +} + +#[test] +fn dropdown_list_hangs_from_its_button_at_its_width_and_picks() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let button = harness.get_by_label("Bilinear | HQ").rect(); + let at = harness.get_by_label("Bilinear | HQ").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + let option = harness.get_by_label("Nearest").rect(); + let list = option.expand(super::choice::LIST_BORDER); + assert_eq!(list.left(), button.left(), "the list starts at the button's left edge"); + assert_eq!(list.width(), button.width(), "the list is the button's width"); + assert!(option.top() > button.bottom(), "the list hangs below the button"); + + let at = harness.get_by_label("Nearest").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert_eq!(harness.state().filtering, Filtering::Nearest); +} + +/// Presses and lets go at `at` through the real pointer path, so a control drawn over another gets the click it would get from a person +fn click_at(harness: &mut Harness<'_, State>, at: egui::Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(1); +} + +/// A reason too long for its caption's row is cut with "…", and hovering it shows it whole +#[test] +fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + const REASON: &str = "Not available with this projection, for a reason far too long to fit beside the caption"; + const TOOLTIP_WAIT_FRAMES: usize = 60; + let mut harness = builder(Brightness::MediumDark).build_ui(|ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "unavailable", |sheet| sheet.section_unavailable("Symmetry", REASON)); + }); + harness.run_steps(2); + let reason = harness.get_by_label(REASON).rect(); + assert!(reason.right() <= PANEL_WIDTH + 1.0, "the reason is cut to fit the panel: {reason:?}"); + + harness.hover_at(reason.center()); + harness.run_steps(TOOLTIP_WAIT_FRAMES); + assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole"); +} + +/// A number field held still until egui starts its drag, then moved, starts its own undo step with its first change +#[test] +fn a_number_field_held_still_then_dragged_starts_an_undo_step_with_its_first_change() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let field = harness.get_by_label("Position X").rect(); + harness.drag_at(field.center()); + + // Past egui's longest click, the press becomes a drag that has not moved + harness.run_steps(5); + harness.hover_at(field.center() + egui::vec2(10.0, 0.0)); + harness.run(); + harness.hover_at(field.center() + egui::vec2(20.0, 0.0)); + harness.run(); + harness.drop_at(field.center() + egui::vec2(20.0, 0.0)); + harness.run(); + + let merges = &harness.state().position_merges; + assert!(merges.len() >= 2, "the drag changes the value more than once: {merges:?}"); + assert_eq!(merges.first(), Some(&false), "the first move starts an undo step: {merges:?}"); + assert!(merges.iter().skip(1).all(|merge| *merge), "later moves continue it: {merges:?}"); +} + +#[test] +fn a_number_field_reads_zero_without_a_minus_sign() { + assert_eq!(shown_number(-0.0, 0), "0"); + assert_eq!(shown_number(-0.004, 2), "0.00"); + assert_eq!(shown_number(-0.3, 0), "0"); + assert_eq!(shown_number(-0.6, 0), "-1"); + assert_eq!(shown_number(-1.25, 2), "-1.25"); + assert_eq!(shown_number(2.5, 1), "2.5"); +} diff --git a/crates/ui-egui/src/property_sheet/tests/filtering.rs b/crates/ui-egui/src/property_sheet/tests/filtering.rs new file mode 100644 index 00000000..b37210ca --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/filtering.rs @@ -0,0 +1,19 @@ +//! The gallery's Filtering choice + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Filtering { + BilinearHq, + BilinearSharp, + Nearest, +} + +impl Filtering { + pub(super) fn name(self) -> String { + match self { + Filtering::BilinearHq => "Bilinear | HQ", + Filtering::BilinearSharp => "Bilinear | Sharp", + Filtering::Nearest => "Nearest", + } + .to_owned() + } +} diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs new file mode 100644 index 00000000..3a9e730a --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -0,0 +1,15 @@ +//! What the gallery's controls last set + +use super::Filtering; + +pub(super) struct Gallery { + pub(super) filtering: Filtering, + pub(super) position: [f32; 3], + pub(super) position_merges: Vec, + pub(super) linked: bool, +} + +impl Default for Gallery { + fn default() -> Self { + } +} diff --git a/crates/ui-egui/src/property_sheet/tooltip.rs b/crates/ui-egui/src/property_sheet/tooltip.rs new file mode 100644 index 00000000..d9c37f65 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tooltip.rs @@ -0,0 +1,32 @@ +use egui::{RectAlign, Response}; + +use super::PropertySheet; + +/// Where a tooltip goes when the window has no room above a control in the panel's right half: below it, then the other edge +const RIGHT_HALF_FALLBACKS: [RectAlign; 3] = [RectAlign::BOTTOM_END, RectAlign::TOP_START, RectAlign::BOTTOM_START]; + +/// The same for a control in the panel's left half +const LEFT_HALF_FALLBACKS: [RectAlign; 3] = [RectAlign::BOTTOM_START, RectAlign::TOP_END, RectAlign::BOTTOM_END]; + +impl PropertySheet<'_> { + /// A tooltip for `response` right next to it: above the control, flush with its edge nearer the panel's side so it grows toward the middle + pub(crate) fn tip(&self, response: Response, text: &str) -> Response { + let (align, fallbacks) = if response.rect.center().x > self.ui.max_rect().center().x { + (RectAlign::TOP_END, &RIGHT_HALF_FALLBACKS) + } else { + (RectAlign::TOP_START, &LEFT_HALF_FALLBACKS) + }; + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(&response).align(align).align_alternatives(fallbacks); + tooltip.show(|ui| ui.label(text)); + response + } + + /// A tooltip for a pad, outside the panel beside it, where it covers no value of the panel; under it when the panel has no room on its left + pub(crate) fn tip_beside(&self, response: Response, text: &str) -> Response { + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(&response).align(RectAlign::LEFT_START).align_alternatives(&[RectAlign::BOTTOM_START]); + tooltip.show(|ui| ui.label(text)); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/track.rs b/crates/ui-egui/src/property_sheet/track.rs new file mode 100644 index 00000000..d4f2f91c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/track.rs @@ -0,0 +1,13 @@ +//! The line a slider's knob runs along + +/// What a slider's knob runs along and shows +pub(super) struct Track { + pub(super) start: f32, + pub(super) end: f32, + pub(super) center_y: f32, + /// Where a two-sided range's fill starts and its tick sits (0 for signed ranges, 0.5 for a 0..1 range centred on "unchanged") + pub(super) zero: Option, + + /// The track is a picture of its range (a gray ramp) drawn by the caller: no line and no fill + pub(super) ramp: bool, +} diff --git a/crates/ui-egui/src/property_sheet/value_text.rs b/crates/ui-egui/src/property_sheet/value_text.rs new file mode 100644 index 00000000..b40ca7a4 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/value_text.rs @@ -0,0 +1,63 @@ +//! Where a slider's value sits and how it reads + +/// A value drawn right-aligned at `right` in a `width` wide box centred on `center_y`, reading `shown`; typing may end in `suffix`; it answers as `label`'s value +pub(super) struct ValueText<'a> { + pub(super) label: &'a dyn std::fmt::Display, + pub(super) right: f32, + pub(super) width: f32, + pub(super) center_y: f32, + pub(super) shown: &'a str, + pub(super) suffix: &'a str, +} + +/// How far below a value's centre its typing line runs +const LINE_DROP: f32 = 9.0; + +/// Where the field `field_id` keeps the text its typing opened with +fn opened_id(field_id: egui::Id) -> egui::Id { + field_id.with("opened") +} + +impl super::PropertySheet<'_> { + /// Starts typing `text` into the field `field_id`, all of it selected so the first key replaces it + pub(super) fn start_typing(&mut self, field_id: egui::Id, text: String) { + let mut state = egui::text_edit::TextEditState::load(self.ui.ctx(), field_id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + state.store(self.ui.ctx(), field_id); + self.ui.data_mut(|data| { + data.insert_temp(opened_id(field_id), text.clone()); + data.insert_temp(field_id, text); + }); + self.ui.memory_mut(|memory| memory.request_focus(field_id)); + } + + /// Ends typing into the field `field_id`; whether `typed` is still the text it opened with (left so, it changes nothing, even after the value changed meanwhile) + pub(super) fn end_typing(&mut self, field_id: egui::Id, typed: &str) -> bool { + let opened = self.ui.data_mut(|data| { + data.remove::(field_id); + data.remove_temp::(opened_id(field_id)) + }); + opened.is_some_and(|opened| opened.trim() == typed.trim()) + } + + /// Shows `edit` from `left` to `right` centred on `center_y` (an edit is never shorter than the theme's interact height), so its value sits where the shown value sat; leaves the sheet's rows where they are + pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, edit: egui::TextEdit<'_>) -> egui::Response { + let line = self.ui.painter().layout_no_wrap("0".to_owned(), crate::theme::semibold(super::TEXT_SIZE), self.tokens.text).size().y; + let height = line.max(self.ui.spacing().interact_size.y); + let rect = egui::Rect::from_min_max(egui::pos2(left, center_y - height / 2.0), egui::pos2(right, center_y + height / 2.0)); + let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); + let mut child = self.ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(layout)); + child.add(edit.frame(egui::Frame::NONE).margin(egui::vec2(0.0, 0.0))) + } + + /// Takes the one auto id [`Self::typing_edit`]'s child takes, for a value shown instead of typed: the controls after it keep their ids when typing starts or ends, so a click from one field to the next types into the one clicked + pub(super) fn skip_typing_edit(&mut self) { + self.ui.skip_ahead_auto_ids(1); + } + + /// The 1 px line under a typeable value centred on `center_y`, from `left` to `right`: grey on hover, accent while typing + pub(super) fn value_line(&self, left: f32, right: f32, center_y: f32, color: egui::Color32) { + let y = (center_y + LINE_DROP).round() + 0.5; + self.ui.painter().line_segment([egui::pos2(left, y), egui::pos2(right, y)], egui::Stroke::new(1.0, color)); + } +} From 9be079d6f8dcf770372861a094c93b35a9bc3f99 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 008/153] Fills: every projection samples with tiling, rotation and offset, Filtering, UV Wrap and Match per UV Tile --- crates/compose/src/axis_frame.rs | 158 +++++++++ crates/compose/src/fill_place.rs | 12 + crates/compose/src/mip_level.rs | 35 ++ crates/compose/src/pattern.rs | 454 +++++++++++++++++------- crates/compose/src/tile_length.rs | 155 ++++++++ crates/core/src/layer.rs | 231 +++++++++++- crates/engine/tests/it/fill_patterns.rs | 69 ++++ crates/engine/tests/it/fill_sampling.rs | 218 ++++++++++++ 8 files changed, 1188 insertions(+), 144 deletions(-) create mode 100644 crates/compose/src/axis_frame.rs create mode 100644 crates/compose/src/fill_place.rs create mode 100644 crates/compose/src/mip_level.rs create mode 100644 crates/compose/src/tile_length.rs create mode 100644 crates/engine/tests/it/fill_patterns.rs create mode 100644 crates/engine/tests/it/fill_sampling.rs diff --git a/crates/compose/src/axis_frame.rs b/crates/compose/src/axis_frame.rs new file mode 100644 index 00000000..a4daa864 --- /dev/null +++ b/crates/compose/src/axis_frame.rs @@ -0,0 +1,158 @@ +//! The frame an axis planar projection projects from: moving one on the model places it as that frame, so its images land where they did + +use texturecraft_core::{Decal, Projection, Projector, Source}; +use texturecraft_geom::glam::{EulerRot, Mat3, Vec3}; + +use crate::frame_placement::culling_folds; +use crate::pattern::{DEPTH_FADE_START, frame_uv_from_corner, mesh_frame, nonzero_stretch, projector_stretch}; + +/// The placed planar projection that reads images exactly as axis planar `proj` does on a mesh within `bounds` (None for other projections, placed ones included, and while backface culling cannot keep its facing in a frame: see [`culling_folds`]) +pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + let Projection::Planar { scale, axis, offset, uv, projector, placed: None } = proj else { return None }; + + if !culling_folds(projector) { + return None; + } + + let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?; + + // The turn and per-axis scale are now in the frame; culling and crop stay + let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector }; + + // An axis planar turns its image round the top left, a frame round its centre + let uv = frame_uv_from_corner(uv); + Some(Projection::Planar { scale: *scale, axis: *axis, offset: *offset, uv, projector, placed: Some(frame) }) +} + +/// Whether placing an axis planar that reads `sources` would move a pattern: a procedural reads an axis planar's plane but a placed frame's uv, so such a planar keeps its axis +pub fn placing_moves_pattern<'a>(mut sources: impl Iterator) -> bool { + sources.any(|source| matches!(source, Source::Procedural { .. })) +} + +/// The frame of an axis planar projection: its image's 0..1 square on the plane through the mesh, turned and sized by `projector` +pub fn axis_frame(scale: f32, axis: u8, offset: Vec3, projector: &Projector, bounds: (Vec3, Vec3)) -> Option { + let (center, radius) = mesh_frame(bounds); + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(projector); + let scale = nonzero_stretch(scale); + + // Where the image's centre sits, then its across, up and out directions with the stretch along each + let origin = center + turn * (stretch * -offset / scale) * radius; + let (across, up, out) = match axis { + 0 => (Vec3::Z, Vec3::Y, Vec3::NEG_X), + 1 => (Vec3::X, Vec3::NEG_Z, Vec3::Y), + _ => (Vec3::X, Vec3::Y, Vec3::Z), + }; + let side = |direction: Vec3| 2.0 * radius * direction.abs().dot(stretch) / scale; + + // A negative stretch or scale turns that side over + let flip = |direction: Vec3| direction * side(direction).signum(); + let (across, up) = (flip(across), flip(up)); + let size = [side(across).abs(), side(up).abs()]; + let out = turn * across.cross(up).normalize_or(out); + + // Deep enough never to crop the mesh by depth: the fade starts at three quarters of it + let reach = (radius + (origin - center).length()) / DEPTH_FADE_START * DEPTH_SPARE; + let frame = Decal { + center: origin.to_array(), + normal: out.to_array(), + up: (turn * up).to_array(), + size, + rotation: 0.0, + offset: [0.0; 2], + depth: reach, + symmetry: None, + flip: [false; 2], + }; + (origin.is_finite() && size.iter().all(|side| side.is_finite() && *side > 0.0) && reach.is_finite()).then_some(frame) +} + +/// Extra reach past the farthest mesh point +const DEPTH_SPARE: f32 = 1.01; + +#[cfg(test)] +mod tests { + use texturecraft_core::{Backface, ShapeCrop, UvTransform}; + use texturecraft_geom::glam::Vec2; + + use super::*; + use crate::pattern::{Coords, image_samples}; + use crate::projector_cover::{framed_cover, projector_cover}; + + /// Points spread through the box `lo`..`hi` with varied normals + fn points(lo: Vec3, hi: Vec3) -> Vec<(Vec3, Vec3)> { + (0..64) + .map(|i| { + let spread = |salt: u32| ((i * 37 + salt * 11) % 64) as f32 / 63.0; + let position = lo + (hi - lo) * Vec3::new(spread(1), spread(2), spread(3)); + let normal = Vec3::new(spread(4) - 0.4, spread(5) - 0.3, spread(6) - 0.2).normalize_or(Vec3::Z); + (position, normal) + }) + .collect() + } + + #[test] + fn a_placed_axis_planar_reads_images_where_it_did() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + for axis in 0..3 { + for (rotation, stretch) in [([0.0; 3], [1.0; 3]), ([20.0, -35.0, 50.0], [1.5, 0.7, 2.0])] { + for crop in [ShapeCrop::ExtendsOutside, ShapeCrop::Cropped] { + let projector = Projector { rotation, scale: stretch, crop, ..Projector::default() }; + let uv = UvTransform { tiling: [2.0, 3.0], rotation: 30.0, offset: [0.1, -0.2] }; + let axis_planar = Projection::Planar { scale: 1.7, axis, offset: [0.3, -0.4, 0.2], uv, projector, placed: None }; + let placed = placed_from_axis(&axis_planar, (lo, hi)).expect("an axis planar has a frame"); + for (position, normal) in points(lo, hi) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (before, _) = image_samples(&axis_planar, &coords)[0]; + let (uv_after, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + let (after, _) = image_samples(&placed, &Coords { uv: uv_after, ..coords })[0]; + assert!(before.distance(after) < 1e-3, "axis {axis} {rotation:?}: {before} became {after}"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "axis {axis} {crop:?}: cover changed at {position}"); + } + } + } + } + } + + #[test] + fn a_placed_axis_planar_keeps_what_backface_culling_hides() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + let backface = Backface { on: true, angle: 60.0, hardness: 1.0 }; + + // Half way between across and out: a stretch across tilts the culled normal past the angle, a negative one turns it round + let halfway = (center, Vec3::new(1.0, 0.0, 1.0).normalize()); + + for stretch in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] { + let projector = Projector { scale: stretch, backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }; + let Some(placed) = placed_from_axis(&axis_planar, (lo, hi)) else { + assert!(!culling_folds(&projector), "{stretch:?}: only a stretch culling cannot keep stays unplaced"); + continue; + }; + + for (position, normal) in points(lo, hi).into_iter().chain([halfway]) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (_, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "{stretch:?}: culling changed at {normal}"); + } + } + + let even = Projector { scale: [1.7; 3], backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: even, placed: None }; + assert!(placed_from_axis(&axis_planar, (lo, hi)).is_some(), "an even stretch is still placed"); + } + + #[test] + fn only_axis_planars_are_placed() { + let bounds = (Vec3::NEG_ONE, Vec3::ONE); + assert!(placed_from_axis(&Projection::default(), bounds).is_none()); + let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame"); + assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none()); + assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none()); + } +} diff --git a/crates/compose/src/fill_place.rs b/crates/compose/src/fill_place.rs new file mode 100644 index 00000000..2bad25f0 --- /dev/null +++ b/crates/compose/src/fill_place.rs @@ -0,0 +1,12 @@ +use texturecraft_core::Fill; + +use crate::projector_depth::ProjectorDepth; + +/// A fill as a texel samples it: the fill, its projector's depth map when it culls by depth, and whether it covers every texel +#[derive(Clone, Copy)] +pub(crate) struct FillPlace<'f> { + pub fill: &'f Fill, + pub depth: Option<&'f ProjectorDepth>, + /// Decided once per tile, so a texel never works its coverage out + pub covers_all: bool, +} diff --git a/crates/compose/src/mip_level.rs b/crates/compose/src/mip_level.rs new file mode 100644 index 00000000..4af44d24 --- /dev/null +++ b/crates/compose/src/mip_level.rs @@ -0,0 +1,35 @@ +//! One halved copy of an image resource, read by high-quality bilinear filtering when an image is shrunk + +use crate::store::texel_of; + +/// One halved copy of an image (box-filtered; see `halve` for its edges) +#[derive(Clone, Debug, PartialEq)] +pub struct MipLevel { + pub width: u32, + pub height: u32, + pub rgba: Vec<[f32; 4]>, +} + +/// Share of each of the 2 × 2 texels in a halved texel +const TEXEL_SHARE: f32 = 0.25; + +impl MipLevel { + /// `rgba` halved: each texel averages the 2 × 2 texels it covers (a size of 1 wraps; an odd size above leaves out its last row or column) + pub(crate) fn halve(rgba: &[[f32; 4]], width: u32, height: u32) -> MipLevel { + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + let mut halved = Vec::with_capacity(w as usize * h as usize); + for y in 0..i64::from(h) { + for x in 0..i64::from(w) { + let mut sum = [0.0f32; 4]; + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let texel = texel_of(rgba, width, height, x * 2 + dx, y * 2 + dy, (true, true)); + for (total, value) in sum.iter_mut().zip(texel) { + *total += value * TEXEL_SHARE; + } + } + halved.push(sum); + } + } + MipLevel { width: w, height: h, rgba: halved } + } +} diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index 5634b3a1..f94b1d8b 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -1,7 +1,7 @@ //! Procedural patterns and projections. -use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection}; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_core::{Decal, FULL_TURN_DEGREES, Procedural, ProceduralKind, Projection, Projector, UvTransform}; +use texturecraft_geom::glam::{EulerRot, Mat3, Vec2, Vec3}; use texturecraft_texel::noise; use crate::pattern_context::PatternContext; @@ -381,7 +381,7 @@ const TRIPLANAR_SKIP: f32 = 1.0 / 131_072.0; /// to change a 0..1 value scaled by `gain` afterwards weigh 0 (see [`TRIPLANAR_SKIP`]). fn triplanar_weights(nrm: Vec3, sharpness: f32, gain: f32) -> Vec3 { let weights = sharpen(nrm.abs(), sharpness); - let weights = weights / (weights.x + weights.y + weights.z).max(1e-6); + let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM); let skip_threshold = TRIPLANAR_SKIP / gain.max(1.0); let retained = Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights); @@ -394,6 +394,132 @@ fn shape(pattern: &Procedural, value: f32) -> f32 { if pattern.invert { 1.0 - adjusted } else { adjusted } } +/// `point` turned by `rotation` degrees, scaled by `tiling` and moved by `offset`, as UV transformations place it +fn place(point: Vec2, tiling: Vec2, rotation: f32, offset: Vec2) -> Vec2 { + placement(tiling, rotation, offset)(point) +} + +/// [`place`] with its turn's sine and cosine worked out once, for a projection that places several points +fn placement(tiling: Vec2, rotation: f32, offset: Vec2) -> impl Fn(Vec2) -> Vec2 { + let (sin, cos) = rotation.to_radians().sin_cos(); + move |point| Vec2::new(point.x * cos - point.y * sin, point.x * sin + point.y * cos) * tiling + offset +} + +/// `point` placed as a 3D projection's UV transformation `uv` lays its image +fn place_uv(point: Vec2, uv: &UvTransform) -> Vec2 { + uv_placement(uv)(point) +} + +/// [`place_uv`] worked out once for every point a projection places +fn uv_placement(uv: &UvTransform) -> impl Fn(Vec2) -> Vec2 { + placement(Vec2::from(uv.tiling), uv.rotation, Vec2::from(uv.offset)) +} + +/// 0..1 around a cylindrical projection's axis (`depth` over `across`), over an arc of `angle` degrees centred on the front +fn around(across: f32, depth: f32, angle: f32) -> f32 { + let turn = depth.atan2(across) / std::f32::consts::TAU + 0.5; + + // A full turn reads the turn untouched, as projects saved before the angle existed did, bit for bit + if angle == FULL_TURN_DEGREES { turn } else { (turn - 0.5) * FULL_TURN_DEGREES / angle.max(MIN_CYLINDER_ANGLE) + 0.5 } +} + +/// Narrowest arc in degrees a cylindrical projection wraps its image round, so a zero angle never divides by zero +pub const MIN_CYLINDER_ANGLE: f32 = *Projection::CYLINDER_ANGLE_RANGE.start(); + +/// How many pattern tiles a procedural lays round and down a spherical projection, so its cells stay near square +const SPHERE_PATTERN_TILES: Vec2 = Vec2::new(4.0, 2.0); + +/// How many pattern tiles a procedural lays round a cylindrical projection's axis +const CYLINDER_PATTERN_TILES: f32 = 4.0; + +/// Smallest sum of tri-planar blend weights, so a zero normal never divides by zero +const MIN_WEIGHT_SUM: f32 = 1e-6; + +/// Smallest frame side or depth (world units), so a flat frame never divides by zero +const MIN_FRAME_EXTENT: f32 = 1e-6; + +/// Where `coords` lies round a spherical projection: 0..1 round its pole axis and down from its top +fn spherical_uv(projector: &Projector, offset: &[f32; 3], coords: &Coords) -> Vec2 { + let direction = (projector_local(projector, coords).pos + Vec3::from(*offset)).try_normalize().unwrap_or(Vec3::Y); + let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5; + let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; + Vec2::new(u, v) +} + +/// The axis index (0 X, 1 Y, 2 Z) a cylindrical projection's stored `axis` wraps round: any value but X or Z reads as Y +pub fn cylinder_axis_index(axis: u8) -> usize { + match axis { + 0 => 0, + 2 => 2, + _ => 1, + } +} + +/// Where `coords` lies for a cylindrical projection round `axis`: 0..1 round the axis over `angle` degrees, and its height along the axis +fn cylinder_coords(axis: u8, projector: &Projector, offset: &[f32; 3], angle: f32, coords: &Coords) -> (f32, f32) { + let point = projector_local(projector, coords).pos + Vec3::from(*offset); + let (across, height, depth) = match cylinder_axis_index(axis) { + 0 => (point.y, point.x, point.z), + 2 => (point.x, point.z, point.y), + _ => (point.x, point.y, point.z), + }; + (around(across, depth, angle), height) +} + +/// Smallest mesh radius projections measure in, so a flat or empty mesh never divides by zero +const MIN_MESH_RADIUS: f32 = 1e-4; + +/// Nearest to zero a projection scale or stretch gets, so it never divides by zero +const MIN_STRETCH: f32 = 1e-6; + +/// The mesh's centre and its radius (half the diagonal) from its bounds +pub fn mesh_frame((lo, hi): (Vec3, Vec3)) -> (Vec3, f32) { + ((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(MIN_MESH_RADIUS)) +} + +/// `value` kept at least [`MIN_STRETCH`] from zero, on its own side +pub fn nonzero_stretch(value: f32) -> f32 { + value.signum() * value.abs().max(MIN_STRETCH) +} + +/// A projector's per-axis scale with no axis at zero, each keeping its sign +pub fn projector_stretch(projector: &Projector) -> Vec3 { + Vec3::from(projector.scale).map(nonzero_stretch) +} + +/// The middle of a frame's 0..1 texture coordinates: a frame's image turns round it +pub const FRAME_UV_CENTER: Vec2 = Vec2::splat(0.5); + +/// `point` (0..1 across and down a frame) placed as `uv` lays a frame's image: turned round the frame's centre, then tiled and moved from its top left +pub fn place_frame_uv(point: Vec2, uv: &UvTransform) -> Vec2 { + // An unplaced image reads `point` itself, bit for bit as decals saved before image placement did + if *uv == UvTransform::default() { + return point; + } + + let tiling = Vec2::from(uv.tiling); + place(point - FRAME_UV_CENTER, tiling, uv.rotation, Vec2::from(uv.offset)) + FRAME_UV_CENTER * tiling +} + +/// The image placement a frame needs to lay images exactly as `uv` does from the top left (a frame turns its image round its centre) +pub fn frame_uv_from_corner(uv: &UvTransform) -> UvTransform { + let offset = place_uv(FRAME_UV_CENTER, uv) - FRAME_UV_CENTER * Vec2::from(uv.tiling); + UvTransform { offset: offset.to_array(), ..*uv } +} + +/// `coords` inside a projector turned and scaled by `projector`; the default projector returns `coords` unchanged +pub fn projector_local(projector: &Projector, coords: &Coords) -> Coords { + if !projector.turns() { + return *coords; + } + + let [x, y, z] = projector.rotation.map(f32::to_radians); + let to_local = Mat3::from_euler(EulerRot::ZYX, z, y, x).transpose(); + let scale = projector_stretch(projector); + let nrm = (to_local * coords.nrm * scale).try_normalize().unwrap_or(coords.nrm); + Coords { pos: to_local * coords.pos / scale, nrm, ..*coords } +} + /// Evaluate a procedural through a projection, at full resolution and without images pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 { procedural_in(pattern, projection, coords, &PatternContext::default()) @@ -402,51 +528,41 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords /// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 { let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE); - let sample = |point: Vec3| plane_value(pattern, point, context); - let value = match projection { - Projection::Uv { scale, rotation, offset } => { - let (sn, cs) = rotation.to_radians().sin_cos(); - let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); - // Evaluate two-dimensional patterns on a slice of the volume - sample((uv * pattern_scale).extend(0.0)) - } - Projection::Triplanar { scale, sharpness, offset } => { - let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); + // Evaluate two-dimensional patterns on a slice of the volume + let flat = |point: Vec2| plane_value(pattern, point.extend(0.0), context); + let value = match projection { + Projection::UvTile => flat((coords.uv - coords.uv.floor()) * pattern_scale), + Projection::Uv { scale, rotation, offset } => flat(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset)) * pattern_scale), + Projection::Triplanar { scale, sharpness, offset, uv, projector } => { + let coords = &projector_local(projector, coords); + let point = coords.pos * *scale * pattern_scale + Vec3::from(*offset); + let place_plane = uv_placement(uv); // Shape scales the blend by the contrast - let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); - let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))]; - planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum() + let weights = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); + let planes = [(weights.x, Vec2::new(point.z, point.y)), (weights.y, Vec2::new(point.x, point.z)), (weights.z, Vec2::new(point.x, point.y))]; + planes.into_iter().filter(|(weight, _)| *weight > 0.0).map(|(weight, plane)| flat(place_plane(plane)) * weight).sum() } - Projection::Planar { scale, axis, offset } => { - let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); - let q = match axis { - 0 => Vec3::new(p.z, p.y, 0.0), - 1 => Vec3::new(p.x, p.z, 0.0), - _ => Vec3::new(p.x, p.y, 0.0), + // The coordinates are already in the placed or warped frame (see [`placed_uv`] and [`crate::warp::warp_uv`]) + Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => flat(place_frame_uv(coords.uv, uv) * pattern_scale), + Projection::Planar { scale, axis, offset, uv, projector, .. } => { + let point = projector_local(projector, coords).pos * *scale * pattern_scale + Vec3::from(*offset); + let plane = match axis { + 0 => Vec2::new(point.z, point.y), + 1 => Vec2::new(point.x, point.z), + _ => Vec2::new(point.x, point.y), }; - sample(q) + flat(place_uv(plane, uv)) } - Projection::Spherical { scale } => { - let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); - let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; - let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale) + Projection::Spherical { scale, uv, offset, projector } => { + let sphere = spherical_uv(projector, offset, coords); + flat(place_uv(sphere * SPHERE_PATTERN_TILES * *scale * pattern_scale, uv)) } - Projection::Cylindrical { scale, axis } => { - let p = coords.pos; - let (a, h, b) = match axis { - 0 => (p.y, p.x, p.z), - 2 => (p.x, p.z, p.y), - _ => (p.x, p.y, p.z), - }; - let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale) + Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => { + let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords); + flat(place_uv(Vec2::new(around_axis * CYLINDER_PATTERN_TILES, height) * *scale * pattern_scale, uv)) } - - // The decal already supplied coordinates in its local frame - Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)), }; shape(pattern, value) @@ -476,7 +592,7 @@ fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f let base = grid.floor(); let fraction = grid - base; - let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context); + let at = |across: f32, down: f32| pattern_value(pattern, ((base + Vec2::new(across, down) + 0.5) / cells).extend(point.z), context); let top_left = at(0.0, 0.0); let bottom_left = at(0.0, 1.0); let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x; @@ -497,45 +613,37 @@ fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { let one = |uv: Vec2| [(uv, 1.0), (Vec2::ZERO, 0.0), (Vec2::ZERO, 0.0)]; match projection { - Projection::Uv { scale, rotation, offset } => { - let (sn, cs) = rotation.to_radians().sin_cos(); - let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); - one(uv) - } - Projection::Triplanar { scale, sharpness, offset } => { - let p = coords.pos * *scale + Vec3::from(*offset); + Projection::UvTile => one(coords.uv - coords.uv.floor()), + Projection::Uv { scale, rotation, offset } => one(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset))), + Projection::Triplanar { scale, sharpness, offset, uv, projector } => { + let coords = &projector_local(projector, coords); + let point = coords.pos * *scale + Vec3::from(*offset); + let place_plane = uv_placement(uv); // Float images can exceed 1, so even a tiny plane weight can carry visible detail let weights = coords.nrm.abs().powf(sharpness.max(1.0)); - let weights = weights / (weights.x + weights.y + weights.z).max(1e-6); - [(Vec2::new(p.z, -p.y), weights.x), (Vec2::new(p.x, p.z), weights.y), (Vec2::new(p.x, -p.y), weights.z)] + let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM); + [ + (place_plane(Vec2::new(point.z, -point.y)), weights.x), + (place_plane(Vec2::new(point.x, point.z)), weights.y), + (place_plane(Vec2::new(point.x, -point.y)), weights.z), + ] } - Projection::Planar { scale, axis, offset } => { - let p = coords.pos * *scale + Vec3::from(*offset); - let q = match axis { - 0 => Vec2::new(p.z, -p.y), - 1 => Vec2::new(p.x, p.z), - _ => Vec2::new(p.x, -p.y), + Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => one(place_frame_uv(coords.uv, uv)), + Projection::Planar { scale, axis, offset, uv, projector, .. } => { + let point = projector_local(projector, coords).pos * *scale + Vec3::from(*offset); + let plane = match axis { + 0 => Vec2::new(point.z, -point.y), + 1 => Vec2::new(point.x, point.z), + _ => Vec2::new(point.x, -point.y), }; - one(q * 0.5 + Vec2::splat(0.5)) + one(place_uv(plane * 0.5 + Vec2::splat(0.5), uv)) } - Projection::Spherical { scale } => { - let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); - let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; - let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - one(Vec2::new(u, v) * *scale) + Projection::Spherical { scale, uv, offset, projector } => one(place_uv(spherical_uv(projector, offset, coords) * *scale, uv)), + Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => { + let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords); + one(place_uv(Vec2::new(around_axis, 0.5 - height * 0.5) * *scale, uv)) } - Projection::Cylindrical { scale, axis } => { - let p = coords.pos; - let (a, h, b) = match axis { - 0 => (p.y, p.x, p.z), - 2 => (p.x, p.z, p.y), - _ => (p.x, p.y, p.z), - }; - let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - one(Vec2::new(u, 0.5 - h * 0.5) * *scale) - } - Projection::Decal(_) => one(coords.uv), } } @@ -561,50 +669,55 @@ pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> { Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh]) } -/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates -/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its -/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit. -pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { - let (o, r, u, n) = decal_axes(d)?; - let facing = nrm.dot(n); - let q = p - o; - let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs()); - let depth = d.depth.max(1e-6); - if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) { - return None; +/// World point `point` in frame `frame` turned and scaled by `projector`: across and up in frame sizes, out along its normal in world units +pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option { + let (origin, right, up, normal) = decal_axes(frame)?; + let from_origin = point - origin; + let mut local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal)); + if projector.turns() { + local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos; } - let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz)); - Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w)) + let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z); + local.is_finite().then_some(local) } -/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame. -fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 { - Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y }) -} - -/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the -/// point more. The copy is the decal reflected through the plane across `center` (the mesh -/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked. -pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { - let direct = decal_uv(d, p, nrm); - let Some(symmetry) = d.symmetry else { return direct }; - let axis = usize::from(symmetry.axis.min(2)); - let (mut mirrored_position, mut mirrored_normal) = (p, nrm); - mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; - mirrored_normal[axis] = -nrm[axis]; - let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| { - let uv = match symmetry.flip { - DecalFlip::None => uv, - DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), - DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), - }; - (uv, w) - }); - match (direct, mirrored) { - (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), - (a, b) => a.or(b), +/// How squarely a surface with normal `nrm` faces frame `frame` turned by `projector` (the cosine of the turn) +pub fn frame_facing(frame: &Decal, projector: &Projector, nrm: Vec3) -> f32 { + let Some((_, right, up, normal)) = decal_axes(frame) else { return 0.0 }; + if !projector.turns() { + return nrm.dot(normal); } + + let turned = Vec3::new(nrm.dot(right), nrm.dot(up), nrm.dot(normal)); + projector_local(projector, &Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: turned }).nrm.z +} + +/// Texture coordinates (v down) of a point at `local` in its frame (see [`frame_local`]) +pub fn placed_uv(local: Vec3) -> Vec2 { + Vec2::new(local.x + 0.5, 0.5 - local.y) +} + +/// How much frame `frame` covers a point at `local` when cropped to its shape: 0 outside the frame or past its depth, fading near the depth +pub fn frame_crop(frame: &Decal, local: Vec3) -> f32 { + if local.x.abs() > 0.5 || local.y.abs() > 0.5 { + return 0.0; + } + + depth_fade(local.z, frame.depth) +} + +/// Where a frame's depth fade starts, as a share of its depth +pub const DEPTH_FADE_START: f32 = 0.75; + +/// How much a frame reaching `depth` in front of and behind it covers a point `z` out from it: 0 past the depth, fading near it +pub fn depth_fade(z: f32, depth: f32) -> f32 { + let (distance, depth) = (z.abs(), depth.max(MIN_FRAME_EXTENT)); + if distance > depth { + return 0.0; + } + + 1.0 - smoothstep(DEPTH_FADE_START * depth, depth, distance) } /// World-space noise used by generators (seamless across UV islands). @@ -642,15 +755,98 @@ mod tests { assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); } + /// A stored cylinder axis past Z (only a hand-edited project holds one) wraps round Y + #[test] + fn a_cylinder_axis_past_z_reads_as_y() { + assert_eq!([0, 1, 2, 3, u8::MAX].map(cylinder_axis_index), [0, 1, 2, 1, 1]); + } + + /// A decal saved before image placement reads its frame coordinates bit for bit as it did: its image at them, its procedural at them times the pattern scale + #[test] + fn an_unplaced_decal_reads_its_frame_coordinates_bit_for_bit() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0; 2], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let decal = Projection::decal(frame); + let pattern = Procedural { scale: 3.0, ..Procedural::new(ProceduralKind::Gradient) }; + for across in 0..=1000 { + for down in [0.0, 0.1, 0.37, 1.0] { + let uv = Vec2::new(across as f32 / 1000.0, down); + let coords = Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z }; + assert_eq!(image_samples(&decal, &coords)[0].0, uv, "image at {uv}"); + + let expected = shape(&pattern, raw(pattern.kind, (uv * pattern.scale).extend(0.0), pattern.seed)); + assert_eq!(procedural(&pattern, &decal, &coords).to_bits(), expected.to_bits(), "procedural at {uv}"); + } + } + } + + /// A frame's image turns round the frame's centre: the centre reads the same texel at any Rotation, and an unturned image reads exactly as before for any Tiling and Offset + #[test] + fn a_frame_image_turns_round_the_frame_centre() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0; 2], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let at = |uv: Vec2| Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z }; + let sample = |rotation: f32, tiling: [f32; 2], offset: [f32; 2], uv: Vec2| { + image_samples( + &Projection::Warp { + frame, + corners: Projection::FRAME_CORNERS, + depth: 0.1, + uv: UvTransform { tiling, rotation, offset }, + projector: Projector::default(), + }, + &at(uv), + )[0] + .0 + }; + for rotation in [37.0, 90.0, 180.0] { + let center = sample(rotation, [1.0; 2], [0.0; 2], FRAME_UV_CENTER); + assert!((center - FRAME_UV_CENTER).length() < 1e-5, "{rotation}°: the centre stays put, not swung round the top left: {center}"); + } + let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO); + assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}"); + let placed = Projection::Planar { + scale: 1.0, + axis: 2, + offset: [0.0; 3], + uv: UvTransform { rotation: 90.0, ..UvTransform::default() }, + projector: Projector::default(), + placed: Some(frame), + }; + assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way"); + for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] { + let before = uv * Vec2::from(tiling) + Vec2::from(offset); + assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before"); + } + } + #[test] fn every_pattern_and_projection_stays_in_range() { let projections = [ Projection::default(), - Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] }, - Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] }, - Projection::Spherical { scale: 1.0 }, - Projection::Cylindrical { scale: 1.0, axis: 1 }, - Projection::Decal(Decal { + Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() }, + Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: Default::default(), projector: Default::default(), placed: None }, + Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() }, + Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES }, + Projection::decal(Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], @@ -662,20 +858,17 @@ mod tests { flip: [false; 2], }), ]; - for kind in ProceduralKind::ALL { let pattern = Procedural::new(kind); for projection in &projections { - for i in 0..50 { - let t = i as f32 * 0.13; + for index in 0..50 { + let position = index as f32 * 0.13; let coords = Coords { - uv: Vec2::new(t.fract(), (t * 0.7).fract()), - pos: Vec3::new(t.sin(), t.cos(), t * 0.1), + uv: Vec2::new(position.fract(), (position * 0.7).fract()), + pos: Vec3::new(position.sin(), position.cos(), position * 0.1), nrm: Vec3::new(0.3, 0.9, 0.1).normalize(), }; - let value = procedural(&pattern, projection, &coords); - assert!((0.0..=1.0).contains(&value), "{kind:?} {projection:?} {value}"); } } @@ -702,7 +895,8 @@ mod tests { for contrast in [1.0, 4.0, 16.0] { let pattern = Procedural { contrast, ..Procedural::new(kind) }; for sharpness in [1.0, 4.0, 8.0, 16.0] { - let projection = Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] }; + let projection = + Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() }; for index in 0..400 { // Cover axis aligned and oblique normals at varied positions let position = index as f32 / 400.0; @@ -731,9 +925,9 @@ mod tests { #[test] fn triplanar_image_sampling_preserves_bright_float_pixels() { - let image = crate::ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], srgb: false }; + let image = crate::ImageRes::new(2, 2, vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], false); let coords = Coords { uv: Vec2::ZERO, pos: Vec3::new(0.25, 0.25, 0.75), nrm: Vec3::new(0.2, 1.0, 0.1).normalize() }; - let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }; + let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() }; let weights = coords.nrm.abs().powf(8.0); let expected = 100_000.0 * weights.x / (weights.x + weights.y + weights.z); @@ -761,6 +955,12 @@ mod tests { } } + /// Where frame `frame`'s planar projection lands at `point` facing `nrm`, None where it does not cover + fn decal_uv(frame: &Decal, point: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { + let Projection::Planar { projector, .. } = Projection::decal(*frame) else { return None }; + crate::projector_cover::placed_cover(frame, &projector, point, nrm).filter(|(_, cover)| *cover > 0.0) + } + #[test] fn decals_cover_their_frame_facing_them() { let d = Decal { diff --git a/crates/compose/src/tile_length.rs b/crates/compose/src/tile_length.rs new file mode 100644 index 00000000..c08e668f --- /dev/null +++ b/crates/compose/src/tile_length.rs @@ -0,0 +1,155 @@ +//! How long one repeat of a fill's tile is on the mesh (mesh units): Physical size reads it from the tiling and writes tiling back + +use std::f32::consts::TAU; + +use texturecraft_core::{FULL_TURN_DEGREES, Projection}; + +use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch}; + +/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshSize { + pub radius: f32, + pub uv_density: f32, +} + +/// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round) +fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { + let radius = size.radius; + match projection { + Projection::Uv { .. } => Some([size.uv_density; 2]), + Projection::Triplanar { scale, projector, .. } => { + // Every plane repeats in the one length only while the stretch is even + let stretch = projector_stretch(projector).abs(); + let even = stretch.x == stretch.y && stretch.y == stretch.z; + even.then_some([radius * stretch.x / scale; 2]) + } + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + Some([frame.size[0] * stretch.x, frame.size[1] * stretch.y]) + } + Projection::Planar { scale, axis, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + let [across, down] = match axis { + 0 => [stretch.z, stretch.y], + 1 => [stretch.x, stretch.z], + _ => [stretch.x, stretch.y], + }; + Some([2.0 * radius * across / scale, 2.0 * radius * down / scale]) + } + Projection::Cylindrical { scale, axis, angle, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + let ([across, depth], height) = match cylinder_axis_index(*axis) { + 0 => ([stretch.y, stretch.z], stretch.x), + 2 => ([stretch.x, stretch.y], stretch.z), + _ => ([stretch.x, stretch.z], stretch.y), + }; + + // Round an uneven cross-section the turn is no fixed length of surface + if across != depth { + return None; + } + + let around = TAU * radius * across * (angle.max(MIN_CYLINDER_ANGLE) / FULL_TURN_DEGREES); + Some([around / scale, 2.0 * radius * height / scale]) + } + Projection::UvTile | Projection::Spherical { .. } => None, + } +} + +/// The tiling a physical size reads and writes: UV's own tiling, a 3D projection's UV tiling +fn tiling(projection: &Projection) -> Option<[f32; 2]> { + match projection { + Projection::Uv { scale, .. } => Some(*scale), + Projection::Triplanar { uv, .. } | Projection::Planar { uv, .. } | Projection::Cylindrical { uv, .. } | Projection::Warp { uv, .. } => Some(uv.tiling), + Projection::UvTile | Projection::Spherical { .. } => None, + } +} + +/// Mesh units one repeat of the tile covers across and down +pub fn tile_length(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { + let unit = unit_tile(projection, size)?; + let tiling = tiling(projection)?; + Some([unit[0] / tiling[0].max(f32::EPSILON), unit[1] / tiling[1].max(f32::EPSILON)]) +} + +/// The tiling that makes one repeat `length` mesh units long across and down +pub fn tiling_for_length(projection: &Projection, size: MeshSize, length: [f32; 2]) -> Option<[f32; 2]> { + let unit = unit_tile(projection, size)?; + Some([unit[0] / length[0].max(f32::EPSILON), unit[1] / length[1].max(f32::EPSILON)]) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pattern::{Coords, image_samples}; + use texturecraft_core::{Projector, UvTransform}; + use texturecraft_geom::glam::{Vec2, Vec3}; + + const SIZE: MeshSize = MeshSize { radius: 2.0, uv_density: 3.0 }; + + #[test] + fn uv_tile_length_is_the_uv_density_over_the_tiling() { + let uv = Projection::Uv { scale: [2.0, 4.0], rotation: 0.0, offset: [0.0; 2] }; + assert_eq!(tile_length(&uv, SIZE), Some([1.5, 0.75])); + } + + #[test] + fn a_length_read_back_gives_the_same_tiling() { + let uv = UvTransform { tiling: [3.0, 1.5], ..UvTransform::default() }; + for projection in [ + Projection::Uv { scale: [3.0, 1.5], rotation: 0.0, offset: [0.0; 2] }, + Projection::Triplanar { scale: 1.5, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector: Default::default() }, + Projection::Planar { scale: 0.5, axis: 2, offset: [0.0; 3], uv, projector: Default::default(), placed: None }, + Projection::Cylindrical { scale: 2.0, axis: 1, uv, offset: [0.0; 3], projector: Default::default(), angle: 360.0 }, + ] { + let length = tile_length(&projection, SIZE).unwrap(); + let tiling = tiling_for_length(&projection, SIZE, length).unwrap(); + assert!((tiling[0] - 3.0).abs() < 1e-5 && (tiling[1] - 1.5).abs() < 1e-5, "{projection:?}: {tiling:?}"); + } + } + + #[test] + fn a_written_length_is_the_repeat_on_the_mesh_through_a_stretched_projector() { + let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() }; + let axis_planar = |uv| Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv, projector, placed: None }; + let length = 2.0; + + let tiling = tiling_for_length(&axis_planar(UvTransform::default()), SIZE, [length; 2]).unwrap(); + let planar = axis_planar(UvTransform { tiling, ..UvTransform::default() }); + let at = |x: f32, y: f32| image_samples(&planar, &Coords { uv: Vec2::ZERO, pos: Vec3::new(x, y, 0.0) / SIZE.radius, nrm: Vec3::Z })[0].0; + let across = at(0.3 + length, 0.1) - at(0.3, 0.1); + let down = at(0.3, 0.1 + length) - at(0.3, 0.1); + + assert_eq!(tile_length(&axis_planar(UvTransform::default()), SIZE), Some([8.0, 4.0]), "the stretch doubles the repeat across"); + assert!((across.x.abs() - 1.0).abs() < 1e-4 && across.y.abs() < 1e-4, "one length across is one tile: {across}"); + assert!(down.x.abs() < 1e-4 && (down.y.abs() - 1.0).abs() < 1e-4, "one length down is one tile: {down}"); + } + + #[test] + fn a_stretch_uneven_round_the_planes_has_no_physical_size() { + let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() }; + let uv = UvTransform::default(); + + let triplanar = Projection::Triplanar { scale: 1.0, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector }; + let cylinder = Projection::Cylindrical { scale: 1.0, axis: 1, uv, offset: [0.0; 3], projector, angle: 360.0 }; + let along_axis = Projection::Cylindrical { scale: 1.0, axis: 0, uv, offset: [0.0; 3], projector, angle: 360.0 }; + + assert_eq!(tile_length(&triplanar, SIZE), None); + assert_eq!(tile_length(&cylinder, SIZE), None); + assert_eq!(tile_length(&along_axis, SIZE).map(|[_, down]| down), Some(8.0), "a stretch along the axis lengthens the repeat down it"); + } + + #[test] + fn a_cylinder_of_no_angle_still_has_a_length() { + let flat = Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default(), angle: 0.0 }; + let length = tile_length(&flat, SIZE).unwrap(); + assert!(length[0] > 0.0, "{length:?}"); + assert!(tiling_for_length(&flat, SIZE, length).unwrap()[0] > 0.0, "a written-back tiling is never 0"); + } + + #[test] + fn spherical_has_no_physical_size() { + assert_eq!(tile_length(&Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default() }, SIZE), None); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ebd2ae0d..b9677515 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -108,6 +108,10 @@ impl HeightMask { } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[expect( + clippy::large_enum_variant, + reason = "a fill holds its projection inline; boxing it would cost every fill read an indirection to save a few hundred bytes per paint layer or folder" +)] pub enum LayerKind { /// Painted pixels, stored per channel by the engine under the layer id. Paint, @@ -178,20 +182,90 @@ impl Layer { pub enum Projection { /// Texture coordinates of the mesh. Uv { scale: [f32; 2], rotation: f32, offset: [f32; 2] }, + /// The source stretched once over each UV tile (0..1 in every tile) + UvTile, /// World-space box projection blended by the normal. - Triplanar { scale: f32, sharpness: f32, offset: [f32; 3] }, - /// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z). - Planar { scale: f32, axis: u8, offset: [f32; 3] }, - /// Spherical projection around the mesh center. - Spherical { scale: f32 }, - /// Cylindrical projection around an axis. - Cylindrical { scale: f32, axis: u8 }, - /// A geometry decal: the image projected from a frame placed on the surface (outside the - /// frame, behind it or beyond its depth the fill does not cover). - Decal(Decal), + Triplanar { + scale: f32, + sharpness: f32, + offset: [f32; 3], + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + }, + /// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z), or from a frame placed on the surface + Planar { + scale: f32, + axis: u8, + offset: [f32; 3], + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + /// The frame it projects from when placed on the surface (scale, axis and offset then unused) + #[serde(default, skip_serializing_if = "Option::is_none")] + placed: Option, + }, + /// Spherical projection around the mesh center + Spherical { + scale: f32, + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "is_zero_offset")] + offset: [f32; 3], + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + }, + /// Cylindrical projection around an axis + Cylindrical { + scale: f32, + axis: u8, + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "is_zero_offset")] + offset: [f32; 3], + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + /// The arc one repeat of the source spans around the axis (degrees), centred on the front + #[serde(default = "full_turn", skip_serializing_if = "is_full_turn")] + angle: f32, + }, + /// A planar projection from a frame whose four corners are pulled freely, bending the image to the quad they make + Warp { + /// The frame it projects from (its depth is unused: `depth` sets the reach) + frame: Decal, + /// Where the frame's corners sit (top left, top right, bottom right, bottom left), across and up in frame sizes from its centre + corners: [[f32; 2]; 4], + /// Projection Depth: how far in front of and behind the frame it reaches when cropped to its shape, in lengths of the frame's longer side + depth: f32, + uv: UvTransform, + projector: Projector, + }, } -/// The frame a decal projects from (world space). +/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct UvTransform { + pub tiling: [f32; 2], + pub rotation: f32, + pub offset: [f32; 2], +} + +impl Default for UvTransform { + fn default() -> Self { + UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } + } +} + +impl UvTransform { + /// Whether it changes nothing, as projections saved before it existed did (not saved then) + pub fn is_default(&self) -> bool { + *self == UvTransform::default() + } +} + +/// The frame a planar projection placed on the surface (a decal) projects from, in world space #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Decal { /// The surface point the decal was placed on. @@ -222,6 +296,21 @@ fn not_flipped(flip: &[bool; 2]) -> bool { !flip[0] && !flip[1] } +/// Serde default of a cylindrical projection's angle: the whole way round +fn full_turn() -> f32 { + crate::FULL_TURN_DEGREES +} + +/// Whether a cylindrical projection spans the whole way round, as ones saved before the angle did (not saved then) +fn is_full_turn(angle: &f32) -> bool { + *angle == full_turn() +} + +/// Whether a spherical or cylindrical projection sits unshifted, as ones saved before the offset did (not saved then) +fn is_zero_offset(offset: &[f32; 3]) -> bool { + *offset == [0.0; 3] +} + impl Default for Projection { fn default() -> Self { Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } @@ -229,14 +318,88 @@ impl Default for Projection { } impl Projection { + /// A warp's corners before any is pulled: the frame's own + pub const FRAME_CORNERS: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]; + + /// A new warp's Projection Depth + pub const WARP_DEPTH: f32 = 0.1; + + /// A new tri-planar projection's blend sharpness + pub const TRIPLANAR_SHARPNESS: f32 = 8.0; + + /// The blend sharpness a tri-planar projection takes: an exponent from soft (1) to near hard (64) + pub const TRIPLANAR_SHARPNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; + + /// The arc in degrees a cylindrical projection wraps its image round; a zero arc would divide by zero + pub const CYLINDER_ANGLE_RANGE: std::ops::RangeInclusive = 1.0..=crate::FULL_TURN_DEGREES; + + /// A tri-planar projection with a new fill's settings + pub fn triplanar() -> Projection { + Projection::Triplanar { + scale: 1.0, + sharpness: Self::TRIPLANAR_SHARPNESS, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector::default(), + } + } + + /// A warp projection from `frame` with its corners where the frame's are + pub fn warp(frame: Decal) -> Projection { + Projection::Warp { + frame, + corners: Projection::FRAME_CORNERS, + depth: Projection::WARP_DEPTH, + uv: UvTransform::default(), + projector: Projector::depth_culled(), + } + } + + /// A planar projection from `frame` with a decal's look: cropped to its frame, depth and image alpha, off faces turned away + pub fn decal(frame: Decal) -> Projection { + let projector = Projector { crop: ShapeCrop::Cropped, backface: Backface { on: true, ..Backface::default() }, ..Projector::default() }; + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame) } + } + + /// The depth culling of a planar or warp projection that has it on + pub fn depth_culling(&self) -> Option { + match self { + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => Some(projector.depth).filter(|depth| depth.on), + _ => None, + } + } + + /// Whether the projection works in 3D, so a fill's symmetry can copy it (UV projections cannot) + pub fn takes_symmetry(&self) -> bool { + !matches!(self, Projection::Uv { .. } | Projection::UvTile) + } + + /// The frame on the surface a placed planar projection projects from + pub fn placed(&self) -> Option<&Decal> { + match self { + Projection::Planar { placed, .. } => placed.as_ref(), + _ => None, + } + } + + /// The frame on the surface a placed planar or a warp projection projects from + pub fn frame(&self) -> Option<&Decal> { + match self { + Projection::Planar { placed, .. } => placed.as_ref(), + Projection::Warp { frame, .. } => Some(frame), + _ => None, + } + } + pub fn label(&self) -> &'static str { match self { + Projection::UvTile => "Fill (Match per UV Tile)", Projection::Uv { .. } => "UV projection", Projection::Triplanar { .. } => "Tri-planar projection", Projection::Planar { .. } => "Planar projection", Projection::Spherical { .. } => "Spherical projection", Projection::Cylindrical { .. } => "Cylindrical projection", - Projection::Decal(_) => "Decal projection", + Projection::Warp { .. } => "Warp projection", } } } @@ -550,7 +713,10 @@ impl Source { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct Fill { pub sources: BTreeMap, + #[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")] pub projection: Projection, + #[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")] + pub sampling: Sampling, /// Set when the sources are maps cooked from a MaterialCraft material. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option>, @@ -1179,7 +1345,10 @@ pub enum EffectKind { /// A uniform or procedural grayscale fill. Fill { source: Source, + #[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")] projection: Projection, + #[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")] + sampling: Sampling, }, Generator(Generator), Levels(Levels), @@ -1198,10 +1367,7 @@ pub enum EffectKind { /// Content only: a material fill (one source per channel; channels without a source are /// left as they are). Material(Fill), - /// Records the stack at its place so masks, fills and generators above can read it - /// ([`Source::Anchor`]). In a content stack it records the composited stack right after its - /// layer (that layer and everything below); in a mask, the mask value at that point (every - /// channel reads that gray). + /// Records the stack at its place so masks, fills and generators above can read it ([`Source::Anchor`]): in a content stack the composited stack right after its layer (that layer and everything below), in a mask the mask value there (every channel reads that gray) Anchor, } @@ -1547,21 +1713,27 @@ mod tests { assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false)); assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); + let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); assert!(!fill_layer.reads_anchor()); + let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }; fill_layer.mask = Some(Mask { - effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], + effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })], ..Mask::new(MaskBackground::Black) }); + assert!(fill_layer.reads_anchor()); // A generator with micro detail reads its anchor too let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); + assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); + generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); + assert!(generator_layer.reads_anchor()); } @@ -1605,6 +1777,31 @@ mod tests { } } + #[test] + fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { + let fills = [ + r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#, + r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#, + r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":1.0}}}"#, + ]; + for saved in fills { + let loaded: Fill = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); + } + + let effects = [ + r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, + r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, + ]; + for saved in effects { + let loaded: EffectKind = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); + } + } + #[test] fn procedural_kinds_parse_labels_and_saved_names() { for kind in ProceduralKind::ALL { diff --git a/crates/engine/tests/it/fill_patterns.rs b/crates/engine/tests/it/fill_patterns.rs new file mode 100644 index 00000000..c5d854ba --- /dev/null +++ b/crates/engine/tests/it/fill_patterns.rs @@ -0,0 +1,69 @@ +//! A fill's procedural pattern through `layer.fill.set`: a parameter given alone changes only itself + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId, LayerKind, Procedural, ProceduralKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A fill layer whose roughness is a Clouds pattern with every parameter away from its default +fn clouds_fill() -> (Session, LayerId) { + let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + let pattern = json!({ + "layer": layer.0, "channel": "roughness", "procedural": "Clouds", "scale": 9.0, "contrast": 1.5, "seed": 7, + "balance": 0.25, "invert": true, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8], + }); + execute(&mut session, "layer.fill.set", &pattern).unwrap(); + (session, layer) +} + +/// The roughness pattern and its Low and High colours +type Roughness = (Procedural, [f32; 3], [f32; 3]); + +fn roughness(session: &Session, layer: LayerId) -> Roughness { + match &session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => match fill.source(Channel::Roughness) { + Source::Procedural { pattern, low, high, .. } => (pattern, low, high), + other => panic!("not a procedural: {other:?}"), + }, + other => panic!("not a fill: {other:?}"), + } +} + +/// One parameter sent alone, its value, and what it changes in the stored pattern +type PatternEdit = (&'static str, Value, fn(&mut Roughness)); + +/// What the Scale, Contrast, Seed, Balance and Invert controls and the Low/High swatches send: one parameter each +#[test] +fn a_pattern_parameter_given_alone_keeps_every_other_one() { + let (mut session, layer) = clouds_fill(); + let edits: [PatternEdit; 7] = [ + ("scale", json!(3.0), |(pattern, ..)| pattern.scale = 3.0), + ("contrast", json!(0.5), |(pattern, ..)| pattern.contrast = 0.5), + ("seed", json!(42), |(pattern, ..)| pattern.seed = 42), + ("balance", json!(-0.5), |(pattern, ..)| pattern.balance = -0.5), + ("invert", json!(false), |(pattern, ..)| pattern.invert = false), + ("low", json!([0.1, 0.1, 0.1]), |(_, low, _)| *low = [0.1; 3]), + ("high", json!([0.9, 0.9, 0.9]), |(.., high)| *high = [0.9; 3]), + ]; + for (key, value, change) in edits { + let mut expected = roughness(&session, layer); + change(&mut expected); + let mut edit = json!({"layer": layer.0, "channel": "roughness", "procedural": "Clouds"}); + edit[key] = value; + execute(&mut session, "layer.fill.set", &edit).unwrap(); + + assert_eq!(roughness(&session, layer), expected, "`{key}` alone changes only itself"); + } + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"balance\":-0.5") && inspected.contains("\"invert\":false"), "inspect shows the balance and invert"); +} + +/// Another kind is a new pattern: its defaults between black and white, as before +#[test] +fn another_pattern_kind_starts_from_its_defaults() { + let (mut session, layer) = clouds_fill(); + execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "procedural": "Cells"})).unwrap(); + assert_eq!(roughness(&session, layer), (Procedural::new(ProceduralKind::Cells), [0.0; 3], [1.0; 3])); +} diff --git a/crates/engine/tests/it/fill_sampling.rs b/crates/engine/tests/it/fill_sampling.rs new file mode 100644 index 00000000..fd17f481 --- /dev/null +++ b/crates/engine/tests/it/fill_sampling.rs @@ -0,0 +1,218 @@ +//! How fills read their image sources (filtering), through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, Fill, Filtering, LayerId, LayerKind, Projection, Sampling, ScaleMode}; +use texturecraft_engine::geom::NO_TRI; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.update(); + s +} + +fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// A fill layer whose base color is a one-texel black and white checker, tiled `tiling` times +fn checker_fill(s: &mut Session, tiling: f32) -> LayerId { + let name = s.import_resource_bytes("checker.png", png(64, 64, |x, y| if (x + y) % 2 == 0 { [255; 4] } else { [0, 0, 0, 255] })).unwrap(); + let layer = LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": name})).unwrap(); + execute(s, "layer.fill.projection", &json!({"layer": layer.0, "scale": tiling})).unwrap(); + layer +} + +/// Lowest and highest base color red across the covered texels of the set's middle band +fn spread(s: &mut Session) -> (f32, f32) { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let mut range = (f32::MAX, f32::MIN); + for y in h * 3 / 8..h * 5 / 8 { + for x in w / 4..w * 3 / 4 { + if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI { + let red = cache.composite.value(Channel::BaseColor, x, y)[0]; + range = (range.0.min(red), range.1.max(red)); + } + } + } + range +} + +fn filtering(s: &mut Session, layer: LayerId, id: &str) { + execute(s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": id})).unwrap(); +} + +/// A checker shrunk to two image texels per texel: HQ averages it, Sharp aliases it, Nearest keeps black and white +#[test] +fn filtering_decides_how_a_shrunk_image_reads() { + let mut s = session(); + let layer = checker_fill(&mut s, 7.3); + let (lo, hi) = spread(&mut s); + assert!(hi - lo < 0.2, "a new fill reads with Bilinear | HQ: an even gray, got {lo}..{hi}"); + + filtering(&mut s, layer, "bilinearSharp"); + let (lo, hi) = spread(&mut s); + assert!(hi - lo > 0.5, "Bilinear | Sharp aliases a shrunk checker: {lo}..{hi}"); + + filtering(&mut s, layer, "nearest"); + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let pure = (h * 3 / 8..h * 5 / 8) + .flat_map(|y| (w / 4..w * 3 / 4).map(move |x| (x, y))) + .filter(|&(x, y)| cache.gbuf.tri[(y * w + x) as usize] != NO_TRI) + .all(|(x, y)| { + let red = cache.composite.value(Channel::BaseColor, x, y)[0]; + !(0.01..=0.99).contains(&red) + }); + assert!(pure, "Nearest reads one image texel: black or white only"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["filtering"], json!("nearest")); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": "trilinear"})).is_err()); +} + +/// Fills saved before Filtering existed read images as before (plain bilinear); new fills start on Bilinear | HQ +#[test] +fn fills_saved_before_filtering_keep_their_look() { + let mut s = session(); + let layer = checker_fill(&mut s, 1.0); + let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; + assert_eq!(fill.sampling.filtering, Filtering::BilinearHq); + + let mut saved = serde_json::to_value(fill).unwrap(); + saved.as_object_mut().unwrap().remove("sampling"); + let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling, Sampling::SAVED_BEFORE); + assert_eq!(loaded.sampling.filtering, Filtering::BilinearSharp); +} + +/// Share of the middle band's covered texels where the white fill shows over the black layer below +fn shown(s: &mut Session) -> f32 { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let (mut on, mut all) = (0usize, 0usize); + for y in h * 3 / 8..h * 5 / 8 { + for x in 0..w { + if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI { + all += 1; + on += usize::from(cache.composite.value(Channel::BaseColor, x, y)[0] > 0.5); + } + } + } + on as f32 / all.max(1) as f32 +} + +/// UV Wrap on a white fill tiled 4 × 2: Repeat covers the band, None one tile, one-axis repeats in between +#[test] +fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 0.0]})).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap()); + let set = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p) + }; + set(&mut s, json!({"scale": [4, 2]})).unwrap(); + let near = |got: f32, want: f32| (got - want).abs() < 0.05; + let repeat = shown(&mut s); + assert!(near(repeat, 1.0), "Repeat covers the band: {repeat}"); + set(&mut s, json!({"wrap": "none"})).unwrap(); + let none = shown(&mut s); + assert!(near(none, 0.125), "None: a quarter across, half down: {none}"); + set(&mut s, json!({"wrap": "repeatHorizontally"})).unwrap(); + let across = shown(&mut s); + assert!(near(across, 0.5), "repeating across: the whole width, half down: {across}"); + set(&mut s, json!({"wrap": "repeatVertically"})).unwrap(); + let down = shown(&mut s); + assert!(near(down, 0.25), "repeating down: a quarter across, the whole height: {down}"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["wrap"], json!("repeatVertically")); + assert!(set(&mut s, json!({"wrap": "mirror"})).is_err()); + + // Tri-planar has no tile: it covers whatever the wrap says + set(&mut s, json!({"projection": "triplanar", "wrap": "none"})).unwrap(); + let triplanar = shown(&mut s); + assert!(near(triplanar, 1.0), "{triplanar}"); +} + +/// 3D projections take UV transformations; older saves look as they did; world scale and offset stay separate +#[test] +fn three_d_projections_take_uv_transformations() { + use texturecraft_engine::core::{Projection, UvTransform}; + let mut s = session(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + let set = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p) + }; + execute( + &mut s, + "layer.fill.set", + &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0, 0, 0], "high": [1, 1, 1]}), + ) + .unwrap(); + set(&mut s, json!({"projection": "triplanar"})).unwrap(); + let projection = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(f) => f.projection.clone(), + _ => panic!("a fill layer"), + }; + let snapshot = |s: &mut Session| { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..w * h).map(|i| cache.composite.value(Channel::BaseColor, i % w, i / w)[0]).collect::>() + }; + let plain = snapshot(&mut s); + + set(&mut s, json!({"tiling": [2, 3], "rotation": 45, "uvOffset": [0.25, 0.5]})).unwrap(); + let Projection::Triplanar { uv, scale, .. } = projection(&s) else { panic!("tri-planar") }; + assert_eq!(uv, UvTransform { tiling: [2.0, 3.0], rotation: 45.0, offset: [0.25, 0.5] }); + assert_eq!(scale, 1.0, "the world scale is its own param"); + assert_ne!(snapshot(&mut s), plain, "the UV transformations move the pattern"); + + // A fill saved before 3D projections had UV transformations loads them as nothing + let mut saved = serde_json::to_value(projection(&s)).unwrap(); + saved["Triplanar"].as_object_mut().unwrap().remove("uv"); + let loaded: Projection = serde_json::from_value(saved).unwrap(); + assert!(matches!(loaded, Projection::Triplanar { uv, .. } if uv == UvTransform::default())); + set(&mut s, json!({"tiling": 1, "rotation": 0, "uvOffset": [0, 0]})).unwrap(); + assert_eq!(snapshot(&mut s), plain, "the identity transform changes nothing"); + + // On a UV projection, tiling is its scale + set(&mut s, json!({"projection": "uv", "tiling": [2, 4]})).unwrap(); + assert!(matches!(projection(&s), Projection::Uv { scale, .. } if scale == [2.0, 4.0])); +} + +/// Physical size keeps the fill's tiling; inspect reports the mode and older fills open on Tiling +#[test] +fn scale_mode_is_stored_without_changing_the_tiling() { + let mut s = session(); + let layer = checker_fill(&mut s, 2.0); + execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "physicalSize"})).unwrap(); + let LayerKind::Fill(fill) = s.doc.project.layer(layer).unwrap().kind.clone() else { panic!("a fill layer") }; + assert_eq!(fill.sampling.scale, ScaleMode::PhysicalSize); + assert!(matches!(fill.projection, Projection::Uv { scale: [2.0, 2.0], .. }), "{:?}", fill.projection); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["scaleMode"], json!("physicalSize")); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "inches"})).is_err()); + + let mut saved = serde_json::to_value(&fill).unwrap(); + saved["sampling"].as_object_mut().unwrap().remove("scale"); + let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling.scale, ScaleMode::Tiling); +} From 9958edaece10fca80473ea7259dda075418c5717 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 009/153] Fills: Shape crop, Backface culling and Depth culling on 3D projections --- crates/compose/src/projector_cover.rs | 281 +++++++++++++++++++++++++ crates/compose/src/projector_depth.rs | 287 ++++++++++++++++++++++++++ crates/compose/src/projector_view.rs | 62 ++++++ 3 files changed, 630 insertions(+) create mode 100644 crates/compose/src/projector_cover.rs create mode 100644 crates/compose/src/projector_depth.rs create mode 100644 crates/compose/src/projector_view.rs diff --git a/crates/compose/src/projector_cover.rs b/crates/compose/src/projector_cover.rs new file mode 100644 index 00000000..e19a6c73 --- /dev/null +++ b/crates/compose/src/projector_cover.rs @@ -0,0 +1,281 @@ +//! How much of a texel a 3D projection reaches: its shape crop and its backface culling + +use texturecraft_core::{Backface, Decal, DecalFlip, Projection, Projector, ShapeCrop}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::frame_placement::warp_reach; +use crate::organic::smoothstep; +use crate::pattern::{Coords, depth_fade, frame_crop, frame_facing, frame_local, placed_uv, projector_local}; +use crate::warp::warp_uv; + +/// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out +const MIN_AXIS_DISTANCE: f32 = 1e-6; + +/// The turn (in cosine) over which backface culling fades at hardness 0 +const BACKFACE_FADE: f32 = 0.6; + +/// The shape crop and backface culling [`projector_cover`] applies, None where it lets every texel through +fn cropping_projector(proj: &Projection) -> Option<&Projector> { + let projector = match proj { + Projection::Triplanar { projector, .. } + | Projection::Planar { projector, .. } + | Projection::Spherical { projector, .. } + | Projection::Cylindrical { projector, .. } => projector, + // Framed on the surface: see [`framed_cover`] + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None, + }; + Some(projector).filter(|projector| projector.crop != ShapeCrop::ExtendsOutside || projector.backface.on) +} + +/// Whether [`projector_cover`] is 1 on every texel, so it needs no texel's place +pub fn projector_covers_all(proj: &Projection) -> bool { + cropping_projector(proj).is_none() +} + +/// How much of the texel at `coords` the projection reaches through its shape crop and backface culling; not for placed planars or warps (see [`framed_cover`]) +pub fn projector_cover(proj: &Projection, coords: &Coords) -> f32 { + let Some(projector) = cropping_projector(proj) else { return 1.0 }; + + let local = projector_local(projector, coords); + let (inside, facing) = match proj { + Projection::Triplanar { .. } => (local.pos.abs().max_element() <= 1.0, None), + Projection::Planar { scale, axis, offset, .. } => { + let scaled = local.pos * *scale + Vec3::from(*offset); + + // The frame across the axis, and the side the image reads the right way round from + let (frame, facing) = match axis { + 0 => (scaled.z.abs().max(scaled.y.abs()), -local.nrm.x), + 1 => (scaled.x.abs().max(scaled.z.abs()), local.nrm.y), + _ => (scaled.x.abs().max(scaled.y.abs()), local.nrm.z), + }; + (frame <= 1.0, Some(facing)) + } + Projection::Spherical { offset, .. } => ((local.pos + Vec3::from(*offset)).length() <= 1.0, None), + Projection::Cylindrical { axis, offset, .. } => { + let position = local.pos + Vec3::from(*offset); + let normal = local.nrm; + let ((across, height, depth), (normal_across, normal_depth)) = match axis { + 0 => ((position.y, position.x, position.z), (normal.y, normal.z)), + 2 => ((position.x, position.z, position.y), (normal.x, normal.y)), + _ => ((position.x, position.y, position.z), (normal.x, normal.z)), + }; + let radius = across.hypot(depth); + let outward = if radius > MIN_AXIS_DISTANCE { (normal_across * across + normal_depth * depth) / radius } else { 1.0 }; + (radius <= 1.0 && height.abs() <= 1.0, Some(outward)) + } + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => (true, None), + }; + if projector.crop == ShapeCrop::Cropped && !inside { + return 0.0; + } + + match facing { + Some(facing) if projector.backface.on => backface_cover(&projector.backface, facing), + _ => 1.0, + } +} + +/// How much a face turned `facing` (the cosine of its turn from the projection) keeps +pub fn backface_cover(backface: &Backface, facing: f32) -> f32 { + // A hand-edited NaN angle or hardness keeps the layer visible rather than making its texels NaN + if !(backface.angle.is_finite() && backface.hardness.is_finite()) { + return 1.0; + } + + // cos(angle) as sin(90 - angle): exactly 0 at 90 degrees + let threshold = (90.0 - backface.angle).to_radians().sin(); + let width = (1.0 - backface.hardness.clamp(0.0, 1.0)) * BACKFACE_FADE; + if width <= f32::EPSILON { + return f32::from(u8::from(facing > threshold)); + } + + smoothstep(threshold, threshold + width, facing) +} + +/// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate) +pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { + let local = frame_local(frame, projector, p)?; + let mut cover = if projector.backface.on { backface_cover(&projector.backface, frame_facing(frame, projector, nrm)) } else { 1.0 }; + if projector.crop == ShapeCrop::Cropped { + cover *= frame_crop(frame, local); + } + Some((flip_uv(placed_uv(local), frame.flip), cover)) +} + +/// [`placed_cover`] for a frame with a mirrored copy: whichever of the frame and its copy covers the point more. The copy is the frame reflected through the plane `offset` away from `center` (the mesh center) on the symmetry axis, its image flipped as asked +pub fn placed_cover_symmetric(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + let direct = placed_cover(frame, projector, p, nrm); + let Some(symmetry) = frame.symmetry else { return direct }; + + let axis = usize::from(symmetry.axis.min(2)); + let (mut mirrored_position, mut mirrored_normal) = (p, nrm); + mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; + mirrored_normal[axis] = -nrm[axis]; + let mirrored = placed_cover(frame, projector, mirrored_position, mirrored_normal).map(|(uv, cover)| { + let uv = match symmetry.flip { + DecalFlip::None => uv, + DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), + DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), + }; + (uv, cover) + }); + match (direct, mirrored) { + (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), + (a, b) => a.or(b), + } +} + +/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame +fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 { + Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y }) +} + +/// A projection from a frame on the surface (a placed planar or a warp) at world point `p` with normal `nrm`, `center` the mesh center a placed planar's mirrored copy reflects across: its texture coordinates and how much it covers there (None for other projections, a degenerate frame or where nothing lands) +pub fn framed_cover(proj: &Projection, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + match proj { + Projection::Planar { projector, placed: Some(frame), .. } => placed_cover_symmetric(frame, projector, p, nrm, center), + Projection::Warp { frame, corners, depth, projector, .. } => warp_cover(frame, corners, *depth, projector, p), + _ => None, + } +} + +/// A warp projection at world point `p`: its texture coordinates in the quad its corners make, and, cropped to its shape, how much of the quad and of its Projection Depth (in lengths of the frame's longer side) cover it +pub fn warp_cover(frame: &Decal, corners: &[[f32; 2]; 4], depth: f32, projector: &Projector, p: Vec3) -> Option<(Vec2, f32)> { + let local = frame_local(frame, projector, p)?; + let uv = warp_uv(corners, local.truncate())?; + if projector.crop == ShapeCrop::ExtendsOutside { + return Some((uv, 1.0)); + } + + let inside = (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y); + let reach = warp_reach(frame.size, depth); + Some((uv, if inside { depth_fade(local.z, reach) } else { 0.0 })) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The decal formula from before decals were placed planar projections, kept to check they still look the same + fn decal_before(frame: &Decal, point: Vec3, surface_normal: Vec3) -> Option<(Vec2, f32)> { + let (origin, right, up, normal) = crate::pattern::decal_axes(frame)?; + let facing = surface_normal.dot(normal); + let offset = point - origin; + let (local_x, local_y, local_z) = (offset.dot(right) / frame.size[0].max(1e-6), offset.dot(up) / frame.size[1].max(1e-6), offset.dot(normal).abs()); + let depth = frame.depth.max(1e-6); + if facing <= 0.0 || local_x.abs() > 0.5 || local_y.abs() > 0.5 || local_z > depth || !(local_x.is_finite() && local_y.is_finite()) { + return None; + } + + let cover = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, local_z)); + Some((Vec2::new(local_x + 0.5, 0.5 - local_y), cover)) + } + + #[test] + fn a_nan_backface_angle_or_hardness_culls_nothing() { + for backface in [Backface { on: true, angle: f32::NAN, hardness: 0.5 }, Backface { on: true, angle: 60.0, hardness: f32::NAN }] { + assert_eq!(backface_cover(&backface, -0.5), 1.0, "{backface:?}"); + } + } + + #[test] + fn saved_decals_cover_exactly_as_before() { + let frames = [ + Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [2.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }, + Decal { + center: [0.3, -0.2, 0.1], + normal: [0.4, 0.5, 0.7], + up: [0.0, 1.0, 0.0], + size: [0.7, 1.3], + rotation: 37.0, + offset: [0.2, -0.1], + depth: 0.4, + symmetry: None, + flip: [false; 2], + }, + ]; + for frame in frames { + let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") }; + for sample in 0..4000 { + let phase = sample as f32 * 0.137; + let point = Vec3::new(phase.sin() * 1.3, (phase * 0.71).cos() * 1.1, (phase * 0.33).sin() * 0.8); + let normal = Vec3::new((phase * 1.7).cos(), (phase * 0.9).sin(), (phase * 0.4).cos()).normalize(); + let now = placed_cover(&placed, &projector, point, normal).filter(|(_, cover)| *cover > 0.0); + match (decal_before(&frame, point, normal), now) { + (Some(before), Some(now)) => assert_eq!(before, now, "{point} {normal}"), + (None, None) => {} + (before, now) => panic!("{point} {normal}: {before:?} became {now:?}"), + } + } + } + } + + /// The mirrored copy's formula as the decal model before placed planar projections had it (flip and symmetry on a decal) + fn symmetric_before(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + let flip = |uv: Vec2| flip_uv(uv, d.flip); + let direct = decal_before(d, p, nrm).map(|(uv, w)| (flip(uv), w)); + let Some(symmetry) = d.symmetry else { return direct }; + let axis = usize::from(symmetry.axis.min(2)); + let (mut q, mut m) = (p, nrm); + q[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; + m[axis] = -nrm[axis]; + let mirrored = decal_before(d, q, m).map(|(uv, w)| { + let uv = flip(uv); + let uv = match symmetry.flip { + DecalFlip::None => uv, + DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), + DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), + }; + (uv, w) + }); + match (direct, mirrored) { + (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), + (a, b) => a.or(b), + } + } + + #[test] + fn saved_mirrored_and_flipped_decals_cover_exactly_as_before() { + let base = Decal { + center: [0.3, -0.2, 0.1], + normal: [0.4, 0.5, 0.7], + up: [0.0, 1.0, 0.0], + size: [0.7, 1.3], + rotation: 37.0, + offset: [0.2, -0.1], + depth: 0.4, + symmetry: None, + flip: [false; 2], + }; + let center = Vec3::new(0.1, -0.05, 0.2); + let frames = [ + Decal { flip: [true, false], ..base }, + Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 }), ..base }, + Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: -0.15 }), flip: [false, true], ..base }, + ]; + for frame in frames { + let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") }; + let mut mirrored = 0; + for i in 0..4000 { + let t = i as f32 * 0.137; + let p = Vec3::new(t.sin() * 1.3, (t * 0.71).cos() * 1.1, (t * 0.33).sin() * 0.8); + let nrm = Vec3::new((t * 1.7).cos(), (t * 0.9).sin(), (t * 0.4).cos()).normalize(); + let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0); + let before = symmetric_before(&frame, p, nrm, center); + mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none()); + assert_eq!(before, now, "{p} {nrm}"); + } + assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not"); + } + } +} diff --git a/crates/compose/src/projector_depth.rs b/crates/compose/src/projector_depth.rs new file mode 100644 index 00000000..bf0aafcd --- /dev/null +++ b/crates/compose/src/projector_depth.rs @@ -0,0 +1,287 @@ +//! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +use texturecraft_core::Projection; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::organic::smoothstep; +use crate::projector_view::ProjectorView; + +/// The nearest surface in each cell of a grid across a projector's view +pub struct ProjectorDepth { + view: ProjectorView, + /// The view point at the grid's lower corner + origin: Vec2, + /// One cell's size across and up in the view + cell: Vec2, + /// Per cell: the nearness of the nearest surface at the cell centre and its slope across and up (nearness -inf where no surface is) + front: Vec<[f32; 3]>, +} + +/// Built maps by their view and the mesh they come from +type CacheEntry = (ProjectorView, u64, Arc); + +/// The smallest grid cell across and up, so a flat view still divides +const MIN_CELL_SIZE: f32 = 1e-6; + +/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps +const EDGE_TOLERANCE: f32 = 1e-6; + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +impl ProjectorDepth { + /// The depth map of `proj` over `mesh` within `bounds`, built once per view and mesh; None unless `proj` culls by depth + pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), proj: &Projection) -> Option> { + let view = ProjectorView::of(proj, bounds)?; + let mesh_key = fingerprint(mesh); + + // Built with the cache locked: the build runs no parallel work, and tiles asking for the same map wait for it instead of building it again + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(at) = cache.iter().position(|(cached_view, cached_mesh, _)| *cached_view == view && *cached_mesh == mesh_key) { + let (cached_view, cached_mesh, depth) = cache.remove(at); + cache.insert(0, (cached_view, cached_mesh, depth.clone())); + return Some(depth); + } + + let depth = Arc::new(ProjectorDepth::build(view, mesh)?); + cache.insert(0, (view, mesh_key, depth.clone())); + cache.truncate(CACHE_MAPS); + Some(depth) + } + + /// Drop every built map: a mesh replacing another (a reimport, another project) can share the old one's fingerprint + pub fn forget_all() { + CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); + } + + /// Rasterize every triangle of `mesh` in `view`, keeping the nearest per cell (None when no vertex lands in the view) + pub fn build(view: ProjectorView, mesh: &Mesh) -> Option { + let local: Vec> = mesh.positions.iter().map(|position| view.local(*position)).collect(); + let (lo, hi) = local + .iter() + .flatten() + .fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate()))); + if lo.x > hi.x || lo.y > hi.y { + return None; + } + + let cell = ((hi - lo) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE)); + let mut depth = ProjectorDepth { view, origin: lo, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] }; + let mut budget = CELL_BUDGET; + for tri in mesh.indices.as_chunks::<3>().0 { + let corner = |i: u32| local.get(i as usize).copied().flatten(); + let (Some(a), Some(b), Some(c)) = (corner(tri[0]), corner(tri[1]), corner(tri[2])) else { continue }; + if !depth.raster([a, b, c], &mut budget) { + break; + } + } + Some(depth) + } + + /// Keep `triangle` where it is nearer than what a cell holds; false once the cell budget runs out + fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool { + let [a, b, c] = triangle; + let (d1, d2) = (b - a, c - a); + let det = d1.x * d2.y - d1.y * d2.x; + if !det.is_finite() || det.abs() < MIN_SCREEN_AREA { + // Seen edge on, it covers nothing + return true; + } + + let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / det, (d1.x * d2.z - d2.x * d1.z) / det).clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE)); + + // Corners in cells: cell (i, j) has its centre at (i + 0.5, j + 0.5) + let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell); + let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc)); + let first = |v: f32| (v - 0.5).ceil().clamp(0.0, SIZE as f32) as usize; + let last = |v: f32| ((v - 0.5).floor() + 1.0).clamp(0.0, SIZE as f32) as usize; + let (x0, x1, y0, y1) = (first(lo.x), last(hi.x), first(lo.y), last(hi.y)); + let cells = x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0)); + let Some(left) = budget.checked_sub(cells) else { return false }; + *budget = left; + + let area = edge(pa, pb, pc); + for y in y0..y1 { + for x in x0..x1 { + let cell_centre = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let inside = [edge(pb, pc, cell_centre), edge(pc, pa, cell_centre), edge(pa, pb, cell_centre)] + .iter() + .all(|weight| weight * area.signum() >= -EDGE_TOLERANCE * area.abs()); + if !inside { + continue; + } + + let near = a.z + slope.dot(self.origin + cell_centre * self.cell - a.truncate()); + if let Some(cell) = self.front.get_mut(y * SIZE + x) + && near > cell[0] + { + *cell = [near, slope.x, slope.y]; + } + } + } + true + } + + /// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front + pub fn cover(&self, p: Vec3, hardness: f32) -> f32 { + // A hand-edited NaN hardness keeps the layer visible rather than making its texels NaN + if !hardness.is_finite() { + return 1.0; + } + + let Some(view_point) = self.view.local(p) else { return 1.0 }; + let at = (view_point.truncate() - self.origin) / self.cell; + if !(at.x >= 0.0 && at.y >= 0.0 && at.x < SIZE as f32 && at.y < SIZE as f32) { + return 1.0; + } + + let (x, y) = (at.x as usize, at.y as usize); + let Some(&[near, across, up]) = self.front.get(y * SIZE + x).filter(|cell| cell[0].is_finite()) else { return 1.0 }; + + // The nearest surface's plane carried from the cell centre to the point, so a surface is never behind itself + let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell; + let slope = Vec2::new(across, up); + let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z; + let unit = self.view.unit(); + + // Neighbouring triangles of a curved surface part from the carried plane by about one cell of its slope + let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit); + let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit; + if width <= f32::EPSILON { + return f32::from(u8::from(behind <= bias)); + } + + 1.0 - smoothstep(bias, bias + width, behind) + } +} + +/// Twice the signed area of triangle `a`, `b`, `q` +fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 { + (b - a).perp_dot(q - a) +} + +/// Which mesh a map was built for: its sizes and a spread of its vertices and indices +fn fingerprint(mesh: &Mesh) -> u64 { + let mut hasher = DefaultHasher::new(); + (mesh.positions.len(), mesh.indices.len()).hash(&mut hasher); + for position in mesh.positions.iter().step_by((mesh.positions.len() / FINGERPRINT_SAMPLES).max(1)) { + position.to_array().map(f32::to_bits).hash(&mut hasher); + } + for index in mesh.indices.iter().step_by((mesh.indices.len() / FINGERPRINT_SAMPLES).max(1)) { + index.hash(&mut hasher); + } + hasher.finish() +} + +/// Cells across and up the grid +const SIZE: usize = 512; + +/// A triangle flatter than this on screen is seen edge on +const MIN_SCREEN_AREA: f32 = 1e-12; + +/// Most cells all triangles together may visit before the rest are left out (hostile meshes of huge overlapping triangles) +const CELL_BUDGET: usize = 256 * SIZE * SIZE; + +/// Steepest surface slope kept, in nearness per view unit +const MAX_SLOPE: f32 = 1e4; + +/// How far behind the nearest surface a point may sit and keep everything, in mesh radii +const BIAS: f32 = 0.002; + +/// Most the slope adds to the bias, in mesh radii +const MAX_SLOPE_BIAS: f32 = 0.05; + +/// How far behind the nearest surface culling fades out at hardness 0, in mesh radii +const FADE: f32 = 0.1; + +/// Maps kept built (each is about 3 MB) +const CACHE_MAPS: usize = 8; + +/// Vertices and indices the mesh fingerprint reads +const FINGERPRINT_SAMPLES: usize = 64; + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::{Projector, UvTransform}; + + /// Two squares facing +Z, one at z = `front` covering x 0..1, one at z = `back` covering x -1..1 + fn two_squares(front: f32, back: f32) -> Mesh { + let positions = vec![ + Vec3::new(0.0, -1.0, front), + Vec3::new(1.0, -1.0, front), + Vec3::new(1.0, 1.0, front), + Vec3::new(0.0, 1.0, front), + Vec3::new(-1.0, -1.0, back), + Vec3::new(1.0, -1.0, back), + Vec3::new(1.0, 1.0, back), + Vec3::new(-1.0, 1.0, back), + ]; + Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7], ..Mesh::default() } + } + + fn planar_z(on: bool, hardness: f32) -> Projection { + let mut projector = Projector::depth_culled(); + projector.depth.on = on; + projector.depth.hardness = hardness; + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None } + } + + #[test] + fn surfaces_behind_others_are_culled_and_the_nearest_keeps_everything() { + let mesh = two_squares(0.5, -0.5); + let bounds = mesh.bounds(); + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), bounds).unwrap(), &mesh).unwrap(); + assert_eq!(depth.cover(Vec3::new(0.5, 0.3, 0.5), 1.0), 1.0, "the front square"); + assert_eq!(depth.cover(Vec3::new(0.5, 0.3, -0.5), 1.0), 0.0, "the back square behind it"); + assert_eq!(depth.cover(Vec3::new(-0.5, 0.3, -0.5), 1.0), 1.0, "the back square where nothing is in front"); + let soft = depth.cover(Vec3::new(0.5, 0.3, 0.5 - 0.01), 0.0); + assert!(soft > 0.0 && soft < 1.0, "a soft cull fades just behind the front: {soft}"); + assert!(ProjectorView::of(&planar_z(false, 1.0), bounds).is_none(), "off, there is nothing to build"); + } + + #[test] + fn a_nan_hardness_culls_nothing() { + let mesh = two_squares(0.5, -0.5); + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap(); + + let behind = depth.cover(Vec3::new(0.5, 0.3, -0.5), f32::NAN); + + assert_eq!(behind, 1.0, "a hand-edited NaN hardness keeps the back square visible"); + } + + #[test] + fn a_mesh_edited_where_its_fingerprint_does_not_look_is_rebuilt_once_forgotten() { + // Unused vertices spread the fingerprint's samples so the front square's right edge is not among them + let mut mesh = two_squares(0.5, -0.5); + mesh.positions.extend((0..FINGERPRINT_SAMPLES * 3).map(|_| Vec3::ZERO)); + let mut edited = mesh.clone(); + for right in [1, 2] { + edited.positions[right].x = 0.5; + } + assert_eq!(fingerprint(&mesh), fingerprint(&edited), "the edit is unseen by the fingerprint"); + let proj = planar_z(true, 1.0); + let behind_the_cut = Vec3::new(0.75, 0.3, -0.5); + let bounds = mesh.bounds(); + assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0); + + ProjectorDepth::forget_all(); + + let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap(); + assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more"); + } + + #[test] + fn a_slanted_surface_is_never_behind_itself() { + let positions = vec![Vec3::new(-1.0, -1.0, -0.9), Vec3::new(1.0, -1.0, 0.9), Vec3::new(1.0, 1.0, 0.9), Vec3::new(-1.0, 1.0, -0.9)]; + let mesh = Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() }; + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap(); + for i in 0..1000 { + let (x, y) = ((i as f32 * 0.618).fract() * 1.98 - 0.99, (i as f32 * 0.377).fract() * 1.98 - 0.99); + assert_eq!(depth.cover(Vec3::new(x, y, x * 0.9), 1.0), 1.0, "{x} {y}"); + } + } +} diff --git a/crates/compose/src/projector_view.rs b/crates/compose/src/projector_view.rs new file mode 100644 index 00000000..982d0820 --- /dev/null +++ b/crates/compose/src/projector_view.rs @@ -0,0 +1,62 @@ +//! Where a planar or warp projection's projector looks from, for depth culling + +use texturecraft_core::{Decal, Projection, Projector}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::pattern::{Coords, frame_local, mesh_frame, projector_local}; + +/// The view of a depth-culled planar or warp projection: points in it run across, up and towards the projector +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ProjectorView { + /// An axis planar projection, reading positions around the mesh centre in mesh radii + Axis { axis: u8, projector: Projector, center: Vec3, radius: f32 }, + /// A planar projection placed on the surface or a warp, from its frame + Frame { frame: Decal, projector: Projector, radius: f32 }, +} + +impl ProjectorView { + /// The view of `proj` over a mesh within `bounds`, None unless it is a planar or warp projection with depth culling on + pub fn of(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + proj.depth_culling()?; + let (center, radius) = mesh_frame(bounds); + match proj { + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => { + Some(ProjectorView::Frame { frame: *frame, projector: turn_only(projector), radius }) + } + Projection::Planar { axis, projector, .. } => Some(ProjectorView::Axis { axis: *axis, projector: turn_only(projector), center, radius }), + _ => None, + } + } + + /// World point `point` in the view: across, up and how near the projector (None where the view is degenerate) + pub fn local(&self, point: Vec3) -> Option { + let local = match self { + ProjectorView::Axis { axis, projector, center, radius } => { + let at = Coords { uv: Vec2::ZERO, pos: (point - *center) / *radius, nrm: Vec3::Z }; + let projected = projector_local(projector, &at).pos; + + // The side each axis projects from, as its backface culling reads it + match axis { + 0 => Vec3::new(projected.z, projected.y, -projected.x), + 1 => Vec3::new(projected.x, projected.z, projected.y), + _ => projected, + } + } + ProjectorView::Frame { frame, projector, .. } => frame_local(frame, projector, point)?, + }; + local.is_finite().then_some(local) + } + + /// The mesh radius in the view's nearness units + pub fn unit(&self) -> f32 { + match self { + ProjectorView::Axis { .. } => 1.0, + ProjectorView::Frame { radius, .. } => *radius, + } + } +} + +/// Only what moves the view: the turn and stretch, not the culling settings (changing those keeps the depth map) +fn turn_only(projector: &Projector) -> Projector { + Projector { rotation: projector.rotation, scale: projector.scale, ..Projector::default() } +} From 891247db6acea1e1f44c1140573f120687ff1736 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH 010/153] Fills: decals are placed planars, and the Warp projection --- crates/compose/src/frame_placement.rs | 331 +++++++++++++++++++++++++ crates/compose/src/warp.rs | 96 ++++++++ crates/core/src/saved_decal.rs | 11 + crates/engine/src/decal_cmds.rs | 335 +++++++++++++++++++------- crates/engine/src/warp_cmds.rs | 68 ++++++ crates/ui-egui/src/warp_checker.rs | 169 +++++++++++++ 6 files changed, 921 insertions(+), 89 deletions(-) create mode 100644 crates/compose/src/frame_placement.rs create mode 100644 crates/compose/src/warp.rs create mode 100644 crates/core/src/saved_decal.rs create mode 100644 crates/engine/src/warp_cmds.rs create mode 100644 crates/ui-egui/src/warp_checker.rs diff --git a/crates/compose/src/frame_placement.rs b/crates/compose/src/frame_placement.rs new file mode 100644 index 00000000..0adac17b --- /dev/null +++ b/crates/compose/src/frame_placement.rs @@ -0,0 +1,331 @@ +//! A frame on the surface (a placed planar or a warp) as its 3D projection settings show it: where its centre is, how it is turned and how big it is + +use texturecraft_core::{Decal, Projection, Projector}; +use texturecraft_geom::glam::{EulerRot, Mat3, Quat, Vec3}; + +use crate::pattern::{decal_axes, mesh_frame, projector_stretch}; + +/// The shortest frame side a depth is divided by, so a collapsed frame keeps a finite depth +pub const MIN_FRAME_SIDE: f32 = 1e-6; + +/// Below this the frame faces nearly straight up or down, so world up gives no upright direction +const MIN_UP_CROSS_SQUARED: f32 = 1e-6; + +/// The longer side of a frame of `size`, at least [`MIN_FRAME_SIDE`]: a warp's Projection Depth counts in it +pub fn longer_side(size: [f32; 2]) -> f32 { + size[0].max(size[1]).max(MIN_FRAME_SIDE) +} + +/// How far a warp whose frame has `size` reaches in front of and behind it at Projection Depth `depth`, in world units +pub fn warp_reach(size: [f32; 2], depth: f32) -> f32 { + depth * longer_side(size) +} + +/// A frame's Offset (its centre in mesh radii from the mesh's centre), Rotation (degrees round X, Y and Z, as a projector turns) and Scale (its width and height, then how far it reaches in front of and behind it, in mesh diagonals) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FramePlacement { + pub offset: [f32; 3], + pub rotation: [f32; 3], + pub scale: [f32; 3], +} + +/// Whether backface culling faces the same way once `projector`'s scale is moved into a frame: culling is off, or the scale is even and keeps the side the frame faces (culling reads the scaled normal, a frame its own) +pub fn culling_folds(projector: &Projector) -> bool { + let stretch = projector_stretch(projector); + let size = stretch.abs(); + let even = size.x == size.y && size.y == size.z; + !projector.backface.on || (even && stretch.x * stretch.y * stretch.z > 0.0) +} + +/// `proj` (a placed planar or a warp) with its projector's turn and scale moved into its frame, so the frame is where the projection lands; culling and crop stay. None for other projections, and while backface culling cannot keep its facing (see [`culling_folds`]) +pub fn folded(proj: &Projection) -> Option { + let (frame, projector) = match proj { + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => (frame, projector), + _ => return None, + }; + + if !projector.turns() { + return Some(proj.clone()); + } + + if !culling_folds(projector) { + return None; + } + + let (origin, across, up, _) = decal_axes(frame)?; + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_cols(across, up, across.cross(up)) * Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(projector); + + // A negative scale turns that side over + let (across, up) = (turn.x_axis * stretch.x.signum(), turn.y_axis * stretch.y.signum()); + let size = [frame.size[0] * stretch.x.abs(), frame.size[1] * stretch.y.abs()]; + let reach = stretch.z.abs(); + let new_frame = Decal { + center: origin.to_array(), + normal: across.cross(up).to_array(), + up: up.to_array(), + size, + rotation: 0.0, + offset: [0.0; 2], + depth: frame.depth * reach, + symmetry: frame.symmetry, + flip: frame.flip, + }; + let unturned = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector }; + let mut out = proj.clone(); + match &mut out { + Projection::Planar { placed: Some(placed), projector, .. } => { + *placed = new_frame; + *projector = unturned; + } + Projection::Warp { frame: warp, projector, depth, .. } => { + // Its depth counts in lengths of the frame's longer side + *depth *= reach * longer_side(frame.size) / longer_side(size); + *warp = new_frame; + *projector = unturned; + } + _ => return None, + } + let finite = new_frame.center.iter().chain(&new_frame.normal).chain(&new_frame.up).chain(&new_frame.size).all(|v| v.is_finite()); + finite.then_some(out) +} + +/// How far frame projection `proj` reaches in front of and behind its frame, in world units (a warp counts its depth in lengths of the longer side) +fn reach(proj: &Projection) -> Option { + match proj { + Projection::Planar { placed: Some(frame), .. } => Some(frame.depth), + Projection::Warp { frame, depth, .. } => Some(warp_reach(frame.size, *depth)), + _ => None, + } +} + +/// Where frame projection `proj` (a placed planar or a warp) sits on a mesh with bounds `bounds`, its projector folded in (None for other projections) +pub fn placement(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + let proj = folded(proj)?; + let frame = proj.frame()?; + let (center, radius) = mesh_frame(bounds); + let (origin, across, up, out) = decal_axes(frame)?; + let (z, y, x) = Quat::from_mat3(&Mat3::from_cols(across, up, out)).to_euler(EulerRot::ZYX); + let diagonal = 2.0 * radius; + let placement = FramePlacement { + offset: ((origin - center) / radius).to_array(), + rotation: [x, y, z].map(f32::to_degrees), + scale: [frame.size[0] / diagonal, frame.size[1] / diagonal, reach(&proj)? / diagonal], + }; + let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale); + values.copied().all(f32::is_finite).then_some(placement) +} + +/// Frame projection `proj` (a placed planar or a warp) moved to `placement`; its projector's turn and scale are folded in first, its other settings kept (None for other projections or a degenerate placement) +pub fn placed(proj: &Projection, placement: &FramePlacement, bounds: (Vec3, Vec3)) -> Option { + let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale); + if !values.copied().all(f32::is_finite) || placement.scale.iter().any(|scale| *scale <= 0.0) { + return None; + } + + let mut proj = folded(proj)?; + let old = *proj.frame()?; + let (center, radius) = mesh_frame(bounds); + let diagonal = 2.0 * radius; + let [x, y, z] = placement.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let [width, height, deep] = placement.scale.map(|scale| scale * diagonal); + let frame = Decal { + center: (center + Vec3::from(placement.offset) * radius).to_array(), + normal: turn.z_axis.to_array(), + up: turn.y_axis.to_array(), + size: [width, height], + rotation: 0.0, + offset: [0.0; 2], + depth: deep, + symmetry: old.symmetry, + flip: old.flip, + }; + match &mut proj { + Projection::Planar { placed: Some(placed), .. } => *placed = frame, + Projection::Warp { frame: warp, depth, .. } => { + *depth = deep / longer_side([width, height]); + + // The warp's own depth is what reaches; the frame's is unused + *warp = Decal { depth: warp.depth, ..frame }; + } + _ => return None, + } + Some(proj) +} + +/// A frame's turn round its own normal, as seen face on with the world's up (or, looking straight down, the far side) at the top: degrees +pub fn upright_turn(frame: &Decal) -> Option { + let (_, _, up, out) = decal_axes(frame)?; + let world_up = if out.cross(Vec3::Y).length_squared() > MIN_UP_CROSS_SQUARED { Vec3::Y } else { Vec3::NEG_Z }; + let upright = (world_up - out * out.dot(world_up)).try_normalize()?; + let upright_across = upright.cross(out); + let turn = (-up.dot(upright_across)).atan2(up.dot(upright)).to_degrees(); + turn.is_finite().then_some(turn) +} + +#[cfg(test)] +mod tests { + use texturecraft_core::{Backface, DecalFlip, DecalSymmetry, ShapeCrop, UvTransform}; + use texturecraft_geom::glam::Vec2; + + use super::*; + use crate::projector_cover::framed_cover; + + const BOUNDS: (Vec3, Vec3) = (Vec3::new(-1.0, -2.0, -0.5), Vec3::new(3.0, 1.0, 1.5)); + + fn frame() -> Decal { + Decal { + center: [0.4, -0.2, 1.3], + normal: [0.2, 0.1, 1.0], + up: [0.0, 1.0, 0.1], + size: [1.2, 0.8], + rotation: 25.0, + offset: [0.1, -0.2], + depth: 0.6, + symmetry: None, + flip: [false; 2], + } + } + + fn planar(projector: Projector) -> Projection { + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame()) } + } + + fn warp(projector: Projector) -> Projection { + Projection::Warp { frame: frame(), corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]], depth: 0.7, uv: UvTransform::default(), projector } + } + + /// The projection's texture coordinates and cover at points through the frame's neighbourhood with varied normals + fn samples(proj: &Projection) -> Vec> { + let mut out = Vec::new(); + for across in 0..7 { + for up in 0..7 { + for out_of in 0..3 { + let position = Vec3::new(-0.5 + across as f32 * 0.25, -0.8 + up as f32 * 0.2, 0.7 + out_of as f32 * 0.3); + let normal = Vec3::new(0.1 * across as f32 - 0.3, 0.2, 1.0).normalize(); + out.push(framed_cover(proj, position, normal, (BOUNDS.0 + BOUNDS.1) * 0.5)); + } + } + } + out + } + + fn projector_of(proj: &Projection) -> Projector { + match proj { + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => *projector, + _ => panic!("a frame projection"), + } + } + + fn close(a: &[Option<(Vec2, f32)>], b: &[Option<(Vec2, f32)>]) { + assert_eq!(a.len(), b.len()); + for (index, (a, b)) in a.iter().zip(b).enumerate() { + match (a, b) { + (Some((uv_a, cover_a)), Some((uv_b, cover_b))) => { + assert!((cover_a - cover_b).abs() < 1e-3, "{index}: cover {cover_a} vs {cover_b}"); + assert!(uv_a.distance(*uv_b) < 1e-3, "{index}: {uv_a} vs {uv_b}"); + } + (None, None) => {} + _ => panic!("{index}: sampled on one side only: {a:?} vs {b:?}"), + } + } + } + + #[test] + fn folding_a_turned_and_evenly_scaled_projector_into_its_frame_lands_the_same() { + let projector = Projector { rotation: [20.0, -35.0, 50.0], scale: [1.7; 3], crop: ShapeCrop::Cropped, ..Projector::default() }; + for proj in [planar(projector), warp(projector)] { + let flat = folded(&proj).unwrap(); + let Projector { rotation, scale, crop, .. } = projector_of(&flat); + assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed"); + close(&samples(&proj), &samples(&flat)); + } + let unturned = planar(Projector::default()); + assert_eq!(folded(&unturned), Some(unturned), "nothing to fold: unchanged"); + assert_eq!(folded(&Projection::default()), None); + } + + #[test] + fn folding_keeps_what_backface_culling_hides() { + let backface = Backface { on: true, angle: 60.0, hardness: 1.0 }; + let square = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [1.0, 1.0], rotation: 0.0, offset: [0.0; 2], ..frame() }; + + // Half way between across and out: a scale across tilts the culled normal past the angle, a negative one turns it round + let normal = Vec3::new(1.0, 0.0, 1.0).normalize(); + let center = (BOUNDS.0 + BOUNDS.1) * 0.5; + let cover = |proj: &Projection| framed_cover(proj, Vec3::ZERO, normal, center).map(|(_, cover)| cover); + + for scale in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] { + let projector = Projector { scale, backface, ..Projector::default() }; + let proj = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(square) }; + match folded(&proj) { + Some(flat) => { + assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed"); + close(&samples(&proj), &samples(&flat)); + } + None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"), + } + } + + assert!(folded(&planar(Projector { scale: [1.7; 3], backface, ..Projector::default() })).is_some(), "an even scale still folds"); + } + + #[test] + fn a_placement_read_and_written_back_lands_the_same_and_its_fields_move_the_frame() { + let projector = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() }; + for proj in [planar(Projector::default()), warp(Projector::default()), planar(projector), warp(projector)] { + let place = placement(&proj, BOUNDS).unwrap(); + let back = placed(&proj, &place, BOUNDS).unwrap(); + close(&samples(&folded(&proj).unwrap()), &samples(&back)); + let again = placement(&back, BOUNDS).unwrap(); + for (a, b) in place.offset.iter().chain(&place.rotation).chain(&place.scale).zip(again.offset.iter().chain(&again.rotation).chain(&again.scale)) { + assert!((a - b).abs() < 1e-3, "{place:?} vs {again:?}"); + } + + let width = folded(&proj).unwrap().frame().unwrap().size[0]; + let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap(); + assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width"); + let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap(); + assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre"); + } + let place = placement(&planar(Projector::default()), BOUNDS).unwrap(); + assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size"); + assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None); + assert_eq!(placement(&Projection::default(), BOUNDS), None); + } + + #[test] + fn a_frames_upright_turn_is_its_turn_round_its_normal() { + let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() }; + assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3); + flat.rotation = -100.0; + assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3); + let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() }; + assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up"); + } + + #[test] + fn folding_and_placing_keep_a_frames_mirror_copy_and_image_flip() { + let symmetry = Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.2 }); + let mirrored = Decal { symmetry, flip: [true, false], ..frame() }; + let turned = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() }; + for proj in [ + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: turned, placed: Some(mirrored) }, + Projection::Warp { + frame: mirrored, + corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]], + depth: 0.7, + uv: UvTransform::default(), + projector: turned, + }, + ] { + let folded = folded(&proj).unwrap(); + let moved = placed(&proj, &placement(&proj, BOUNDS).unwrap(), BOUNDS).unwrap(); + for frame in [folded.frame().unwrap(), moved.frame().unwrap()] { + assert_eq!((frame.symmetry, frame.flip), (symmetry, [true, false])); + } + } + } +} diff --git a/crates/compose/src/warp.rs b/crates/compose/src/warp.rs new file mode 100644 index 00000000..29a1ec95 --- /dev/null +++ b/crates/compose/src/warp.rs @@ -0,0 +1,96 @@ +//! Where a point in a warp projection's frame lands in its image: the inverse of the bilinear quad its four corners make + +use texturecraft_geom::glam::Vec2; + +/// Texture coordinates (v down) of the point `p` (across and up in frame sizes) inside the quad `corners` makes (top left, top right, bottom right, bottom left); past the quad they run on, so the image can repeat. None where no texture coordinates land +pub fn warp_uv(corners: &[[f32; 2]; 4], p: Vec2) -> Option { + let [a, b, c, d] = corners.map(Vec2::from); + let (e, f, g, h) = (b - a, d - a, a - b + c - d, p - a); + let k2 = g.perp_dot(f); + let k1 = e.perp_dot(f) + h.perp_dot(g); + let k0 = h.perp_dot(e); + let uv = if k2.abs() < PARALLEL { + // Opposite edges parallel: the quad's equation is linear in v + let v = -k0 / k1; + Vec2::new(across(e, f, g, h, v)?, v) + } else { + let discriminant = k1 * k1 - 4.0 * k0 * k2; + if discriminant < 0.0 { + return None; + } + + let root = discriminant.sqrt(); + let near = |v: f32| across(e, f, g, h, v).map(|u| Vec2::new(u, v)); + + // Two solutions, neither found by subtracting near-equal values (which loses the answer when the quad is nearly a parallelogram): keep the one nearer the quad + let q = -0.5 * (k1 + root.copysign(k1)); + // q is 0 only for a double root at 0, which q / k2 still finds (k0 / q is then not finite, so no candidate) + let candidates = [near(q / k2), near(k0 / q)]; + candidates.into_iter().flatten().min_by(|x, y| outside(*x).total_cmp(&outside(*y)))? + }; + uv.is_finite().then_some(uv) +} + +/// How far across (u) a point lies at height `v`, solved on whichever axis the quad's edge spans most +fn across(e: Vec2, f: Vec2, g: Vec2, h: Vec2, v: f32) -> Option { + let span = e + g * v; + let u = if span.x.abs() >= span.y.abs() { (h.x - f.x * v) / span.x } else { (h.y - f.y * v) / span.y }; + u.is_finite().then_some(u) +} + +/// How far `uv` lies outside the image's 0..1 square (0 inside) +fn outside(uv: Vec2) -> f32 { + (uv - uv.clamp(Vec2::ZERO, Vec2::ONE)).length_squared() +} + +/// Below this, a quad's opposite edges count as parallel (frame sizes squared) +const PARALLEL: f32 = 1e-6; + +#[cfg(test)] +mod tests { + use super::*; + + const FRAME: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]; + + /// The point at texture coordinates `uv` inside the quad `corners` + fn bilinear(corners: &[[f32; 2]; 4], uv: Vec2) -> Vec2 { + let [a, b, c, d] = corners.map(Vec2::from); + let top = a.lerp(b, uv.x); + let bottom = d.lerp(c, uv.x); + top.lerp(bottom, uv.y) + } + + #[test] + fn the_unpulled_frame_maps_like_a_planar_frame() { + for (x, y) in [(0.0, 0.0), (-0.5, 0.5), (0.25, -0.4), (1.3, 0.7), (-2.0, -1.5)] { + assert_eq!(warp_uv(&FRAME, Vec2::new(x, y)), Some(Vec2::new(x + 0.5, 0.5 - y)), "{x} {y}"); + } + } + + #[test] + fn pulled_corners_bend_the_image_to_their_quad() { + let quads = [ + [[-0.6, 0.4], [0.5, 0.7], [0.3, -0.5], [-0.4, -0.45]], + [[-0.5, 0.5], [0.9, 0.5], [0.5, -0.5], [-0.5, -0.5]], + [[-0.2, 0.6], [0.2, 0.6], [0.7, -0.6], [-0.7, -0.6]], + // Nearly a parallelogram: one corner a hair out + [[0.0, 0.0], [1.0, 0.0], [1.0 + 1.0 / 262_144.0, 1.0], [0.0, 1.0]], + ]; + for quad in quads { + for i in 0..=10 { + for j in 0..=10 { + let uv = Vec2::new(i as f32 / 10.0, j as f32 / 10.0); + let found = warp_uv(&quad, bilinear(&quad, uv)).unwrap_or(Vec2::NAN); + assert!((found - uv).length() < 1e-4, "{quad:?} {uv}: {found}"); + } + } + } + } + + #[test] + fn a_collapsed_quad_lands_nowhere_instead_of_failing() { + let point = [[0.0, 0.0]; 4]; + assert_eq!(warp_uv(&point, Vec2::new(0.3, 0.2)), None); + assert_eq!(warp_uv(&[[f32::NAN; 2]; 4], Vec2::ZERO), None); + } +} diff --git a/crates/core/src/saved_decal.rs b/crates/core/src/saved_decal.rs new file mode 100644 index 00000000..c8c7a0b6 --- /dev/null +++ b/crates/core/src/saved_decal.rs @@ -0,0 +1,11 @@ +//! A decal written in the shape saved before decals were planar projections + +use serde::Serialize; + +use crate::Decal; + +/// A decal in the shape saved before decals were planar projections +#[derive(Serialize)] +pub(crate) enum SavedDecal<'a> { + Decal(&'a Decal), +} diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index 392da975..d49e7afe 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -1,13 +1,17 @@ //! Geometry decals: an image resource projected onto the surface from a frame placed on it -//! (a decal fill with a planar projection), as a fill layer with a decal projection. +//! (a decal fill with a planar projection), as a fill layer with a decal projection, and moving +//! the frame of any planar or warp projection use serde_json::{Value, json}; +use texturecraft_compose::axis_frame::{placed_from_axis, placing_moves_pattern}; +use texturecraft_compose::frame_placement::{MIN_FRAME_SIDE, culling_folds, folded, longer_side, placed, placement as frame_placement}; use texturecraft_core::{ Channel, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source, }; use texturecraft_geom::glam::{Quat, Vec2, Vec3}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, layer_param, strp, u64p, vec3}; +use crate::layer_cmds::{FULL_TURN_DEGREES, MAX_PROJECTION_DEPTH}; use crate::tool_cmds::viewport_of; use crate::{Result, Session, StackTarget, cmd}; @@ -27,7 +31,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer) — any fill with a planar or warp projection: moves the frame it projects from (an axis planar is first placed as the frame it projects from, reading images exactly as before; a warp keeps its corners), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?: world units (a warp: its Projection Depth becomes this over the frame's longer side), frameOffset?: [x, y, z] (the frame's centre in mesh radii from the mesh's centre), frameRotation?: [x, y, z] degrees (its turn: unturned it faces +Z with +Y up), frameScale?: [width, height, reach] (in mesh diagonals; reach = how far it projects in front of and behind it, a warp's Projection Depth times its longer side) — the frame as the 3D projection settings show it, applied before the other fields; any projector turn or scale is first folded into the frame (it lands the same); refused: an axis planar reading a procedural (placing it would move the pattern) and, under backface culling with an uneven or mirrored projector scale, placing an axis planar or the frame fields (even the scale out or turn culling off), symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags); a call that changes nothing adds no undo step}", always, set ), @@ -62,15 +66,24 @@ const MIN_SIZE: f32 = 1e-4; /// The largest decal side or depth, relative to the mesh diagonal const MAX_SIZE: f32 = 10.0; +/// The smallest mesh diagonal decal sizes count in, so a collapsed mesh still places one +const MIN_MESH_DIAGONAL: f32 = 1e-3; + +/// A given `up` this near the normal (squared sine of the angle between them) leaves no upright direction +const MIN_GIVEN_UP_CROSS_SQUARED: f32 = 1e-8; + +/// The camera's up this near the normal (squared sine) is a top face seen from the front: up is where the camera looks +const MIN_CAMERA_UP_CROSS_SQUARED: f32 = 1e-4; + /// The mesh's diagonal (decal sizes are relative to it). -fn mesh_size(s: &Session) -> f32 { - let (lo, hi) = s.mesh.bounds(); - (hi - lo).length().max(1e-3) +fn mesh_size(session: &Session) -> f32 { + let (lo, hi) = session.mesh.bounds(); + (hi - lo).length().max(MIN_MESH_DIAGONAL) } /// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits -fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { - let value = p.get("size")?; +fn size_param(params: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { + let value = params.get("size")?; let size = match value.as_array() { Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32], None => { @@ -84,13 +97,16 @@ fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { /// The decal's up direction: `up` when given, else the camera's (decals are placed upright on /// screen), or where the camera looks when that is along `normal` (a top face seen from the /// front: its far edge is up, as on a table). -fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { - if p.get("up").is_some() { - return vec3(p, "up").filter(|u| u.cross(normal).length_squared() > 1e-8).ok_or_else(|| bad(cmd, "`up` must be [x, y, z], not along the normal")); +fn decal_up(session: &Session, command: &str, params: &Value, normal: Vec3) -> Result { + if params.get("up").is_some() { + return vec3(params, "up") + .filter(|up| up.cross(normal).length_squared() > MIN_GIVEN_UP_CROSS_SQUARED) + .ok_or_else(|| bad(command, "`up` must be [x, y, z], not along the normal")); } - let to_world = s.camera.view().inverse(); + + let to_world = session.camera.view().inverse(); let up = to_world.transform_vector3(Vec3::Y); - Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) }) + Ok(if up.normalize_or_zero().cross(normal).length_squared() > MIN_CAMERA_UP_CROSS_SQUARED { up } else { to_world.transform_vector3(Vec3::NEG_Z) }) } /// The mirrored copy asked for by `symmetry` (x, y, z or off) and `symmetryFlip` (none, u or v), @@ -143,87 +159,197 @@ fn carried_up(s: &Session, from: (Vec3, Vec3), to: Vec3) -> Vec3 { Quat::from_rotation_arc(old_normal, new_normal) * old_up } -fn add(s: &mut Session, p: &Value) -> Result { - let cmd = "layer.add.decal"; - let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string(); - let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; +fn add(session: &mut Session, params: &Value) -> Result { + let command = "layer.add.decal"; + let image = strp(params, "image").ok_or_else(|| bad(command, "`image` is required"))?.to_string(); + let resource = session.images.get(&image).ok_or_else(|| bad(command, format!("no image resource `{image}` (import it first)")))?; let aspect = resource.width as f32 / resource.height.max(1) as f32; - let (center, normal, ts) = placement(s, cmd, p, s.ts(), false)?.ok_or_else(|| bad(cmd, "no placement"))?; + let (center, normal, texture_set) = placement(session, command, params, session.ts(), false)?.ok_or_else(|| bad(command, "no placement"))?; // None: the image masks a new fill layer - let target = match strp(p, "channel") { + let target = match strp(params, "channel") { Some("mask") => None, - _ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)), + _ => Some(channel_param(command, params, "channel")?.unwrap_or(Channel::BaseColor)), }; - let set_channels = s.doc.project.texture_set(ts)?.channel_list(); + let set_channels = session.doc.project.texture_set(texture_set)?.channel_list(); if let Some(channel) = target && !set_channels.contains(&channel) { - return Err(bad(cmd, format!("the texture set has no {} channel", channel.label()))); + return Err(bad(command, format!("the texture set has no {} channel", channel.label()))); } - let mesh_diagonal = mesh_size(s); + let mesh_diagonal = mesh_size(session); let default_height = mesh_diagonal * DEFAULT_HEIGHT; - let mut size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); - if boolp(p, "keepProportions") == Some(true) && p.get("size").is_some_and(Value::is_array) { + let mut size = size_param(params, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); + if boolp(params, "keepProportions") == Some(true) && params.get("size").is_some_and(Value::is_array) { size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); } let decal = Decal { center: center.to_array(), normal: normal.to_array(), - up: decal_up(s, cmd, p, normal)?.to_array(), + up: decal_up(session, command, params, normal)?.to_array(), size, - rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), + rotation: f32p(params, "rotation").unwrap_or(0.0).rem_euclid(FULL_TURN_DEGREES), offset: [0.0; 2], - flip: [boolp(p, "flipU").unwrap_or(false), boolp(p, "flipV").unwrap_or(false)], + flip: [boolp(params, "flipU").unwrap_or(false), boolp(params, "flipV").unwrap_or(false)], // By default it reaches half its larger side into the surface - depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), - symmetry: symmetry_param(cmd, p, None, s.mesh.bounds())?, + depth: f32p(params, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), + symmetry: symmetry_param(command, params, None, session.mesh.bounds())?, }; // A decal dropped on another texture set goes there and selects it, as a dropped material does - if ts != s.ts() { - crate::set_cmds::select_set(s, ts)?; + if texture_set != session.ts() { + crate::set_cmds::select_set(session, texture_set)?; } - let base = strp(p, "name") + let base = strp(params, "name") .map(str::to_string) .unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string()); - let name = s.doc.project.next_layer_name(ts, &base); - let (id, mask_effect) = s.edit("Add decal", |s| { - let id = s.doc.project.alloc_id(); + let name = session.doc.project.next_layer_name(texture_set, &base); + let (id, mask_effect) = session.edit("Add decal", |session| { + let id = session.doc.project.alloc_id(); let Some(channel) = target else { - let effect_id = s.doc.project.alloc_id(); + let effect_id = session.doc.project.alloc_id(); let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels); let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) })); + mask.effects.push(Effect::new( + effect_id, + EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::decal(decal), sampling: Default::default() }, + )); layer.mask = Some(mask); - crate::layer_cmds::insert_selected(s, layer)?; - s.target = StackTarget::Effect(effect_id); + crate::layer_cmds::insert_selected(session, layer)?; + session.target = StackTarget::Effect(effect_id); return Ok((id, Some(effect_id))); }; - let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() }; + let mut fill = Fill { projection: Projection::decal(decal), ..Fill::default() }; fill.sources.insert(channel, Source::image(image.clone())); - crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; + crate::layer_cmds::insert_selected(session, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; Ok((id, None)) })?; Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) })) } -/// The decal of fill layer `id`, or of mask fill effect `effect` when given -fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option) -> Result { - if let Some(effect) = effect { - return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { - Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), - _ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")), - }; +/// The projection of fill layer `id`, or of mask fill effect `effect` when given, with the frame it projects from: an axis planar is placed as the frame it already projects from (it reads images exactly as before), a turned or scaled projector is folded into its frame +fn framed(session: &Session, command: &str, id: LayerId, effect: Option) -> Result<(Projection, Decal)> { + let projection = stored_projection(session, command, id, effect)?; + if matches!(projection, Projection::Planar { placed: None, .. }) && placing_moves_pattern(stored_sources(session, id, effect).into_iter()) { + return Err(bad(command, "an axis planar reading a procedural pattern keeps its axis: placing its frame would move the pattern")); } - match &s.doc.project.layer(id)?.kind { - LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), - _ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")), + // A frame faces one way: culling read through an uneven or mirrored scale would hide other faces once the scale is in the frame (a placed frame keeps its edits that move no frame) + if matches!(projection, Projection::Planar { placed: None, .. }) && !culling_keeps_facing(projection) { + return Err(bad(command, UNFOLDABLE_CULLING)); + } + + let projection = placed_from_axis(projection, session.mesh.bounds()).unwrap_or_else(|| projection.clone()); + + // The frame moves as it lands: a projector's own turn and scale go into it first + let projection = folded(&projection).unwrap_or(projection); + let frame = projection + .frame() + .copied() + .ok_or_else(|| bad(command, "the projection has no frame: a planar or warp projection has one (layer.add.decal places one)"))?; + Ok((projection, frame)) +} + +/// Whether `projection`'s backface culling keeps its facing once its projector's turn and scale are in its frame +fn culling_keeps_facing(projection: &Projection) -> bool { + match projection { + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => culling_folds(projector), + _ => true, + } +} + +/// Why a projector whose backface culling cannot keep its facing in a frame is not moved, and the way out +const UNFOLDABLE_CULLING: &str = + "backface culling under an uneven or mirrored projector scale cannot move into a frame: even out the projector scale or turn backface culling off"; + +/// The projection fill layer `id`, or mask fill effect `effect` when given, holds +fn stored_projection<'a>(session: &'a Session, command: &str, id: LayerId, effect: Option) -> Result<&'a Projection> { + match effect { + Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { projection, .. }) => Ok(projection), + _ => Err(bad(command, "the effect is not a mask fill effect")), + }, + None => match &session.doc.project.layer(id)?.kind { + LayerKind::Fill(fill) => Ok(&fill.projection), + _ => Err(bad(command, "the layer is not a fill layer")), + }, + } +} + +/// The sources fill layer `id`, or mask fill effect `effect` when given, reads +fn stored_sources(session: &Session, id: LayerId, effect: Option) -> Vec<&Source> { + match effect { + Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { source, .. }) => vec![source], + _ => Vec::new(), + }, + None => match session.doc.project.layer(id).map(|layer| &layer.kind) { + Ok(LayerKind::Fill(fill)) => fill.sources.values().collect(), + _ => Vec::new(), + }, + } +} + +/// The image a decal projects: the mask fill effect's, or the fill layer's (the channel it was placed in) +fn placed_image(session: &Session, id: LayerId, effect: Option) -> Option { + let image_name = |source: &Source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }; + match effect { + Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { source, .. }) => image_name(source), + _ => None, + }, + None => match &session.doc.project.layer(id).ok()?.kind { + LayerKind::Fill(fill) => fill.sources.values().find_map(image_name), + _ => None, + }, + } +} + +/// `projection` with its frame where `frameOffset`, `frameRotation` and `frameScale` put it (None when none is given) +fn placed_as_shown(session: &Session, command: &str, params: &Value, projection: &Projection) -> Result> { + let fields = ["frameOffset", "frameRotation", "frameScale"]; + if fields.iter().all(|key| params.get(*key).is_none()) { + return Ok(None); + } + + let read = |key: &str| match params.get(key) { + None => Ok(None), + Some(_) => vec3(params, key).map(Some).ok_or_else(|| bad(command, format!("`{key}` must be [x, y, z]"))), + }; + let bounds = session.mesh.bounds(); + if !culling_keeps_facing(projection) { + return Err(bad(command, UNFOLDABLE_CULLING)); + } + + let mut shown = frame_placement(projection, bounds).ok_or_else(|| bad(command, "the frame is degenerate"))?; + if let Some(offset) = read("frameOffset")? { + shown.offset = offset.clamp(Vec3::splat(-MAX_FRAME_OFFSET), Vec3::splat(MAX_FRAME_OFFSET)).to_array(); + } + if let Some(rotation) = read("frameRotation")? { + shown.rotation = rotation.clamp(Vec3::splat(-FULL_TURN_DEGREES), Vec3::splat(FULL_TURN_DEGREES)).to_array(); + } + if let Some(scale) = read("frameScale")? { + shown.scale = scale.clamp(Vec3::splat(MIN_SIZE), Vec3::splat(MAX_SIZE)).to_array(); + } + placed(projection, &shown, bounds).map(Some).ok_or_else(|| bad(command, "that frame is degenerate")) +} + +/// How far from the mesh's centre `frameOffset` may put a frame, in mesh radii +const MAX_FRAME_OFFSET: f32 = 100.0; + +/// `projection` projecting from `frame`, its other settings kept +fn move_frame(projection: &mut Projection, frame: Decal) { + match projection { + Projection::Planar { placed: Some(placed), .. } => *placed = frame, + Projection::Warp { frame: warp, .. } => *warp = frame, + _ => {} } } @@ -261,10 +387,19 @@ fn set(session: &mut Session, params: &Value) -> Result { return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0))); } - let mut decal = decal_of(session, command, layer_id, effect)?; + let (mut projection, mut decal) = framed(session, command, layer_id, effect)?; let texture_set = session.doc.project.locate(layer_id).map(|(texture_set, _, _)| texture_set).ok_or_else(|| bad(command, "the decal has no texture set"))?; let mesh_diagonal = mesh_size(session); + if let Some(moved) = placed_as_shown(session, command, params, &projection)? { + projection = moved; + decal = projection.frame().copied().ok_or_else(|| bad(command, "the projection lost its frame"))?; + + // A reach from frameScale keeps the Projection Depth in the range every other path keeps + if let Projection::Warp { depth: warp_depth, .. } = &mut projection { + *warp_depth = warp_depth.clamp(0.0, MAX_PROJECTION_DEPTH); + } + } if let Some((center, normal, hit_set)) = placement(session, command, params, texture_set, true)? { // Selecting another set must not let this decal leave its layer's stack if hit_set != texture_set { @@ -282,7 +417,7 @@ fn set(session: &mut Session, params: &Value) -> Result { decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array(); } let keep = boolp(params, "keepProportions") == Some(true); - let ratio = decal.size[0] / decal.size[1].max(1e-6); + let ratio = decal.size[0] / decal.size[1].max(MIN_FRAME_SIDE); let aspect = if keep { image_aspect(session, layer_id, effect, strp(params, "image")).unwrap_or(ratio) } else { ratio }; if let Some(mut size) = size_param(params, aspect, mesh_diagonal).or_else(|| keep.then_some(decal.size)) { // A height sets the width through `aspect`; a pair or the current size sets the height from the width @@ -298,7 +433,7 @@ fn set(session: &mut Session, params: &Value) -> Result { decal.flip[1] = flip; } if let Some(rotation) = f32p(params, "rotation") { - decal.rotation = rotation.rem_euclid(360.0); + decal.rotation = rotation.rem_euclid(FULL_TURN_DEGREES); } if let Some(offset) = params.get("offset").and_then(Value::as_array) { let values: Vec = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect(); @@ -306,8 +441,13 @@ fn set(session: &mut Session, params: &Value) -> Result { decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)]; } - if let Some(depth) = f32p(params, "depth") { - decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); + let depth = f32p(params, "depth").map(|depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)); + + // A warp reaches by its Projection Depth (set below); its frame's own depth is unused, so it stays + if let Some(depth) = depth + && !matches!(projection, Projection::Warp { .. }) + { + decal.depth = depth; } decal.symmetry = symmetry_param(command, params, decal.symmetry, session.mesh.bounds())?; @@ -318,39 +458,56 @@ fn set(session: &mut Session, params: &Value) -> Result { return Err(bad(command, format!("no image resource `{name}`"))); } - session.edit("Edit decal", |session| { - if let Some(effect) = effect { - if let Some(EffectKind::Fill { source, projection }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { - *projection = Projection::Decal(decal); - if let Some(image) = image { - *source = Source::image(image); - } - } - } else if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind { - fill.projection = Projection::Decal(decal); + move_frame(&mut projection, decal); - // The new image goes where the decal's image is (the channel it was placed in) - let placed = fill.sources.values().find_map(|source| match source { - Source::Image { name, .. } => Some(name.clone()), - _ => None, - }); - match (image, placed) { - (Some(image), Some(placed)) => { - for source in fill.sources.values_mut() { - if let Source::Image { name, .. } = source - && *name == placed - { - name.clone_from(&image); - } - } - } - (Some(image), None) => { - fill.sources.insert(Channel::BaseColor, Source::image(image)); - } - (None, _) => {} - } - } - Ok(()) - })?; + // A warp reaches by its own Projection Depth, in lengths of the frame's longer side + if let (Some(depth), Projection::Warp { depth: warp_depth, .. }) = (depth, &mut projection) { + *warp_depth = (depth / longer_side(decal.size)).clamp(0.0, MAX_PROJECTION_DEPTH); + } + + // Nothing moved and the image is the one it shows: no undo step + let unchanged = *stored_projection(session, command, layer_id, effect)? == projection + && image.as_ref().is_none_or(|image| placed_image(session, layer_id, effect).as_ref() == Some(image)); + if !unchanged { + session.edit("Edit decal", |session| store_decal(session, layer_id, effect, projection, image))?; + } Ok(json!({ "layer": layer_id.0, "decal": decal })) } + +/// Store `projection` (and `image`, in the channel or mask it was placed in) on fill layer `layer_id`, or on mask fill effect `effect` when given +fn store_decal(session: &mut Session, layer_id: LayerId, effect: Option, projection: Projection, image: Option) -> Result<()> { + if let Some(effect) = effect { + if let Some(EffectKind::Fill { source, projection: stored, .. }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { + *stored = projection; + if let Some(image) = image { + *source = Source::image(image); + } + } + return Ok(()); + } + + let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind else { return Ok(()) }; + fill.projection = projection; + + // The new image goes where the decal's image is (the channel it was placed in) + let placed = fill.sources.values().find_map(|source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }); + match (image, placed) { + (Some(image), Some(placed)) => { + for source in fill.sources.values_mut() { + if let Source::Image { name, .. } = source + && *name == placed + { + name.clone_from(&image); + } + } + } + (Some(image), None) => { + fill.sources.insert(Channel::BaseColor, Source::image(image)); + } + (None, _) => {} + } + Ok(()) +} diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs new file mode 100644 index 00000000..71d0f051 --- /dev/null +++ b/crates/engine/src/warp_cmds.rs @@ -0,0 +1,68 @@ +//! Warp projections: the frame a new warp starts from, and Reset frame, which puts a warp's frame and corners back there + +use serde_json::Value; +use texturecraft_core::{Decal, Projection}; +use texturecraft_geom::Mesh; + +use crate::commands::{CommandSpec, bad, has_layer}; +use crate::layer_cmds::{fill_target, placement_mut}; +use crate::{Result, Session, cmd}; + +/// Reset frame's command id, the prefix of its errors +const RESET_FRAME: &str = "layer.fill.resetFrame"; + +pub fn specs() -> Vec { + vec![cmd!( + "layer.fill.resetFrame", + "Reset frame", + [], + None, + has_layer, + reset_frame + )] +} + +/// The frame a new warp projection starts from: around the whole mesh, seen from the front (+Z), up along +Y +pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal { + let (lo, hi) = mesh.bounds(); + let smallest = ((hi - lo).length() * SMALLEST_SIDE).max(f32::MIN_POSITIVE); + let size = [(hi.x - lo.x).max(smallest), (hi.y - lo.y).max(smallest)]; + Decal { + center: ((lo + hi) * 0.5).to_array(), + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size, + rotation: 0.0, + offset: [0.0; 2], + depth: 0.0, + symmetry: None, + flip: [false; 2], + } +} + +/// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame) +const SMALLEST_SIDE: f32 = 1e-3; + +fn reset_frame(s: &mut Session, p: &Value) -> Result { + let target = fill_target(s, p, RESET_FRAME)?; + let fitted = fitted_frame(&s.mesh); + let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { + return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); + }; + + // A frame already fitted with unpulled corners adds no undo step + if *frame == fitted && *corners == Projection::FRAME_CORNERS { + return Ok(Value::Null); + } + + s.edit("Reset frame", |s| { + let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else { + return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection")); + }; + + *frame = fitted; + *corners = Projection::FRAME_CORNERS; + Ok(()) + })?; + Ok(Value::Null) +} diff --git a/crates/ui-egui/src/warp_checker.rs b/crates/ui-egui/src/warp_checker.rs new file mode 100644 index 00000000..70421b23 --- /dev/null +++ b/crates/ui-egui/src/warp_checker.rs @@ -0,0 +1,169 @@ +//! The checker a warp preview bends into its frame: laid on the frame as the fill's Tiling, Rotation and Offset lay the image, so turning or tiling the image shows + +use egui::Pos2; +use texturecraft_engine::compose::pattern::FRAME_UV_CENTER; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::fill_pictures::PREVIEW_MIN_TILES; +use crate::placement::Placement; +use crate::projection_preview::CHECKER_CELLS; + +/// Most repeats drawn across the frame: beyond this the checker is too fine to read and too many cells to draw each frame +const MAX_TILES: f32 = 6.0; + +/// The checker cells inside a frame whose corners land at `quad` (top left, top right, bottom right, bottom left), each with whether it is a light cell: a cell's corners in image coordinates go back to the frame (undo the offset, the tiling, the turn), are cut to the frame and bent with its corners +pub(crate) fn warp_checker(quad: [Pos2; 4], placement: Placement) -> Vec<(Vec, bool)> { + let [top_left, top_right, bottom_right, bottom_left] = quad; + let at = |[u, v]: [f32; 2]| -> Pos2 { + let top = top_left + (top_right - top_left) * u; + let bottom = bottom_left + (bottom_right - bottom_left) * u; + top + (bottom - top) * v + }; + let tiling = placement.tiling.map(|tiles| if tiles.is_finite() { tiles.clamp(PREVIEW_MIN_TILES, MAX_TILES) } else { 1.0 }); + + // The checker repeats every tile, so only the offset within one tile matters (and the cell numbers stay small) + let offset = placement.offset.map(|offset| if offset.is_finite() { offset.rem_euclid(1.0) } else { 0.0 }); + let rotation = if placement.rotation.is_finite() { placement.rotation.rem_euclid(FULL_TURN_DEGREES) } else { 0.0 }; + let (sin, cos) = rotation.to_radians().sin_cos(); + let [middle_u, middle_v] = FRAME_UV_CENTER.to_array(); + + // The frame (0..1 across and down) → image coordinates in cells: turn round the frame's centre, tile, offset, as the compositor places a warp's image + let to_cells = |[u, v]: [f32; 2]| -> [f32; 2] { + let (u, v) = (u - middle_u, v - middle_v); + let (x, y) = (u * cos - v * sin + middle_u, u * sin + v * cos + middle_v); + [(x * tiling[0] + offset[0]) * CHECKER_CELLS, (y * tiling[1] + offset[1]) * CHECKER_CELLS] + }; + let to_frame = |[x, y]: [f32; 2]| -> [f32; 2] { + let (x, y) = ((x / CHECKER_CELLS - offset[0]) / tiling[0] - middle_u, (y / CHECKER_CELLS - offset[1]) / tiling[1] - middle_v); + [x * cos + y * sin + middle_u, -x * sin + y * cos + middle_v] + }; + let corners = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]].map(to_cells); + let low = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::INFINITY, f32::min).floor() as i32; + let high = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::NEG_INFINITY, f32::max).ceil() as i32; + let mut cells = Vec::new(); + + // One outline and one cutting buffer for every cell: only the drawn outlines are kept + let mut outline = Vec::with_capacity(CLIPPED_CORNERS_MAX); + let mut scratch = Vec::with_capacity(CLIPPED_CORNERS_MAX); + for x in low(0)..high(0) { + for y in low(1)..high(1) { + let (x0, y0) = (x as f32, y as f32); + outline.clear(); + outline.extend([[x0, y0], [x0 + 1.0, y0], [x0 + 1.0, y0 + 1.0], [x0, y0 + 1.0]].map(to_frame)); + clip_to_frame(&mut outline, &mut scratch); + if area(&outline) > MIN_CELL_AREA { + cells.push((outline.iter().copied().map(at).collect(), (x + y).rem_euclid(2) == 0)); + } + } + } + cells +} + +/// Most corners a cell keeps once cut: its four, plus one for each side of the frame that cuts it +const CLIPPED_CORNERS_MAX: usize = 8; + +/// Least share of the frame a cut cell must cover to be drawn (slivers left by rounding at the frame's sides are not) +const MIN_CELL_AREA: f32 = 1e-6; + +/// The area of polygon `outline` (shoelace) +fn area(outline: &[[f32; 2]]) -> f32 { + let twice: f32 = outline.iter().zip(outline.iter().cycle().skip(1)).map(|(a, b)| a[0] * b[1] - b[0] * a[1]).sum(); + twice.abs() * 0.5 +} + +/// Cuts convex polygon `polygon` (frame coordinates) to the frame's 0..1 square in place (Sutherland–Hodgman, one side at a time), `scratch` holding each side's cut +fn clip_to_frame(polygon: &mut Vec<[f32; 2]>, scratch: &mut Vec<[f32; 2]>) { + // Each side of the square: the axis it bounds, and whether points must stay below (1) or above (0) it + for (axis, bound, below) in [(0, 0.0, false), (0, 1.0, true), (1, 0.0, false), (1, 1.0, true)] { + let inside = |p: &[f32; 2]| if below { p[axis] <= bound } else { p[axis] >= bound }; + scratch.clear(); + for (point, next) in polygon.iter().zip(polygon.iter().cycle().skip(1)) { + let next = *next; + if inside(point) { + scratch.push(*point); + } + if inside(point) != inside(&next) { + let t = (bound - point[axis]) / (next[axis] - point[axis]); + scratch.push([point[0] + (next[0] - point[0]) * t, point[1] + (next[1] - point[1]) * t]); + } + } + std::mem::swap(polygon, scratch); + if polygon.is_empty() { + break; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::pos2; + + const QUAD: [Pos2; 4] = [pos2(0.0, 0.0), pos2(100.0, 0.0), pos2(100.0, 100.0), pos2(0.0, 100.0)]; + const STILL: Placement = Placement { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }; + + fn rounded(cells: &[(Vec, bool)]) -> Vec<(Vec<[i32; 2]>, bool)> { + cells.iter().map(|(outline, light)| (outline.iter().map(|p| [p.x.round() as i32, p.y.round() as i32]).collect(), *light)).collect() + } + + #[test] + fn an_untouched_image_shows_four_by_four_cells_filling_the_frame() { + let cells = warp_checker(QUAD, STILL); + assert_eq!(cells.len(), 16); + assert!(cells.iter().all(|(outline, _)| outline.len() == 4), "whole cells"); + assert_eq!(cells.iter().filter(|(_, light)| *light).count(), 8, "a checker"); + let area: f32 = cells.iter().map(|(outline, _)| (outline[2].x - outline[0].x).abs() * (outline[2].y - outline[0].y).abs()).sum(); + assert!((area - 100.0 * 100.0).abs() < 1.0, "they fill the frame: {area}"); + } + + #[test] + fn rotation_turns_the_checker_inside_the_frame() { + let still = rounded(&warp_checker(QUAD, STILL)); + let turned = warp_checker(QUAD, Placement { rotation: 30.0, ..STILL }); + assert_ne!(rounded(&turned), still, "a turned image turns the checker"); + assert!(turned.iter().any(|(outline, _)| outline.len() != 4), "cells cut by the frame's sides"); + assert!( + turned.iter().flat_map(|(outline, _)| outline).all(|p| (-0.01..=100.01).contains(&p.x) && (-0.01..=100.01).contains(&p.y)), + "kept inside the frame" + ); + assert_eq!(rounded(&warp_checker(QUAD, Placement { rotation: 360.0, ..STILL })), still, "a full turn looks unturned"); + assert_ne!(rounded(&warp_checker(QUAD, Placement { tiling: [2.0, 2.0], ..STILL })), still, "tiling shows"); + assert_ne!(rounded(&warp_checker(QUAD, Placement { offset: [0.1, 0.0], ..STILL })), still, "offset shows"); + } + + /// The checker turns round the frame's centre, as the compositor turns a warp's image: a half turn maps the checker onto itself, mirrored through the centre + #[test] + fn rotation_turns_the_checker_round_the_frame_centre() { + // A tiling whose cells do not divide the frame evenly: a turn round the top left would cut it elsewhere + let off_center = Placement { tiling: [0.7, 0.7], offset: [0.1, 0.05], ..STILL }; + let still = rounded(&warp_checker(QUAD, off_center)); + let half_turn = Placement { rotation: 180.0, ..off_center }; + let turned: Vec<_> = rounded(&warp_checker(QUAD, half_turn)) + .into_iter() + .map(|(outline, light)| (outline.into_iter().map(|[x, y]| [100 - x, 100 - y]).collect::>(), light)) + .collect(); + let corners = |cells: &[(Vec<[i32; 2]>, bool)]| { + let mut points: Vec<[i32; 2]> = cells.iter().flat_map(|(outline, _)| outline.iter().copied()).collect(); + points.sort_unstable(); + points.dedup(); + points + }; + assert_eq!(corners(&turned), corners(&still), "half turned round the centre: the same cut lines, mirrored through it"); + } + + #[test] + fn hostile_placements_draw_a_bounded_checker() { + // The most cells a turned frame spans along an axis: its diagonal at the finest tiling, rounded out at both ends + let cells_per_axis = (MAX_TILES * CHECKER_CELLS * std::f32::consts::SQRT_2).ceil() + 1.0; + let most_cells = (cells_per_axis * cells_per_axis) as usize; + for placement in [ + Placement { tiling: [f32::NAN, 1e9], ..STILL }, + Placement { rotation: f32::INFINITY, ..STILL }, + Placement { offset: [f32::NAN, 1e30], ..STILL }, + Placement { tiling: [0.0, -5.0], ..STILL }, + ] { + let cells = warp_checker(QUAD, placement); + assert!(cells.len() <= most_cells, "{placement:?}: {} cells", cells.len()); + } + } +} From 80072b2b050d01991d2267d2a3534af2fc8a7155 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 011/153] Panels: one header bar per docked panel, its close button and the group tab boxes --- crates/ui-egui/src/docking.rs | 171 ++++++++++--- crates/ui-egui/src/docking/header_band.rs | 60 +++++ crates/ui-egui/src/docking/shown_group_tab.rs | 102 ++++++++ crates/ui-egui/src/property_sheet/mod.rs | 8 + .../src/property_sheet/section_tabs.rs | 19 ++ crates/ui-egui/tests/it/panel_header.rs | 235 ++++++++++++++++++ crates/ui-egui/tests/it/rail.rs | 33 +-- crates/ui-egui/tests/it/settings_window.rs | 4 +- crates/ui-egui/tests/it/split_divider.rs | 25 +- crates/ui-egui/tests/ui_snapshots.rs | 59 +++++ 10 files changed, 652 insertions(+), 64 deletions(-) create mode 100644 crates/ui-egui/src/docking/header_band.rs create mode 100644 crates/ui-egui/src/docking/shown_group_tab.rs create mode 100644 crates/ui-egui/src/property_sheet/mod.rs create mode 100644 crates/ui-egui/src/property_sheet/section_tabs.rs create mode 100644 crates/ui-egui/tests/it/panel_header.rs diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index d779bf77..b4f64ad4 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -12,7 +12,7 @@ use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement}; use craft_ui::layout::{SplitAxis, SplitSize}; -use egui::{Id, Margin, RichText, Ui, vec2}; +use egui::{Id, Margin, RichText, Ui, Vec2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -20,6 +20,11 @@ use crate::TextureCraftApp; use crate::i18n::tr; use crate::theme::Tokens; +mod header_band; +mod shown_group_tab; + +pub(crate) use shown_group_tab::HEADER_TITLE_LEFT; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Panel { Viewport, @@ -160,7 +165,9 @@ pub fn default_workspace() -> Workspace { const ASSETS_SPLIT_RATIO: f32 = 0.16; const VIEWPORT_SPLIT_RATIO: f32 = 0.80; const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; - const LAYERS_SPLIT_RATIO: f32 = 0.57; + + // Layers' share under the texture sets: Properties' 69% shows a fill down to its channels, Layers keeps three rows + const LAYERS_SPLIT_RATIO: f32 = 0.31; let column = split( SplitAxis::Vertical, @@ -412,15 +419,17 @@ const TAB_TEXT_SIZE: f32 = 12.5; /// Narrowest panel tab, in points const MIN_TAB_WIDTH: f32 = 54.0; -/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill +/// The dock look: every panel group is a card under one chrome-coloured header bar, names in capitals at the left, a close × at the right fn style(ui: &Ui, tokens: &Tokens) -> DockStyle { let mut dock_style = DockStyle::from_ui(ui); dock_style.gap = f32::from(crate::theme::GUTTER); dock_style.min_pane = MIN_PANE_EXTENT; dock_style.background = tokens.panel; - dock_style.tab_background = tokens.panel; - dock_style.active_background = tokens.button; + dock_style.tab_background = tokens.chrome; + + // The shown and the hovered tab keep the bar's colour; their names brighten instead + dock_style.active_background = tokens.chrome; dock_style.text = tokens.text_strong; dock_style.inactive_text = tokens.text_dim; dock_style.border = egui::Stroke::NONE; @@ -468,7 +477,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens }); + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, style: style.clone() }); crate::rail_popup::hand_drag_to_dock(&context, area_id()); // After the dock, which records the viewport the popup reaches into, and before a changed layout returns early @@ -491,15 +500,51 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// Size of the panel names on a header bar +const HEADER_TITLE_SIZE: f32 = 12.0; + +/// Side of the close × at the right end of a header bar +const HEADER_CLOSE_SIZE: f32 = 22.0; + +/// Room right of the close × button, so its glyph ends where the Properties controls end (side padding plus scroll bar gutter) +const HEADER_CLOSE_RIGHT_MARGIN: f32 = 18.0; + +/// Whether a docked group's header bar ends in a close × (floating windows have one on their title bar; the viewport never closes) +fn header_closes(active: &Panel, floating: bool) -> bool { + !floating && permissions(active).closable +} + /// The panels' contents, names and limits for the dock area struct Panels<'a> { app: &'a mut TextureCraftApp, tokens: Tokens, + style: DockStyle, } /// Room between a panel's edges and its contents const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); +/// Narrowest Properties panel and so its dock column: the 300 point design width plus the solid scroll bar; narrower, the 3D projection settings' X, Y, Z fields (the widest row) overlap +pub const PROPERTIES_MIN_WIDTH: f32 = 310.0; + +/// Least size of a docked or floating panel other than the 3D view and Properties +const PANEL_MIN_SIZE: Vec2 = vec2(120.0, 60.0); + +/// Least size of the 3D view +const VIEWPORT_MIN_SIZE: Vec2 = vec2(200.0, 150.0); + +/// Size a panel opens at when it floats +const FLOATING_SIZE: Vec2 = vec2(300.0, 380.0); + +/// Least size of `panel`, docked or floating; a dock column or split stops shrinking at its panels' largest +fn min_size(panel: Panel) -> Vec2 { + match panel { + Panel::Viewport => VIEWPORT_MIN_SIZE, + Panel::Properties => vec2(PROPERTIES_MIN_WIDTH, PANEL_MIN_SIZE.y), + _ => PANEL_MIN_SIZE, + } +} + /// The body of every panel except the viewport, in the dock or on the rail pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { // No project open: the library and the log work, the other panels about a project stay empty @@ -508,7 +553,9 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { return; } - egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel { + // Properties draws full-width bands and tabs, so it keeps its own margins + let margin = if panel == Panel::Properties { Margin::ZERO } else { PANEL_BODY_MARGIN }; + egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), @@ -532,15 +579,16 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { impl DockContent for Panels<'_> { fn body(&mut self, ui: &mut Ui, panel: &Panel) { - let app = &mut *self.app; if *panel == Panel::Viewport { crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); - crate::viewport::central(app, ui); + crate::viewport::central(self.app, ui); return; } - panel_body(app, ui, *panel); + // Before the rows, which draw over the foot of the shown tab's box + self.paint_shown_group_tab(ui, *panel); + panel_body(self.app, ui, *panel); } fn logical_label(&self, panel: &Panel) -> String { @@ -550,8 +598,58 @@ impl DockContent for Panels<'_> { } } - fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { - RichText::new(logical).font(font.clone()).color(color).into() + fn label(&mut self, ui: &Ui, panel: &Panel, logical: &str, _font: &egui::FontId, color: egui::Color32) -> egui::WidgetText { + // Capitals on the bar only: menus and screen readers keep the logical name + let name = logical.to_uppercase(); + let font = crate::theme::semibold(HEADER_TITLE_SIZE); + + // Menus list the panels by these names too, in popups; only a header bar's names, docked or floating, centre on its band + if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) { + return RichText::new(name).font(font).color(color).into(); + } + + header_band::header_name(ui, &name, font, color, self.header_lift(*panel)).into() + } + + fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { + if header_closes(active, floating) { + HEADER_CLOSE_SIZE + HEADER_CLOSE_RIGHT_MARGIN + } else if redocks(panels, active, floating) { + DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN + } else { + 0.0 + } + } + + /// A docked group's bar ends in its close ×; a rail panel floating on its own carries the Dock button that sends it back to the rail + fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { + if redocks(panels, active, floating) { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { + self.app.ui.dock.close(*active); + } + }); + return; + } + + if !header_closes(active, floating) { + return; + } + + // On the names' line: the middle of the header band + let rect = ui.max_rect(); + let button = egui::Rect::from_center_size( + egui::pos2(rect.right() - HEADER_CLOSE_RIGHT_MARGIN - HEADER_CLOSE_SIZE / 2.0, rect.center().y - self.header_lift(*active)), + vec2(HEADER_CLOSE_SIZE, HEADER_CLOSE_SIZE), + ); + let clicked = ui + .scope_builder(egui::UiBuilder::new().max_rect(button), |ui| { + crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close Panel"), false, HEADER_CLOSE_SIZE).clicked() + }) + .inner; + if clicked { + self.app.ui.dock.close(*active); + } } fn permissions(&self, panel: &Panel) -> Permissions { @@ -559,29 +657,11 @@ impl DockContent for Panels<'_> { } fn limits(&self, panel: &Panel) -> PanelLimits { - let min = if *panel == Panel::Viewport { vec2(200.0, 150.0) } else { vec2(120.0, 60.0) }; - PanelLimits { min, ..PanelLimits::default() } + PanelLimits { min: min_size(*panel), ..PanelLimits::default() } } - fn floating_size(&self, _panel: &Panel) -> Option { - Some(vec2(300.0, 380.0)) - } - - fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 { - if redocks(panels, active, floating) { DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN } else { 0.0 } - } - - /// A rail panel floating on its own carries the Dock button that sends it back to the rail - fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) { - if !redocks(panels, active, floating) { - return; - } - - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() { - self.app.ui.dock.close(*active); - } - }); + fn floating_size(&self, panel: &Panel) -> Option { + Some(FLOATING_SIZE.max(min_size(*panel))) } } @@ -614,6 +694,31 @@ mod tests { assert_eq!(panels_of(&w), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); } + #[test] + fn the_default_right_column_gives_properties_about_two_thirds_under_the_texture_sets() { + let workspace = default_workspace(); + let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_ref() else { panic!("assets | rest") }; + let Node::Split { second: column, .. } = right.as_ref() else { panic!("viewport | right column") }; + let Node::Split { second: below_sets, .. } = column.as_ref() else { panic!("texture sets | rest") }; + let Node::Split { size: SplitSize::Ratio(layers), first, second, .. } = below_sets.as_ref() else { panic!("layers | properties") }; + assert!(matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.first() == Some(&Panel::Layers))); + assert!(matches!(second.as_ref(), Node::Tabs { panels, .. } if panels == &[Panel::Properties])); + let properties = 1.0 - layers; + assert!((2.0 / 3.0..0.7).contains(&properties), "Properties takes about 69% of the column, at least two thirds: {properties}"); + } + + #[test] + fn a_saved_split_keeps_its_own_share() { + let mut workspace = default_workspace(); + let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_mut() else { panic!("assets | rest") }; + let Node::Split { second: column, .. } = right.as_mut() else { panic!("viewport | right column") }; + let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets | rest") }; + let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") }; + *size = SplitSize::Ratio(0.57); + let back = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged"); + } + #[test] fn default_dock_round_trips() { let dock = Dock::default(); diff --git a/crates/ui-egui/src/docking/header_band.rs b/crates/ui-egui/src/docking/header_band.rs new file mode 100644 index 00000000..95dcdeec --- /dev/null +++ b/crates/ui-egui/src/docking/header_band.rs @@ -0,0 +1,60 @@ +//! A docked header's band: the tab strip plus the gutter above it, less a hairline of separation, with the names' capitals centred on it + +use craft_ui::docking::{Layout, Node}; +use craft_ui::layout::SplitAxis; +use egui::text::{LayoutJob, TextFormat}; +use egui::{Align, Color32, FontId, Ui}; + +use super::Panel; + +/// Gutter between two stacked panels left showing between the upper panel and the header band under it, as the reference keeps a dark line there +const PANEL_SEPARATION: f32 = 2.0; + +/// How far a header under another panel reaches above its tab strip: the gutter between them, less the separation +pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - PANEL_SEPARATION; + +/// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none +pub(super) fn under_a_panel(layout: &Layout, panel: Panel) -> bool { + let Some(root) = &layout.root else { return false }; + let mut nodes: Vec<(&Node, bool)> = vec![(root, false)]; + while let Some((node, below)) = nodes.pop() { + match node { + Node::Split { axis, first, second, .. } => { + nodes.push((first, below)); + nodes.push((second, below || *axis == SplitAxis::Vertical)); + } + Node::Tabs { panels, .. } if panels.contains(&panel) => return below, + Node::Dock { columns, .. } => { + for column in columns { + if let Some(index) = column.groups.iter().position(|group| group.panels.contains(&panel)) { + return below || index > 0; + } + } + } + _ => {} + } + } + + false +} + +/// `name` laid out so that, centred as the dock centres every name, its capitals' middle sits `lift` above the strip's (a galley's height counts descenders) +pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift: f32) -> LayoutJob { + let format = TextFormat { font_id: font, color, valign: Align::TOP, ..Default::default() }; + let mut job = LayoutJob::single_section(name.to_owned(), format); + let galley = ui.painter().layout_job(job.clone()); + + // The first capital's ink; a name without one (a script without capitals) keeps the galley's middle + let capital = galley.rows.first().and_then(|row| row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase()).map(|glyph| (row.pos.y, glyph))); + let ink_middle = capital.map_or(galley.size().y / 2.0, |(row_top, glyph)| row_top + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0); + + // Room below the name raises it when centred, room above lowers it + let shift = ink_middle - galley.size().y / 2.0 + lift; + if shift < 0.0 + && let Some(section) = job.sections.first_mut() + { + section.format.valign = Align::BOTTOM; + } + job.first_row_min_height = galley.size().y + 2.0 * shift.abs(); + job +} diff --git a/crates/ui-egui/src/docking/shown_group_tab.rs b/crates/ui-egui/src/docking/shown_group_tab.rs new file mode 100644 index 00000000..61f5d4e0 --- /dev/null +++ b/crates/ui-egui/src/docking/shown_group_tab.rs @@ -0,0 +1,102 @@ +//! The shown tab of a docked panel group, drawn as the Properties section tabs draw theirs: a raised box joined to the panel's body + +use craft_ui::docking::{DockContent, Layout, Node}; +use egui::text::TextWrapping; +use egui::{Rect, Ui, pos2}; + +use super::header_band::{HEADER_RISE, header_name, under_a_panel}; +use super::{HEADER_TITLE_SIZE, Panel, Panels}; +use crate::property_sheet::{full_height_tab_rect, shown_tab_box}; +use crate::theme::semibold; + +/// Room the dock leaves around a tab's name, half on each side (craft-ui's dock renderer keeps its own copy private) +const DOCK_TAB_PADDING: f32 = 24.0; + +/// From a panel's left edge to its header's name +pub(crate) const HEADER_TITLE_LEFT: f32 = DOCK_TAB_PADDING / 2.0; + +/// Width of the dock's "…" button for the tabs that do not fit (private in craft-ui's dock renderer as well) +const OVERFLOW_WIDTH: f32 = 22.0; + +/// Room between a tab's box and its neighbouring tabs; the first tab's box starts on the panel's left edge +const BOX_INSET: f32 = 4.0; + +/// The panels of the group holding `panel` and whether that group floats; a collapsed stack has no tabs +fn group_of(layout: &Layout, panel: Panel) -> Option<(&[Panel], bool)> { + let docked = layout.root.iter().map(|root| (root, false)); + let floating = layout.floating.iter().map(|window| (&window.root, true)); + let mut nodes: Vec<(&Node, bool)> = docked.chain(floating).collect(); + while let Some((node, floats)) = nodes.pop() { + match node { + Node::Split { first, second, .. } => { + nodes.push((first, floats)); + nodes.push((second, floats)); + } + Node::Tabs { panels, .. } if panels.contains(&panel) => return Some((panels, floats)), + Node::Dock { columns, .. } => { + let group = columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)); + if let Some(group) = group { + return Some((&group.panels, floats)); + } + } + _ => {} + } + } + None +} + +impl Panels<'_> { + /// How far `panel`'s header band reaches above its tab strip: the gutter above it, under another panel + fn header_rise(&self, panel: Panel) -> f32 { + if under_a_panel(&self.app.ui.dock.workspace.layout, panel) { HEADER_RISE } else { 0.0 } + } + + /// How far `panel`'s header name sits above its tab strip's middle: on its header band's middle + pub(super) fn header_lift(&self, panel: Panel) -> f32 { + self.header_rise(panel) / 2.0 + } + + /// Over the tab the dock drew for `panel`, the panel shown in its group, paints the section tabs' raised box and the name again; a panel alone keeps its plain header. `ui` is the panel's body, right under the strip + pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) { + let Some((panels, floating)) = group_of(&self.app.ui.dock.workspace.layout, panel) else { return }; + if panels.len() < 2 { + return; + } + + let Some(shown) = panels.iter().position(|member| *member == panel) else { return }; + + // The dock's own tab layout: names at their natural width, shrunk or moved to "…" when the strip is short + let body = ui.max_rect(); + let strip = Rect::from_min_max(pos2(body.left(), body.top() - self.style.tab_height), pos2(body.right(), body.top())); + let band = Rect::from_x_y_ranges(strip.x_range(), strip.top() - self.header_rise(panel)..=strip.bottom()); + let font = semibold(HEADER_TITLE_SIZE); + let names: Vec = panels.iter().map(|member| self.logical_label(member).to_uppercase()).collect(); + let natural: Vec = + names.iter().map(|name| ui.painter().layout_no_wrap(name.clone(), font.clone(), self.style.text).size().x + DOCK_TAB_PADDING).collect(); + let header = self.group_header_width(panels, &panel, floating, strip.width()).clamp(0.0, strip.width()); + let available = (strip.width() - header - self.style.drag_bar_width).max(0.0); + let fit = craft_ui::tabs::fit(&natural, shown, available, self.style.min_tab_width, OVERFLOW_WIDTH); + let mut left = strip.left(); + for (index, width) in fit.shown { + if index != shown { + left += width; + continue; + } + + // The body's clip stops at the strip, which the box rises into up to the band's top + let clip = ui.clip_rect(); + let mut painter = ui.painter().clone(); + painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band.top()..=clip.bottom())); + let box_left = if left > strip.left() { left + BOX_INSET } else { left }; + shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, left + width - BOX_INSET)); + + let Some(name) = names.get(index) else { return }; + let mut job = header_name(ui, name, font, self.style.text, self.header_lift(panel)); + job.wrap = TextWrapping::truncate_at_width((width - DOCK_TAB_PADDING).max(0.0)); + let galley = painter.layout_job(job); + let at = pos2(left + HEADER_TITLE_LEFT, strip.center().y - galley.size().y / 2.0); + painter.galley(at, galley, self.style.text); + return; + } + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs new file mode 100644 index 00000000..53afe419 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -0,0 +1,8 @@ +//! The Properties panel's rows, groups and controls, shared by every panel so they line up + +mod section_tabs; + +pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; + +/// Side padding: every row starts and ends this far inside the panel +pub(crate) const PAD: f32 = 12.0; diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs new file mode 100644 index 00000000..5b7d6187 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -0,0 +1,19 @@ +use egui::{CornerRadius, Painter, Rect, pos2}; + +use crate::theme::Tokens; + +/// The chosen tab starts this far below the strip's top and reaches this far into the panel +const TAB_BELOW: f32 = 6.0; + +/// Corner rounding of the chosen tab +pub(crate) const TAB_ROUNDING: u8 = 5; + +/// A tab from `left` to `right` filling `strip`'s whole height and reaching as far into the panel as a section tab: a docked group's shown tab +pub(crate) fn full_height_tab_rect(strip: Rect, left: f32, right: f32) -> Rect { + Rect::from_min_max(pos2(left, strip.top()), pos2(right, strip.bottom() + TAB_BELOW)) +} + +/// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip +pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { + painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); +} diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs new file mode 100644 index 00000000..8a9caed5 --- /dev/null +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -0,0 +1,235 @@ +//! Every docked panel group sits under one header bar: its names at the left, the shown one raised as a box when the group has several, a close × at the right + +use craft_ui::docking::{Action, Placement}; +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, panel_close_button}; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// A floating window over the viewport, `[x, y, width, height]` +const FLOATING_RECT: [f32; 4] = [600.0, 200.0, 320.0, 400.0]; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + 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(STARTUP_FRAMES); + + harness +} + +/// The rect of the tab whose name starts with `name` +fn tab_rect(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Rect { + harness + .get_all_by_role(Role::Tab) + .find(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with(name))) + .map(|tab| tab.rect()) + .unwrap_or_else(|| panic!("a {name} tab")) +} + +#[test] +fn every_docked_panel_header_ends_in_its_own_close_button() { + let harness = app(); + let names = ["Assets", "Texture Sets", "Layers", "Properties - "]; + let tabs: Vec = names.iter().map(|name| tab_rect(&harness, name)).collect(); + for (name, tab) in names.iter().zip(&tabs) { + let close = panel_close_button(&harness, *tab); + + // No other group's tab between a tab and its close button: the button is on its own bar + let between = tabs.iter().any(|other| other.y_range().contains(close.center().y) && other.min.x > tab.max.x && other.max.x < close.min.x); + assert!(!between, "{name} has no close button on its own header"); + } +} + +#[test] +fn the_header_close_button_closes_its_panel() { + let mut harness = app(); + assert!(harness.state().ui.dock.is_visible(Panel::Properties)); + let close = panel_close_button(&harness, tab_rect(&harness, "Properties - ")); + click_at(&mut harness, close.center()); + + assert!(!harness.state().ui.dock.is_open(Panel::Properties)); + assert!(harness.state().ui.dock.is_visible(Panel::Layers), "only the panel under the bar closes"); +} + +/// With an effect selected the Properties header names its type, not the effect's own name (every filter reads "Filter") +#[test] +fn the_properties_header_names_the_selected_effects_type() { + let mut harness = app(); + let session = &mut harness.state_mut().session; + let layer = texturecraft_engine::execute(session, "layer.add.fill", &serde_json::Value::Null).unwrap()["layer"].as_u64().unwrap(); + let blur = texturecraft_engine::execute(session, "effect.add.filter", &serde_json::json!({"layer": layer, "target": "content", "filter": "blur"})).unwrap() + ["effect"] + .as_u64() + .unwrap(); + texturecraft_engine::execute(session, "effect.set", &serde_json::json!({"effect": blur, "name": "Soften edges"})).unwrap(); + texturecraft_engine::execute(session, "layer.select", &serde_json::json!({"layer": layer, "target": blur})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + tab_rect(&harness, "Properties - Filter"); + + let level = texturecraft_engine::execute(&mut harness.state_mut().session, "effect.add.levels", &serde_json::json!({"layer": layer, "target": "content"})) + .unwrap()["effect"] + .as_u64() + .unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &serde_json::json!({"layer": layer, "target": level})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + tab_rect(&harness, "Properties - Levels"); +} + +/// How far a header under another panel reaches above its tab strip: the 6 px gutter less a 2 px separation (docking/header_band.rs) +const HEADER_RISE: f32 = 4.0; + +/// Room between a later tab's box and its tab's left edge (docking/shown_group_tab.rs, private to the crate) +const BOX_INSET: f32 = 4.0; + +/// Rounded boxes painted this frame over `tab` whose top is `rise` above it: the raised box of a shown tab +fn tab_boxes(harness: &Harness<'_, TextureCraftApp>, tab: egui::Rect, rise: f32) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) => { + let rises = (rect.rect.top() - (tab.top() - rise)).abs() < 0.5; + let raised = rises && rect.corner_radius != egui::CornerRadius::ZERO && tab.x_range().contains(rect.rect.center().x); + raised.then_some(rect.rect) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_groups_shown_tab_rises_as_a_box_and_the_others_and_a_lone_panels_do_not() { + let mut harness = app(); + let layers = tab_rect(&harness, "Layers"); + let settings = tab_rect(&harness, "Texture Set Settings"); + + assert_eq!(tab_boxes(&harness, layers, HEADER_RISE).len(), 1, "the shown Layers tab has its box, from the top of its header band"); + assert_eq!(tab_boxes(&harness, settings, HEADER_RISE).len(), 0, "the hidden tab is its name only"); + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Properties - "), HEADER_RISE).len(), 0, "a panel alone keeps its plain header"); + + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Texture Set Settings"), HEADER_RISE).len(), 1, "the box goes with the shown tab"); + assert_eq!(tab_boxes(&harness, tab_rect(&harness, "Layers"), HEADER_RISE).len(), 0); +} + +#[test] +fn the_first_tabs_box_starts_on_the_panels_edge_and_a_later_tabs_box_keeps_its_inset() { + let mut harness = app(); + let layers = tab_rect(&harness, "Layers"); + let boxes = tab_boxes(&harness, layers, HEADER_RISE); + assert!(!boxes.is_empty(), "the shown Layers tab has its box"); + assert!(boxes.iter().all(|shown| (shown.left() - layers.left()).abs() < 0.5), "{boxes:?} starts on the panel's left edge {}", layers.left()); + + let settings = tab_rect(&harness, "Texture Set Settings"); + + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + let boxes = tab_boxes(&harness, settings, HEADER_RISE); + assert!(!boxes.is_empty(), "the shown Texture Set Settings tab has its box"); + assert!(boxes.iter().all(|shown| (shown.left() - (settings.left() + BOX_INSET)).abs() < 0.5), "{boxes:?} keeps its air from the Layers tab"); +} + +/// The middle of the first capital's ink in each painted text reading `name` +fn capital_middles(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == name => { + let row = text.galley.rows.first()?; + let glyph = row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase())?; + Some(text.pos.y + row.pos.y + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0) + } + _ => None, + }) + .collect() +} + +/// Names' capitals and the close × share the header band's middle: the tab strip plus, under another panel, the gutter above it less the separation +#[test] +fn header_names_capitals_and_close_buttons_sit_on_the_header_bands_middle() { + let harness = app(); + let headers = [ + ("Texture Sets", "TEXTURE SETS", 0.0), + ("Layers", "LAYERS", HEADER_RISE), + ("Texture Set Settings", "TEXTURE SET SETTINGS", HEADER_RISE), + ("Properties - ", "PROPERTIES - PAINT", HEADER_RISE), + ]; + for (tab, name, rise) in headers { + let tab = tab_rect(&harness, tab); + let middle = (tab.top() - rise + tab.bottom()) / 2.0; + let capitals = capital_middles(&harness, name); + assert!(!capitals.is_empty(), "{name} is painted"); + assert!(capitals.iter().all(|capital| (capital - middle).abs() < 0.75), "{name}'s capitals at {capitals:?}, its band's middle at {middle}"); + } + + let properties = tab_rect(&harness, "Properties - "); + let close = panel_close_button(&harness, properties); + let middle = (properties.top() - HEADER_RISE + properties.bottom()) / 2.0; + assert!((close.center().y - middle).abs() < 0.5, "the close × at {}, the band's middle at {middle}", close.center().y); +} + +/// A floating group's names sit on one line: the shown name, painted again over its tab, and the dimmed one beside it (the dimmed one kept its galley's middle) +#[test] +fn a_floating_groups_names_share_one_line() { + let mut harness = app(); + let mut workspace = harness.state().ui.dock.workspace().clone(); + let actions = [ + Action::Float { panel: Panel::Properties, rect: FLOATING_RECT }, + Action::Move { panel: Panel::TextureSetSettings, anchor: Panel::Properties, placement: Placement::Tab { before: None } }, + Action::Activate { panel: Panel::Properties }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + harness.run_steps(SETTLE_FRAMES); + + let shown = capital_middles(&harness, "PROPERTIES - PAINT"); + let dimmed = capital_middles(&harness, "TEXTURE SET SETTINGS"); + assert!(!shown.is_empty() && !dimmed.is_empty(), "both names are painted"); + assert!(shown.iter().chain(&dimmed).all(|capital| (capital - shown[0]).abs() < 0.5), "the shown name's capitals at {shown:?}, the other's at {dimmed:?}"); +} + +/// The tab menu's panel names keep their plain layout: only the header bar pads a name to centre its capitals on the band +#[test] +fn a_tab_menus_panel_names_keep_their_plain_layout() { + let mut harness = app(); + let properties = tab_rect(&harness, "Properties - "); + let button = egui::PointerButton::Secondary; + harness.hover_at(properties.center()); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: properties.center(), button, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(SETTLE_FRAMES); + + let move_to = harness.get_by_role_and_label(Role::Button, "Move Panel to Group").rect(); + harness.hover_at(move_to.center()); + harness.run_steps(SETTLE_FRAMES); + + let entry = harness.get_by_role_and_label(Role::Button, "Layers").rect(); + let padded: Vec = harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "LAYERS" && entry.contains(text.pos) => Some(text.galley.job.first_row_min_height), + _ => None, + }) + .collect(); + assert!(!padded.is_empty(), "the menu paints the Layers entry"); + assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); +} diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index a994bcb3..30f3a153 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -7,18 +7,13 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::ViewLayout; +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at}; + const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); /// The rail is the last 38 points of the window; the popup's own buttons sit left of it const RAIL_LEFT_EDGE: f32 = WINDOW_SIZE.x - 38.0; -// Small texture and bake sizes keep the sample session fast; the rail 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; - /// Where a drag out of the popup ends: in the viewport, clear of every panel const INTO_THE_VIEWPORT: egui::Vec2 = egui::vec2(-500.0, 100.0); @@ -28,9 +23,6 @@ const DRAG_STEPS: usize = 6; /// Frames between a drag's events: the press must land before the moves, and each move be seen const FRAMES_PER_DRAG_EVENT: usize = 2; -/// Frames for a click to reach the rail, the popup and the dock -const SETTLE_FRAMES: usize = 3; - // A setting only Shader Settings shows, and one only Display Settings shows const SHADER_SETTING: &str = "Index of refraction"; const DISPLAY_SETTING: &str = "Environment Opacity"; @@ -60,16 +52,8 @@ fn rail_icon<'h>(harness: &'h Harness<'_, TextureCraftApp>, name: &str) -> Optio } fn click_rail(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { - rail_icon(harness, name).expect("the panel's icon on the rail").click(); - harness.run_steps(SETTLE_FRAMES); -} - -fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { - harness.hover_at(position); - harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.run_steps(1); - harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(SETTLE_FRAMES); + let at = rail_icon(harness, name).expect("the panel's icon on the rail").rect().center(); + click_at(harness, at); } /// Drag with the primary button from `from` to `to` in a few moves @@ -197,9 +181,12 @@ fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { let mut harness = app(); click_rail(&mut harness, "Log"); - let title = popup_title(&harness, "Log").center(); - let properties_tab = harness.get_by_label("Properties - Paint").rect().center(); - drag(&mut harness, title, properties_tab); + let title = popup_title(&harness, "Log"); + + // The popup covers the Properties strip and stays put while dragged: drop on the Texture Sets strip above it + let texture_sets_tab = harness.get_by_label("Texture Sets").rect(); + assert!(texture_sets_tab.bottom() < title.top(), "the Texture Sets strip {texture_sets_tab:?} is under the popup at {title:?}"); + drag(&mut harness, title.center(), texture_sets_tab.center()); let layout = &harness.state().ui.dock.workspace().layout; assert!(layout.contains(&Panel::Log) && !layout.floating.iter().any(|window| window.contains(&Panel::Log)), "the Log is docked"); diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index c2e31b66..477283c9 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -9,9 +9,7 @@ use texturecraft_ui_egui::state::{LibraryLocation, UiState}; use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; use texturecraft_ui_egui::{TextureCraftApp, menus}; -#[path = "../../src/ui_state_store/memory_storage.rs"] -mod memory_storage; -use memory_storage::MemoryStorage; +use crate::memory_storage::MemoryStorage; /// The section captions of the General page, top to bottom. const SECTIONS: [&str; 13] = [ diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 98a6c39c..075d4b80 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -1,10 +1,12 @@ //! 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::{Event, Modifiers, PointerButton, Pos2, Role, pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::theme::GUTTER; use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` @@ -37,6 +39,9 @@ impl eframe::Storage for MemoryStorage { 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)); + + // The Layers tab is found by its English name, whatever the OS language is + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); harness } @@ -57,6 +62,17 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: harness.run_steps(3); } +/// The views' right edge: a gutter left of the right column, whose Layers header starts at the column's left edge +fn views_right(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let column_left = harness + .get_all_by_role(Role::Tab) + .filter(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with("Layers"))) + .map(|tab| tab.rect().left()) + .next() + .expect("the right column's Layers header"); + column_left - f32::from(GUTTER) +} + /// 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 @@ -111,8 +127,8 @@ 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 views_right = views_right(&harness); + let views_width = views_right - views_left; let y = harness.state().viewport_rect.center().y; assert_eq!(harness.state().ui.split_ratio, 0.5); @@ -204,9 +220,8 @@ fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { 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 views_right = views_right(&harness); let y = harness.state().viewport_rect.center().y; let before = uv_texture_on_screen(&harness, views_right); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index b29ce0ed..7462516b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -858,6 +858,35 @@ fn tile_generator_gradient_map_snapshot() { save(&mut harness, &output_dir, "tile-generator-gradient-map"); } +/// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered +#[test] +#[ignore] +fn panel_header_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("panel-header-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let close = harness + .get_all_by_label("Close Panel") + .map(|node| node.rect()) + .filter(|rect| rect.min.x > 1200.0) + .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) + .expect("the Properties header's close button"); + harness.hover_at(close.center()); + save(&mut harness, &output_dir, "panel-header-close-hovered"); +} + /// Edit > Settings: the three pages and a compact window at 150% scale #[test] #[ignore] @@ -898,3 +927,33 @@ fn settings_pages_snapshot() { harness.state_mut().ui.windows.settings_draft.as_mut().unwrap().page = SettingsPage::General; save(&mut harness, &output_dir, "settings-compact"); } + +#[test] +#[ignore] +fn default_layout_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for color in [[0.2, 0.4, 0.7], [0.5, 0.5, 0.5], [0.8, 0.3, 0.1]] { + execute(&mut session, "layer.add.fill", &json!({ "color": color })).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("default-layout-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let properties_close = harness + .get_all_by_label("Close Panel") + .map(|node| node.rect()) + .filter(|rect| rect.min.x > 1200.0) + .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) + .expect("the Properties header's close button"); + harness.hover_at(egui::pos2(properties_close.center().x - 120.0, properties_close.min.y - 6.0)); + save(&mut harness, &output_dir, "default-layout-split-hovered"); +} From 91310e5a734892d6a0e508407101b5af70789076 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:11 +0000 Subject: [PATCH 012/153] Fills: the Fill tab with its preview square, Move on model and section reset --- crates/engine/src/fill_reset_cmds.rs | 101 +++ crates/engine/tests/it/fill_projections.rs | 767 ++++++++++++++++ crates/ui-egui/src/fill_panel.rs | 484 ++++++++++ crates/ui-egui/src/fill_pictures.rs | 403 +++++++++ crates/ui-egui/src/move_hold.rs | 15 + crates/ui-egui/src/move_on_model.rs | 498 +++++++++++ crates/ui-egui/src/preview_dots.rs | 53 ++ crates/ui-egui/src/projection_kind.rs | 68 ++ crates/ui-egui/src/projection_preview.rs | 846 ++++++++++++++++++ .../src/projection_preview/preview_shape.rs | 24 + .../projection_preview/rendered_preview.rs | 11 + .../ui-egui/src/projection_preview/screen.rs | 30 + crates/ui-egui/src/projection_preview/view.rs | 25 + .../ui-egui/tests/it/fill_projection_rows.rs | 242 +++++ 14 files changed, 3567 insertions(+) create mode 100644 crates/engine/src/fill_reset_cmds.rs create mode 100644 crates/engine/tests/it/fill_projections.rs create mode 100644 crates/ui-egui/src/fill_panel.rs create mode 100644 crates/ui-egui/src/fill_pictures.rs create mode 100644 crates/ui-egui/src/move_hold.rs create mode 100644 crates/ui-egui/src/move_on_model.rs create mode 100644 crates/ui-egui/src/preview_dots.rs create mode 100644 crates/ui-egui/src/projection_kind.rs create mode 100644 crates/ui-egui/src/projection_preview.rs create mode 100644 crates/ui-egui/src/projection_preview/preview_shape.rs create mode 100644 crates/ui-egui/src/projection_preview/rendered_preview.rs create mode 100644 crates/ui-egui/src/projection_preview/screen.rs create mode 100644 crates/ui-egui/src/projection_preview/view.rs create mode 100644 crates/ui-egui/tests/it/fill_projection_rows.rs diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs new file mode 100644 index 00000000..d5d1afa6 --- /dev/null +++ b/crates/engine/src/fill_reset_cmds.rs @@ -0,0 +1,101 @@ +//! Reset of a fill's Fill section: its projection's settings and its sampling back to a new fill's, its projection kind, symmetry and material kept + +use serde_json::Value; +use texturecraft_core::{Projection, Sampling}; + +use crate::commands::{CommandSpec, has_layer}; +use crate::layer_cmds::{UNFRAMED_PROJECTION_IDS, fill_target, new_unframed_projection, placement_mut}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "layer.fill.resetProjection", + "Reset fill settings", + [], + None, + has_layer, + reset_projection + )] +} + +/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) +pub fn reset_sampling(current: Sampling) -> Sampling { + Sampling { symmetry: current.symmetry, ..Sampling::default() } +} + +/// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept +pub fn reset_projection_of(current: &Projection) -> Projection { + if let Projection::Warp { frame, .. } = current { + return Projection::warp(*frame); + } + + // The new projection of the same kind; one no id makes (none today) stays as it is + let same_kind = UNFRAMED_PROJECTION_IDS + .iter() + .filter_map(|id| new_unframed_projection(id)) + .find(|fresh| std::mem::discriminant(fresh) == std::mem::discriminant(current)); + let Some(mut fresh) = same_kind else { return current.clone() }; + + if let (Projection::Planar { placed, .. }, Projection::Planar { placed: Some(frame), .. }) = (&mut fresh, current) { + *placed = Some(*frame); + } + fresh +} + +/// Whether the Fill section of a fill projected by `projection` and sampled by `sampling` is already a new fill's (of the same projection kind) +pub fn at_defaults(projection: &Projection, sampling: Sampling) -> bool { + *projection == reset_projection_of(projection) && sampling == reset_sampling(sampling) +} + +fn reset_projection(s: &mut Session, p: &Value) -> Result { + let target = fill_target(s, p, "layer.fill.resetProjection")?; + let (projection, sampling) = placement_mut(s, target)?; + if at_defaults(projection, *sampling) { + return Ok(Value::Null); + } + + s.edit("Reset fill settings", |s| { + let (projection, sampling) = placement_mut(s, target)?; + *projection = reset_projection_of(projection); + *sampling = reset_sampling(*sampling); + Ok(()) + })?; + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use texturecraft_core::{Decal, Projector}; + + use super::*; + + #[test] + fn every_projection_kind_resets_to_its_own_kind() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let mut kinds: Vec = UNFRAMED_PROJECTION_IDS.iter().filter_map(|id| new_unframed_projection(id)).collect(); + assert_eq!(kinds.len(), UNFRAMED_PROJECTION_IDS.len(), "every listed id makes a projection"); + + kinds.extend([Projection::warp(frame), Projection::decal(frame)]); + for kind in kinds { + let turned = match kind.clone() { + Projection::Planar { scale, axis, offset, uv, placed, .. } => { + Projection::Planar { scale: scale * 2.0, axis, offset, uv, placed, projector: Projector { rotation: [10.0; 3], ..Projector::default() } } + } + other => other, + }; + let reset = reset_projection_of(&turned); + assert_eq!(std::mem::discriminant(&reset), std::mem::discriminant(&kind), "{kind:?}"); + assert_eq!(reset.frame(), kind.frame(), "the frame stays where it is placed"); + } + } +} diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs new file mode 100644 index 00000000..7d0ebc93 --- /dev/null +++ b/crates/engine/tests/it/fill_projections.rs @@ -0,0 +1,767 @@ +//! The 3D projection settings and the projection kinds of a fill, through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, DepthCulling, FillSymmetry, LayerId, LayerKind, Projection, Projector, Sampling, UvTransform}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + s.update(); + s +} + +/// A fill layer with a checker procedural in base color +fn checker_fill(s: &mut Session) -> LayerId { + let layer = LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0, 0, 0], "high": [1, 1, 1]})) + .unwrap(); + layer +} + +fn set(s: &mut Session, layer: LayerId, mut p: Value) { + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p).unwrap(); +} + +fn projection(s: &Session, layer: LayerId) -> Projection { + match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(f) => f.projection.clone(), + _ => panic!("a fill layer"), + } +} + +/// Base color red of every texel +fn snapshot(s: &mut Session) -> Vec { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..w * h).map(|i| cache.composite.value(Channel::BaseColor, i % w, i / w)[0]).collect() +} + +/// Rotation, per-axis scale and offset move every 3D projection; the defaults and older saves change nothing +#[test] +fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() { + let mut s = session(); + let layer = checker_fill(&mut s); + for kind in ["triplanar", "planar", "spherical", "cylindrical"] { + set(&mut s, layer, json!({"projection": kind})); + let plain = snapshot(&mut s); + + set(&mut s, layer, json!({"projectorRotation": [30, 45, 60]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: rotation turns the pattern"); + set(&mut s, layer, json!({"projectorRotation": [0, 0, 0], "projectorScale": [2, 0.5, 1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: per-axis scale stretches the pattern"); + set(&mut s, layer, json!({"projectorScale": 1, "offset": [0.3, 0.2, 0.1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: offset moves the pattern"); + set(&mut s, layer, json!({"offset": 0})); + assert_eq!(snapshot(&mut s), plain, "{kind}: the defaults change nothing"); + + set(&mut s, layer, json!({"projectorRotation": [10, 20, 30], "projectorScale": [1, 2, 3]})); + let mut saved = serde_json::to_value(projection(&s, layer)).unwrap(); + let fields = saved.as_object_mut().unwrap().values_mut().next().unwrap().as_object_mut().unwrap(); + fields.remove("projector"); + let loaded: Projection = serde_json::from_value(saved).unwrap(); + let settings = match loaded { + Projection::Triplanar { projector, .. } + | Projection::Planar { projector, .. } + | Projection::Spherical { projector, .. } + | Projection::Cylindrical { projector, .. } => projector, + other => panic!("{kind}: loaded as {other:?}"), + }; + assert_eq!(settings, Projector::default(), "{kind}: an older save has no turn or stretch"); + set(&mut s, layer, json!({"projectorRotation": 0, "projectorScale": 1})); + } + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + let cylindrical = &row["fill"]["projectionSettings"]["Cylindrical"]; + assert!( + cylindrical.is_object() && cylindrical.get("projector").is_none(), + "a reset projector is the default, left out as older projects saved it: {cylindrical}" + ); +} + +/// A negative projector scale mirrors that axis, as a project file's does: the command keeps its sign and limits only its size +#[test] +fn a_negative_projector_scale_keeps_its_mirror() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "spherical", "projectorScale": [-1.5, 0.0, 5000.0]})); + let Projection::Spherical { projector, .. } = projection(&s, layer) else { panic!("a spherical projection") }; + assert_eq!(projector.scale, [-1.5, 0.001, 1000.0], "the mirror kept, each axis's size within the scale limits"); + + set(&mut s, layer, json!({"projectorScale": -0.0001})); + let Projection::Spherical { projector, .. } = projection(&s, layer) else { panic!("a spherical projection") }; + assert_eq!(projector.scale, [-0.001; 3], "a tiny mirrored scale keeps the smallest size, still mirrored"); +} + +/// Fill (Match per UV Tile) shows the same pattern on both UDIM tiles, where UV runs on across them +#[test] +fn match_per_uv_tile_repeats_the_source_once_per_tile() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute( + &mut s, + "layer.fill.set", + &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Clouds", "scale": 3, "low": [0, 0, 0], "high": [1, 1, 1]}), + ) + .unwrap(); + let tiles = |s: &mut Session| { + s.update(); + let composite = &s.caches[0].composite; + let tile = |block: u32| (0..128 * 128).map(|i| composite.value(Channel::BaseColor, block * 128 + i % 128, i / 128)[0]).collect::>(); + (tile(0), tile(1)) + }; + let (left, right) = tiles(&mut s); + assert_ne!(left, right, "a UV projection runs on into the next tile"); + + set(&mut s, layer, json!({"projection": "uvTile"})); + assert_eq!(projection(&s, layer), Projection::UvTile); + let (left, right) = tiles(&mut s); + let worst = left.iter().zip(&right).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 1e-4, "every tile shows the same pattern (worst difference {worst})"); +} + +/// Cylindrical Angle is the arc one repeat spans; older saves go the whole way round +#[test] +fn cylindrical_angle_is_the_arc_one_repeat_spans() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "cylindrical"})); + let plain = snapshot(&mut s); + set(&mut s, layer, json!({"angle": 120})); + assert!(matches!(projection(&s, layer), Projection::Cylindrical { angle: 120.0, .. })); + assert_ne!(snapshot(&mut s), plain, "a third of the way round repeats three times"); + set(&mut s, layer, json!({"angle": 360})); + assert_eq!(snapshot(&mut s), plain, "360 degrees is the whole way round"); + + let mut saved = serde_json::to_value(projection(&s, layer)).unwrap(); + saved["Cylindrical"].as_object_mut().unwrap().remove("angle"); + assert!(matches!(serde_json::from_value(saved).unwrap(), Projection::Cylindrical { angle: 360.0, .. })); +} + +/// Texel indices whose surface normal has a Z above `above` (and below `below`) +fn facing_z(s: &Session, above: f32, below: f32) -> Vec { + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..(w * h) as usize).filter(|&i| cache.gbuf.surface(&s.mesh, i).is_some_and(|surface| surface.nrm.z > above && surface.nrm.z < below)).collect() +} + +/// Cropped to Shape stops a shrunk tri-planar box short of the mesh; the default box holds it all +#[test] +fn shape_crop_stops_a_projection_at_its_shape() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + set(&mut s, layer, json!({"projection": "triplanar"})); + let plain = snapshot(&mut s); + set(&mut s, layer, json!({"shapeCrop": "cropped"})); + assert_eq!(snapshot(&mut s), plain, "the default box holds the whole mesh"); + + set(&mut s, layer, json!({"projectorScale": 0.5})); + let cropped = snapshot(&mut s); + let gone = cropped.iter().zip(&empty).filter(|(a, b)| a == b).count(); + set(&mut s, layer, json!({"shapeCrop": "extendsOutside"})); + let extends = snapshot(&mut s); + let gone_extending = extends.iter().zip(&empty).filter(|(a, b)| a == b).count(); + assert!(gone > gone_extending + 1000, "the half-size box leaves the rest of the mesh bare ({gone} vs {gone_extending} bare texels)"); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "shapeCrop": "clipped"})).is_err()); +} + +/// Backface culling leaves the far side of the sphere bare and the near side unchanged +#[test] +fn backface_culling_keeps_a_planar_projection_off_faces_turned_away() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + // Without depth culling the planar projection reaches the far side, so only backface culling can take it off + set(&mut s, layer, json!({"projection": "planar", "axis": 2, "depthCulling": false})); + let plain = snapshot(&mut s); + let (far, near) = (facing_z(&s, -1.1, -0.05), facing_z(&s, 0.05, 1.1)); + assert!(!far.is_empty() && !near.is_empty()); + assert!(far.iter().any(|&i| plain[i] != empty[i]), "without culling the projection reaches the far side"); + set(&mut s, layer, json!({"backfaceCulling": true, "backfaceAngle": 90, "backfaceHardness": 1})); + let culled = snapshot(&mut s); + assert!(far.iter().all(|&i| culled[i] == empty[i]), "faces turned away get none of the projection"); + assert!(near.iter().all(|&i| culled[i] == plain[i]), "faces turned towards it keep all of it"); + + set(&mut s, layer, json!({"backfaceAngle": 45})); + let narrow = snapshot(&mut s); + let sideways = facing_z(&s, 0.1, 0.6); + assert!(sideways.iter().all(|&i| narrow[i] == empty[i]), "past 45 degrees nothing is left"); +} + +/// A decal saved before decals were planar projections loads as a planar projection placed on its frame, cropped to it and off faces turned away +#[test] +fn saved_decals_load_as_planar_projections_placed_on_the_surface() { + use texturecraft_engine::core::{Backface, Decal, DecalFlip, DecalSymmetry, Fill, ShapeCrop}; + + // A decal saved with a mirrored copy and a flipped image keeps both + let frame = Decal { + center: [0.0, 0.0, 1.0], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [0.5, 0.4], + rotation: 10.0, + offset: [0.1, 0.0], + depth: 0.3, + symmetry: Some(DecalSymmetry { axis: 0, flip: DecalFlip::U, offset: 0.25 }), + flip: [true, false], + }; + let mut saved = serde_json::to_value(Fill::default()).unwrap(); + saved["projection"] = json!({ "Decal": frame }); + let fill: Fill = serde_json::from_value(saved).unwrap(); + let Projection::Planar { placed: Some(placed), projector, .. } = fill.projection else { panic!("{:?}", fill.projection) }; + assert_eq!(placed, frame); + assert_eq!(projector.crop, ShapeCrop::Cropped); + assert_eq!(projector.backface, Backface { on: true, angle: 90.0, hardness: 0.5 }); +} + +/// A planar projection with a decal's look saves as a decal, so versions from before planar decals still read a decal; changed in any way it saves as a planar projection +#[test] +fn placed_planars_with_a_decals_look_save_as_decals() { + use texturecraft_engine::core::{Decal, Fill}; + let frame = Decal { + center: [0.0, 0.0, 1.0], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [0.5, 0.4], + rotation: 10.0, + offset: [0.1, 0.0], + depth: 0.3, + symmetry: None, + flip: [false; 2], + }; + let fill = Fill { projection: Projection::decal(frame), ..Fill::default() }; + + let saved = serde_json::to_value(&fill).unwrap(); + assert_eq!(saved["projection"], json!({ "Decal": frame })); + assert_eq!(serde_json::from_value::(saved).unwrap(), fill, "and reads back the same"); + + let mut turned = fill; + let Projection::Planar { uv, .. } = &mut turned.projection else { panic!("{:?}", turned.projection) }; + uv.rotation = 30.0; + let saved = serde_json::to_value(&turned).unwrap(); + assert_eq!(saved["projection"]["Planar"]["placed"], json!(frame)); + assert_eq!(serde_json::from_value::(saved).unwrap(), turned); +} + +/// A warp projects from a frame around the mesh: pulling a corner bends the image, Projection Depth bounds it when cropped, and Reset frame unpulls the corners +#[test] +fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame, corners, depth, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; + assert_eq!((corners, depth), (Projection::FRAME_CORNERS, Projection::WARP_DEPTH)); + assert_eq!((frame.normal, frame.up), ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), "seen from the front"); + assert!(frame.size.iter().all(|side| (side - 2.0).abs() < 1e-3) && frame.center.iter().all(|c| c.abs() < 1e-3), "around the unit sphere: {frame:?}"); + let unpulled = snapshot(&mut s); + assert_ne!(unpulled, empty); + + let pulled = json!([[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]); + set(&mut s, layer, json!({"warpCorners": pulled})); + let bent = snapshot(&mut s); + assert_ne!(bent, unpulled, "a pulled corner bends the image"); + set(&mut s, layer, json!({"projection": "warp", "rotation": 0})); + assert_eq!(snapshot(&mut s), bent, "picking warp again keeps the corners"); + + set(&mut s, layer, json!({"shapeCrop": "cropped", "warpCorners": Projection::FRAME_CORNERS})); + let cropped = snapshot(&mut s); + + // Depth 0.1 of a frame 2 wide reaches 0.2 in front of and behind the frame through the sphere's middle + let (beyond, within) = (facing_z(&s, 0.35, 1.1), facing_z(&s, -0.05, 0.05)); + assert!(!beyond.is_empty() && !within.is_empty()); + assert!(beyond.iter().all(|&i| cropped[i] == empty[i]), "past its Projection Depth the warp does not reach"); + assert!(within.iter().all(|&i| cropped[i] == unpulled[i]), "within it the warp covers as before"); + set(&mut s, layer, json!({"projectionDepth": 1})); + let deep = snapshot(&mut s); + assert!(beyond.iter().all(|&i| deep[i] == unpulled[i]), "a deeper warp reaches the whole sphere"); + + set(&mut s, layer, json!({"warpCorners": pulled})); + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); + let Projection::Warp { frame: reset, corners, depth, .. } = projection(&s, layer) else { panic!("still a warp") }; + assert_eq!((reset, corners, depth), (frame, Projection::FRAME_CORNERS, 1.0), "the frame and corners go back; the depth stays"); + let steps = s.history_labels().len(); + execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a frame already reset adds no undo step"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projection"], "Warp projection"); + assert_eq!(row["fill"]["projectionSettings"]["Warp"]["corners"], json!(Projection::FRAME_CORNERS)); + set(&mut s, layer, json!({"projection": "planar"})); + assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset"); +} + +/// Depth culling keeps planar and warp projections off surfaces hidden behind others from the projector; new ones start with it on, older saves without it +#[test] +fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 2})); + let Projection::Planar { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; + assert_eq!(projector.depth, DepthCulling::NEW, "a new planar projection culls by depth"); + let culled = snapshot(&mut s); + set(&mut s, layer, json!({"depthCulling": false})); + let plain = snapshot(&mut s); + + // The sphere's far side sits behind its near side, seen from +Z + let (far, near) = (facing_z(&s, -1.1, -0.3), facing_z(&s, 0.3, 1.1)); + assert!(!far.is_empty() && !near.is_empty()); + assert!(far.iter().any(|&i| plain[i] != empty[i]), "without depth culling the far side gets the projection"); + assert!(far.iter().all(|&i| culled[i] == empty[i]), "hidden behind the near side, the far side gets none of it"); + assert!(near.iter().all(|&i| culled[i] == plain[i]), "the near side keeps all of it"); + + set(&mut s, layer, json!({"depthCulling": true, "depthCullingHardness": 0})); + assert_ne!(snapshot(&mut s), culled, "a softer cull fades further behind the near side"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projectionSettings"]["Planar"]["projector"]["depth"], json!({"on": true, "hardness": 0.0})); + + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; + assert_eq!(projector.depth, DepthCulling::NEW, "a new warp culls by depth"); + let warped = snapshot(&mut s); + assert!(far.iter().all(|&i| warped[i] == empty[i]), "a warp from the front leaves the far side bare"); + + let saved: Projector = serde_json::from_value(json!({"rotation": [0, 0, 0], "scale": [1, 1, 1]})).unwrap(); + assert_eq!(saved.depth, DepthCulling { on: false, hardness: 0.75 }, "an older save has no depth culling"); +} + +/// Texels of `far` that `values` gives something other than the bare `empty` +fn filled(far: &[usize], values: &[f32], empty: &[f32]) -> usize { + far.iter().filter(|&&i| values[i] != empty[i]).count() +} + +/// The symmetry axis is read from an index or from the letter tool.brush takes; any other value is refused, never ignored +#[test] +fn fill_symmetry_axis_reads_an_index_or_a_letter() { + let mut s = session(); + let layer = checker_fill(&mut s); + let axis = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.sampling.symmetry.axis, + _ => panic!("a fill layer"), + }; + + set(&mut s, layer, json!({"symmetryAxis": "Y"})); + assert_eq!(axis(&s), 1); + set(&mut s, layer, json!({"symmetryAxis": 2})); + assert_eq!(axis(&s), 2); + + for refused in [json!("w"), json!(true), json!(-1), json!(3)] { + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": refused})).is_err(), "{refused}"); + } + assert_eq!(axis(&s), 2, "a refused axis changes nothing"); +} + +/// Mirror and radial symmetry copy a planar projection onto the sphere's far side and leave the near side as it was; Flip copy turns the copies' images over; UV projections and older saves have no copies +#[test] +fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() { + let mut s = session(); + let layer = checker_fill(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + let empty = snapshot(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + + // Depth culled from +Z, the planar projection reaches only the near side + set(&mut s, layer, json!({"projection": "planar", "axis": 2})); + let plain = snapshot(&mut s); + let (far, near) = (facing_z(&s, -1.1, -0.3), facing_z(&s, 0.3, 1.1)); + assert_eq!(filled(&far, &plain, &empty), 0); + + set(&mut s, layer, json!({"symmetry": true, "symmetryType": "mirror", "symmetryAxis": 2})); + let mirrored = snapshot(&mut s); + assert!(filled(&far, &mirrored, &empty) > far.len() / 2, "the mirror copy reaches the far side"); + assert!(near.iter().all(|&i| mirrored[i] == plain[i]), "the original keeps its own half"); + + set(&mut s, layer, json!({"symmetryType": "radial", "symmetryAxis": 1, "symmetryCount": 2})); + let turned = snapshot(&mut s); + assert!(filled(&far, &turned, &empty) > far.len() / 2, "the copy turned half round reaches the far side"); + assert!(near.iter().all(|&i| turned[i] == plain[i]), "the original keeps its own wedge"); + assert_ne!(turned, mirrored, "a turned copy is not a mirrored one"); + set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), plain, "switched off, the copies go"); + + // A left to right ramp shows a copy's image turned over + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"symmetry": true})); + let copied = snapshot(&mut s); + set(&mut s, layer, json!({"flipCopy": [true, false]})); + let flipped = snapshot(&mut s); + assert!(far.iter().filter(|&&i| (flipped[i] - copied[i]).abs() > 0.1).count() > far.len() / 4, "Flip copy U turns the copy's ramp round"); + assert!(near.iter().all(|&i| flipped[i] == copied[i]), "the original is never flipped"); + + set(&mut s, layer, json!({"projection": "uv"})); + let uv = snapshot(&mut s); + set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), uv, "a UV projection has no copies"); + + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryType": "spiral"})).is_err()); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": 3})).is_err()); + let saved: Sampling = serde_json::from_value(json!({"filtering": "BilinearHq", "wrap": "Repeat", "scale": "Tiling"})).unwrap(); + assert_eq!(saved.symmetry, FillSymmetry::OFF, "an older save has no symmetry"); +} + +/// Moving an axis planar on the model first places it as the frame it projects from: nothing moves until the frame does, and undo puts the axis planar back +#[test] +fn moving_an_axis_planar_places_it_as_its_frame_first() { + let mut s = session(); + let layer = checker_fill(&mut s); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 0, "scale": 1.5, "offset": [0.2, -0.1, 0.0], "projectorRotation": [0, 30, 10]})); + let axis = projection(&s, layer); + let before = snapshot(&mut s); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + let placed = projection(&s, layer); + let Projection::Planar { placed: Some(frame), projector, .. } = &placed else { panic!("placed: {placed:?}") }; + assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "the turn is in the frame now"); + let after = snapshot(&mut s); + let moved = before.iter().zip(&after).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); + assert!(moved * 200 < before.len(), "the image stays where it was: {moved} of {} texels changed", before.len()); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.4, 0.0], "merge": true})).unwrap(); + assert_ne!(snapshot(&mut s), after, "then the frame moves the image"); + let Projection::Planar { placed: Some(slid), .. } = projection(&s, layer) else { panic!("still placed") }; + assert_eq!((slid.offset, slid.size), ([0.4, 0.0], frame.size)); + + s.undo().unwrap(); + assert_eq!(projection(&s, layer), axis, "placing and moving is one step"); + + set(&mut s, layer, json!({"projection": "warp", "warpCorners": [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap(); + let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("still a warp") }; + assert_eq!((frame.rotation, corners[1]), (30.0, [0.9, 0.9]), "a warp's frame turns and keeps its corners"); + set(&mut s, layer, json!({"projection": "spherical"})); + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).is_err(), "a spherical projection has no frame"); +} + +/// An axis planar reading a procedural keeps its axis: a placed frame reads the pattern in its own uv, so placing it would move the pattern; a mask fill's pattern stays the same way +#[test] +fn an_axis_planar_reading_a_pattern_is_not_placed() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "planar", "axis": 0, "scale": 1.5})); + let axis = projection(&s, layer); + let before = snapshot(&mut s); + + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).is_err(), "placing would move the pattern"); + assert_eq!(projection(&s, layer), axis, "the planar keeps its axis"); + assert_eq!(snapshot(&mut s), before, "and the pattern stays where it was"); + + let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); + let effect = added["effect"].as_u64().unwrap(); + + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); +} + +/// Backface culling under an uneven or mirrored projector scale cannot keep its facing in a frame: moving it is refused with the way out, and nothing changes +#[test] +fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing() { + let mut s = session(); + let layer = checker_fill(&mut s); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 2, "backfaceCulling": true})); + + // An axis planar with an uneven then a mirrored scale, then a placed frame with an uneven one + for (scale, placed) in [(json!([2, 1, 1]), false), (json!([1.5, -1.5, 1.5]), false), (json!([2, 1, 1]), true)] { + let edit = if placed { json!({"layer": layer.0, "frameOffset": [0.1, 0, 0]}) } else { json!({"layer": layer.0}) }; + if placed { + set(&mut s, layer, json!({"projectorScale": 1})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + assert!(projection(&s, layer).placed().is_some(), "an even scale places the frame"); + } + + set(&mut s, layer, json!({"projectorScale": scale})); + let before = projection(&s, layer); + let steps = s.history_labels().len(); + + let refused = execute(&mut s, "layer.decal.set", &edit).unwrap_err().to_string(); + + assert!(refused.contains("even out the projector scale or turn backface culling off"), "{scale} placed {placed}: {refused}"); + assert_eq!(projection(&s, layer), before, "{scale} placed {placed}: the projection is unchanged"); + assert_eq!(s.history_labels().len(), steps, "{scale} placed {placed}: no undo step"); + } + + // A placed frame's edit that moves no frame still lands + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "flipU": true})).unwrap(); + assert!(projection(&s, layer).frame().is_some_and(|frame| frame.flip[0]), "the flip lands on the placed frame"); +} + +/// A frame's 3D projection settings (Offset, Rotation, Scale as the panel and the gizmo share them) move it in one undo step, and a turned or scaled projector folds into the frame first, landing the same +#[test] +fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first() { + let mut s = session(); + let layer = checker_fill(&mut s); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap(); + set(&mut s, layer, json!({"projection": "planar", "axis": 2})); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + + // Depth culling off: its depth map is drawn along the frame, so a folded turn re-draws it (a few silhouette texels differ) + set(&mut s, layer, json!({"projectorRotation": [0, 0, 30], "projectorScale": 1.25, "depthCulling": false})); + let turned = snapshot(&mut s); + let steps = s.history_labels().len(); + + // Moving the frame as shown: the turn and scale are in the frame now, the image where it was + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameOffset": [0.0, 0.0, 0.0]})).unwrap(); + let Projection::Planar { placed: Some(frame), projector, .. } = projection(&s, layer) else { panic!("still placed") }; + assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "folded into the frame"); + let (lo, hi) = s.mesh.bounds(); + assert!((Vec3::from(frame.center) - (lo + hi) * 0.5).length() < 1e-4, "offset 0 = the mesh's centre: {frame:?}"); + let shown = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((shown.rotation[2] - 30.0).abs() < 1e-3 && shown.rotation[0].abs() < 1e-3, "the projector's turn shows as the frame's: {shown:?}"); + let folded = snapshot(&mut s); + let changed = turned.iter().zip(&folded).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); + assert!(changed * 200 < turned.len(), "the frame was already at the centre: the image stays, {changed} of {} texels changed", turned.len()); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [shown.scale[0] * 0.5, shown.scale[1], shown.scale[2]], "merge": true})) + .unwrap(); + let Projection::Planar { placed: Some(narrow), .. } = projection(&s, layer) else { panic!("still placed") }; + assert!((narrow.size[0] - frame.size[0] * 0.5).abs() < 1e-4 && (narrow.size[1] - frame.size[1]).abs() < 1e-4, "Scale X halves the width"); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameRotation": [0, 0, 90], "merge": true})).unwrap(); + let again = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((again.rotation[2] - 90.0).abs() < 1e-3 && (again.scale[0] - shown.scale[0] * 0.5).abs() < 1e-4, "{again:?}"); + assert_eq!(s.history_labels().len(), steps + 1, "a drag is one undo step"); + s.undo().unwrap(); + assert_eq!(snapshot(&mut s), turned, "undo puts the turned projector back"); + + for bad in [json!({"frameScale": [1, 2]}), json!({"frameOffset": "x"}), json!({"frameScale": [0, -1, "deep"]})] { + let mut params = bad.clone(); + params["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.decal.set", ¶ms).is_err(), "{bad}"); + } + + // A collapsed or turned-over scale is clamped to the smallest frame, not refused + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [0, -1, 0]})).unwrap(); + let Projection::Planar { placed: Some(smallest), .. } = projection(&s, layer) else { panic!("still placed") }; + assert!(smallest.size.iter().chain([&smallest.depth]).all(|side| *side > 0.0 && side.is_finite()), "{smallest:?}"); + + // A warp's Scale Z is its reach: Projection Depth times the longer side + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame, .. } = projection(&s, layer) else { panic!("a warp") }; + let diagonal = (hi - lo).length(); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [frame.size[0] / diagonal, frame.size[1] / diagonal, 0.1]})).unwrap(); + let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") }; + assert!((depth * frame.size[0].max(frame.size[1]) - 0.1 * diagonal).abs() < 1e-4, "reach {depth}"); +} + +/// A decal edit that moves nothing and keeps its image adds no undo step and leaves the project unmodified; one that moves it adds one +#[test] +fn a_decal_edit_that_changes_nothing_adds_no_undo_step() { + let mut s = session(); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + let added = execute(&mut s, "layer.add.decal", &json!({"image": ramp, "position": [0, 0, 1], "normal": [0, 0, 1], "rotation": 30})).unwrap(); + let layer = added["layer"].as_u64().unwrap(); + let mask = execute(&mut s, "layer.add.decal", &json!({"image": ramp, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap(); + let mask_effect = mask["maskEffect"].as_u64().unwrap(); + let steps = s.history_labels().len(); + + for unchanged in [ + json!({"layer": layer}), + json!({"layer": layer, "rotation": 30}), + json!({"layer": layer, "image": ramp}), + json!({"layer": layer, "offset": [0, 0]}), + json!({"effect": mask_effect}), + json!({"effect": mask_effect, "image": ramp}), + ] { + execute(&mut s, "layer.decal.set", &unchanged).unwrap(); + assert_eq!(s.history_labels().len(), steps, "{unchanged} changes nothing"); + } + + execute(&mut s, "layer.decal.set", &json!({"layer": layer, "rotation": 45})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1, "a turn is an edit"); +} + +/// Inspect shows the frame a decal was placed on, for a decal placed as a mask as for one placed as a layer +#[test] +fn inspect_shows_a_mask_decals_frame_as_a_layer_decals() { + let mut s = session(); + let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap(); + let placement = json!({"image": ramp, "position": [0, 0, 1], "normal": [0, 0, 1], "size": 0.5}); + let layer_decal = execute(&mut s, "layer.add.decal", &placement).unwrap(); + let mut mask_placement = placement.clone(); + mask_placement["channel"] = json!("mask"); + let mask_decal = execute(&mut s, "layer.add.decal", &mask_placement).unwrap(); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let layers = inspect["layers"].as_array().unwrap(); + let row = |id: &Value| layers.iter().find(|layer| &layer["id"] == id).unwrap().clone(); + let layer_frame = row(&layer_decal["layer"])["fill"]["decal"].clone(); + let mask_effects = row(&mask_decal["layer"])["mask"]["effects"].clone(); + let mask_effect = mask_effects.as_array().unwrap().iter().find(|effect| effect["id"] == mask_decal["maskEffect"]).unwrap().clone(); + + // Each side holds a frame on the requested point and normal, so two missing frames cannot match as nulls + let on_request = |frame: &Value| { + let near = |key: &str, want: [f64; 3]| { + frame[key] + .as_array() + .is_some_and(|got| got.len() == 3 && got.iter().zip(want).all(|(got, want)| got.as_f64().is_some_and(|got| (got - want).abs() < 1e-3))) + }; + near("center", [0.0, 0.0, 1.0]) && near("normal", [0.0, 0.0, 1.0]) + }; + for (name, frame) in [ + ("layer decal", &layer_frame), + ("layer decal reply", &layer_decal["decal"]), + ("mask decal", &mask_effect["decal"]), + ("mask decal reply", &mask_decal["decal"]), + ] { + assert!(on_request(frame), "the {name} shows its frame on the requested placement: {frame}"); + } + assert_eq!(layer_frame, layer_decal["decal"], "a layer decal's frame"); + assert_eq!(mask_effect["decal"], mask_decal["decal"], "a mask decal's frame"); +} + +/// `depth` on a warp sets how far it reaches: its Projection Depth becomes the depth over the frame's longer side +#[test] +fn a_warps_depth_sets_its_projection_depth() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": 0.5})).unwrap(); + let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") }; + assert!((depth * frame.size[0].max(frame.size[1]) - 0.5).abs() < 1e-5, "reach {depth} × {:?}", frame.size); +} + +/// `depth` at a warp's current reach changes nothing, so it adds no undo step (its frame's unused depth is left alone) +#[test] +fn a_warps_current_reach_as_depth_adds_no_undo_step() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp", "projectionDepth": 0.5})); + let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") }; + let steps = s.history_labels().len(); + + let reach = depth * frame.size[0].max(frame.size[1]); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": reach})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "reach {reach} is the one it has"); +} + +/// A frameScale reach on a warp keeps its Projection Depth within the range `projectionDepth` allows +#[test] +fn a_warps_frame_scale_keeps_its_projection_depth_in_range() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + + let deepest = checker_fill(&mut s); + set(&mut s, deepest, json!({"projection": "warp", "projectionDepth": 1e9})); + let Projection::Warp { depth: max_depth, .. } = projection(&s, deepest) else { panic!("a warp") }; + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [0.0001, 0.0001, 10]})).unwrap(); + let Projection::Warp { depth, .. } = projection(&s, layer) else { panic!("a warp") }; + assert!(depth <= max_depth, "Projection Depth {depth} past {max_depth}"); +} + +/// A 64 × 8 PNG whose red climbs from left to right +fn ramp_png() -> Vec { + let mut out = Vec::new(); + let ramp = image::RgbaImage::from_fn(64, 8, |x, _| image::Rgba([(x * 4) as u8, 0, 0, 255])); + ramp.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// Reset fill settings puts the Fill section back to the defaults of the projection it uses, in one undo step, and leaves the projection kind, the symmetry and sources alone +#[test] +fn reset_fill_settings_keeps_the_projection_and_restores_its_defaults_in_one_undo_step() { + let mut s = session(); + let layer = checker_fill(&mut s); + let fresh = snapshot(&mut s); + set( + &mut s, + layer, + json!({"projection": "planar", "tiling": [3, 2], "rotation": 30, "axis": 0, "filtering": "nearest", "wrap": "none", "scaleMode": "physicalSize", "shapeCrop": "cropped", "symmetry": true, "symmetryAxis": 1}), + ); + let fill = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(f) => f.clone(), + _ => panic!("a fill layer"), + }; + let changed = fill(&s); + assert!(!texturecraft_engine::fill_reset_cmds::at_defaults(&changed.projection, changed.sampling)); + + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + let reset = fill(&s); + let Projection::Planar { scale, axis, offset, uv, projector, placed } = reset.projection else { panic!("still planar, got {:?}", reset.projection) }; + assert_eq!((scale, axis, offset, uv, placed), (1.0, 2, [0.0; 3], UvTransform::default(), None), "a new planar's placement"); + assert_eq!(projector, Projector::depth_culled(), "a new planar's 3D settings and culling"); + assert_eq!(reset.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the sampling is a new fill's; the symmetry stays"); + assert_eq!(reset.sources, changed.sources, "the material stays"); + assert!(texturecraft_engine::fill_reset_cmds::at_defaults(&reset.projection, reset.sampling)); + let steps = s.history_labels().len(); + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a Fill section at its defaults adds no undo step"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill(&s), changed, "one undo brings every setting back"); + assert!(execute(&mut s, "layer.fill.resetProjection", &json!({"layer": 9999})).is_err(), "no such layer"); + + // A UV fill comes back to a UV projection at tiling 1 and renders like a new fill + set(&mut s, layer, json!({"projection": "uv", "tiling": [3, 2], "rotation": 30})); + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(fill(&s).projection, Projection::default()); + assert_eq!(snapshot(&mut s), fresh, "it renders like the new fill"); +} + +/// A warp's reset keeps its frame where it is placed and restores its corners, Projection Depth, UV transform and projector settings +#[test] +fn reset_fill_settings_keeps_a_warp_frame_and_restores_its_settings() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + let Projection::Warp { frame: fitted, .. } = projection(&s, layer) else { panic!("a warp") }; + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.2, 0.1]})).unwrap(); + set( + &mut s, + layer, + json!({"warpCorners": [[-0.6, 0.5], [0.5, 0.6], [0.4, -0.5], [-0.5, -0.4]], "projectionDepth": 0.5, "tiling": [2, 2], "rotation": 45, "shapeCrop": "extendsOutside"}), + ); + let Projection::Warp { frame: moved, .. } = projection(&s, layer) else { panic!("a warp") }; + assert_ne!(moved, fitted, "the frame was moved"); + + execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(projection(&s, layer), Projection::warp(moved), "still a warp: its frame stays, every setting is a new warp's"); +} + +#[test] +fn malformed_warp_corners_copy_flips_and_a_warps_own_placement_are_rejected_and_change_nothing() { + let mut s = session(); + let layer = checker_fill(&mut s); + set(&mut s, layer, json!({"projection": "warp"})); + let before = projection(&s, layer); + let steps = s.history_labels().len(); + + for bad in [ + json!({"warpCorners": [[1, 2]]}), + json!({"warpCorners": [[0, 0], [0, 0], [0, 0], ["x", 0]]}), + json!({"warpCorners": "pulled"}), + json!({"flipCopy": [true, "x"]}), + // A warp is placed by its frame (layer.decal.set): a scale or offset of its own would change nothing + json!({"scale": 2}), + json!({"offset": [1, 0, 0]}), + json!({"projection": "warp", "scale": 2, "offset": [1, 0, 0]}), + ] { + let mut p = bad.clone(); + p["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.fill.projection", &p).is_err(), "{bad}"); + } + + assert_eq!(projection(&s, layer), before); + assert_eq!(s.history_labels().len(), steps, "no undo step for a rejected edit"); +} diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs new file mode 100644 index 00000000..b58dcde4 --- /dev/null +++ b/crates/ui-egui/src/fill_panel.rs @@ -0,0 +1,484 @@ +//! A fill's Properties: its projection, size, placement and edges, then its material + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::compose::frame_placement; +use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length}; +use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE}; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::TextureCraftApp; +use crate::dock::with; +use crate::fill_pictures::{ + angle_picture, backface_picture, crop_picture, depth_picture, filtering_picture, projection_picture, warp_preview, window_preview, wrap_picture, +}; +use crate::i18n::{filtering_label, n_, tr, wrap_label}; +use crate::move_on_model::MoveOnModel; +use crate::placement::Placement; +use crate::projection_kind::ProjectionKind; +use crate::projection_preview::projection_preview; +use crate::property_sheet::{NumberField, PreviewLower, PreviewSize, PropertySheet, RowLead}; +use crate::theme::{AXIS_COLORS, AXIS_NAMES, Tokens}; + +/// Centimetres in one mesh unit: meshes are read in metres +const CM_PER_UNIT: f32 = 100.0; + +/// What the Tiling track spans +const TILING_TRACK: RangeInclusive = 0.01..=5.0; + +/// What a typed tiling may be: the command's own limits +const TILING_TYPED: RangeInclusive = MIN_SCALE..=MAX_PLACEMENT; + +/// What the Size (cm) track spans +const SIZE_CM_TRACK: RangeInclusive = 1.0..=500.0; + +/// What a typed size (cm) may be +const SIZE_CM_TYPED: RangeInclusive = 0.1..=100_000.0; + +/// What an Offset track spans (tiles, centred on zero) +const OFFSET_TRACK: RangeInclusive = -2.0..=2.0; + +/// What a typed offset may be (tiles): the command's own limits +const OFFSET_TYPED: RangeInclusive = -MAX_PLACEMENT..=MAX_PLACEMENT; + +/// Range of a fill's rotation, a full turn +const ROTATION_RANGE: RangeInclusive = 0.0..=FULL_TURN_DEGREES; + +/// Tri-planar blend's largest exponent: Hardness 1 (0 = exponent 1, 0.5 = 8) +const TRIPLANAR_SHARPNESS_MAX: f32 = *Projection::TRIPLANAR_SHARPNESS_RANGE.end(); + +/// Range of every Hardness the panel shows +const HARDNESS_RANGE: RangeInclusive = 0.0..=1.0; + +/// What a cylindrical projection's Angle may be: the arc one repeat spans, in degrees +const CYLINDER_ANGLE_RANGE: RangeInclusive = Projection::CYLINDER_ANGLE_RANGE; + +/// What Backface culling's Angle may be, in degrees from facing the projector +const BACKFACE_ANGLE_RANGE: RangeInclusive = Backface::ANGLE_RANGE; + +/// What the Projection Depth track spans, in lengths of the frame's longer side +const PROJECTION_DEPTH_TRACK: RangeInclusive = 0.0..=1.0; + +/// A degenerate warp frame's preview size: its side spans the preview's middle +const WARP_SPAN_FALLBACK: f32 = 1.7; + +/// Change per pixel dragged on a 3D offset field +pub(crate) const OFFSET_FIELD_SPEED: f32 = 0.01; + +/// Change per pixel dragged on a 3D rotation field, in degrees +const ROTATION_FIELD_SPEED: f32 = 0.5; + +/// Change per pixel dragged on a 3D scale field +const SCALE_FIELD_SPEED: f32 = 0.01; + +} + +/// Which fill a `base` addresses, (layer, effect), as the salt of its rows' widget state +pub(crate) type FillKey = (Option, Option); + +/// The [`FillKey`] of the fill at `base` +pub(crate) fn fill_key(base: &Value) -> FillKey { + (base.get("layer").and_then(Value::as_u64), base.get("effect").and_then(Value::as_u64)) +} + +/// The mesh's size for the texture set being painted, as the projections see it, measured once per mesh and material +fn mesh_size(app: &TextureCraftApp, ctx: &egui::Context) -> MeshSize { + let mesh = &app.session.mesh; + let material = app.session.doc.project.texture_set(app.session.ts()).map_or(0, |texture_set| texture_set.material); + let key = (app.session.mesh_id, material); + + // Both measures walk the whole mesh, too slow for every frame the sheet draws on a dense mesh + let cache_id = egui::Id::unique("tc_fill_mesh_size"); + if let Some((cached_key, size)) = ctx.data(|data| data.get_temp::<((u64, usize), MeshSize)>(cache_id)) + && cached_key == key + { + return size; + } + + let size = MeshSize { radius: mesh.radius(), uv_density: mesh.uv_density(material).unwrap_or(1.0) }; + ctx.data_mut(|data| data.insert_temp(cache_id, (key, size))); + size +} + +/// The Fill section (with its reset) and the Symmetry section of the fill at `base`: a fill layer's, a content fill effect's or a mask fill's +pub(crate) fn placement_sections(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, reader: LayerId) { + // The section reset: projection, placement, sampling and culling back to a new fill's in one undo step + if sheet.section_reset(tr("Fill"), !texturecraft_engine::fill_reset_cmds::at_defaults(&fill.projection, fill.sampling)) { + app.run("layer.fill.resetProjection", base.clone()); + } + projection_rows(app, sheet, fill, base, fill_key(base), reader); + crate::fill_symmetry_panel::symmetry_section(app, sheet, &fill.projection, fill.sampling, base); +} + +/// Runs `layer.fill.projection` on the fill `base` names with `fields` +pub(crate) fn run_projection(app: &mut TextureCraftApp, base: &Value, fields: Value) { + app.run("layer.fill.projection", with(base, fields)); +} + +/// Projection, Scale, the preview with size and offset (held, it moves the projection on the model), Rotation, the culling rows, then the Filtering and edges and 3D projection settings bands +fn projection_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, salt: FillKey, reader: LayerId) { + let tokens = Tokens::get(sheet.ui.ctx()); + let kind = ProjectionKind::of(&fill.projection); + let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + + let picture = |painter: &Painter, rect: Rect, kind: ProjectionKind| projection_picture(painter, rect, kind, &tokens); + + // A projection with a gizmo in the 3D view ends its row in the eye that shows or hides it (a view setting saved with the project) + let gizmos = app.session.doc.project.display.projection_gizmos; + let tip = if gizmos { tr("Hide projection gizmos") } else { tr("Show projection gizmos") }; + let name = |kind: ProjectionKind| tr(kind.label()).to_owned(); + let (picked, eye) = if matches!(kind, ProjectionKind::Uv | ProjectionKind::UvTile) { + (sheet.dropdown(tr("Projection"), kind, &ProjectionKind::ALL, name, Some(&picture)).0, false) + } else { + sheet.dropdown_with_eye(tr("Projection"), kind, &ProjectionKind::ALL, name, Some(&picture), (gizmos, tip)) + }; + if let Some(kind) = picked { + run(app, json!({"projection": kind.id()})); + } + if eye { + app.run("display.set", json!({"projectionGizmos": !gizmos})); + } + + // Per UV tile, the source fills each tile once: nothing to place + if kind == ProjectionKind::UvTile { + return; + } + + let size = mesh_size(app, sheet.ui.ctx()); + let length = tile_length(&fill.projection, size); + let physical = length.is_some() && fill.sampling.scale == ScaleMode::PhysicalSize; + if length.is_some() { + let modes = [tr("Tiling"), tr("Physical size")]; + if let Some(index) = sheet.switch(tr("Scale"), &modes, usize::from(physical)) + && let Some(mode) = ScaleMode::ALL.get(index) + { + run(app, json!({"scaleMode": mode.id()})); + } + } + + // Move on model: hold the preview square and drag to slide the projection + let target = match base.get("effect").and_then(Value::as_u64) { + Some(effect) => MoveOnModel { layer: reader, effect: Some(LayerId(effect)) }, + None => MoveOnModel::layer(reader), + }; + placement_rows(app, sheet, fill, base, length.filter(|_| physical), size, target); + frame_rows(app, sheet, fill, base); + culling_rows(app, sheet, fill, base); + + let crop = projector_of(&fill.projection).map(|projector| projector.crop); + let shows_wrap = kind != ProjectionKind::Triplanar; + let edges_changed = fill.sampling.filtering != Filtering::default() + || (shows_wrap && fill.sampling.wrap != UvWrap::default()) + || crop.is_some_and(|crop| crop != ShapeCrop::default()); + let band = sheet.band(tr("Filtering and edges"), true, Some(edges_changed), None); + if band.reset { + let mut fields = json!({"filtering": Filtering::default().id(), "wrap": UvWrap::default().id()}); + if crop.is_some() { + fields["shapeCrop"] = json!(ShapeCrop::default().id()); + } + run(app, fields); + } + if band.open { + let filtering = fill.sampling.filtering; + let picture = |painter: &Painter, rect: Rect, filtering: Filtering| filtering_picture(painter, rect, filtering, &tokens); + let (picked, _) = sheet.dropdown(tr("Filtering"), filtering, &Filtering::ALL, |filtering| tr(filtering_label(filtering)).to_owned(), Some(&picture)); + if let Some(filtering) = picked { + run(app, json!({"filtering": filtering.id()})); + } + + // Tri-planar has no tile to repeat + if shows_wrap { + let picture = |painter: &Painter, rect: Rect, wrap: UvWrap| wrap_picture(painter, rect, wrap, &tokens); + let (picked, _) = sheet.dropdown(tr("UV Wrap"), fill.sampling.wrap, &UvWrap::ALL, |wrap| tr(wrap_label(wrap)).to_owned(), Some(&picture)); + if let Some(wrap) = picked { + run(app, json!({"wrap": wrap.id()})); + } + } + if let Some(projector) = projector_of(&fill.projection) { + let picture = |painter: &Painter, rect: Rect, crop: ShapeCrop| crop_picture(painter, rect, crop, &tokens); + let (picked, _) = sheet.dropdown(tr("Shape crop"), projector.crop, &ShapeCrop::ALL, |crop| tr(crop_label(crop)).to_owned(), Some(&picture)); + if let Some(crop) = picked { + run(app, json!({"shapeCrop": crop.id()})); + } + } + } + + world_rows(app, sheet, fill, base, salt); +} + +/// The settings of the projector itself, shared by every 3D projection +fn projector_of(projection: &Projection) -> Option<&Projector> { + match projection { + Projection::Triplanar { projector, .. } + | Projection::Planar { projector, .. } + | Projection::Spherical { projector, .. } + | Projection::Cylindrical { projector, .. } + | Projection::Warp { projector, .. } => Some(projector), + Projection::Uv { .. } | Projection::UvTile => None, + } +} + +/// The name of a Shape crop choice; both fit beside the label at the default panel width +fn crop_label(crop: ShapeCrop) -> &'static str { + match crop { + ShapeCrop::Cropped => n_("Cropped to Shape"), + ShapeCrop::ExtendsOutside => n_("Extends Outside Shape"), + } +} + +/// Tri-planar Hardness as the panel shows it (0..1) from the blend's exponent (1..64): exponent = 64^hardness +fn triplanar_hardness(sharpness: f32) -> f32 { + (sharpness.max(1.0).ln() / TRIPLANAR_SHARPNESS_MAX.ln()).clamp(0.0, 1.0) +} + +/// The blend's exponent for a tri-planar Hardness the panel shows +fn triplanar_sharpness(hardness: f32) -> f32 { + TRIPLANAR_SHARPNESS_MAX.powf(hardness.clamp(0.0, 1.0)) +} + +/// A warp's Projection Depth and Reset frame +fn frame_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value) { + let Projection::Warp { depth, .. } = &fill.projection else { return }; + let mut depth = *depth; + + // Its i tells it apart from Depth culling; it keeps the column every projection shares + sheet.info(tr("How far the warp projection reaches into the mesh, in front of and behind its frame, in lengths of the frame's longer side. It bounds the fill only when cropped to its shape.")); + if let Some(merge) = sheet.slider_led(RowLead::Loose(tr("Depth")), &mut depth, PROJECTION_DEPTH_TRACK, 2, "") { + run_projection(app, base, json!({"projectionDepth": depth, "merge": merge})); + } + if sheet.button(ic::ARROW_CLOCKWISE, tr("Reset frame")).clicked() { + app.run("layer.fill.resetFrame", base.clone()); + } +} + +/// Cylindrical Angle, then Depth culling (planar, warp) and Backface culling (planar, cylindrical), each with its settings under it +fn culling_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value) { + let tokens = Tokens::get(sheet.ui.ctx()); + let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + let (projector, angle) = match &fill.projection { + Projection::Cylindrical { projector, angle, .. } => (projector, Some(*angle)), + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => (projector, None), + _ => return, + }; + + if let Some(mut angle) = angle { + let arc = angle; + let picture = |painter: &Painter, rect: Rect| angle_picture(painter, rect, arc, &tokens); + let lead = RowLead::Picture { picture: &picture, text: tr("Angle") }; + if let Some(merge) = sheet.slider_led(lead, &mut angle, CYLINDER_ANGLE_RANGE, 0, "°") { + run(app, json!({"angle": angle, "merge": merge})); + } + } + + if !matches!(fill.projection, Projection::Cylindrical { .. }) { + let mut culling = projector.depth; + let picture = |painter: &Painter, rect: Rect| depth_picture(painter, rect, &tokens); + sheet.info(tr("Paints only the surface the projector sees first; parts hidden behind it stay unpainted.")); + if sheet.picture_toggle(&picture, tr("Depth culling"), &mut culling.on) { + run(app, json!({"depthCulling": culling.on})); + } + if let Some(merge) = sheet.slider_led(RowLead::Child(tr("Hardness")), &mut culling.hardness, HARDNESS_RANGE, 2, "") { + run(app, json!({"depthCullingHardness": culling.hardness, "merge": merge})); + } + } + + if !matches!(fill.projection, Projection::Warp { .. }) { + let mut backface = projector.backface; + let culled = backface.on; + let picture = |painter: &Painter, rect: Rect| backface_picture(painter, rect, culled, &tokens); + sheet.info(tr("Leaves out faces turned away from the projector, so the fill doesn't run onto their back.")); + if sheet.picture_toggle(&picture, tr("Backface culling"), &mut backface.on) { + run(app, json!({"backfaceCulling": backface.on})); + } + + // Cylindrical culls by the angle to its axis's outward direction alone + if angle.is_none() + && let Some(merge) = sheet.angle_led(RowLead::Child(tr("Angle")), &mut backface.angle, BACKFACE_ANGLE_RANGE) + { + run(app, json!({"backfaceAngle": backface.angle, "merge": merge})); + } + if let Some(merge) = sheet.slider_led(RowLead::Child(tr("Hardness")), &mut backface.hardness, HARDNESS_RANGE, 2, "") { + run(app, json!({"backfaceHardness": backface.hardness, "merge": merge})); + } + } +} + +/// The preview square beside the size (tiling, or the tile's length while Physical size) and offset, held to move `target` on the model; Rotation under it +fn placement_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + fill: &Fill, + base: &Value, + length: Option<[f32; 2]>, + size: MeshSize, + target: MoveOnModel, +) { + let tokens = Tokens::get(sheet.ui.ctx()); + let (tiling, rotation, offset, offset_key) = match &fill.projection { + Projection::Uv { scale, rotation, offset } => (*scale, *rotation, *offset, "offset"), + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => (uv.tiling, uv.rotation, uv.offset, "uvOffset"), + Projection::UvTile => return, + }; + + let link_id = sheet.ui.make_persistent_id(("fill_tiling_link", fill_key(base))); + let mut linked = sheet.ui.data(|data| data.get_temp::(link_id)).unwrap_or(tiling[0] == tiling[1]); + let was_linked = linked; + let mut values = match length { + Some(length) => length.map(|units| (units * CM_PER_UNIT).round()), + None => tiling, + }; + let shown = values; + let (label, range, typed, decimals) = match length { + Some(_) => (tr("Size (cm)"), SIZE_CM_TRACK, SIZE_CM_TYPED, 0), + None => (tr("Tiling"), TILING_TRACK, TILING_TYPED, 2), + }; + let size_edit = PreviewSize { label, values: &mut values, range, typed, decimals, linked: &mut linked }; + + let mut lower_offset = offset; + let mut hardness = match &fill.projection { + Projection::Triplanar { sharpness, .. } => Some(triplanar_hardness(*sharpness)), + _ => None, + }; + let lower = match hardness.as_mut() { + Some(hardness) => PreviewLower::Slider { label: tr("Hardness"), value: hardness, range: HARDNESS_RANGE, decimals: 2 }, + None => PreviewLower::Offset { values: &mut lower_offset, range: OFFSET_TRACK, typed: OFFSET_TYPED }, + }; + let placement = Placement { tiling, rotation, offset }; + let bounds = app.session.mesh.bounds(); + + // A warp shows its frame's size and turn as its gizmo leaves them + let warp = match &fill.projection { + Projection::Warp { corners, .. } => { + let landed = frame_placement::folded(&fill.projection); + let frame = landed.as_ref().and_then(Projection::frame); + let diagonal = (bounds.1 - bounds.0).length().max(f32::EPSILON); + let size = frame.map_or([1.0 / WARP_SPAN_FALLBACK; 2], |frame| frame.size.map(|side| side / diagonal)); + let turn = frame.and_then(frame_placement::upright_turn).unwrap_or(0.0); + Some((*corners, size, turn)) + } + _ => None, + }; + let projection = &fill.projection; + let owner = sheet.ui.scope_id(); + let picture = |painter: &Painter, rect: Rect| match warp { + Some((corners, size, turn)) => warp_preview(painter, rect, corners, size, turn, placement, &tokens), + None => { + if projection_preview(painter, rect, projection, bounds, &tokens, owner).is_none() { + window_preview(painter, rect, placement, &tokens); + } + } + }; + let edit = sheet.preview_block(&picture, size_edit, lower); + crate::move_on_model::pad(app, sheet, edit.square, target); + + if linked != was_linked { + sheet.ui.data_mut(|data| data.insert_temp(link_id, linked)); + } + if let Some(merge) = edit.size + && values != shown + { + let tiling = match length { + Some(_) => tiling_for_length(&fill.projection, size, values.map(|cm| cm / CM_PER_UNIT)).unwrap_or(tiling), + None => values, + }; + run_projection(app, base, json!({"tiling": tiling, "merge": merge})); + } + if let Some(merge) = edit.lower { + let fields = match hardness { + Some(hardness) => json!({"sharpness": triplanar_sharpness(hardness), "merge": merge}), + None => json!({offset_key: lower_offset, "merge": merge}), + }; + run_projection(app, base, fields); + } + + let mut degrees = rotation; + if let Some(merge) = sheet.angle(tr("Rotation"), &mut degrees, ROTATION_RANGE) { + run_projection(app, base, json!({"rotation": degrees, "merge": merge})); + } +} + +/// One X, Y, Z row of the 3D projection settings +fn xyz_fields(values: [f32; 3], speed: f32, decimals: usize, suffix: &'static str) -> [NumberField<'static>; 3] { + std::array::from_fn(|axis| NumberField { tag: AXIS_NAMES[axis], tag_color: Some(AXIS_COLORS[axis]), value: values[axis], speed, decimals, suffix }) +} + +/// The 3D projection settings: the projector's Offset, Rotation and Scale in X, Y and Z; a frame on the surface shows its own (where its centre is, how it is turned, how big it is), the same values its gizmo drags +fn world_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, salt: FillKey) { + let Some(projector) = projector_of(&fill.projection) else { return }; + if !sheet.band(tr("3D projection settings"), true, None, None).open { + return; + } + + let edited = |fields: &[NumberField]| -> Vec { fields.iter().map(|field| field.value).collect() }; + + // A placed planar or a warp: the frame, its projector folded in + if let Some(shown) = frame_placement::placement(&fill.projection, app.session.mesh.bounds()) { + let run = |app: &mut TextureCraftApp, key: &str, values: Vec, merge: bool| { + app.run("layer.decal.set", with(base, json!({key: values, "merge": merge}))); + }; + let mut fields = xyz_fields(shown.offset, OFFSET_FIELD_SPEED, 2, ""); + if let Some((_, merge)) = sheet.number_fields(tr("Offset"), &mut fields, None, true) { + run(app, "frameOffset", edited(&fields), merge); + } + let mut fields = xyz_fields(shown.rotation, ROTATION_FIELD_SPEED, 0, "°"); + if let Some((_, merge)) = sheet.number_fields(tr("Rotation"), &mut fields, None, true) { + run(app, "frameRotation", edited(&fields), merge); + } + if let Some((scale, merge)) = scale_row(sheet, shown.scale, salt) { + run(app, "frameScale", scale, merge); + } + return; + } + + let offset = match &fill.projection { + Projection::Triplanar { offset, .. } + | Projection::Planar { offset, .. } + | Projection::Spherical { offset, .. } + | Projection::Cylindrical { offset, .. } => Some(*offset), + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => None, + }; + if let Some(offset) = offset { + let mut fields = xyz_fields(offset, OFFSET_FIELD_SPEED, 2, ""); + if let Some((_, merge)) = sheet.number_fields(tr("Offset"), &mut fields, None, true) { + run_projection(app, base, json!({"offset": edited(&fields), "merge": merge})); + } + } + let mut fields = xyz_fields(projector.rotation, ROTATION_FIELD_SPEED, 0, "°"); + if let Some((_, merge)) = sheet.number_fields(tr("Rotation"), &mut fields, None, true) { + run_projection(app, base, json!({"projectorRotation": edited(&fields), "merge": merge})); + } + if let Some((scale, merge)) = scale_row(sheet, projector.scale, salt) { + run_projection(app, base, json!({"projectorScale": scale, "merge": merge})); + } +} + +/// The least size of the edited axis's scale a linked edit scales the others from by a factor +const MIN_LINKED_SCALE_BASE: f32 = f32::EPSILON; + +/// The Scale X, Y, Z row with its link: the new scale and whether it continues the drag's undo step; linked, one field scales all three by the same factor +fn scale_row(sheet: &mut PropertySheet<'_>, scale: [f32; 3], salt: FillKey) -> Option<(Vec, bool)> { + let link_id = sheet.ui.make_persistent_id(("projector_scale_link", salt)); + let [x, y, z] = scale; + let mut linked = sheet.ui.data(|data| data.get_temp::(link_id)).unwrap_or(x == y && y == z); + let was_linked = linked; + let mut fields = xyz_fields(scale, SCALE_FIELD_SPEED, 2, ""); + let edit = sheet.number_fields(tr("Scale"), &mut fields, Some(&mut linked), false); + if linked != was_linked { + sheet.ui.data_mut(|data| data.insert_temp(link_id, linked)); + } + let (axis, merge) = edit?; + let mut values: Vec = fields.iter().map(|field| field.value).collect(); + if linked && let (Some(&value), Some(&before)) = (values.get(axis), scale.get(axis)) { + // From a scale of about zero no factor reaches the new value: all three take it instead + let factor = (before.abs() > MIN_LINKED_SCALE_BASE).then(|| value / before); + values = scale.iter().map(|old| factor.map_or(value, |factor| old * factor)).collect(); + } + Some((values, merge)) +} diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs new file mode 100644 index 00000000..25c48d60 --- /dev/null +++ b/crates/ui-egui/src/fill_pictures.rs @@ -0,0 +1,403 @@ +//! Pictures of what a fill's settings do: one per projection, filtering and UV wrap choice, the window preview and the ring of radial copies + +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, pos2, vec2}; +use texturecraft_engine::core::{FillSymmetry, Filtering, ShapeCrop, UvWrap}; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::placement::Placement; +use crate::projection_kind::ProjectionKind; +use crate::projection_preview::{edge_markers, passed_sides}; +use crate::warp_checker::warp_checker; + +use crate::theme::{Tokens, lerp_color}; + +/// The projection glyph's height, as a share of its picture's +const PROJECTION_GLYPH_SHARE: f32 = 0.85; + +/// The shape a projection wraps around, as an icon in the accent colour +pub(crate) fn projection_picture(painter: &Painter, rect: Rect, kind: ProjectionKind, tokens: &Tokens) { + use egui_phosphor::regular as icon; + let glyph = match kind { + ProjectionKind::UvTile | ProjectionKind::Uv => icon::SQUARE, + ProjectionKind::Triplanar => icon::CUBE, + ProjectionKind::Planar | ProjectionKind::Warp => icon::SELECTION, + ProjectionKind::Spherical => icon::GLOBE, + ProjectionKind::Cylindrical => icon::CYLINDER, + }; + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(rect.height() * PROJECTION_GLYPH_SHARE), tokens.accent); +} + +/// Cells across a magnified edge in the Filtering picture +const EDGE_CELLS: usize = 6; + +/// How steeply Bilinear Sharp ramps across the magnified edge: nearly a step +const SHARP_EDGE_RAMP: f32 = 3.0; + +/// How steeply Bilinear HQ ramps across the magnified edge: a soft blend +const HQ_EDGE_RAMP: f32 = 1.2; + +/// A magnified diagonal edge: smooth (HQ), crisp (Sharp) or stair-stepped (Nearest) +pub(crate) fn filtering_picture(painter: &Painter, rect: Rect, filtering: Filtering, tokens: &Tokens) { + let cell = rect.width() / EDGE_CELLS as f32; + for i in 0..EDGE_CELLS { + for j in 0..EDGE_CELLS { + let across = (i as f32 - j as f32) / EDGE_CELLS as f32; + let amount = match filtering { + Filtering::Nearest => f32::from(u8::from(i >= j)), + Filtering::BilinearSharp => (0.5 + across * SHARP_EDGE_RAMP).clamp(0.0, 1.0), + Filtering::BilinearHq => (0.5 + across * HQ_EDGE_RAMP).clamp(0.0, 1.0), + }; + let color = lerp_color(tokens.field, tokens.accent, amount); + let min = pos2(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell); + painter.rect_filled(Rect::from_min_size(min, vec2(cell, cell)), 0, color); + } + } +} + +/// Cells of the UV Wrap picture's grid +const WRAP_CELLS: usize = 3; + +/// The gap kept around each Wrap tile, in points +const WRAP_TILE_INSET: f32 = 0.75; + +/// A repeated tile's accent strength beside the own tile's +const WRAP_REPEAT_SHADE: f32 = 0.55; + +/// A 3 × 3 grid: the middle tile is the image's own; filled tiles are where it repeats +pub(crate) fn wrap_picture(painter: &Painter, rect: Rect, wrap: UvWrap, tokens: &Tokens) { + let (across, down) = wrap.repeats(); + let cell = rect.width() / WRAP_CELLS as f32; + let middle = WRAP_CELLS / 2; + for i in 0..WRAP_CELLS { + for j in 0..WRAP_CELLS { + let own = i == middle && j == middle; + let repeated = own || (across && j == middle) || (down && i == middle) || (across && down); + let tile = Rect::from_min_size(pos2(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell), vec2(cell, cell)).shrink(WRAP_TILE_INSET); + if own { + painter.rect_filled(tile, 1, tokens.accent); + } else if repeated { + painter.rect_filled(tile, 1, tokens.accent.gamma_multiply(WRAP_REPEAT_SHADE)); + } else { + painter.rect_stroke(tile, 1, Stroke::new(LINE_WIDTH, tokens.separator), egui::StrokeKind::Inside); + } + } + } +} + +/// Most tiles drawn across the window preview: beyond this the pattern is too fine to read +const PREVIEW_MAX_TILES: f32 = 24.0; + +/// The fewest tiles a preview shows, so a zero Tiling cannot divide by zero +pub(crate) const PREVIEW_MIN_TILES: f32 = 1e-3; + +/// Most tiles drawn along one direction of a lattice preview, whatever its map +const PREVIEW_MAX_SPAN: i32 = 64; + +/// The preview checker's dark cells, as a fraction of the way from `field` to `text` +const PREVIEW_DARK: f32 = 0.18; + +/// The preview checker's light cells, as a fraction of the way from `field` to `text` +const PREVIEW_LIGHT: f32 = 0.55; + +/// Where the mean of the checker's dark and light cells sits between them +const CHECKER_MEAN: f32 = 0.5; + +/// The width of every outline, border and ring line in these pictures +const LINE_WIDTH: f32 = 1.0; + +/// A lattice preview tile's checker cells, each half a tile wide, by the corner they start at in halves of a tile; even ones light +const TILE_CELLS: [(u8, u8); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)]; + +/// A checker cell's side in tiles: two cells across a tile +const CELL_SIDE: f32 = 0.5; + +/// The window's centre (0..1) before any slide +const WINDOW_MIDDLE: f32 = 0.5; + +/// A flatter map shows nothing: the window could not be undone from it +const MIN_MAP_DETERMINANT: f32 = 1e-9; + +/// A window on the surface that never moves: a UV checker (2 × 2 cells per tile, accent tile borders) tiled, turned and slid as the fill is, the ring in the middle where Offset 0 puts the projection, the filled dot where its Offset carried that point +pub(crate) fn window_preview(painter: &Painter, rect: Rect, placement: Placement, tokens: &Tokens) { + let (columns, carried) = slid_window(placement); + lattice_preview(painter, rect, (columns, placement.offset), true, tokens); + let position = pos2(rect.left() + carried[0] * rect.width(), rect.top() + carried[1] * rect.height()); + let painter = painter.with_clip_rect(rect.intersect(painter.clip_rect())); + crate::preview_dots::preview_dots(&painter, rect.center(), position, tokens); + edge_markers(&painter, rect, passed_sides(std::iter::once(position), rect), tokens); +} + +/// The window preview's map, and where the Offset carried the window's middle (0..1): the checker slides with it, so a drag right moves both right +fn slid_window(placement: Placement) -> ([[f32; 2]; 2], [f32; 2]) { + let tiling = placement.tiling.map(|tiles| tiles.clamp(PREVIEW_MIN_TILES, PREVIEW_MAX_TILES)); + let (sin, cos) = placement.rotation.to_radians().sin_cos(); + + // Turn, scale, then offset: one step across the window moves (cos, sin) scaled in the texture + let columns = [[cos * tiling[0], sin * tiling[1]], [-sin * tiling[0], cos * tiling[1]]]; + let [[a, b], [c, d]] = columns; + let det = a * d - c * b; + let [x, y] = placement.offset; + + // The window step the Offset is worth: the map undone; the image moves against the Offset it samples at + let moved = [(d * x - c * y) / det, (a * y - b * x) / det]; + let carried = if moved.iter().all(|value| value.is_finite()) { [WINDOW_MIDDLE - moved[0], WINDOW_MIDDLE - moved[1]] } else { [WINDOW_MIDDLE; 2] }; + (columns, carried) +} + +/// The window preview for any linear map: window point (u, v) shows the texture at `columns[0] · u + columns[1] · v + shift`; without `repeat` only tile 0..1 +pub(crate) fn lattice_preview(painter: &Painter, rect: Rect, (columns, shift): ([[f32; 2]; 2], [f32; 2]), repeat: bool, tokens: &Tokens) { + let painter = painter.with_clip_rect(rect); + painter.rect_filled(rect, 0, tokens.field); + let [[a, b], [c, d]] = columns; + let det = a * d - c * b; + if det.abs() > MIN_MAP_DETERMINANT && det.is_finite() && shift.iter().all(|value| value.is_finite()) { + // Texture coordinates → the window: undo the shift, then the map + let to_window = |t: [f32; 2]| -> Pos2 { + let (x, y) = (t[0] - shift[0], t[1] - shift[1]); + let (u, v) = ((d * x - c * y) / det, (a * y - b * x) / det); + pos2(rect.left() + u * rect.width(), rect.top() + v * rect.height()) + }; + let to_texture = |u: f32, v: f32| -> [f32; 2] { [a * u + c * v + shift[0], b * u + d * v + shift[1]] }; + let corners = [to_texture(0.0, 0.0), to_texture(1.0, 0.0), to_texture(0.0, 1.0), to_texture(1.0, 1.0)]; + let low = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::INFINITY, f32::min).floor() as i32; + let high = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::NEG_INFINITY, f32::max).ceil() as i32; + let span = |first: i32, last: i32| if repeat { first..last.min(first.saturating_add(PREVIEW_MAX_SPAN)) } else { first.max(0)..last.min(1) }; + let (dark, light) = (lerp_color(tokens.field, tokens.text, PREVIEW_DARK), lerp_color(tokens.field, tokens.text, PREVIEW_LIGHT)); + let border = Stroke::new(LINE_WIDTH, tokens.accent); + + // Repeating past the most tiles drawn, a tile is about a pixel: the window reads as the checker's mean, so the undrawn tiles leave no bare field + if repeat && (0..2).any(|axis| high(axis).saturating_sub(low(axis)) > PREVIEW_MAX_SPAN) { + painter.rect_filled(rect, 0, lerp_color(dark, light, CHECKER_MEAN)); + } + for tile_x in span(low(0), high(0)) { + for tile_y in span(low(1), high(1)) { + for (cell_x, cell_y) in TILE_CELLS { + let (x0, y0) = (tile_x as f32 + f32::from(cell_x) * CELL_SIDE, tile_y as f32 + f32::from(cell_y) * CELL_SIDE); + let corners = [[x0, y0], [x0 + CELL_SIDE, y0], [x0 + CELL_SIDE, y0 + CELL_SIDE], [x0, y0 + CELL_SIDE]].map(to_window); + let color = if (cell_x + cell_y) % 2 == 0 { light } else { dark }; + painter.add(Shape::convex_polygon(corners.to_vec(), color, Stroke::NONE)); + } + let (x, y) = (tile_x as f32, tile_y as f32); + painter.add(Shape::closed_line([[x, y], [x + 1.0, y], [x + 1.0, y + 1.0], [x, y + 1.0]].map(to_window).to_vec(), border)); + } + } + } + painter.rect_stroke(rect, 0, Stroke::new(LINE_WIDTH, tokens.field_border), egui::StrokeKind::Inside); +} + +/// How far the darker accent sits from the accent towards black +const ACCENT_SHADE: f32 = 0.36; + +/// The darker accent pictures fill with, beside the accent itself +fn accent_shade(tokens: &Tokens) -> Color32 { + lerp_color(tokens.accent, Color32::BLACK, ACCENT_SHADE) +} + +/// The margin inside a small setting picture, in points +const PICTURE_INSET: f32 = 3.0; + +/// Depth culling's hidden part, as a share of its picture's height +const DEPTH_UNDER_SHARE: f32 = 0.45; + +/// The arrow glyph's size in the Depth picture +const DEPTH_ARROW_SIZE: f32 = 9.0; + +/// The Angle picture's radius, as a share of its width +const ANGLE_RADIUS_SHARE: f32 = 0.45; + +/// The warp preview's outline width +const WARP_EDGE_WIDTH: f32 = 1.5; + +/// Corner radius of the crop picture's shape +const CROP_SHAPE_CORNER_RADIUS: u8 = 3; + +/// Corner radius of a fill that reaches a picture's edges +const PICTURE_CORNER_RADIUS: u8 = 2; + +/// Where the depth picture's surface sits, as a share of its height from the top +const DEPTH_SURFACE_SHARE: f32 = 0.25; + +/// Points what lies under the surface reaches past its share, so it still reads at small sizes +const DEPTH_UNDER_EXTRA: f32 = 2.0; + +/// How far the backface picture's face stays inside the picture's sides +const BACKFACE_SIDE_INSET: f32 = 2.0; + +/// Shape crop: the projection inside its shape only, or past it too +pub(crate) fn crop_picture(painter: &Painter, rect: Rect, crop: ShapeCrop, tokens: &Tokens) { + let inner = rect.shrink(PICTURE_INSET); + match crop { + ShapeCrop::Cropped => { + painter.rect_filled(inner, CROP_SHAPE_CORNER_RADIUS, accent_shade(tokens)); + } + ShapeCrop::ExtendsOutside => { + painter.rect_filled(rect, PICTURE_CORNER_RADIUS, accent_shade(tokens)); + } + } + painter.rect_stroke(inner, CROP_SHAPE_CORNER_RADIUS, Stroke::new(LINE_WIDTH, tokens.text), egui::StrokeKind::Inside); +} + +/// Depth culling, seen from the side: the surface the projection lands on and what lies under it +pub(crate) fn depth_picture(painter: &Painter, rect: Rect, tokens: &Tokens) { + let top = rect.top() + rect.height() * DEPTH_SURFACE_SHARE; + let under = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + rect.height() * DEPTH_UNDER_SHARE + DEPTH_UNDER_EXTRA)); + painter.rect_filled(under, PICTURE_CORNER_RADIUS, accent_shade(tokens)); + painter.line_segment([pos2(rect.left(), top), pos2(rect.right(), top)], Stroke::new(LINE_WIDTH, tokens.text)); + painter.text( + pos2(rect.center().x, rect.top() + PICTURE_INSET), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::ARROW_DOWN, + egui::FontId::proportional(DEPTH_ARROW_SIZE), + tokens.accent, + ); +} + +/// Backface culling: a face turned away, darker while culled +pub(crate) fn backface_picture(painter: &Painter, rect: Rect, on: bool, tokens: &Tokens) { + let (left, apex, right) = ( + pos2(rect.left() + BACKFACE_SIDE_INSET, rect.bottom() - PICTURE_INSET), + pos2(rect.center().x, rect.top() + PICTURE_INSET), + pos2(rect.right() - BACKFACE_SIDE_INSET, rect.bottom() - PICTURE_INSET), + ); + painter.add(Shape::convex_polygon(vec![left, apex, right], if on { accent_shade(tokens) } else { tokens.accent }, Stroke::NONE)); + painter.line_segment([apex, right], Stroke::new(LINE_WIDTH, tokens.text)); +} + +/// Points around the Angle picture's arc per full turn +const ARC_POINTS: usize = 48; + +/// The angle and ring pictures start at the top: a quarter turn back from +x (egui's y points down), in turns +const TOP_START_TURNS: f32 = 0.25; + +/// A cylindrical projection's Angle seen from above: the slice of a turn one repeat spans +pub(crate) fn angle_picture(painter: &Painter, rect: Rect, degrees: f32, tokens: &Tokens) { + let center = rect.center(); + let radius = rect.width() * ANGLE_RADIUS_SHARE; + let sweep = degrees.clamp(0.0, FULL_TURN_DEGREES) / FULL_TURN_DEGREES; + if sweep >= 1.0 { + painter.circle_filled(center, radius, tokens.accent); + } else { + let steps = ((ARC_POINTS as f32 * sweep).ceil() as usize).max(1); + let mut points = vec![center]; + for step in 0..=steps { + let turn = (step as f32 / steps as f32 * sweep - TOP_START_TURNS) * std::f32::consts::TAU; + points.push(pos2(center.x + radius * turn.cos(), center.y + radius * turn.sin())); + } + + // A slice wider than half a turn is not convex: fill it as a fan from the centre + for pair in points[1..].windows(2) { + painter.add(Shape::convex_polygon(vec![center, pair[0], pair[1]], tokens.accent, Stroke::NONE)); + } + } + painter.circle_stroke(center, radius, Stroke::new(LINE_WIDTH, tokens.button_border)); +} + +/// How much of the preview an unpulled frame spans per mesh diagonal of its side (a new warp's frame round a ball spans about 0.62) +const WARP_SPAN_PER_DIAGONAL: f32 = 1.07; +/// The least and most of the preview a frame's side spans +const WARP_SPAN_RANGE: std::ops::RangeInclusive = 0.05..=0.95; + +/// Radius of a warp preview's corner handle +const WARP_HANDLE_RADIUS: f32 = 3.5; + +/// A warp's frame with its corners where they are pulled, the checker bending with them and laid as `placement` lays the image (tiling, rotation, offset); `size` is the frame's width and height in mesh diagonals, `turn` its turn round its normal (degrees), so resizing or turning the frame shows +pub(crate) fn warp_preview(painter: &Painter, rect: Rect, corners: [[f32; 2]; 4], size: [f32; 2], turn: f32, placement: Placement, tokens: &Tokens) { + let painter = painter.with_clip_rect(rect); + painter.rect_filled(rect, 0, tokens.field); + let span = size.map(|side| (side * WARP_SPAN_PER_DIAGONAL).clamp(*WARP_SPAN_RANGE.start(), *WARP_SPAN_RANGE.end())); + let (sin, cos) = turn.to_radians().sin_cos(); + + // Across and up in frame sizes from its centre -> turned -> the square + let [top_left, top_right, bottom_right, bottom_left] = corners.map(|[x, y]| { + let (x, y) = (x * span[0], y * span[1]); + let (x, y) = (x * cos - y * sin, x * sin + y * cos); + pos2(rect.center().x + x * rect.width(), rect.center().y - y * rect.height()) + }); + let (dark, light) = (lerp_color(tokens.field, tokens.text, PREVIEW_DARK), lerp_color(tokens.field, tokens.text, PREVIEW_LIGHT)); + for (outline, lit) in warp_checker([top_left, top_right, bottom_right, bottom_left], placement) { + painter.add(Shape::convex_polygon(outline, if lit { light } else { dark }, Stroke::NONE)); + } + let edge = [top_left, top_right, bottom_right, bottom_left]; + painter.add(Shape::closed_line(edge.to_vec(), Stroke::new(WARP_EDGE_WIDTH, tokens.accent))); + for corner in edge { + painter.circle(corner, WARP_HANDLE_RADIUS, tokens.text, Stroke::new(LINE_WIDTH, tokens.accent)); + } + painter.rect_stroke(rect, 0, Stroke::new(LINE_WIDTH, tokens.field_border), egui::StrokeKind::Inside); +} + +/// The ring's radius, in the picture's widths +const RING_RADIUS: f32 = 0.34; + +/// The radius of the axis's dot at the ring's centre +const RING_AXIS_DOT: f32 = 2.0; + +/// The radius of each copy's dot on the ring +const RING_COPY_DOT: f32 = 3.5; + +/// The straight pieces the ring is drawn with +const RING_SEGMENTS: usize = 64; + +/// Radial copies seen along their axis: the axis at the centre (its colour), the original (white) at the top and the other copies (accent) round the ring, spaced as the engine spaces them +pub(crate) fn ring_picture(painter: &Painter, rect: Rect, symmetry: &FillSymmetry, axis_color: Color32, tokens: &Tokens) { + painter.rect_filled(rect, 0, tokens.field); + let center = rect.center(); + let radius = rect.width() * RING_RADIUS; + let at = |degrees: f32| { + let turn = (degrees - TOP_START_TURNS * FULL_TURN_DEGREES).to_radians(); + center + vec2(turn.cos(), turn.sin()) * radius + }; + + // The ring runs over the span the engine spreads the copies over: a stored span past a full turn or below none reads as the engine reads it + let ring_end = symmetry.span.clamp(0.0, FULL_TURN_DEGREES); + let ring: Vec = (0..=RING_SEGMENTS).map(|k| at(ring_end * k as f32 / RING_SEGMENTS as f32)).collect(); + painter.add(Shape::line(ring, Stroke::new(LINE_WIDTH, tokens.separator))); + painter.circle_filled(center, RING_AXIS_DOT, axis_color); + for (k, degrees) in copy_angles(symmetry).enumerate() { + let color = if k == 0 { tokens.text } else { tokens.accent }; + painter.circle_filled(at(degrees), RING_COPY_DOT, color); + } +} + +/// The degrees each radial copy of `symmetry` turns, the original's 0 first, from the engine's count and spacing +fn copy_angles(symmetry: &FillSymmetry) -> impl Iterator { + let step = symmetry.step(); + (0..symmetry.copies()).map(move |k| k as f32 * step) +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::SymmetryKind; + + use super::*; + + /// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another + #[test] + fn the_ring_spaces_its_copies_as_the_engine_does() { + let symmetry = FillSymmetry { on: true, kind: SymmetryKind::Radial, count: 6, span: 720.0, ..FillSymmetry::OFF }; + + let angles: Vec = copy_angles(&symmetry).collect(); + + assert_eq!(angles, [0.0, 60.0, 120.0, 180.0, 240.0, 300.0]); + } + + /// The UV view stands still: the checker slides with the Offset as on the model, and the filled dot (the window's middle, carried) slides with it, the way a drag moves them + #[test] + fn the_uv_view_stands_still_and_the_dot_slides_with_the_checker() { + let placement = |offset: [f32; 2]| Placement { tiling: [2.0, 2.0], rotation: 30.0, offset }; + let (still, rest) = slid_window(placement([0.0, 0.0])); + assert_eq!(rest, [0.5, 0.5], "at Offset 0 the dot sits in the ring"); + let slid = placement([-0.25, 0.0]); + let (columns, dot) = slid_window(slid); + assert_eq!(columns, still, "the view never zooms or turns for the Offset"); + + // A pad drag right lowers the Offset: the dot goes right, an eighth of the window along the turned U + let expected = [0.5 + 0.125 * 30f32.to_radians().cos(), 0.5 - 0.125 * 30f32.to_radians().sin()]; + assert!((dot[0] - expected[0]).abs() < 1e-5 && (dot[1] - expected[1]).abs() < 1e-5, "{dot:?} vs {expected:?}"); + + // The checker point under the middle at Offset 0 shows under the dot now + let [[a, b], [c, d]] = columns; + let texture_at = |[u, v]: [f32; 2], offset: [f32; 2]| [a * u + c * v + offset[0], b * u + d * v + offset[1]]; + let (before, after) = (texture_at([0.5, 0.5], [0.0, 0.0]), texture_at(dot, slid.offset)); + assert!((before[0] - after[0]).abs() < 1e-5 && (before[1] - after[1]).abs() < 1e-5, "{before:?} vs {after:?}"); + } +} diff --git a/crates/ui-egui/src/move_hold.rs b/crates/ui-egui/src/move_hold.rs new file mode 100644 index 00000000..c07dc553 --- /dev/null +++ b/crates/ui-egui/src/move_hold.rs @@ -0,0 +1,15 @@ +//! A Move on model hold under way, kept in egui's memory between frames + +use egui::Pos2; + +use crate::move_on_model::MoveOnModel; + +/// The Move on model button held down: the fill it moves, where the pointer was on the last frame and the session revision its last edit left (its undo step, while the history is still there) +#[derive(Clone, Copy, Debug)] +pub(crate) struct MoveHold { + pub target: MoveOnModel, + pub last: Pos2, + pub edited_revision: Option, + /// The pass that last applied it: a sheet drawn twice in one frame moves the projection once + pub pass: u64, +} diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs new file mode 100644 index 00000000..0871d95e --- /dev/null +++ b/crates/ui-egui/src/move_on_model.rs @@ -0,0 +1,498 @@ +//! Move on model: hold the preview square and drag to slide the selected fill's projection, with Shift or the right button held to turn it, and turn the wheel to scale it. The pointer is held while it lasts (hidden, no screen edge stops it, back where the press began when let go). Letting go ends it, as one undo step; the 3D view keeps its own drags and wheel + +use egui::{CursorIcon, Pos2, Rect}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, LayerId, LayerKind, Projection}; + +use crate::TextureCraftApp; +use crate::frame_gizmo::FrameGizmo; +use crate::i18n::tr; +use crate::move_hold::MoveHold; +use crate::property_sheet::PropertySheet; +use crate::round_gizmo::RoundGizmo; + +/// The fill whose projection Move on model moves: a fill layer, or a content fill effect in it +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MoveOnModel { + pub layer: LayerId, + pub effect: Option, +} + +impl MoveOnModel { + /// A fill layer's own projection + pub(crate) fn layer(layer: LayerId) -> MoveOnModel { + MoveOnModel { layer, effect: None } + } + + /// The `layer` or `effect` param of the fill commands + pub(crate) fn target(self) -> Value { + match self.effect { + Some(effect) => json!({"effect": effect.0}), + None => json!({"layer": self.layer.0}), + } + } + + /// The selected fill layer, or the selected fill effect in it (its content or its mask); its projector shows in the 3D view + pub(crate) fn selected(app: &TextureCraftApp) -> Option { + let layer = app.session.selected_layer()?; + let effect = match app.session.target { + texturecraft_engine::StackTarget::Content => None, + texturecraft_engine::StackTarget::Effect(effect) => Some(effect), + texturecraft_engine::StackTarget::Mask => return None, + }; + Some(MoveOnModel { layer, effect }) + } + + pub(crate) fn projection(self, app: &TextureCraftApp) -> Option { + let project = &app.session.doc.project; + match self.effect { + Some(effect) => match &project.effect(effect)?.1.kind { + EffectKind::Material(fill) => Some(fill.projection.clone()), + EffectKind::Fill { projection, .. } => Some(projection.clone()), + _ => None, + }, + None => match &project.layer(self.layer).ok()?.kind { + LayerKind::Fill(fill) => Some(fill.projection.clone()), + _ => None, + }, + } + } +} + +fn hold_id() -> egui::Id { + egui::Id::unique("tc_move_on_model_hold") +} + +/// Image repeats a drag across the view's height slides by +const SLIDE_PER_HEIGHT: f32 = 1.0; +/// Degrees a turning drag turns per point +const TURN_PER_POINT: f32 = 0.5; +/// Growth per wheel point (exponential) +const SCALE_PER_WHEEL_POINT: f32 = 0.0015; + +/// Move on model on `target`'s preview square: while it is held down it moves the projection +pub(crate) fn pad(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, square: Rect, target: MoveOnModel) { + let held = app.moving_on_model == Some(target); + let mut response = sheet.hold_pad(square, ic::HAND, tr("Move on model"), held); + if !held { + response = sheet.tip_beside(response, tr("Hold and drag to slide the projection; Shift or the right button turns it, the wheel scales it")); + } + let ctx = sheet.ui.ctx().clone(); + hold(app, &ctx, &response, target); +} + +/// Whether a Move on model hold is under way, or let go this frame (that release is no click in the view); the 3D view then keeps its camera, brush and gizmos still. Ends a hold whose window lost the focus +pub(crate) fn holding(app: &mut TextureCraftApp, ctx: &egui::Context) -> bool { + let held = app.moving_on_model.is_some(); + if held && !still_pressed(ctx) { + end(app, ctx); + } + held +} + +/// Ends a hold whose fill or pad went away, once a frame whichever views show +pub(crate) fn end_when_gone(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(target) = app.moving_on_model else { return }; + + if target.projection(app).is_none() || pad_gone(ctx) { + end(app, ctx); + } +} + +/// Whether the held pad was not drawn last pass nor this one (its layer was deselected, its panel hidden) +fn pad_gone(ctx: &egui::Context) -> bool { + let last_drawn = ctx.data(|data| data.get_temp::(hold_id())).map(|held| held.pass); + last_drawn.is_none_or(|pass| pass.saturating_add(1) < ctx.cumulative_pass_nr()) +} + +/// Whether the left button still holds: a window that lost the focus gets no release, so the hold ends there as on one +fn still_pressed(ctx: &egui::Context) -> bool { + ctx.input(|input| input.pointer.primary_down()) && !crate::viewport::focus_lost(ctx) +} + +/// Ends the hold where it is: its edits stay one undo step +fn end(app: &mut TextureCraftApp, ctx: &egui::Context) { + app.moving_on_model = None; + ctx.data_mut(|data| data.remove::(hold_id())); +} + +/// A press on the pad starts the hold; each frame until the left button lets go, pointer moves and wheel steps edit the projection +fn hold(app: &mut TextureCraftApp, ctx: &egui::Context, pad: &egui::Response, target: MoveOnModel) { + let primary = still_pressed(ctx); + let (pressed, turn, pointer) = + ctx.input(|input| (input.pointer.primary_pressed(), input.modifiers.shift || input.pointer.secondary_down(), input.pointer.latest_pos())); + let pass = ctx.cumulative_pass_nr(); + let mut held = ctx.data(|data| data.get_temp::(hold_id())).filter(|held| held.target == target); + + // Only a fresh press starts it: after a focus loss egui still has the left button down + if held.is_none() + && primary + && pressed + && pad.is_pointer_button_down_on() + && let Some(at) = pointer + { + held = Some(MoveHold { target, last: at, edited_revision: None, pass: pass.wrapping_sub(1) }); + } + + let Some(mut held) = held.filter(|_| primary && target.projection(app).is_some()) else { + if app.moving_on_model == Some(target) { + end(app, ctx); + } + if pad.hovered() { + ctx.set_cursor_icon(CursorIcon::Grab); + } + return; + }; + + app.moving_on_model = Some(target); + crate::pointer_lock::ask_for_hold(ctx); + if held.pass == pass { + return; + } + + held.pass = pass; + + let rect = app.viewport_rect; + if let Some(at) = pointer.filter(|at| *at != held.last) { + if let Some((command, params)) = dragged(app, target, held.last, at, turn, rect) { + step(app, &mut held, command, params); + } + held.last = at; + } + + // The wheel scales the projection instead of scrolling the panel or zooming the camera while the pad is held + let wheel = ctx.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta).y); + if wheel != 0.0 + && let Some((command, params)) = resized(app, target, (SCALE_PER_WHEEL_POINT * wheel).exp(), rect) + { + step(app, &mut held, command, params); + } + + ctx.data_mut(|data| data.insert_temp(hold_id(), held)); + + // The panel drew before this edit: one more frame shows its fields and preview where the projection is now + ctx.request_repaint(); +} + +/// Runs one edit of the hold; the edits after the first that changed something join its undo step +fn step(app: &mut TextureCraftApp, held: &mut MoveHold, command: &str, params: Value) { + crate::projection_gizmo::edit_in_one_step(&mut app.session, command, params, &mut held.edited_revision); +} + +/// The selected planar or warp frame of a fill layer or of a mask fill effect, which moves by its frame +fn frame_of(app: &TextureCraftApp, target: MoveOnModel, rect: Rect) -> Option { + FrameGizmo::of(app, rect).filter(|gizmo| match target.effect { + Some(effect) => gizmo.effect == Some(effect), + None => gizmo.layer == target.layer && gizmo.effect.is_none(), + }) +} + +/// The `layer` (and for a mask fill `effect`) params of `layer.decal.set` editing `gizmo`'s frame, added to `params` +fn frame_target(mut params: Value, gizmo: &FrameGizmo) -> Value { + params["layer"] = json!(gizmo.layer.0); + if let Some(effect) = gizmo.effect { + params["effect"] = json!(effect.0); + } + params +} + +/// A projection's UV tiling, rotation and offset (None for Fill (Match per UV Tile)) +fn placement(projection: &Projection) -> Option<([f32; 2], f32, [f32; 2])> { + match projection { + Projection::UvTile => None, + Projection::Uv { scale, rotation, offset } => Some((*scale, *rotation, *offset)), + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => Some((uv.tiling, uv.rotation, uv.offset)), + } +} + +/// The edit a pointer move from `from` to `to` makes: a frame or projector slides by it, a UV image slides; with `turn` it turns instead +fn dragged(app: &TextureCraftApp, target: MoveOnModel, from: Pos2, to: Pos2, turn: bool, rect: Rect) -> Option<(&'static str, Value)> { + let delta = to - from; + if let Some(gizmo) = frame_of(app, target, rect) { + let params = if turn { json!({"rotation": gizmo.decal.rotation - delta.x * TURN_PER_POINT}) } else { json!({"offset": gizmo.slid_on_screen(delta)?}) }; + return Some(("layer.decal.set", frame_target(params, &gizmo))); + } + + if !turn && let Some(round) = RoundGizmo::of(app, rect).filter(|round| round.target == target) { + return Some(("layer.fill.projection", round.slid(app, rect, from, to)?)); + } + + let projection = target.projection(app)?; + let (_, rotation, offset) = placement(&projection)?; + let slide = delta * SLIDE_PER_HEIGHT / rect.height().max(1.0); + let offset = [offset[0] - slide.x, offset[1] - slide.y]; + let mut params = match (turn, projection) { + (true, _) => json!({"rotation": rotation + delta.x * TURN_PER_POINT}), + (false, Projection::Uv { .. }) => json!({"offset": offset}), + (false, _) => json!({"uvOffset": offset}), + }; + merge_target(&mut params, target); + Some(("layer.fill.projection", params)) +} + +/// The edit a wheel step growing the projection by `growth` makes: a frame grows, other projections' images repeat less +fn resized(app: &TextureCraftApp, target: MoveOnModel, growth: f32, rect: Rect) -> Option<(&'static str, Value)> { + if let Some(gizmo) = frame_of(app, target, rect) { + let [width, height] = gizmo.decal.size; + return Some(("layer.decal.set", frame_target(json!({"size": [width * growth, height * growth]}), &gizmo))); + } + + let (tiling, _, _) = placement(&target.projection(app)?)?; + let mut params = json!({"tiling": [tiling[0] / growth, tiling[1] / growth]}); + merge_target(&mut params, target); + Some(("layer.fill.projection", params)) +} + +/// Adds the `layer` or `effect` param naming `target` to `params` +fn merge_target(params: &mut Value, target: MoveOnModel) { + if let (Some(params), Value::Object(fields)) = (params.as_object_mut(), target.target()) { + params.extend(fields); + } +} + +#[cfg(test)] +mod tests { + use egui::{Modifiers, PointerButton, vec2}; + use egui_kittest::kittest::Queryable; + use texturecraft_engine::core::{Projection, UvTransform}; + + use super::*; + use crate::frame_gizmo::tests::{drag, fill_app, projection}; + use crate::pointer_lock::system_pointer::SystemPointer; + use crate::round_gizmo::tests::on_the_model_off_the_handles; + use crate::state::ViewLayout; + + type Harness = egui_kittest::Harness<'static, TextureCraftApp>; + + fn uv_of(projection: &Projection) -> UvTransform { + match projection { + Projection::Triplanar { uv, .. } => *uv, + other => panic!("tri-planar: {other:?}"), + } + } + + fn projector_offset(projection: &Projection) -> [f32; 3] { + match projection { + Projection::Triplanar { offset, .. } => *offset, + other => panic!("tri-planar: {other:?}"), + } + } + + /// Presses the left button on Move on model (the preview square) and holds it; returns the system's pointer, resting there + fn press_the_button(harness: &mut Harness) -> SystemPointer { + let at = harness.get_by_label("Move on model").rect().center(); + let mut pointer = SystemPointer::at(harness, at); + pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE); + pointer + } + + /// A wheel step up where the pointer is, over a few frames as the wheel scrolls smoothly + fn wheel(harness: &mut Harness, pointer: &mut SystemPointer) { + harness.input_mut().events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 120.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: Modifiers::NONE, + }); + for _ in 0..6 { + pointer.frame(harness); + } + } + + /// Lets go of the left button, and lets a frame show where the pointer came back to + fn let_go(harness: &mut Harness, pointer: &mut SystemPointer) { + pointer.button(harness, PointerButton::Primary, false, Modifiers::NONE); + pointer.frame(harness); + } + + /// Holding the pad and dragging carries the projector with the mouse, the pointer hidden and kept on the pad; letting go ends it there + #[test] + fn holding_the_button_and_dragging_carries_the_projector_as_one_undo_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let rect = harness.state().viewport_rect; + let before = RoundGizmo::of(harness.state(), rect).unwrap(); + let (steps, camera) = (harness.state().session.history_labels().len(), harness.state().session.camera); + + let mut pointer = press_the_button(&mut harness); + let from = pointer.at; + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press starts the hold"); + let moved = vec2(-300.0, -20.0); + pointer.drags(&mut harness, moved, 30, Modifiers::NONE); + let after = RoundGizmo::of(harness.state(), rect).unwrap(); + assert!((after.center - (before.center + moved)).length() < 2.0, "the projector follows the mouse: {:?} -> {:?}", before.center, after.center); + assert!(pointer.hidden, "the pointer hides while held"); + assert!(pointer.at.distance(from) < 1.0, "and stays on the pad, so no screen edge stops the drag: {:?}", pointer.at); + let slid = projection(&harness, layer); + assert_ne!(projector_offset(&slid), [0.0; 3], "the projector itself moved: {slid:?}"); + assert_eq!(uv_of(&slid), UvTransform::default(), "not only the image inside it"); + + let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().moving_on_model, None, "letting go ends it"); + assert!(!pointer.hidden && pointer.at == from, "the pointer shows again where the press began: {:?}", pointer.at); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per hold"); + assert_eq!(harness.state().session.camera, camera, "the camera kept still"); + + // The 3D view has its drags back: a drag on the model off the projector's handles moves nothing + let off = on_the_model_off_the_handles(&harness); + drag(&mut harness, off, off + vec2(60.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), slid, "no mode is left on"); + } + + /// Losing the focus mid-hold (Alt+Tab) ends it as letting go does: one undo step, the pointer shown, and moves after it (egui still has the button down) leave the projection alone + #[test] + fn losing_the_window_focus_mid_hold_ends_it_as_letting_go_does() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let steps = harness.state().session.history_labels().len(); + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "the hold is under way"); + + harness.input_mut().events.push(egui::Event::WindowFocused(false)); + pointer.frame(&mut harness); + let left = projection(&harness, layer); + assert_eq!(harness.state().moving_on_model, None, "the focus loss ends the hold"); + assert!(!pointer.hidden, "the pointer shows again"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step, as letting go makes"); + + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, None, "the button still down in egui starts no new hold"); + assert_eq!(projection(&harness, layer), left, "moves after it leave the projection alone"); + } + + /// Removing the held fill mid-hold (its pad goes with it) ends the hold at once, the button still down, with or without the 3D view: the pointer shows + #[test] + fn removing_the_held_fill_ends_the_hold() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for layout in [ViewLayout::Split, ViewLayout::Only2D] { + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().ui.layout = layout; + harness.run_steps(2); + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "{layout:?}: the hold is under way"); + + harness.state_mut().run("layer.remove", json!({"layer": layer.0})).unwrap(); + pointer.frame(&mut harness); + assert_eq!(harness.state().moving_on_model, None, "{layout:?}: the hold ended with its fill"); + assert!(!pointer.hidden, "{layout:?}: the pointer shows again"); + } + } + + /// The preview square is the pad: a press anywhere on it, its corner too, starts the hold and holds the pointer + #[test] + fn the_preview_square_is_the_pad_from_corner_to_corner() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let pad = harness.get_by_label("Move on model").rect(); + assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}"); + let before = projection(&harness, layer); + let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0)); + pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold"); + pointer.drags(&mut harness, vec2(40.0, 0.0), 10, Modifiers::NONE); + assert!(pointer.hidden, "the pointer is held"); + let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), before, "the drag moved the projection"); + assert_eq!(harness.state().moving_on_model, None); + } + + /// While held, Shift or the right button turns the image and the wheel scales it, all in the hold's one undo step; the camera neither orbits nor zooms. Released, the wheel zooms again + #[test] + fn shift_or_the_right_button_turns_and_the_wheel_scales_while_held() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let rect = harness.state().viewport_rect; + let (steps, camera) = (harness.state().session.history_labels().len(), harness.state().session.camera); + let mut pointer = press_the_button(&mut harness); + let from = pointer.at; + + pointer.drags(&mut harness, vec2(-40.0, 0.0), 30, Modifiers::SHIFT); + let shifted = uv_of(&projection(&harness, layer)); + assert!(shifted.rotation > 0.0, "Shift turns the image: {shifted:?}"); + assert_eq!(projector_offset(&projection(&harness, layer)), [0.0; 3], "and does not slide it"); + + // The right button pressed once the drag has carried the held pointer over the 3D view, the left still holding the button + let over_view = rect.center() + vec2(-100.0, 80.0); + pointer.drags(&mut harness, over_view - (from + vec2(-40.0, 0.0)), 30, Modifiers::NONE); + let slid = projection(&harness, layer); + pointer.button(&mut harness, PointerButton::Secondary, true, Modifiers::NONE); + pointer.drags(&mut harness, vec2(-40.0, 0.0), 30, Modifiers::NONE); + let turned = projection(&harness, layer); + assert!(uv_of(&turned).rotation < shifted.rotation, "the right button turns it: {shifted:?} -> {turned:?}"); + assert_eq!(projector_offset(&turned), projector_offset(&slid), "without sliding"); + pointer.button(&mut harness, PointerButton::Secondary, false, Modifiers::NONE); + + wheel(&mut harness, &mut pointer); + let scaled = uv_of(&projection(&harness, layer)); + assert!(scaled.tiling[0] < uv_of(&turned).tiling[0] && scaled.tiling[0] == scaled.tiling[1], "the wheel up makes the image bigger: {scaled:?}"); + assert_eq!(harness.state().session.camera, camera, "the camera neither orbited nor zoomed"); + assert!(harness.state().properties_popup.is_none(), "the right click opened no Properties popup"); + + let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the whole hold is one undo step"); + let back = pointer.at; + pointer.moves(&mut harness, over_view - back, Modifiers::NONE); + wheel(&mut harness, &mut pointer); + assert_ne!(harness.state().session.camera, camera, "let go, the wheel zooms the camera"); + assert_eq!(uv_of(&projection(&harness, layer)), scaled, "and leaves the projection alone"); + } + + /// A hold whose first edit changes nothing (Shift with an up and down drag turns a frame by nothing) makes no undo step, so its later edits make the hold's own step instead of joining the edit before it + #[test] + fn a_hold_that_first_changes_nothing_keeps_its_own_undo_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30.0})).unwrap(); + harness.run_steps(2); + let turned = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::SHIFT); + assert_eq!(projection(&harness, layer), turned, "an up and down turn changes nothing"); + pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), turned, "the slide moved the frame"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the hold made its own undo step"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), turned, "undo takes back the hold only"); + } + + /// A UV image slides as far as the mouse goes, past the window's edge; a warp's frame slides across its plane + #[test] + fn a_hold_slides_a_uv_image_and_a_frame_across_its_plane() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("uv"); + let height = harness.state().viewport_rect.height(); + let mut pointer = press_the_button(&mut harness); + let from = pointer.at; + wheel(&mut harness, &mut pointer); + assert_eq!(harness.get_by_label("Move on model").rect().center(), from, "a wheel step over the panel while held scales, it does not scroll the panel"); + let Projection::Uv { scale, .. } = projection(&harness, layer) else { panic!("still UV") }; + assert!(scale[0] < 1.0, "the wheel up makes the image bigger: {scale:?}"); + let far = vec2(-3.0 * from.x, 0.0); + pointer.drags(&mut harness, far, 60, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + let Projection::Uv { offset, .. } = projection(&harness, layer) else { panic!("still UV") }; + assert!( + (offset[0] - (-far.x) * SLIDE_PER_HEIGHT / height).abs() < 0.01 && offset[1] == 0.0, + "a drag left slides the image left, all the way: {offset:?}" + ); + + let (mut harness, layer) = fill_app("warp"); + let mut pointer = press_the_button(&mut harness); + pointer.drags(&mut harness, vec2(0.0, -40.0), 30, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + let Projection::Warp { frame, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert!(frame.offset[1] > 0.0 && frame.offset[0].abs() < frame.offset[1] * 0.2, "a drag up slides the frame up: {frame:?}"); + } +} diff --git a/crates/ui-egui/src/preview_dots.rs b/crates/ui-egui/src/preview_dots.rs new file mode 100644 index 00000000..09af91a8 --- /dev/null +++ b/crates/ui-egui/src/preview_dots.rs @@ -0,0 +1,53 @@ +//! The preview square's two dots: a ring where the projection sits with Offset 0, a filled dot where its Offset puts it, a dotted line between + +use egui::{Painter, Pos2, Stroke}; + +use crate::theme::Tokens; + +/// The ring's radius (points) +const RING_RADIUS: f32 = 5.5; + +/// The ring's line width (points) +const RING_LINE: f32 = 1.6; + +/// The width of the line under the ring that keeps it readable on the checker (points) +const RING_UNDER: f32 = 3.6; + +/// The filled dot's radius (points) +const DOT_RADIUS: f32 = 3.3; + +/// The width of the rim under the filled dot (points) +const DOT_RIM: f32 = 1.0; + +/// The dotted line's air between its dots (points) +const LINE_SPACING: f32 = 3.5; + +/// The radius of the dotted line's dots (points) +const LINE_DOT: f32 = 0.9; + +/// The width of the rim under the dotted line's dots (points) +const LINE_RIM: f32 = 0.6; + +/// Most dots the line draws: more than any preview square holds, the rest would be cut off anyway +const MAX_LINE_DOTS: usize = 256; + +/// Paints the two dots and the dotted line between them, from the filled dot out so a ring far past the square still gets its line +pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, tokens: &Tokens) { + let span = center - position; + let length = span.length(); + let start = DOT_RADIUS + LINE_SPACING; + let end = length - RING_RADIUS - LINE_SPACING / 2.0; + if length.is_finite() && end > start { + let toward = span / length; + let count = (((end - start) / LINE_SPACING).floor() as usize).min(MAX_LINE_DOTS); + for step in 0..=count { + let at = position + toward * (start + step as f32 * LINE_SPACING); + painter.circle_filled(at, LINE_DOT + LINE_RIM, tokens.field); + painter.circle_filled(at, LINE_DOT, tokens.text); + } + } + painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_UNDER, tokens.field)); + painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_LINE, tokens.text)); + painter.circle_filled(position, DOT_RADIUS + DOT_RIM, tokens.field); + painter.circle_filled(position, DOT_RADIUS, tokens.text); +} diff --git a/crates/ui-egui/src/projection_kind.rs b/crates/ui-egui/src/projection_kind.rs new file mode 100644 index 00000000..4d3b676c --- /dev/null +++ b/crates/ui-egui/src/projection_kind.rs @@ -0,0 +1,68 @@ +//! The projections a fill's Projection dropdown offers + +use texturecraft_engine::core::Projection; + +use crate::i18n::n_; + +/// The projections a fill's Projection dropdown offers, with their command ids +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ProjectionKind { + UvTile, + Uv, + Triplanar, + Planar, + Spherical, + Cylindrical, + Warp, +} + +impl ProjectionKind { + pub(crate) const ALL: [ProjectionKind; 7] = [ + ProjectionKind::UvTile, + ProjectionKind::Uv, + ProjectionKind::Triplanar, + ProjectionKind::Planar, + ProjectionKind::Warp, + ProjectionKind::Spherical, + ProjectionKind::Cylindrical, + ]; + + /// The `projection` param of `layer.fill.projection` + pub(crate) fn id(self) -> &'static str { + match self { + ProjectionKind::UvTile => "uvTile", + ProjectionKind::Uv => "uv", + ProjectionKind::Triplanar => "triplanar", + ProjectionKind::Planar => "planar", + ProjectionKind::Spherical => "spherical", + ProjectionKind::Cylindrical => "cylindrical", + ProjectionKind::Warp => "warp", + } + } + + /// The kind `projection` is, as the Projection dropdown lists it + pub(crate) fn of(projection: &Projection) -> ProjectionKind { + match projection { + Projection::UvTile => ProjectionKind::UvTile, + Projection::Uv { .. } => ProjectionKind::Uv, + Projection::Triplanar { .. } => ProjectionKind::Triplanar, + Projection::Planar { .. } => ProjectionKind::Planar, + Projection::Spherical { .. } => ProjectionKind::Spherical, + Projection::Cylindrical { .. } => ProjectionKind::Cylindrical, + Projection::Warp { .. } => ProjectionKind::Warp, + } + } + + /// The dropdown's name for it + pub(crate) fn label(self) -> &'static str { + match self { + ProjectionKind::UvTile => n_("Fill (Match per UV Tile)"), + ProjectionKind::Uv => n_("UV projection"), + ProjectionKind::Triplanar => n_("Tri-planar projection"), + ProjectionKind::Planar => n_("Planar projection"), + ProjectionKind::Spherical => n_("Spherical projection"), + ProjectionKind::Cylindrical => n_("Cylindrical projection"), + ProjectionKind::Warp => n_("Warp projection"), + } + } +} diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs new file mode 100644 index 00000000..fefc92d8 --- /dev/null +++ b/crates/ui-egui/src/projection_preview.rs @@ -0,0 +1,846 @@ +//! The preview square of a 3D projection: a checker laid on a sphere, cylinder or cube through the fill's own projection +//! +//! Each pixel casts a ray at the shape and samples the checker with the compositor's projection math +//! ([`image_samples`] and [`projector_cover`]), so tiling, offset, rotation, Hardness, Angle, the 3D projection +//! settings, Shape crop and Backface culling show as they will on the model. Depth culling needs the model's depth +//! map and is not previewed. The projector is drawn round the shape as the 3D view's gizmo draws it round the model, and the +//! view zooms out until both fit, down to half the shape's size; a projector bigger than that runs off the square, marked on +//! each side it passes + +use egui::{Color32, ColorImage, Painter, Pos2, Rect, Shape, Stroke, TextureOptions, pos2, vec2}; +use texturecraft_engine::compose::frame_placement::{folded, upright_turn}; +use texturecraft_engine::compose::pattern::{Coords, decal_axes, image_samples}; +use texturecraft_engine::compose::projector_cover::projector_cover; +use texturecraft_engine::core::{Projection, Projector, ShapeCrop}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; + +use rayon::prelude::*; + +use crate::projector_outline::ProjectorOutline; +use crate::theme::Tokens; + +mod preview_shape; +mod rendered_preview; +mod screen; +mod view; + +use preview_shape::PreviewShape; +use rendered_preview::RenderedPreview; +use screen::Screen; +use view::View; + + +/// Largest preview side in pixels; the square is never drawn bigger than this +const MAX_SIDE_PX: usize = 256; + +/// Rays per pixel along each axis (smooth outline) +const SUPERSAMPLE: usize = 2; + +/// Rays per pixel along each axis while a drag is held: a quarter of the rays, so the square keeps up with the pointer; the full picture follows on release +const DRAG_SUPERSAMPLE: usize = 1; + +/// Checker cells across one repeat of the source along each axis, in this square and in a warp's frame alike (an untiled, unturned image shows 4 × 4 cells), so a fill looks the same in both +pub(crate) const CHECKER_CELLS: f32 = 4.0; + +/// Half the view's width and height, in mesh radii: as near as the view comes +const VIEW_HALF: f32 = 1.0; + +/// Half the view's width and height as far as it zooms out, in mesh radii (the shape at half its size) +const MAX_VIEW_HALF: f32 = 2.0; + +/// Room left round the projector when the view zooms out to it +const FIT_MARGIN: f32 = 1.12; + +/// How far in front of the middle the rays start, in mesh radii (past every shape and every outline point tested for cover) +const CAMERA_DISTANCE: f32 = 3.0; + +/// Screen length of the pieces an outline is split into to find its hidden parts (points) +const OUTLINE_STEP: f32 = 3.0; + +/// The most pieces one outline segment is split into, however long it runs on screen +const MAX_OUTLINE_PIECES: f32 = 256.0; + +/// The outline's dashes where the shape hides it (points) +const HIDDEN_DASH: f32 = 3.0; + +/// The edge marker's dashes (points) +const EDGE_DASH: f32 = 6.0; + +/// The edge marker's inset from the square's side (points) +const EDGE_INSET: f32 = 2.0; + +/// The edge marker's chevron arm (points) +const CHEVRON_ARM: f32 = 5.0; + +/// The clear margin round the chevron, so the dashes and the shape stop short of it (points) +const CHEVRON_PATCH_MARGIN: f32 = 1.5; + +/// The dot at a planar's direction tip (points) +const TIP_DOT: f32 = 2.2; + +/// How far the field-coloured rim under the tip dot reaches past it (points) +const TIP_DOT_RIM: f32 = 0.8; + +/// The width of the field-coloured line under the outline, which keeps it readable on the checker (points) +const OUTLINE_UNDER_WIDTH: f32 = 2.5; + +/// The width of the outline itself (points) +const OUTLINE_WIDTH: f32 = 1.2; + +/// How strong the line under the outline and the outline show where the camera sees them +const SEEN_SHADES: (f32, f32) = (0.55, 1.0); + +/// How strong the line under the outline and the outline show where the shape hides them: fainter +const HIDDEN_SHADES: (f32, f32) = (0.35, 0.65); + +/// Points a point may lie past a side of the square and still count as inside it (a point on the side's pixel rounds either way) +const PAST_SIDE_SLACK: f32 = 0.5; + +/// Camera turn around the up axis (degrees): three faces of the cube and the cylinder's top show +const CAMERA_YAW: f32 = 35.0; + +/// Camera turn down from level (degrees) +const CAMERA_PITCH: f32 = 25.0; + +/// Where the light comes from, along the view's right, up and towards the eye: above and to the left of the camera +const LIGHT_FROM: [f32; 3] = [-0.5, 0.6, 0.6]; + +/// Light that reaches faces turned away from the light +const AMBIENT: f32 = 0.3; + +/// The sphere's radius, in mesh radii, inside the unit sphere the compositor's coordinates span +const SPHERE_RADIUS: f32 = 0.85; + +/// The cylinder's radius, in mesh radii +const CYLINDER_RADIUS: f32 = 0.55; + +/// Half the cylinder's height, in mesh radii +const CYLINDER_HALF_HEIGHT: f32 = 0.7; + +/// Half the cube's side, in mesh radii +const CUBE_HALF: f32 = 0.55; + +/// The checker's dark cells, as a fraction of the way from `field` to `text` +const CHECKER_DARK: f32 = 0.12; + +/// The checker's light cells, as a fraction of the way from `field` to `text` +const CHECKER_LIGHT: f32 = 1.0; + +/// The shape where the projection does not reach, as a fraction of the way from `field` to `text` +const UNCOVERED: f32 = 0.45; + +/// How much of the projection reaches a ray past which it counts as covered, for the edge of its reach +const HALF_COVERED: f32 = 0.5; + +/// How far a ray on the edge of the projection's reach is drawn from the accent towards the shape's colour +const EDGE_BLEND: f32 = 0.5; + +/// The smallest model radius and frame half size the preview divides by, in mesh units and mesh radii +const MIN_SIZE: f32 = 1e-4; + +/// A ray this close to parallel to a face or the cylinder's axis never meets it +const PARALLEL_TOLERANCE: f32 = 1e-6; + +/// Draw the preview of `projection` on a mesh within `bounds` into `rect`, rendered once per projection, size and theme, with a quarter of the rays while a drag is held (None for projections without one: UV, warp); each `owner` (the docked panel's square, the popup's) keeps its own picture +pub(crate) fn projection_preview(painter: &Painter, rect: Rect, projection: &Projection, bounds: (Vec3, Vec3), tokens: &Tokens, owner: egui::Id) -> Option<()> { + let shown = shown_projection(projection, bounds)?; + let ctx = painter.ctx(); + let side = ((rect.width() * ctx.pixels_per_point()).round() as usize).clamp(1, MAX_SIDE_PX); + let shape = shape_for(&shown); + let outline = ProjectorOutline::of(&shown, shape.half_size()); + let (resting, half) = resting_fit(&shown, shape); + let key = format!("{side}{half}{shown:?}{:?}{:?}{:?}", tokens.field, tokens.text, tokens.accent); + let held = ctx.input(|input| input.pointer.any_down()); + let id = slot(owner); + #[cfg(test)] + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(LAST_OWNER), owner)); + + // The picture, the key and the rays per pixel it was rendered with; a drag's lighter picture is redone in full once the pointer is let go + let cached = ctx.data(|data| data.get_temp::(id)); + let up_to_date = cached.as_ref().is_some_and(|cached| cached.key == key && (held || cached.supersample == SUPERSAMPLE)); + let texture = match cached { + Some(cached) if up_to_date => cached.texture, + cached => { + let supersample = if held { DRAG_SUPERSAMPLE } else { SUPERSAMPLE }; + let image = render(&shown, side, half, supersample, tokens); + let texture = match cached { + Some(RenderedPreview { mut texture, .. }) => { + texture.set(image, TextureOptions::LINEAR); + texture + } + None => ctx.load_texture("projection-preview", image, TextureOptions::LINEAR), + }; + ctx.data_mut(|data| data.insert_temp(id, RenderedPreview { key, supersample, texture: texture.clone() })); + texture + } + }; + painter.image(texture.id(), rect, FULL_UV, Color32::WHITE); + if let Some(outline) = &outline { + let painter = painter.with_clip_rect(rect.intersect(painter.clip_rect())); + let screen = Screen { view: View::new(), rect, half }; + draw_outline(&painter, &screen, shape, outline, tokens); + let center = resting.as_ref().map_or(rect.center(), |resting| screen.at(resting.center)); + crate::preview_dots::preview_dots(&painter, center, screen.at(outline.center), tokens); + edge_markers(&painter, rect, passed_sides(outline.points().chain([outline.center]).map(|point| screen.at(point)), rect), tokens); + } + painter.rect_stroke(rect, 0, egui::Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + Some(()) +} + +/// Where `owner`'s preview square keeps its picture +fn slot(owner: egui::Id) -> egui::Id { + egui::Id::unique(("projection_preview", owner)) +} + +/// Where tests find the owner of the square drawn last +#[cfg(test)] +const LAST_OWNER: &str = "projection_preview_last_owner"; + +/// The picture of the square drawn last (tests) +#[cfg(test)] +fn last_rendered(ctx: &egui::Context) -> Option { + let owner = ctx.data(|data| data.get_temp::(egui::Id::unique(LAST_OWNER)))?; + ctx.data(|data| data.get_temp::(slot(owner))) +} + +/// What the preview square last rendered (tests: a drag re-renders it) +#[cfg(test)] +pub(crate) fn shown_key(ctx: &egui::Context) -> Option { + last_rendered(ctx).map(|rendered| rendered.key) +} + +/// How the preview square was last rendered, with rays per pixel (tests: a drag renders it lighter, the release in full) +#[cfg(test)] +pub(crate) fn shown_supersample(ctx: &egui::Context) -> Option { + last_rendered(ctx).map(|rendered| rendered.supersample) +} + +/// The projection the preview renders: a planar placed on the model shows straight onto the sphere's front as big against the sphere as its frame is against the mesh, stretched, turned round its normal and slid across its plane as the frame is, cropped to its rectangle +fn shown_projection(projection: &Projection, bounds: (Vec3, Vec3)) -> Option { + match projection { + Projection::Planar { placed: Some(_), uv, .. } => { + let landed = folded(projection)?; + let Projection::Planar { placed: Some(frame), projector, .. } = &landed else { return None }; + + // The sphere stands for the model: its radius is the model's largest half size + let radius = ((bounds.1 - bounds.0) * 0.5).max_element().max(MIN_SIZE); + let half = frame.size.map(|side| (SPHERE_RADIUS * side / (2.0 * radius)).max(MIN_SIZE)); + let turn = upright_turn(frame).unwrap_or(0.0); + + // Slid across its own plane away from the mesh's centre: off the sphere's middle by as much + let (origin, across, up, _) = decal_axes(frame)?; + let from_center = (origin - (bounds.0 + bounds.1) * 0.5) / radius * SPHERE_RADIUS; + let offset = [-from_center.dot(across) / half[0], -from_center.dot(up) / half[1], 0.0]; + let projector = Projector { rotation: [0.0, 0.0, turn], scale: [half[0], half[1], 1.0], crop: ShapeCrop::Cropped, ..*projector }; + offset.iter().all(|value| value.is_finite()).then_some(Projection::Planar { scale: 1.0, axis: 2, offset, uv: *uv, projector, placed: None }) + } + Projection::Planar { .. } | Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Triplanar { .. } => Some(projection.clone()), + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => None, + } +} + +/// The projector `shown` round `shape` back at Offset 0, and how far the view reaches to fit it there: sliding the projector never zooms +fn resting_fit(shown: &Projection, shape: PreviewShape) -> (Option, f32) { + let resting = ProjectorOutline::of(&at_rest(shown), shape.half_size()); + let half = view_half(resting.as_ref()); + (resting, half) +} + +/// `projection` with its projector back at Offset 0 (its turn and size kept) +fn at_rest(projection: &Projection) -> Projection { + let mut resting = projection.clone(); + match &mut resting { + Projection::Planar { offset, .. } + | Projection::Triplanar { offset, .. } + | Projection::Spherical { offset, .. } + | Projection::Cylindrical { offset, .. } => { + *offset = [0.0; 3]; + } + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => {} + } + resting +} + +/// Which way the preview camera looks +pub(crate) fn view_direction() -> Vec3 { + View::new().forward +} + +/// How far the view reaches each way from the middle so the shape and the projector `outline` both fit: never nearer than today's framing, never so far the shape drops below half its size +fn view_half(outline: Option<&ProjectorOutline>) -> f32 { + let view = View::new(); + let reach = + outline.into_iter().flat_map(ProjectorOutline::points).map(|point| point.dot(view.right).abs().max(point.dot(view.up).abs())).fold(0.0, f32::max); + if reach.is_finite() { (reach * FIT_MARGIN).clamp(VIEW_HALF, MAX_VIEW_HALF) } else { MAX_VIEW_HALF } +} + +/// The outline's line in the text colour and the field-coloured line under it that keeps it readable on the checker, as the 3D view's gizmo draws its white outline on a dark shadow (the square's field is light in the light themes); fainter where the shape hides it +fn outline_strokes(hidden: bool, tokens: &Tokens) -> [Stroke; 2] { + let (under, over) = if hidden { HIDDEN_SHADES } else { SEEN_SHADES }; + [Stroke::new(OUTLINE_UNDER_WIDTH, tokens.field.gamma_multiply(under)), Stroke::new(OUTLINE_WIDTH, tokens.text.gamma_multiply(over))] +} + +/// The projector outline over the preview: solid where the camera sees it, dashed where the shape hides it, a dot where a planar's image travels to +fn draw_outline(painter: &Painter, screen: &Screen, shape: PreviewShape, outline: &ProjectorOutline, tokens: &Tokens) { + for line in &outline.lines { + // Runs of the line that are all seen or all hidden + let mut runs: Vec<(bool, Vec)> = Vec::new(); + for pair in line.windows(2) { + let [from, to] = [pair[0], pair[1]]; + let pieces = ((screen.at(to) - screen.at(from)).length() / OUTLINE_STEP).ceil().clamp(1.0, MAX_OUTLINE_PIECES) as usize; + for piece in 0..pieces { + let (start, end) = (from.lerp(to, piece as f32 / pieces as f32), from.lerp(to, (piece + 1) as f32 / pieces as f32)); + let hidden = screen.hidden(shape, start.lerp(end, 0.5)); + match runs.last_mut() { + Some((run_hidden, points)) if *run_hidden == hidden => points.push(screen.at(end)), + _ => runs.push((hidden, vec![screen.at(start), screen.at(end)])), + } + } + } + for (hidden, points) in runs { + for stroke in outline_strokes(hidden, tokens) { + if hidden { + painter.extend(Shape::dashed_line(&points, stroke, HIDDEN_DASH, HIDDEN_DASH)); + } else { + painter.add(Shape::line(points.clone(), stroke)); + } + } + } + } + if let Some(tip) = outline.tip { + let [under, over] = outline_strokes(false, tokens); + painter.circle_filled(screen.at(tip), TIP_DOT + TIP_DOT_RIM, under.color); + painter.circle_filled(screen.at(tip), TIP_DOT, over.color); + } +} + +/// The sides of `rect` some of `points` lie past: left, right, top, bottom +pub(crate) fn passed_sides(points: impl Iterator, rect: Rect) -> [bool; 4] { + let outer = rect.expand(PAST_SIDE_SLACK); + points.fold([false; 4], |[left, right, top, bottom], point| { + [left || point.x < outer.left(), right || point.x > outer.right(), top || point.y < outer.top(), bottom || point.y > outer.bottom()] + }) +} + +/// A dashed line just inside each side of `rect` the projector runs past, with a chevron pointing out at its middle +pub(crate) fn edge_markers(painter: &Painter, rect: Rect, sides: [bool; 4], tokens: &Tokens) { + let inner = rect.shrink(EDGE_INSET); + let center = rect.center(); + + // Per side: its two ends, the chevron's point and the way into the square + let edges = [ + ([inner.left_top(), inner.left_bottom()], pos2(inner.left(), center.y), vec2(1.0, 0.0)), + ([inner.right_top(), inner.right_bottom()], pos2(inner.right(), center.y), vec2(-1.0, 0.0)), + ([inner.left_top(), inner.right_top()], pos2(center.x, inner.top()), vec2(0.0, 1.0)), + ([inner.left_bottom(), inner.right_bottom()], pos2(center.x, inner.bottom()), vec2(0.0, -1.0)), + ]; + for (passed, (ends, point, inward)) in sides.into_iter().zip(edges) { + if !passed { + continue; + } + + let along = vec2(inward.y, inward.x); + let chevron = vec![point + (inward - along) * CHEVRON_ARM, point, point + (inward + along) * CHEVRON_ARM]; + for stroke in outline_strokes(false, tokens) { + painter.extend(Shape::dashed_line(&ends, stroke, EDGE_DASH, EDGE_DASH)); + } + + // The chevron on a clear patch, so the dashes and the shape do not run through it + let patch = Rect::from_points(&chevron).expand(CHEVRON_PATCH_MARGIN); + painter.rect_filled(patch, 0, tokens.field); + for stroke in outline_strokes(false, tokens) { + painter.add(Shape::line(chevron.clone(), stroke)); + } + } +} + +/// The shape the preview shows `projection` on: a cylinder for a cylindrical, a cube for a tri-planar, else a sphere +fn shape_for(projection: &Projection) -> PreviewShape { + match projection { + Projection::Cylindrical { .. } => PreviewShape::Cylinder, + Projection::Triplanar { .. } => PreviewShape::Cube, + _ => PreviewShape::Sphere, + } +} + +/// `side²` pixels of the checker on the projection's shape over the `field` background, the view `half` mesh radii across each way from the middle, `supersample²` rays per pixel cast on every core +fn render(projection: &Projection, side: usize, half: f32, supersample: usize, tokens: &Tokens) -> ColorImage { + let shape = shape_for(projection); + let View { eye, forward, right, up } = View::new(); + let [light_right, light_up, light_eye] = LIGHT_FROM; + let light = (light_right * right + light_up * up + light_eye * eye).normalize_or_zero(); + + let field = tokens.field; + let (background, text) = (linear(field), linear(tokens.text)); + let shades = [CHECKER_DARK, CHECKER_LIGHT, UNCOVERED].map(|t| background.lerp(text, t)); + let supersample = supersample.max(1); + let rays = side * supersample; + + // Per ray: the lit colour and how much of the projection lands there (None = the background) + let samples: Vec> = (0..rays * rays) + .into_par_iter() + .map(|ray| { + let (x, y) = (ray % rays, ray / rays); + let across = ((x as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; + let down = ((y as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; + let origin = right * across - up * down + eye * CAMERA_DISTANCE; + let hit = intersect(shape, origin, forward)?; + let shade = AMBIENT + (1.0 - AMBIENT) * hit.nrm.dot(light).max(0.0); + let (color, cover) = surface(projection, &hit, shades); + Some((color * shade, cover)) + }) + .collect(); + + let edge = linear(tokens.accent); + let mut image = ColorImage::new([side, side], vec![field; side * side]); + image.pixels.par_iter_mut().enumerate().for_each(|(pixel, out)| { + let (x, y) = (pixel % side, pixel / side); + let mut sum = Vec3::ZERO; + for sub in 0..supersample * supersample { + let (rx, ry) = (x * supersample + sub % supersample, y * supersample + sub / supersample); + let color = match samples.get(ry * rays + rx).copied().flatten() { + Some((color, cover)) if on_edge(&samples, rays, rx, ry, cover) => edge.lerp(color, EDGE_BLEND), + Some((color, _)) => color, + None => background, + }; + sum += color; + } + *out = from_linear(sum / (supersample * supersample) as f32); + }); + image +} + +/// Where the projection's reach ends on the shape: covered here, not on a neighbouring ray of the shape +fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cover: f32) -> bool { + if cover <= HALF_COVERED { + return false; + } + + let neighbours = [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)]; + neighbours + .into_iter() + .any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).copied().flatten().is_some_and(|(_, cover)| cover <= HALF_COVERED)) +} + +/// The unlit colour at a hit and how much of the projection reaches it, from the dark and light checker and the uncovered shape `shades` in linear light +fn surface(projection: &Projection, hit: &Coords, shades: [Vec3; 3]) -> (Vec3, f32) { + let cover = projector_cover(projection, hit).clamp(0.0, 1.0); + let mut light = 0.0; + for (uv, weight) in image_samples(projection, hit) { + let cell = (uv * CHECKER_CELLS).floor(); + let even = (cell.x + cell.y).rem_euclid(2.0) < 0.5; + light += weight * f32::from(u8::from(even)); + } + let [dark, bright, uncovered] = shades; + (uncovered.lerp(dark.lerp(bright, light.clamp(0.0, 1.0)), cover), cover) +} + +/// The nearest hit of the ray from `origin` along unit `dir` on the preview shape +fn intersect(shape: PreviewShape, origin: Vec3, dir: Vec3) -> Option { + match shape { + PreviewShape::Sphere => intersect_sphere(origin, dir), + PreviewShape::Cube => intersect_cube(origin, dir), + PreviewShape::Cylinder => intersect_cylinder(origin, dir), + } +} + +/// The nearer hit of the ray from `ray_origin` along unit `ray_dir` on the sphere round the middle +fn intersect_sphere(ray_origin: Vec3, ray_dir: Vec3) -> Option { + // |origin + t·dir|² = r², with |dir| = 1: t² + 2·half_b·t + c = 0 + let half_b = ray_origin.dot(ray_dir); + let c = ray_origin.length_squared() - SPHERE_RADIUS * SPHERE_RADIUS; + let discriminant = half_b * half_b - c; + if discriminant < 0.0 { + return None; + } + + let point = ray_origin + ray_dir * (-half_b - discriminant.sqrt()); + Some(hit(point, point.normalize_or_zero())) +} + +/// Where the ray from `ray_origin` along `ray_dir` enters the cube round the middle: the latest of the three slabs' entries, before the earliest exit +fn intersect_cube(ray_origin: Vec3, ray_dir: Vec3) -> Option { + let (mut near, mut far, mut nrm) = (f32::NEG_INFINITY, f32::INFINITY, Vec3::ZERO); + for axis in 0..3 { + let (start, along) = (ray_origin[axis], ray_dir[axis]); + if along.abs() < PARALLEL_TOLERANCE { + if start.abs() > CUBE_HALF { + return None; + } + + continue; + } + + let (low_face, high_face) = ((-CUBE_HALF - start) / along, (CUBE_HALF - start) / along); + let (enter, exit) = (low_face.min(high_face), low_face.max(high_face)); + if enter > near { + near = enter; + nrm = Vec3::ZERO; + nrm[axis] = -along.signum(); + } + far = far.min(exit); + } + (near <= far && near.is_finite()).then(|| hit(ray_origin + ray_dir * near, nrm)) +} + +/// The nearest hit in front of `ray_origin` along `ray_dir` on the upright cylinder round the middle: its side or one of its caps +fn intersect_cylinder(ray_origin: Vec3, ray_dir: Vec3) -> Option { + let mut best: Option<(f32, Coords)> = None; + let mut keep = |distance: f32, hit: Coords| { + if distance > 0.0 && best.as_ref().is_none_or(|(best_distance, _)| distance < *best_distance) { + best = Some((distance, hit)); + } + }; + + // The side: x² + z² = r² within the height, a·t² + 2·half_b·t + c = 0 + let a = ray_dir.x * ray_dir.x + ray_dir.z * ray_dir.z; + let half_b = ray_origin.x * ray_dir.x + ray_origin.z * ray_dir.z; + let c = ray_origin.x * ray_origin.x + ray_origin.z * ray_origin.z - CYLINDER_RADIUS * CYLINDER_RADIUS; + let discriminant = half_b * half_b - a * c; + if a > PARALLEL_TOLERANCE && discriminant >= 0.0 { + let distance = (-half_b - discriminant.sqrt()) / a; + let point = ray_origin + ray_dir * distance; + if point.y.abs() <= CYLINDER_HALF_HEIGHT { + keep(distance, hit(point, Vec3::new(point.x, 0.0, point.z).normalize_or_zero())); + } + } + + // The caps + if ray_dir.y.abs() > PARALLEL_TOLERANCE { + for sign in [1.0, -1.0] { + let distance = (sign * CYLINDER_HALF_HEIGHT - ray_origin.y) / ray_dir.y; + let point = ray_origin + ray_dir * distance; + if point.x * point.x + point.z * point.z <= CYLINDER_RADIUS * CYLINDER_RADIUS { + keep(distance, hit(point, Vec3::Y * sign)); + } + } + } + best.map(|(_, hit)| hit) +} + +/// A shape point the camera sees, in the compositor's coordinates (no texture coordinates) +fn hit(pos: Vec3, nrm: Vec3) -> Coords { + Coords { uv: Vec2::ZERO, pos, nrm } +} + +/// `color` in linear light +fn linear(color: Color32) -> Vec3 { + let rgba = egui::Rgba::from(color); + Vec3::new(rgba.r(), rgba.g(), rgba.b()) +} + +/// A linear-light `color` back as a display colour +fn from_linear(color: Vec3) -> Color32 { + egui::Rgba::from_rgb(color.x, color.y, color.z).into() +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Projector, UvTransform}; + + fn tokens() -> Tokens { + Tokens::for_brightness(crate::theme::Brightness::MediumDark) + } + + fn spherical(tiling: f32) -> Projection { + Projection::Spherical { + scale: 1.0, + uv: UvTransform { tiling: [tiling; 2], ..UvTransform::default() }, + offset: [0.0; 3], + projector: Projector::default(), + } + } + + fn cylindrical(projector: Projector) -> Projection { + Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector, angle: 360.0 } + } + + #[test] + fn the_shape_fills_the_middle_and_leaves_the_corners_to_the_background() { + let tokens = tokens(); + for projection in [spherical(1.0), cylindrical(Projector::default()), Projection::triplanar()] { + let image = render(&projection, 32, VIEW_HALF, SUPERSAMPLE, &tokens); + assert_eq!(image.pixels[0], tokens.field, "{projection:?}: the corner is background"); + assert_ne!(image.pixels[16 * 32 + 16], tokens.field, "{projection:?}: the middle shows the shape"); + } + } + + #[test] + fn the_preview_follows_the_fill_settings() { + let tokens = tokens(); + assert_ne!( + render(&spherical(1.0), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + render(&spherical(3.0), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + "tiling changes the checker" + ); + + let culled = + Projector { backface: texturecraft_engine::core::Backface { on: true, ..Default::default() }, crop: ShapeCrop::Cropped, ..Projector::default() }; + assert_ne!( + render(&cylindrical(Projector::default()), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + render(&cylindrical(culled), 32, VIEW_HALF, SUPERSAMPLE, &tokens).pixels, + "culling shows on the cylinder" + ); + } + + #[test] + fn projections_without_a_shape_have_no_preview() { + assert!(shown_projection(&Projection::UvTile, BOUNDS).is_none()); + assert!(shown_projection(&Projection::Uv { scale: [1.0; 2], rotation: 0.0, offset: [0.0; 2] }, BOUNDS).is_none()); + assert!(shown_projection(&spherical(1.0), BOUNDS).is_some()); + } + + const BOUNDS: (Vec3, Vec3) = (Vec3::NEG_ONE, Vec3::ONE); + + fn shown(projection: &Projection) -> Vec { + let shown = shown_projection(projection, BOUNDS).unwrap(); + let half = view_half(ProjectorOutline::of(&shown, shape_for(&shown).half_size()).as_ref()); + render(&shown, 32, half, SUPERSAMPLE, &tokens()).pixels + } + + /// What the 3D view's gizmo changes shows here too: a sphere's or cylinder's size, turn and centre, a placed frame's size, stretch and turn + #[test] + fn the_preview_shows_the_projectors_size_turn_and_place() { + let base = shown(&spherical(1.0)); + let bigger = Projector { scale: [1.15; 3], ..Projector::default() }; + let Projection::Spherical { uv, .. } = spherical(1.0) else { panic!("spherical() makes a spherical projection") }; + let sphere = |projector: Projector, offset: [f32; 3]| Projection::Spherical { scale: 1.0, uv, offset, projector }; + assert_ne!(shown(&sphere(bigger, [0.0; 3])), base, "a bigger sphere zooms the view out"); + assert_ne!(shown(&sphere(Projector { rotation: [0.0, 0.0, 40.0], ..Projector::default() }, [0.0; 3])), base, "a turned sphere turns its checker"); + assert_ne!(shown(&sphere(Projector::default(), [0.3, 0.0, 0.0])), base, "an offset moves it"); + assert_eq!(shown(&sphere(Projector::default(), [0.0; 3])), base, "unmoved: as before"); + assert_ne!( + shown(&cylindrical(Projector { scale: [1.3, 1.0, 1.3], ..Projector::default() })), + shown(&cylindrical(Projector::default())), + "a wider cylinder" + ); + + let frame = texturecraft_engine::core::Decal { + center: [0.0, 0.0, 1.0], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 1.0, + symmetry: None, + flip: [false; 2], + }; + let placed = |frame| Projection::decal(frame); + let square = shown(&placed(frame)); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { size: [0.5, 0.5], ..frame })), square, "a smaller frame"); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { size: [1.5, 1.0], ..frame })), square, "a stretched frame"); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { rotation: 30.0, ..frame })), square, "a turned frame"); + assert_ne!(shown(&placed(texturecraft_engine::core::Decal { offset: [0.3, 0.0], ..frame })), square, "a slid frame"); + } + + fn fitted_half(projection: &Projection) -> f32 { + let shown = shown_projection(projection, BOUNDS).unwrap(); + resting_fit(&shown, shape_for(&shown)).1 + } + + fn sized(scale: f32) -> Projection { + let Projection::Spherical { uv, .. } = spherical(1.0) else { panic!("spherical() makes a spherical projection") }; + Projection::Spherical { scale: 1.0, uv, offset: [0.0; 3], projector: Projector { scale: [scale; 3], ..Projector::default() } } + } + + /// The view zooms out until the projector fits, never nearer than the plain framing and never past half the shape's size; past that the projector runs off the square and each side it passes is marked + #[test] + fn the_view_fits_the_projector_down_to_half_the_shape() { + assert_eq!(fitted_half(&sized(0.4)), VIEW_HALF, "a small projector keeps the plain framing"); + let default = fitted_half(&sized(1.0)); + assert!(default > VIEW_HALF && default < MAX_VIEW_HALF, "{default}"); + assert_eq!(fitted_half(&sized(3.0)), MAX_VIEW_HALF, "x3 stops at half the shape's size"); + + let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)); + let sides = |scale: f32| { + let shown = sized(scale); + let outline = ProjectorOutline::of(&shown, PreviewShape::Sphere.half_size()).unwrap(); + let screen = Screen { view: View::new(), rect, half: fitted_half(&shown) }; + passed_sides(outline.points().map(|point| screen.at(point)), rect) + }; + assert_eq!(sides(1.0), [false; 4], "a fitted projector stays inside the square"); + assert_eq!(sides(3.0), [true; 4], "an x3 sphere runs past every side"); + + let triplanar = Projection::Triplanar { + scale: 1.0, + sharpness: Projection::TRIPLANAR_SHARPNESS, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector { scale: [10.0; 3], ..Projector::default() }, + }; + assert_eq!(fitted_half(&triplanar), MAX_VIEW_HALF, "every kind fits the same way"); + } + + /// Sliding a projector never zooms the view: it fits the projector at Offset 0, the ring stays in the middle and the projector's centre slides away from it + #[test] + fn the_offset_slides_the_projector_without_zooming_the_view() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)); + let Projection::Spherical { scale, uv, projector, .. } = sized(1.0) else { panic!("sized() makes a spherical projection") }; + for offset in [[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [1.5, 0.8, 0.0]] { + let slid = Projection::Spherical { scale, uv, offset, projector }; + assert_eq!(fitted_half(&slid), fitted_half(&sized(1.0)), "Offset {offset:?} keeps the view"); + let (resting, half) = resting_fit(&slid, PreviewShape::Sphere); + let screen = Screen { view: View::new(), rect, half }; + let ring = screen.at(resting.unwrap().center); + let dot = screen.at(ProjectorOutline::of(&slid, PreviewShape::Sphere.half_size()).unwrap().center); + assert!(ring.distance(rect.center()) < 1e-3, "the ring marks the middle: {ring:?}"); + assert_eq!(dot.distance(ring) > 1.0, offset != [0.0; 3], "the filled dot leaves the ring only when slid: {dot:?}"); + } + } + + /// A huge spherical projector no longer fills the square with its own ball: the shape keeps half its size in the middle with background round it + #[test] + fn a_huge_sphere_keeps_the_shape_in_the_square() { + let tokens = tokens(); + let image = render(&sized(3.0), 32, fitted_half(&sized(3.0)), SUPERSAMPLE, &tokens); + assert_eq!(image.pixels[0], tokens.field, "the corner is background"); + assert_eq!(image.pixels[16 * 32 + 4], tokens.field, "the shape is half its size: its side is background"); + assert_ne!(image.pixels[16 * 32 + 16], tokens.field, "the shape is in the middle"); + } + + /// The outline is dashed where the shape hides it: the equator's back half runs behind the ball + #[test] + fn the_shape_hides_the_back_of_the_outline() { + let screen = Screen { view: View::new(), rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), half: 1.2 }; + let outline = ProjectorOutline::of(&sized(1.0), PreviewShape::Sphere.half_size()).unwrap(); + let hidden = |line: &Vec| line.iter().filter(|point| screen.hidden(PreviewShape::Sphere, **point)).count(); + assert_eq!(hidden(&outline.lines[0]), 0, "the rim is all seen"); + let equator = hidden(&outline.lines[1]); + assert!(equator > 0 && equator < outline.lines[1].len(), "the equator is half hidden: {equator}"); + } + + /// Every kind at x0.4, x1, x2, x3 and x10 (projector scale), as the panel's square draws it + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn preview_fit_snapshots() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + use crate::theme::Brightness; + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + std::fs::create_dir_all(&directory).unwrap(); + const SIZES: [f32; 5] = [0.4, 1.0, 2.0, 3.0, 10.0]; + const SQUARE: f32 = 104.0; + const MARGIN: f32 = 4.0; + type Kind = (&'static str, fn(f32) -> Projection); + let kinds: [Kind; 4] = [ + ("planar", |s| Projection::Planar { + scale: 1.0, + axis: 2, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector { scale: [s, s, 1.0], ..Projector::default() }, + placed: None, + }), + ("spherical", sized), + ("cylindrical", |s| cylindrical(Projector { scale: [s; 3], ..Projector::default() })), + ("triplanar", |s| Projection::Triplanar { + scale: 1.0, + sharpness: Projection::TRIPLANAR_SHARPNESS, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector { scale: [s; 3], ..Projector::default() }, + }), + ]; + + // One square per picture: the preview keeps one rendered texture. The medium theme at every size, the others at two + let themes = [(Brightness::MediumDark, "", &SIZES[..]), (Brightness::Dark, "-dark", &[1.0, 3.0][..]), (Brightness::Light, "-light", &[1.0, 3.0][..])]; + for ((brightness, theme, sizes), (name, make)) in themes.into_iter().flat_map(|theme| kinds.map(|kind| (theme, kind))) { + for &scale in sizes { + let projection = make(scale); + let rect = Rect::from_min_size(pos2(MARGIN, MARGIN), vec2(SQUARE, SQUARE)); + let mut harness = + egui_kittest::Harness::builder().with_size(vec2(SQUARE + 2.0 * MARGIN, SQUARE + 2.0 * MARGIN)).with_pixels_per_point(2.0).wgpu().build_ui( + move |ui| { + let tokens = Tokens::for_brightness(brightness); + ui.painter().rect_filled(ui.ctx().content_rect(), 0, tokens.panel); + projection_preview(ui.painter(), rect, &projection, BOUNDS, &tokens, egui::Id::unique("square")); + }, + ); + harness.run_steps(2); + harness.render().unwrap().save(directory.join(format!("preview-fit-{name}-x{scale}{theme}.png"))).unwrap(); + } + } + + // In the panel: a x3 sphere zoomed out to its floor, marked on every side + let (mut harness, _) = crate::frame_gizmo::tests::fill_app_rendered(serde_json::json!({"projection": "spherical", "projectorScale": [3, 3, 3]}), true); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("preview-fit-in-panel-spherical-x3.png")).unwrap(); + } + + /// One frame of `projection`'s preview square, with `events` as the frame's input + fn preview_frame(ctx: &egui::Context, projection: &Projection, events: Vec) { + let tokens = tokens(); + let input = egui::RawInput { events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + projection_preview(ui.painter(), Rect::from_min_size(pos2(0.0, 0.0), vec2(64.0, 64.0)), projection, BOUNDS, &tokens, egui::Id::unique("square")); + }); + + // No renderer takes the uploads here + output.textures_delta.clear(); + } + + #[test] + fn a_drag_renders_the_square_lighter_and_the_release_renders_it_in_full() { + let ctx = egui::Context::default(); + let at = pos2(10.0, 10.0); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + preview_frame(&ctx, &spherical(1.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "at rest: in full"); + + preview_frame(&ctx, &spherical(1.0), vec![egui::Event::PointerMoved(at), button(true)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "a press alone keeps the full picture: nothing changed"); + preview_frame(&ctx, &spherical(2.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(DRAG_SUPERSAMPLE), "a change while held renders lighter"); + let dragged = shown_key(&ctx); + + preview_frame(&ctx, &spherical(2.0), vec![button(false)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "let go: the same picture in full"); + assert_eq!(shown_key(&ctx), dragged); + } + + /// Two squares of one projection at different sizes in one frame (the docked panel's and the popup's) keep their own pictures, so neither re-renders over the other + #[test] + fn two_squares_drawn_together_keep_their_own_pictures() { + let ctx = egui::Context::default(); + let tokens = tokens(); + let (docked, popup) = (egui::Id::unique("docked"), egui::Id::unique("popup")); + let rendered = |owner| ctx.data(|data| data.get_temp::(slot(owner))).expect("a picture"); + let mut shown = Vec::new(); + for _ in 0..2 { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + projection_preview(ui.painter(), Rect::from_min_size(pos2(0.0, 0.0), vec2(64.0, 64.0)), &spherical(1.0), BOUNDS, &tokens, docked); + projection_preview(ui.painter(), Rect::from_min_size(pos2(100.0, 0.0), vec2(96.0, 96.0)), &spherical(1.0), BOUNDS, &tokens, popup); + }); + output.textures_delta.clear(); + shown.push([docked, popup].map(|owner| rendered(owner).texture.id())); + } + + let [docked_picture, popup_picture] = [rendered(docked), rendered(popup)]; + assert_ne!(docked_picture.texture.id(), popup_picture.texture.id(), "each square draws its own texture"); + assert!(docked_picture.key.starts_with("64") && popup_picture.key.starts_with("96"), "each picture is rendered at its own side"); + assert_eq!(shown[0], shown[1], "the next frame keeps both pictures"); + } + + /// Render times of the preview square (prints ms per render at its largest side; run with --ignored --nocapture) + #[test] + #[ignore] + fn preview_render_timings() { + let tokens = tokens(); + let kinds = [("sphere", spherical(2.0)), ("cylinder", cylindrical(Projector::default())), ("cube", Projection::triplanar())]; + for (name, projection) in kinds { + let start = std::time::Instant::now(); + const RUNS: u32 = 10; + for _ in 0..RUNS { + std::hint::black_box(render(&projection, MAX_SIDE_PX, VIEW_HALF, SUPERSAMPLE, &tokens)); + } + let full = start.elapsed().as_secs_f64() * 1000.0 / f64::from(RUNS); + let start = std::time::Instant::now(); + for _ in 0..RUNS { + std::hint::black_box(render(&projection, MAX_SIDE_PX, VIEW_HALF, DRAG_SUPERSAMPLE, &tokens)); + } + let dragged = start.elapsed().as_secs_f64() * 1000.0 / f64::from(RUNS); + println!("preview {name}: {full:.1} ms at rest, {dragged:.1} ms while dragged"); + } + } +} diff --git a/crates/ui-egui/src/projection_preview/preview_shape.rs b/crates/ui-egui/src/projection_preview/preview_shape.rs new file mode 100644 index 00000000..2865561b --- /dev/null +++ b/crates/ui-egui/src/projection_preview/preview_shape.rs @@ -0,0 +1,24 @@ +//! The shapes the projection preview wraps its checker around + +use texturecraft_engine::geom::glam::Vec3; + +use super::{CUBE_HALF, CYLINDER_HALF_HEIGHT, CYLINDER_RADIUS, SPHERE_RADIUS}; + +/// What the preview wraps the checker around +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PreviewShape { + Sphere, + Cylinder, + Cube, +} + +impl PreviewShape { + /// Half the shape's size along X, Y and Z, in mesh radii + pub(super) fn half_size(self) -> Vec3 { + match self { + PreviewShape::Sphere => Vec3::splat(SPHERE_RADIUS), + PreviewShape::Cylinder => Vec3::new(CYLINDER_RADIUS, CYLINDER_HALF_HEIGHT, CYLINDER_RADIUS), + PreviewShape::Cube => Vec3::splat(CUBE_HALF), + } + } +} diff --git a/crates/ui-egui/src/projection_preview/rendered_preview.rs b/crates/ui-egui/src/projection_preview/rendered_preview.rs new file mode 100644 index 00000000..5e9bd7a0 --- /dev/null +++ b/crates/ui-egui/src/projection_preview/rendered_preview.rs @@ -0,0 +1,11 @@ +//! The projection preview's cached picture + +use egui::TextureHandle; + +/// The preview square's last picture: what it shows (`key`), how many rays per pixel along each axis it was cast with, and the texture holding it +#[derive(Clone)] +pub(super) struct RenderedPreview { + pub(super) key: String, + pub(super) supersample: usize, + pub(super) texture: TextureHandle, +} diff --git a/crates/ui-egui/src/projection_preview/screen.rs b/crates/ui-egui/src/projection_preview/screen.rs new file mode 100644 index 00000000..7935b2b4 --- /dev/null +++ b/crates/ui-egui/src/projection_preview/screen.rs @@ -0,0 +1,30 @@ +//! The preview camera laid on the square: where a point shows and whether the shape hides it + +use egui::{Pos2, Rect, vec2}; +use texturecraft_engine::geom::glam::Vec3; + +use super::{CAMERA_DISTANCE, PreviewShape, View, intersect}; + +/// The preview's view laid on the square `rect`, `half` mesh radii each way from its middle +pub(super) struct Screen { + pub(super) view: View, + pub(super) rect: Rect, + pub(super) half: f32, +} + +/// A hit this close in front of the point is the point's own surface +const OWN_SURFACE_DEPTH: f32 = 1e-3; + +impl Screen { + /// Where `point` shows on the square + pub(super) fn at(&self, point: Vec3) -> Pos2 { + let per_radius = self.rect.width() * 0.5 / self.half; + self.rect.center() + vec2(point.dot(self.view.right), -point.dot(self.view.up)) * per_radius + } + + /// Whether `shape` hides `point` from the camera + pub(super) fn hidden(&self, shape: PreviewShape, point: Vec3) -> bool { + let origin = point + self.view.eye * CAMERA_DISTANCE; + intersect(shape, origin, self.view.forward).is_some_and(|hit| (hit.pos - point).dot(self.view.eye) > OWN_SURFACE_DEPTH) + } +} diff --git a/crates/ui-egui/src/projection_preview/view.rs b/crates/ui-egui/src/projection_preview/view.rs new file mode 100644 index 00000000..7fe9a473 --- /dev/null +++ b/crates/ui-egui/src/projection_preview/view.rs @@ -0,0 +1,25 @@ +//! The projection preview's fixed camera + +use texturecraft_engine::geom::glam::Vec3; + +use super::{CAMERA_PITCH, CAMERA_YAW}; + +/// The preview camera's directions: towards the eye, the view direction, and the view's right and up +#[derive(Clone, Copy, Debug)] +pub(super) struct View { + pub(super) eye: Vec3, + pub(super) forward: Vec3, + pub(super) right: Vec3, + pub(super) up: Vec3, +} + +impl View { + /// The fixed preview camera, turned CAMERA_YAW round and CAMERA_PITCH down + pub(super) fn new() -> View { + let (yaw, pitch) = (CAMERA_YAW.to_radians(), CAMERA_PITCH.to_radians()); + let eye = Vec3::new(pitch.cos() * yaw.sin(), pitch.sin(), pitch.cos() * yaw.cos()); + let forward = -eye; + let right = forward.cross(Vec3::Y).normalize_or_zero(); + View { eye, forward, right, up: right.cross(forward) } + } +} diff --git a/crates/ui-egui/tests/it/fill_projection_rows.rs b/crates/ui-egui/tests/it/fill_projection_rows.rs new file mode 100644 index 00000000..8d0fbe71 --- /dev/null +++ b/crates/ui-egui/tests/it/fill_projection_rows.rs @@ -0,0 +1,242 @@ +//! A fill's Fill section shows the rows its projection has, and each new row changes the projection + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{Fill, LayerId, Projection, ShapeCrop}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::fill_support::{click_label, fill_app, fill_of}; +use crate::filter_support::click_at; +use crate::{PROPERTIES_WINDOW, SETTLE_FRAMES}; + +/// 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 (harness, LayerId(layer)) = fill_app(json!({}), Some(projection), None, PROPERTIES_WINDOW); + (harness, layer) +} + +/// The fill layer's projection as the document holds it +fn projection(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> Projection { + fill(harness, layer).projection +} + +/// The fill layer as the document holds it +fn fill(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> Fill { + fill_of(harness, LayerId(layer)) +} + +#[test] +fn each_projection_shows_its_own_rows() { + let shows = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_by_label(label).is_some(); + + let (harness, _) = app_with_fill("planar"); + for label in ["Depth culling", "Backface culling", "Angle", "Extends Outside Shape", "Offset X", "Rotation Y", "Scale Z"] { + assert!(shows(&harness, label), "planar: {label}"); + } + assert!(!shows(&harness, "Reset frame"), "planar has no frame to reset"); + + let (harness, _) = app_with_fill("warp"); + + // A warp's 3D projection settings are its frame's: where its centre is, its turn and its size + for label in ["Depth", "Reset frame", "Depth culling", "Offset X", "Rotation X", "Scale X"] { + assert!(shows(&harness, label), "warp: {label}"); + } + assert!(!shows(&harness, "Backface culling"), "a warp has no backface culling"); + + let (harness, _) = app_with_fill("cylindrical"); + for label in ["Angle", "Backface culling", "Extends Outside Shape", "Offset X"] { + assert!(shows(&harness, label), "cylindrical: {label}"); + } + assert!(!shows(&harness, "Depth culling")); + + let (harness, _) = app_with_fill("triplanar"); + assert!(shows(&harness, "Hardness") && !shows(&harness, "UV Wrap") && !shows(&harness, "Backface culling")); + + let (harness, _) = app_with_fill("uvTile"); + assert!(shows(&harness, "Fill (Match per UV Tile)")); + assert!(!shows(&harness, "Rotation") && !shows(&harness, "Filtering and edges"), "per UV tile there is nothing to place"); +} + +#[test] +fn culling_toggles_change_the_projection() { + let (mut harness, layer) = app_with_fill("planar"); + click_label(&mut harness, "Depth culling"); + click_label(&mut harness, "Backface culling"); + let Projection::Planar { projector, .. } = projection(&harness, layer) else { panic!("still planar") }; + assert!(!projector.depth.on, "a new planar starts depth culled; the toggle turns it off"); + assert!(projector.backface.on); +} + +/// What the Depth culling row's i says on hover +const DEPTH_CULLING_TIP: &str = "Paints only the surface the projector sees first; parts hidden behind it stay unpainted."; + +/// What the Backface culling row's i says on hover +const BACKFACE_CULLING_TIP: &str = "Leaves out faces turned away from the projector, so the fill doesn't run onto their back."; + +/// A point away from the Properties panel, where the pointer leaves no tooltip +const AWAY_FROM_PANEL: egui::Pos2 = egui::pos2(800.0, 500.0); + +/// Frames for the pointer to rest long enough for a tooltip +const TOOLTIP_FRAMES: usize = 60; + +/// Room the i's tooltip leaves at the panel's right edge for the values +const TIP_VALUE_ROOM: f32 = 70.0; + +#[test] +fn the_culling_rows_i_explains_the_row_on_hover_without_covering_its_values() { + let (mut harness, layer) = app_with_fill("planar"); + + // The i ends on the panel's right edge, where the values end + let panel_right = harness.get_by_label(DEPTH_CULLING_TIP).rect().right(); + for (tip, row) in [(DEPTH_CULLING_TIP, "Depth culling"), (BACKFACE_CULLING_TIP, "Backface culling")] { + let info = harness.get_by_label(tip).rect(); + let switch = harness.get_by_label(row).rect(); + assert!(info.left() >= switch.right() && (info.center().y - switch.center().y).abs() < 1.0, "{row}: the i sits at its row's end"); + assert_eq!(info.right(), panel_right, "{row}: on the panel's right edge"); + assert_eq!(harness.query_all_by_label(tip).count(), 1, "{row}: no tooltip before the hover"); + + harness.hover_at(info.center()); + harness.run_steps(TOOLTIP_FRAMES); + let shown = harness.query_all_by_label(tip).map(|node| node.rect()).find(|rect| *rect != info); + let Some(shown) = shown else { panic!("{row}: hovering the i shows its tooltip") }; + assert!(shown.top() >= info.bottom() - 2.0, "{row}: the tooltip hangs under the row"); + assert!(shown.right() <= panel_right - TIP_VALUE_ROOM, "{row}: the tooltip ends before the value column"); + + harness.hover_at(AWAY_FROM_PANEL); + harness.run_steps(SETTLE_FRAMES); + } + + // The i only explains: a click on it changes nothing + let before = projection(&harness, layer); + let info = harness.get_by_label(DEPTH_CULLING_TIP).rect().center(); + click_at(&mut harness, info); + assert_eq!(projection(&harness, layer), before); +} + +/// What a warp's Depth row says on its i +const WARP_DEPTH_TIP: &str = "How far the warp projection reaches into the mesh, in front of and behind its frame, in lengths of the frame's longer side. It bounds the fill only when cropped to its shape."; + +#[test] +fn shape_crop_sits_beside_its_label_and_a_warps_depth_explains_itself() { + let (harness, _) = app_with_fill("warp"); + + // Beside its label like Filtering, not under a stacked label at the panel's full width + let crop = harness.get_by_label("Extends Outside Shape").rect(); + let filtering = harness.get_by_label("Bilinear | HQ").rect(); + assert!((crop.left() - filtering.left()).abs() < 0.5, "Shape crop's list starts on the controls column: {crop:?} vs {filtering:?}"); + assert!((crop.width() - filtering.width()).abs() < 0.5, "and is as wide as Filtering's"); + + // Depth, not "Projection Depth": its i, on its row, tells it apart from Depth culling + let info = harness.get_by_label(WARP_DEPTH_TIP).rect(); + let depth = harness.get_by_label("Depth").rect(); + assert!((info.center().y - depth.center().y).abs() < 1.0 && info.right() <= depth.left() + 1.0, "the i sits left of Depth"); + assert!(harness.query_by_label("Projection Depth").is_none()); +} + +#[test] +fn shape_crop_is_picked_from_its_list() { + // Tri-planar's Shape crop sits highest in the panel, in view + let (mut harness, layer) = app_with_fill("triplanar"); + click_label(&mut harness, "Extends Outside Shape"); + click_label(&mut harness, "Cropped to Shape"); + let Projection::Triplanar { projector, .. } = projection(&harness, layer) else { panic!("still tri-planar") }; + assert_eq!(projector.crop, ShapeCrop::Cropped); +} + +#[test] +fn triplanar_hardness_runs_from_soft_to_the_hardest_blend() { + let (mut harness, layer) = app_with_fill("triplanar"); + let track = harness.get_by_label("Hardness").rect(); + click_at(&mut harness, egui::pos2(track.right() - 1.0, track.center().y)); + let Projection::Triplanar { sharpness, .. } = projection(&harness, layer) else { panic!("still tri-planar") }; + assert!(sharpness > 48.0, "Hardness 1 is the hardest blend, 64: {sharpness}"); + + click_at(&mut harness, egui::pos2(track.left() + 1.0, track.center().y)); + let Projection::Triplanar { sharpness, .. } = projection(&harness, layer) else { panic!("still tri-planar") }; + assert!(sharpness < 1.5, "Hardness 0 is the softest, 1: {sharpness}"); +} + +#[test] +fn reset_frame_puts_a_warps_corners_back() { + let (mut harness, layer) = app_with_fill("warp"); + let pulled = json!({"layer": layer, "warpCorners": [[-0.7, 0.6], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]}); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &pulled).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + click_label(&mut harness, "Reset frame"); + let Projection::Warp { corners, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert_eq!(corners, Projection::FRAME_CORNERS); +} + +#[test] +fn the_3d_projection_settings_fold_away() { + let (mut harness, _) = app_with_fill("spherical"); + assert!(harness.query_by_label("Scale X").is_some(), "the band starts open"); + click_label(&mut harness, "3D projection settings"); + assert!(harness.query_by_label("Scale X").is_none()); + assert!(harness.query_by_label("Spherical projection").is_some(), "the rows above it stay"); +} + +#[test] +fn the_fill_caption_resets_the_whole_fill_section_to_its_projections_defaults_in_one_undo_step() { + use texturecraft_engine::core::{Filtering, Sampling}; + let (mut harness, layer) = app_with_fill("planar"); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "tiling": 3, "filtering": "nearest", "shapeCrop": "cropped", "symmetry": true})); + harness.run_steps(SETTLE_FRAMES); + let changed = fill(&harness, layer); + let reset = harness.get_by_label("Fill: Reset to defaults").rect().center(); + let edges = harness.get_by_label("Restore defaults").rect().center(); + + // The band's reset puts back only Filtering and edges, through a real pointer click + click_at(&mut harness, edges); + let after_band = fill(&harness, layer); + assert_eq!((after_band.sampling.filtering, crop(&after_band.projection)), (Filtering::default(), Some(ShapeCrop::default()))); + assert!(matches!(after_band.projection, Projection::Planar { .. }), "the projection stays planar"); + assert!(harness.get_by_label("Restore defaults").accesskit_node().is_disabled(), "at its defaults the band's reset is inert"); + + // The caption's reset puts back the whole section + click_at(&mut harness, reset); + let after = fill(&harness, layer); + assert!( + matches!(after.projection, Projection::Planar { scale, uv, placed: None, .. } if scale == 1.0 && uv == Default::default()), + "still planar, at a new planar's defaults: {:?}", + after.projection + ); + assert_eq!(after.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the symmetry stays"); + assert!(harness.get_by_label("Fill: Reset to defaults").accesskit_node().is_disabled(), "at the defaults it is faint and inert"); + click_at(&mut harness, reset); + assert_eq!(fill(&harness, layer), after, "a click at the defaults changes nothing"); + + harness.state_mut().run("edit.undo", json!({})); + assert_eq!(fill(&harness, layer), after_band, "one undo step brings the whole section back"); +} + +/// A click from one typed number field to the next types into the one clicked: the field after it keeps its own value +#[test] +fn a_click_from_one_typed_field_to_the_next_types_into_the_one_clicked() { + let (mut harness, _) = app_with_fill("planar"); + let value = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.get_by_label(label).accesskit_node().numeric_value().unwrap(); + let untouched = value(&harness, "Offset Z"); + + click_label(&mut harness, "Offset X"); + harness.event(egui::Event::Text("0.1".into())); + harness.run_steps(SETTLE_FRAMES); + click_label(&mut harness, "Offset Y"); + harness.event(egui::Event::Text("0.2".into())); + harness.run_steps(SETTLE_FRAMES); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + + assert!((value(&harness, "Offset X") - 0.1).abs() < 1e-4, "the first field took its value"); + assert!((value(&harness, "Offset Y") - 0.2).abs() < 1e-4, "the clicked field took the typing"); + assert_eq!(value(&harness, "Offset Z"), untouched, "the field after it kept its value"); +} + +/// A projection's Shape crop, if it has a projector +fn crop(projection: &Projection) -> Option { + match projection { + Projection::Planar { projector, .. } | Projection::Triplanar { projector, .. } => Some(projector.crop), + _ => None, + } +} From c6ab3aa586517755794b6b6eaf6cb48728edf61d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 013/153] Popups: a press outside a popup closes it when it turns into a drag; Properties keeps a minimum width --- crates/ui-egui/src/decal_drop.rs | 4 +- crates/ui-egui/src/popup_drag.rs | 22 +++ crates/ui-egui/src/properties_popup.rs | 2 +- crates/ui-egui/src/symmetry/mod.rs | 12 +- crates/ui-egui/tests/it/popup_press_close.rs | 141 ++++++++++++++++++ .../ui-egui/tests/it/properties_min_width.rs | 108 ++++++++++++++ 6 files changed, 281 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/popup_drag.rs create mode 100644 crates/ui-egui/tests/it/popup_press_close.rs create mode 100644 crates/ui-egui/tests/it/properties_min_width.rs diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs index 2071ceb6..2d75dd83 100644 --- a/crates/ui-egui/src/decal_drop.rs +++ b/crates/ui-egui/src/decal_drop.rs @@ -71,7 +71,7 @@ impl DecalDrop { }); } - /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click or a drag elsewhere drops nothing pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { let id = Self::menu_id(); let Some(drop) = Self::current(ui.ctx()) else { return }; @@ -110,7 +110,7 @@ impl DecalDrop { }); }); - if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) || crate::popup_drag::drag_outside_popups(ui.ctx()) { Self::close(ui.ctx()); } diff --git a/crates/ui-egui/src/popup_drag.rs b/crates/ui-egui/src/popup_drag.rs new file mode 100644 index 00000000..b1bb14a2 --- /dev/null +++ b/crates/ui-egui/src/popup_drag.rs @@ -0,0 +1,22 @@ +//! A press outside the popups that turns into a drag closes them: egui closes a popup only on a click, so a paint stroke or slider drag left it open + +use egui::{Order, PointerButton}; + +/// Whether a primary press outside every popup has just been held or moved past a click: it starts a stroke, a slider drag or a panel move +pub(crate) fn drag_outside_popups(ctx: &egui::Context) -> bool { + let (dragging, origin, orbiting) = ctx.input(|input| { + let dragging = input.pointer.button_down(PointerButton::Primary) && input.pointer.is_decidedly_dragging(); + (dragging, input.pointer.press_origin(), input.modifiers.alt) + }); + + // Alt+drag orbits the camera, which keeps popups open like the colour picker; a drag in a popup or a dropdown it opened stays in it + let over_popup = |at| ctx.layer_id_at(at).is_some_and(|layer| matches!(layer.order, Order::Foreground | Order::Tooltip | Order::Debug)); + dragging && !orbiting && origin.is_some_and(|at| !over_popup(at)) +} + +/// Closes egui's open popup, menu or dropdown when [`drag_outside_popups`]; a plain click outside is egui's own close +pub(crate) fn close_on_drag_outside(ctx: &egui::Context) { + if egui::Popup::is_any_open(ctx) && drag_outside_popups(ctx) { + egui::Popup::close_all(ctx); + } +} diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 5c174cdd..305c8bb6 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -67,7 +67,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { 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| { + egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::ZERO).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); diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 363ddd37..94eec7d8 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -102,14 +102,16 @@ pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { .close_behavior(egui::PopupCloseBehavior::IgnoreClicks) .show(|ui| settings_popup::show(app, ui)); - // A click outside the popup and the dropdowns it opens (foreground layers too) closes it + // A click outside the popup and the dropdowns it opens (foreground layers too) closes it, and so does a drag that starts outside them if let Some(shown) = shown && !response.clicked() - && ui.input(|input| input.pointer.any_click()) - && let Some(at) = ui.input(|input| input.pointer.interact_pos()) - && ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground) { - open = false; + let clicked_at = ui.input(|input| input.pointer.interact_pos().filter(|_| input.pointer.any_click())); + let click_outside = clicked_at + .is_some_and(|at| ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground)); + if click_outside || crate::popup_drag::drag_outside_popups(ui.ctx()) { + open = false; + } } ui.data_mut(|data| data.insert_temp(popup_id, open)); diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs new file mode 100644 index 00000000..31e2d868 --- /dev/null +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -0,0 +1,141 @@ +//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the tool's colour, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart + +use eframe::App as _; +use egui::{Event, Modifiers, PointerButton, Pos2, Vec2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Dock; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, PROPERTIES_WINDOW, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +use crate::memory_storage::MemoryStorage; + +/// Moves of a drag on the model, each a few points, so it is a drag well before its release +const DRAG_MOVES: usize = 6; + +/// A short stroke on the model +const STROKE: Vec2 = vec2(-60.0, 40.0); + +/// From the tool's Base color label to inside its swatch +const LABEL_TO_SWATCH: f32 = 60.0; + +/// The app started on `storage` (its saved arrangement, if any) with the paint tool's Properties showing +fn app(storage: &MemoryStorage) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + + // The view has no accessible name of its own; these tests drive it by position + let builder = Harness::builder().with_size(PROPERTIES_WINDOW).with_accessibility_check(false); + let mut harness = builder.build_eframe(|context| { + let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); + creation.storage = Some(storage); + TextureCraftApp::new(&creation, 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(STARTUP_FRAMES); + harness +} + +/// Properties swapped with Assets (now left of the view), saved and the app started again from that save +fn restarted_rearranged() -> Harness<'static, TextureCraftApp> { + let mut storage = MemoryStorage::default(); + let mut first = app(&storage); + let saved = serde_json::to_string(&first.state().ui.dock).unwrap(); + let swapped = saved.replace("\"Assets\"", "\"Swap\"").replace("\"Properties\"", "\"Assets\"").replace("\"Swap\"", "\"Properties\""); + first.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); + first.run_steps(STARTUP_FRAMES); + first.state_mut().save(&mut storage); + + let restarted = app(&storage); + assert_eq!(restarted.state().ui.dock, first.state().ui.dock, "the rearranged layout comes back"); + restarted +} + +fn press(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2, pressed: bool, modifiers: Modifiers) { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers }); + harness.run_steps(DRAG_STEP_FRAMES); +} + +/// A primary press at `from` dragged by `by` in small moves, then released +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, by: Vec2, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.run_steps(1); + press(harness, from, true, modifiers); + for step in 1..=DRAG_MOVES { + harness.hover_at(from + by * (step as f32 / DRAG_MOVES as f32)); + harness.run_steps(1); + } + press(harness, from + by, false, modifiers); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(SETTLE_FRAMES); +} + +/// A plain press and release at `at` +fn click(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + press(harness, at, true, Modifiers::NONE); + press(harness, at, false, Modifiers::NONE); + harness.run_steps(SETTLE_FRAMES); +} + +/// A stroke on the model, clear of the panels and the popups that open beside them +fn stroke_on_model(harness: &mut Harness<'_, TextureCraftApp>, modifiers: Modifiers) { + let view = harness.state().viewport_rect; + drag(harness, view.center(), STROKE, modifiers); +} + +/// Opens the paint tool's Base color swatch from its Properties' Material tab +fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { + let header = harness.get_by_label("Properties - Paint").rect(); + let in_properties = |rect: egui::Rect| header.x_range().contains(rect.center().x) && rect.top() > header.top(); + let material = harness.get_all_by_label("Material").find(|node| in_properties(node.rect())).unwrap(); + material.click(); + harness.run_steps(SETTLE_FRAMES); + + let label = harness.get_all_by_value("Base color").find(|node| in_properties(node.rect())).unwrap().rect(); + click(harness, label.right_center() + vec2(LABEL_TO_SWATCH, 0.0)); + assert!(egui::Popup::is_any_open(&harness.ctx), "the swatch opens its colour popup"); +} + +#[test] +fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_restored_rearranged_layout() { + for (mut harness, layout) in [(app(&MemoryStorage::default()), "default"), (restarted_rearranged(), "restored rearranged")] { + open_tool_color(&mut harness); + let history = harness.state().session.history_labels().len(); + + stroke_on_model(&mut harness, Modifiers::NONE); + + assert!(!egui::Popup::is_any_open(&harness.ctx), "{layout}: the stroke closes the popup"); + assert!(harness.state().session.history_labels().len() > history, "{layout}: the stroke still paints"); + } +} + +#[test] +fn an_alt_orbit_keeps_the_tool_colour_popup_open() { + let mut harness = app(&MemoryStorage::default()); + open_tool_color(&mut harness); + + stroke_on_model(&mut harness, Modifiers::ALT); + + assert!(egui::Popup::is_any_open(&harness.ctx), "an Alt+drag orbits the camera and keeps the popup, like the colour picker"); +} + +#[test] +fn a_stroke_on_the_model_closes_the_symmetry_settings() { + let mut harness = app(&MemoryStorage::default()); + + // The paint controls overflow the bar at this width; its arrow brings the Symmetry buttons into view + harness.get_by_label("Scroll right").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Radial symmetry").is_some(), "the settings open"); + + stroke_on_model(&mut harness, Modifiers::NONE); + + assert!(harness.query_by_label("Radial symmetry").is_none(), "the stroke closes the settings"); +} diff --git a/crates/ui-egui/tests/it/properties_min_width.rs b/crates/ui-egui/tests/it/properties_min_width.rs new file mode 100644 index 00000000..79c39f5d --- /dev/null +++ b/crates/ui-egui/tests/it/properties_min_width.rs @@ -0,0 +1,108 @@ +//! The Properties panel never gets narrower than its rows need: the column it docks in stops shrinking there + +use craft_ui::docking::Node; +use craft_ui::layout::SplitSize; +use egui::{Event, Modifiers, PointerButton, Pos2, Role, pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, PROPERTIES_MIN_WIDTH}; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, panel_close_button}; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// A right column comfortably wider than the minimum, where a drag starts +const WIDE_COLUMN: f32 = 420.0; + +/// Half the gutter between the views and the right column, where its divider is grabbed +const DIVIDER_OFFSET: f32 = 3.0; + +/// How far under the Properties header the divider is grabbed: beside the panel's rows, clear of the header bar +const DIVIDER_GRAB_BELOW_HEADER: f32 = 100.0; + +/// How far right of the window's edge a drag aims, past any width the column could stop at +const WINDOW_RIGHT_INSET: f32 = 4.0; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The header names below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// Gives the right column (Layers over Properties) `width` points, as a layout saved at that width would +fn set_column_width(harness: &mut Harness<'_, TextureCraftApp>, width: f32) { + let mut workspace = harness.state().ui.dock.workspace().clone(); + let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("the assets column and the rest") }; + let Node::Split { size, .. } = second.as_mut() else { panic!("the 3D view and the right column") }; + *size = SplitSize::FixedSecond(width); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + harness.run_steps(SETTLE_FRAMES); +} + +/// The Properties header's title, which starts at the column's left edge +fn properties_title(harness: &Harness<'_, TextureCraftApp>) -> egui::Rect { + harness + .get_all_by_role(Role::Tab) + .find(|tab| tab.accesskit_node().label().is_some_and(|label| label.starts_with("Properties - "))) + .map(|tab| tab.rect()) + .expect("the Properties header") +} + +/// Width of the Properties header bar, from its title's left edge to its close button's right edge +fn properties_header_width(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let title = properties_title(harness); + panel_close_button(harness, title).max.x - title.min.x +} + +/// Moves of a divider drag, so the dock follows the pointer as it does by hand +const DRAG_MOVES: usize = 4; + +/// Drags with the primary button from `from` to `to` in [`DRAG_MOVES`] 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(DRAG_STEP_FRAMES); + + for step in 1..=DRAG_MOVES { + harness.hover_at(from + (to - from) * (step as f32 / DRAG_MOVES as f32)); + harness.run_steps(1); + } + + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn dragging_the_right_column_narrow_stops_at_the_properties_minimum_width() { + let mut harness = app(); + set_column_width(&mut harness, PROPERTIES_MIN_WIDTH); + let at_minimum = properties_header_width(&harness); + + set_column_width(&mut harness, WIDE_COLUMN); + let before = properties_title(&harness).min.x; + assert!(properties_header_width(&harness) > at_minimum, "a wide column gives Properties more than its minimum"); + + let y = properties_title(&harness).max.y + DIVIDER_GRAB_BELOW_HEADER; + drag(&mut harness, pos2(before - DIVIDER_OFFSET, y), pos2(WINDOW_SIZE.x - WINDOW_RIGHT_INSET, y)); + + assert!(properties_title(&harness).min.x > before, "the divider moved right"); + let width = properties_header_width(&harness); + assert!((width - at_minimum).abs() < 0.5, "Properties stopped at its minimum: header {width}, {at_minimum} at the minimum"); +} + +#[test] +fn a_layout_saved_narrower_draws_properties_at_its_minimum_width() { + let mut harness = app(); + set_column_width(&mut harness, PROPERTIES_MIN_WIDTH); + let at_minimum = properties_header_width(&harness); + + set_column_width(&mut harness, PROPERTIES_MIN_WIDTH * 0.5); + let width = properties_header_width(&harness); + assert!((width - at_minimum).abs() < 0.5, "a narrow saved column opens at the minimum: header {width}, {at_minimum} at the minimum"); +} From ed481a4a0109ffd99c87fd374a830b6c13266014 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:11 +0000 Subject: [PATCH 014/153] Fills: projection gizmos in the 3D view with a handle for every transform --- crates/ui-egui/src/frame_gizmo.rs | 988 ++++++++++++++++++ crates/ui-egui/src/frame_gizmo/frame_grab.rs | 29 + crates/ui-egui/src/projection_gizmo.rs | 77 ++ crates/ui-egui/src/projection_gizmo/gizmo.rs | 25 + .../src/projection_gizmo/gizmo_drag.rs | 14 + .../src/projection_gizmo/shown_gizmo.rs | 73 ++ crates/ui-egui/src/projector_outline.rs | 159 +++ crates/ui-egui/src/projector_outline/place.rs | 27 + crates/ui-egui/src/round_gizmo.rs | 885 ++++++++++++++++ crates/ui-egui/src/round_gizmo/round_grab.rs | 12 + crates/ui-egui/src/round_gizmo/shape.rs | 8 + crates/ui-egui/src/round_gizmo/size_handle.rs | 33 + 12 files changed, 2330 insertions(+) create mode 100644 crates/ui-egui/src/frame_gizmo.rs create mode 100644 crates/ui-egui/src/frame_gizmo/frame_grab.rs create mode 100644 crates/ui-egui/src/projection_gizmo.rs create mode 100644 crates/ui-egui/src/projection_gizmo/gizmo.rs create mode 100644 crates/ui-egui/src/projection_gizmo/gizmo_drag.rs create mode 100644 crates/ui-egui/src/projection_gizmo/shown_gizmo.rs create mode 100644 crates/ui-egui/src/projector_outline.rs create mode 100644 crates/ui-egui/src/projector_outline/place.rs create mode 100644 crates/ui-egui/src/round_gizmo.rs create mode 100644 crates/ui-egui/src/round_gizmo/round_grab.rs create mode 100644 crates/ui-egui/src/round_gizmo/shape.rs create mode 100644 crates/ui-egui/src/round_gizmo/size_handle.rs diff --git a/crates/ui-egui/src/frame_gizmo.rs b/crates/ui-egui/src/frame_gizmo.rs new file mode 100644 index 00000000..6b27767b --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo.rs @@ -0,0 +1,988 @@ +//! The frame of the selected planar or warp projection in the 3D view: the centre square slides it, the axis arrows move it along its across, up and out directions, the ring turns it round its normal, a planar's corners scale it, the edge dots stretch one side, a warp's corners pull freely + +use egui::{Color32, Pos2, Rect, Stroke, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::compose::axis_frame::{placed_from_axis, placing_moves_pattern}; +use texturecraft_engine::compose::frame_placement::folded; +use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; +use texturecraft_engine::core::{Decal, EffectKind, Fill, LayerId, LayerKind, Projection}; +use texturecraft_engine::geom::glam::Vec3; + +use crate::TextureCraftApp; +use crate::projection_gizmo::{Gizmo, dragging}; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, Tokens}; +use crate::viewport::{project, view_ray}; + +mod frame_grab; + +pub(crate) use frame_grab::FrameGrab; + +/// The selected fill's frame as the 3D view shows it +#[derive(Clone, Copy, Debug)] +pub(crate) struct FrameGizmo { + pub layer: LayerId, + /// The selected mask fill effect projecting from the frame, when it is in a mask + pub effect: Option, + /// The frame; an axis planar shows the frame it is placed as on its first drag + pub decal: Decal, + /// A warp's corners, across and up in frame sizes from its centre + pub warp: Option<[[f32; 2]; 4]>, + /// On screen: the corners (a warp's pulled ones), the edge dots and the centre + pub corners: [Pos2; 4], + pub sides: [Pos2; 4], + pub center: Pos2, + /// On screen, the tips of the across, up and out arrows (None when one points at the camera) + pub arrows: [Option; 3], + /// On screen, the turn ring round the centre in the frame's plane (None when it is edge on) + pub ring: Option<[Pos2; TURN_RING_POINTS]>, + /// In the world: the frame's centre, and its across, up and out directions + origin: Vec3, + axes: [Vec3; 3], + /// Screen movement per world unit along each direction at the centre + steps: [Option; 3], +} + +/// Screen length of the axis arrows, and their heads (points): long enough to grab each one apart from the others +pub(crate) const ARROW: f32 = 56.0; +const ARROW_HEAD: f32 = 14.0; +/// The centre square's side, the corner and edge dot radii, a warp corner's radius (points) +pub(crate) const CENTER_SQUARE: f32 = 16.0; +const CORNER_DOT: f32 = 6.5; +const SIDE_DOT: f32 = 5.5; +const WARP_DOT: f32 = 8.0; +/// How near a handle or arrow a press grabs it (points) +pub(crate) const GRAB: f32 = 11.0; +/// Screen radius of the turn rings (frames and round projectors alike): past the arrow heads, so a ring is grabbed apart from the arrows +pub(crate) const TURN_RING: f32 = 84.0; +/// Points on a frame's turn ring, the first repeated at the end to close it +pub(crate) const TURN_RING_POINTS: usize = 49; +/// The smallest share of its size a dragged side keeps +const MIN_SIDE_STRETCH: f32 = 0.02; +/// The least distance from the centre a resize drag measures from, so a press on the centre never divides by zero (points) +pub(crate) const MIN_HANDLE_REACH: f32 = 1.0; + +impl FrameGizmo { + /// The frame as the 3D view shows it: none while the Projection row's eye hides the projection gizmos + pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { + FrameGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) + } + + /// The frame of the selected fill layer, or of the selected mask fill effect, with a planar or warp projection + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + use texturecraft_engine::StackTarget; + + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + let layers = &app.session.doc.project; + let selected = app.session.selected_layer()?; + let (layer, effect, projection, sources) = match app.session.target { + StackTarget::Content => { + let layer = layers.content_layer(selected)?; + let LayerKind::Fill(Fill { projection, sources, .. }) = &layer.kind else { return None }; + + (layer.id, None, projection, sources.values().collect::>()) + } + StackTarget::Effect(effect) => { + // Only the selected layer's effective mask may supply a frame, including an instance's inherited mask + let owner = layers.mask_owner(selected); + let mask = layers.layer(owner).ok()?.mask.as_ref()?; + let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; + let EffectKind::Fill { projection, source, .. } = &mask_effect.kind else { return None }; + + (owner, Some(effect), projection, vec![source]) + } + StackTarget::Mask => return None, + }; + + // An axis planar reading a pattern keeps its axis (see [`placing_moves_pattern`]): it has no frame to move + let unplaced = matches!(projection, Projection::Planar { placed: None, .. }); + if unplaced && placing_moves_pattern(sources.into_iter()) { + return None; + } + let placed = placed_from_axis(projection, app.session.mesh.bounds()); + + // Where the projection lands: a projector's own turn and scale moved into the frame, as the panel's 3D projection settings show it + let landed = folded(placed.as_ref().unwrap_or(projection))?; + let decal = *landed.frame()?; + let warp = match projection { + Projection::Warp { corners, .. } => Some(*corners), + _ => None, + }; + let (origin, across, up, out) = decal_axes(&decal)?; + + // The corners on screen: a warp's pulled ones, or the frame's own + let at = |[x, y]: [f32; 2]| project(app, rect, origin + across * x * decal.size[0] + up * y * decal.size[1]); + let corners = match warp { + Some([top_left, top_right, bottom_right, bottom_left]) => [at(top_left)?, at(top_right)?, at(bottom_right)?, at(bottom_left)?], + None => { + let [top_left, top_right, bottom_right, bottom_left] = decal_corners(&decal)?.map(|corner| project(app, rect, corner)); + [top_left?, top_right?, bottom_right?, bottom_left?] + } + }; + + let sides = [0, 1, 2, 3].map(|side| corners[side].lerp(corners[(side + 1) % 4], 0.5)); + let center = project(app, rect, origin)?; + + // Screen movement per world unit along each direction, and an arrow along each one not pointing at the camera + let reach = decal.size[0].max(decal.size[1]); + let axes = [across, up, out]; + let steps = axes.map(|axis| Some((project(app, rect, origin + axis * reach)? - center) / reach.max(f32::MIN_POSITIVE))); + let arrows = steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW)); + + // The turn ring, unless the frame is seen too near edge on to grab it + let ring = steps[0] + .zip(steps[1]) + .filter(|(across_step, up_step)| { + across_step.length() > f32::EPSILON && solve(*across_step, *up_step, egui::Vec2::X).is_some() && ring_open(app, rect, center, out) + }) + .and_then(|(step, _)| { + let radius = TURN_RING / step.length(); + let last = (TURN_RING_POINTS - 1) as f32; + let points = (0..TURN_RING_POINTS).map(|index| { + let (sin, cos) = (index as f32 / last * std::f32::consts::TAU).sin_cos(); + project(app, rect, origin + (across * cos + up * sin) * radius) + }); + points.collect::>>()?.try_into().ok() + }); + + Some(FrameGizmo { layer, effect, decal, warp, corners, sides, center, arrows, ring, origin, axes, steps }) + } + + /// The frame's offset after sliding it across its plane by screen movement `delta` (None when the frame is edge-on) + pub(crate) fn slid_on_screen(&self, delta: egui::Vec2) -> Option<[f32; 2]> { + let [across, up] = solve(self.steps[0]?, self.steps[1]?, delta)?; + Some(self.slid(across, up)) + } + + /// Where screen point `p` meets the frame's plane, across and up in frame sizes from its centre + fn on_plane(&self, app: &TextureCraftApp, rect: Rect, p: Pos2) -> Option<[f32; 2]> { + let ray = view_ray(app, rect, p); + let [across, up, out] = self.axes; + let facing = ray.dir.dot(out); + if facing.abs() < EDGE_ON_FACING { + return None; + } + + let hit = ray.origin + ray.dir * ((self.origin - ray.origin).dot(out) / facing); + let local = [(hit - self.origin).dot(across) / self.decal.size[0], (hit - self.origin).dot(up) / self.decal.size[1]]; + local.iter().all(|value| value.is_finite()).then_some(local) + } + + /// The frame's offset after moving `across` and `up` world units along its turned directions, unturned as `layer.decal.set` stores it + fn slid(&self, across: f32, up: f32) -> [f32; 2] { + let (sin, cos) = self.decal.rotation.to_radians().sin_cos(); + [self.decal.offset[0] + across * cos - up * sin, self.decal.offset[1] + across * sin + up * cos] + } +} + +/// Half a turn in degrees: a ring drag's sweep is kept within one either way +const HALF_TURN: f32 = 180.0; + +/// The smallest determinant of two screen steps (points² per world unit²) that still tells them apart: below it they run parallel on screen +const PARALLEL_DETERMINANT: f32 = 1e-6; + +/// The smallest cosine between a view ray and a plane's normal for the ray to meet the plane: nearer edge on, the hit runs off far away +pub(crate) const EDGE_ON_FACING: f32 = 1e-4; + +/// The smallest length a direction spans on screen to point somewhere (points): shorter, it points at the camera +pub(crate) const MIN_SCREEN_SPAN: f32 = 1.0; + +/// The smallest cosine between the view ray and a turn ring's axis for the ring to show: flatter, its half height on screen is under its drawn line's width, it reads as a line and a drag along it turns half a turn at once across the centre +const MIN_RING_FACING: f32 = (SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) / TURN_RING; + +/// Whether a turn ring round `axis`, centred on screen at `center`, is seen open enough to show and grab +pub(crate) fn ring_open(app: &TextureCraftApp, rect: Rect, center: Pos2, axis: Vec3) -> bool { + view_ray(app, rect, center).dir.dot(axis).abs() >= MIN_RING_FACING +} + +/// `delta` as a mix of screen steps `across_step` and `up_step` (None when they are parallel on screen) +fn solve(across_step: egui::Vec2, up_step: egui::Vec2, delta: egui::Vec2) -> Option<[f32; 2]> { + let determinant = across_step.x * up_step.y - across_step.y * up_step.x; + if determinant.abs() < PARALLEL_DETERMINANT { + return None; + } + + Some([(delta.x * up_step.y - delta.y * up_step.x) / determinant, (across_step.x * delta.y - across_step.y * delta.x) / determinant]) +} + +/// How far `p` is from the centre square (0 inside it) +pub(crate) fn center_distance(center: Pos2, p: Pos2) -> f32 { + Rect::from_center_size(center, egui::Vec2::splat(CENTER_SQUARE)).distance_to_pos(p) +} + +/// How far `p` is from the arrow from `center` to `tip`, its head included +pub(crate) fn arrow_distance(p: Pos2, center: Pos2, tip: Pos2) -> f32 { + distance_to_segment(p, center, tip + (tip - center).normalized() * ARROW_HEAD) +} + +/// The handle nearest its distance, if one is within `GRAB` (the first listed wins a tie) +pub(crate) fn nearest(handles: impl IntoIterator) -> Option { + let mut best: Option<(T, f32)> = None; + for (handle, distance) in handles { + if distance <= GRAB && best.is_none_or(|(_, nearest)| distance < nearest) { + best = Some((handle, distance)); + } + } + best.map(|(handle, _)| handle) +} + +pub(crate) fn distance_to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 { + let ab = b - a; + let t = ((p - a).dot(ab) / ab.length_sq().max(f32::MIN_POSITIVE)).clamp(0.0, 1.0); + p.distance(a + ab * t) +} + +impl Gizmo for FrameGizmo { + type Grab = FrameGrab; + + fn drag_id() -> egui::Id { + egui::Id::unique("tc_frame_drag") + } + + /// The handle under screen point `p`: the nearest one within reach, so a small frame's corners stay grabbable beside its arrows + fn grab(&self, at: Pos2) -> Option { + let mut handles = vec![(FrameGrab::Slide, center_distance(self.center, at))]; + handles.extend((0..3).filter_map(|axis| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?))))); + let near = |points: [Pos2; 4], grab: fn(usize) -> FrameGrab| (0..4).map(move |index| (grab(index), points[index].distance(at))); + match self.warp { + // A mask effect's warp corners have no command to pull them + Some(_) if self.effect.is_none() => handles.extend(near(self.corners, FrameGrab::Corner)), + Some(_) => {} + None => handles.extend(near(self.corners, |_| FrameGrab::Scale)), + } + handles.extend(near(self.sides, FrameGrab::Side)); + if let Some(ring) = &self.ring { + handles.push((FrameGrab::Turn, ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min))); + } + nearest(handles) + } + + fn same_projection(&self, other: &FrameGizmo) -> bool { + self.layer == other.layer && self.effect == other.effect + } + + /// The command and params a drag of `grab` from `from` to `to` runs + fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: FrameGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> { + let delta = to - from; + let center = self.center; + let mut params = match grab { + FrameGrab::Slide => json!({"offset": self.slid_on_screen(delta)?}), + FrameGrab::Axis(axis) => { + let step = (*self.steps.get(axis)?)?; + let distance = delta.dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + match axis { + 0 => json!({"offset": self.slid(distance, 0.0)}), + 1 => json!({"offset": self.slid(0.0, distance)}), + _ => json!({"position": (self.origin + self.axes[2] * distance).to_array(), "normal": self.axes[2].to_array()}), + } + } + FrameGrab::Scale => { + let scale = (to - center).length() / (from - center).length().max(MIN_HANDLE_REACH); + json!({"size": [self.decal.size[0] * scale, self.decal.size[1] * scale]}) + } + FrameGrab::Side(side) => { + let direction = (*self.sides.get(side)? - center).normalized(); + let stretch = ((to - center).dot(direction) / (from - center).dot(direction).max(MIN_HANDLE_REACH)).max(MIN_SIDE_STRETCH); + let mut size = self.decal.size; + size[1 - side % 2] *= stretch; + json!({"size": size}) + } + FrameGrab::Turn => { + // The sweep round the centre on the frame's own plane (across turning towards up is a positive turn), so a tilted or off-centre frame follows the pointer too + let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees()); + let swept = angle(to)? - angle(from)?; + let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN; + json!({"rotation": self.decal.rotation + swept}) + } + FrameGrab::Corner(corner) => { + let mut corners = self.warp?; + *corners.get_mut(corner)? = self.on_plane(app, rect, to)?; + return Some(("layer.fill.projection", json!({"layer": self.layer.0, "warpCorners": corners}))); + } + }; + params["layer"] = json!(self.layer.0); + if let Some(effect) = self.effect { + params["effect"] = json!(effect.0); + } + Some(("layer.decal.set", params)) + } + + fn cursor(&self, grab: FrameGrab, dragging: bool) -> egui::CursorIcon { + grab.cursor(dragging) + } +} + +/// The selected frame over the 3D view: dashed outline, corner and edge dots, and the centre square with its axis arrows +pub(crate) fn overlay(ui: &Ui, rect: Rect, gizmo: &FrameGizmo) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let active = dragging::(ui.ctx()).map(|drag| drag.grab); + let hovered = ui.ctx().pointer_hover_pos().filter(|hover| rect.contains(*hover)).and_then(|hover| gizmo.grab(hover)); + let lit = |grab: FrameGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab)); + let dot_fill = |grab: FrameGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE }; + + let mut outline = gizmo.corners.to_vec(); + outline.push(gizmo.corners[0]); + dashed_outline(&painter, &outline); + if let Some(ring) = &gizmo.ring { + let color = if lit(FrameGrab::Turn) { tokens.viewport_accent } else { AXIS_COLORS[2] }; + painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO))); + painter.add(egui::Shape::line(ring.to_vec(), Stroke::new(SHAFT_WIDTH, color))); + } + match gizmo.warp { + Some(_) => { + for (index, corner) in gizmo.corners.into_iter().enumerate() { + handle_dot(&painter, corner, WARP_DOT, dot_fill(FrameGrab::Corner(index))); + } + } + None => { + for corner in gizmo.corners { + handle_dot(&painter, corner, CORNER_DOT, dot_fill(FrameGrab::Scale)); + } + } + } + for (index, side) in gizmo.sides.into_iter().enumerate() { + handle_dot(&painter, side, SIDE_DOT, dot_fill(FrameGrab::Side(index))); + } + + let arrow_color = |axis: usize| if lit(FrameGrab::Axis(axis)) { tokens.viewport_accent } else { AXIS_COLORS[axis] }; + move_handles(&painter, gizmo.center, gizmo.arrows, arrow_color, dot_fill(FrameGrab::Slide)); +} + +/// The centre square (filled `square`) with its X/Y/Z arrows to `arrows`, coloured by `arrow_color`; shafts and heads over a dark halo like the symmetry manipulator's +pub(crate) fn move_handles(painter: &egui::Painter, center: Pos2, arrows: [Option; 3], arrow_color: impl Fn(usize) -> Color32, square: Color32) { + for (axis, tip) in arrows.into_iter().enumerate() { + let Some(tip) = tip else { continue }; + + let color = arrow_color(axis); + let direction = (tip - center).normalized(); + let side = direction.rot90() * ARROW_HEAD * ARROW_HEAD_HALF_WIDTH; + let start = center + direction * CENTER_SQUARE * 0.5; + painter.line_segment([start, tip], Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)); + painter.line_segment([start, tip], Stroke::new(SHAFT_WIDTH, color)); + painter.add(egui::Shape::convex_polygon(vec![tip + direction * ARROW_HEAD, tip + side, tip - side], color, HANDLE_EDGE)); + } + let square_rect = Rect::from_center_size(center, vec2(CENTER_SQUARE, CENTER_SQUARE)); + painter.rect(square_rect, CENTER_SQUARE_CORNER_RADIUS, square, HANDLE_EDGE, egui::StrokeKind::Middle); +} + +/// The dashed outline: the dark shadow's width and colour, the light dashes' width and colour over it (white at 230 alpha, premultiplied), the dash and gap lengths +const OUTLINE_SHADOW_WIDTH: f32 = 3.0; +const OUTLINE_SHADOW: Color32 = Color32::from_black_alpha(140); +const OUTLINE_WIDTH: f32 = 1.2; +const OUTLINE_COLOR: Color32 = Color32::from_rgba_premultiplied(230, 230, 230, 230); +const OUTLINE_DASH: f32 = 6.0; +const OUTLINE_GAP: f32 = 4.0; + +/// A gizmo's dashed outline through `points`, light over a dark shadow so it reads on any model +pub(crate) fn dashed_outline(painter: &egui::Painter, points: &[Pos2]) { + for stroke in [Stroke::new(OUTLINE_SHADOW_WIDTH, OUTLINE_SHADOW), Stroke::new(OUTLINE_WIDTH, OUTLINE_COLOR)] { + painter.add(egui::Shape::dashed_line(points, stroke, OUTLINE_DASH, OUTLINE_GAP)); + } +} + +/// An arrow head's half width, as a share of its length +const ARROW_HEAD_HALF_WIDTH: f32 = 0.45; + +/// The dark rim around a handle dot +const DOT_RIM: f32 = 1.5; +/// The thin dark edge round handle dots, arrow heads and the centre square +pub(crate) const HANDLE_EDGE: Stroke = Stroke { width: 1.0, color: Color32::from_black_alpha(200) }; +/// The centre square's corner radius (points) +const CENTER_SQUARE_CORNER_RADIUS: f32 = 2.0; + +/// A handle dot of `radius`: `fill` over a dark rim, so it reads on a light or dark model +pub(crate) fn handle_dot(painter: &egui::Painter, at: Pos2, radius: f32, fill: Color32) { + painter.circle_filled(at, radius + DOT_RIM, SHAFT_HALO); + painter.circle(at, radius, fill, HANDLE_EDGE); +} + +#[cfg(test)] +pub(crate) mod tests { + use egui::{Modifiers, PointerButton, Pos2, vec2}; + use egui_kittest::kittest::Queryable; + use serde_json::json; + use texturecraft_engine::Session; + use texturecraft_engine::core::{LayerId, LayerKind, Projection}; + + use super::*; + + /// The test window: big enough that the docked panels leave the 3D view room for the ball with every gizmo handle round it + const TEST_WINDOW: egui::Vec2 = vec2(1600.0, 960.0); + + /// The ball in a new project, its first frames run; with `render` the views render through wgpu + pub(crate) fn ball_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> { + let session = Session::new_project("Gizmo", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(TEST_WINDOW); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness + } + + /// The ball with a selected fill layer projecting `projection` + pub(crate) fn fill_app(projection: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + fill_app_with(json!({"projection": projection})) + } + + /// The ball with a selected fill layer set up by `fields` of layer.fill.projection + pub(crate) fn fill_app_with(fields: serde_json::Value) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + fill_app_rendered(fields, false) + } + + /// As [`fill_app_with`]; with `render` the views render through wgpu + pub(crate) fn fill_app_rendered(mut fields: serde_json::Value, render: bool) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let mut harness = ball_app(render); + let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + fields["layer"] = json!(layer); + harness.state_mut().run("layer.fill.projection", fields).unwrap(); + harness.run_steps(2); + (harness, LayerId(layer)) + } + + pub(crate) fn projection(harness: &egui_kittest::Harness<'_, TextureCraftApp>, layer: LayerId) -> Projection { + match &harness.state().session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.projection.clone(), + _ => panic!("a fill layer"), + } + } + + /// A primary-button drag from `from` to `to` over a few frames, with `modifiers` held + pub(crate) fn drag(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) { + press_and_move(harness, from, to, modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }, modifiers); + harness.run_steps(2); + } + + /// The press and moves of [`drag`], the button still down at `to` + pub(crate) fn press_and_move(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, modifiers: Modifiers) { + harness.event_modifiers(egui::Event::PointerMoved(from), modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }, modifiers); + harness.run_steps(2); + for step in 1..=4 { + harness.event_modifiers(egui::Event::PointerMoved(from.lerp(to, step as f32 / 4.0)), modifiers); + harness.run_steps(1); + } + } + + /// Whether a frame drag is under way + fn frame_dragging(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> bool { + crate::projection_gizmo::dragging::(&harness.ctx).is_some() + } + + /// A drag as a mouse sends it, one small move per frame; after each frame `check` looks at the app and (with `preview`) the 3D preview square must have re-rendered + #[track_caller] + pub(crate) fn drag_frames( + harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, + layer: LayerId, + from: Pos2, + to: Pos2, + modifiers: Modifiers, + preview: bool, + mut check: impl FnMut(&egui_kittest::Harness<'_, TextureCraftApp>), + ) { + harness.event_modifiers(egui::Event::PointerMoved(from), modifiers); + harness.event_modifiers(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }, modifiers); + harness.run_steps(2); + let mut shown = crate::projection_preview::shown_key(&harness.ctx); + let mut was = projection(harness, layer); + let mut moved = 0; + for step in 1..=6 { + harness.event_modifiers(egui::Event::PointerMoved(from.lerp(to, step as f32 / 6.0)), modifiers); + harness.step(); + let now = projection(harness, layer); + + // Until the pointer passes the drag threshold nothing moves + if now == was { + assert_eq!(moved, 0, "frame {step}: once started, every frame of the drag moves it"); + continue; + } + + moved += 1; + check(harness); + let key = crate::projection_preview::shown_key(&harness.ctx); + assert!(!preview || (key.is_some() && key != shown), "frame {step}: the preview square re-rendered for the new values"); + (shown, was) = (key, now); + } + assert!(moved >= 4, "the drag moved it on {moved} frames"); + harness.event_modifiers(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }, modifiers); + harness.run_steps(2); + check(harness); + } + + /// The panel's X, Y and Z fields of a 3D projection settings row + pub(crate) fn panel_xyz(harness: &egui_kittest::Harness<'_, TextureCraftApp>, row: &str) -> [f32; 3] { + use egui_kittest::kittest::NodeT; + ["X", "Y", "Z"].map(|tag| harness.get_by_label(&format!("{row} {tag}")).accesskit_node().numeric_value().unwrap() as f32) + } + + fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> FrameGizmo { + FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() + } + + #[test] + fn an_axis_planar_is_placed_on_its_first_drag_and_its_handles_move_size_and_stretch_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + + // Repeating three times across the mesh, the frame is smaller than the ball + let (mut harness, layer) = fill_app_with(json!({"projection": "planar", "scale": 3})); + let axis = gizmo(&harness); + assert!(matches!(projection(&harness, layer), Projection::Planar { placed: None, .. }), "a new planar projects along its axis"); + assert!(axis.warp.is_none() && axis.arrows.iter().all(Option::is_some), "a planar frame with its three arrows: {axis:?}"); + + drag(&mut harness, axis.center, axis.center + vec2(30.0, 0.0), Modifiers::NONE); + let Projection::Planar { placed: Some(slid), .. } = projection(&harness, layer) else { panic!("placed on the first drag") }; + assert!(slid.offset[0] > 0.0 && slid.offset[1].abs() < slid.offset[0] * 0.2, "the centre square slides it right: {slid:?}"); + assert_eq!(slid.size, axis.decal.size, "sliding keeps its size"); + assert_eq!(harness.state().session.history_labels().last().map(String::as_str), Some("Edit decal")); + let steps = harness.state().session.history_labels().len(); + + let placed = gizmo(&harness); + drag(&mut harness, placed.sides[1], placed.center + (placed.sides[1] - placed.center) * 0.5, Modifiers::NONE); + let Projection::Planar { placed: Some(stretched), .. } = projection(&harness, layer) else { panic!("still placed") }; + assert!(stretched.size[0] < slid.size[0] * 0.75 && stretched.size[1] == slid.size[1], "the right edge dot narrows it only: {stretched:?}"); + + let narrowed = gizmo(&harness); + drag(&mut harness, narrowed.corners[2], narrowed.center + (narrowed.corners[2] - narrowed.center) * 1.5, Modifiers::NONE); + let Projection::Planar { placed: Some(scaled), .. } = projection(&harness, layer) else { panic!("still placed") }; + assert!(scaled.size[1] > stretched.size[1] * 1.2, "a corner scales it: {scaled:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2, "one undo step per drag"); + } + + #[test] + fn a_warp_corner_follows_the_pointer_on_the_frame_plane() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + assert_eq!(warp.warp, Some(Projection::FRAME_CORNERS)); + let to = warp.corners[1] + vec2(-40.0, 30.0); + drag(&mut harness, warp.corners[1], to, Modifiers::NONE); + let Projection::Warp { corners, frame, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert_eq!((frame, corners[0], corners[2], corners[3]), (warp.decal, [-0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]), "only that corner moves"); + assert!(corners[1][0] < 0.45 && corners[1][1] < 0.45, "top right pulled in: {corners:?}"); + assert!(gizmo(&harness).corners[1].distance(to) < 1.5, "the corner sits under the pointer"); + } + + /// A move that arrives in the same frame as the release still moves the corner: it ends under the pointer, not one step short + #[test] + fn a_move_in_the_release_frame_still_moves_the_corner() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("warp"); + let warp = gizmo(&harness); + let to = warp.corners[1] + vec2(-40.0, 30.0); + press_and_move(&mut harness, warp.corners[1], warp.corners[1].lerp(to, 0.5), Modifiers::NONE); + + // Straight into the next frame's input: the harness's queued events would each get a frame of their own + let release = egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }; + harness.input_mut().events.extend([egui::Event::PointerMoved(to), release]); + harness.run_steps(2); + + assert!(crate::projection_gizmo::dragging::(&harness.ctx).is_none(), "the release ends the drag"); + assert!(gizmo(&harness).corners[1].distance(to) < 1.5, "the corner sits under the release point: {:?} {to:?}", gizmo(&harness).corners[1]); + } + + /// The across and up arrows slide a frame on its own plane and the out arrow moves it along its normal, each following the pointer; one undo step per drag + #[test] + fn the_arrows_move_a_frame_along_its_directions() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let steps = harness.state().session.history_labels().len(); + let frame = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| match projection(harness, layer) { + Projection::Warp { frame, .. } => frame, + other => panic!("still a warp: {other:?}"), + }; + + for axis in 0..3 { + let start = gizmo(&harness); + let tip = start.arrows[axis].unwrap_or_else(|| panic!("arrow {axis} shows")); + let along = (tip - start.center).normalized(); + let before = frame(&harness); + drag(&mut harness, tip, tip + along * 25.0, Modifiers::NONE); + + let moved = gizmo(&harness); + assert!( + (moved.center - start.center).dot(along) > 15.0, + "arrow {axis}: the centre follows the pointer along it: {:?} -> {:?}", + start.center, + moved.center + ); + assert_eq!(frame(&harness).normal, before.normal, "arrow {axis}: moving never turns the frame"); + + // Across and up slide it on its own plane, out moves it along its normal + let shift = moved.origin - start.origin; + assert!(shift.normalize().dot(start.axes[axis]) > 0.99, "arrow {axis} moves it along its own direction: {shift:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + axis + 1, "arrow {axis}: one undo step per drag"); + } + } + + /// The panel's Rotation turns a frame and its Scale sizes it, so the gizmo does both: the ring turns a planar or warp frame round its normal, following the pointer round the centre; a warp's edge dots size its frame as a planar's do + #[test] + fn the_ring_turns_a_frame_and_a_warps_edge_dots_size_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["warp", "planar"] { + let (mut harness, _) = fill_app(kind); + let start = gizmo(&harness); + let ring = start.ring.unwrap_or_else(|| panic!("{kind}: a frame facing the camera shows its ring")); + let on_ring = *ring + .iter() + .filter(|at| start.grab(**at) == Some(FrameGrab::Turn)) + .max_by(|a, b| a.y.total_cmp(&b.y)) + .expect("a ring point clear of the other handles"); + let steps = harness.state().session.history_labels().len(); + let quarter = start.center + (on_ring - start.center).rot90(); + drag(&mut harness, on_ring, quarter, Modifiers::NONE); + let turned = gizmo(&harness); + let sweep = |from: egui::Vec2, to: egui::Vec2| (to.angle() - from.angle()).to_degrees(); + let pointer = sweep(on_ring - start.center, quarter - start.center); + let corner = sweep(start.corners[1] - start.center, turned.corners[1] - turned.center); + let off = (corner - pointer + 180.0).rem_euclid(360.0) - 180.0; + assert!(off.abs() < 6.0, "{kind}: the frame turns a quarter with the pointer: corner {corner}°, pointer {pointer}°"); + assert!(turned.center.distance(start.center) < 1.0, "{kind}: round its centre"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "{kind}: one undo step"); + } + + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1))); + drag(&mut harness, warp.sides[1], warp.center + (warp.sides[1] - warp.center) * 0.5, Modifiers::NONE); + let Projection::Warp { frame, corners, .. } = projection(&harness, layer) else { panic!("still a warp") }; + assert!(frame.size[0] < warp.decal.size[0] * 0.75 && (frame.size[1] - warp.decal.size[1]).abs() < 1e-4, "the right edge dot narrows it: {frame:?}"); + assert_eq!(corners, Projection::FRAME_CORNERS, "its corners stay where they are on the frame"); + } + + /// Losing the focus mid-drag (Alt+Tab) ends a frame drag as a release does: one undo step, and moves after it (egui still has the button down) leave the frame alone + #[test] + fn losing_the_window_focus_ends_a_frame_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(frame_dragging(&harness), "the centre square is held"); + + harness.event(egui::Event::WindowFocused(false)); + harness.run_steps(1); + let left = projection(&harness, layer); + assert!(!frame_dragging(&harness), "the focus loss ends the drag"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "as one undo step"); + + for step in 1..=3 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), left, "moves after it leave the frame where it was"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "and add no step"); + } + + /// Alt pressed mid-drag hands the pointer to the camera and ends the frame drag where it is: let go of Alt with the button still down, the drag does not resume from where it began; one undo step + #[test] + fn alt_mid_drag_ends_a_frame_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + let slid = projection(&harness, layer); + let camera = harness.state().session.camera; + + harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); + harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); + assert!(!frame_dragging(&harness), "and ends the frame drag"); + + for step in 2..=4 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the frame stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + } + + /// The rest of a drag held at `from`: moves to `to` over a few frames and lets go there + fn move_and_let_go(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + for step in 1..=4 { + harness.event(egui::Event::PointerMoved(from.lerp(to, step as f32 / 4.0))); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + /// A drag whose first edit changes nothing (its arrow pulled further past the offset limit) makes no undo step, so its later edits make the drag's own step instead of joining the edit before it + #[test] + fn a_drag_that_first_changes_nothing_keeps_its_own_undo_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + + // The frame waits at its left limit, a mesh diagonal off the ball's centre, clear of the panels on the right; the camera backs off so it shows with its arrows + harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "offset": [-100.0, 0.0]})).unwrap(); + harness.state_mut().session.camera.distance *= 3.0; + harness.run_steps(2); + let at_limit = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + let start = gizmo(&harness); + let tip = start.arrows[0].expect("the across arrow shows"); + let inward = (tip - start.center).normalized(); + + press_and_move(&mut harness, tip, tip - inward * 25.0, Modifiers::NONE); + + assert_eq!(projection(&harness, layer), at_limit, "past the limit the frame stays where it is"); + move_and_let_go(&mut harness, tip - inward * 25.0, tip + inward * 25.0); + + assert_ne!(projection(&harness, layer), at_limit, "back inside the frame moves"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag made its own undo step"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), at_limit, "undo takes back the drag only"); + } + + /// An axis planar reading a pattern keeps its axis, so it shows no frame to drag; reading an image it shows one + #[test] + fn an_axis_planar_reading_a_pattern_has_no_frame() { + let (mut harness, layer) = fill_app("planar"); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some(), "a uniform fill places as its frame"); + + harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "roughness", "procedural": "Checker"})).unwrap(); + harness.run_steps(2); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "placing would move the pattern"); + } + + /// An Undo mid-drag takes the drag's step away: the drag's next edits make a step of their own instead of joining the drag before it + #[test] + fn undo_mid_drag_leaves_the_drag_before_its_own_step() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("warp"); + let center = gizmo(&harness).center; + drag(&mut harness, center, center + vec2(30.0, 0.0), Modifiers::NONE); + let first = projection(&harness, layer); + let steps = harness.state().session.history_labels().len(); + + let center = gizmo(&harness).center; + press_and_move(&mut harness, center, center + vec2(0.0, 30.0), Modifiers::NONE); + harness.key_press_modifiers(Modifiers::COMMAND, egui::Key::Z); + harness.run_steps(1); + assert_eq!(projection(&harness, layer), first, "Ctrl+Z undid the drag so far"); + move_and_let_go(&mut harness, center + vec2(0.0, 30.0), center + vec2(0.0, 40.0)); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag's later edits made a step of their own"); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), first, "undo goes back to where the first drag left the frame"); + } + + /// A click as a mouse sends it: move there, press, release + fn click(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, at: Pos2) { + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + /// The Projection row's eye hides the gizmo: not drawn, a press on where its handle was moves nothing, and the eye brings it back + #[test] + fn the_projection_rows_eye_hides_and_shows_the_gizmo() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "planar", "scale": 3})); + let shown = gizmo(&harness); + let eye = harness.get_by_label("Hide projection gizmos").rect(); + let projection_row = harness.get_by_label("Planar projection").rect(); + assert!(eye.left() > projection_row.right() && (eye.center().y - projection_row.center().y).abs() < 0.5, "the eye ends the Projection row"); + + click(&mut harness, eye.center()); + assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos"); + assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab"); + let before = projection(&harness, layer); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), before, "a drag where the centre square was moves nothing"); + + let eye = harness.get_by_label("Show projection gizmos").rect(); + click(&mut harness, eye.center()); + assert!(harness.state().session.doc.project.display.projection_gizmos, "the eye shows them again"); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "shown, the centre square slides it again"); + + // A UV projection has no gizmo: its row keeps the whole width for the dropdown + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "uv"})).unwrap(); + harness.run_steps(2); + assert!(harness.query_by_label("Hide projection gizmos").is_none(), "no eye without a gizmo"); + } + + #[test] + fn round_projections_have_no_frame() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for projection in ["uv", "triplanar", "spherical", "cylindrical"] { + let (harness, _) = fill_app(projection); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "{projection}"); + } + } + + /// The planar and warp frames over the ball, a handle hovered, Move on model lit, and the round projectors + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn frame_gizmo_snapshots() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + 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 checker = |harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, layer: LayerId| { + let fields = + json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0.2, 0.2, 0.2], "high": [0.6, 0.6, 0.6]}); + harness.state_mut().run("layer.fill.set", fields).unwrap(); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "shapeCrop": "cropped"})).unwrap(); + }; + let (mut harness, layer) = fill_app_rendered(json!({"projection": "planar", "scale": 3}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let planar = gizmo(&harness); + harness.hover_at(planar.sides[1]); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("move-planar-side-hover.png")).unwrap(); + + // Move on model held down and dragged into the 3D view: the button stays lit and the frame follows + let button = harness.get_by_label("Move on model").rect().center(); + harness.event(egui::Event::PointerMoved(button)); + harness.event(egui::Event::PointerButton { pos: button, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(button + vec2(-40.0, 10.0) * step as f32)); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("move-planar-held.png")).unwrap(); + harness.event(egui::Event::PointerButton { + pos: button + vec2(-240.0, 60.0), + button: PointerButton::Primary, + pressed: false, + modifiers: Modifiers::NONE, + }); + harness.run_steps(2); + + let (mut harness, layer) = fill_app_rendered(json!({"projection": "warp"}), true); + checker(&mut harness, layer); + let pulled = json!([[-0.35, 0.3], [0.4, 0.42], [0.42, -0.4], [-0.3, -0.32]]); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "warpCorners": pulled, "projectionDepth": 1})).unwrap(); + harness.run_steps(4); + harness.hover_at(gizmo(&harness).corners[1]); + harness.run_steps(4); + harness.render().unwrap().save(directory.join("move-warp-corner-hover.png")).unwrap(); + + // Mid drag: the panel's 3D projection settings and the preview square hold the frame the gizmo is dragging + let (mut harness, layer) = fill_app_rendered(json!({"projection": "planar", "scale": 3}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let held = gizmo(&harness); + let (from, to) = (held.sides[0], held.center + (held.sides[0] - held.center) * 0.6 + vec2(30.0, 0.0)); + harness.event(egui::Event::PointerMoved(from)); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(from.lerp(to, step as f32 / 6.0))); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("sync-planar-mid-drag.png")).unwrap(); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + let (mut harness, layer) = fill_app_rendered(json!({"projection": "spherical"}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let round = crate::round_gizmo::RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + let dot = round.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + let to = round.center + (dot - round.center) * 0.6; + harness.event(egui::Event::PointerMoved(dot)); + harness.event(egui::Event::PointerButton { pos: dot, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.event(egui::Event::PointerMoved(dot.lerp(to, step as f32 / 6.0))); + harness.run_steps(1); + } + harness.run_steps(3); + harness.render().unwrap().save(directory.join("sync-sphere-mid-drag.png")).unwrap(); + + // The round projections with their fill selected: the shape round it, a ring hovered (a sphere: its one dot; a cylinder: its height arrow) + for kind in ["triplanar", "spherical", "cylindrical"] { + let (mut harness, layer) = fill_app_rendered(json!({"projection": kind}), true); + checker(&mut harness, layer); + harness.run_steps(4); + let round = crate::round_gizmo::RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + let size_at = |axes: [bool; 3]| round.sizes.iter().find(|size| size.axes == axes).expect("the size handle").at; + let hover = match kind { + "triplanar" => round.rings[2][crate::round_gizmo::CIRCLE_POINTS / 8], + "spherical" => size_at([true; 3]), + _ => size_at([false, true, false]), + }; + harness.hover_at(hover); + harness.run_steps(4); + harness.render().unwrap().save(directory.join(format!("move-{kind}.png"))).unwrap(); + } + } + + /// The panel's 3D projection settings show the frame the gizmo drags (its centre, turn and size), and the preview square follows, every frame of every drag: resize, stretch, slide, turn, a warp's slide and corners; one undo step per drag + #[test] + fn the_panel_and_its_preview_follow_every_frame_of_a_frame_drag() { + // Dolly exponent stepping the camera back before the corner drag + const CORNER_ZOOM_OUT: f32 = 0.4; + + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + use texturecraft_engine::compose::frame_placement::placement; + + let check = |layer: LayerId| { + move |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + let Some(shown) = placement(&projection(harness, layer), harness.state().session.mesh.bounds()) else { panic!("placed on its first drag") }; + for (row, value) in [("Offset", shown.offset), ("Rotation", shown.rotation), ("Scale", shown.scale)] { + let field = panel_xyz(harness, row); + for axis in 0..3 { + assert!((field[axis] - value[axis]).abs() < 1e-3, "the panel's {row} shows the frame's {value:?}, not {field:?}"); + } + } + } + }; + + let (mut harness, layer) = fill_app("planar"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + drag_frames(&mut harness, layer, center, center + vec2(30.0, -10.0), Modifiers::NONE, true, check(layer)); + let slid = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + + // The top edge dot and a corner inside the view (the frame starts bigger than the model) + let side = gizmo(&harness); + drag_frames(&mut harness, layer, side.sides[0], side.center + (side.sides[0] - side.center) * 0.5, Modifiers::NONE, true, check(layer)); + let narrowed = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(narrowed.scale[1] < slid.scale[1] * 0.75 && (narrowed.scale[0] - slid.scale[0]).abs() < 1e-4, "{slid:?} -> {narrowed:?}"); + + // The view steps back so a corner shows beside the panels + harness.state_mut().session.camera.zoom(-CORNER_ZOOM_OUT); + harness.run_steps(2); + let corner = gizmo(&harness); + let view = harness.state().viewport_rect.shrink(10.0); + let inside = *corner.corners.iter().find(|at| view.contains(**at)).expect("a corner in the view"); + drag_frames(&mut harness, layer, inside, corner.center + (inside - corner.center) * 0.6, Modifiers::NONE, true, check(layer)); + let scaled = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(scaled.scale[1] < narrowed.scale[1] * 0.8 && scaled.scale[0] < narrowed.scale[0] * 0.8, "a corner scales it: {scaled:?}"); + + // Move on model held with Shift turns the frame round its normal + let before = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + let button = harness.get_by_label("Move on model").rect().center(); + drag_frames(&mut harness, layer, button, button + vec2(-60.0, 0.0), Modifiers::SHIFT, true, check(layer)); + let turned = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!((turned.rotation[2] - before.rotation[2]).abs() > 10.0, "turned: {before:?} -> {turned:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 4, "one undo step per drag"); + + let (mut harness, layer) = fill_app("warp"); + let warp = gizmo(&harness); + drag_frames(&mut harness, layer, warp.center, warp.center + vec2(30.0, 25.0), Modifiers::NONE, false, check(layer)); + let warp = gizmo(&harness); + drag_frames(&mut harness, layer, warp.corners[0], warp.corners[0] + vec2(-25.0, -15.0), Modifiers::NONE, false, check(layer)); + let Projection::Warp { corners, .. } = projection(&harness, layer) else { panic!("a warp") }; + assert_ne!(corners[0], Projection::FRAME_CORNERS[0], "the corner was pulled"); + } +} diff --git a/crates/ui-egui/src/frame_gizmo/frame_grab.rs b/crates/ui-egui/src/frame_gizmo/frame_grab.rs new file mode 100644 index 00000000..a0733168 --- /dev/null +++ b/crates/ui-egui/src/frame_gizmo/frame_grab.rs @@ -0,0 +1,29 @@ +/// What a drag on the frame does +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum FrameGrab { + /// The centre square: slide the frame across its own plane + Slide, + /// Along the frame's across (0), up (1) or out (2) direction + Axis(usize), + /// A planar's corner: scale it about its centre + Scale, + /// A planar's edge dot (top, right, bottom, left): stretch that side + Side(usize), + /// A warp's corner (top left, top right, bottom right, bottom left): pull it + Corner(usize), + /// The ring: turn it round its normal + Turn, +} + +impl FrameGrab { + pub(super) fn cursor(self, dragging: bool) -> egui::CursorIcon { + match self { + FrameGrab::Slide if dragging => egui::CursorIcon::Grabbing, + FrameGrab::Slide => egui::CursorIcon::Grab, + FrameGrab::Axis(_) | FrameGrab::Corner(_) | FrameGrab::Turn => egui::CursorIcon::Move, + FrameGrab::Scale => egui::CursorIcon::ResizeNwSe, + FrameGrab::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical, + FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal, + } + } +} diff --git a/crates/ui-egui/src/projection_gizmo.rs b/crates/ui-egui/src/projection_gizmo.rs new file mode 100644 index 00000000..06b1c199 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo.rs @@ -0,0 +1,77 @@ +//! A drag on a handle of the selected fill's projection gizmo, a planar or warp frame or a round projector: one undo step per drag, the projection updating live + +mod gizmo; +mod gizmo_drag; +mod shown_gizmo; + +use egui::{PointerButton, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::Session; + +use crate::TextureCraftApp; +use crate::viewport::focus_lost; + +pub(crate) use gizmo::Gizmo; +pub(crate) use gizmo_drag::GizmoDrag; +pub(crate) use shown_gizmo::ShownGizmo; + +/// The drag under way on a handle of a `G` gizmo +pub(crate) fn dragging(ctx: &egui::Context) -> Option> { + ctx.data(|data| data.get_temp::>(G::drag_id())) +} + +/// Ends a drag under way on a `G` gizmo where it is: its undo step stays one step +pub(crate) fn let_go(ctx: &egui::Context) { + ctx.data_mut(|data| data.remove::>(G::drag_id())); +} + +/// Drags on `gizmo`'s handles (one undo step per drag, the projection updates live); returns whether a drag owns the pointer. The cursor shows what the handle under it, or the one dragged, does (only while the gizmo takes input: an Alt orbit or a held Move on model keeps its own) +pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, response: &egui::Response, rect: Rect, gizmo: Option<&G>) -> bool { + let mut drag = dragging::(ctx).filter(|drag| gizmo.is_some_and(|gizmo| gizmo.same_projection(&drag.start))); + if response.drag_started_by(PointerButton::Primary) + && let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin())) + && let Some(grab) = gizmo.grab(from) + { + drag = Some(GizmoDrag { grab, from, start: gizmo.clone(), edited_revision: None }); + } + + // A window that lost the focus gets no release: the drag ends there. A release still applies a move that came in the same frame + let released = response.drag_stopped_by(PointerButton::Primary); + let pressed = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary) || released; + let Some(mut drag) = drag.filter(|_| pressed && !focus_lost(ctx)) else { + let_go::(ctx); + if let Some((gizmo, grab)) = gizmo.and_then(|gizmo| Some((gizmo, gizmo.grab(response.hover_pos()?)?))) { + ctx.set_cursor_icon(gizmo.cursor(grab, false)); + } + return false; + }; + + // A drag lives only while its gizmo shows, so the gizmo drawn this frame names the cursor + ctx.set_cursor_icon(gizmo.unwrap_or(&drag.start).cursor(drag.grab, true)); + + if let Some(pointer) = response.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) + && let Some((command, params)) = drag.start.edit(app, rect, drag.grab, drag.from, pointer) + { + edit_in_one_step(&mut app.session, command, params, &mut drag.edited_revision); + + // The panel drew before this edit: one more frame shows its fields and preview where the projection is now + ctx.request_repaint(); + } + if released { + let_go::(ctx); + } else { + ctx.data_mut(|data| data.insert_temp(G::drag_id(), drag)); + } + true +} + +/// Runs one edit of a drag or hold, joining the undo step its last edit (at `edited_revision`) made while the history is still where that edit left it: an edit that changed nothing made no step to join, and an Undo took the step away +pub(crate) fn edit_in_one_step(session: &mut Session, command: &str, mut params: Value, edited_revision: &mut Option) { + params["merge"] = json!(*edited_revision == Some(session.revision)); + let before = session.revision; + + // Off the plane or past the size limits: the projection waits where it is + if texturecraft_engine::execute(session, command, ¶ms).is_ok() && session.revision != before { + *edited_revision = Some(session.revision); + } +} diff --git a/crates/ui-egui/src/projection_gizmo/gizmo.rs b/crates/ui-egui/src/projection_gizmo/gizmo.rs new file mode 100644 index 00000000..e95c8270 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/gizmo.rs @@ -0,0 +1,25 @@ +use egui::{Pos2, Rect}; +use serde_json::Value; + +use crate::TextureCraftApp; + +/// A projection gizmo whose handles a drag edits +pub(crate) trait Gizmo: Clone + Send + Sync + 'static { + /// What a drag on one of its handles does + type Grab: Copy + PartialEq + Send + Sync + 'static; + + /// Where a drag on it is kept in egui's memory + fn drag_id() -> egui::Id; + + /// The handle under screen point `at` + fn grab(&self, at: Pos2) -> Option; + + /// Whether `other` shows the same projection: a drag goes on only while the projection it began on shows + fn same_projection(&self, other: &Self) -> bool; + + /// The command and params a drag of `grab` from `from` to `to` runs + fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: Self::Grab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)>; + + /// The cursor over `grab`, or dragging it + fn cursor(&self, grab: Self::Grab, dragging: bool) -> egui::CursorIcon; +} diff --git a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs new file mode 100644 index 00000000..bf8221b5 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs @@ -0,0 +1,14 @@ +use egui::Pos2; + +use super::Gizmo; + +/// A handle of a projection gizmo being dragged (kept in egui's memory between frames) +#[derive(Clone, Debug)] +pub(crate) struct GizmoDrag { + pub(crate) grab: G::Grab, + /// Where the drag started and the gizmo then + pub(crate) from: Pos2, + pub(crate) start: G, + /// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there + pub(crate) edited_revision: Option, +} diff --git a/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs new file mode 100644 index 00000000..cd2a7e26 --- /dev/null +++ b/crates/ui-egui/src/projection_gizmo/shown_gizmo.rs @@ -0,0 +1,73 @@ +use egui::{Pos2, Rect, Ui}; + +use super::{Gizmo, dragging, let_go}; +use crate::TextureCraftApp; +use crate::frame_gizmo::FrameGizmo; +use crate::round_gizmo::RoundGizmo; + +/// The selected fill's projection gizmo the 3D view shows, built once a frame: a planar or warp frame, or a round projector +pub(crate) enum ShownGizmo { + // Both boxed: each gizmo is hundreds of bytes and of a different size + Frame(Box), + Round(Box), +} + +impl ShownGizmo { + /// The gizmo of the selected fill's projection: none while the Projection row's eye hides it + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + FrameGizmo::shown(app, rect) + .map(|frame| ShownGizmo::Frame(Box::new(frame))) + .or_else(|| RoundGizmo::shown(app, rect).map(|round| ShownGizmo::Round(Box::new(round)))) + } + + fn frame(gizmo: Option<&ShownGizmo>) -> Option<&FrameGizmo> { + match gizmo? { + ShownGizmo::Frame(frame) => Some(frame), + ShownGizmo::Round(_) => None, + } + } + + fn round(gizmo: Option<&ShownGizmo>) -> Option<&RoundGizmo> { + match gizmo? { + ShownGizmo::Round(round) => Some(round), + ShownGizmo::Frame(_) => None, + } + } + + /// Drags on `gizmo`'s handles; returns whether a drag owns the pointer + pub(crate) fn input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, rect: Rect, gizmo: Option<&ShownGizmo>) -> bool { + let ctx = ui.ctx(); + super::input(app, ctx, response, rect, ShownGizmo::frame(gizmo)) || super::input(app, ctx, response, rect, ShownGizmo::round(gizmo)) + } + + /// Ends a drag under way on either gizmo where it is + pub(crate) fn let_go(ctx: &egui::Context) { + let_go::(ctx); + let_go::(ctx); + } + + /// Whether screen point `at` is on one of its handles + pub(crate) fn on_handle(&self, rect: Rect, at: Pos2) -> bool { + rect.contains(at) + && match self { + ShownGizmo::Frame(frame) => frame.grab(at).is_some(), + ShownGizmo::Round(round) => round.grab(at).is_some(), + } + } + + /// Whether the pointer is over one of `gizmo`'s handles or dragging one (the brush cursor hides there) + pub(crate) fn hovered(ui: &Ui, rect: Rect, gizmo: Option<&ShownGizmo>) -> bool { + let ctx = ui.ctx(); + dragging::(ctx).is_some() + || dragging::(ctx).is_some() + || ctx.pointer_hover_pos().is_some_and(|hover| gizmo.is_some_and(|gizmo| gizmo.on_handle(rect, hover))) + } + + /// The gizmo over the 3D view + pub(crate) fn overlay(&self, app: &TextureCraftApp, ui: &Ui, rect: Rect) { + match self { + ShownGizmo::Frame(frame) => crate::frame_gizmo::overlay(ui, rect, frame), + ShownGizmo::Round(round) => crate::round_gizmo::overlay(app, ui, rect, round), + } + } +} diff --git a/crates/ui-egui/src/projector_outline.rs b/crates/ui-egui/src/projector_outline.rs new file mode 100644 index 00000000..ddd40e64 --- /dev/null +++ b/crates/ui-egui/src/projector_outline.rs @@ -0,0 +1,159 @@ +//! The projector a 3D projection's preview square draws round its object, as the 3D view's gizmo shows it round the model: a planar's frame with the dot its image travels to, a sphere's rim, equator and meridian, a tri-planar box or a cylinder + +use texturecraft_engine::compose::axis_frame::axis_frame; +use texturecraft_engine::compose::pattern::{cylinder_axis_index, decal_axes}; +use texturecraft_engine::core::Projection; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; + +use crate::round_gizmo::{BOX_REACH, CIRCLE_POINTS, CYLINDER_HEIGHT, CYLINDER_REACH, SPHERE_REACH, box_corner, box_edges}; + +mod place; + +use place::Place; + +/// How far in front of the object a planar's frame stands (preview units) +const FRAME_GAP: f32 = 0.15; + +/// How far a planar's direction line reaches back from its frame (preview units) +const DIRECTION_LENGTH: f32 = 0.35; + +/// The projector's outline in the preview's coordinates (the compositor's: the mesh's centre at the origin, its half diagonal 1) +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct ProjectorOutline { + /// Polylines; a closed one repeats its first point at its end + pub lines: Vec>, + /// Where a planar's image travels to from its frame: the direction dot + pub tip: Option, + /// The projector's centre: a frame's middle, a round projector's centre + pub center: Vec3, +} + +impl ProjectorOutline { + /// The outline of `projection`'s projector round an object with half sizes `object` (None for projections without one: UV, warp, placed planars, which the preview shows as axis planars) + pub(crate) fn of(projection: &Projection, object: Vec3) -> Option { + let outline = match projection { + Projection::Planar { scale, axis, offset, projector, placed: None, .. } => { + // The compositor's coordinates as a mesh: centred, half diagonal 1, so each corner sits 1/√3 out along every axis + let corner = Vec3::splat(1.0 / 3f32.sqrt()); + let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, (-corner, corner))?; + planar(frame.size, decal_axes(&frame)?, object) + } + Projection::Triplanar { scale, offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), *scale); + let size = object * BOX_REACH; + let corner = |index: usize| place.world(place.local + size * box_corner(index)); + let lines = box_edges().map(|(first, second)| vec![corner(first), corner(second)]).collect(); + + ProjectorOutline { lines, tip: None, center: place.world(place.local) } + } + Projection::Spherical { offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), 1.0); + let radius = object.max_element() * SPHERE_REACH; + let (u, v) = place.facing().any_orthonormal_pair(); + let ring = |a: Vec3, b: Vec3| circle(|t| place.world(place.local + (a * t.x + b * t.y) * radius)); + ProjectorOutline { lines: vec![ring(u, v), ring(Vec3::X, Vec3::Z), ring(Vec3::Y, Vec3::Z)], tip: None, center: place.world(place.local) } + } + Projection::Cylindrical { axis, offset, projector, .. } => { + let place = Place::new(projector.rotation, projector.scale, Vec3::from(*offset), 1.0); + let axis = cylinder_axis_index(*axis); + let along = Vec3::AXES[axis]; + let (u, v) = (Vec3::AXES[(axis + 1) % Vec3::AXES.len()], Vec3::AXES[(axis + 2) % Vec3::AXES.len()]); + let radius = (object * (Vec3::ONE - along)).max_element() * CYLINDER_REACH; + let half_height = object[axis] * CYLINDER_HEIGHT; + let cap = |height: f32| circle(|t| place.world(place.local + along * height + (u * t.x + v * t.y) * radius)); + let mut lines = vec![cap(half_height), cap(-half_height)]; + + // The two side lines, where the round side turns away from the camera + let facing = place.facing(); + if let Some(side) = along.cross(facing - along * facing.dot(along)).try_normalize() { + for edge in [side, -side] { + lines.push(vec![ + place.world(place.local + edge * radius + along * half_height), + place.world(place.local + edge * radius - along * half_height), + ]); + } + } + ProjectorOutline { lines, tip: None, center: place.world(place.local) } + } + Projection::Planar { placed: Some(_), .. } | Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None, + }; + let finite = outline.points().all(|point| point.is_finite()) && outline.center.is_finite(); + finite.then_some(outline) + } + + /// Every point the outline draws, the direction dot included + pub(crate) fn points(&self) -> impl Iterator + '_ { + self.lines.iter().flatten().copied().chain(self.tip) + } +} + +/// A planar's frame, `size` across and up on the frame `axes` (origin, across, up, out), stood just in front of the object on the side its image reads from, and the line its image travels along into the object +fn planar(size: [f32; 2], (origin, across, up, out): (Vec3, Vec3, Vec3, Vec3), object: Vec3) -> ProjectorOutline { + let center = origin + out * (object.max_element() + FRAME_GAP - origin.dot(out)); + let (across, up) = (across * size[0] / 2.0, up * size[1] / 2.0); + let corners = [center - across - up, center + across - up, center + across + up, center - across + up, center - across - up]; + let tip = center - out * DIRECTION_LENGTH; + ProjectorOutline { lines: vec![corners.to_vec(), vec![center, tip]], tip: Some(tip), center } +} + +/// A closed circle through `at` of the unit circle's points +fn circle(at: impl Fn(Vec2) -> Vec3) -> Vec { + (0..=CIRCLE_POINTS) + .map(|index| { + let angle = index as f32 / CIRCLE_POINTS as f32 * std::f32::consts::TAU; + at(Vec2::new(angle.cos(), angle.sin())) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Projector, UvTransform}; + + const BALL: Vec3 = Vec3::splat(0.85); + + fn spherical(projector: Projector, offset: [f32; 3]) -> Projection { + Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset, projector } + } + + #[test] + fn every_3d_projection_has_its_projector_outline() { + let planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default(), placed: None }; + let outline = ProjectorOutline::of(&planar, BALL).unwrap(); + assert_eq!(outline.lines.len(), 2, "a frame and its direction line"); + let tip = outline.tip.unwrap(); + assert!(tip.z < BALL.z + FRAME_GAP && outline.lines[0][0].z > BALL.z, "the frame stands in front of the ball, the dot points into it"); + + assert_eq!(ProjectorOutline::of(&spherical(Projector::default(), [0.0; 3]), BALL).unwrap().lines.len(), 3, "rim, equator, meridian"); + let cylinder = + Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Projector::default(), angle: 360.0 }; + assert_eq!(ProjectorOutline::of(&cylinder, Vec3::new(0.55, 0.7, 0.55)).unwrap().lines.len(), 4, "two caps, two side lines"); + let triplanar = Projection::triplanar(); + assert_eq!(ProjectorOutline::of(&triplanar, Vec3::splat(0.55)).unwrap().lines.len(), 12, "a box's edges"); + assert!(ProjectorOutline::of(&Projection::UvTile, BALL).is_none()); + } + + #[test] + fn a_cylinder_axis_past_z_wraps_round_y_as_the_compositor_reads_it() { + let cylinder = |axis: u8| Projection::Cylindrical { + scale: 1.0, + axis, + uv: UvTransform::default(), + offset: [0.0; 3], + projector: Projector::default(), + angle: 360.0, + }; + let object = Vec3::new(0.55, 0.7, 0.4); + assert_eq!(ProjectorOutline::of(&cylinder(3), object), ProjectorOutline::of(&cylinder(1), object)); + } + + #[test] + fn the_outline_follows_the_projectors_size_and_centre() { + let reach = |projection: &Projection| ProjectorOutline::of(projection, BALL).unwrap().points().map(Vec3::length).fold(0.0, f32::max); + let plain = reach(&spherical(Projector::default(), [0.0; 3])); + assert!((plain - 0.85 * SPHERE_REACH).abs() < 1e-4, "{plain}"); + assert!((reach(&spherical(Projector { scale: [3.0; 3], ..Projector::default() }, [0.0; 3])) - 3.0 * plain).abs() < 1e-3, "x3 is three times as far"); + assert!(reach(&spherical(Projector::default(), [0.5, 0.0, 0.0])) > plain + 0.4, "an offset moves it"); + } +} diff --git a/crates/ui-egui/src/projector_outline/place.rs b/crates/ui-egui/src/projector_outline/place.rs new file mode 100644 index 00000000..9cf1d79a --- /dev/null +++ b/crates/ui-egui/src/projector_outline/place.rs @@ -0,0 +1,27 @@ +use texturecraft_engine::compose::pattern::nonzero_stretch; +use texturecraft_engine::geom::glam::{EulerRot, Mat3, Vec3}; + +/// A round projector's turn, stretch and centre: a point in its own units lands at `turn × (stretch × point)` (the gizmo's placement) +pub(super) struct Place { + pub(super) turn: Mat3, + pub(super) stretch: Vec3, + /// Its centre in its own units + pub(super) local: Vec3, +} + +impl Place { + /// `offset` moves the centre by `-offset / per_local` of its own units + pub(super) fn new(rotation: [f32; 3], scale: [f32; 3], offset: Vec3, per_local: f32) -> Place { + let [x, y, z] = rotation.map(f32::to_radians); + Place { turn: Mat3::from_euler(EulerRot::ZYX, z, y, x), stretch: Vec3::from(scale).map(nonzero_stretch), local: -offset / nonzero_stretch(per_local) } + } + + pub(super) fn world(&self, local: Vec3) -> Vec3 { + self.turn * (self.stretch * local) + } + + /// The preview camera's view direction in the projector's own units: the rim is the circle across it + pub(super) fn facing(&self) -> Vec3 { + (self.turn.transpose() * crate::projection_preview::view_direction() / self.stretch).try_normalize().unwrap_or(Vec3::Z) + } +} diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs new file mode 100644 index 00000000..146cd50f --- /dev/null +++ b/crates/ui-egui/src/round_gizmo.rs @@ -0,0 +1,885 @@ +//! The selected tri-planar, spherical or cylindrical fill shows its projector round the whole model: a dashed box, sphere or cylinder with the centre square, X/Y/Z arrows and turn rings, and size handles: a dot scales it evenly (or a cylinder across its axis), a double arrow stretches it along one direction. Only a press on one of those handles moves it: any other drag paints or turns the camera + +use egui::{Color32, Pos2, Rect, Stroke, Ui}; +use serde_json::{Value, json}; +use texturecraft_engine::compose::pattern::{cylinder_axis_index, mesh_frame, nonzero_stretch, projector_stretch}; +use texturecraft_engine::core::Projection; +use texturecraft_engine::geom::glam::{EulerRot, Mat3, Quat, Vec2, Vec3}; +use texturecraft_engine::layer_cmds::signed_scale; + +use crate::TextureCraftApp; +use crate::frame_gizmo::{ + ARROW, EDGE_ON_FACING, HANDLE_EDGE, MIN_HANDLE_REACH, MIN_SCREEN_SPAN, TURN_RING, arrow_distance, center_distance, dashed_outline, distance_to_segment, + handle_dot, move_handles, nearest, ring_open, +}; +use crate::move_on_model::MoveOnModel; +use crate::projection_gizmo::{Gizmo, dragging}; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH, Tokens}; +use crate::viewport::{project, view_ray}; + +mod round_grab; +mod shape; +mod size_handle; + +pub(crate) use round_grab::RoundGrab; +use shape::Shape; +pub(crate) use size_handle::SizeHandle; + +/// The projector of the fill Move on model moves, as the 3D view shows it +#[derive(Clone, Debug)] +pub(crate) struct RoundGizmo { + pub(crate) target: MoveOnModel, + /// Mesh centre and radius: the projector reads positions around it in radii + mesh_center: Vec3, + radius: f32, + /// The projector's turn and per-axis scale (a mirrored axis keeps its sign, as the projection reads it) + turn: Mat3, + stretch: Vec3, + /// The projection's centre in the projector's units, and what offset puts it there (offset = -local × this) + local: Vec3, + offset_per_local: f32, + /// On screen: the centre, the arrow tips, the turn rings, the dashed outline and the size handles + pub center: Pos2, + pub arrows: [Option; 3], + pub rings: [Vec; 3], + outline: Vec>, + pub sizes: Vec, + /// Screen movement per world unit along each projector direction at the centre + steps: [Option; 3], +} + +/// How far round the model each shape reaches, in the mesh's half sizes: the box, the sphere, the cylinder's radius and half height +pub(crate) const BOX_REACH: f32 = 1.08; +pub(crate) const SPHERE_REACH: f32 = 1.2; +pub(crate) const CYLINDER_REACH: f32 = 1.1; +pub(crate) const CYLINDER_HEIGHT: f32 = 1.15; +/// The size dots' radius (points) +const SIZE_DOT: f32 = 7.0; +/// A size double arrow's half length, tip to middle, and its heads' length and half width (points) +const SIZE_ARROW: f32 = 12.0; +const SIZE_ARROW_HEAD: f32 = 7.0; +const SIZE_ARROW_HEAD_HALF_WIDTH: f32 = 5.0; +/// How far from the centre a box face's double arrow must land on screen to show: nearer, the face is seen head on and its arrow would sit on the centre square +const FACE_CLEARANCE: f32 = 40.0; +/// Points on a drawn circle +pub(crate) const CIRCLE_POINTS: usize = 48; +/// A box's corners, and the bit of a corner's index that flips it along each axis +const BOX_CORNERS: usize = 8; +const BOX_AXIS_BITS: [usize; 3] = [1, 2, 4]; +/// How far along each direction its screen step is measured, in mesh radii: half way out, inside the model, where perspective bends it little +const STEP_PROBE_RADII: f32 = 0.5; + +impl RoundGizmo { + /// The projector as the 3D view shows it: none while the Projection row's eye hides the projection gizmos + pub(crate) fn shown(app: &TextureCraftApp, rect: Rect) -> Option { + RoundGizmo::of(app, rect).filter(|_| app.session.doc.project.display.projection_gizmos) + } + + /// The projector of the selected tri-planar, spherical or cylindrical fill + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + let target = MoveOnModel::selected(app)?; + let (shape, offset, projector, offset_per_local) = match target.projection(app)? { + Projection::Triplanar { scale, offset, projector, .. } => (Shape::Box, offset, projector, scale), + Projection::Spherical { offset, projector, .. } => (Shape::Sphere, offset, projector, 1.0), + Projection::Cylindrical { axis, offset, projector, .. } => (Shape::Cylinder(cylinder_axis_index(axis)), offset, projector, 1.0), + _ => return None, + }; + + let (lower, upper) = app.session.mesh.bounds(); + let (mesh_center, radius) = mesh_frame((lower, upper)); + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(&projector); + let offset_per_local = nonzero_stretch(offset_per_local); + let local = -Vec3::from(offset) / offset_per_local; + let mut gizmo = RoundGizmo { + target, + mesh_center, + radius, + turn, + stretch, + local, + offset_per_local, + center: Pos2::ZERO, + arrows: [None; 3], + rings: Default::default(), + outline: Vec::new(), + sizes: Vec::new(), + steps: [None; 3], + }; + let origin = gizmo.world(local); + if !origin.is_finite() { + return None; + } + + gizmo.center = project(app, rect, origin)?; + gizmo.move_and_turn_handles(app, rect, origin)?; + + // The shape, sized round the mesh in the projector's units; a size handle past the view's edge waits at the edge, where it can be grabbed + let at = |point: Vec3| project(app, rect, mesh_center + turn * (stretch * point) * radius); + let view = rect.shrink(SIZE_ARROW); + let half = (upper - lower) * 0.5 / radius; + let forward = app.session.camera.forward(); + + // The view direction in the projector's units: what faces the camera there + let facing = (turn.transpose() * forward / stretch).try_normalize().unwrap_or(Vec3::Z); + match shape { + Shape::Box => gizmo.box_handles(at, half * BOX_REACH, forward, view), + Shape::Sphere => gizmo.sphere_handles(at, half.max_element() * SPHERE_REACH, facing, view), + Shape::Cylinder(axis) => gizmo.cylinder_handles(at, axis, half, facing, view), + } + Some(gizmo) + } + + /// The arrows along the projector's turned directions and the rings that turn round them, each ring seen too near edge on left out (empty: neither drawn nor grabbed) + fn move_and_turn_handles(&mut self, app: &TextureCraftApp, rect: Rect, origin: Vec3) -> Option<()> { + let center = self.center; + let directions = self.directions(); + let reach = self.radius * STEP_PROBE_RADII; + self.steps = directions.map(|direction| Some((project(app, rect, origin + direction * reach)? - center) / reach)); + self.arrows = self.steps.map(|step| step.filter(|step| step.length() * reach > MIN_SCREEN_SPAN).map(|step| center + step.normalized() * ARROW)); + + let right = app.session.camera.forward().cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let pixels = (project(app, rect, origin + right * reach)? - center).length() / reach; + let ring = TURN_RING / pixels.max(f32::MIN_POSITIVE); + self.rings = directions.map(|direction| { + if !ring_open(app, rect, center, direction) { + return Vec::new(); + } + + let (tangent, bitangent) = direction.any_orthonormal_pair(); + circle(|unit| project(app, rect, origin + (tangent * unit.x + bitangent * unit.y) * ring)) + }); + Some(()) + } + + /// A box of half size `size`: its edges, a dot on the corner up and right on screen that scales it evenly, and a double arrow on each face turned towards the camera that stretches it along that direction + fn box_handles(&mut self, at: impl Fn(Vec3) -> Option, size: Vec3, forward: Vec3, view: Rect) { + let local = self.local; + let corner = |index: usize| local + size * box_corner(index); + for (first_corner, second_corner) in box_edges() { + if let (Some(from), Some(to)) = (at(corner(first_corner)), at(corner(second_corner))) { + self.outline.push(vec![from, to]); + } + } + + let corners = (0..BOX_CORNERS).filter_map(|index| at(corner(index))); + if let Some(top_right) = corners.max_by(|first, second| (first.x - first.y).total_cmp(&(second.x - second.y))) { + self.sizes.push(SizeHandle { at: kept_in(view, top_right), axes: [true; 3], along: None }); + } + for (axis, direction) in self.directions().iter().enumerate() { + // The face toward the camera, on the other side in the projector's units when a mirrored axis flips it + let facing_side = if direction.dot(forward) > 0.0 { -1.0 } else { 1.0 }; + let toward = facing_side * self.stretch[axis].signum(); + let Some(face) = at(local + Vec3::AXES[axis] * size * toward) else { continue }; + let out = face - self.center; + if out.length() >= FACE_CLEARANCE { + self.sizes.push(SizeHandle { at: kept_in(view, face), axes: only_axis(axis), along: Some(out.normalized()) }); + } + } + } + + /// A sphere of `radius`: its silhouette across `facing` and its equator, and one dot on its right side (a sphere only scales evenly) + fn sphere_handles(&mut self, at: impl Fn(Vec3) -> Option, radius: f32, facing: Vec3, view: Rect) { + let local = self.local; + let (tangent, bitangent) = facing.any_orthonormal_pair(); + let silhouette = circle(|unit| at(local + (tangent * unit.x + bitangent * unit.y) * radius)); + if let Some(side) = silhouette.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)) { + self.sizes.push(SizeHandle { at: kept_in(view, side), axes: [true; 3], along: None }); + } + self.outline.push(silhouette); + self.outline.push(circle(|unit| at(local + Vec3::new(unit.x, 0.0, unit.y) * radius))); + } + + /// A cylinder round `axis` over a mesh of half sizes `half`: its caps and side lines, a double arrow on the top rim that stretches its height (seen end on, a dot) and a dot on its right side that scales it across (seen end on, on the rim's right) + fn cylinder_handles(&mut self, at: impl Fn(Vec3) -> Option, axis: usize, half: Vec3, facing: Vec3, view: Rect) { + let local = self.local; + let along = Vec3::AXES[axis]; + let (tangent, bitangent) = (Vec3::AXES[(axis + 1) % 3], Vec3::AXES[(axis + 2) % 3]); + let radius = (half * (Vec3::ONE - along)).max_element() * CYLINDER_REACH; + let half_height = half[axis] * CYLINDER_HEIGHT; + let cap = |height: f32| circle(|unit| at(local + along * height + (tangent * unit.x + bitangent * unit.y) * radius)); + let top = cap(half_height); + let along_axis = match (at(local + along * half_height), at(local - along * half_height)) { + (Some(top), Some(bottom)) => Some(top - bottom).filter(|span| span.length() > MIN_SCREEN_SPAN).map(egui::Vec2::normalized), + _ => None, + }; + if let Some(rim) = top.iter().copied().min_by(|first, second| first.y.total_cmp(&second.y)) { + self.sizes.push(SizeHandle { at: kept_in(view, rim), axes: only_axis(axis), along: along_axis }); + } + let right_of_rim = top.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)); + self.outline.extend([top, cap(-half_height)]); + + // The two side lines, where the round side turns away from the camera; seen end on there are none, and the dot sits on the rim's right + let side = along.cross(facing - along * facing.dot(along)).try_normalize(); + let mut sides = Vec::new(); + for edge in side.into_iter().flat_map(|side| [side, -side]) { + if let (Some(top), Some(bottom)) = (at(local + edge * radius + along * half_height), at(local + edge * radius - along * half_height)) { + self.outline.push(vec![top, bottom]); + sides.push(top.lerp(bottom, 0.5)); + } + } + let across_at = match side { + Some(_) => sides.into_iter().max_by(|first, second| first.x.total_cmp(&second.x)), + None => right_of_rim, + }; + if let Some(side) = across_at { + let mut across = [true; 3]; + across[axis] = false; + self.sizes.push(SizeHandle { at: kept_in(view, side), axes: across, along: None }); + } + } + + /// A point in the projector's units, in the world + fn world(&self, local: Vec3) -> Vec3 { + self.mesh_center + self.turn * (self.stretch * local) * self.radius + } + + /// The projector's turned X, Y and Z directions in the world + fn directions(&self) -> [Vec3; 3] { + Vec3::AXES.map(|axis| self.turn * axis) + } + + /// The `layer.fill.projection` params that slide the projector across the view from `from` to `to`, as its centre square does + pub(crate) fn slid(&self, app: &TextureCraftApp, rect: Rect, from: Pos2, to: Pos2) -> Option { + self.params(app, rect, RoundGrab::Slide, from, to) + } + + /// The `layer.fill.projection` params a drag of `grab` from `from` to `to` sets; only a size handle sets the scale, so a mirrored axis keeps its sign through a slide or turn + fn params(&self, app: &TextureCraftApp, rect: Rect, grab: RoundGrab, from: Pos2, to: Pos2) -> Option { + let origin = self.world(self.local); + let (turn, stretch, center) = match grab { + RoundGrab::Slide => { + let forward = app.session.camera.forward(); + let moved = on_view_plane(app, rect, origin, forward, to)? - on_view_plane(app, rect, origin, forward, from)?; + (self.turn, self.stretch, origin + moved) + } + RoundGrab::Axis(axis) => { + let step = (*self.steps.get(axis)?)?; + let distance = (to - from).dot(step) / step.length_sq().max(f32::MIN_POSITIVE); + (self.turn, self.stretch, origin + self.directions()[axis] * distance) + } + RoundGrab::Ring(axis) => { + let angle = (to - self.center).angle() - (from - self.center).angle(); + + // Seen from the side its direction points to, a turn runs the other way round on screen + let facing = self.directions()[axis].dot(app.session.camera.forward()); + let angle = if facing < 0.0 { -angle } else { angle }; + let turn = self.turn * Mat3::from_axis_angle(Vec3::AXES[axis], angle); + (turn, self.stretch, origin) + } + RoundGrab::Size(axes) => { + // How far the pointer went along the line from the centre through where the handle was grabbed (past the centre, none: a drag never flips it); the command keeps each axis's size in its limits on its own side, so does the offset worked out here + let reach = from - self.center; + let factor = ((to - self.center).dot(reach) / reach.length().max(MIN_HANDLE_REACH).powi(2)).max(0.0); + let stretch = Vec3::from(axes.map(|on| if on { factor } else { 1.0 })) * self.stretch; + (self.turn, stretch.map(signed_scale), origin) + } + }; + + // The centre stays where it was put: the offset follows the turn and scale + let local = turn.transpose() * ((center - self.mesh_center) / self.radius) / stretch; + let offset = -local * self.offset_per_local; + let (z, y, x) = Quat::from_mat3(&turn).to_euler(EulerRot::ZYX); + let rotation = [x, y, z].map(f32::to_degrees); + let values = [offset.to_array(), rotation, stretch.to_array()]; + if !values.iter().flatten().all(|value| value.is_finite()) { + return None; + } + + let mut params = self.target.target(); + params["offset"] = json!(offset.to_array()); + params["projectorRotation"] = json!(rotation); + if matches!(grab, RoundGrab::Size(_)) { + params["projectorScale"] = json!(stretch.to_array()); + } + Some(params) + } +} + +impl Gizmo for RoundGizmo { + type Grab = RoundGrab; + + fn drag_id() -> egui::Id { + egui::Id::unique("tc_round_drag") + } + + /// The handle under screen point `p`: the nearest one within reach (where rings cross, the nearest ring) + fn grab(&self, at: Pos2) -> Option { + let mut handles = vec![(RoundGrab::Slide, center_distance(self.center, at))]; + handles.extend((0..3).filter_map(|axis| Some((RoundGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?))))); + handles.extend(self.sizes.iter().map(|size| (RoundGrab::Size(size.axes), size.distance(at)))); + let distance = |ring: &Vec| ring.windows(2).map(|pair| distance_to_segment(at, pair[0], pair[1])).fold(f32::INFINITY, f32::min); + handles.extend((0..3).map(|axis| (RoundGrab::Ring(axis), distance(&self.rings[axis])))); + nearest(handles) + } + + fn same_projection(&self, other: &RoundGizmo) -> bool { + self.target == other.target + } + + fn edit(&self, app: &TextureCraftApp, rect: Rect, grab: RoundGrab, from: Pos2, to: Pos2) -> Option<(&'static str, Value)> { + Some(("layer.fill.projection", self.params(app, rect, grab, from, to)?)) + } + + /// A size handle's resize cursor runs along its arrow + fn cursor(&self, grab: RoundGrab, dragging: bool) -> egui::CursorIcon { + match grab { + RoundGrab::Slide if dragging => egui::CursorIcon::Grabbing, + RoundGrab::Slide => egui::CursorIcon::Grab, + RoundGrab::Axis(_) | RoundGrab::Ring(_) => egui::CursorIcon::Move, + RoundGrab::Size(axes) => self.sizes.iter().find(|size| size.axes == axes).map_or(egui::CursorIcon::ResizeNeSw, SizeHandle::cursor), + } + } +} + +/// A size handle that stretches one way: a double arrow through `at` along `along`, `fill` over a dark halo like the axis arrows +fn size_arrow(painter: &egui::Painter, at: Pos2, along: egui::Vec2, fill: Color32) { + let side = along.rot90() * SIZE_ARROW_HEAD_HALF_WIDTH; + let shaft = [at - along * (SIZE_ARROW - SIZE_ARROW_HEAD), at + along * (SIZE_ARROW - SIZE_ARROW_HEAD)]; + painter.line_segment(shaft, Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO)); + painter.line_segment(shaft, Stroke::new(SHAFT_WIDTH, fill)); + for direction in [along, -along] { + let base = at + direction * (SIZE_ARROW - SIZE_ARROW_HEAD); + painter.add(egui::Shape::convex_polygon(vec![at + direction * SIZE_ARROW, base + side, base - side], fill, HANDLE_EDGE)); + } +} + +/// Corner `index` of a box from -1 to 1: the index's three low bits pick its low (0) or high (1) side along X, Y and Z +pub(crate) fn box_corner(index: usize) -> Vec3 { + let side = |bit: usize| if index & bit == 0 { -1.0 } else { 1.0 }; + Vec3::new(side(BOX_AXIS_BITS[0]), side(BOX_AXIS_BITS[1]), side(BOX_AXIS_BITS[2])) +} + +/// A box's twelve edges as pairs of corner indices, each once: from a corner on an axis's low side to the corner across that axis +pub(crate) fn box_edges() -> impl Iterator { + (0..BOX_CORNERS).flat_map(|corner| BOX_AXIS_BITS.into_iter().filter(move |bit| corner & bit == 0).map(move |bit| (corner, corner | bit))) +} + +/// Which projector directions a handle along `axis` alone works on +fn only_axis(axis: usize) -> [bool; 3] { + let mut axes = [false; 3]; + axes[axis] = true; + axes +} + +/// `point` kept inside `view`, where a handle past its edge can still be grabbed +fn kept_in(view: Rect, point: Pos2) -> Pos2 { + point.clamp(view.min, view.max) +} + +/// A closed circle of screen points from `at` (given the unit circle's points); empty when a point is off screen +fn circle(at: impl Fn(Vec2) -> Option) -> Vec { + (0..=CIRCLE_POINTS) + .map(|index| { + let angle = index as f32 / CIRCLE_POINTS as f32 * std::f32::consts::TAU; + at(Vec2::new(angle.cos(), angle.sin())) + }) + .collect::>>() + .unwrap_or_default() +} + +/// Where screen point `p` meets the plane facing the camera through `origin` +fn on_view_plane(app: &TextureCraftApp, rect: Rect, origin: Vec3, forward: Vec3, p: Pos2) -> Option { + let ray = view_ray(app, rect, p); + let facing = ray.dir.dot(forward); + if facing.abs() < EDGE_ON_FACING { + return None; + } + + let hit = ray.origin + ray.dir * ((origin - ray.origin).dot(forward) / facing); + hit.is_finite().then_some(hit) +} + +/// The projector over the 3D view: dashed shape, rings, arrows, centre square and dots, the handle under the pointer lit +pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, gizmo: &RoundGizmo) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let active = dragging::(ui.ctx()).map(|drag| drag.grab); + + // A held Move on model button lights none + let hovered = ui.ctx().pointer_hover_pos().filter(|hover| rect.contains(*hover) && app.moving_on_model.is_none()).and_then(|hover| gizmo.grab(hover)); + let lit = |grab: RoundGrab| active == Some(grab) || (active.is_none() && hovered == Some(grab)); + let fill = |grab: RoundGrab| if lit(grab) { tokens.viewport_accent } else { Color32::WHITE }; + let axis_color = |axis: usize, grab: RoundGrab| if lit(grab) { tokens.viewport_accent } else { AXIS_COLORS[axis] }; + for line in &gizmo.outline { + dashed_outline(&painter, line); + } + for (axis, ring) in gizmo.rings.iter().enumerate() { + painter.add(egui::Shape::line(ring.clone(), Stroke::new(SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH, SHAFT_HALO))); + painter.add(egui::Shape::line(ring.clone(), Stroke::new(SHAFT_WIDTH, axis_color(axis, RoundGrab::Ring(axis))))); + } + for size in &gizmo.sizes { + let color = fill(RoundGrab::Size(size.axes)); + match size.along { + Some(along) => size_arrow(&painter, size.at, along, color), + None => handle_dot(&painter, size.at, SIZE_DOT, color), + } + } + move_handles(&painter, gizmo.center, gizmo.arrows, |axis| axis_color(axis, RoundGrab::Axis(axis)), fill(RoundGrab::Slide)); +} + +#[cfg(test)] +pub(crate) mod tests { + use egui::{Modifiers, PointerButton, vec2}; + use texturecraft_engine::core::{Fill, LayerId, LayerKind, Projection, Projector}; + + use super::*; + + fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> RoundGizmo { + RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() + } + + fn projector_and_offset(projection: &Projection) -> (Projector, [f32; 3]) { + match projection { + Projection::Triplanar { projector, offset, .. } + | Projection::Spherical { projector, offset, .. } + | Projection::Cylindrical { projector, offset, .. } => (*projector, *offset), + other => panic!("a round projection: {other:?}"), + } + } + + #[test] + fn round_projections_show_their_projector_while_their_fill_is_selected() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["triplanar", "spherical", "cylindrical"] { + let (mut harness, _) = fill_app(kind); + harness.run_steps(2); + let shown = gizmo(&harness); + assert!(shown.arrows.iter().all(Option::is_some) && shown.rings.iter().all(|ring| ring.len() > 8), "{kind}: arrows and rings {shown:?}"); + assert!(!shown.outline.is_empty(), "{kind}: its shape is drawn"); + + // A box's corner and a double arrow per face (the ball is seen from above and aside, no face head on); a sphere's one dot; a cylinder's top rim and side + let size_handles = match kind { + "triplanar" => 4, + "spherical" => 1, + _ => 2, + }; + assert_eq!(shown.sizes.len(), size_handles, "{kind}: size handles {:?}", shown.sizes); + } + let (harness, _) = fill_app("planar"); + assert!(RoundGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "planar projections show their frame instead"); + } + + #[test] + fn a_cylinder_axis_past_z_shows_round_y_as_the_compositor_wraps_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "cylindrical", "axis": 1})); + let round_y = gizmo(&harness).outline; + + // A hand-edited project can store an axis past Z: no command writes one + let stored = &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind; + let LayerKind::Fill(Fill { projection: Projection::Cylindrical { axis, .. }, .. }) = stored else { panic!("a cylindrical fill") }; + *axis = 3; + assert_eq!(gizmo(&harness).outline, round_y); + } + + #[test] + fn the_arrows_move_the_rings_turn_and_the_dots_scale_the_projector_one_step_per_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + + let start = gizmo(&harness); + let tip = start.arrows[0].unwrap(); + drag(&mut harness, tip, tip + (tip - start.center).normalized() * 30.0, Modifiers::NONE); + let (projector, offset) = projector_and_offset(&projection(&harness, layer)); + assert!(offset[0] < -0.05 && offset[1].abs() < 1e-3 && offset[2].abs() < 1e-3, "the X arrow moves the centre along X: {offset:?}"); + assert_eq!(projector.rotation, [0.0; 3]); + let moved = gizmo(&harness); + assert!(moved.center.x > start.center.x + 20.0, "the centre follows: {moved:?}"); + + // The Z ring (seen face on) turns it round Z; the centre stays where it is + let clear = |p: &&Pos2| moved.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); + let on_ring = *moved.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + assert_eq!(moved.grab(on_ring), Some(RoundGrab::Ring(2))); + drag(&mut harness, on_ring, moved.center + (on_ring - moved.center).rot90(), Modifiers::NONE); + let (turned, _) = projector_and_offset(&projection(&harness, layer)); + assert!(turned.rotation[2].abs() > 30.0 && turned.rotation[0].abs() < 1e-2, "{:?}", turned.rotation); + assert!(gizmo(&harness).center.distance(moved.center) < 1.0, "turning keeps the centre"); + + let scaling = gizmo(&harness); + let dot = scaling.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + let center = scaling.center; + assert_eq!(gizmo(&harness).grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, center + (dot - center) * 1.5, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.5).abs() < 0.05), "the side dot scales it evenly: {:?}", scaled.scale); + assert!(gizmo(&harness).center.distance(center) < 1.0, "scaling keeps the centre"); + assert_eq!(harness.state().session.history_labels().len(), steps + 3, "one undo step per drag"); + } + + #[test] + fn a_cylinders_top_dot_stretches_its_height_and_a_tri_planar_box_moves_by_its_texture_offset() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("cylindrical"); + let cylinder = gizmo(&harness); + let height = cylinder.sizes.iter().find(|size| size.axes == [false, true, false]).expect("the height handle"); + let SizeHandle { at: top, axes, along } = *height; + assert_eq!(axes, [false, true, false], "the top handle works along the axis"); + let along = along.expect("the height handle is a double arrow"); + assert!(along.y.abs() > 0.99, "drawn upright, along the upright axis: {along:?}"); + assert_eq!(cylinder.cursor(RoundGrab::Size(axes), false), egui::CursorIcon::ResizeVertical); + drag(&mut harness, top, cylinder.center + (top - cylinder.center) * 0.5, Modifiers::NONE); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!(projector.scale[1] < 0.7 && projector.scale[0] == 1.0 && projector.scale[2] == 1.0, "{:?}", projector.scale); + + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "scale": 4})).unwrap(); + harness.run_steps(2); + let box_gizmo = gizmo(&harness); + drag(&mut harness, box_gizmo.center, box_gizmo.center + vec2(0.0, -30.0), Modifiers::NONE); + let (_, offset) = projector_and_offset(&projection(&harness, layer)); + assert!(offset[1] < -0.1 && offset[0].abs() < 0.05, "sliding up shifts the texture by the tiling: {offset:?}"); + assert!(gizmo(&harness).center.distance(box_gizmo.center + vec2(0.0, -30.0)) < 1.5, "the centre sits under the pointer"); + } + + /// Every drag on the projector shows in the panel the same frame: its Offset, Rotation and Scale fields hold the projector's values and the preview square re-renders, every frame of the drag; one undo step per drag + #[test] + fn the_panel_and_its_preview_follow_every_frame_of_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["spherical", "cylindrical"] { + let (mut harness, layer) = fill_app(kind); + let steps = harness.state().session.history_labels().len(); + let read = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + let (projector, offset) = projector_and_offset(&projection(harness, layer)); + let (row_offset, row_rotation, row_scale) = (panel_xyz(harness, "Offset"), panel_xyz(harness, "Rotation"), panel_xyz(harness, "Scale")); + for (row, field, value) in + [("Offset", row_offset, offset), ("Rotation", row_rotation, projector.rotation), ("Scale", row_scale, projector.scale)] + { + for axis in 0..3 { + assert!((field[axis] - value[axis]).abs() < 1e-3, "{kind}: the panel's {row} shows the projector's {value:?}, not {field:?}"); + } + } + }; + + // A sphere's one dot scales it evenly, a cylinder's height arrow stretches it along its axis + let start = gizmo(&harness); + let axes = if kind == "spherical" { [true; 3] } else { [false, true, false] }; + let dot = start.sizes.iter().find(|size| size.axes == axes).unwrap_or_else(|| panic!("{kind}: its size handle {axes:?}")).at; + drag_frames(&mut harness, layer, dot, start.center + (dot - start.center) * 1.5, Modifiers::NONE, true, read); + let tip = gizmo(&harness).arrows[0].unwrap(); + let center = gizmo(&harness).center; + drag_frames(&mut harness, layer, tip, tip + (tip - center).normalized() * 30.0, Modifiers::NONE, true, read); + let turned = gizmo(&harness); + let clear = |p: &&Pos2| turned.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); + let on_ring = *turned.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + drag_frames(&mut harness, layer, on_ring, turned.center + (on_ring - turned.center).rot90(), Modifiers::NONE, true, read); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!( + projector.scale.iter().copied().fold(0.0, f32::max) > 1.3 && projector.rotation[2].abs() > 30.0, + "{kind}: resized and turned: {projector:?}" + ); + assert_eq!(harness.state().session.history_labels().len(), steps + 3, "{kind}: one undo step per drag"); + } + } + + /// Whether a projector drag is under way + fn round_dragging(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> bool { + dragging::(&harness.ctx).is_some() + } + + /// Losing the focus mid-drag (Alt+Tab) ends a projector drag as a release does: one undo step, and moves after it (egui still has the button down) leave the projector alone + #[test] + fn losing_the_window_focus_ends_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(round_dragging(&harness), "the centre square is held"); + + harness.event(egui::Event::WindowFocused(false)); + harness.run_steps(1); + let left = projection(&harness, layer); + assert!(!round_dragging(&harness), "the focus loss ends the drag"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "as one undo step"); + + for step in 1..=3 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), left, "moves after it leave the projector where it was"); + } + + /// Alt pressed mid-drag hands the pointer to the camera and ends the projector drag where it is: let go of Alt with the button still down, the drag does not resume; one undo step + #[test] + fn alt_mid_drag_ends_a_projector_drag() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let steps = harness.state().session.history_labels().len(); + let center = gizmo(&harness).center; + let to = center + vec2(40.0, 0.0); + press_and_move(&mut harness, center, to, Modifiers::NONE); + let slid = projection(&harness, layer); + let camera = harness.state().session.camera; + + harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); + harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); + assert!(!round_dragging(&harness), "and ends the projector drag"); + + for step in 2..=4 { + harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); + harness.run_steps(1); + } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the projector stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + } + + /// Seen edge on a ring is a line, whose screen-angle turn would jump half a turn across the centre: from straight in front (no yaw) the X ring is neither drawn nor grabbed while the Y and Z rings stay; turned aside, it opens and shows again + #[test] + fn a_ring_seen_edge_on_is_neither_drawn_nor_grabbed() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("spherical"); + harness.state_mut().session.camera.yaw = 0.0; + harness.run_steps(2); + + let front = gizmo(&harness); + assert!(front.rings[0].is_empty(), "the X ring seen edge on is left out: {:?}", front.rings[0]); + assert!(front.rings[1..].iter().all(|ring| !ring.is_empty()), "the Y and Z rings show"); + let on_the_line = front.center + vec2(0.0, 40.0); + assert_ne!(front.grab(on_the_line), Some(RoundGrab::Ring(0)), "a press where its line would be does not grab it"); + + harness.state_mut().session.camera.yaw = 0.5; + harness.run_steps(2); + assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows"); + } + + /// A point on the model clear of every handle of the shown gizmo + pub(crate) fn on_the_model_off_the_handles(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let round = RoundGizmo::of(app, rect); + let frame = crate::frame_gizmo::FrameGizmo::of(app, rect); + let clear = |p: Pos2| { + round.as_ref().is_none_or(|gizmo| gizmo.grab(p).is_none()) + && frame.as_ref().is_none_or(|gizmo| gizmo.grab(p).is_none()) + && app.session.pick(texturecraft_engine::geom::glam::Vec2::new(p.x - rect.left(), p.y - rect.top()), app.session.viewport).is_some() + }; + (1..12) + .flat_map(|ring| (0..16).map(move |step| rect.center() + egui::Vec2::angled(step as f32 / 16.0 * std::f32::consts::TAU) * (ring as f32 * 14.0))) + .find(|p| clear(*p) && clear(*p + vec2(30.0, 0.0))) + .expect("the model shows past the handles") + } + + /// A sphere has one size handle (it only scales evenly); a tri-planar box scales evenly from its corner and along one direction from a face's double arrow + #[test] + fn a_sphere_scales_from_one_dot_and_a_tri_planar_box_from_its_corner_and_faces() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let start = gizmo(&harness); + assert_eq!(start.sizes.len(), 1, "one dot: {:?}", start.sizes); + let dot = start.sizes[0].at; + assert_eq!(start.grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, start.center + (dot - start.center) * 1.4, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.4).abs() < 0.08), "it scales evenly: {:?}", scaled.scale); + + let (mut harness, layer) = fill_app("triplanar"); + let start = gizmo(&harness); + let corner = start.sizes.iter().find(|size| size.axes == [true; 3]).expect("a corner dot").at; + drag(&mut harness, corner, start.center + (corner - start.center) * 1.25, Modifiers::NONE); + let (scaled, _) = projector_and_offset(&projection(&harness, layer)); + assert!(scaled.scale.iter().all(|scale| (scale - 1.25).abs() < 0.05), "the corner scales it evenly: {:?}", scaled.scale); + assert!(gizmo(&harness).center.distance(start.center) < 1.0, "scaling keeps the centre"); + + let box_gizmo = gizmo(&harness); + let across = *box_gizmo.sizes.iter().find(|size| size.axes == [true, false, false]).expect("an X face arrow"); + assert!(across.along.is_some_and(|along| along.x.abs() > 0.95), "it points across: {across:?}"); + assert_eq!( + box_gizmo.grab(across.at + across.along.unwrap_or_default() * (SIZE_ARROW - 1.0)), + Some(RoundGrab::Size([true, false, false])), + "grabbed from its tip" + ); + drag(&mut harness, across.at, box_gizmo.center + (across.at - box_gizmo.center) * 0.5, Modifiers::NONE); + let (stretched, _) = projector_and_offset(&projection(&harness, layer)); + assert!((stretched.scale[0] - scaled.scale[0] * 0.5).abs() < 0.05, "the X face halves it across: {:?}", stretched.scale); + assert!( + (stretched.scale[1] - scaled.scale[1]).abs() < 1e-4 && (stretched.scale[2] - scaled.scale[2]).abs() < 1e-4, + "and only across: {:?}", + stretched.scale + ); + } + + /// A projector a project file mirrors along X (a negative scale, as the projection reads it) reads mirrored in the gizmo and stays mirrored through a slide, a move along an arrow, a turn and a resize + #[test] + fn a_mirrored_projector_keeps_its_mirror_through_every_handle() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("spherical"); + let mirrored = [-1.0, 1.0, 1.0]; + match &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind { + texturecraft_engine::core::LayerKind::Fill(fill) => match &mut fill.projection { + Projection::Spherical { projector, .. } => projector.scale = mirrored, + other => panic!("a spherical projection: {other:?}"), + }, + other => panic!("a fill layer: {other:?}"), + } + harness.run_steps(2); + + let start = gizmo(&harness); + assert_eq!(start.stretch, Vec3::from(mirrored), "the gizmo reads the mirror as the projection does"); + drag(&mut harness, start.center, start.center + vec2(30.0, -20.0), Modifiers::NONE); + let (slid, offset) = projector_and_offset(&projection(&harness, layer)); + assert_eq!(slid.scale, mirrored, "a slide keeps the mirror"); + assert!(offset.iter().any(|axis| axis.abs() > 0.05), "and slides it: {offset:?}"); + + let tip = gizmo(&harness).arrows[1].unwrap(); + let center = gizmo(&harness).center; + drag(&mut harness, tip, tip + (tip - center).normalized() * 20.0, Modifiers::NONE); + assert_eq!(projector_and_offset(&projection(&harness, layer)).0.scale, mirrored, "so does a move along an arrow"); + + let before_turn = projector_and_offset(&projection(&harness, layer)).0; + let ring = gizmo(&harness).rings[2].clone(); + drag(&mut harness, ring[CIRCLE_POINTS / 8], ring[CIRCLE_POINTS / 8 + 3], Modifiers::NONE); + let turned = projector_and_offset(&projection(&harness, layer)).0; + assert_ne!(turned.rotation, before_turn.rotation, "the ring turns it"); + assert_eq!(turned.scale, mirrored, "and keeps the mirror"); + + let resized = gizmo(&harness); + let dot = resized.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; + drag(&mut harness, dot, resized.center + (dot - resized.center) * 1.5, Modifiers::NONE); + let scale = projector_and_offset(&projection(&harness, layer)).0.scale; + let expected = [-1.5, 1.5, 1.5]; + assert!(scale.iter().zip(expected).all(|(axis, wanted)| (axis - wanted).abs() < 1e-3), "a resize scales it evenly, still mirrored: {scale:?}"); + } + + /// A box mirrored along X (a negative scale from a project file) keeps its X double arrow on the face toward the camera, where the unmirrored box shows it + #[test] + fn a_mirrored_box_keeps_its_face_arrow_toward_the_camera() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let x_face_arrow = |harness: &egui_kittest::Harness<'_, TextureCraftApp>| { + gizmo(harness).sizes.iter().find(|size| size.axes == [true, false, false]).map(|size| size.at) + }; + let unmirrored = x_face_arrow(&harness).expect("an X face arrow"); + match &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind { + LayerKind::Fill(fill) => match &mut fill.projection { + Projection::Triplanar { projector, .. } => projector.scale = [-1.0, 1.0, 1.0], + other => panic!("a tri-planar projection: {other:?}"), + }, + other => panic!("a fill layer: {other:?}"), + } + harness.run_steps(2); + + let mirrored = x_face_arrow(&harness).expect("the mirrored box's X face arrow"); + assert!(mirrored.distance(unmirrored) < 0.5, "the arrow stays on the near face: {mirrored:?}, unmirrored {unmirrored:?}"); + } + + /// The pointer over a handle shows what it does only while the gizmo takes input: with Alt held the camera orbits, and the handle's cursor is not shown + #[test] + fn alt_over_a_handle_shows_no_handle_cursor() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = fill_app("triplanar"); + let center = gizmo(&harness).center; + harness.hover_at(center); + harness.run_steps(2); + assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "the centre square shows it slides"); + + harness.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + harness.event(egui::Event::PointerMoved(center + vec2(1.0, 0.0))); + harness.run_steps(2); + assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "with Alt held it does not"); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + } + + /// A tri-planar fill selected while the quick mask is edited with the Paint tool: brushes act and the projector shows + fn quick_mask_paint_app() -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("viewport.quickMask", json!({"enabled": true})).unwrap(); + harness.state_mut().run("viewport.quickMask.edit", json!({"editing": true})).unwrap(); + harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; + harness.run_steps(2); + assert!(gizmo(&harness).sizes.len() > 1, "the projector shows"); + (harness, layer) + } + + /// A Ctrl+drag that starts on a handle changes the brush only: the projector stays where it is + #[test] + fn a_ctrl_drag_on_a_handle_changes_the_brush_and_not_the_projection() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = quick_mask_paint_app(); + let before = projection(&harness, layer); + let flow = harness.state().session.tool.brush.flow; + let center = gizmo(&harness).center; + + harness.event(egui::Event::ModifiersChanged(Modifiers::COMMAND)); + drag(&mut harness, center, center + vec2(-40.0, 0.0), Modifiers::COMMAND); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + assert_ne!(harness.state().session.tool.brush.flow, flow, "the drag changes the brush"); + assert_eq!(projection(&harness, layer), before, "and leaves the projection"); + } + + /// A press on a handle's edge that drifts just off it before release (still a click) is the handle's: it paints no dab + #[test] + fn a_click_that_drifts_off_a_handle_paints_nothing() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = quick_mask_paint_app(); + let shown = gizmo(&harness); + let rect = harness.state().viewport_rect; + let on_model = |p: Pos2| { + harness + .state() + .session + .pick(texturecraft_engine::geom::glam::Vec2::new(p.x - rect.left(), p.y - rect.top()), harness.state().session.viewport) + .is_some() + }; + let drift = 2.0; + + // The centre square's last point along some direction whose point a drift further is off every handle and on the model + let (edge, off) = (0..16) + .filter_map(|step| { + let toward = egui::Vec2::angled(step as f32 / 16.0 * std::f32::consts::TAU); + let edge = (0..200).map(|half| shown.center + toward * (half as f32 * 0.5)).take_while(|p| shown.grab(*p).is_some()).last()?; + let off = edge + toward * drift; + (shown.grab(off).is_none() && on_model(off)).then_some((edge, off)) + }) + .next() + .expect("a handle edge on the model"); + let click = |harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2| { + harness.hover_at(from); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerMoved(to)); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + }; + + let painted = harness.state().session.quick_mask.revision; + click(&mut harness, edge, off); + assert_eq!(harness.state().session.quick_mask.revision, painted, "a press that began on the handle paints no dab"); + + // The same click a little past the handle paints + click(&mut harness, off, off + (off - edge)); + assert_ne!(harness.state().session.quick_mask.revision, painted, "a press off the handle paints"); + } + + /// A cylinder seen straight down its axis keeps the dot that scales it across, on its rim's right + #[test] + fn a_cylinder_seen_end_on_keeps_its_across_dot() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app_with(json!({"projection": "cylindrical", "axis": 2})); + harness.state_mut().session.camera.yaw = 0.0; + harness.state_mut().session.camera.pitch = 0.0; + harness.run_steps(2); + + let end_on = gizmo(&harness); + let across = [true, true, false]; + let dot = end_on.sizes.iter().find(|size| size.axes == across).unwrap_or_else(|| panic!("the across dot: {:?}", end_on.sizes)).at; + assert_eq!(end_on.grab(dot), Some(RoundGrab::Size(across))); + drag(&mut harness, dot, end_on.center + (dot - end_on.center) * 1.5, Modifiers::NONE); + let (projector, _) = projector_and_offset(&projection(&harness, layer)); + assert!(projector.scale[0] > 1.2 && projector.scale[1] > 1.2 && projector.scale[2] == 1.0, "it scales across only: {:?}", projector.scale); + } +} diff --git a/crates/ui-egui/src/round_gizmo/round_grab.rs b/crates/ui-egui/src/round_gizmo/round_grab.rs new file mode 100644 index 00000000..321c7b20 --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/round_grab.rs @@ -0,0 +1,12 @@ +/// What a drag on the projector does +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum RoundGrab { + /// The centre square: slide it across the view + Slide, + /// Along the projector's X (0), Y (1) or Z (2) direction + Axis(usize), + /// Turn it round its X, Y or Z direction + Ring(usize), + /// A size dot: scale it along the directions marked + Size([bool; 3]), +} diff --git a/crates/ui-egui/src/round_gizmo/shape.rs b/crates/ui-egui/src/round_gizmo/shape.rs new file mode 100644 index 00000000..3cd4ebd8 --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/shape.rs @@ -0,0 +1,8 @@ +/// Which shape the projector shows +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Shape { + Box, + Sphere, + /// Round the axis 0, 1 or 2 + Cylinder(usize), +} diff --git a/crates/ui-egui/src/round_gizmo/size_handle.rs b/crates/ui-egui/src/round_gizmo/size_handle.rs new file mode 100644 index 00000000..f2f3c57f --- /dev/null +++ b/crates/ui-egui/src/round_gizmo/size_handle.rs @@ -0,0 +1,33 @@ +use egui::Pos2; + +use super::SIZE_ARROW; +use crate::frame_gizmo::distance_to_segment; + +/// A handle that resizes the projector +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SizeHandle { + pub at: Pos2, + /// The projector directions it scales + pub axes: [bool; 3], + /// A double arrow's direction on screen; None for a dot + pub along: Option, +} + +impl SizeHandle { + /// How far screen point `p` is from the handle (a double arrow: from anywhere along it) + pub(super) fn distance(&self, p: Pos2) -> f32 { + match self.along { + Some(along) => distance_to_segment(p, self.at - along * SIZE_ARROW, self.at + along * SIZE_ARROW), + None => self.at.distance(p), + } + } + + /// The resize cursor along its arrow, or a diagonal one for a dot + pub(super) fn cursor(&self) -> egui::CursorIcon { + match self.along { + Some(along) if along.y.abs() >= along.x.abs() => egui::CursorIcon::ResizeVertical, + Some(_) => egui::CursorIcon::ResizeHorizontal, + None => egui::CursorIcon::ResizeNeSw, + } + } +} From d31604cc97b9e0d191f3b1a167fccdefbcb8a057 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 015/153] Properties: the panel keeps its scroll place per layer, titles an effect by its type, and an empty panel shows its note --- crates/engine/src/session.rs | 2 +- crates/ui-egui/src/dock.rs | 57 ++++++++++++++----- crates/ui-egui/src/lib.rs | 5 ++ crates/ui-egui/src/widgets.rs | 16 ++++++ crates/ui-egui/tests/it/empty_start.rs | 13 ++++- crates/ui-egui/tests/it/layer_multi_select.rs | 11 ++++ crates/ui-egui/tests/it/layers_panel.rs | 10 +++- crates/ui-egui/tests/it/main.rs | 49 ++++++++++++++++ crates/ui-egui/tests/it/tool_availability.rs | 2 +- 9 files changed, 145 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 10dc72df..b493a8b6 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -328,7 +328,7 @@ impl Default for ToolState { } /// What is selected in the layer stack. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] pub enum StackTarget { #[default] Content, diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d831213d..6256973b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1798,7 +1798,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { // Polygon fill keeps its own properties wherever it can fill _ if tool == Tool::PolygonFill && tool_usable => tr(tool.label()).to_string(), - (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), + // The effect's type, not its own name (every filter reads "Filter") + (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| tr(effect_type_label(&found.kind)).to_string()).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(), @@ -1809,44 +1810,70 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { format!("{} - {what}", tr("Properties")) } +/// The name of effect type `kind` in the Properties title +fn effect_type_label(kind: &EffectKind) -> &'static str { + match kind { + EffectKind::Filter(_) => n_("Filter"), + other => other.name(), + } +} + pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); - egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); + egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); +} + +/// What the docked Properties list keeps its own scroll place for: the selected layer and the part of it edited, none for the tool +fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> { + // A short panel in between would clamp a shared place back to the top; a greyed tool shows the layer's own sheet + if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { + return None; + } + + app.session.selected_layer().map(|layer| (layer, app.session.target)) +} + +/// Room around the Properties rows not yet laid out by the property sheet: the sheet's side padding, so both start under the panel's name +const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::PAD as i8, 4); + +/// Lays out `body` with the other panels' margin +fn legacy_body(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { + egui::Frame::new().inner_margin(LEGACY_BODY_MARGIN).show(ui, body); } /// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder, instance or mask, else the tool (or a hint to select a layer when it can't act) pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); if !app.session.project_open { - ui.label(RichText::new(tr("No properties found")).color(tokens.text_dim)); + crate::widgets::empty_note(ui, tr("No properties found")); return; } let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); let tool = app.session.tool.tool; let tool_usable = app.session.tool_usable(tool); + let tokens = Tokens::get(ui.ctx()); match (&selected, app.session.target) { // Polygon fill shows its own settings and says what it fills into, wherever it can fill - _ if tool == Tool::PolygonFill && tool_usable => 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() => { + _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), + (Some(layer), StackTarget::Effect(effect)) => legacy_body(ui, |ui| effect_properties(app, ui, layer, effect)), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => legacy_body(ui, |ui| fill_properties(app, ui, layer)), + (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { 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(layer), StackTarget::Content) if layer.instance_source().is_some() => instance_properties(app, ui, layer), - (Some(layer), StackTarget::Mask) => { + }), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => legacy_body(ui, |ui| instance_properties(app, ui, layer)), + (Some(layer), StackTarget::Mask) => legacy_body(ui, |ui| { height_mask_section(app, ui, layer); if tool_usable { ui.separator(); tool_properties(app, ui); } - } - (None, _) if !tool_usable => { + }), + (None, _) if !tool_usable => legacy_body(ui, |ui| { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); - } - _ => tool_properties(app, ui), + }), + _ => legacy_body(ui, |ui| tool_properties(app, ui)), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3df3eb31..90519b44 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -68,6 +68,7 @@ mod path_surface_cache; mod pattern_panel; mod pattern_target; pub mod pbr_import; +mod popup_drag; mod preview_image; mod preview_request; mod preview_worker; @@ -76,6 +77,7 @@ pub mod profile; mod project_config; pub mod project_form; pub mod properties_popup; +mod property_sheet; mod query_field; mod rail_popup; pub mod render_mode; @@ -1053,6 +1055,9 @@ impl eframe::App for TextureCraftApp { self.ui.mode = state::Mode::Painting; } + // Before any popup draws, so one a drag closes is gone from this frame + popup_drag::close_on_drag_outside(&ctx); + if !self.ui.hide_ui { titlebar::show(self, ui); banner(self, ui); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index fa5ecd4c..ef2455a1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -495,6 +495,22 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> painter.add(mesh); } +/// From a panel body's top to its empty note's lettering: the reference's gap under the header's name +const EMPTY_NOTE_TOP: f32 = 9.0; + +/// The line an empty panel shows instead of its contents ("No properties found"): under the header at its name's left edge, greyed as the disabled toolbar icons are +pub(crate) fn empty_note(ui: &mut Ui, text: &str) { + let tokens = Tokens::get(ui.ctx()); + ui.add_enabled_ui(false, |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let galley = ui.painter().layout_no_wrap(text.to_owned(), font, tokens.text); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), EMPTY_NOTE_TOP + galley.size().y), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, false, text)); + let at = egui::pos2(rect.left() + crate::docking::HEADER_TITLE_LEFT, rect.top() + EMPTY_NOTE_TOP); + ui.painter().galley(at, galley, tokens.text); + }); +} + /// Panel title row with optional trailing content. pub fn panel_header(ui: &mut Ui, title: &str, trailing: impl FnOnce(&mut Ui)) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 54f4e925..3ca2f721 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -105,8 +105,8 @@ fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { assert!(!has_camera_picker(&empty), "no camera picker"); - // The picker shows "Material" right of the tool shelf and the Assets panel: one per view in the split layout - let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && *x > 400.0).count(); + // The picker shows "Material" right of the tool shelf and the Assets panel and left of the right column: one per view in the split layout + let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && (300.0..1200.0).contains(x)).count(); assert_eq!(pickers, 2, "each of the two views keeps its view picker"); @@ -393,3 +393,12 @@ fn close_releases_the_layer_thumbnail_snapshot() { ); } } + +#[test] +fn the_empty_properties_note_starts_at_its_header_names_left_edge() { + let harness = empty(); + let texts = painted(&harness); + let left_of = |wanted: &str| texts.iter().find(|(text, _)| text == wanted).map(|(_, left)| *left).unwrap_or_else(|| panic!("{wanted} is painted")); + + assert_eq!(left_of("No properties found"), left_of("PROPERTIES")); +} diff --git a/crates/ui-egui/tests/it/layer_multi_select.rs b/crates/ui-egui/tests/it/layer_multi_select.rs index 92201b7c..5dab5e1d 100644 --- a/crates/ui-egui/tests/it/layer_multi_select.rs +++ b/crates/ui-egui/tests/it/layer_multi_select.rs @@ -20,8 +20,18 @@ fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) { (h, rows) } +/// Frames for a scroll to bring a row into view (it animates) +const SCROLL_FRAMES: usize = 25; + +/// Scrolls the row `name` into view: six rows overflow the Layers panel +fn show_row(h: &mut Harness<'_, TextureCraftApp>, name: &str) { + h.get_by_label(name).scroll_to_me(); + h.run_steps(SCROLL_FRAMES); +} + /// Click the row `name` while `modifiers` are held (pressed before and released after the click). fn click(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: Modifiers) { + show_row(h, name); let at: Pos2 = h.get_by_label(name).rect().center(); h.event(Event::PointerMoved(at)); h.event(Event::ModifiersChanged(modifiers)); @@ -161,6 +171,7 @@ fn ctrl_a_leaves_text_fields_and_other_panels_alone() { /// Right-click the row `name` and choose the menu item whose label starts with `item`. fn row_menu(h: &mut Harness<'_, TextureCraftApp>, name: &str, item: &str) { + show_row(h, name); h.get_by_label(name).click_secondary(); h.run_steps(3); h.get_by(|node| node.label().is_some_and(|label| label.starts_with(item))).click(); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index ccbd9074..6b2b6a3e 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -107,9 +107,17 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { } let mut workspace = h.state().ui.dock.workspace().clone(); let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; - let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; + let Node::Split { size, second: column, .. } = second.as_mut() else { panic!("viewport and right column") }; *size = SplitSize::Ratio(0.99); + + // Layers tall enough for the whole nested stack: the default gives most of the column to Properties + let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets and the rest") }; + let Node::Split { size: layers_share, .. } = below_sets.as_mut() else { panic!("layers and properties") }; + *layers_share = SplitSize::Ratio(0.9); h.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + + // Properties holds its column at its minimum width: without it the column narrows as far as Layers allows + h.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); h.run_steps(4); let row = h.get_by_label("Effect A").rect(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 914bb830..2b938e89 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -52,11 +52,14 @@ mod nav_buttons; mod new_project_baked_maps; mod new_project_window; mod output_templates; +mod panel_header; mod path_in_view; mod path_list; mod pen_pressure; mod polygon_fill; +mod popup_press_close; mod project_config; +mod properties_min_width; mod properties_popup; mod rail; mod reference_order; @@ -93,3 +96,49 @@ mod stencil; mod symmetry; mod symmetry_2d; mod tile_generator_panel; + +/// eframe's in-memory storage, shared by the tests that save and restore the UI state +#[path = "../../src/ui_state_store/memory_storage.rs"] +mod memory_storage; + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Window of the Properties tests: tall enough that a whole sheet shows without scrolling +const PROPERTIES_WINDOW: egui::Vec2 = egui::vec2(1600.0, 1400.0); + +// Small texture and bake sizes keep the sample session fast; the panels don'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 key to reach the panels and its change to show +const SETTLE_FRAMES: usize = 3; + +/// Frames between the moves of a drag, and between a press and its release +const DRAG_STEP_FRAMES: usize = 2; + +/// Presses and releases the primary button at `at` without moving, as a pointer click does +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + harness.hover_at(at); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + + harness.run_steps(SETTLE_FRAMES); +} + +/// The close button nearest the right of a docked panel's `title` (its tab or header title), on the same row +fn panel_close_button(harness: &Harness<'_, TextureCraftApp>, title: egui::Rect) -> egui::Rect { + harness + .get_all_by_role(egui::Role::Button) + .filter(|button| button.accesskit_node().label().as_deref() == Some("Close Panel")) + .map(|button| button.rect()) + .filter(|close| close.min.x > title.max.x && title.y_range().contains(close.center().y)) + .min_by(|a, b| a.min.x.total_cmp(&b.min.x)) + .expect("a close button right of the title") +} diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index cc6d97ff..2d55e09f 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -68,7 +68,7 @@ fn a_fill_layer_greys_the_paint_tools_and_shows_its_own_properties() { assert!(shelf_button_disabled(&harness, "Polygon fill (4)")); assert!(!shelf_button_selected(&harness, "Polygon fill (4)"), "the equipped tool doesn't show as selected while greyed"); assert!(!shelf_button_disabled(&harness, "Geometry mask (8)")); - assert!(shows_text(&harness, "Properties - Fill"), "a fill layer shows its fill whatever the tool"); + assert!(shows_text(&harness, "PROPERTIES - FILL"), "a fill layer shows its fill whatever the tool"); assert!(!shows_text(&harness, "Size"), "a tool that can't act leaves the top bar"); } From e131e826b1b52b86f23e490c8622ddf159877c9f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:11 +0000 Subject: [PATCH 016/153] Fills: Symmetry, mirrored or radial copies of a 3D projection --- crates/compose/src/fill_copies.rs | 154 ++++++++++++++++++ crates/core/src/fill_symmetry.rs | 93 +++++++++++ crates/core/src/symmetry_kind.rs | 31 ++++ crates/ui-egui/src/fill_symmetry_panel.rs | 113 +++++++++++++ crates/ui-egui/src/symmetry/settings_popup.rs | 3 +- crates/ui-egui/src/symmetry/view_overlay.rs | 9 +- crates/ui-egui/tests/it/fill_symmetry_rows.rs | 111 +++++++++++++ 7 files changed, 504 insertions(+), 10 deletions(-) create mode 100644 crates/compose/src/fill_copies.rs create mode 100644 crates/core/src/fill_symmetry.rs create mode 100644 crates/core/src/symmetry_kind.rs create mode 100644 crates/ui-egui/src/fill_symmetry_panel.rs create mode 100644 crates/ui-egui/tests/it/fill_symmetry_rows.rs diff --git a/crates/compose/src/fill_copies.rs b/crates/compose/src/fill_copies.rs new file mode 100644 index 00000000..cd4fc02a --- /dev/null +++ b/crates/compose/src/fill_copies.rs @@ -0,0 +1,154 @@ +//! The copies a symmetric fill makes of its projection, as mirrors and turns of the surface point each copy samples + +use texturecraft_core::{FULL_TURN_DEGREES, FillSymmetry, SymmetryKind}; +use texturecraft_geom::glam::{Mat3, Vec3}; + +use crate::fill_copy::FillCopy; + +/// The copies of a fill's projection one texel shows, the original among them: the one whose half (mirror) or wedge (radial) holds the texel comes first, so it lies on top where copies overlap +pub struct FillCopies { + symmetry: FillSymmetry, + pivot: Vec3, + axis: usize, + step: f32, + first: u32, + count: u32, + next: u32, +} + +impl FillCopies { + /// The copies `symmetry` makes for a texel at world point `point`, on a mesh whose bounds have centre `center` and radius `radius` + pub fn new(symmetry: &FillSymmetry, point: Vec3, center: Vec3, radius: f32) -> FillCopies { + let reach = FillSymmetry::REACH; + let position = Vec3::from(symmetry.position.map(|coordinate| if coordinate.is_finite() { coordinate.clamp(-reach, reach) } else { 0.0 })); + let pivot = center + position * radius; + let axis = symmetry.axis_index(); + let count = symmetry.copies(); + let step = symmetry.step(); + + let from_pivot = point - pivot; + let first = match symmetry.kind { + // The original keeps the half on the axis's positive side + SymmetryKind::Mirror => u32::from(from_pivot[axis] < 0.0), + SymmetryKind::Radial => { + let turned = from_pivot[(axis + 2) % 3].atan2(from_pivot[(axis + 1) % 3]).to_degrees().rem_euclid(FULL_TURN_DEGREES); + nearest_copy(turned, step, count, symmetry.span) + } + }; + + FillCopies { symmetry: *symmetry, pivot, axis, step, first, count, next: 0 } + } + + /// Copy `index`: the original at 0, then the mirror or the radial copies in turn + fn copy(&self, index: u32) -> FillCopy { + let flip = if index == 0 { [false; 2] } else { self.symmetry.flip }; + let turn = match self.symmetry.kind { + _ if index == 0 => Mat3::IDENTITY, + SymmetryKind::Mirror => { + let mut scale = Vec3::ONE; + scale[self.axis] = -1.0; + Mat3::from_diagonal(scale) + } + + // Copy `index` is the original turned by `index` steps, so a texel samples the original turned back + SymmetryKind::Radial => Mat3::from_axis_angle(Vec3::AXES[self.axis], -(index as f32 * self.step).to_radians()), + }; + FillCopy::new(turn, self.pivot, flip) + } +} + +/// The radial copy nearest a texel `turned` degrees round the axis, of `count` copies `step` degrees apart over `span` degrees: copy 0 across the gap a span under a full turn leaves, else the nearest by its step +fn nearest_copy(turned: f32, step: f32, count: u32, span: f32) -> u32 { + // A span of nothing (or no step at all) stacks every copy on the original + if step.is_nan() || step <= 0.0 { + return 0; + } + + let by_step = (turned / step).round() as u32; + if span >= FULL_TURN_DEGREES || span.is_nan() { + return by_step % count; + } + + let last = by_step.min(count - 1); + let past_last = (turned - last as f32 * step).abs(); + let before_first = FULL_TURN_DEGREES - turned; + if before_first <= past_last { 0 } else { last } +} + +impl Iterator for FillCopies { + type Item = FillCopy; + + fn next(&mut self) -> Option { + if self.next >= self.count { + return None; + } + + let index = (self.first + self.next) % self.count; + self.next += 1; + Some(self.copy(index)) + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::glam::Vec2; + + use super::*; + + fn symmetry(kind: SymmetryKind, axis: u8) -> FillSymmetry { + FillSymmetry { on: true, kind, axis, ..FillSymmetry::OFF } + } + + #[test] + fn a_mirror_puts_the_texels_own_half_first_and_reflects_across_the_axis_position() { + let mut mirror = symmetry(SymmetryKind::Mirror, 0); + mirror.position = [0.5, 0.0, 0.0]; + let left: Vec = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert_eq!(left.len(), 2); + + // The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first + assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5)); + assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5)); + assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5)); + let right: Vec = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5)); + } + + #[test] + fn radial_copies_turn_by_their_step_and_flip_only_the_copies() { + let mut radial = symmetry(SymmetryKind::Radial, 2); + radial.count = 4; + radial.flip = [true, false]; + let copies: Vec = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect(); + assert_eq!(copies.len(), 4); + assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5)); + assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5)); + + // Copy 1 sits a quarter turn on: a texel on +Y samples the original on +X + assert!(copies[1].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5)); + + // A texel on +Y lies in copy 1's wedge, so copy 1 comes first there + let on_y: Vec = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect(); + assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5)); + } + + #[test] + fn the_nearest_copy_is_found_by_its_step_as_a_search_of_every_copy_finds_it() { + for (count, span) in [(6, 360.0), (5, 360.0), (4, 180.0), (3, 90.0), (64, 300.0), (2, 1.0)] { + let step = radial_step(count, span); + for tenth in 0..3600 { + let turned = tenth as f32 / 10.0 + 0.05; + let gap = |index: u32| { + let past_copy = (turned - index as f32 * step).rem_euclid(FULL_TURN_DEGREES); + past_copy.min(FULL_TURN_DEGREES - past_copy) + }; + let searched = (0..count).min_by(|a, b| gap(*a).total_cmp(&gap(*b))).unwrap_or(0); + assert_eq!(nearest_copy(turned, step, count, span), searched, "{count} copies over {span} at {turned}"); + } + } + } + + fn radial_step(count: u32, span: f32) -> f32 { + FillSymmetry { count, span, ..symmetry(SymmetryKind::Radial, 2) }.step() + } +} diff --git a/crates/core/src/fill_symmetry.rs b/crates/core/src/fill_symmetry.rs new file mode 100644 index 00000000..be0ebc40 --- /dev/null +++ b/crates/core/src/fill_symmetry.rs @@ -0,0 +1,93 @@ +//! Symmetry of a fill's 3D projection: mirrored or radial copies of it on the model + +use serde::{Deserialize, Serialize}; + +use crate::{FULL_TURN_DEGREES, SymmetryKind}; + +/// Copies of a fill's projection: off for every fill saved before symmetry existed +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct FillSymmetry { + pub on: bool, + pub kind: SymmetryKind, + /// 0 = X, 1 = Y, 2 = Z: the mirror plane's normal, or the axis radial copies turn round + pub axis: u8, + /// Whether the copies' images are turned over across (U) and down (V) + pub flip: [bool; 2], + /// Where the mirror plane or the turning axis passes, in mesh radii from the mesh's centre + pub position: [f32; 3], + /// How many radial copies, the original included + pub count: u32, + /// The degrees the radial copies spread over; a full turn spaces them evenly round it + pub span: f32, +} + +impl FillSymmetry { + /// Off; switched on, a mirror across X through the mesh's centre, or six radial copies over a full turn + pub const OFF: FillSymmetry = + FillSymmetry { on: false, kind: SymmetryKind::Mirror, axis: 0, flip: [false; 2], position: [0.0; 3], count: 6, span: FULL_TURN_DEGREES }; + /// The fewest and most radial copies + pub const COUNTS: std::ops::RangeInclusive = 2..=64; + /// The degrees an Angle span may be set to: at least one, at most a full turn + pub const SPANS: std::ops::RangeInclusive = 1.0..=FULL_TURN_DEGREES; + /// How far the axis position reaches from the mesh's centre, in mesh radii + pub const REACH: f32 = 1.0; + /// [`FillSymmetry::axis`] of the last axis, Z + pub const LAST_AXIS: u8 = 2; + + /// The degrees between radial copies: a full turn spaces `count` copies evenly, a smaller span puts the first and last at its ends (a span that is not a number is a full turn) + pub fn step(&self) -> f32 { + let count = self.radial_count() as f32; + let span = if self.span.is_nan() { FULL_TURN_DEGREES } else { self.span.clamp(0.0, FULL_TURN_DEGREES) }; + if span >= FULL_TURN_DEGREES { span / count } else { span / (count - 1.0) } + } + + /// The copies there are, the original included: two for a mirror + pub fn copies(&self) -> u32 { + match self.kind { + SymmetryKind::Mirror => 2, + SymmetryKind::Radial => self.radial_count(), + } + } + + /// The axis the copies mirror across or turn round, the last one for an axis past it + pub fn axis_index(&self) -> usize { + usize::from(self.axis.min(Self::LAST_AXIS)) + } + + /// How many radial copies, kept within [`FillSymmetry::COUNTS`] + fn radial_count(&self) -> u32 { + self.count.clamp(*Self::COUNTS.start(), *Self::COUNTS.end()) + } + + /// Whether this is the symmetry a new fill starts with, so saves leave it out + pub fn is_default(&self) -> bool { + *self == FillSymmetry::default() + } +} + +impl Default for FillSymmetry { + fn default() -> Self { + FillSymmetry::OFF + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn radial(count: u32, span: f32) -> FillSymmetry { + FillSymmetry { on: true, kind: SymmetryKind::Radial, count, span, ..FillSymmetry::OFF } + } + + #[test] + fn a_span_under_a_full_turn_puts_the_last_copy_at_its_end() { + assert_eq!(radial(4, 180.0).step(), 60.0); + assert_eq!(radial(4, 360.0).step(), 90.0); + } + + #[test] + fn a_span_that_is_not_a_number_spaces_the_copies_round_a_full_turn() { + assert_eq!(radial(4, f32::NAN).step(), 90.0); + } +} diff --git a/crates/core/src/symmetry_kind.rs b/crates/core/src/symmetry_kind.rs new file mode 100644 index 00000000..01b5c407 --- /dev/null +++ b/crates/core/src/symmetry_kind.rs @@ -0,0 +1,31 @@ +//! The kind of copies a symmetric fill makes: mirrored or turned round an axis + +use serde::{Deserialize, Serialize}; + +/// How a symmetric fill copies its projection +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SymmetryKind { + /// One copy mirrored across the plane through the axis position, square to the axis + #[default] + Mirror, + /// Copies turned round the axis through the axis position + Radial, +} + +impl SymmetryKind { + /// Every kind, in the order the Type list shows them + pub const ALL: [SymmetryKind; 2] = [SymmetryKind::Mirror, SymmetryKind::Radial]; + + /// The id commands use + pub fn id(self) -> &'static str { + match self { + SymmetryKind::Mirror => "mirror", + SymmetryKind::Radial => "radial", + } + } + + /// The kind with command id `id` + pub fn from_id(id: &str) -> Option { + SymmetryKind::ALL.into_iter().find(|kind| kind.id() == id) + } +} diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs new file mode 100644 index 00000000..0a95f428 --- /dev/null +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -0,0 +1,113 @@ +//! A fill's Symmetry section: mirrored or radial copies of its 3D projection + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{FillSymmetry, Projection, Sampling, SymmetryKind}; + +use crate::TextureCraftApp; +use crate::fill_panel::run_projection; +use crate::fill_pictures::ring_picture; +use crate::i18n::{n_, tr}; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::theme::{AXIS_COLORS, AXIS_NAMES, Tokens}; +use crate::widgets::press_edit; + +/// What the Axis position track spans, in mesh radii from the mesh's centre +const POSITION_RANGE: RangeInclusive = -FillSymmetry::REACH..=FillSymmetry::REACH; + +/// What the Count track spans; a typed count reaches the engine's fewest and most copies, as the symmetry popup's Count does +const COUNT_TRACK: RangeInclusive = *FillSymmetry::COUNTS.start() as f32..=16.0; + +/// What a typed Count may reach +const COUNT_TYPED: RangeInclusive = *FillSymmetry::COUNTS.start() as f32..=*FillSymmetry::COUNTS.end() as f32; + +/// The Angle span slider's place in the stack beside the ring, under Count +const SPAN_SLIDER: usize = 1; + +/// The Symmetry section under the Fill section: its switch on the caption, then Type, Axis, the radial copies beside their picture, Flip copy and Axis position +pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, projection: &Projection, sampling: Sampling, base: &Value) { + let symmetry = sampling.symmetry; + let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + if !projection.takes_symmetry() { + let reason = match projection { + Projection::UvTile => tr("Not available with Fill (Match per UV Tile)"), + _ => tr("Not available with UV projection"), + }; + sheet.section_unavailable(tr("Symmetry"), reason); + return; + } + + let switch = sheet.section_switch(tr("Symmetry"), symmetry.on); + if switch.clicked() { + run(app, json!({"symmetry": !symmetry.on})); + } + if !symmetry.on { + return; + } + + let (picked, _) = sheet.dropdown(tr("Type"), symmetry.kind, &SymmetryKind::ALL, |kind| tr(kind_label(kind)).to_owned(), None); + if let Some(kind) = picked { + run(app, json!({"symmetryType": kind.id()})); + } + let axis = symmetry.axis_index(); + if let Some(picked) = sheet.switch_tinted(tr("Axis"), &AXIS_NAMES, axis, &AXIS_COLORS) { + run(app, json!({"symmetryAxis": picked})); + } + if symmetry.kind == SymmetryKind::Radial { + radial_rows(app, sheet, &symmetry, base); + } + + let mut flip = symmetry.flip; + if sheet.toggle_pair(tr("Flip copy"), ["U", "V"], &mut flip).is_some() { + run(app, json!({"flipCopy": flip})); + } + + // A mirror moves its plane along its axis; radial copies turn round an axis that moves across it + let moving: Vec = match symmetry.kind { + SymmetryKind::Mirror => vec![axis], + SymmetryKind::Radial => (0..AXIS_NAMES.len()).filter(|other| *other != axis).collect(), + }; + let mut parts: Vec<(&str, egui::Color32, f32)> = moving.iter().map(|&moved| (AXIS_NAMES[moved], AXIS_COLORS[moved], symmetry.position[moved])).collect(); + if let Some((index, merge)) = sheet.lettered_sliders(tr("Axis position"), &mut parts, POSITION_RANGE, 2) + && let (Some(&moved), Some((_, _, value))) = (moving.get(index), parts.get(index)) + { + let mut position = symmetry.position; + position[moved] = *value; + run(app, json!({"axisPosition": position, "merge": merge})); + } +} + +/// Count and Angle span beside the ring of copies, seen along the axis +fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetry: &FillSymmetry, base: &Value) { + let tokens = Tokens::get(sheet.ui.ctx()); + let axis_color = AXIS_COLORS[symmetry.axis_index()]; + let picture = |painter: &Painter, rect: Rect| ring_picture(painter, rect, symmetry, axis_color, &tokens); + let count = symmetry.copies(); + let (mut count_value, mut span_value) = (count as f32, symmetry.span); + let mut sliders = [ + StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" }, + StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" }, + ]; + let edited = sheet.picture_sliders(&picture, &mut sliders); + if let Some((SPAN_SLIDER, merge)) = edited { + run_projection(app, base, json!({"angleSpan": span_value, "merge": merge})); + return; + } + + // Whole counts: a press's first whole-number change starts its undo step, changes that round to the count it has apply nothing + let counted = count_value.round(); + let press = sheet.ui.make_persistent_id("symmetry_count_press"); + if let Some(merge) = press_edit(sheet.ui, press, edited.is_some() && counted as u32 != count) { + run_projection(app, base, json!({"symmetryCount": counted, "merge": merge})); + } +} + +/// The Type dropdown's name for `kind` +fn kind_label(kind: SymmetryKind) -> &'static str { + match kind { + SymmetryKind::Mirror => n_("Mirror symmetry"), + SymmetryKind::Radial => n_("Radial symmetry"), + } +} diff --git a/crates/ui-egui/src/symmetry/settings_popup.rs b/crates/ui-egui/src/symmetry/settings_popup.rs index b92e37cd..8e072d9e 100644 --- a/crates/ui-egui/src/symmetry/settings_popup.rs +++ b/crates/ui-egui/src/symmetry/settings_popup.rs @@ -6,6 +6,7 @@ use texturecraft_engine::paint::{FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Symmetry} use super::{DEFAULT_RADIAL_COUNT, movable_axes}; use crate::TextureCraftApp; use crate::i18n::tr; +use crate::theme::AXIS_NAMES; use crate::widgets::{color_swatch, section, slider}; /// The popup's width (points) @@ -14,8 +15,6 @@ const POPUP_WIDTH: f32 = 340.0; /// Width of the radial Axis row's label column const LABEL_WIDTH: f32 = 64.0; -const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; - /// Space between the mirror section and the radial toggle const SECTIONS_GAP: f32 = 4.0; diff --git a/crates/ui-egui/src/symmetry/view_overlay.rs b/crates/ui-egui/src/symmetry/view_overlay.rs index 3ceb5be6..4f805951 100644 --- a/crates/ui-egui/src/symmetry/view_overlay.rs +++ b/crates/ui-egui/src/symmetry/view_overlay.rs @@ -11,6 +11,7 @@ use super::symmetry_intersection::SymmetryIntersection; use super::symmetry_manipulator::SymmetryManipulator; use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; use crate::TextureCraftApp; +use crate::theme::{AXIS_COLORS, SHAFT_HALO, SHAFT_HALO_EXTRA_WIDTH, SHAFT_WIDTH}; /// The plane reaches this far past the mesh, as a fraction of its size const PLANE_MARGIN: f32 = 0.05; @@ -30,14 +31,6 @@ const VISIBILITY_TOLERANCE: f32 = 2e-3; const INTERSECTION_WIDTH: f32 = 1.5; const INTERSECTION_POINT_RADIUS: f32 = 3.0; -/// Manipulator arrows along X, Y and Z (the view-corner axis colors, a little softer) -const AXIS_COLORS: [Color32; 3] = [Color32::from_rgb(0xd8, 0x60, 0x4f), Color32::from_rgb(0x6c, 0xbc, 0x5a), Color32::from_rgb(0x5a, 0x8c, 0xe0)]; - -/// Arrow shaft width, its dark halo and the halo's extra width (points at the default size) -const SHAFT_WIDTH: f32 = 2.2; -const SHAFT_HALO: Color32 = Color32::from_black_alpha(128); -const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; - /// Faces around a cone const CONE_SEGMENTS: usize = 20; diff --git a/crates/ui-egui/tests/it/fill_symmetry_rows.rs b/crates/ui-egui/tests/it/fill_symmetry_rows.rs new file mode 100644 index 00000000..466f07f5 --- /dev/null +++ b/crates/ui-egui/tests/it/fill_symmetry_rows.rs @@ -0,0 +1,111 @@ +//! A fill's Symmetry section: its switch, Type, Axis, Flip copy and the radial rows each change the fill's symmetry + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{FillSymmetry, LayerId, SymmetryKind}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::fill_support::{click_label, click_node, fill_app, fill_of}; +use crate::filter_support::{along, click_at, drag, undo_depth}; +use crate::{PROPERTIES_WINDOW, SETTLE_FRAMES}; + +/// The app with a new fill layer (projected as `projection`) selected, its Symmetry tab clicked, and its layer id +fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { + let (harness, LayerId(layer)) = fill_app(json!({}), Some(projection), Some("Symmetry"), PROPERTIES_WINDOW); + (harness, layer) +} + +/// The fill layer's symmetry as the document holds it +fn symmetry(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> FillSymmetry { + fill_of(harness, LayerId(layer)).sampling.symmetry +} + +/// The app with a planar fill's radial symmetry on (six copies over a full turn) and its radial rows showing +fn app_with_radial() -> (Harness<'static, TextureCraftApp>, u64) { + let (mut harness, layer) = app_with_fill("planar"); + harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "symmetry": true, "symmetryType": "radial"})); + harness.run_steps(SETTLE_FRAMES); + (harness, layer) +} + +/// The Count track's start: the fewest copies +const COUNT_TRACK_FEWEST: f32 = *FillSymmetry::COUNTS.start() as f32; + +/// The Count track's end; a typed count reaches further +const COUNT_TRACK_MOST: f32 = 16.0; + +/// Where the Count track shows `count` copies +fn count_at(harness: &Harness<'_, TextureCraftApp>, count: f32) -> egui::Pos2 { + let track = harness.get_by_role_and_label(Role::Slider, "Count").rect(); + along(track, (count - COUNT_TRACK_FEWEST) / (COUNT_TRACK_MOST - COUNT_TRACK_FEWEST)) +} + +#[test] +fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() { + let (mut harness, layer) = app_with_fill("planar"); + assert!(harness.query_by_label("Mirror symmetry").is_none(), "off, the section is the caption alone"); + + click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(symmetry(&harness, layer).on); + assert!(harness.query_by_label("Axis position X").is_some(), "a mirror across X moves along X"); + assert!(harness.query_by_label("Count").is_none(), "a mirror has no radial rows"); + + click_node(&mut harness, Role::RadioButton, "Y"); + assert_eq!(symmetry(&harness, layer).axis, 1); + click_node(&mut harness, Role::CheckBox, "Flip copy U"); + assert_eq!(symmetry(&harness, layer).flip, [true, false]); + + click_node(&mut harness, Role::ComboBox, "Mirror symmetry"); + click_node(&mut harness, Role::ListBoxOption, "Radial symmetry"); + assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial); + for label in ["Count", "Angle span", "Axis position X", "Axis position Z"] { + assert!(harness.query_by_label(label).is_some(), "radial round Y: {label}"); + } + assert!(harness.query_by_label("Axis position Y").is_none(), "the turning axis does not move along itself"); + + click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(!symmetry(&harness, layer).on); + assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial, "switched off, the settings stay"); +} + +#[test] +fn a_uv_fill_says_why_in_place_of_the_symmetry_switch() { + let (mut harness, layer) = app_with_fill("uv"); + assert!(harness.query_by_role_and_label(Role::CheckBox, "Symmetry").is_none(), "no switch to click"); + click_label(&mut harness, "Not available with UV projection"); + assert!(!symmetry(&harness, layer).on, "a UV projection has no symmetry to switch on"); + assert!(harness.query_by_label("Type").is_none(), "its settings stay hidden, not greyed"); +} + +/// A click on the Count track that rounds to the count it has changes nothing and adds no undo step; a drag to the next whole count is one step +#[test] +fn a_count_click_that_keeps_the_count_adds_no_undo_step_and_a_drag_to_the_next_adds_one() { + let (mut harness, layer) = app_with_radial(); + let steps = undo_depth(&harness); + + let inside = count_at(&harness, 6.2); + click_at(&mut harness, inside); + assert_eq!(symmetry(&harness, layer).count, 6); + assert_eq!(undo_depth(&harness), steps, "a count that stays six is no edit"); + + let (from, to) = (count_at(&harness, 6.0), count_at(&harness, 7.3)); + drag(&mut harness, from, to); + assert_eq!(symmetry(&harness, layer).count, 7); + assert_eq!(undo_depth(&harness), steps + 1, "the drag's frames merge into one step"); +} + +/// A typed count reaches past the track's end, up to the engine's most copies, as the symmetry popup's Count does +#[test] +fn a_typed_count_reaches_past_the_track_to_the_engines_most() { + let (mut harness, layer) = app_with_radial(); + + click_node(&mut harness, Role::Label, "Count value"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("40".into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(symmetry(&harness, layer).count, 40); +} From eb362a790ec41ad915582d270b77a4bbddd496a2 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:28:49 +0000 Subject: [PATCH 017/153] Panel shell: review repairs from #698 Chasse's repairs to the panel shell, carried over from the #698 head (5644b7d3). --- crates/ui-egui/src/docking.rs | 4 ++++ crates/ui-egui/src/docking/header_band.rs | 2 ++ crates/ui-egui/src/docking/shown_group_tab.rs | 4 ++++ crates/ui-egui/src/symmetry/mod.rs | 2 +- crates/ui-egui/tests/it/empty_start.rs | 1 + crates/ui-egui/tests/it/layers_panel.rs | 1 + crates/ui-egui/tests/it/panel_header.rs | 2 ++ crates/ui-egui/tests/it/popup_press_close.rs | 1 + crates/ui-egui/tests/it/properties_min_width.rs | 4 ++++ crates/ui-egui/tests/it/rail.rs | 1 + crates/ui-egui/tests/it/split_divider.rs | 3 +++ 11 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index b4f64ad4..16164aa4 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -688,9 +688,11 @@ mod tests { fn default_workspace_has_every_panel_and_is_valid() { let w = default_workspace(); assert!(validate(&w).is_ok()); + for panel in Panel::ALL { assert!(w.layout.contains(&panel) || w.hidden.iter().any(|(p, _)| *p == panel), "{panel:?} is neither shown nor hidden"); } + assert_eq!(panels_of(&w), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); } @@ -703,6 +705,7 @@ mod tests { let Node::Split { size: SplitSize::Ratio(layers), first, second, .. } = below_sets.as_ref() else { panic!("layers | properties") }; assert!(matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.first() == Some(&Panel::Layers))); assert!(matches!(second.as_ref(), Node::Tabs { panels, .. } if panels == &[Panel::Properties])); + let properties = 1.0 - layers; assert!((2.0 / 3.0..0.7).contains(&properties), "Properties takes about 69% of the column, at least two thirds: {properties}"); } @@ -716,6 +719,7 @@ mod tests { let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") }; *size = SplitSize::Ratio(0.57); let back = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged"); } diff --git a/crates/ui-egui/src/docking/header_band.rs b/crates/ui-egui/src/docking/header_band.rs index 95dcdeec..3c00cd31 100644 --- a/crates/ui-egui/src/docking/header_band.rs +++ b/crates/ui-egui/src/docking/header_band.rs @@ -16,6 +16,7 @@ pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - PANEL_SEPARATI /// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none pub(super) fn under_a_panel(layout: &Layout, panel: Panel) -> bool { let Some(root) = &layout.root else { return false }; + let mut nodes: Vec<(&Node, bool)> = vec![(root, false)]; while let Some((node, below)) = nodes.pop() { match node { @@ -55,6 +56,7 @@ pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lif { section.format.valign = Align::BOTTOM; } + job.first_row_min_height = galley.size().y + 2.0 * shift.abs(); job } diff --git a/crates/ui-egui/src/docking/shown_group_tab.rs b/crates/ui-egui/src/docking/shown_group_tab.rs index 61f5d4e0..c9c500cb 100644 --- a/crates/ui-egui/src/docking/shown_group_tab.rs +++ b/crates/ui-egui/src/docking/shown_group_tab.rs @@ -26,6 +26,7 @@ fn group_of(layout: &Layout, panel: Panel) -> Option<(&[Panel], bool)> { let docked = layout.root.iter().map(|root| (root, false)); let floating = layout.floating.iter().map(|window| (&window.root, true)); let mut nodes: Vec<(&Node, bool)> = docked.chain(floating).collect(); + while let Some((node, floats)) = nodes.pop() { match node { Node::Split { first, second, .. } => { @@ -42,6 +43,7 @@ fn group_of(layout: &Layout, panel: Panel) -> Option<(&[Panel], bool)> { _ => {} } } + None } @@ -59,6 +61,7 @@ impl Panels<'_> { /// Over the tab the dock drew for `panel`, the panel shown in its group, paints the section tabs' raised box and the name again; a panel alone keeps its plain header. `ui` is the panel's body, right under the strip pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) { let Some((panels, floating)) = group_of(&self.app.ui.dock.workspace.layout, panel) else { return }; + if panels.len() < 2 { return; } @@ -76,6 +79,7 @@ impl Panels<'_> { let header = self.group_header_width(panels, &panel, floating, strip.width()).clamp(0.0, strip.width()); let available = (strip.width() - header - self.style.drag_bar_width).max(0.0); let fit = craft_ui::tabs::fit(&natural, shown, available, self.style.min_tab_width, OVERFLOW_WIDTH); + let mut left = strip.left(); for (index, width) in fit.shown { if index != shown { diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 94eec7d8..081387c3 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -102,7 +102,7 @@ pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { .close_behavior(egui::PopupCloseBehavior::IgnoreClicks) .show(|ui| settings_popup::show(app, ui)); - // A click outside the popup and the dropdowns it opens (foreground layers too) closes it, and so does a drag that starts outside them + // Outside clicks and drags dismiss the menu unless they belong to a child popup if let Some(shown) = shown && !response.clicked() { diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index 3ca2f721..eedbb9c2 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -381,6 +381,7 @@ fn close_releases_the_layer_thumbnail_snapshot() { invoke(&mut harness, "file.close"); assert!(!harness.state().session.project_open); + assert_eventually_released(&old_mesh); for (pixels, _) in &old_maps { assert_eventually_released(pixels); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 6b2b6a3e..e346617a 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -122,6 +122,7 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { let row = h.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); + let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0); click(&mut h, egui::pos2(row.left() + 15.0 + indent, row.center().y)); diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs index 8a9caed5..6485f50a 100644 --- a/crates/ui-egui/tests/it/panel_header.rs +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -52,6 +52,7 @@ fn every_docked_panel_header_ends_in_its_own_close_button() { fn the_header_close_button_closes_its_panel() { let mut harness = app(); assert!(harness.state().ui.dock.is_visible(Panel::Properties)); + let close = panel_close_button(&harness, tab_rect(&harness, "Properties - ")); click_at(&mut harness, close.center()); @@ -230,6 +231,7 @@ fn a_tab_menus_panel_names_keep_their_plain_layout() { _ => None, }) .collect(); + assert!(!padded.is_empty(), "the menu paints the Layers entry"); assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); } diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index 31e2d868..b56d3c91 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -133,6 +133,7 @@ fn a_stroke_on_the_model_closes_the_symmetry_settings() { harness.run_steps(SETTLE_FRAMES); harness.get_by_label("Symmetry settings").click(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Radial symmetry").is_some(), "the settings open"); stroke_on_model(&mut harness, Modifiers::NONE); diff --git a/crates/ui-egui/tests/it/properties_min_width.rs b/crates/ui-egui/tests/it/properties_min_width.rs index 79c39f5d..f9d5fd68 100644 --- a/crates/ui-egui/tests/it/properties_min_width.rs +++ b/crates/ui-egui/tests/it/properties_min_width.rs @@ -39,6 +39,7 @@ fn set_column_width(harness: &mut Harness<'_, TextureCraftApp>, width: f32) { let mut workspace = harness.state().ui.dock.workspace().clone(); let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("the assets column and the rest") }; let Node::Split { size, .. } = second.as_mut() else { panic!("the 3D view and the right column") }; + *size = SplitSize::FixedSecond(width); harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); harness.run_steps(SETTLE_FRAMES); @@ -86,12 +87,14 @@ fn dragging_the_right_column_narrow_stops_at_the_properties_minimum_width() { set_column_width(&mut harness, WIDE_COLUMN); let before = properties_title(&harness).min.x; + assert!(properties_header_width(&harness) > at_minimum, "a wide column gives Properties more than its minimum"); let y = properties_title(&harness).max.y + DIVIDER_GRAB_BELOW_HEADER; drag(&mut harness, pos2(before - DIVIDER_OFFSET, y), pos2(WINDOW_SIZE.x - WINDOW_RIGHT_INSET, y)); assert!(properties_title(&harness).min.x > before, "the divider moved right"); + let width = properties_header_width(&harness); assert!((width - at_minimum).abs() < 0.5, "Properties stopped at its minimum: header {width}, {at_minimum} at the minimum"); } @@ -104,5 +107,6 @@ fn a_layout_saved_narrower_draws_properties_at_its_minimum_width() { set_column_width(&mut harness, PROPERTIES_MIN_WIDTH * 0.5); let width = properties_header_width(&harness); + assert!((width - at_minimum).abs() < 0.5, "a narrow saved column opens at the minimum: header {width}, {at_minimum} at the minimum"); } diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index 30f3a153..b6b3617b 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -186,6 +186,7 @@ fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { // The popup covers the Properties strip and stays put while dragged: drop on the Texture Sets strip above it let texture_sets_tab = harness.get_by_label("Texture Sets").rect(); assert!(texture_sets_tab.bottom() < title.top(), "the Texture Sets strip {texture_sets_tab:?} is under the popup at {title:?}"); + drag(&mut harness, title.center(), texture_sets_tab.center()); let layout = &harness.state().ui.dock.workspace().layout; diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 075d4b80..63ce4ee7 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -133,15 +133,18 @@ fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { 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)); } From 9e7943463217f214cb5d3926c73c14814b36e55b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:27 +0000 Subject: [PATCH 018/153] Fills: the Material tab's source picker and slot cards (picture picker for every source) --- crates/ui-egui/src/fill_source_slot.rs | 335 ---------- crates/ui-egui/src/fill_source_target.rs | 12 - crates/ui-egui/src/filter_slot.rs | 13 +- crates/ui-egui/src/picker_group.rs | 9 + crates/ui-egui/src/picker_tab.rs | 18 + crates/ui-egui/src/resource_picker.rs | 633 +++++++++++-------- crates/ui-egui/src/resource_picker_anchor.rs | 12 - crates/ui-egui/src/resource_picker_choice.rs | 9 - crates/ui-egui/src/resource_picker_item.rs | 91 ++- crates/ui-egui/src/resource_picker_tab.rs | 8 - crates/ui-egui/src/resource_picker_tile.rs | 18 - crates/ui-egui/src/slot_thumbnail.rs | 61 ++ crates/ui-egui/src/source_choice.rs | 14 + crates/ui-egui/src/source_slot.rs | 67 ++ crates/ui-egui/src/tile_picture.rs | 17 + crates/ui-egui/tests/it/source_picker.rs | 209 ++++++ 16 files changed, 852 insertions(+), 674 deletions(-) delete mode 100644 crates/ui-egui/src/fill_source_slot.rs delete mode 100644 crates/ui-egui/src/fill_source_target.rs create mode 100644 crates/ui-egui/src/picker_group.rs create mode 100644 crates/ui-egui/src/picker_tab.rs delete mode 100644 crates/ui-egui/src/resource_picker_anchor.rs delete mode 100644 crates/ui-egui/src/resource_picker_choice.rs delete mode 100644 crates/ui-egui/src/resource_picker_tab.rs delete mode 100644 crates/ui-egui/src/resource_picker_tile.rs create mode 100644 crates/ui-egui/src/slot_thumbnail.rs create mode 100644 crates/ui-egui/src/source_choice.rs create mode 100644 crates/ui-egui/src/source_slot.rs create mode 100644 crates/ui-egui/src/tile_picture.rs create mode 100644 crates/ui-egui/tests/it/source_picker.rs diff --git a/crates/ui-egui/src/fill_source_slot.rs b/crates/ui-egui/src/fill_source_slot.rs deleted file mode 100644 index cecfd509..00000000 --- a/crates/ui-egui/src/fill_source_slot.rs +++ /dev/null @@ -1,335 +0,0 @@ -//! The source slot of a fill: a mask fill's grayscale or one channel of a fill. It shows what the fill reads and opens the source picker: the patterns, the project's images and a uniform value, or the anchor points below the layer - -use std::sync::{Arc, LazyLock}; - -use egui::{Sense, Ui, vec2}; -use serde_json::json; -use texturecraft_engine::compose::{ImageRes, ThumbTarget}; -use texturecraft_engine::core::{Channel, LayerId, ProceduralKind, Source}; - -use crate::TextureCraftApp; -use crate::dock::with; -use crate::fill_source_target::FillSourceTarget; -use crate::filter_slot::{SLOT_HEIGHT, paint}; -use crate::i18n::tr; -use crate::resource_picker; -use crate::resource_picker_anchor::ResourcePickerAnchor; -use crate::resource_picker_choice::ResourcePickerChoice; -use crate::resource_picker_tile::ResourcePickerTile; -use crate::shelf_preview::ShelfPreview; - -/// The key of the uniform value tile, and the prefixes of the pattern and image tiles' keys -const UNIFORM_KEY: &str = "uniform"; -const PATTERN_PREFIX: &str = "pattern:"; -const IMAGE_PREFIX: &str = "image:"; -/// The gray the uniform value tile shows -const UNIFORM_TILE_GRAY: f32 = 0.8; -/// The swatch's name among the image previews, prefixed like the stencil previews so it is not taken for a project image -const UNIFORM_SWATCH_NAME: &str = "swatch:uniform"; -/// One swatch for every frame, so its preview stays cached -static UNIFORM_SWATCH: LazyLock> = - LazyLock::new(|| Arc::new(ImageRes::new(1, 1, vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], false))); - -/// The slot of `fill`, which reads `source`; `anchors` are the anchor points below its layer and `caption` names what it fills -pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, fill: &FillSourceTarget, source: &Source, (anchors, caption): (&[(LayerId, String)], &str)) { - let ctx = ui.ctx().clone(); - let channel = match fill { - FillSourceTarget::Mask { .. } => source_channel(source), - FillSourceTarget::Channel { channel, .. } => *channel, - }; - let (name, picture) = shown(app, &ctx, source); - - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); - - // Read as a dropdown named for what it fills, its value the source - response.widget_info(|| egui::WidgetInfo { current_text_value: Some(name.clone()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, caption) }); - let popup = ui.make_persistent_id(("fill_source_picker", fill_key(fill))); - if response.clicked() { - resource_picker::toggle(&ctx, popup); - } - let highlighted = response.hovered() || resource_picker::is_open(&ctx, popup); - paint(ui, rect, (highlighted, response.has_focus()), picture, (caption, &name)); - if !resource_picker::is_open(&ctx, popup) { - return; - } - - let tiles = tiles(app, &ctx); - let anchors: Vec = anchors - .iter() - .map(|(anchor, name)| ResourcePickerAnchor { - anchor: *anchor, - name: name.clone(), - layer: layer_name(app, *anchor), - channel: read_label(app, *anchor, channel), - }) - .collect(); - let current = current_key(source); - let picked = resource_picker::show_sources(&response, popup, &mut app.thumbs, (current.as_deref(), source.anchor()), tiles, anchors, |ui, anchor| { - app.layer_panel.texture_outside(ui.ctx(), &app.session, ThumbTarget::Stage { effect: anchor, channel }) - }); - match picked { - Some(ResourcePickerChoice::Resource(key)) if Some(&key) != current.as_ref() => pick_resource(app, fill, &key), - Some(ResourcePickerChoice::Anchor(anchor)) if source.anchor() != Some(anchor) => pick_anchor(app, fill, anchor, channel), - _ => {} - } -} - -/// The name and picture of what `source` reads -fn shown(app: &mut TextureCraftApp, ctx: &egui::Context, source: &Source) -> (String, Option) { - match source { - Source::Uniform(_) => (tr("Uniform value").to_string(), None), - Source::Procedural { pattern, .. } => (tr(pattern.kind.label()).to_string(), app.thumbs.procedural(ctx, pattern.kind).map(|texture| texture.id())), - Source::Image { name, .. } => { - let picture = app.session.images.get(name).cloned().map(|image| app.thumbs.image(ctx, name, &image).id()); - (name.clone(), picture) - } - Source::Anchor { anchor, channel, .. } => { - let name = format!("{} · {}", layer_name(app, *anchor), tr(read_label(app, *anchor, *channel))); - (name, app.layer_panel.texture_outside(ctx, &app.session, ThumbTarget::Stage { effect: *anchor, channel: *channel })) - } - } -} - -/// What a fill reads at anchor point `anchor`: its mask's gray when it sits in a mask, else `channel` -fn read_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> &'static str { - if crate::dock::anchor_in_mask(app, anchor) { "Mask" } else { channel.label() } -} - -/// The name of the layer anchor point `anchor` sits on -fn layer_name(app: &TextureCraftApp, anchor: LayerId) -> String { - let project = &app.session.doc.project; - let layer = project.effect(anchor).and_then(|(owner, _)| project.layers.get(&owner)); - layer.map_or_else(|| tr("missing").to_string(), |layer| layer.name.clone()) -} - -/// The channel a mask fill's anchor is read in (height until one is picked) -fn source_channel(source: &Source) -> Channel { - match source { - Source::Anchor { channel, .. } => *channel, - _ => Channel::Height, - } -} - -/// Keeps the pickers of two slots shown at once apart -fn fill_key(fill: &FillSourceTarget) -> String { - match fill { - FillSourceTarget::Mask { effect } => format!("mask_{effect}"), - FillSourceTarget::Channel { base, channel } => format!("{base}_{}", channel.id()), - } -} - -/// The key of the tile `source` is, outlined in the picker -fn current_key(source: &Source) -> Option { - match source { - Source::Uniform(_) => Some(UNIFORM_KEY.to_string()), - Source::Procedural { pattern, .. } => Some(format!("{PATTERN_PREFIX}{}", pattern.kind.label())), - Source::Image { name, .. } => Some(format!("{IMAGE_PREFIX}{name}")), - Source::Anchor { .. } => None, - } -} - -/// The Resources tab: the patterns, the project's images and a uniform value -fn tiles(app: &mut TextureCraftApp, ctx: &egui::Context) -> Vec> { - let mut tiles = Vec::with_capacity(ProceduralKind::ALL.len() + app.session.images.len() + 1); - tiles.extend(ProceduralKind::ALL.into_iter().map(|kind| ResourcePickerTile { - key: format!("{PATTERN_PREFIX}{}", kind.label()), - label: tr(kind.label()).to_string(), - group: tr("Patterns"), - thumbnail: None, - image: None, - preview: Box::new(move || ShelfPreview::Procedural(kind)), - })); - - let first_image = tiles.len(); - for (name, image) in &app.session.images { - let preview_name = name.clone(); - let preview_image = image.clone(); - tiles.push(ResourcePickerTile { - key: format!("{IMAGE_PREFIX}{name}"), - label: name.clone(), - group: tr("Images"), - thumbnail: None, - image: Some(image.clone()), - preview: Box::new(move || ShelfPreview::Image(preview_name.clone(), preview_image.clone())), - }); - } - tiles[first_image..].sort_unstable_by(|left, right| left.label.cmp(&right.label)); - - tiles.push(ResourcePickerTile { - key: UNIFORM_KEY.to_string(), - label: tr("Uniform value").to_string(), - group: tr("Uniform"), - thumbnail: Some(app.thumbs.image(ctx, UNIFORM_SWATCH_NAME, &UNIFORM_SWATCH)), - image: None, - preview: Box::new(|| ShelfPreview::Image(UNIFORM_SWATCH_NAME.to_string(), UNIFORM_SWATCH.clone())), - }); - - tiles -} - -/// Sets the fill to the resource whose tile key is `key` -fn pick_resource(app: &mut TextureCraftApp, fill: &FillSourceTarget, key: &str) { - let pattern = key.strip_prefix(PATTERN_PREFIX).and_then(ProceduralKind::parse); - match (fill, pattern) { - (FillSourceTarget::Mask { effect }, Some(kind)) => { - app.run("effect.set", json!({"effect": effect, "procedural": kind.label()})); - } - (FillSourceTarget::Mask { effect }, None) => match key.strip_prefix(IMAGE_PREFIX) { - Some(name) => { - app.run("effect.set", json!({"effect": effect, "image": name})); - } - None => { - app.run("effect.set", json!({"effect": effect, "uniform": 1.0})); - } - }, - (FillSourceTarget::Channel { base, channel }, Some(kind)) => { - let (low, high) = pattern_range(*channel); - app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "procedural": kind.label(), "low": low, "high": high}))); - } - (FillSourceTarget::Channel { base, channel }, None) => match key.strip_prefix(IMAGE_PREFIX) { - Some(name) => { - app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "image": name}))); - } - None => { - app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "value": channel.default_value()}))); - } - }, - } -} - -/// Sets the fill to read anchor point `anchor` in `channel` -fn pick_anchor(app: &mut TextureCraftApp, fill: &FillSourceTarget, anchor: LayerId, channel: Channel) { - let (command, params) = match fill { - FillSourceTarget::Mask { effect } => ("effect.set", json!({"effect": effect, "anchor": anchor.0, "anchorChannel": channel.id()})), - FillSourceTarget::Channel { base, channel } => ("layer.fill.set", with(base, json!({"channel": channel.id(), "anchor": anchor.0}))), - }; - app.run(command, params); -} - -/// The values a new pattern maps to in `channel`: grays for the base color, a small relief for height, most of the range otherwise -fn pattern_range(channel: Channel) -> ([f32; 3], [f32; 3]) { - match channel { - Channel::BaseColor => ([0.15; 3], [0.85; 3]), - Channel::Height => ([-0.05; 3], [0.05; 3]), - _ => ([0.2; 3], [0.8; 3]), - } -} - -#[cfg(test)] -mod tests { - use egui_kittest::{Harness, kittest::Queryable}; - use texturecraft_engine::core::LayerKind; - use texturecraft_engine::{Session, execute, geom::primitives}; - - use super::*; - - fn picker_harness(session: Session, anchors: Vec<(LayerId, String)>) -> Harness<'static, (TextureCraftApp, Vec<(LayerId, String)>)> { - let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); - let app = TextureCraftApp::new(&creation_context, session); - Harness::builder().with_size(vec2(500.0, 700.0)).with_context_setup(crate::theme::install).build_ui_state( - |ui, (app, anchors)| { - let layer = app.session.selected_layer().unwrap(); - let LayerKind::Fill(fill) = &app.session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; - let source = fill.source(Channel::Height); - let target = FillSourceTarget::Channel { base: json!({"layer": layer.0}), channel: Channel::Height }; - show(app, ui, &target, &source, (anchors, "Source")); - app.layer_panel.end(ui.ctx(), &app.session); - }, - (app, anchors), - ) - } - - fn image_preview_count(context: &egui::Context) -> usize { - context.tex_manager().read().allocated().filter(|(_, metadata)| metadata.name.starts_with("res_picker-image-")).count() - } - - #[test] - fn searching_the_picker_only_renders_visible_pattern_previews() { - let mut session = Session::new_project("picker", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); - execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(); - let mut harness = picker_harness(session, Vec::new()); - let texture_manager = harness.ctx.tex_manager(); - let pattern_texture_count = || texture_manager.read().allocated().filter(|(_, metadata)| metadata.name.starts_with("thumb_proc:")).count(); - - harness.get_by_role_and_label(egui::Role::ComboBox, "Source").click(); - harness.run_steps(2); - harness.event(egui::Event::Text("Smooth fur".into())); - harness.run_steps(30); - - let after_search = pattern_texture_count(); - let matching_preview = texture_manager.read().allocated().any(|(_, metadata)| metadata.name == "thumb_proc:SmoothFur"); - eprintln!("pattern previews after filtered frames: {after_search} of {}", ProceduralKind::ALL.len()); - assert!(matching_preview, "the selected search result must get a swatch"); - assert!(after_search < ProceduralKind::ALL.len(), "filtered frames must not fill the complete procedural cache"); - - harness.get_by_role_and_label(egui::Role::Button, "Smooth fur").click(); - harness.run_steps(3); - let app = &harness.state().0; - let layer = app.session.selected_layer().unwrap(); - let LayerKind::Fill(fill) = &app.session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; - - assert!(matches!(fill.source(Channel::Height), Source::Procedural { pattern, .. } if pattern.kind == ProceduralKind::SmoothFur)); - assert_eq!(pattern_texture_count(), after_search, "closing the picker reuses the selected swatch"); - drop(harness); - - assert_eq!(pattern_texture_count(), 0, "dropping the app releases procedural swatches"); - } - - #[test] - fn source_picker_images_render_on_scroll_and_release_on_removal() { - const IMAGE_COUNT: usize = 128; - let mut session = Session::new_project("picker", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); - execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(); - for index in 0..IMAGE_COUNT { - let name = format!("picker-image-{index:03}.png"); - session.doc.resources.insert(name.clone(), Arc::new(vec![0])); - session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false))); - } - let mut harness = picker_harness(session, Vec::new()); - - harness.get_by_role_and_label(egui::Role::ComboBox, "Source").click(); - harness.run_steps(30); - let initial_previews = image_preview_count(&harness.ctx); - - assert!(initial_previews > 0 && initial_previews < IMAGE_COUNT, "only visible images should have previews: {initial_previews}"); - harness.run_steps(3); - assert_eq!(image_preview_count(&harness.ctx), initial_previews, "warm frames reuse image previews"); - - let first_name = "picker-image-000.png"; - harness.get_by_role_and_label(egui::Role::Button, first_name).scroll_to_me(); - harness.run_steps(30); - let scrolled_previews = image_preview_count(&harness.ctx); - harness.get_by_role_and_label(egui::Role::Button, first_name).click(); - harness.run_steps(3); - - assert!(scrolled_previews > initial_previews, "scrolling must render newly visible image tiles"); - let app = &mut harness.state_mut().0; - let layer = app.session.selected_layer().unwrap(); - let LayerKind::Fill(fill) = &app.session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; - assert_eq!(fill.source(Channel::Height), Source::image(first_name)); - - app.session.images.clear(); - app.thumbs.sync_images(&app.session.images, app.session.revision + 1); - - assert_eq!(image_preview_count(&harness.ctx), 0, "removed images release all picker preview textures"); - eprintln!("picker image previews: initial {initial_previews}, after scroll {scrolled_previews}, after removal 0"); - } - - #[test] - fn source_tiles_defer_image_previews_until_drawn() { - let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); - for index in 0..128 { - let name = format!("picker-{index:03}.png"); - session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false))); - } - let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); - let mut app = TextureCraftApp::new(&creation_context, session); - let context = egui::Context::default(); - - let tiles = tiles(&mut app, &context); - let image_previews = context.tex_manager().read().allocated().filter(|(_, metadata)| metadata.name.starts_with("res_picker-")).count(); - - assert_eq!(tiles.iter().filter(|tile| tile.key.starts_with(IMAGE_PREFIX)).count(), 128); - assert_eq!(image_previews, 0, "opening the picker must not resample all project images"); - } -} diff --git a/crates/ui-egui/src/fill_source_target.rs b/crates/ui-egui/src/fill_source_target.rs deleted file mode 100644 index 78b5fe63..00000000 --- a/crates/ui-egui/src/fill_source_target.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! Which fill a source slot sets - -use serde_json::Value; -use texturecraft_engine::core::Channel; - -/// Which fill the slot sets, and how -pub(crate) enum FillSourceTarget { - /// A mask fill effect: one grayscale value, set with `effect.set` - Mask { effect: u64 }, - /// One channel of a fill layer or content fill (`base` names it), set with `layer.fill.set` - Channel { base: Value, channel: Channel }, -} diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 95880e2d..8f2bbb03 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -8,11 +8,13 @@ use texturecraft_engine::filter_lib::{filter_effects, find}; use crate::TextureCraftApp; use crate::i18n::tr; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; use crate::resource_picker; use crate::resource_picker_item::ResourcePickerItem; -use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; +use crate::tile_picture::TilePicture; use crate::widgets::elided; pub(crate) const SLOT_HEIGHT: f32 = 52.0; @@ -50,12 +52,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); paint(ui, rect, (highlighted, response.has_focus()), thumbnail.as_ref().map(egui::TextureHandle::id), (tr("Filter"), name)); - let items = |thumbs: &mut Thumbs| { - filter_effects() - .iter() - .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() + let tabs = |thumbs: &mut Thumbs| { + } + } }; let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter); if let Some(id) = picked.filter(|id| Some(*id) != current) { diff --git a/crates/ui-egui/src/picker_group.rs b/crates/ui-egui/src/picker_group.rs new file mode 100644 index 00000000..d49a79de --- /dev/null +++ b/crates/ui-egui/src/picker_group.rs @@ -0,0 +1,9 @@ +//! A group of a resource picker's tiles under one header + +use crate::resource_picker_item::ResourcePickerItem; + +/// Items under one bright header (none: no header row) +pub(crate) struct PickerGroup { + pub header: Option<&'static str>, + pub items: Vec>, +} diff --git a/crates/ui-egui/src/picker_tab.rs b/crates/ui-egui/src/picker_tab.rs new file mode 100644 index 00000000..193896ec --- /dev/null +++ b/crates/ui-egui/src/picker_tab.rs @@ -0,0 +1,18 @@ +//! A tab of a resource picker's edge strip + +use crate::picker_group::PickerGroup; +use crate::resource_picker_item::ResourcePickerItem; + +/// A tab of the picker's edge strip: its icon, name and groups (a picker with one tab draws no strip) +pub(crate) struct PickerTab { + pub icon: &'static str, + pub name: &'static str, + pub groups: Vec>, +} + +impl PickerTab { + /// Every item of the tab, group after group + pub fn items(&self) -> impl Iterator> { + self.groups.iter().flat_map(|group| group.items.iter()) + } +} diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 96eb65fc..d418eade 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -1,53 +1,80 @@ -//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name; a fill source's picker adds a second tab with the anchor points it can read +//! A popup hanging under a slot that picks a resource (a filter, a channel's source) from tiles under bright group headers, behind edge tabs and a search field -use egui::{Id, Response, Sense, Stroke, Ui, pos2, vec2}; +use egui::{Align, Align2, Color32, CornerRadius, FontId, Frame, Id, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2}; use egui_phosphor::regular as ic; -use texturecraft_engine::core::LayerId; use crate::i18n::tr; -use crate::resource_picker_anchor::ResourcePickerAnchor; -use crate::resource_picker_choice::ResourcePickerChoice; -use crate::resource_picker_item::ResourcePickerItem; -use crate::resource_picker_tab::ResourcePickerTab; -use crate::resource_picker_tile::ResourcePickerTile; -use crate::shelf; -use crate::shelf_preview::ShelfPreview; -use crate::theme::Tokens; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP}; +use crate::resource_picker_item::{ResourcePickerItem, search_query}; +use crate::theme::{HARD_SHADOW, Tokens, semibold}; use crate::thumbs::Thumbs; +use crate::tile_picture::TilePicture; -/// 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; -/// Group headers read as the shelf's section titles, a size above the tile labels -const GROUP_FONT_SIZE: f32 = 13.0; -const GROUP_GAP: f32 = 2.0; +/// Columns of tiles in the grid +const COLUMNS: usize = 4; +/// One row of tiles: the picture, two lines of name and air +const ROW_HEIGHT: f32 = 86.0; +/// Rows of tiles the grid shows at once +const GRID_ROWS: f32 = 4.0; +/// The grid's height, fixed so the popup keeps its place and size while searching or switching tabs; less only in a window too short for it +const GRID_HEIGHT: f32 = GRID_ROWS * ROW_HEIGHT; +/// Air between the slot and the popup hanging from it +const POPUP_GAP: f32 = 1.0; +/// Room kept between the popup's shadow and the window's top or bottom edge +const WINDOW_MARGIN: f32 = 8.0; +/// Where the popup goes when it doesn't fit under its slot: above it, then flush with the slot's right edge below or above +const HANG_FALLBACKS: [egui::RectAlign; 3] = [egui::RectAlign::TOP_START, egui::RectAlign::BOTTOM_END, egui::RectAlign::TOP_END]; +const TILE_GAP: f32 = 4.0; +/// Air on each side of a tile inside its grid cell, so neighbouring tiles' hover fills never touch +const TILE_SIDE_GAP: f32 = 1.0; +const PICTURE_SIZE: f32 = 52.0; +const PICTURE_TOP: f32 = 6.0; +const PICTURE_ROUNDING: u8 = 3; +const TILE_ROUNDING: u8 = 5; +const NAME_SIZE: f32 = 10.0; +/// From the tile's top to the first name line's centre, and between the two lines: both lines sit inside the tile's box +const NAME_CENTER: f32 = PICTURE_SIZE + 14.0; +const NAME_LINE: f32 = 12.0; +const NAME_MARGIN: f32 = 4.0; +const IMPORT_GLYPH_SIZE: f32 = 16.0; +const LOADING_GLYPH_SIZE: f32 = 24.0; +/// The loading glyph is fainter than the other glyphs: it stands in for a picture still coming +const LOADING_GLYPH_OPACITY: f32 = 0.5; +const GLYPH_SIZE: f32 = 22.0; -/// The tab strip along the popup's top edge: its height, the tabs' padding, rounding and the gap between them -const TAB_STRIP_HEIGHT: f32 = 28.0; -const TAB_PADDING: f32 = 10.0; -const TAB_ICON_GAP: f32 = 6.0; -const TAB_ROUNDING: f32 = 4.0; -const TAB_GAP: f32 = 4.0; -const TAB_INSET: f32 = 4.0; -const TAB_FONT_SIZE: f32 = 12.0; -/// How much darker the strip is than the popup body -const TAB_STRIP_DARKEN: f32 = 0.2; +/// The bright group header row and the dim sub-caption row +const HEADER_HEIGHT: f32 = 24.0; +const HEADER_SIZE: f32 = 12.0; +const CAPTION_HEIGHT: f32 = 18.0; +const CAPTION_SIZE: f32 = 11.0; +/// Header and caption text from the grid's left edge +const HEADER_INSET: f32 = 4.0; -/// Anchor tiles: the shelf's tile size, the picture's size and place, the anchor badge in its corner and the channel line's size -const ANCHOR_TILE_SIZE: egui::Vec2 = vec2(72.0, 86.0); -const ANCHOR_PICTURE_SIZE: f32 = 56.0; -const ANCHOR_PICTURE_TOP: f32 = 4.0; -const ANCHOR_BADGE_SIZE: f32 = 13.0; -const ANCHOR_BADGE_INSET: f32 = 2.0; -const ANCHOR_BADGE_ICON_SIZE: f32 = 10.0; -/// Space kept clear at each side of an anchor tile's name -const ANCHOR_LABEL_INSET: f32 = 3.0; -const ANCHOR_LABEL_FONT_SIZE: f32 = 9.5; -const ANCHOR_LABEL_GAP: f32 = 3.0; -const ANCHOR_LINE_HEIGHT: f32 = 11.0; +/// The edge tab strip and its tabs +const STRIP_HEIGHT: f32 = 28.0; +const STRIP_ROUNDING: u8 = 6; +const COUNT_SIZE: f32 = 10.0; +const COUNT_GAP: f32 = 4.0; + +/// The search row and its field +const SEARCH_ROW: f32 = 36.0; +const FIELD_HEIGHT: f32 = 24.0; +const FIELD_ROUNDING: u8 = 5; +const SEARCH_TEXT_SIZE: f32 = 12.0; +const SEARCH_ICON_X: f32 = 13.0; +const SEARCH_TEXT_X: f32 = 25.0; +const CLEAR_X: f32 = 13.0; +const CLEAR_SIZE: f32 = 12.0; +const SEARCH_ICON_SIZE: f32 = 13.0; + +/// Air from the popup's border to the search field and the grid, the grid's right room for the scroll bar, air under the grid +const SIDE: f32 = 5.0; +const SCROLL_ROOM: f32 = 10.0; +const BOTTOM: f32 = 6.0; +const POPUP_ROUNDING: u8 = 7; +const BORDER: f32 = 1.0; +const SHADOW_OFFSET: [i8; 2] = [2, 4]; /// Opens the picker `popup_id` with an empty, focused search field, or closes it pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { @@ -59,103 +86,80 @@ pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { 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); + data.insert_temp(opened_id(popup_id), true); }); } -/// Whether picker `popup_id` is open: its tiles are worth gathering only then -pub(crate) fn is_open(ctx: &egui::Context, popup_id: Id) -> bool { - egui::Popup::is_id_open(ctx, popup_id) -} - -/// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) -pub(crate) fn show( +/// Draws picker `popup_id` under `slot` (above it where the window ends first) at its width while open, on the tab holding `current` (scrolled to it when `reveal_current`, else at the top); returns the id clicked, and runs `tabs` only while open +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> { - if !is_open(&slot.ctx, popup_id) { - return None; - } - - let items = items(thumbs); - let tiles = items - .iter() - .map(|item| { - let id = item.id; - let preview = &preview; - ResourcePickerTile { - key: id.to_string(), - label: item.label.to_string(), - group: item.group, - thumbnail: item.thumbnail.clone(), - image: None, - preview: Box::new(move || preview(id)), - } - }) - .collect(); - match popup(slot, popup_id, thumbs, (current, None), tiles, None, |_, _| None) { - Some(ResourcePickerChoice::Resource(key)) => items.iter().find(|item| item.id == key).map(|item| item.id), - _ => None, - } -} - -/// Draws fill source picker `popup_id` at `slot` while open, with its Resources and Anchor points tabs: returns the tile clicked; `current` is the key of the source shown, `current_anchor` the anchor it reads (its tab opens first) -pub(crate) fn show_sources( - slot: &Response, - popup_id: Id, - thumbs: &mut Thumbs, - (current, current_anchor): (Option<&str>, Option), - tiles: Vec>, - anchors: Vec, - picture: impl FnMut(&Ui, LayerId) -> Option, -) -> Option { - if !is_open(&slot.ctx, popup_id) { - return None; - } - - popup(slot, popup_id, thumbs, (current, current_anchor), tiles, Some(anchors), picture) -} - -/// The popup: the tabs when there are anchors to offer, the search field, then the tiles of the shown tab -fn popup( - slot: &Response, - popup_id: Id, - thumbs: &mut Thumbs, - (current, current_anchor): (Option<&str>, Option), - tiles: Vec>, - anchors: Option>, - mut picture: impl FnMut(&Ui, LayerId) -> Option, -) -> Option { + current: Option<&K>, + reveal_current: bool, + tabs: impl FnOnce(&mut Thumbs) -> Vec>, +) -> Option { let ctx = slot.ctx.clone(); + if !egui::Popup::is_id_open(&ctx, popup_id) { + return None; + } + + let tokens = Tokens::get(&ctx); + let tabs = tabs(thumbs); + let width = slot.rect.width() - 2.0 * BORDER; + let frame = Frame::NONE + .fill(tokens.panel) + .stroke(Stroke::new(BORDER, tokens.field_border)) + .corner_radius(CornerRadius::same(POPUP_ROUNDING)) + .shadow(Shadow { offset: SHADOW_OFFSET, blur: 0, spread: 0, color: HARD_SHADOW }); + + // Always its full size, under the slot or above it where the window ends first; only a window too short for it anywhere gets a shorter grid + let head = if tabs.len() > 1 { STRIP_HEIGHT } else { 0.0 } + SEARCH_ROW; + let room = ctx.content_rect().height() - head - BOTTOM - 2.0 * BORDER - 2.0 * WINDOW_MARGIN; + let grid_height = room.clamp(ROW_HEIGHT, GRID_HEIGHT); 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) + .align(egui::RectAlign::BOTTOM_START) + .align_alternatives(&HANG_FALLBACKS) + .gap(POPUP_GAP) + .width(width) + .frame(frame) .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 tab = match &anchors { - Some(_) => tab_strip(ui, popup_id, just_opened && current_anchor.is_some()), - None => ResourcePickerTab::Resources, - }; + ui.set_width(width); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let just_opened = !ui.is_sizing_pass() && ui.data_mut(|data| data.remove_temp::(opened_id(popup_id))).unwrap_or(false); + let current_tab = || current.and_then(|current| tabs.iter().position(|tab| tab.items().any(|item| &item.id == current))); + let stored_tab = ui.data(|data| data.get_temp::(tab_id(popup_id))); + let mut open_tab = + if just_opened { current_tab().or(stored_tab) } else { stored_tab.or_else(current_tab) }.unwrap_or(0).min(tabs.len().saturating_sub(1)); + + let query = search_query(&ui.data(|data| data.get_temp::(search_id(popup_id))).unwrap_or_default()); + if tabs.len() > 1 + && let Some(clicked) = tab_strip(ui, &tabs, open_tab, &query) + { + open_tab = clicked; + } + ui.data_mut(|data| data.insert_temp(tab_id(popup_id), open_tab)); 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 = match (tab, &anchors) { - (ResourcePickerTab::Anchors, Some(anchors)) => { - anchor_grid(ui, anchors, &query, current_anchor, &mut picture).map(ResourcePickerChoice::Anchor) - } - _ => grid(ui, thumbs, &tiles, &query, current, just_opened).map(ResourcePickerChoice::Resource), - }; - }); + + if let Some(tab) = tabs.get(open_tab) { + let reveal = just_opened && reveal_current; + let mut scroll = egui::ScrollArea::vertical().id_salt((popup_id, open_tab)).max_height(grid_height); + + // A new opening with nothing to reveal starts at the top, not where the last one was left + if just_opened && !reveal { + scroll = scroll.vertical_scroll_offset(0.0); + } + scroll.show(ui, |ui| { + // A search that leaves few tiles must not shrink the popup, or egui moves it + ui.set_min_height(grid_height); + picked = grid(ui, thumbs, tab, &query, current, reveal.then_some(grid_height)); + }); + } + ui.add_space(BOTTOM); }); if picked.is_some() { @@ -164,185 +168,275 @@ fn popup( picked } -/// The tabs on the popup's top edge: a darker strip, the shown tab in the body's color so it joins the list below. Returns the shown tab -fn tab_strip(ui: &mut Ui, popup_id: Id, open_anchors: bool) -> ResourcePickerTab { +/// The edge tabs on the popup's top: a chrome strip, the open tab a panel-coloured box joined to the body; while searching each counts its matches +fn tab_strip(ui: &mut Ui, tabs: &[PickerTab], open: usize, query: &str) -> Option { let tokens = Tokens::get(ui.ctx()); - let tab_id = popup_id.with("tab"); - let mut shown = if open_anchors { - ResourcePickerTab::Anchors - } else { - ui.data(|data| data.get_temp::(tab_id)).unwrap_or(ResourcePickerTab::Resources) - }; + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + let top_only = CornerRadius { nw: STRIP_ROUNDING, ne: STRIP_ROUNDING, sw: 0, se: 0 }; + ui.painter().rect_filled(strip, top_only, tokens.chrome); - let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), TAB_STRIP_HEIGHT), Sense::hover()); - let body = ui.visuals().window_fill; - ui.painter().rect_filled(strip, 0.0, body.lerp_to_gamma(egui::Color32::BLACK, TAB_STRIP_DARKEN)); - let font = egui::FontId::proportional(TAB_FONT_SIZE); - let mut left = strip.left() + TAB_INSET; - for (tab, icon, label) in [(ResourcePickerTab::Resources, ic::SQUARES_FOUR, tr("Resources")), (ResourcePickerTab::Anchors, ic::ANCHOR, tr("Anchor points"))] - { - let icon_width = ui.painter().layout_no_wrap(icon.to_string(), font.clone(), tokens.text).size().x; - let label_width = ui.painter().layout_no_wrap(label.to_string(), font.clone(), tokens.text).size().x; - let width = TAB_PADDING * 2.0 + icon_width + TAB_ICON_GAP + label_width; - let rect = egui::Rect::from_min_max(pos2(left, strip.top() + TAB_INSET), pos2(left + width, strip.bottom())); - let response = ui.interact(rect, popup_id.with(label), Sense::click()); - if response.clicked() { - shown = tab; - } - let on = shown == tab; - if on { - ui.painter().rect_filled(rect, egui::CornerRadius { nw: TAB_ROUNDING as u8, ne: TAB_ROUNDING as u8, sw: 0, se: 0 }, body); - } - let color = if on { - tokens.text_strong - } else if response.hovered() { + let mut clicked = None; + let mut left = strip.left() + SIDE; + for (index, tab) in tabs.iter().enumerate() { + let is_open = index == open; + let empty = tab.items().next().is_none(); + let color = if is_open { tokens.text + } else if empty { + tokens.button_border } else { tokens.text_dim }; - let painter = ui.painter(); - painter.text(pos2(rect.left() + TAB_PADDING, rect.center().y), egui::Align2::LEFT_CENTER, icon, font.clone(), color); - painter.text(pos2(rect.left() + TAB_PADDING + icon_width + TAB_ICON_GAP, rect.center().y), egui::Align2::LEFT_CENTER, label, font.clone(), color); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, on, label)); + let name_font = if is_open { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + let name = ui.painter().layout_no_wrap(tab.name.to_owned(), name_font, color); + let count = (!query.is_empty()).then(|| tab.items().filter(|item| item.matches(query)).count()); + let count_galley = count.map(|count| { + let count_color = if count > 0 { tokens.accent } else { tokens.button_border }; + ui.painter().layout_no_wrap(count.to_string(), FontId::proportional(COUNT_SIZE), count_color) + }); + let width = name.size().x + TAB_PADDING + count_galley.as_ref().map_or(0.0, |galley| COUNT_GAP + galley.size().x); + + let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, ui.scope_id().with(("picker_tab", index)), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, is_open, tab.name)); + if is_open { + ui.painter().rect_filled(rect, CornerRadius { nw: TAB_ROUNDING, ne: TAB_ROUNDING, sw: 0, se: 0 }, tokens.panel); + } + let text_color = if response.hovered() && !is_open { tokens.text } else { color }; + let center_y = strip.center().y + TAB_TOP / 2.0; + ui.painter().text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, tab.icon, FontId::proportional(TAB_ICON_SIZE), text_color); + let name_left = left + TAB_NAME_LEFT; + ui.painter().galley(pos2(name_left, center_y - name.size().y / 2.0), name.clone(), text_color); + if let Some(galley) = count_galley { + ui.painter().galley(pos2(name_left + name.size().x + COUNT_GAP, center_y - galley.size().y / 2.0), galley, Color32::PLACEHOLDER); + } + if response.clicked() { + clicked = Some(index); + } left += width + TAB_GAP; } - ui.data_mut(|data| data.insert_temp(tab_id, shown)); - shown + clicked } -/// The search field, focused the frame the picker opens; returns the lowercase query +/// The neutral search field (no accent outline, focused or not), focused the frame the picker opens, × clearing it; returns the lowercase query fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { + let tokens = Tokens::get(ui.ctx()); 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)); + let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), SEARCH_ROW), Sense::hover()); + let field = Rect::from_center_size(row.center(), vec2(row.width() - 2.0 * SIDE, FIELD_HEIGHT)); + let painter = ui.painter(); + painter.rect(field, CornerRadius::same(FIELD_ROUNDING), tokens.field, Stroke::new(BORDER, tokens.field_border), StrokeKind::Inside); + painter.text( + pos2(field.left() + SEARCH_ICON_X, field.center().y), + Align2::CENTER_CENTER, + ic::MAGNIFYING_GLASS, + FontId::proportional(SEARCH_ICON_SIZE), + tokens.text_dim, + ); + + let text_rect = Rect::from_min_max(pos2(field.left() + SEARCH_TEXT_X, field.top()), pos2(field.right() - 2.0 * CLEAR_X, field.bottom())); + let hint = egui::RichText::new(tr("Search")).color(tokens.text_dim).size(SEARCH_TEXT_SIZE); + let edit = egui::TextEdit::singleline(&mut search) + .frame(Frame::NONE) + .hint_text(hint) + .font(semibold(SEARCH_TEXT_SIZE)) + .text_color(tokens.text) + .align(Align2::LEFT_CENTER) + .desired_width(text_rect.width()); + let response = ui.put(text_rect, edit); if just_opened { - field.request_focus(); + response.request_focus(); } - let query = search.trim().to_lowercase(); + if !search.is_empty() { + let clear = Rect::from_center_size(pos2(field.right() - CLEAR_X, field.center().y), vec2(FIELD_HEIGHT, FIELD_HEIGHT)); + let clear = ui.interact(clear, popup_id.with("clear"), Sense::click()); + clear.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Clear search"))); + let color = if clear.hovered() { tokens.text_strong } else { tokens.text }; + ui.painter().text(clear.rect.center(), Align2::CENTER_CENTER, ic::X, FontId::proportional(CLEAR_SIZE), color); + if clear.clicked() { + search.clear(); + response.request_focus(); + } + } + + let query = search_query(&search); ui.data_mut(|data| data.insert_temp(search_id(popup_id), search)); query } -/// A group's title over its tiles, as the shelf's section titles -fn group_header(ui: &mut Ui, text: &str) { +/// The open tab's items matching `query` as tiles under their headers and captions, `current` outlined and, given the grid's height in `reveal_in`, scrolled to; returns the one clicked +fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tab: &PickerTab, query: &str, current: Option<&K>, reveal_in: Option) -> Option { let tokens = Tokens::get(ui.ctx()); - ui.add_space(GROUP_GAP); - ui.label(egui::RichText::new(text).size(GROUP_FONT_SIZE).color(tokens.text)); -} - -/// The tiles matching `query` under group headers, `current` outlined; returns the key of the one clicked -fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tiles: &[ResourcePickerTile<'_>], query: &str, current: Option<&str>, reveal_current: bool) -> Option { - let tokens = Tokens::get(ui.ctx()); - let shown: Vec<&ResourcePickerTile<'_>> = tiles.iter().filter(|tile| shelf::matches(query, &[&tile.label, &tile.key])).collect(); - + let left = ui.max_rect().left() + SIDE; + let cell = (ui.available_width() - SIDE - SCROLL_ROOM) / COLUMNS as f32; let mut picked = None; - for group in shelf::categories(&shown, |tile| tile.group) { - group_header(ui, group); - shelf::tiles(ui, |ui| { - for tile in shown.iter().filter(|tile| tile.group == group) { - let response = shelf::tile( - ui, - thumbs, - |ui, thumbs| { - if let Some(image) = &tile.image { - return Some(thumbs.image(ui.ctx(), &tile.label, image)); - } + let mut place = 0; + for group in &tab.groups { + let shown: Vec<&ResourcePickerItem> = group.items.iter().filter(|item| item.matches(query)).collect(); + if shown.is_empty() { + continue; + } - tile.thumbnail.clone().or_else(|| match (tile.preview)() { - ShelfPreview::Procedural(kind) => thumbs.procedural(ui.ctx(), kind), - _ => None, - }) - }, - || (tile.preview)(), - &tile.label, - None, - ); - - if current == Some(tile.key.as_str()) { - if reveal_current { - response.scroll_to_me(Some(egui::Align::Center)); - } - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tokens.accent), egui::StrokeKind::Inside); - } - - if response.clicked() { - picked = Some(tile.key.clone()); + let group_top = ui.cursor().top(); + if let Some(header) = group.header { + caption_row(ui, left, HEADER_HEIGHT, header, semibold(HEADER_SIZE), tokens.text); + } + let mut caption_top = group_top; + let mut row: Vec<(usize, &ResourcePickerItem)> = Vec::new(); + let mut last_caption = None; + for (index, item) in shown.iter().enumerate() { + if item.caption != last_caption { + flush_row(ui, thumbs, &mut row, left, cell, current, &mut picked); + if let Some(caption) = item.caption { + caption_top = ui.cursor().top(); + caption_row(ui, left, CAPTION_HEIGHT, caption, FontId::proportional(CAPTION_SIZE), tokens.text_dim); } + last_caption = item.caption; } - }); - } - - picked -} - -/// The anchor points matching `query` as tiles: a picture of what each reads, an anchor badge, the layer and the channel -fn anchor_grid( - ui: &mut Ui, - anchors: &[ResourcePickerAnchor], - query: &str, - current: Option, - picture: &mut impl FnMut(&Ui, LayerId) -> Option, -) -> Option { - let tokens = Tokens::get(ui.ctx()); - if anchors.is_empty() { - ui.label(egui::RichText::new(tr("No anchor point below this layer.")).color(tokens.text_dim)); - return None; - } - - let shown: Vec<&ResourcePickerAnchor> = anchors.iter().filter(|anchor| shelf::matches(query, &[&anchor.name, tr(anchor.channel)])).collect(); - let mut picked = None; - shelf::tiles(ui, |ui| { - for anchor in shown { - let response = anchor_tile(ui, anchor, picture); - if current == Some(anchor.anchor) { - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tokens.accent), egui::StrokeKind::Inside); + row.push((place, item)); + place += 1; + if let Some(grid_height) = reveal_in + && current == Some(&item.id) + { + // The current's header or caption shows above it when both fit, so the artist sees where it sits + let row_top = ui.cursor().top(); + let label_top = if item.caption.is_some() { caption_top } else { group_top }; + let from = if row_top + ROW_HEIGHT - label_top <= grid_height { label_top } else { row_top }; + ui.scroll_to_rect(Rect::from_min_max(pos2(left, from), pos2(left + cell, row_top + ROW_HEIGHT)), Some(Align::TOP)); } - if response.clicked() { - picked = Some(anchor.anchor); + if row.len() == COLUMNS || index + 1 == shown.len() { + flush_row(ui, thumbs, &mut row, left, cell, current, &mut picked); } } - }); + } + picked } -/// One anchor tile, the shelf tile's size: the picture, the anchor badge in its corner, the layer's name and the channel under it -fn anchor_tile(ui: &mut Ui, anchor: &ResourcePickerAnchor, picture: &mut impl FnMut(&Ui, LayerId) -> Option) -> Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(ANCHOR_TILE_SIZE, Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &anchor.name)); +/// A header or caption line of `height`, its text `font` in `color` +fn caption_row(ui: &mut Ui, left: f32, height: f32, text: &str, font: FontId, color: Color32) { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + ui.painter().text(pos2(left + HEADER_INSET, rect.center().y), Align2::LEFT_CENTER, text, font, color); +} - // Offscreen tiles must not queue composition of their anchor stacks +/// Lays out the tiles in `row` as one grid row and empties it, recording a click in `picked` +fn flush_row( + ui: &mut Ui, + thumbs: &mut Thumbs, + row: &mut Vec<(usize, &ResourcePickerItem)>, + left: f32, + cell: f32, + current: Option<&K>, + picked: &mut Option, +) { + if row.is_empty() { + return; + } + + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + for (column, (place, item)) in row.drain(..).enumerate() { + let x = left + column as f32 * cell; + let tile = Rect::from_min_max(pos2(x + TILE_SIDE_GAP, rect.top()), pos2(x + cell - TILE_SIDE_GAP, rect.bottom() - TILE_GAP)); + if tile_ui(ui, thumbs, tile, (place, item), current == Some(&item.id)).clicked() { + *picked = Some(item.id.clone()); + } + } +} + +/// One tile, `place` its order in the tab: its picture, its name in up to two lines; hovered = button fill, current = accent outline and a bold name +fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usize, &ResourcePickerItem), chosen: bool) -> Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("picker_tile", place)), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListBoxOption, true, chosen, &item.label)); if !ui.is_rect_visible(rect) { return response; } - let texture = picture(ui, anchor.anchor); + let hovered = response.hovered(); let painter = ui.painter(); - if response.hovered() { - painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover); + if hovered { + painter.rect_filled(rect, CornerRadius::same(TILE_ROUNDING), tokens.button); } - let picture = egui::Rect::from_min_size( - pos2(rect.center().x - ANCHOR_PICTURE_SIZE * 0.5, rect.top() + ANCHOR_PICTURE_TOP), - vec2(ANCHOR_PICTURE_SIZE, ANCHOR_PICTURE_SIZE), - ); - painter.rect_filled(picture, TILE_ROUNDING, tokens.field); - if let Some(texture) = texture { - painter.image(texture, picture, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + if chosen { + painter.rect_stroke(rect, CornerRadius::same(TILE_ROUNDING), Stroke::new(BORDER, tokens.accent), StrokeKind::Inside); } - let badge = egui::Rect::from_min_size( - picture.right_bottom() - vec2(ANCHOR_BADGE_SIZE + ANCHOR_BADGE_INSET, ANCHOR_BADGE_SIZE + ANCHOR_BADGE_INSET), - vec2(ANCHOR_BADGE_SIZE, ANCHOR_BADGE_SIZE), - ); - painter.rect_filled(badge, TILE_ROUNDING, tokens.panel); - painter.text(badge.center(), egui::Align2::CENTER_CENTER, ic::ANCHOR, egui::FontId::proportional(ANCHOR_BADGE_ICON_SIZE), tokens.text); - let font = egui::FontId::proportional(ANCHOR_LABEL_FONT_SIZE); - let width = rect.width() - ANCHOR_LABEL_INSET * 2.0; - let name = crate::widgets::elided(painter, anchor.layer.clone(), ANCHOR_LABEL_FONT_SIZE, tokens.text, width); - let top = picture.bottom() + ANCHOR_LABEL_GAP; - painter.galley(pos2(rect.center().x - name.size().x * 0.5, top), name, tokens.text); - painter.text(pos2(rect.center().x, top + ANCHOR_LINE_HEIGHT), egui::Align2::CENTER_TOP, tr(anchor.channel), font, tokens.text_dim); - response.on_hover_text(&anchor.name) + let picture = Rect::from_min_size(pos2(rect.center().x - PICTURE_SIZE / 2.0, rect.top() + PICTURE_TOP), vec2(PICTURE_SIZE, PICTURE_SIZE)); + let rounding = CornerRadius::same(PICTURE_ROUNDING); + + // A project image's or a pattern's thumbnail is made only once its tile is drawn + let texture = match &item.picture { + TilePicture::Texture(texture) => texture.clone(), + TilePicture::Image(name, image) => Some(thumbs.image(ui.ctx(), name, image)), + TilePicture::Procedural(kind) => thumbs.procedural(ui.ctx(), *kind), + TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, + }; + + match (&item.picture, texture) { + (_, Some(texture)) => { + egui::Image::from_texture((texture.id(), picture.size())).corner_radius(rounding).paint_at(ui, picture); + } + (TilePicture::Texture(_) | TilePicture::Image(..) | TilePicture::Procedural(_), None) => { + painter.text( + picture.center(), + Align2::CENTER_CENTER, + ic::ARROWS_CLOCKWISE, + FontId::proportional(LOADING_GLYPH_SIZE), + tokens.text_dim.gamma_multiply(LOADING_GLYPH_OPACITY), + ); + } + (TilePicture::Swatch(color), None) => { + painter.rect_filled(picture, rounding, *color); + } + (TilePicture::Glyph(glyph), None) => { + painter.rect(picture, rounding, tokens.field, Stroke::new(BORDER, tokens.field_border), StrokeKind::Inside); + painter.text(picture.center(), Align2::CENTER_CENTER, *glyph, FontId::proportional(GLYPH_SIZE), tokens.text_dim); + } + (TilePicture::Import, None) => { + painter.rect(picture, rounding, tokens.field, Stroke::new(BORDER, tokens.field_border), StrokeKind::Inside); + let color = if hovered { tokens.text } else { tokens.text_dim }; + painter.text(picture.center(), Align2::CENTER_CENTER, ic::PLUS, FontId::proportional(IMPORT_GLYPH_SIZE), color); + } + } + name_lines(ui, rect, &item.label, hovered || chosen, chosen); + + response +} + +/// The tile's name under its picture: whole words on the first line, the rest on a second, each cut with "…" when too long +fn name_lines(ui: &Ui, rect: Rect, label: &str, bright: bool, bold: bool) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let color = if bright { tokens.text } else { tokens.text_dim }; + let font = if bold { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + let room = rect.width() - NAME_MARGIN; + let fits = |text: &str| painter.layout_no_wrap(text.to_owned(), font.clone(), color).size().x <= room; + + // Each word's end in the trimmed name, so a first line of whole words is measured as a slice of it + let trimmed = label.trim(); + let prefix = |end: usize| trimmed.get(..end).unwrap_or_default(); + let word_ends = trimmed + .char_indices() + .filter(|(at, character)| character.is_whitespace() && !prefix(*at).ends_with(char::is_whitespace)) + .map(|(at, _)| at) + .chain(std::iter::once(trimmed.len())); + + // Most names fit whole: one measure, and the words are only measured for a name that wraps + let first_line_end = if fits(trimmed) { None } else { word_ends.take_while(|end| fits(prefix(*end))).last() }; + + let (first, second) = match first_line_end { + Some(end) if end < trimmed.len() => (prefix(end), trimmed.get(end..).map(str::trim_start)), + _ => (label, None), + }; + + for (index, line) in std::iter::once(first).chain(second).enumerate() { + let mut job = egui::text::LayoutJob::simple_singleline(line.to_owned(), font.clone(), color); + job.wrap = egui::text::TextWrapping::truncate_at_width(room); + let galley = painter.layout_job(job); + let center = pos2(rect.center().x, rect.top() + NAME_CENTER + index as f32 * NAME_LINE); + painter.galley(center - galley.size() / 2.0, galley, color); + } } /// Where the picker keeps its search text @@ -351,6 +445,11 @@ fn search_id(popup_id: Id) -> Id { } /// Set while the picker waits for its first frame open -fn focus_id(popup_id: Id) -> Id { - popup_id.with("focus") +fn opened_id(popup_id: Id) -> Id { + popup_id.with("opened") +} + +/// The tab the picker shows +fn tab_id(popup_id: Id) -> Id { + popup_id.with("tab") } diff --git a/crates/ui-egui/src/resource_picker_anchor.rs b/crates/ui-egui/src/resource_picker_anchor.rs deleted file mode 100644 index 1b823d62..00000000 --- a/crates/ui-egui/src/resource_picker_anchor.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! One tile of a fill source picker's Anchor points tab - -use texturecraft_engine::core::LayerId; - -/// One tile of the Anchor points tab: the anchor, its layer's name and the channel it is read in -pub(crate) struct ResourcePickerAnchor { - pub anchor: LayerId, - /// The anchor's full name ("layer / anchor"), for its tooltip and screen readers - pub name: String, - pub layer: String, - pub channel: &'static str, -} diff --git a/crates/ui-egui/src/resource_picker_choice.rs b/crates/ui-egui/src/resource_picker_choice.rs deleted file mode 100644 index 432be0db..00000000 --- a/crates/ui-egui/src/resource_picker_choice.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! What a fill source picker's click picked - -use texturecraft_engine::core::LayerId; - -/// What a fill source picker's click picked -pub(crate) enum ResourcePickerChoice { - Resource(String), - Anchor(LayerId), -} diff --git a/crates/ui-egui/src/resource_picker_item.rs b/crates/ui-egui/src/resource_picker_item.rs index 5b9e8071..c568d8c5 100644 --- a/crates/ui-egui/src/resource_picker_item.rs +++ b/crates/ui-egui/src/resource_picker_item.rs @@ -1,9 +1,88 @@ //! 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, +use texturecraft_engine::compose::ImageStore; +use texturecraft_engine::fill_alpha::library_alpha_of; + +use crate::i18n::tr; +use crate::tile_picture::TilePicture; + +/// A resource the picker offers: its id, translated label, the dim sub-caption it sits under, and its picture +pub(crate) struct ResourcePickerItem { + pub id: K, + pub label: String, + pub caption: Option<&'static str>, + pub picture: TilePicture, +} + +impl ResourcePickerItem { + /// A picker's Textures tiles: Import... first, then the project's images sorted by name, library alphas left out; `image` gives an image's id. A thumbnail is made only once its tile is drawn, so opening the picker does not resample every image + pub fn textures(images: &ImageStore, import: K, image: impl Fn(&str) -> K) -> Vec { + let mut named: Vec<_> = images.iter().filter(|(name, _)| library_alpha_of(name).is_none()).collect(); + named.sort_by_key(|(name, _)| *name); + + let mut tiles = vec![Self { id: import, label: tr("Import...").to_owned(), caption: None, picture: TilePicture::Import }]; + tiles.extend(named.into_iter().map(|(name, resource)| Self { + id: image(name), + label: name.clone(), + caption: None, + picture: TilePicture::Image(name.clone(), resource.clone()), + })); + tiles + } + + /// Whether a search for `query` (from [`search_query`]) keeps the item; compares as it lowercases, so the open picker builds no lowercase copy of every label each frame + pub fn matches(&self, query: &str) -> bool { + query.is_empty() || self.label.char_indices().any(|(start, _)| self.label.get(start..).is_some_and(|rest| starts_with_lowercase(rest, query))) + } +} + +/// The search for `text` as [`ResourcePickerItem::matches`] takes it: trimmed and lowercased letter by letter as labels are (a word's last Σ lowercases to σ, as in the label, not to ς) +pub(crate) fn search_query(text: &str) -> String { + text.trim().chars().flat_map(char::to_lowercase).collect() +} + +/// Whether `text`, lowercased, starts with `query` +fn starts_with_lowercase(text: &str, query: &str) -> bool { + let mut lowered = text.chars().flat_map(char::to_lowercase); + query.chars().all(|wanted| lowered.next() == Some(wanted)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An item labelled `label` + fn item(label: &str) -> ResourcePickerItem<()> { + ResourcePickerItem { id: (), label: label.to_owned(), caption: None, picture: TilePicture::Import } + } + + #[test] + fn a_search_finds_a_label_by_any_part_of_it_whatever_its_case() { + assert!(item("Fine Cracks").matches("crack"), "mid-label, an uppercase label found by a lowercase query"); + assert!(item("Fine Cracks").matches("fine c"), "across a space"); + assert!(!item("Fine Cracks").matches("cracked"), "past the label's end"); + assert!(!item("Rust").matches("dust")); + } + + #[test] + fn an_empty_search_keeps_every_item() { + assert!(item("Rust").matches("")); + assert!(item("").matches("")); + } + + #[test] + fn a_search_lowercases_a_label_beyond_ascii() { + assert!(item("ÜBERZUG Grün").matches("überzug")); + assert!(item("ÜBERZUG Grün").matches("grün")); + assert!(item("Ποτάμι").matches("ποτ")); + assert!(!item("Grün").matches("grun"), "an accent is part of the letter"); + } + + #[test] + fn a_search_for_a_whole_label_ending_in_capital_sigma_finds_it() { + let query = search_query(" ΟΣ "); + assert!(item("ΟΣ").matches(&query), "the query lowercases the final Σ as the label does: {query}"); + assert!(item("ΚΟΣΜΟΣ").matches(&search_query("ΚΟΣΜΟΣ"))); + assert!(item("Fine Cracks").matches(&search_query("CRACK"))); + } } diff --git a/crates/ui-egui/src/resource_picker_tab.rs b/crates/ui-egui/src/resource_picker_tab.rs deleted file mode 100644 index 3b9c6b87..00000000 --- a/crates/ui-egui/src/resource_picker_tab.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! The tabs of a fill source picker - -/// The tabs of a fill source picker -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum ResourcePickerTab { - Resources, - Anchors, -} diff --git a/crates/ui-egui/src/resource_picker_tile.rs b/crates/ui-egui/src/resource_picker_tile.rs deleted file mode 100644 index aa601a5d..00000000 --- a/crates/ui-egui/src/resource_picker_tile.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! One tile of a resource picker's Resources tab - -use std::sync::Arc; - -use egui::TextureHandle; -use texturecraft_engine::compose::ImageRes; - -use crate::shelf_preview::ShelfPreview; - -/// One tile of the Resources tab: the key a pick returns, its label and group, its picture and its hover preview -pub(crate) struct ResourcePickerTile<'a> { - pub key: String, - pub label: String, - pub group: &'static str, - pub thumbnail: Option, - pub image: Option>, - pub preview: Box ShelfPreview + 'a>, -} diff --git a/crates/ui-egui/src/slot_thumbnail.rs b/crates/ui-egui/src/slot_thumbnail.rs new file mode 100644 index 00000000..68f972d0 --- /dev/null +++ b/crates/ui-egui/src/slot_thumbnail.rs @@ -0,0 +1,61 @@ +//! The picture a slot card shows of a fill channel's source + +use egui_phosphor::regular as ic; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::Source; + +use crate::TextureCraftApp; +use crate::fill_material_panel::shown_color; +use crate::theme::Tokens; + +/// The picture a slot shows of its source +pub(crate) enum SlotThumbnail { + Swatch(Color32), + Texture(TextureHandle), + /// A picture of the layer stack (an anchor point's), drawn over the field colour where the stack has nothing + Stack(TextureId), + Glyph(&'static str), +} + +/// The picture of `source`: its uniform colour, the procedural's or image's thumbnail, the anchored stack, a glyph for what has none +pub(crate) fn thumbnail(app: &mut TextureCraftApp, ctx: &egui::Context, source: &Source) -> SlotThumbnail { + match source { + Source::Uniform(value) => SlotThumbnail::Swatch(shown_color(*value)), + Source::Procedural { pattern, .. } => app.thumbs.procedural(ctx, pattern.kind).map_or(SlotThumbnail::Glyph(ic::WAVE_SINE), SlotThumbnail::Texture), + Source::Image { name, .. } => match app.session.images.get(name).cloned() { + Some(image) => SlotThumbnail::Texture(app.thumbs.image(ctx, name, &image)), + None => SlotThumbnail::Glyph(ic::IMAGE), + }, + // The stack the anchor point keeps, as the Layers panel shows that point (the glyph while it renders) + Source::Anchor { anchor, channel, .. } => app + .layer_panel + .texture_outside(ctx, &app.session, ThumbTarget::Stage { effect: *anchor, channel: *channel }) + .map_or(SlotThumbnail::Glyph(ic::ANCHOR), SlotThumbnail::Stack), + } +} + +/// The glyph size of a slot without a picture +const GLYPH_SIZE: f32 = 14.0; + +/// The whole of a texture, as the part of it a picture shows +pub(crate) const FULL_UV: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + +/// Paints `thumbnail` into a slot's square +pub(crate) fn paint_thumbnail(painter: &Painter, rect: Rect, thumbnail: &SlotThumbnail, tokens: &Tokens) { + match thumbnail { + SlotThumbnail::Swatch(color) => { + painter.rect_filled(rect, CornerRadius::ZERO, *color); + } + SlotThumbnail::Texture(texture) => { + painter.image(texture.id(), rect, FULL_UV, Color32::WHITE); + } + SlotThumbnail::Stack(texture) => { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + painter.image(*texture, rect, FULL_UV, Color32::WHITE); + } + SlotThumbnail::Glyph(glyph) => { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + painter.text(rect.center(), Align2::CENTER_CENTER, *glyph, FontId::proportional(GLYPH_SIZE), tokens.text_dim); + } + } +} diff --git a/crates/ui-egui/src/source_choice.rs b/crates/ui-egui/src/source_choice.rs new file mode 100644 index 00000000..907c2963 --- /dev/null +++ b/crates/ui-egui/src/source_choice.rs @@ -0,0 +1,14 @@ +//! What a fill slot's source picker offers + +use texturecraft_engine::core::{LayerId, ProceduralKind}; + +/// A source the slot's picker offers +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum SourceChoice { + Uniform, + Procedural(ProceduralKind), + Image(String), + Alpha(&'static str), + Import, + Anchor(LayerId), +} diff --git a/crates/ui-egui/src/source_slot.rs b/crates/ui-egui/src/source_slot.rs new file mode 100644 index 00000000..3de5e7b2 --- /dev/null +++ b/crates/ui-egui/src/source_slot.rs @@ -0,0 +1,67 @@ + +use serde_json::{Value, json}; + +use crate::i18n::tr; + +/// The one source a slot card edits, and how its values read +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum SourceSlot { + Channel(Channel), +} + +impl SourceSlot { + /// The slot's name on its card + pub(crate) fn name(self) -> &'static str { + match self { + SourceSlot::Channel(channel) => tr(channel.label()), + } + } + + /// What the slot's values are + pub(crate) fn kind(self) -> ChannelKind { + match self { + SourceSlot::Channel(channel) => channel.kind(), + } + } + + pub(crate) fn default_value(self) -> [f32; 3] { + match self { + SourceSlot::Channel(channel) => channel.default_value(), + } + } + + /// The range a uniform value or a procedural's two ends run over + pub(crate) fn range(self) -> std::ops::RangeInclusive { + if self.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 } + } + + pub(crate) fn procedural_ends(self) -> ([f32; 3], [f32; 3]) { + /// Base color stays off pure black and white, which read as unlit or blown out + const BASE_COLOR_ENDS: ([f32; 3], [f32; 3]) = ([0.15; 3], [0.85; 3]); + + /// Height stays a shallow relief around flat, as a full −1..1 swing reads as deep cuts + const HEIGHT_ENDS: ([f32; 3], [f32; 3]) = ([-0.05; 3], [0.05; 3]); + + /// The other channels keep off their extremes, so the pattern changes the surface without flattening it to one end + const CHANNEL_ENDS: ([f32; 3], [f32; 3]) = ([0.2; 3], [0.8; 3]); + + match self { + SourceSlot::Channel(Channel::BaseColor) => BASE_COLOR_ENDS, + SourceSlot::Channel(Channel::Height) => HEIGHT_ENDS, + SourceSlot::Channel(_) => CHANNEL_ENDS, + } + } + + pub(crate) fn fields(self) -> Value { + match self { + SourceSlot::Channel(channel) => json!({"channel": channel.id()}), + } + } + + /// A key for the slot's own widget state + pub(crate) fn key(self) -> &'static str { + match self { + SourceSlot::Channel(channel) => channel.id(), + } + } +} diff --git a/crates/ui-egui/src/tile_picture.rs b/crates/ui-egui/src/tile_picture.rs new file mode 100644 index 00000000..3d938a19 --- /dev/null +++ b/crates/ui-egui/src/tile_picture.rs @@ -0,0 +1,17 @@ +//! What a resource picker's tile shows + +use std::sync::Arc; + +use egui::{Color32, TextureHandle}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; + +/// What a tile shows: a thumbnail (none while it renders), a project image or a pattern (its thumbnail made only once the tile is drawn), a colour, a glyph, or the import square +pub(crate) enum TilePicture { + Texture(Option), + Image(String, Arc), + Procedural(ProceduralKind), + Swatch(Color32), + Glyph(&'static str), + Import, +} diff --git a/crates/ui-egui/tests/it/source_picker.rs b/crates/ui-egui/tests/it/source_picker.rs new file mode 100644 index 00000000..23214a4b --- /dev/null +++ b/crates/ui-egui/tests/it/source_picker.rs @@ -0,0 +1,209 @@ +//! A fill channel's source picker: Resources | Anchor points tabs, Procedurals / Textures / Alphas / Uniform tiles, a search, opened on the current source + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{Channel, LayerId, LayerKind, ProceduralKind, Source}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, assert_list_leaves_the_wheel_and_closes, click_widget}; + +/// Tall enough that Properties shows a fill's cards and an open picker without scrolling the panel +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1600.0); +/// Frames for the grid's scroll to the current tile to finish its animation +const SCROLL_FRAMES: usize = 25; +/// A channel slot low in the Material card, with too little room under it for the picker in [`WINDOW_SIZE`] +const SLOT_LOW_IN_THE_CARD: &str = "Height"; +/// The tile the picker shows first on its Resources tab +const FIRST_TILE: &str = "Clouds"; +/// A window with room for the picker under every slot +const TALL_WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 3200.0); +/// A window too short for the picker under Roughness's slot, so the snapshot shows it opened above +const SNAPSHOT_WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1000.0); +/// Frames for the hovered tile's fill to show before the snapshot +const HOVER_FRAMES: usize = 8; +/// A wheel turn down over the grid, enough to scroll it past its first row +const GRID_WHEEL: egui::Vec2 = egui::vec2(0.0, -400.0); + +/// The app with a new fill layer selected on its Material tab, the layer's id; `prepare` runs on the session first +fn app_with_fill(prepare: impl FnOnce(&mut texturecraft_engine::Session, LayerId)) -> (Harness<'static, TextureCraftApp>, LayerId) { + 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 = LayerId(added["layer"].as_u64().unwrap()); + prepare(&mut session, layer); + 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(STARTUP_FRAMES); + click_widget(&mut harness, Role::Tab, "Material"); + (harness, layer) +} + +fn source(harness: &Harness<'_, TextureCraftApp>, layer: LayerId, channel: Channel) -> Source { + match &harness.state().session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.source(channel), + other => panic!("not a fill: {other:?}"), + } +} + +/// Clicks the slot named `slot`, which opens or closes its picker +fn click_slot(harness: &mut Harness<'_, TextureCraftApp>, slot: &str) { + click_widget(harness, Role::ComboBox, slot); +} + +/// Clicks the picker's tile labelled `label` +fn click_tile(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + click_widget(harness, Role::ListBoxOption, label); +} + +fn type_search(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + harness.event(egui::Event::Text(text.into())); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn a_procedural_tile_sets_the_channel_and_closes_the_picker() { + let (mut harness, layer) = app_with_fill(|_, _| {}); + click_slot(&mut harness, "Roughness"); + assert!(harness.query_by_role_and_label(Role::Tab, "Resources").is_some(), "the picker has its Resources tab"); + assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "and its Anchor points tab"); + + click_tile(&mut harness, FIRST_TILE); + let Source::Procedural { pattern, .. } = source(&harness, layer, Channel::Roughness) else { panic!("a procedural") }; + assert_eq!(pattern.kind, ProceduralKind::Clouds); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); + + // The Uniform tile at the end of Resources puts the channel back to a uniform value + click_slot(&mut harness, "Roughness"); + type_search(&mut harness, "uniform"); + click_tile(&mut harness, "Uniform value"); + assert_eq!(source(&harness, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness)); +} + +#[test] +fn an_alpha_from_the_search_becomes_the_channels_source() { + let (mut harness, layer) = app_with_fill(|_, _| {}); + click_slot(&mut harness, "Roughness"); + + // The search field has the focus as the picker opens and searches every Resources group + type_search(&mut harness, "crack"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Clouds").is_none(), "the search hides what doesn't match"); + click_widget(&mut harness, Role::Button, "Clear search"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Clouds").is_some(), "× clears the search"); + type_search(&mut harness, "crack"); + + click_tile(&mut harness, "Cracks"); + let Source::Image { name, .. } = source(&harness, layer, Channel::Roughness) else { panic!("an alpha is read as an image") }; + assert_eq!(texturecraft_engine::fill_alpha::library_alpha_of(&name).map(|alpha| alpha.label.as_str()), Some("Cracks")); +} + +#[test] +fn the_picker_opens_on_the_current_sources_tab_scrolled_to_it() { + let (mut harness, layer) = app_with_fill(|session, layer| { + let stencil = json!({"layer": layer.0, "channel": "roughness", "alpha": "letter_z"}); + texturecraft_engine::execute(session, "layer.fill.set", &stencil).unwrap(); + }); + assert!(matches!(source(&harness, layer, Channel::Roughness), Source::Image { .. })); + click_slot(&mut harness, "Roughness"); + harness.run_steps(SCROLL_FRAMES); + + // The last alpha sits far below the picker's first rows; it shows, outlined as the current + let tile = harness.get_by_role_and_label(Role::ListBoxOption, "Stencil Z"); + assert_eq!(tile.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the current tile is outlined"); + let picker = picker_rect(&harness, "Stencil Z"); + assert!(picker.contains_rect(tile.rect()), "the current tile is scrolled into view: {:?} in {picker:?}", tile.rect()); +} + +#[test] +fn the_anchor_points_tab_lists_the_stacks_anchors() { + // An anchor on the first fill, then a second fill above it reads the anchor + let (mut harness, _) = app_with_fill(|session, layer| { + texturecraft_engine::execute(session, "effect.add.anchor", &json!({"layer": layer.0, "name": "Edge wear"})).unwrap(); + texturecraft_engine::execute(session, "layer.add.fill", &json!({})).unwrap(); + }); + let reader = harness.state().session.selected_layer().unwrap(); + click_slot(&mut harness, "Roughness"); + click_widget(&mut harness, Role::Tab, "Anchor points"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Clouds").is_none(), "the tab shows anchors only"); + + let anchor = harness.get_all_by_role(Role::ListBoxOption).find_map(|node| node.accesskit_node().label().filter(|label| label.contains("Edge wear"))); + click_tile(&mut harness, &anchor.expect("the anchor below is offered")); + assert!(matches!(source(&harness, reader, Channel::Roughness), Source::Anchor { .. })); +} + +#[test] +fn escape_or_a_click_outside_closes_it_and_the_wheel_still_zooms_the_view() { + let (mut harness, layer) = app_with_fill(|_, _| {}); + assert_list_leaves_the_wheel_and_closes(&mut harness, |harness| { + click_slot(harness, "Roughness"); + + // The search takes the focus, which would keep Escape from the list + harness.ctx.memory_mut(|memory| memory.stop_text_input()); + harness.get_by_role_and_label(Role::ComboBox, "Roughness").rect() + }); + + // Opened again from Uniform after a scroll down, it starts at the top + click_slot(&mut harness, "Roughness"); + let clouds = |harness: &Harness<'_, TextureCraftApp>| harness.get_by_role_and_label(Role::ListBoxOption, FIRST_TILE).rect(); + let first_tile = clouds(&harness); + harness.hover_at(first_tile.center()); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: GRID_WHEEL, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(SCROLL_FRAMES); + assert!(clouds(&harness).top() < first_tile.top(), "the wheel over the picker scrolls its grid"); + click_slot(&mut harness, "Roughness"); + click_slot(&mut harness, "Roughness"); + assert_eq!(clouds(&harness), first_tile, "the first tile shows again"); + assert_eq!(source(&harness, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness), "nothing changed"); +} + +/// The open picker's popup: the area under its shown tile `label` +fn picker_rect(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { + let tile = harness.get_by_role_and_label(Role::ListBoxOption, label).rect().center(); + let layer = harness.ctx.layer_id_at(tile).expect("a layer under the tile"); + harness.ctx.memory(|memory| memory.area_rect(layer.id)).expect("the picker's area") +} + +#[test] +fn near_the_windows_bottom_the_picker_opens_above_its_slot_at_full_size() { + let (mut harness, _) = app_with_fill(|_, _| {}); + click_slot(&mut harness, SLOT_LOW_IN_THE_CARD); + let slot = harness.get_by_role_and_label(Role::ComboBox, SLOT_LOW_IN_THE_CARD).rect(); + let shown = picker_rect(&harness, FIRST_TILE); + assert!(shown.bottom() <= slot.top(), "with no room under the slot it opens above it, never over it: {shown:?} {slot:?}"); + assert!(harness.ctx.content_rect().contains_rect(shown), "inside the window: {shown:?}"); + click_slot(&mut harness, SLOT_LOW_IN_THE_CARD); + + harness.set_size(TALL_WINDOW_SIZE); + harness.run_steps(SETTLE_FRAMES); + click_slot(&mut harness, SLOT_LOW_IN_THE_CARD); + let slot = harness.get_by_role_and_label(Role::ComboBox, SLOT_LOW_IN_THE_CARD).rect(); + let roomy = picker_rect(&harness, FIRST_TILE); + assert!(roomy.top() >= slot.bottom(), "a tall window has room under the slot: {roomy:?} {slot:?}"); + assert!((shown.height() - roomy.height()).abs() < 0.5, "above the slot the picker keeps its full height: {shown:?} vs {roomy:?}"); +} + +#[test] +#[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered view"] +fn picker_above_its_slot_snapshot() { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let mut harness = Harness::builder().with_size(SNAPSHOT_WINDOW_SIZE).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + click_widget(&mut harness, Role::Tab, "Material"); + click_slot(&mut harness, "Roughness"); + harness.hover_at(harness.get_by_role_and_label(Role::ListBoxOption, FIRST_TILE).rect().center()); + harness.run_steps(HOVER_FRAMES); + let image = harness.render().unwrap(); + if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { + image.save(std::path::Path::new(&directory).join("picker-above-slot.png")).unwrap(); + } +} From 5afbbbe08b09de3dcaff8393dfaa6cac8067cbb9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:27 +0000 Subject: [PATCH 019/153] Fills: the Material section with Material | Channels and linked materials --- crates/engine/src/link_cmds.rs | 140 ++- crates/engine/src/link_cmds/link_job.rs | 2 +- crates/ui-egui/src/fill_material_panel.rs | 617 ++++++++++++++ crates/ui-egui/tests/it/fill_material_rows.rs | 800 ++++++++++++++++++ 4 files changed, 1544 insertions(+), 15 deletions(-) create mode 100644 crates/ui-egui/src/fill_material_panel.rs create mode 100644 crates/ui-egui/tests/it/fill_material_rows.rs diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 1fcf5b34..bf4df701 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -1,17 +1,18 @@ //! MaterialCraft materials as fill layers. A `.mcmat` portable material becomes a fill whose //! channel sources are its cooked maps (image resources) and whose [`MaterialLink`] keeps the //! graph's exposed parameters. Changing one re-cooks the maps through `materialcraft-cli` at the -//! texture set's resolution, with the set's baked mesh maps feeding graph inputs of the same name. -//! Both apps use the shared craft-mcmat container and the public CLI. +//! layer's picked resolution (default: the texture set's), with the set's baked mesh maps feeding graph inputs of the same name; +//! both apps use the shared craft-mcmat container and the public CLI +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Map, Value, json}; -use texturecraft_core::{Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source}; +use texturecraft_core::{Channel, CookResolution, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source}; use texturecraft_formats::RamReservation as CookReservation; use texturecraft_formats::mcmat::{MCRAFT_EXT, is_mcmat, is_mcraft, validate_mcmat_version}; -use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp}; +use crate::commands::{CommandSpec, bad, boolp, channel_param, has_layer, layer_param, strp}; use crate::materials::Place; use crate::{EngineError, Result, Session, cmd}; @@ -61,13 +62,31 @@ pub fn specs() -> Vec { "Re-cook MaterialCraft material", [], None, - "{layer?} — re-cooks a MaterialCraft material layer at its texture set's resolution with the set's baked mesh maps", + "{layer?} — re-cooks a MaterialCraft material layer at its picked resolution (default: the texture set's) with the set's baked mesh maps", has_layer, |s, p| { let id = layer_param(s, "material.link.cook", p)?; cook(s, id, Map::new()) } ), + cmd!( + "material.link.map", + "Map material channel", + [], + None, + "{layer?, channel, output} — makes a channel of a MaterialCraft material layer read another output of the material (an output id such as \"roughness\")", + has_layer, + map + ), + cmd!( + "material.link.resolution", + "Set material resolution", + [], + None, + "{layer?, relative: -3..3 | fixed: 128..8192 (power of two), cook?: true} — the size a MaterialCraft material layer cooks at: the texture set's resolution times 2^relative (0 = the texture set's), or fixed pixels across", + has_layer, + resolution + ), cmd!( "material.link.saveSource", "Save MaterialCraft package", @@ -192,6 +211,81 @@ fn update(s: &mut Session, cmd: &str, id: LayerId, overrides: impl IntoIterator< Ok(json!({"layer": id.0, "cooked": false})) } +fn map(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "material.link.map"; + let id = layer_param(s, CMD, p)?; + let channel = channel_param(CMD, p, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?; + let output = strp(p, "output").ok_or_else(|| bad(CMD, "`output` is required"))?; + link_of(s, CMD, id)?; + s.edit("Map material channel", |s| { + let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(id)?.kind else { return Ok(()) }; + let outputs = fill.link_outputs(); + let image = outputs.get(output).ok_or_else(|| bad(CMD, format!("the material has no output `{output}`")))?.clone(); + let normal_format = match fill.sources.get(&channel) { + Some(Source::Image { normal_format, .. }) => *normal_format, + _ => Default::default(), + }; + fill.sources.insert(channel, Source::Image { name: image, normal_format }); + if let Some(link) = &mut fill.link { + if output == channel.id() { + link.mapping.remove(&channel); + } else { + link.mapping.insert(channel, output.to_string()); + } + + // Sources no longer name every output once one is mapped elsewhere + link.outputs = outputs; + } + Ok(()) + })?; + Ok(json!({"layer": id.0, "channel": channel.id(), "output": output})) +} + +/// The `relative` or `fixed` param of `material.link.resolution`; `Some(None)` is the texture set's own size +pub(crate) fn picked_resolution(p: &Value) -> Option> { + let integer = |key: &str| p.get(key).and_then(Value::as_i64); + match (integer("relative"), integer("fixed")) { + (Some(factor), None) => { + let factor = i8::try_from(factor).ok().filter(|factor| CookResolution::FACTORS.contains(factor))?; + Some((factor != 0).then_some(CookResolution::Relative(factor))) + } + (None, Some(size)) => u32::try_from(size).ok().filter(|size| CookResolution::cookable(*size)).map(|size| Some(CookResolution::Fixed(size))), + _ => None, + } +} + +fn resolution(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "material.link.resolution"; + let id = layer_param(s, CMD, p)?; + let size = picked_resolution(p).ok_or_else(|| bad(CMD, "give `relative` (-3..3) or `fixed` (a power of two from 128 to 8192)"))?; + let link = link_of(s, CMD, id)?; + let store = |s: &mut Session| { + s.edit(EDIT, |s| { + if let LayerKind::Fill(Fill { link: Some(link), .. }) = &mut s.doc.project.layer_mut(id)?.kind { + link.resolution = size; + } + Ok(()) + }) + }; + if !boolp(p, "cook").unwrap_or(true) { + // Only the stored size changes, so the size it already has adds no undo step + if link.resolution != size { + store(s)?; + } + + return Ok(json!({"layer": id.0, "cooked": false})); + } + + // Cook first so a failed cook changes nothing, then store and swap the maps as one step + let mut job = s.link_job(id, &Map::new())?; + let (texture_set, _, _) = s.doc.project.locate(id).ok_or_else(|| bad(CMD, format!("layer {} is not in a stack", id.0)))?; + job.size = size.unwrap_or(CookResolution::TEXTURE_SET).size(s.doc.project.texture_set(texture_set)?.resolution); + let material = job.run()?; + store(s)?; + s.apply_link_cook(id, &material, true)?; + Ok(json!({"layer": id.0, "cooked": true, "size": job.size})) +} + fn cook(s: &mut Session, id: LayerId, overrides: Map) -> Result { let job = s.link_job(id, &overrides)?; let material = job.run()?; @@ -377,6 +471,9 @@ impl Session { presets: m.interface.presets.clone(), inputs: m.interface.inputs.iter().map(|i| i.identifier.clone()).collect(), size: m.size, + resolution: None, + mapping: BTreeMap::new(), + outputs: BTreeMap::new(), }; let mut fill = Fill { link: Some(Box::new(link)), ..Fill::default() }; let names = put_maps(s, &stem, &m.maps, &mut fill); @@ -447,14 +544,12 @@ impl Session { let mut values = self.link_values(id)?; values.extend(overrides.clone()); - // UDIM tiles share one cook at the texture set's base resolution - let size = self.doc.project.texture_set(texture_set)?.resolution; Ok(LinkJob { layer: id, package: self.link_package(id)?, source_ext: source_extension(&link.package), graph: Some(link.graph.clone()), - size, + size: self.link_size(id)?, values, input_identifiers: link.inputs, baked: self.doc.baked.get(&texture_set).cloned(), @@ -463,6 +558,14 @@ impl Session { }) } + /// Pixels across linked layer `id` cooks at: its picked resolution, else its texture set's + pub fn link_size(&self, id: LayerId) -> Result { + let link = link_of(self, "material.link", id)?; + let (texture_set, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("layer {} is not in a stack", id.0)))?; + // UDIM tiles share one cook at the texture set's base resolution + Ok(link.resolution.unwrap_or(CookResolution::TEXTURE_SET).size(self.doc.project.texture_set(texture_set)?.resolution)) + } + /// Install the maps and exposed values returned by a completed [`LinkJob`]. /// With `merge`, this folds into the previous undo step when that was an edit of the same kind /// (a parameter set while the cook ran). @@ -481,8 +584,9 @@ impl Session { } link.size = material.size; let stem = texturecraft_formats::sanitize_resource_name(&link.name); - let old_names: Vec = + let mut old_names: Vec = fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect(); + old_names.extend(fill.link_outputs().into_values()); let names = put_maps(session, &stem, &material.maps, &mut fill); session.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill); @@ -537,26 +641,34 @@ fn unique(session: &Session, stem: &str, suffix: &str) -> String { format!("{stem}{suffix}") } -/// Store `maps` as new resources (names carry a fresh id, so the decoded-image cache never -/// confuses two cooks) and point `fill`'s channels at them. Returns the names, in map order. +/// Store `maps` as new resources (names carry a fresh id, so the decoded-image cache never confuses two cooks), list them as the link's outputs and point `fill`'s channels at them: each channel at its mapped output, else at the output named like it. Returns the names, in map order fn put_maps(s: &mut Session, stem: &str, maps: &[CookedMap], fill: &mut Fill) -> Vec { let cook = s.doc.project.alloc_id().0; let mut names = Vec::new(); + let mut outputs = BTreeMap::new(); for map in maps { let channel = map.channel; let extension = if map.bytes.starts_with(crate::resource_cmds::EXR_SIGNATURE) { "exr" } else { "png" }; let name = unique(s, stem, &format!("_{}_{cook}.{extension}", channel.id())); s.doc.resources.insert(name.clone(), Arc::clone(&map.bytes)); + outputs.insert(channel.id().to_string(), name.clone()); + names.push(name); + } - // Preserve a normal convention the user chose for this layer + // Both callers cook a linked fill; one without a link only keeps the stored maps + let Some(link) = fill.link.as_mut() else { return names }; + let channels: BTreeSet = maps.iter().map(|map| map.channel).chain(link.mapping.keys().copied()).collect(); + for channel in channels { + let Some(name) = outputs.get(link.output_of(channel)) else { continue }; + + // A normal map the user marked DirectX stays marked through re-cooks let normal_format = match fill.sources.get(&channel) { Some(Source::Image { normal_format, .. }) => *normal_format, _ => Default::default(), }; fill.sources.insert(channel, Source::Image { name: name.clone(), normal_format }); - names.push(name); } - + link.outputs = outputs; names } diff --git a/crates/engine/src/link_cmds/link_job.rs b/crates/engine/src/link_cmds/link_job.rs index 56d57ec1..dba31f78 100644 --- a/crates/engine/src/link_cmds/link_job.rs +++ b/crates/engine/src/link_cmds/link_job.rs @@ -21,7 +21,7 @@ pub struct LinkJob { pub source_ext: &'static str, /// The named graph in a linked material; direct package imports use its default. pub graph: Option, - /// Pixels across (the texture set's resolution). + /// Pixels across: the layer's picked resolution (default: the texture set's) pub size: u32, /// Every parameter's value, by id, in MaterialCraft's typed form. pub values: Map, diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs new file mode 100644 index 00000000..23776d76 --- /dev/null +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -0,0 +1,617 @@ +//! A fill's Material section: the channel strip, the orb with the Material | Channels switch, then one slot card per channel that is on (Channels) or the fill's whole material (Material) + +use std::collections::HashMap; +use std::sync::Arc; + +use egui::{Color32, Painter, Rect}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::compose::{ImageRes, ImageStore}; +use texturecraft_engine::core::{ + Channel, ChannelKind, CookResolution, Fill, LayerId, LinkParam, MaterialLink, NormalFormat, OutputResolution, Procedural, ProceduralKind, ResolutionMode, + Source, +}; +use texturecraft_engine::fill_alpha::library_alpha_of; +use texturecraft_engine::fill_material_cmds::whole_materials; +use texturecraft_engine::materials::find; +use texturecraft_engine::paint::alphas; +use texturecraft_engine::texel::linear_to_srgb; + +use crate::TextureCraftApp; +use crate::color_picker::{ColorPick, SwatchEdit}; +use crate::dock::{anchors_below, project_effect_anchors_below, with}; +use crate::fill_panel::{FillKey, fill_key}; +use crate::i18n::{n_, tr}; +use crate::material_orb::material_orb; +use crate::orb_material::OrbMaterial; +use crate::pattern_panel::tile_generator_sections; +use crate::pattern_target::PatternTarget; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::PropertySheet; +use crate::resolution_band::{resolution_band, resolution_row}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::slot_thumbnail::{paint_thumbnail, thumbnail}; +use crate::source_choice::SourceChoice; +use crate::source_slot::SourceSlot; +use crate::state::UiState; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; +use crate::tile_picture::TilePicture; +use crate::widgets::press_edit; + +/// The switch's two sides: the fill's whole material, or one source per channel +const MODES: [&str; 2] = [n_("Material"), n_("Channels")]; + +/// The switch's side that shows the fill's whole material +const MATERIAL_MODE: usize = 0; + +/// The switch's side that shows one source per channel +const CHANNELS_MODE: usize = 1; + +/// Decimals a linked material's number input shows +const FLOAT_DECIMALS: usize = 2; + +/// Pattern scale a procedural's slider runs over (typed values stay inside it too) +const PATTERN_SCALE: std::ops::RangeInclusive = 0.1..=32.0; + +/// Pattern contrast a procedural's slider runs over +const PATTERN_CONTRAST: std::ops::RangeInclusive = 0.0..=2.0; + +/// Pattern balance a procedural's slider runs over: below the middle darker, above lighter +const PATTERN_BALANCE: std::ops::RangeInclusive = -1.0..=1.0; + +/// The size a pattern's Resolution reads the texture set at when none is open: a new project's default +const FALLBACK_TEXTURE_SET_SIZE: u32 = 2048; + +/// The Material section of the fill at `base`; `on` holds the channels the fill writes +pub(crate) fn material_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { + sheet.section(tr("Material"), false); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + let names: Vec<&str> = channels.iter().map(|channel| tr(pill_name(*channel))).collect(); + let enabled: Vec = channels.iter().map(|channel| on.contains(channel)).collect(); + if let Some((index, solo)) = sheet.channel_pills(&names, &enabled) + && let Some(channel) = channels.get(index) + { + let enable = solo || !enabled.get(index).copied().unwrap_or(false); + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "enabled": enable, "solo": solo}))); + } + + let tokens = Tokens::get(sheet.ui.ctx()); + let salt = fill_key(base); + let look = OrbMaterial::of_fill(fill, on, &app.session.images); + let channel_look = channel_orb_look(&app.ui, fill, on, &app.session.images); + let shown = channel_look.as_ref().unwrap_or(&look); + let orb = |painter: &Painter, rect: Rect| material_orb(painter, rect, shown, &tokens, ("orb", salt)); + let link = fill.link.as_deref().zip(base.get("layer").and_then(Value::as_u64)).map(|(link, layer)| (link, LayerId(layer))); + let mode_id = sheet.ui.make_persistent_id(("material_mode", salt)); + + // A fill opens on the side that made it: a material (linked or built-in) on Material, separate sources on Channels + let made_whole = link.is_some() || fill.material.is_some(); + let mode = sheet.ui.data(|data| data.get_temp::(mode_id)).unwrap_or(if made_whole { MATERIAL_MODE } else { CHANNELS_MODE }); + let modes = MODES.map(tr); + if let Some(picked) = sheet.orb_switch(&orb, &modes, mode) { + sheet.ui.data_mut(|data| data.insert_temp(mode_id, picked)); + } + + match link { + Some((link, layer)) if mode == MATERIAL_MODE => { + let shown: Vec = channels.into_iter().filter(|channel| on.contains(channel)).collect(); + material_card(app, sheet, link, layer, &look, salt); + mapping_band(app, sheet, fill, &shown, layer); + let texture_set = texture_set_size(app, link.size); + let picked = resolution_band(sheet, link.resolution.unwrap_or(CookResolution::TEXTURE_SET), texture_set).filter(|_| LINK_EDITABLE); + if let Some(picked) = picked { + let size = resolution_json(picked); + if app.run("material.link.resolution", with(&json!({"layer": layer.0, "cook": false}), size)).is_some() { + app.cook_link(layer); + } + } + #[cfg(not(target_arch = "wasm32"))] + if sheet.button(ic::ARROW_SQUARE_OUT, tr("Open in MaterialCraft")).clicked() { + crate::dock::open_link_in_materialcraft(app, layer, link); + } + } + None if mode == MATERIAL_MODE => whole_material_card(app, sheet, fill, base, &look, salt), + _ => { + for channel in channels.into_iter().filter(|channel| on.contains(channel)) { + source_card(app, sheet, fill.source(channel), base, SourceSlot::Channel(channel), reader, false); + } + } + } +} + +/// Whether a linked material's settings can change here: a change cooks it again, which needs the MaterialCraft CLI the browser has not got (it shows them as they were cooked) +const LINK_EDITABLE: bool = cfg!(not(target_arch = "wasm32")); + +/// What the orb shows instead of the whole material, following the Layers panel's channel list: the channel picked there alone (None: the whole material) +fn channel_orb_look(ui: &UiState, fill: &Fill, on: &[Channel], images: &HashMap>) -> Option { + (!ui.layer_material_view).then(|| OrbMaterial::of_channel(fill, ui.layer_channel, on, images)) +} + +/// `resolution` as the commands read it: `{"relative": factor}` or `{"fixed": size}` +fn resolution_json(resolution: CookResolution) -> Value { + match resolution { + CookResolution::Relative(factor) => json!({"relative": factor}), + CookResolution::Fixed(size) => json!({"fixed": size}), + } +} + +/// The size of the texture set being painted, `fallback` when none is +fn texture_set_size(app: &TextureCraftApp, fallback: u32) -> u32 { + app.session.doc.project.texture_set(app.session.ts()).map_or(fallback, |texture_set| texture_set.resolution) +} + +/// A channel's name on its pill: the reference strip's short Title Case words, the full name where it has none +pub(crate) fn pill_name(channel: Channel) -> &'static str { + match channel { + Channel::BaseColor => n_("Color"), + Channel::Metallic => n_("Metal"), + Channel::Roughness => n_("Rough"), + Channel::Normal => n_("Normal"), + Channel::Height => n_("Height"), + Channel::Opacity => n_("Opacity"), + other => other.label(), + } +} + +/// A linear colour as the sRGB colour the screen shows +pub(crate) fn shown_color(linear: [f32; 3]) -> Color32 { + let [r, g, b] = linear.map(|channel_value| (linear_to_srgb(channel_value.clamp(0.0, 1.0)) * 255.0).round() as u8); + Color32::from_rgb(r, g, b) +} + +/// What the slot's source line says +pub(crate) fn source_line(app: &TextureCraftApp, source: &Source) -> String { + match source { + Source::Uniform(_) => tr("Uniform").to_owned(), + Source::Procedural { pattern, .. } => format!("{} · {}", tr(pattern.kind.label()), tr("procedural")), + Source::Image { name, .. } => match library_alpha_of(name) { + Some(alpha) => format!("{} · {}", tr(&alpha.label), tr("alpha")), + None => format!("{name} · {}", tr("image")), + }, + Source::Anchor { anchor, .. } => { + let name = app.session.doc.project.effect(*anchor).map_or_else(|| tr("missing").to_owned(), |(_, effect)| effect.name.clone()); + format!("{} · {name}", tr("Anchor")) + } + } +} + +pub(crate) fn source_card( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + source: Source, + base: &Value, + slot_of: SourceSlot, + reader: LayerId, + in_card: bool, +) { + let set = |extra: Value| with(base, with(&slot_of.fields(), extra)); + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); + let line = source_line(app, &source); + let uniform = matches!(source, Source::Uniform(_)); + let procedural = matches!(source, Source::Procedural { .. }); + let thumb = |painter: &egui::Painter, rect: egui::Rect| paint_thumbnail(painter, rect, &picture, &tokens); + let slot = if in_card { + sheet.slot_in_card(&thumb, slot_of.name(), &line, !uniform) + } else { + sheet.slot(&thumb, slot_of.name(), &line, None, !uniform, procedural) + }; + + let popup = sheet.ui.make_persistent_id(("source_picker", fill_key(base), slot_of.key())); + if slot.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = source_choice(&source); + + // From Uniform the picker opens at the top, not at its Uniform tile at the end + let reveal = current != SourceChoice::Uniform; + let uniform = match source { + Source::Uniform(value) => value, + _ => slot_of.default_value(), + }; + let ctx = sheet.ui.ctx().clone(); + + // The anchors below the reader are listed only while the picker is open; an effect's (an instance's inherited mask fill) must also sit below the effect's owner + let effect = base.get("effect").and_then(Value::as_u64).map(LayerId); + let tabs = |thumbs: &mut Thumbs| { + let anchors = match effect { + Some(effect) => project_effect_anchors_below(&app.session.doc.project, reader, effect), + None => anchors_below(&app.session.doc.project, reader), + }; + source_tabs(thumbs, &ctx, &app.session.images, &anchors, shown_color(uniform)) + }; + let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), reveal, tabs); + if let Some(choice) = picked.filter(|choice| *choice != current) { + pick_source(app, sheet.ui.ctx(), slot_of, choice, &set); + } + if slot.clear { + app.run("layer.fill.set", set(json!({"value": slot_of.default_value()}))); + } + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("layer.fill.set", set(json!({"image": name}))); + } + + // A slot in a mode's card shows a pattern's Scale and Contrast like every slot; its other rows and Resolution band would split the card + if in_card { + if let Source::Procedural { pattern, .. } = source { + let mut edited = pattern.clone(); + if let Some((key, value, merge)) = scale_and_contrast(sheet, &mut edited) { + let mut settings = json!({"procedural": pattern.kind.label(), "merge": merge}); + settings[key] = value; + app.run("layer.fill.set", set(settings)); + } + } + return; + } + match source { + Source::Uniform(value) => uniform_rows(app, sheet, slot_of, value, &set), + Source::Procedural { pattern, low, high, .. } => procedural_rows(app, sheet, slot_of, &pattern, [low, high], slot.reset, &set), + Source::Image { normal_format, .. } if slot_of.kind() == ChannelKind::NormalMap => { + if sheet.fold(tr("Attributes"), None, false) { + let formats = [tr("OpenGL"), tr("DirectX")]; + let chosen = usize::from(normal_format == NormalFormat::DirectX); + if let Some(picked) = sheet.switch(tr("Normal format"), &formats, chosen) { + app.run("layer.fill.set", set(json!({"normalFormat": if picked == 1 { "directX" } else { "openGl" }}))); + } + } + } + Source::Image { .. } | Source::Anchor { .. } => {} + } + sheet.close_card(); +} + +/// Runs the fill command `choice` asks for on the slot (Import opens the import dialog) +fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSlot, choice: SourceChoice, set: &impl Fn(Value) -> Value) { + match choice { + SourceChoice::Uniform => { + app.run("layer.fill.set", set(json!({"value": slot_of.default_value()}))); + } + SourceChoice::Procedural(kind) => { + let (low, high) = slot_of.procedural_ends(); + app.run("layer.fill.set", set(json!({"procedural": kind.label(), "low": low, "high": high}))); + } + SourceChoice::Image(name) => { + app.run("layer.fill.set", set(json!({"image": name}))); + } + SourceChoice::Alpha(id) => { + app.run("layer.fill.set", set(json!({"alpha": id}))); + } + SourceChoice::Import => crate::menus::invoke(app, ctx, "resource.import"), + SourceChoice::Anchor(anchor) => { + app.run("layer.fill.set", set(json!({"anchor": anchor.0}))); + } + } +} + +/// The picker's choice `source` is: a library alpha's image is its alpha + match source { + Source::Uniform(_) => SourceChoice::Uniform, + Source::Procedural { pattern, .. } => SourceChoice::Procedural(pattern.kind), + Source::Image { name, .. } => library_alpha_of(name).map_or_else(|| SourceChoice::Image(name.clone()), |alpha| SourceChoice::Alpha(alpha.id.as_str())), + Source::Anchor { anchor, .. } => SourceChoice::Anchor(*anchor), + } +} + +/// The source picker's tabs: Resources (Procedurals, Textures with Import... first, Alphas in their shelf groups, Uniform) and the stack's Anchor points + let procedurals = + ProceduralKind::ALL.into_iter().map(|kind| tile(SourceChoice::Procedural(kind), tr(kind.label()), None, TilePicture::Procedural(kind))).collect(); + let textures = ResourcePickerItem::textures(images, SourceChoice::Import, |name| SourceChoice::Image(name.to_owned())); + let alphas = alphas::library() + .iter() + .map(|alpha| { + let picture = TilePicture::Texture(thumbs.alpha(ctx, alpha)); + tile(SourceChoice::Alpha(alpha.id.as_str()), tr(&alpha.label), Some(tr(alpha.category)), picture) + }) + .collect(); + let uniform = vec![tile(SourceChoice::Uniform, tr("Uniform value"), None, TilePicture::Swatch(uniform))]; + let resources = [(n_("Procedurals"), procedurals), (n_("Textures"), textures), (n_("Alphas"), alphas), (n_("Uniform"), uniform)] + .into_iter() + .map(|(header, items)| PickerGroup { header: Some(tr(header)), items }) + .collect(); + let anchors = anchors.iter().map(|(anchor, label)| tile(SourceChoice::Anchor(*anchor), label, None, TilePicture::Glyph(ic::ANCHOR))).collect(); + vec![ + PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups: resources }, + PickerTab { icon: ic::ANCHOR, name: tr("Anchor points"), groups: vec![PickerGroup { header: None, items: anchors }] }, + ] +} + +/// One tile of the source picker +fn tile(id: SourceChoice, label: &str, caption: Option<&'static str>, picture: TilePicture) -> ResourcePickerItem { + ResourcePickerItem { id, label: label.to_owned(), caption, picture } +} + +/// A uniform source: the colour bar (a click opens the picker) or the gray ramp with its invert glyph +fn uniform_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, slot_of: SourceSlot, value: [f32; 3], set: &impl Fn(Value) -> Value) { + let label = slot_of.name(); + if slot_of.kind() == ChannelKind::Color { + let pick = sheet.color_bar(label, value, app.picking_color, &app.session.doc.project.swatches); + if let Some(color) = take_color_pick(app, pick) { + app.run("layer.fill.set", set(json!({"color": color, "merge": pick.merge}))); + } + return; + } + let mut gray = value[0]; + let edit = sheet.ramp(label, &mut gray, slot_of.range()); + if edit.invert { + let inverted = if slot_of.kind() == ChannelKind::Signed { -gray } else { 1.0 - gray }; + app.run("layer.fill.set", set(json!({"value": inverted}))); + } else if let Some(merge) = edit.changed { + app.run("layer.fill.set", set(json!({"value": gray, "merge": merge}))); + } +} + +/// The colour `pick` picked, after starting or ending an eyedropper pick its eyedropper asked for and making the change its Swatches row asked for +pub(crate) fn take_color_pick(app: &mut TextureCraftApp, pick: ColorPick) -> Option<[f32; 3]> { + if pick.eyedropper { + app.picking_color = if app.picking_color == Some(pick.id) { None } else { Some(pick.id) }; + } + match pick.swatch { + Some(SwatchEdit::Add(color)) => { + app.run("swatch.add", json!({"color": color})); + } + Some(SwatchEdit::Remove(index)) => { + app.run("swatch.remove", json!({"index": index})); + } + None => {} + } + pick.picked +} + +/// A pattern's Scale and Contrast rows; returns the edit (key, value, whether it continues a drag) +fn scale_and_contrast(sheet: &mut PropertySheet<'_>, edited: &mut Procedural) -> Option<(&'static str, Value, bool)> { + let mut edit = None; + if let Some(merge) = sheet.slider(tr("Scale"), &mut edited.scale, PATTERN_SCALE, 2) { + edit = Some(("scale", json!(edited.scale), merge)); + } + if let Some(merge) = sheet.slider(tr("Contrast"), &mut edited.contrast, PATTERN_CONTRAST, 2) { + edit = edit.or(Some(("contrast", json!(edited.contrast), merge))); + } + edit +} + +/// A pattern's Balance and Seed rows; returns the edit like [`scale_and_contrast`] +fn balance_and_seed(sheet: &mut PropertySheet<'_>, edited: &mut Procedural) -> Option<(&'static str, Value, bool)> { + let mut edit = None; + if let Some(merge) = sheet.signed_slider(tr("Balance"), &mut edited.balance, PATTERN_BALANCE, 2) { + edit = Some(("balance", json!(edited.balance), merge)); + } + if sheet.seed(tr("Seed"), &mut edited.seed) { + edit = edit.or(Some(("seed", json!(edited.seed), false))); + } + edit +} + +/// A procedural source: Scale and Contrast, then its Attributes (seed, balance, invert and its two values), each sending only its own parameter +fn procedural_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + slot_of: SourceSlot, + pattern: &Procedural, + [low, high]: [[f32; 3]; 2], + reset: bool, + set: &impl Fn(Value) -> Value, +) { + let kind = pattern.kind.label(); + if reset { + let fresh = Procedural::new(pattern.kind); + let settings = json!({ + "procedural": kind, "scale": fresh.scale, "contrast": fresh.contrast, "seed": fresh.seed, + "balance": fresh.balance, "invert": fresh.invert, "low": low, "high": high, "merge": false, + "resolution": "auto", "customResolution": fresh.resolution.custom, "resolutionFactor": fresh.resolution.factor, + }); + app.run("layer.fill.set", set(settings)); + return; + } + + let mut edited = pattern.clone(); + let mut edit = scale_and_contrast(sheet, &mut edited); + if sheet.fold(tr("Attributes"), None, false) { + edit = edit.or(balance_and_seed(sheet, &mut edited)); + if sheet.toggle(tr("Invert"), &mut edited.invert) { + edit = edit.or(Some(("invert", json!(edited.invert), false))); + } + let ends = [("low", tr("Low"), low), ("high", tr("High"), high)]; + if slot_of.kind() == ChannelKind::Color { + for (key, label, value) in ends { + let pick = sheet.color_bar_led(label, value, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + edit = edit.or(Some((key, json!(picked), pick.merge))); + } + } + } else { + for (key, label, value) in ends { + let mut gray = value[0]; + if let Some(merge) = sheet.slider(label, &mut gray, slot_of.range(), 2) { + edit = edit.or(Some((key, json!([gray, gray, gray]), merge))); + } + } + } + } + + // The size the pattern is made at, as a cooked texture would be (the texture set's own by default) + let texture_set = texture_set_size(app, FALLBACK_TEXTURE_SET_SIZE); + if let Some(picked) = resolution_row(sheet, band_size(pattern.resolution, texture_set), texture_set) { + let size = match picked { + CookResolution::Relative(factor) => json!({"resolution": "auto", "resolutionFactor": factor}), + CookResolution::Fixed(size) => json!({"resolution": "custom", "customResolution": size, "resolutionFactor": 0}), + }; + app.run("layer.fill.set", set(with(&json!({"procedural": kind}), size))); + return; + } + if let Some((key, value, merge)) = edit { + let mut settings = json!({"procedural": kind, "merge": merge}); + settings[key] = value; + app.run("layer.fill.set", set(settings)); + } + + // The Tile Generator's own parameters and image inputs follow the rows every pattern has + if let Some(tile) = pattern.tile.as_deref() { + let base = set(json!({"low": low, "high": high})); + let target = PatternTarget { command: "layer.fill.set", salt: base.to_string(), base }; + sheet.embed(|ui| tile_generator_sections(app, ui, &target, pattern, tile)); + } +} + +/// The Resolution band's reading of a pattern's saved output resolution: a size of its own is Fixed, any other follows the texture set +fn band_size(resolution: OutputResolution, texture_set: u32) -> CookResolution { + match resolution.mode { + ResolutionMode::Custom => CookResolution::Fixed(resolution.output_size(texture_set, texture_set)), + _ => CookResolution::Relative(resolution.factor), + } +} + +/// The Material side: the fill's whole material in one card (the row lists its presets), its inputs, then opening it in MaterialCraft +fn material_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, link: &MaterialLink, layer: LayerId, look: &OrbMaterial, salt: FillKey) { + let tokens = Tokens::get(sheet.ui.ctx()); + let base = json!({"layer": layer.0, "cook": false}); + let slot = sheet.slot(&|painter, rect| material_orb(painter, rect, look, &tokens, ("card", salt)), &link.name, tr("Material"), None, false, false); + let presets: Vec = (0..link.presets.len()).collect(); + let preset_name = |index: usize| link.presets.get(index).map(|preset| preset.name.clone()).unwrap_or_default(); + let editable = LINK_EDITABLE; + if editable + && let (Some(index), _) = sheet.hanging_list(&slot.pick, usize::MAX, &presets, &preset_name, None) + && app.run("material.link.preset", with(&base, json!({"name": preset_name(index)}))).is_some() + { + app.cook_link(layer); + } + + let pending = sheet.ui.make_persistent_id(("material_cook_pending", layer.0)); + for param in &link.params { + if let Some((value, merge)) = link_input(sheet, layer, param, editable) + && app.run("material.link.set", with(&base, json!({"id": param.id, "value": value, "merge": merge}))).is_some() + { + sheet.ui.data_mut(|data| data.insert_temp(pending, true)); + } + } + + // A drag stores every step; the maps re-cook once the pointer lets go + let waiting = sheet.ui.data(|data| data.get_temp::(pending)).unwrap_or(false); + if waiting && !sheet.ui.input(|input| input.pointer.any_down()) { + sheet.ui.data_mut(|data| data.remove::(pending)); + app.cook_link(layer); + } + sheet.close_card(); +} + +/// The Material side of a fill without a linked material: one card holding the built-in material its sources came from (the row lists every plain material, × returns the channels to their defaults) +fn whole_material_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, look: &OrbMaterial, salt: FillKey) { + let tokens = Tokens::get(sheet.ui.ctx()); + let held = fill.material.as_deref().and_then(find); + let name = held.map_or_else(|| tr("None"), |material| tr(material.label)); + let slot = sheet.slot(&|painter, rect| material_orb(painter, rect, look, &tokens, ("card", salt)), name, tr("Material"), None, held.is_some(), false); + let popup = sheet.ui.make_persistent_id(("material_picker", salt)); + if slot.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = held.map(|material| material.id); + let ctx = sheet.ui.ctx().clone(); + let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), |thumbs| material_tabs(&ctx, thumbs)); + if let Some(id) = picked.filter(|id| Some(*id) != current) { + app.run("layer.fill.material", with(base, json!({"material": id}))); + } + if slot.clear { + app.run("layer.fill.material", with(base, json!({"material": null}))); + } + sheet.close_card(); +} + +/// The material picker's one tab: every plain material's preview ball, grouped under its shelf category in library order +fn material_tabs(ctx: &egui::Context, thumbs: &mut Thumbs) -> Vec> { + let mut groups: Vec> = Vec::new(); + for material in whole_materials() { + let item = ResourcePickerItem { + id: material.id, + label: tr(material.label).to_owned(), + caption: None, + picture: TilePicture::Texture(thumbs.material(ctx, material.id)), + }; + let header = Some(tr(material.category)); + match groups.iter_mut().find(|group| group.header == header) { + Some(group) => group.items.push(item), + None => groups.push(PickerGroup { header, items: vec![item] }), + } + } + vec![PickerTab { icon: ic::SPHERE, name: tr("Materials"), groups }] +} + +/// Channels mapping: which of the material's outputs each channel that is on reads +fn mapping_band(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, shown: &[Channel], layer: LayerId) { + let Some(link) = &fill.link else { return }; + if !sheet.band(tr("Channels mapping"), true, None, None).open { + return; + } + + let outputs: Vec = fill.link_outputs().into_keys().collect(); + let indices: Vec = (0..outputs.len()).collect(); + for channel in shown { + let reads = link.output_of(*channel); + let current = outputs.iter().position(|output| output == reads).unwrap_or(usize::MAX); + let name = |index: usize| outputs.get(index).map_or(reads, String::as_str).to_owned(); + if let (Some(index), _) = sheet.dropdown(tr(channel.label()), current, &indices, name, None) + && let Some(output) = outputs.get(index) + { + app.run("material.link.map", json!({"layer": layer.0, "channel": channel.id(), "output": output})); + } + } +} + +/// One input of the material: a slider for numbers, a toggle, a dropdown for choices, an egui editor for colours and vectors; its new typed value when it changed and whether it continues a drag +fn link_input(sheet: &mut PropertySheet<'_>, layer: LayerId, param: &LinkParam, editable: bool) -> Option<(Value, bool)> { + let kind = param.default.get("t").and_then(Value::as_str).unwrap_or(""); + let value = param.value.get("v").unwrap_or(&Value::Null); + let number = value.as_f64().unwrap_or(0.0) as f32; + let (low, high) = if param.max > param.min { (param.min, param.max) } else { (0.0, 1.0) }; + let changed = match kind { + "bool" => { + let mut on = value.as_bool().unwrap_or(number != 0.0); + sheet.toggle(¶m.label, &mut on).then(|| (json!(on), false)) + } + "enum" if !param.options.is_empty() => { + let options: Vec = (0..param.options.len()).collect(); + let name = |index: usize| param.options.get(index).cloned().unwrap_or_default(); + sheet.dropdown(¶m.label, number.max(0.0) as usize, &options, name, None).0.map(|index| (json!(index), false)) + } + "float" => { + let mut edited = number; + sheet.slider(¶m.label, &mut edited, low.min(number)..=high.max(number), FLOAT_DECIMALS).map(|merge| (json!(edited), merge)) + } + "int" | "enum" => { + let mut edited = number; + let moved = sheet.slider(¶m.label, &mut edited, low.min(number)..=high.max(number), 0).is_some(); + + // Whole numbers: a press's first whole-number change starts its undo step, moves that round to the value it has send nothing (no step, no cook) + let whole = edited.round(); + let press = sheet.ui.make_persistent_id(("link_input_press", layer.0, ¶m.id)); + press_edit(sheet.ui, press, moved && whole != number).map(|merge| (json!(whole), merge)) + } + + // Colours and vectors keep their egui editors until the sheet draws them + _ => sheet.embed(|ui| crate::dock::link_param_editor(ui, layer, param)), + }; + changed.filter(|_| editable) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_orb_shows_the_channel_the_layers_panel_shows_and_the_whole_material_on_material() { + let mut ui = UiState::default(); + let on = [Channel::BaseColor, Channel::Roughness]; + + let whole = OrbMaterial::of_fill(&Fill::default(), &on, &HashMap::new()); + let starting = channel_orb_look(&ui, &Fill::default(), &on, &HashMap::new()); + ui.layer_material_view = false; + ui.layer_channel = Channel::Roughness; + let roughness = channel_orb_look(&ui, &Fill::default(), &on, &HashMap::new()).unwrap(); + + assert!(starting.is_none(), "the list starts on Material: the whole material"); + assert_eq!(whole.alone(), None); + assert_eq!(roughness.alone(), Some(Channel::Roughness)); + assert_ne!(whole.key(), roughness.key(), "a new pick draws a new orb"); + } +} diff --git a/crates/ui-egui/tests/it/fill_material_rows.rs b/crates/ui-egui/tests/it/fill_material_rows.rs new file mode 100644 index 00000000..0e20a2df --- /dev/null +++ b/crates/ui-egui/tests/it/fill_material_rows.rs @@ -0,0 +1,800 @@ +//! A fill's Material section: the channel strip turns channels on and off, each slot's row lists the sources, ⟲ and × restore and clear, the ramp inverts, a linked material maps its channels and picks its resolution + +use std::sync::Arc; + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::{Channel, CookResolution, LayerId, LayerKind, LinkParam, MaterialLink, Procedural, ProceduralKind, Source}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::screen_pick::{PickOutcome, ScreenPick}; + +use crate::fill_support::{click_node, fill_app, fill_of}; +use crate::filter_support::{along, click_at, drag, undo_depth}; +use crate::{SETTLE_FRAMES, TEXTURE_RESOLUTION}; + +/// Tall enough that Properties shows the whole fill and an open source list without scrolling +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1600.0); + +/// Frames for the shelf's and the picker's thumbnails to render a few per frame, enough for every pattern were all of them asked for +const THUMBNAIL_FRAMES: usize = 200; + +/// Frames for a scroll to bring a control into view +const SCROLL_FRAMES: usize = 25; + +/// The app with a new fill layer (`settings` given to layer.add.fill) selected and its Material tab clicked, and the layer's id +fn app_with_fill(settings: serde_json::Value) -> (Harness<'static, TextureCraftApp>, LayerId) { + fill_app(settings, None, Some("Material"), WINDOW_SIZE) +} + +/// The source `channel` of the fill `layer` reads +fn source(harness: &Harness<'_, TextureCraftApp>, layer: LayerId, channel: Channel) -> Source { + fill_of(harness, layer).source(channel) +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + // A link without a package fails to re-cook with a toast, which must not take the click + harness.state_mut().toasts.clear(); + click_node(harness, role, label); +} + +/// Scrolls the `role` named `label` into view (the scroll animates for about twenty frames), then clicks it +fn click_below(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + click(harness, role, label); +} + +/// Clicks the eyedropper at the end of the Base color bar's row in the panel (the open picker has its own) +fn click_bar_eyedropper(harness: &mut Harness<'_, TextureCraftApp>) { + let bar = harness.get_by_role_and_label(Role::Button, "Base color").rect(); + let eyedropper = harness + .get_all_by_role_and_label(Role::Button, "Pick color") + .find(|node| bar.y_range().contains(node.rect().center().y) && node.rect().left() >= bar.right()) + .unwrap() + .rect(); + click_at(harness, eyedropper.center()); +} + +/// Clicks the open picker's own eyedropper, beside its hex field +fn click_picker_eyedropper(harness: &mut Harness<'_, TextureCraftApp>) { + let hex = harness.get_by_role_and_label(Role::TextInput, "Hex color").rect(); + let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); + let in_picker_row = |at: egui::Pos2| hex.y_range().contains(at.y) && at.x >= hex.right() && at.x <= title.right() + CLOSE_ROOM; + let eyedropper = harness.get_all_by_role_and_label(Role::Button, "Pick color").map(|node| node.rect().center()).find(|at| in_picker_row(*at)).unwrap(); + click_at(harness, eyedropper); +} + +/// Clicks the `role` named `label` that sits in the row of the slot named `slot` (bands above have their own ⟲) +fn click_in_slot(harness: &mut Harness<'_, TextureCraftApp>, slot: &str, role: Role, label: &str) { + let row = harness.get_by_role_and_label(Role::ComboBox, slot).rect(); + let at = harness.get_all_by_role_and_label(role, label).map(|node| node.rect().center()).find(|at| row.contains(*at)).unwrap(); + click_at(harness, at); +} + +#[test] +fn the_channel_strip_turns_a_channel_and_its_card_off_and_on() { + let (mut harness, layer) = app_with_fill(json!({})); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "Metallic is on: its card shows"); + + click(&mut harness, Role::CheckBox, "Metal"); + let channels = &harness.state().session.doc.project.layer(layer).unwrap().channels; + assert!(!channels.contains_key(&Channel::Metallic), "off in the strip, the fill stops writing Metallic"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "a channel that is off has no card"); + + click(&mut harness, Role::CheckBox, "Metal"); + assert!(harness.state().session.doc.project.layer(layer).unwrap().channels.contains_key(&Channel::Metallic)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some()); +} + +#[test] +fn a_slot_lists_its_sources_restores_a_procedural_and_clears_back_to_uniform() { + let (mut harness, layer) = app_with_fill(json!({})); + click(&mut harness, Role::ComboBox, "Metallic"); + click(&mut harness, Role::ListBoxOption, ProceduralKind::Clouds.label()); + let Source::Procedural { pattern, .. } = source(&harness, layer, Channel::Metallic) else { panic!("a procedural") }; + assert_eq!(pattern.kind, ProceduralKind::Clouds); + assert!(harness.query_by_role_and_label(Role::Slider, "Contrast").is_some(), "a procedural shows its Scale and Contrast"); + + texturecraft_engine::execute( + &mut harness.state_mut().session, + "layer.fill.set", + &json!({"layer": layer.0, "channel": "metallic", "procedural": "Clouds", "scale": 9.0, "seed": 7}), + ) + .unwrap(); + harness.run_steps(SETTLE_FRAMES); + click_in_slot(&mut harness, "Metallic", Role::Button, "Restore defaults"); + let Source::Procedural { pattern, .. } = source(&harness, layer, Channel::Metallic) else { panic!("still a procedural") }; + assert_eq!(pattern, Procedural::new(ProceduralKind::Clouds), "⟲ keeps the pattern and restores its settings"); + + click_in_slot(&mut harness, "Metallic", Role::Button, "Clear"); + assert_eq!(source(&harness, layer, Channel::Metallic), Source::uniform_of(Channel::Metallic), "× goes back to a uniform value"); +} + +/// A pattern's thumbnail is made only once its tile is drawn: a search renders the patterns it shows, not every pattern +#[test] +fn searching_the_source_picker_renders_only_the_shown_pattern_thumbnails() { + let (mut harness, layer) = app_with_fill(json!({})); + let pattern_thumbnails = |harness: &Harness<'_, TextureCraftApp>| { + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("thumb_proc:")).count() + }; + click(&mut harness, Role::ComboBox, "Metallic"); + harness.event(egui::Event::Text("Smooth fur".into())); + harness.run_steps(THUMBNAIL_FRAMES); + + let after_search = pattern_thumbnails(&harness); + let rendered = |name: &str| harness.ctx.tex_manager().read().allocated().any(|(_, texture)| texture.name == name); + assert!(rendered("thumb_proc:SmoothFur"), "the pattern the search shows gets its thumbnail"); + assert!(after_search < ProceduralKind::ALL.len(), "{after_search} of {} pattern thumbnails made", ProceduralKind::ALL.len()); + + click(&mut harness, Role::ListBoxOption, ProceduralKind::SmoothFur.label()); + let Source::Procedural { pattern, .. } = source(&harness, layer, Channel::Metallic) else { panic!("a procedural") }; + assert_eq!(pattern.kind, ProceduralKind::SmoothFur); + assert_eq!(pattern_thumbnails(&harness), after_search, "the pick reuses the thumbnail it showed"); + + let context = harness.ctx.clone(); + drop(harness); + let left = context.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("thumb_proc:")).count(); + assert_eq!(left, 0, "closing the app releases the pattern thumbnails"); +} + +/// A project image's thumbnail is made once its tile scrolls into view, not when the picker opens, and goes with the image +#[test] +fn source_picker_images_render_on_scroll_and_release_on_removal() { + const IMAGE_COUNT: usize = 128; + const IMAGE_SIDE: u32 = 64; + let (mut harness, layer) = app_with_fill(json!({})); + let session = &mut harness.state_mut().session; + for index in 0..IMAGE_COUNT { + let name = format!("picker-image-{index:03}.png"); + let texels = (IMAGE_SIDE * IMAGE_SIDE) as usize; + session.doc.resources.insert(name.clone(), Arc::new(vec![0])); + session.images.insert(name, Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[0.5; 4]; texels], false))); + } + let image_thumbnails = |harness: &Harness<'_, TextureCraftApp>| { + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("res_picker-image-")).count() + }; + + click(&mut harness, Role::ComboBox, "Metallic"); + harness.run_steps(THUMBNAIL_FRAMES); + let opened = image_thumbnails(&harness); + assert!(opened < IMAGE_COUNT, "opening the picker makes thumbnails only for the tiles in view: {opened}"); + + let last = format!("picker-image-{:03}.png", IMAGE_COUNT - 1); + harness.get_by_role_and_label(Role::ListBoxOption, &last).scroll_to_me(); + harness.run_steps(THUMBNAIL_FRAMES); + let scrolled = image_thumbnails(&harness); + assert!(scrolled > opened, "a scroll makes the thumbnails of the tiles it brings into view: {opened} -> {scrolled}"); + click(&mut harness, Role::ListBoxOption, &last); + assert_eq!(source(&harness, layer, Channel::Metallic), Source::image(last)); + + let app = harness.state_mut(); + app.session.images.clear(); + app.thumbs.sync_images(&app.session.images, app.session.revision + 1); + assert_eq!(image_thumbnails(&harness), 0, "removed images release their picker thumbnails"); +} + +/// Dragging the pattern's Contrast changes only the contrast: the pattern keeps its balance, invert, seed, scale and values +#[test] +fn dragging_a_pattern_slider_changes_only_its_own_parameter() { + let (mut harness, layer) = app_with_fill(json!({})); + let pattern = json!({ + "layer": layer.0, "channel": "metallic", "procedural": "Clouds", "scale": 9.0, "contrast": 1.0, "seed": 7, + "balance": 0.25, "invert": true, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8], + }); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.set", &pattern).unwrap(); + harness.run_steps(SETTLE_FRAMES); + let Source::Procedural { pattern: before, low, high, .. } = source(&harness, layer, Channel::Metallic) else { panic!("a procedural") }; + + harness.get_by_role_and_label(Role::Slider, "Contrast").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + let track = harness.get_by_role_and_label(Role::Slider, "Contrast").rect(); + let from = track.center(); + drag(&mut harness, from, from + egui::vec2(track.width() / 4.0, 0.0)); + + let Source::Procedural { pattern: after, low: after_low, high: after_high, .. } = source(&harness, layer, Channel::Metallic) else { + panic!("still a procedural") + }; + + assert_ne!(after.contrast, before.contrast, "the drag changes the contrast"); + assert_eq!(Procedural { contrast: before.contrast, ..after }, before, "the rest of the pattern stays"); + assert_eq!((after_low, after_high), (low, high), "the pattern's values stay"); +} + +#[test] +fn a_uniform_gray_ramp_inverts_its_value() { + let (mut harness, layer) = app_with_fill(json!({"roughness": 0.3})); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "solo": true})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + click(&mut harness, Role::Button, "Invert"); + let Source::Uniform(value) = source(&harness, layer, Channel::Roughness) else { panic!("uniform") }; + assert!((value[0] - 0.7).abs() < 1e-5, "1 - 0.3: {value:?}"); +} + +#[test] +fn a_linked_material_shows_its_inputs_and_the_switch_shows_its_channels() { + let (mut harness, layer) = app_with_fill(json!({})); + assert!(harness.query_by_role_and_label(Role::RadioButton, "Material").is_some(), "every fill has the switch"); + + let wear = float_param("wear", "Wear", 0.5); + link_fill(&mut harness, layer, vec![wear], &[]); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Painted steel").is_some(), "the Material side shows the whole material"); + assert!(harness.query_by_role_and_label(Role::Slider, "Wear").is_some(), "with its inputs"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "and no channel cards"); + + click(&mut harness, Role::RadioButton, "Channels"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "the Channels side shows a card per channel"); + assert!(harness.query_by_role_and_label(Role::Slider, "Wear").is_none()); +} + +/// A drag on a linked material's number input is one undo step, however many frames it spans +#[test] +fn dragging_a_linked_material_input_adds_one_undo_step() { + let (mut harness, layer) = app_with_fill(json!({})); + let wear = float_param("wear", "Wear", 0.25); + link_fill(&mut harness, layer, vec![wear], &[]); + let steps = undo_depth(&harness); + + let track = harness.get_by_role_and_label(Role::Slider, "Wear").rect(); + let from = track.center(); + drag(&mut harness, from, from + egui::vec2(track.width() / 4.0, 0.0)); + + let fill = fill_of(&harness, layer); + assert_ne!(fill.link.as_deref().unwrap().params[0].value, json!({"t": "float", "v": 0.25}), "the drag changes the input"); + assert_eq!(undo_depth(&harness), steps + 1, "every frame of the drag merges into one step"); +} + +/// A click inside a linked whole-number input's current band is no edit (no undo step, no re-cook); a drag across whole numbers is one step +#[test] +fn a_linked_whole_number_input_changes_only_on_a_new_whole_number() { + let (mut harness, layer) = app_with_fill(json!({})); + let rings = LinkParam { value: json!({"t": "int", "v": 3}), default: json!({"t": "int", "v": 3}), max: 10.0, ..float_param("rings", "Rings", 0.0) }; + link_fill(&mut harness, layer, vec![rings], &[]); + harness.state_mut().toasts.clear(); + let steps = undo_depth(&harness); + let track = harness.get_by_role_and_label(Role::Slider, "Rings").rect(); + + // A link without a package fails to re-cook with a toast: no toast, no cook + click_at(&mut harness, along(track, 0.32)); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(undo_depth(&harness), steps, "3.2 rounds to the 3 the input holds: no undo step"); + assert!(harness.state().toasts.is_empty(), "and no re-cook"); + + drag(&mut harness, along(track, 0.3), along(track, 0.53)); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(fill_of(&harness, layer).link.unwrap().params[0].value, json!({"t": "int", "v": 5}), "the drag ends on 5"); + assert_eq!(undo_depth(&harness), steps + 1, "the drag's whole numbers merge into one step"); +} + +/// A drag in a linked material's colour picker is one undo step, however many frames it spans +#[test] +fn dragging_in_a_linked_colour_picker_adds_one_undo_step() { + let (mut harness, layer) = app_with_fill(json!({})); + let gray = json!({"t": "color", "v": [0.5, 0.5, 0.5, 1.0]}); + let tint = LinkParam { value: gray.clone(), default: gray.clone(), ..float_param("tint", "Tint", 0.0) }; + link_fill(&mut harness, layer, vec![tint], &[]); + let steps = undo_depth(&harness); + + // The swatch sits right of its label; its picker's saturation and value square lies under the R, G, B row + let label = harness.get_by_label("Tint").rect(); + let swatch = egui::pos2(label.right() + SWATCH_REACH, label.center().y); + harness.drag_at(swatch); + harness.drop_at(swatch); + harness.run_steps(SETTLE_FRAMES); + let copy = harness.get_by_role_and_label(Role::Button, "Copy RGB values").rect(); + let red = harness + .get_all_by_role(Role::SpinButton) + .map(|node| node.rect()) + .filter(|field| field.center().y < copy.bottom()) + .min_by(|a, b| a.left().total_cmp(&b.left())) + .unwrap(); + let from = egui::pos2(red.left() + SQUARE_REACH, copy.bottom() + SQUARE_REACH); + drag(&mut harness, from, from + egui::vec2(SQUARE_REACH / 2.0, SQUARE_REACH / 2.0)); + + let fill = fill_of(&harness, layer); + assert_ne!(fill.link.as_deref().unwrap().params[0].value, gray, "the drag changes the colour"); + assert_eq!(undo_depth(&harness), steps + 1, "every frame of the drag merges into one step"); +} + +/// From a label's right edge into the colour swatch beside it +const SWATCH_REACH: f32 = 30.0; + +/// From the picker's top-left content corner into its saturation and value square, and half of it for the drag +const SQUARE_REACH: f32 = 80.0; + +#[test] +fn a_linked_material_maps_its_channels_and_picks_its_resolution() { + let (mut harness, layer) = app_with_fill(json!({})); + link_fill(&mut harness, layer, Vec::new(), &[("baseColor", "steel_base.png"), ("roughness", "steel_rough.png")]); + let link = |harness: &Harness<'_, TextureCraftApp>| *fill_of(harness, layer).link.unwrap(); + + // Channels mapping: the Roughness row lists the outputs; picking one makes Roughness read it + click_below(&mut harness, Role::ComboBox, "roughness"); + click(&mut harness, Role::ListBoxOption, "baseColor"); + assert_eq!(link(&harness).output_of(Channel::Roughness), "baseColor"); + assert!(matches!(source(&harness, layer, Channel::Roughness), Source::Image { name, .. } if name == "steel_base.png")); + + // Resolution: folded until clicked; Fixed keeps the size, the list picks another, Relative goes back to a factor + assert!(harness.query_by_role_and_label(Role::RadioButton, "Fixed").is_none(), "Resolution starts folded"); + click_below(&mut harness, Role::Button, "Resolution"); + click_below(&mut harness, Role::RadioButton, "Fixed"); + assert_eq!(link(&harness).resolution, Some(CookResolution::Fixed(TEXTURE_RESOLUTION))); + click_below(&mut harness, Role::ComboBox, "256 × 256"); + click(&mut harness, Role::ListBoxOption, "1024 × 1024"); + assert_eq!(link(&harness).resolution, Some(CookResolution::Fixed(1024))); + click_below(&mut harness, Role::RadioButton, "Relative"); + assert_eq!(link(&harness).resolution, Some(CookResolution::Relative(2)), "1024 is the texture set's ×4"); +} + +/// Links the fill `layer` to a material with `params` and image `outputs` (output, image), as a cooked link leaves it +fn link_fill(harness: &mut Harness<'_, TextureCraftApp>, layer: LayerId, params: Vec, outputs: &[(&str, &str)]) { + let link = MaterialLink { + name: "Painted steel".into(), + package: String::new(), + graph: "main".into(), + params, + presets: Vec::new(), + inputs: Vec::new(), + size: 256, + resolution: None, + mapping: Default::default(), + outputs: outputs.iter().map(|(output, image)| ((*output).to_owned(), (*image).to_owned())).collect(), + }; + if let Some(LayerKind::Fill(fill)) = harness.state_mut().session.doc.project.layers.get_mut(&layer).map(|layer| &mut layer.kind) { + fill.link = Some(Box::new(link)); + } + harness.run_steps(SETTLE_FRAMES); +} + +/// A 0..1 number input `id` shown as `label`, at `value` and by default +fn float_param(id: &str, label: &str, value: f64) -> LinkParam { + let value = json!({"t": "float", "v": value}); + LinkParam { id: id.into(), label: label.into(), group: String::new(), value: value.clone(), default: value, min: 0.0, max: 1.0, options: Vec::new() } +} + +/// Types the sRGB code `hex` into the open picker's Hex field and confirms it +fn type_hex(harness: &mut Harness<'_, TextureCraftApp>, hex: &str) { + click(harness, Role::TextInput, "Hex color"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text(hex.into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); +} + +/// The fill's uniform base colour (linear) +fn base_color(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> [f32; 3] { + let Source::Uniform(color) = source(harness, layer, Channel::BaseColor) else { panic!("a uniform colour") }; + color +} + +#[test] +fn the_colour_bar_opens_the_picker_which_types_restores_and_waits_for_an_eyedropper_click() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + let before = base_color(&harness, layer); + click(&mut harness, Role::Button, "Base color"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "the picker shows its colour space"); + + type_hex(&mut harness, "FF8000"); + let typed = base_color(&harness, layer); + let expected = [1.0, texturecraft_engine::texel::srgb_to_linear(128.0 / 255.0), 0.0]; + assert!(typed.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3), "the typed sRGB code is stored linear: {typed:?}"); + + click(&mut harness, Role::ComboBox, "HSV"); + click(&mut harness, Role::ListBoxOption, "RGB"); + assert!(harness.query_by_role_and_label(Role::Slider, "R").is_some(), "the sliders edit R, G and B"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "picking from its own list keeps the picker open"); + + click(&mut harness, Role::Button, "Previous color"); + let restored = base_color(&harness, layer); + assert!(restored.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-4), "a click on the previous colour restores it: {restored:?} {before:?}"); + + click_picker_eyedropper(&mut harness); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model"); +} + +#[test] +fn the_picker_is_a_window_beside_the_panel_that_its_title_drags_and_its_close_or_escape_closes() { + let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + let bar = harness.get_by_role_and_label(Role::Button, "Base color").rect(); + let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); + let space = harness.get_by_role_and_label(Role::ComboBox, "sRGB").rect(); + assert!(title.right() <= bar.left(), "the window stands beside the panel, off its rows: {title:?} {bar:?}"); + assert!(title.top() <= bar.top() + 1.0, "level with the bar, or raised to stay on screen: {title:?} {bar:?}"); + assert!(space.width() < title.width() / 3.0, "the colour space dropdown is as wide as its text: {space:?}"); + + let from = title.left_center() + egui::vec2(20.0, 0.0); + let by = egui::vec2(-120.0, 90.0); + harness.hover_at(from); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=4 { + harness.hover_at(from + by * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: from + by, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(SETTLE_FRAMES); + let moved = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); + assert!((moved.min - (title.min + by)).length() < 1.0, "the title bar drags the window: {moved:?} from {title:?}"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a drag on the title keeps it open"); + + let close = harness + .get_all_by_role_and_label(Role::Button, "Close") + .find(|node| moved.y_range().contains(node.rect().center().y) && node.rect().left() >= moved.right()) + .unwrap() + .rect(); + click_at(&mut harness, close.center()); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "× closes it"); + + click(&mut harness, Role::Button, "Base color"); + let reopened = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); + assert!((reopened.min - moved.min).length() < 1.0, "it opens again where it was dragged: {reopened:?}"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "Escape closes it"); +} + +#[test] +fn escape_ends_an_eyedropper_pick_before_the_picker_and_an_alt_orbit_keeps_the_picker_open() { + let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + click_bar_eyedropper(&mut harness); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_none(), "Escape ends the pick"); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the same Escape leaves the picker open"); + + let view = harness.state().viewport_rect.center(); + let alt = egui::Modifiers::ALT; + harness.event(egui::Event::ModifiersChanged(alt)); + harness.hover_at(view); + harness.event(egui::Event::PointerButton { pos: view, button: egui::PointerButton::Primary, pressed: true, modifiers: alt }); + harness.run_steps(1); + harness.hover_at(view + egui::vec2(40.0, 10.0)); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: view + egui::vec2(40.0, 10.0), button: egui::PointerButton::Primary, pressed: false, modifiers: alt }); + harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "an Alt+drag on the model orbits and keeps the picker open"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the next Escape closes the picker"); +} + +/// A secondary-button press and release at `pos`, a frame apart, as a real right-click arrives +fn right_click(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Pos2) { + let button = egui::PointerButton::Secondary; + harness.hover_at(pos); + harness.run_steps(1); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_swatches_row_keeps_the_picker_colour_in_the_project_applies_it_on_a_click_and_removes_it_from_its_menu() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + let before = base_color(&harness, layer); + click(&mut harness, Role::Button, "Base color"); + type_hex(&mut harness, "FF8000"); + let orange = base_color(&harness, layer); + + let add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect(); + let space = harness.get_by_role_and_label(Role::ComboBox, "sRGB").rect(); + assert!(add.top() > space.bottom() && (add.left() - space.left()).abs() < 1.0, "the row is under the picker, at its left edge: {add:?}"); + click_at(&mut harness, add.center()); + assert_eq!(harness.state().session.doc.project.swatches, vec![orange], "+ keeps the picker's colour in the project"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "the picker stays open"); + let depth = undo_depth(&harness); + let kept = harness.get_by_role_and_label(Role::Button, "#FF8000").rect(); + click_at(&mut harness, kept.center()); + assert_eq!(undo_depth(&harness), depth, "a swatch the picker already shows changes nothing"); + + click(&mut harness, Role::Button, "Previous color"); + assert_eq!(base_color(&harness, layer), before); + let chip = harness.get_by_role_and_label(Role::Button, "#FF8000").rect(); + let moved_add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect(); + assert!((chip.left() - add.left()).abs() < 1.0 && moved_add.left() > chip.right(), "the swatch takes the + chip's place, + moves right"); + click_at(&mut harness, chip.center()); + assert_eq!(base_color(&harness, layer), orange, "a click on a swatch applies it"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "applying keeps the picker open"); + + right_click(&mut harness, chip.center()); + let remove = harness.get_by_role_and_label(Role::Button, "Remove swatch").rect(); + click_at(&mut harness, remove.center()); + assert!(harness.state().session.doc.project.swatches.is_empty(), "its right-click menu removes it"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a pick in the menu keeps the picker open"); +} + +#[test] +fn a_hex_code_left_as_it_opened_is_no_edit() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + let depth = undo_depth(&harness); + click(&mut harness, Role::TextInput, "Hex color"); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "the colour is not rounded to the code it shows"); + assert_eq!(undo_depth(&harness), depth, "no undo step"); +} + +#[test] +fn a_hex_code_typed_is_applied_when_another_widget_takes_the_focus() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + let depth = undo_depth(&harness); + click(&mut harness, Role::TextInput, "Hex color"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("FF8000".into())); + harness.run_steps(1); + + // As a shortcut focusing another field would: the field hears it lost the focus only a pass later + harness.ctx.memory_mut(|memory| memory.request_focus(egui::Id::unique("another field"))); + harness.run_steps(SETTLE_FRAMES); + let [red, green, blue] = base_color(&harness, layer); + assert!(red > green && green > blue, "the code typed is the colour: {:?}", [red, green, blue]); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step"); +} + +#[test] +fn a_hex_code_half_typed_when_a_press_closes_the_picker_is_gone_when_it_opens_again() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + click(&mut harness, Role::TextInput, "Hex color"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("FF8000".into())); + harness.run_steps(1); + let view = harness.state().viewport_rect.center(); + click_at(&mut harness, view); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the press closes the picker"); + assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "closing applies nothing"); + + let depth = undo_depth(&harness); + click(&mut harness, Role::Button, "Base color"); + click(&mut harness, Role::TextInput, "Hex color"); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "the field shows the colour's own code, not the text typed before"); + assert_eq!(undo_depth(&harness), depth, "no undo step"); +} + +/// The open picker's frame: its title bar's top and sides, down to the air under the + chip +fn picker_face(harness: &Harness<'_, TextureCraftApp>) -> egui::Rect { + // The air under the picker's last line (color_bar.rs PICKER_BOTTOM) + const PICKER_BOTTOM: f32 = 10.0; + let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); + let add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect(); + egui::Rect::from_min_max(title.min, egui::pos2(title.right() + CLOSE_ROOM, add.bottom() + PICKER_BOTTOM)) +} + +/// The title bar stops at the × (color_bar.rs: from the right edge to the close target's left edge: PAD + CLOSE_INK_HALF_WIDTH + half of CLOSE_TARGET) +const CLOSE_ROOM: f32 = 25.0; + +/// The narrowest the picker resizes to and the shortest its colour field gets (color_bar.rs PICKER_MIN_WIDTH, color_picker_rows.rs FIELD_MIN_HEIGHT) +const PICKER_MIN_WIDTH: f32 = 240.0; +const FIELD_MIN_HEIGHT: f32 = 100.0; + +#[test] +fn the_picker_is_titled_by_its_channel_resizes_from_its_edges_keeps_its_size_and_previews_nothing_on_hover() { + let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the title is the channel's name alone"); + + let face = picker_face(&harness); + let field = harness.get_by_role_and_label(Role::Slider, "Saturation and value").rect(); + let hue = harness.get_by_role_and_label(Role::Slider, "Hue").rect(); + let track = harness.get_by_role_and_label(Role::Slider, "S").rect(); + let by = egui::vec2(80.0, 60.0); + let corner = face.right_bottom() - egui::vec2(2.0, 2.0); + drag(&mut harness, corner, corner + by); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a resize keeps the picker open"); + let grown = picker_face(&harness); + assert!((grown.min - face.min).length() < 1.0, "the bottom right corner leaves the top left where it was: {grown:?} {face:?}"); + assert!((grown.size() - (face.size() + by)).length() < 1.0, "the corner drags the size: {grown:?} from {face:?}"); + let grown_field = harness.get_by_role_and_label(Role::Slider, "Saturation and value").rect(); + let grown_hue = harness.get_by_role_and_label(Role::Slider, "Hue").rect(); + let grown_track = harness.get_by_role_and_label(Role::Slider, "S").rect(); + assert!((grown_field.size() - (field.size() + by)).length() < 1.0, "the field takes the new width and height: {grown_field:?} {field:?}"); + assert!((grown_hue.height() - (hue.height() + by.y)).abs() < 1.0 && (grown_hue.right() - hue.right() - by.x).abs() < 1.0, "the hue strip grows with it"); + assert!((grown_track.width() - (track.width() + by.x)).abs() < 1.0, "the sliders' tracks take the new width"); + + let left_edge = egui::pos2(grown.left() + 2.0, grown.center().y); + drag(&mut harness, left_edge, left_edge + egui::vec2(-50.0, 0.0)); + let wider = picker_face(&harness); + assert!( + (wider.left() - (grown.left() - 50.0)).abs() < 1.0 && (wider.right() - grown.right()).abs() < 1.0, + "the left edge moves, the right stays: {wider:?}" + ); + + let wider_corner = wider.right_bottom() - egui::vec2(2.0, 2.0); + drag(&mut harness, wider_corner, wider_corner + egui::vec2(-1000.0, -1000.0)); + let least = picker_face(&harness); + let least_field = harness.get_by_role_and_label(Role::Slider, "Saturation and value").rect(); + assert!(least.width() >= PICKER_MIN_WIDTH - 1.0 && least_field.height() >= FIELD_MIN_HEIGHT - 1.0, "it stops at a usable size: {least:?} {least_field:?}"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + click(&mut harness, Role::Button, "Base color"); + let reopened = picker_face(&harness); + assert!((reopened.size() - least.size()).length() < 1.0, "it opens again at the size it was left: {reopened:?} {least:?}"); + + let value = |harness: &Harness<'_, TextureCraftApp>| harness.get_by_role_and_label(Role::Slider, "V").accesskit_node().numeric_value(); + let shown = value(&harness); + assert!(shown.is_some(), "the V slider says its value"); + click(&mut harness, Role::ComboBox, "sRGB"); + harness.get_by_role_and_label(Role::ListBoxOption, "Linear").hover(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(value(&harness), shown, "a hovered colour space changes nothing"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + click(&mut harness, Role::ComboBox, "HSV"); + harness.get_by_role_and_label(Role::ListBoxOption, "RGB").hover(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::Slider, "R").is_none(), "a hovered model changes nothing"); + click(&mut harness, Role::ListBoxOption, "RGB"); + assert!(harness.query_by_role_and_label(Role::Slider, "R").is_some(), "a click picks it"); +} + +/// The whole material the fill `layer` holds +fn whole_material(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Option { + fill_of(harness, layer).material +} + +#[test] +fn a_plain_fill_switches_to_one_whole_material_picks_it_from_its_card_and_clears_it() { + let (mut harness, layer) = app_with_fill(json!({})); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "a plain fill opens on Channels: a card per channel"); + + click_node(&mut harness, Role::RadioButton, "Material"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "the Material side has no channel cards"); + click_node(&mut harness, Role::ComboBox, "None"); + + // The card opens the material picker, not a list: unfiltered it offers the plain materials but no smart ones + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Steel").is_some(), "the picker offers the plain materials"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Steel Painted Worn").is_none(), "smart materials are folders of layers: not offered"); + + // Its search keeps only the materials it names + harness.event(egui::Event::Text("hammered".into())); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Steel").is_none(), "searching hides what it doesn't name"); + click_node(&mut harness, Role::ListBoxOption, "Copper Hammered"); + assert_eq!(whole_material(&harness, layer).as_deref(), Some("copper_hammered"), "the picker sets the whole material"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Copper Hammered").is_some(), "the card names it"); + assert!(harness.query_by_role(Role::ListBoxOption).is_none(), "the picker closed on the pick"); + + click_node(&mut harness, Role::RadioButton, "Channels"); + assert!(matches!(source(&harness, layer, Channel::BaseColor), Source::Procedural { .. }), "the material set every channel"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Height").is_some(), "its channels show as cards"); + + click_node(&mut harness, Role::RadioButton, "Material"); + click_in_slot(&mut harness, "Copper Hammered", Role::Button, "Clear"); + assert_eq!(whole_material(&harness, layer), None, "× drops the material"); + assert_eq!(source(&harness, layer, Channel::BaseColor), Source::uniform_of(Channel::BaseColor), "and returns the channels to their defaults"); +} + +/// Arms the base colour bar's eyedropper and gives its pick the click outside the app that ended as `outcome` +fn pick_outside(harness: &mut Harness<'_, TextureCraftApp>, outcome: PickOutcome) { + click_bar_eyedropper(harness); + harness.run_steps(SETTLE_FRAMES); + let bar = harness.state().picking_color.expect("the eyedropper waits for a click"); + harness.state_mut().screen_pick = Some(ScreenPick::ended(bar, outcome)); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn a_click_outside_the_app_hands_its_screen_colour_to_the_bar_and_a_cancelled_or_impossible_one_changes_nothing() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + assert!(!harness.state().screen_picking, "tests have no real window: no system hook or grab"); + let before = base_color(&harness, layer); + click(&mut harness, Role::Button, "Base color"); + + pick_outside(&mut harness, PickOutcome::Unavailable); + assert!(harness.state().picking_color.is_some(), "where the system cannot read the screen the pick stays on the model"); + assert_eq!(base_color(&harness, layer), before, "nothing changes until a click"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "Escape ends the pick and its wait"); + + pick_outside(&mut harness, PickOutcome::Cancelled); + assert!(harness.state().picking_color.is_none(), "dismissing the desktop's picker ends the pick"); + assert_eq!(base_color(&harness, layer), before, "a cancelled pick changes nothing"); + + let undo_before = undo_depth(&harness); + pick_outside(&mut harness, PickOutcome::Picked([255, 128, 0])); + let picked = base_color(&harness, layer); + let expected = [1.0, texturecraft_engine::texel::srgb_to_linear(128.0 / 255.0), 0.0]; + assert!(picked.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3), "the screen's sRGB pixel is stored linear: {picked:?}"); + assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "the click ends the pick"); + assert_eq!(undo_depth(&harness), undo_before + 1, "one undo step"); +} + +#[test] +fn an_armed_eyedropper_is_the_pointer_over_the_whole_window_and_the_app_losing_the_focus_ends_it() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + let before = base_color(&harness, layer); + click(&mut harness, Role::Button, "Base color"); + click_bar_eyedropper(&mut harness); + harness.run_steps(SETTLE_FRAMES); + let bar = harness.state().picking_color.expect("the eyedropper waits for a click"); + + harness.get_by_role_and_label(Role::Tab, "Material").hover(); + harness.run_steps(SETTLE_FRAMES); + let pointer = harness.output().platform_output.cursor_icon; + assert_eq!(pointer, egui::CursorIcon::None, "over the Properties panel, not only the 3D view, the drawn eyedropper is the pointer"); + + harness.state_mut().screen_pick = Some(ScreenPick::waiting(bar)); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_some(), "a focused app keeps waiting"); + harness.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().focused = Some(false); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "another app came forward: the pick ends"); + assert_eq!(base_color(&harness, layer), before, "nothing changes"); + assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::None, "the pointer is the user's again"); +} + +#[test] +fn escape_in_the_hex_field_ends_the_typing_and_a_second_escape_closes_the_picker() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + click(&mut harness, Role::TextInput, "Hex color"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("FF8000".into())); + harness.run_steps(1); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the first Escape only ends the typing"); + assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "and applies nothing"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the next Escape closes the picker"); +} + +#[test] +fn a_hex_code_left_as_it_opened_keeps_a_colour_set_meanwhile() { + let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + click(&mut harness, Role::Button, "Base color"); + click(&mut harness, Role::TextInput, "Hex color"); + + // An agent sets the colour while the field is open + harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + harness.run_steps(2); + let depth = undo_depth(&harness); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(base_color(&harness, layer), [0.0, 0.0, 1.0], "the untouched code is not written back"); + assert_eq!(undo_depth(&harness), depth, "no undo step"); +} + +#[test] +fn a_swatch_menu_left_open_while_the_list_changes_never_removes_another_swatch() { + let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); + let [red, green, blue] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + for color in [red, green, blue] { + harness.state_mut().run("swatch.add", json!({"color": color})).unwrap(); + } + click(&mut harness, Role::Button, "Base color"); + let green_chip = harness.get_by_role_and_label(Role::Button, "#00FF00").rect(); + right_click(&mut harness, green_chip.center()); + assert!(harness.query_by_role_and_label(Role::Button, "Remove swatch").is_some(), "the green swatch's menu is open"); + + // An agent removes the first swatch: green moves to its place, blue to green's + harness.state_mut().run("swatch.remove", json!({"index": 0})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + if let Some(remove) = harness.query_by_role_and_label(Role::Button, "Remove swatch").map(|node| node.rect()) { + click_at(&mut harness, remove.center()); + } + let swatches = &harness.state().session.doc.project.swatches; + assert!(swatches.contains(&blue), "blue stays: {swatches:?}"); + assert!(*swatches == vec![blue] || *swatches == vec![green, blue], "only the green swatch the menu was opened on may go: {swatches:?}"); +} From fdcdde41cba3c28640f84864d14426aab8a7f9d8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:27 +0000 Subject: [PATCH 020/153] Fills: material orbs lit by a photographed studio (Studio Small 09, CC0) --- ATTRIBUTION.md | 1 + assets/hdr/studio_small_09_512.hdr | Bin 0 -> 409867 bytes crates/ui-egui/src/material_orb.rs | 356 ++++++++++++++++++ crates/ui-egui/src/orb_environment.rs | 78 ++++ crates/ui-egui/src/orb_material.rs | 185 +++++++++ .../ui-egui/src/orb_material/hash_writer.rs | 12 + crates/ui-egui/src/orb_material/orb_sample.rs | 11 + crates/ui-egui/src/orb_previews.rs | 352 +++++++++++++++++ crates/ui-egui/src/orb_previews/orb_job.rs | 49 +++ crates/ui-egui/src/orb_previews/orb_result.rs | 14 + crates/ui-egui/src/orb_previews/picture.rs | 14 + crates/ui-egui/src/orb_previews/worker.rs | 73 ++++ 12 files changed, 1145 insertions(+) create mode 100644 assets/hdr/studio_small_09_512.hdr create mode 100644 crates/ui-egui/src/material_orb.rs create mode 100644 crates/ui-egui/src/orb_environment.rs create mode 100644 crates/ui-egui/src/orb_material.rs create mode 100644 crates/ui-egui/src/orb_material/hash_writer.rs create mode 100644 crates/ui-egui/src/orb_material/orb_sample.rs create mode 100644 crates/ui-egui/src/orb_previews.rs create mode 100644 crates/ui-egui/src/orb_previews/orb_job.rs create mode 100644 crates/ui-egui/src/orb_previews/orb_result.rs create mode 100644 crates/ui-egui/src/orb_previews/picture.rs create mode 100644 crates/ui-egui/src/orb_previews/worker.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 500328aa..bdd983f6 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -23,6 +23,7 @@ licensed and keep their license file next to them. | `docs/images/texturecraft-light.png` | README screenshot: the light brightness level with the blue accent | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-lantern.png` | README render: a storm lantern (original procedural mesh of lathes and swept wires, eight texture sets) in chipped red enamel, rust, soot, tarnished brass and glass with an emissive flame (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-camera.png` | README render: a rangefinder camera (original procedural mesh) in black enamel worn to brass, leatherette, chrome and coated glass; the lens distance scale is an original image drawn in code (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | +| `assets/environments/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | https://polyhaven.com/a/studio_small_09 (1K .hdr) | CC0-1.0 | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | diff --git a/assets/hdr/studio_small_09_512.hdr b/assets/hdr/studio_small_09_512.hdr new file mode 100644 index 0000000000000000000000000000000000000000..3a3f4f350b16a64177aafbf293aefbcdf220402b GIT binary patch literal 409867 zcmYhjXOLuBb{?kgnVntiF0dd#LIOevfq@W(5CcC55@N^&xd90ZhD0g?1cTxd5JF%; zyEENgT{gXc@1^(Nd+)vXzB02itFpYeU2Ue#bWiuRnKnAFdKN--Ri~|&dEdSFeCK@M zci!*+i$DA6|MIVX`fvW^fBoT~{-1yLuYdaI|MNfnqd)xX&lmq{{^sBO)%?%@`fq;t z!$15FzxPLf{NMfFKmNad?~nhGJpjkwmuK z8g3k3e)TOI6G#+VgW2YQ7yQ9cI1-Jq=L-dH@smP6 zkL0drvuN%I_%p>~sf<>xSF8LAQodH`u2Y5RN6Yg-WBdJf7|xUOf2f6=bD%6LEP6|7~KD!*X#57kpLFF7UBl41(4t;fnX2|To1xsB=n+~{j<#0&jZ!uq@;aJMQDp#zwdMhwz=l6*e8k3E1`67v2sn+TY zMw7+*aUljn5hQv&9!C<_lQ1ivrIM*sGKnNUjbE+JA4S69P%seic|C5#^_kP@aMS2uE)4y85C-~bI2?gv{{Wv{d~tI#-0Za+lKtnI zOezrz2fX-#gt4d;GKmPr$)Zz;_s;e=SBITOIiHFKJPwNiKM4}CNGK5SF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409WfD2+&%k9Og;u9ev*2b{cdirIFM8J`- z!3rc@DghvA{?ZTnC&#OEWmx~^dfs2}*Ldqv`(&YsgkC zubb!d#L!r=l zyTqXg0Pw1urnM2w2ky5X%xj!Vl*|d1YBdatbt#J^N`wbUj) zg{uo&Zx>gNUp4}5bM1fGo=8e??b@-cZ|{0!R5dlR-6$P27zO}R-N-hx@kl5LG6ogx+^Jf8-?;h;s)C%Dugd~ zoAVync+xldM;}PC{gEH@vV;}SQQ>Mg2M$qJ4CEvzl@DIF2semO>MW84Mx z9?Z$F^Xtd_B)HF8Qx?zacS9HF`&E=xDB8t?zhC_P2Rt-S8D8*KKIU5}#X?mBt?FS- z29L)CLo=vq{=%dyQ60QuBC@~;m*#z>#P?KI-Pc}N$N{YMDNo$HerEc#7ycr3#0z{R zBxGz2dc0`~w*u0_+Hn2*sX|ozn)jZ&J}L@fA-q}m>+AEMLs0#1WaEmQp}j+&b|K-e zT`QGsxVo@15MA5l1#DXy6fV=Q9$WjO3v^pQ=&5MK3yQh@AoR_M?W_MGSH35vwOd0h zG&!~P9xZWX>xV+qeE#^s)xW-$U>Q;Df9Fd7J}y;1-$No7wtjf!?L5t!A&gsZB|QEg zTW? ColorImage { + let side = side.clamp(1, MAX_SIDE_PX); + let env = OrbEnvironment::get(); + let back = [backdrop.r(), backdrop.g(), backdrop.b()].map(|component| f32::from(component) / 255.0); + + // One pixel in orb radii: the step for the height slope and the reach of the anti-aliased outline + let pixel = 2.0 / (side as f32 * SPHERE_RADIUS); + let uniform = (!material.varies()).then(|| material.sample(&orb_coords(Vec3::Y), 1.0)); + let mut pixels = vec![Color32::TRANSPARENT; side * side]; + pixels.par_chunks_mut(side).enumerate().for_each(|(y, row)| { + for (x, out) in row.iter_mut().enumerate() { + let u = ((x as f32 + 0.5) / side as f32 * 2.0 - 1.0) / SPHERE_RADIUS; + let v = (1.0 - (y as f32 + 0.5) / side as f32 * 2.0) / SPHERE_RADIUS; + let distance = (u * u + v * v).sqrt(); + let coverage = ((1.0 - distance) / pixel + 0.5).clamp(0.0, 1.0); + if coverage <= 0.0 { + *out = backdrop; + continue; + } + + // Pixels on the outline shade the sphere's rim + let (u, v) = if distance > 1.0 { (u / distance, v / distance) } else { (u, v) }; + let normal = Vec3::new(u, v, (1.0 - u * u - v * v).max(0.0).sqrt()); + let (shown, alpha) = match material.alone() { + Some(channel) => { + let footprint = pixel * std::f32::consts::FRAC_1_PI; + (channel_view(channel, material.value(channel, &orb_coords(normal), footprint)), coverage) + } + None => { + let (linear, opacity) = shade(material, env, normal, pixel, uniform); + (linear.map(|component| linear_to_srgb(aces(component * EXPOSURE))), coverage * opacity) + } + }; + let [r, g, b] = [0, 1, 2].map(|channel| ((back[channel] + (shown[channel] - back[channel]) * alpha) * 255.0).round().clamp(0.0, 255.0) as u8); + *out = Color32::from_rgb(r, g, b); + } + }); + ColorImage::new([side, side], pixels) +} + +/// The linear light leaving the orb at view-space unit `direction` from its centre, and the material's opacity there +fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f32, uniform: Option) -> ([f32; 3], f32) { + // Facing the viewer, the orb's poles sit on its outline, where their UV pinch does not show + let coords = orb_coords(direction); + let footprint = pixel * std::f32::consts::FRAC_1_PI; + let sample = uniform.unwrap_or_else(|| material.sample(&coords, footprint)); + + // Tangent frame on the material: east along the UVs, then north + let east = Vec3::new(-direction.z, 0.0, direction.x).try_normalize().unwrap_or(Vec3::X); + let north = direction.cross(east).try_normalize().unwrap_or(Vec3::Y); + let mapped = Vec3::from(sample.normal.map(|component| component * 2.0 - 1.0)); + let mut surface = (east * mapped.x + north * mapped.y + direction * mapped.z).try_normalize().unwrap_or(direction); + if material.has_relief() { + let height = material.height(&coords, footprint); + let slope = |toward: Vec3| (material.height(&orb_coords((direction + toward * pixel).normalize()), footprint) - height) / pixel; + surface = (surface - (east * slope(east) + north * slope(north)) * HEIGHT_DEPTH).try_normalize().unwrap_or(surface); + } + + let normal = surface; + let roughness = sample.roughness.clamp(MIN_ROUGHNESS, 1.0); + let metallic = sample.metallic.clamp(0.0, 1.0); + let normal_dot_view = normal.z.max(MIN_NORMAL_DOT_VIEW); + + // 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 = env.reflected(reflected, roughness); + let diffuse_light = env.diffuse(normal); + let (scale, bias) = environment_brdf(roughness, normal_dot_view); + let mut out = [0.0; 3]; + for (channel, value) in out.iter_mut().enumerate() { + let base = sample.base[channel].clamp(0.0, 1.0); + let f0 = DIELECTRIC_REFLECTANCE + (base - DIELECTRIC_REFLECTANCE) * metallic; + let specular = f0 * scale + bias; + *value = diffuse_light[channel] * base * (1.0 - metallic) * (1.0 - specular) + specular_light[channel] * specular + sample.emissive[channel].max(0.0); + } + (out, sample.opacity.clamp(0.0, 1.0)) +} + +/// `channel`'s `value` on screen (0..1) as the viewport's channel view shows it: colours sRGB-encoded, height around mid gray +fn channel_view(channel: Channel, value: [f32; 3]) -> [f32; 3] { + let value = value.map(|c| if c.is_finite() { c } else { 0.0 }); + let shown = match channel { + Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => value.map(|c| linear_to_srgb(c.clamp(0.0, 1.0))), + // The viewport encodes these as it does colours (they share its colour output) + Channel::Metallic | Channel::Roughness | Channel::Glossiness => [linear_to_srgb(value[0].clamp(0.0, 1.0)); 3], + Channel::Normal | Channel::CoatNormal => value, + Channel::Height => [value[0] * 0.5 + 0.5; 3], + _ => [value[0]; 3], + }; + shown.map(|c| c.clamp(0.0, 1.0)) +} + +/// The split-sum environment BRDF as scale and bias on F0, from Karis' analytic fit for mobile (no lookup table) +fn environment_brdf(roughness: f32, normal_dot_view: f32) -> (f32, f32) { + let [gloss, gloss_offset, scale_base, bias_base] = [1.0 - roughness, roughness * -0.0275 + 0.0425, roughness * -0.572 + 1.04, roughness * 0.022 - 0.04]; + let shared = (gloss * gloss).min((-9.28 * normal_dot_view).exp2()) * gloss + gloss_offset; + (shared * -1.04 + scale_base, shared * 1.04 + bias_base) +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::{Channel, Fill, Procedural, ProceduralKind, Source}; + + use super::*; + + const BACKDROP: Color32 = Color32::from_rgb(27, 31, 39); + + fn copper() -> OrbMaterial { + OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, 0.35) + } + + fn at(image: &ColorImage, x: usize, y: usize) -> Color32 { + image.pixels.get(y * image.size[0] + x).copied().unwrap_or_default() + } + + /// Mean of how far each pixel's channels spread apart (0 = gray) + fn saturation(image: &ColorImage) -> f32 { + let spread = |pixel: &Color32| f32::from(pixel.r().max(pixel.g()).max(pixel.b()) - pixel.r().min(pixel.g()).min(pixel.b())); + let shown: Vec = image.pixels.iter().filter(|pixel| **pixel != BACKDROP).map(spread).collect(); + shown.iter().sum::() / shown.len().max(1) as f32 + } + + #[test] + fn the_orb_sits_on_its_backdrop_and_shows_its_colour() { + let image = render(&copper(), 64, BACKDROP); + assert_eq!(image.pixels[0], BACKDROP, "the corner is off the sphere"); + let middle = at(&image, 32, 32); + assert!(middle.r() > middle.b(), "copper is warm: {middle:?}"); + } + + #[test] + fn rougher_materials_spread_their_highlight() { + let peak = |roughness: f32| { + let image = render(&OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, roughness), 64, Color32::BLACK); + image.pixels.iter().map(|pixel| pixel.r()).max().unwrap_or(0) + }; + assert!(peak(0.1) > peak(0.9), "a polished orb has a brighter hot spot"); + } + + #[test] + fn a_metal_reflects_the_studio_in_its_own_colour() { + // The studio's soft boxes and dark walls show as bright and dark bands across a polished metal, tinted by its colour + let image = render(&OrbMaterial::uniform([0.95, 0.64, 0.54], 1.0, 0.15), 96, BACKDROP); + let lightness: Vec = image.pixels.iter().filter(|pixel| **pixel != BACKDROP).map(|pixel| pixel.r()).collect(); + let (darkest, brightest) = (lightness.iter().min().copied().unwrap_or(0), lightness.iter().max().copied().unwrap_or(0)); + assert!(brightest - darkest > 120, "reflections show light and dark: {darkest}..{brightest}"); + assert!(saturation(&image) > 25.0, "copper stays coloured, not gray: {}", saturation(&image)); + } + + fn fill_with(channel: Channel, source: Source) -> Fill { + let mut fill = Fill::default(); + fill.sources.insert(channel, source); + fill + } + + #[test] + fn a_colour_procedurals_gradient_map_colours_the_orb() { + let source = |ramp: Vec<[f32; 3]>| Source::Procedural { pattern: Procedural::new(ProceduralKind::Cells), low: [0.0; 3], high: [1.0; 3], ramp }; + let on = [Channel::BaseColor]; + let gray = render(&OrbMaterial::of_fill(&fill_with(Channel::BaseColor, source(Vec::new())), &on, &Default::default()), 64, BACKDROP); + let red = render(&OrbMaterial::of_fill(&fill_with(Channel::BaseColor, source(vec![[1.0, 0.0, 0.0]; 2])), &on, &Default::default()), 64, BACKDROP); + let reddened = + red.pixels.iter().zip(&gray.pixels).filter(|(r, g)| i32::from(r.r()) - i32::from(r.g()) > i32::from(g.r()) - i32::from(g.g()) + 16).count(); + assert!(reddened > 64 * 64 / 4, "the ramp's red shows on the orb: {reddened} pixels"); + } + + #[test] + fn every_channel_shows_on_the_orb_relief_included() { + let flat = render(&OrbMaterial::of_fill(&Fill::default(), &[Channel::BaseColor, Channel::Height, Channel::Normal], &Default::default()), 64, BACKDROP); + let pattern = Procedural::new(ProceduralKind::Cells); + for channel in [Channel::BaseColor, Channel::Roughness, Channel::Height, Channel::Normal] { + let (low, high) = match channel { + Channel::Normal => ([0.2, 0.5, 0.9], [0.8, 0.5, 0.9]), + Channel::Height => ([-1.0; 3], [1.0; 3]), + _ => ([0.0; 3], [1.0; 3]), + }; + let fill = fill_with(channel, Source::Procedural { pattern: pattern.clone(), low, high, ramp: Vec::new() }); + let on = [Channel::BaseColor, Channel::Roughness, Channel::Height, Channel::Normal]; + let shown = render(&OrbMaterial::of_fill(&fill, &on, &Default::default()), 64, BACKDROP); + let changed = shown.pixels.iter().zip(&flat.pixels).filter(|(a, b)| a != b).count(); + assert!(changed > 64 * 64 / 4, "{channel:?} changes the orb: {changed} pixels"); + let off = render(&OrbMaterial::of_fill(&fill, &[], &Default::default()), 64, BACKDROP); + let flat_off = render(&OrbMaterial::of_fill(&Fill::default(), &[], &Default::default()), 64, BACKDROP); + assert_eq!(off.pixels, flat_off.pixels, "{channel:?} switched off shows its default"); + } + } + + #[test] + fn an_image_source_shows_on_the_orb() { + use std::sync::Arc; + use texturecraft_engine::compose::ImageRes; + + // Left half black, right half white + let rgba = (0..64 * 64).map(|i| if i % 64 < 32 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }).collect(); + let images = std::collections::HashMap::from([("stripes".to_owned(), Arc::new(ImageRes::new(64, 64, rgba, false)))]); + let fill = fill_with(Channel::BaseColor, Source::Image { name: "stripes".into(), normal_format: Default::default() }); + let image = render(&OrbMaterial::of_fill(&fill, &[Channel::BaseColor], &images), 64, BACKDROP); + let lightness: Vec = image.pixels.iter().filter(|pixel| **pixel != BACKDROP).map(|pixel| pixel.g()).collect(); + let (darkest, brightest) = (lightness.iter().min().copied().unwrap_or(0), lightness.iter().max().copied().unwrap_or(0)); + assert!(brightest - darkest > 100, "the black and white halves both show: {darkest}..{brightest}"); + let missing = render(&OrbMaterial::of_fill(&fill, &[Channel::BaseColor], &Default::default()), 64, BACKDROP); + assert_ne!(missing.pixels, image.pixels, "a missing image reads the default"); + } + + #[test] + fn hostile_sizes_and_values_render_without_panicking() { + for side in [0, 1, 2, 100_000] { + let image = render(&OrbMaterial::uniform([f32::NAN, f32::INFINITY, -1.0], f32::NAN, f32::NEG_INFINITY), side, BACKDROP); + assert!(image.size[0] >= 1 && image.size[0] <= MAX_SIDE_PX); + } + } + + #[test] + fn the_orb_renders_at_its_size_on_screen_times_the_screen_scale() { + use std::time::{Duration, Instant}; + + use crate::orb_previews::OrbPreviews; + + // 160 points: wider than the old 256-pixel cap once doubled + for scale in [1.0_f32, 2.0] { + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(scale); + let material = copper(); + let expected = (160.0 * scale) as usize; + let start = Instant::now(); + while OrbPreviews::shown_size(&ctx, "hidpi") != Some([expected, expected]) && start.elapsed() < Duration::from_secs(20) { + let mut output = ctx.run_pass(Default::default(), |ctx| { + let painter = ctx.layer_painter(egui::LayerId::background()); + let rect = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(160.0, 160.0)); + material_orb(&painter, rect, &material, &Tokens::get(ctx), "hidpi"); + }); + + // Nothing draws these textures here + output.textures_delta.clear(); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(OrbPreviews::shown_size(&ctx, "hidpi"), Some([expected, expected]), "at {scale}x"); + } + } + + /// Milliseconds per orb, written by `cargo test --release -p texturecraft-ui-egui --lib -- orb_render_timing --ignored --nocapture` + #[test] + #[ignore = "a timing, not a check"] + fn orb_render_timing() { + use std::time::Instant; + + use texturecraft_engine::compose::ImageRes; + + let started = Instant::now(); + crate::orb_environment::OrbEnvironment::get(); + eprintln!("studio prefilter (once): {:.1} ms", started.elapsed().as_secs_f64() * 1000.0); + let rgba = (0..512 * 512).map(|i| [(i % 512) as f32 / 512.0, 0.5, (i / 512) as f32 / 512.0, 1.0]).collect(); + let images = std::collections::HashMap::from([("photo".to_owned(), std::sync::Arc::new(ImageRes::new(512, 512, rgba, true)))]); + let mut complex = Fill::default(); + complex.sources.insert(Channel::BaseColor, Source::Image { name: "photo".into(), normal_format: Default::default() }); + complex.sources.insert( + Channel::Roughness, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.2; 3], high: [0.8; 3], ramp: Vec::new() }, + ); + complex + .sources + .insert(Channel::Height, Source::Procedural { pattern: Procedural::new(ProceduralKind::Cells), low: [-1.0; 3], high: [1.0; 3], ramp: Vec::new() }); + complex.sources.insert( + Channel::Normal, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Perlin), low: [0.3, 0.5, 0.9], high: [0.7, 0.5, 0.9], ramp: Vec::new() }, + ); + let on = [Channel::BaseColor, Channel::Roughness, Channel::Height, Channel::Normal]; + let looks = [("uniform", copper()), ("image+procedurals+height+normal", OrbMaterial::of_fill(&complex, &on, &images))]; + for (name, look) in looks { + for side in [25, 100, 200, 400] { + let runs = 10; + let started = Instant::now(); + for _ in 0..runs { + std::hint::black_box(render(&look, side, BACKDROP)); + } + eprintln!("{name} {side}px: {:.2} ms", started.elapsed().as_secs_f64() * 1000.0 / f64::from(runs)); + } + } + } + + #[test] + fn a_channel_alone_shows_unlit_as_the_viewports_channel_view_draws_it() { + let mut fill = fill_with(Channel::BaseColor, Source::Uniform([0.8, 0.35, 0.18])); + fill.sources.insert(Channel::Roughness, Source::Uniform([0.3; 3])); + fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + let on = [Channel::BaseColor, Channel::Roughness, Channel::Height]; + let byte = |value: f32| (value * 255.0).round() as u8; + let encoded = |value: f32| byte(linear_to_srgb(value)); + + for (channel, expected) in [ + (Channel::BaseColor, Color32::from_rgb(encoded(0.8), encoded(0.35), encoded(0.18))), + (Channel::Roughness, Color32::from_gray(encoded(0.3))), + (Channel::Height, Color32::from_gray(byte(0.75))), + (Channel::Metallic, Color32::from_gray(0)), + ] { + let image = render(&OrbMaterial::of_channel(&fill, channel, &on, &Default::default()), 64, BACKDROP); + + assert_eq!(at(&image, 32, 32), expected, "{channel:?} at the centre"); + assert_eq!(at(&image, 12, 32), expected, "{channel:?} unlit: the same off the centre"); + assert_eq!(image.pixels[0], BACKDROP, "{channel:?} sits on the backdrop"); + } + } + + #[test] + fn the_key_changes_with_the_look_and_only_with_it() { + let a = OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, 0.35); + assert_eq!(a.key(), copper().key()); + assert_ne!(a.key(), OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, 0.36).key()); + } +} diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs new file mode 100644 index 00000000..c7d50c8e --- /dev/null +++ b/crates/ui-egui/src/orb_environment.rs @@ -0,0 +1,78 @@ +//! The studio that lights every material orb: a bundled photographed environment (CC0, see ATTRIBUTION.md), prefiltered once for +//! glossy reflections and reduced to spherical harmonics for diffuse light + +use std::sync::OnceLock; + +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_render::ibl::{self, EnvImage}; + +/// The bundled environment: a small photo studio with soft boxes, 512 x 256 equirect Radiance HDR +const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/environments/studio_small_09_512.hdr"); + +/// Prefiltered levels from mirror (0) to fully rough (last) +const LEVELS: u32 = 6; + +/// How far the studio is turned about the vertical axis (radians) so its key soft box lights the orb from the upper left +const TURN: f32 = 4.4; + +/// The prefiltered studio +pub(crate) struct OrbEnvironment { + /// Level `l` holds reflections for roughness `l / (LEVELS - 1)` + levels: Vec, + /// Diffuse light as 9 spherical-harmonics coefficients + irradiance: [[f32; 3]; 9], +} + +impl OrbEnvironment { + /// The studio, decoded and prefiltered by the first caller (about a tenth of a second in release) + pub(crate) fn get() -> &'static OrbEnvironment { + static STUDIO: OnceLock = OnceLock::new(); + STUDIO.get_or_init(|| OrbEnvironment::from_hdr(STUDIO_HDR).unwrap_or_else(OrbEnvironment::fallback)) + } + + fn from_hdr(bytes: &[u8]) -> Option { + let decoded = + image::load_from_memory_with_format(bytes, image::ImageFormat::Hdr).inspect_err(|e| log::warn!("the orb studio did not load: {e}")).ok()?; + + let rgb = decoded.into_rgb32f(); + let (pixels, _) = rgb.as_raw().as_chunks::<3>(); + drop(rgb); + + Some(OrbEnvironment::of(&env)) + } + + /// The built-in procedural studio, should the bundled one ever fail to decode + fn fallback() -> OrbEnvironment { + OrbEnvironment::of(&ibl::environment("Studio Soft", 256)) + } + + fn of(env: &EnvImage) -> OrbEnvironment { + OrbEnvironment { levels: ibl::prefilter(env, LEVELS), irradiance: ibl::sh9(env) } + } + + /// Light reflected towards unit direction `direction` (view space: +X right, +Y up, +Z towards the viewer) by a surface of `roughness` + pub(crate) fn reflected(&self, direction: Vec3, roughness: f32) -> Vec3 { + let turned = turn(direction); + let level = roughness.clamp(0.0, 1.0) * (self.levels.len().saturating_sub(1)) as f32; + let below = level.floor() as usize; + let sample = |index: usize| self.levels.get(index).or(self.levels.last()).map_or(Vec3::ZERO, |env| env.sample(turned)); + let fraction = level - level.floor(); + if fraction <= 0.0 { sample(below) } else { sample(below).lerp(sample(below + 1), fraction) } + } + + /// Diffuse light reaching a surface with unit normal `normal` (view space) + pub(crate) fn diffuse(&self, normal: Vec3) -> Vec3 { + let basis = ibl::sh_basis(turn(normal)); + let mut light = Vec3::ZERO; + for (coefficient, weight) in self.irradiance.iter().zip(basis) { + light += Vec3::from(*coefficient) * weight; + } + light.max(Vec3::ZERO) + } +} + +/// `direction` in the studio's frame +fn turn(direction: Vec3) -> Vec3 { + let (sin, cos) = TURN.sin_cos(); + Vec3::new(direction.x * cos + direction.z * sin, direction.y, direction.z * cos - direction.x * sin) +} diff --git a/crates/ui-egui/src/orb_material.rs b/crates/ui-egui/src/orb_material.rs new file mode 100644 index 00000000..5a1a7da6 --- /dev/null +++ b/crates/ui-egui/src/orb_material.rs @@ -0,0 +1,185 @@ +//! What a material orb shows: every channel the orb lights with, read from the fill's own sources through its own projection + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Weak}; + +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::compose::pattern::{Coords, image_samples, procedural}; +use texturecraft_engine::core::blend::lum; +use texturecraft_engine::core::{Channel, ChannelKind, Fill, NormalFormat, Projection, Sampling, Source}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; +use texturecraft_engine::texel::srgb_to_linear; + +mod hash_writer; +mod orb_sample; + +use hash_writer::HashWriter; +pub(crate) use orb_sample::OrbSample; + +/// The channels the orb reads; the others do not change how it looks +pub(crate) const ORB_CHANNELS: [Channel; 7] = + [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Normal, Channel::Height, Channel::Emissive, Channel::Opacity]; + +/// Fewest and most image repeats the orb's filtering assumes, so a tiny or huge projection scale neither blurs nor aliases without bound +const MIN_IMAGE_SCALE: f32 = 0.01; +const MAX_IMAGE_SCALE: f32 = 64.0; + +/// A material as the orb shows it +#[derive(Clone, Debug)] +pub(crate) struct OrbMaterial { + sources: BTreeMap, + projection: Projection, + sampling: Sampling, + /// The images the sources read, shared with the session + images: BTreeMap>, + /// The one channel shown on its own, unlit, as the viewport's channel view draws it; `None` = the whole material, lit + alone: Option, +} + +impl OrbMaterial { + /// One value per channel: a plain material's base colour, metallic and roughness + #[cfg(test)] + pub(crate) fn uniform(base: [f32; 3], metallic: f32, roughness: f32) -> OrbMaterial { + let sources = BTreeMap::from([ + (Channel::BaseColor, Source::Uniform(base)), + (Channel::Metallic, Source::Uniform([metallic; 3])), + (Channel::Roughness, Source::Uniform([roughness; 3])), + ]); + OrbMaterial { sources, projection: Projection::default(), sampling: Sampling::default(), images: BTreeMap::new(), alone: None } + } + + /// `fill` with the channels in `on`; channels that are off show their defaults, images come from `images` + pub(crate) fn of_fill(fill: &Fill, on: &[Channel], images: &std::collections::HashMap>) -> OrbMaterial { + OrbMaterial::with_channels(fill, ORB_CHANNELS.into_iter().filter(|channel| on.contains(channel)), images, None) + } + + /// `fill`'s `channel` alone (its default when the fill does not write it, `on` being the channels it writes) + pub(crate) fn of_channel(fill: &Fill, channel: Channel, on: &[Channel], images: &std::collections::HashMap>) -> OrbMaterial { + OrbMaterial::with_channels(fill, on.contains(&channel).then_some(channel), images, Some(channel)) + } + + fn with_channels( + fill: &Fill, + channels: impl IntoIterator, + images: &std::collections::HashMap>, + alone: Option, + ) -> OrbMaterial { + let sources: BTreeMap = channels.into_iter().map(|channel| (channel, fill.source(channel))).collect(); + let images = sources + .values() + .filter_map(|source| match source { + Source::Image { name, .. } => images.get(name).map(|image| (name.clone(), image.clone())), + _ => None, + }) + .collect(); + OrbMaterial { sources, projection: fill.projection.clone(), sampling: fill.sampling, images, alone } + } + + /// The channel the orb shows on its own, if any + pub(crate) fn alone(&self) -> Option { + self.alone + } + + /// The images it reads, held weakly: while a cached picture holds them, a new image can't take a freed one's address, which [`OrbMaterial::key`] hashes + pub(crate) fn image_handles(&self) -> Vec> { + self.images.values().map(Arc::downgrade).collect() + } + + /// A key that changes whenever the orb would look different + pub(crate) fn key(&self) -> u64 { + let mut hasher = DefaultHasher::new(); + + // Writing to a hasher cannot fail + let _ = write!(HashWriter(&mut hasher), "{:?}{:?}{:?}{:?}", self.sources, self.projection, self.sampling, self.alone); + for (name, image) in &self.images { + // The same name re-imported is a new image + (name, Arc::as_ptr(image) as usize, image.width, image.height).hash(&mut hasher); + } + hasher.finish() + } + + /// Whether any channel varies over the surface (a uniform material needs no per-pixel reads) + pub(crate) fn varies(&self) -> bool { + self.sources.values().any(|source| !matches!(source, Source::Uniform(_))) + } + + /// The material at `coords`; `footprint` = how far one orb pixel reaches in UVs + pub(crate) fn sample(&self, coords: &Coords, footprint: f32) -> OrbSample { + let value = |channel: Channel| self.value(channel, coords, footprint); + let [metallic, roughness, opacity] = [Channel::Metallic, Channel::Roughness, Channel::Opacity].map(|channel| value(channel)[0]); + OrbSample { base: value(Channel::BaseColor), metallic, roughness, normal: value(Channel::Normal), emissive: value(Channel::Emissive), opacity } + } + + /// The height at `coords` (0 without a height channel) + pub(crate) fn height(&self, coords: &Coords, footprint: f32) -> f32 { + self.value(Channel::Height, coords, footprint)[0] + } + + /// Whether the height channel varies (only then does it bump the surface) + pub(crate) fn has_relief(&self) -> bool { + self.sources.get(&Channel::Height).is_some_and(|source| !matches!(source, Source::Uniform(_))) + } + + /// `channel`'s value at `coords` (linear; normals 0..1 per component, height -1..1) + pub(crate) fn value(&self, channel: Channel, coords: &Coords, footprint: f32) -> [f32; 3] { + let Some(source) = self.sources.get(&channel) else { return channel.default_value() }; + match source { + Source::Uniform(value) => *value, + Source::Procedural { pattern, low, high, ramp } => { + let amount = procedural(pattern, &self.projection, coords); + + // A colour channel's gradient map colours the pattern as the layer stack does + if channel.kind() == ChannelKind::Color && !ramp.is_empty() { + texturecraft_engine::core::gradient(ramp, amount).unwrap_or_default() + } else { + [0, 1, 2].map(|k| low[k] + (high[k] - low[k]) * amount) + } + } + Source::Image { name, normal_format } => { + let Some(image) = self.images.get(name) else { return channel.default_value() }; + self.image_value(image, channel.kind(), *normal_format, coords, footprint) + } + + // An anchor reads another layer's result, which only the layer stack knows + Source::Anchor { .. } => channel.default_value(), + } + } + + fn image_value(&self, image: &ImageRes, kind: ChannelKind, normal_format: NormalFormat, coords: &Coords, footprint: f32) -> [f32; 3] { + let mut sum = [0.0f32; 3]; + for (uv, weight) in image_samples(&self.projection, coords).into_iter().filter(|(_, weight)| *weight > 0.0) { + let texel = image.sample_filtered(uv.x, uv.y, self.sampling, footprint * image.width as f32 * image_scale(&self.projection)); + for (total, value) in sum.iter_mut().zip(texel) { + *total += value * weight; + } + } + match kind { + ChannelKind::Color if image.srgb => sum.map(srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips + ChannelKind::NormalMap if normal_format == NormalFormat::DirectX => [sum[0], 1.0 - sum[1], sum[2]], + ChannelKind::Color | ChannelKind::NormalMap => sum, + ChannelKind::Scalar => [lum(sum); 3], + ChannelKind::Signed => [lum(sum) * 2.0 - 1.0; 3], + } + } +} + +/// How many image repeats the projection lays across the orb's width, roughly (sharper filtering for fewer) +fn image_scale(projection: &Projection) -> f32 { + let scale = match projection { + Projection::Triplanar { scale, .. } | Projection::Planar { scale, .. } => *scale, + Projection::Spherical { scale, .. } | Projection::Cylindrical { scale, .. } => scale.max(1.0), + Projection::Uv { scale, .. } => scale[0].abs().max(scale[1].abs()), + Projection::UvTile | Projection::Warp { .. } => 1.0, + }; + if scale.is_finite() { scale.abs().clamp(MIN_IMAGE_SCALE, MAX_IMAGE_SCALE) } else { 1.0 } +} + +/// Where a point of the unit orb lies for a fill's projection: its position and normal (both the unit direction `direction`), and UVs wrapping once around the equator (two across) and once from pole to pole +pub(crate) fn orb_coords(direction: Vec3) -> Coords { + let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5; + let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; + Coords { uv: Vec2::new(u * 2.0, v), pos: direction, nrm: direction } +} diff --git a/crates/ui-egui/src/orb_material/hash_writer.rs b/crates/ui-egui/src/orb_material/hash_writer.rs new file mode 100644 index 00000000..4c0c6140 --- /dev/null +++ b/crates/ui-egui/src/orb_material/hash_writer.rs @@ -0,0 +1,12 @@ +use std::fmt; +use std::hash::Hasher; + +/// Feeds formatted text straight into a hasher, so a `Debug` key needs no string +pub(super) struct HashWriter<'h, H: Hasher>(pub(super) &'h mut H); + +impl fmt::Write for HashWriter<'_, H> { + fn write_str(&mut self, text: &str) -> fmt::Result { + self.0.write(text.as_bytes()); + Ok(()) + } +} diff --git a/crates/ui-egui/src/orb_material/orb_sample.rs b/crates/ui-egui/src/orb_material/orb_sample.rs new file mode 100644 index 00000000..606b07fe --- /dev/null +++ b/crates/ui-egui/src/orb_material/orb_sample.rs @@ -0,0 +1,11 @@ +/// The orb's values at one point of its surface (linear) +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct OrbSample { + pub(crate) base: [f32; 3], + pub(crate) metallic: f32, + pub(crate) roughness: f32, + /// Tangent-space normal, OpenGL (+Y up), 0..1 per component + pub(crate) normal: [f32; 3], + pub(crate) emissive: [f32; 3], + pub(crate) opacity: f32, +} diff --git a/crates/ui-egui/src/orb_previews.rs b/crates/ui-egui/src/orb_previews.rs new file mode 100644 index 00000000..ffc478d4 --- /dev/null +++ b/crates/ui-egui/src/orb_previews.rs @@ -0,0 +1,352 @@ +//! Material orb pictures, cached by look and rendered off the UI thread: a quick low-resolution picture first, then the full one +//! (the web, which has no threads, renders the full picture at once) + +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::sync::{Arc, Mutex}; + +use egui::{ColorImage, Context, Id, TextureHandle, TextureOptions}; + +mod orb_job; +#[cfg(not(target_arch = "wasm32"))] +mod orb_result; +mod picture; +#[cfg(not(target_arch = "wasm32"))] +mod worker; + +pub(crate) use orb_job::OrbJob; +#[cfg(not(target_arch = "wasm32"))] +use orb_result::OrbResult; +use picture::Picture; +#[cfg(not(target_arch = "wasm32"))] +use worker::Worker; + +/// Pictures kept; the least recently drawn go first (a list of every plain material holds about fifty) +const MAX_PICTURES: usize = 160; + +/// Most places that keep their last drawn picture (an orb place outlives its look, so places can outnumber pictures) +const MAX_SHOWN_PLACES: usize = MAX_PICTURES * 2; + +/// The quick first picture is this many times smaller than the full one, and pictures this small skip it +const QUICK_DIVISOR: usize = 4; +const QUICK_BELOW_PX: usize = 48; + +/// Every orb picture of one egui context +#[derive(Default)] +pub struct OrbPreviews { + pictures: HashMap, + /// The picture last drawn at each place and the pass it was drawn in, shown while that place's new one renders + shown: HashMap, + #[cfg(not(target_arch = "wasm32"))] + worker: Option, +} + +type Shared = Arc>; + +impl OrbPreviews { + /// The picture to draw at `place` for the look `key` (see [`OrbJob::key_of`]): its own once rendered, else the last one drawn there (None before the first); `job` builds the render only when the look is new + pub(crate) fn texture(ctx: &Context, place: Id, key: u64, job: impl FnOnce() -> OrbJob) -> Option { + let shared = ctx.data_mut(|data| data.get_temp_mut_or_default::(Id::unique("orb_previews")).clone()); + let mut previews = shared.lock().ok()?; + previews.take_results(ctx); + let pass = ctx.cumulative_pass_nr(); + if let Entry::Vacant(slot) = previews.pictures.entry(key) { + let job = job(); + slot.insert(Picture { texture: None, full: false, drawn: pass, _images: job.material.image_handles() }); + #[cfg(not(target_arch = "wasm32"))] + let job = OrbJob { place, ..job }; + previews.start(ctx, job); + } + let ready = previews.pictures.get_mut(&key).and_then(|picture| { + picture.drawn = pass; + picture.texture.clone() + }); + let on_screen = match ready { + Some(texture) => { + previews.shown.insert(place, (texture.clone(), pass)); + Some(texture) + } + None => previews.shown.get_mut(&place).map(|(texture, drawn)| { + *drawn = pass; + texture.clone() + }), + }; + + // A new look or a new place may pass the cap + previews.forget_old(); + on_screen + } + + /// Whether every orb asked for has its full picture (tests and captures wait for this) + pub fn settled(ctx: &Context) -> bool { + let shared = ctx.data_mut(|data| data.get_temp_mut_or_default::(Id::unique("orb_previews")).clone()); + let Ok(mut previews) = shared.lock() else { return true }; + previews.take_results(ctx); + previews.pictures.values().all(|picture| picture.full) + } + + /// The size in pixels of the picture last drawn at `place` (tests) + #[cfg(test)] + pub(crate) fn shown_size(ctx: &Context, place: &str) -> Option<[usize; 2]> { + let shared = ctx.data_mut(|data| data.get_temp_mut_or_default::(Id::unique("orb_previews")).clone()); + let previews = shared.lock().ok()?; + previews.shown.get(&Id::unique(("material_orb", place))).map(|(texture, _)| texture.size()) + } + + fn store(&mut self, ctx: &Context, key: u64, full: bool, image: ColorImage) { + if let Some(picture) = self.pictures.get_mut(&key) + && !picture.full + { + picture.texture = Some(ctx.load_texture("material-orb", image, TextureOptions::LINEAR)); + picture.full = full; + } + } + + /// Drop the least recently drawn pictures past [`MAX_PICTURES`] and places' last shown pictures past [`MAX_SHOWN_PLACES`] + fn forget_old(&mut self) { + while self.pictures.len() > MAX_PICTURES { + let Some(oldest) = self.pictures.iter().min_by_key(|(_, picture)| picture.drawn).map(|(key, _)| *key) else { break }; + self.pictures.remove(&oldest); + } + + // A place no longer drawn (a deleted layer) must not keep its texture alive + while self.shown.len() > MAX_SHOWN_PLACES { + let Some(oldest) = self.shown.iter().min_by_key(|(_, (_, drawn))| *drawn).map(|(place, _)| *place) else { break }; + self.shown.remove(&oldest); + } + } + + /// The web renders the full picture at once + #[cfg(target_arch = "wasm32")] + fn start(&mut self, ctx: &Context, job: OrbJob) { + let job = OrbJob { quick: false, ..job }; + self.store(ctx, job.key, true, job.picture()); + } + + #[cfg(target_arch = "wasm32")] + fn take_results(&mut self, _ctx: &Context) {} + + #[cfg(not(target_arch = "wasm32"))] + fn start(&mut self, ctx: &Context, job: OrbJob) { + let key = job.key; + let worker = match self.worker.take() { + Some(worker) => worker, + None => match Worker::start() { + Some(worker) => worker, + None => { + // No thread: render here rather than show nothing + let job = OrbJob { quick: false, ..job }; + self.store(ctx, key, true, job.picture()); + return; + } + }, + }; + match worker.jobs.send((job, ctx.clone())) { + Ok(()) => self.worker = Some(worker), + Err(std::sync::mpsc::SendError((job, _))) => { + let job = OrbJob { quick: false, ..job }; + self.store(ctx, key, true, job.picture()); + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn take_results(&mut self, ctx: &Context) { + let Some(worker) = &self.worker else { return }; + let results: Vec = worker.results.try_iter().collect(); + for result in results { + match result { + OrbResult::Picture { key, full, image } => self.store(ctx, key, full, image), + OrbResult::Dropped { key } => { + // Asked for again the next time it is drawn (its place keeps showing what it last showed) + self.pictures.remove(&key); + } + } + } + } +} + +/// Keep only the newest job per place (others than [`Id::NULL`]); returns the keys of the jobs dropped +#[cfg(not(target_arch = "wasm32"))] +fn newest_per_place(waiting: &mut Vec) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut dropped = Vec::new(); + let mut kept: Vec = Vec::with_capacity(waiting.len()); + for job in waiting.drain(..).rev() { + if job.place == Id::NULL || seen.insert(job.place) { + kept.push(job); + } else { + dropped.push(job.key); + } + } + kept.reverse(); + *waiting = kept; + dropped +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + use std::time::{Duration, Instant}; + + use egui::Color32; + use texturecraft_engine::compose::ImageRes; + use texturecraft_engine::core::{Channel, Fill, Source}; + + use super::*; + use crate::orb_material::OrbMaterial; + + fn copper(roughness: f32) -> OrbMaterial { + OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, roughness) + } + + /// One UI pass; nothing draws the textures it makes, so their updates are dropped + fn run(ctx: &Context, ui: impl FnMut(&Context)) { + let mut output = ctx.run_pass(Default::default(), ui); + output.textures_delta.clear(); + } + + /// Draw `job` at `place` every pass until it is full or 20 s pass; returns the sizes shown on the way + fn draw_until_settled(ctx: &Context, place: Id, job: &OrbJob) -> Vec<[usize; 2]> { + let start = Instant::now(); + let mut sizes = Vec::new(); + while start.elapsed() < Duration::from_secs(20) { + let mut size = None; + run(ctx, |ctx| size = OrbPreviews::texture(ctx, place, job.key, || job.clone()).map(|texture| texture.size())); + if let Some(size) = size + && sizes.last() != Some(&size) + { + sizes.push(size); + } + if OrbPreviews::settled(ctx) { + run(ctx, |ctx| size = OrbPreviews::texture(ctx, place, job.key, || job.clone()).map(|texture| texture.size())); + if let Some(size) = size + && sizes.last() != Some(&size) + { + sizes.push(size); + } + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + sizes + } + + #[test] + fn an_orb_renders_off_the_ui_thread_quick_first_then_full_and_is_cached_by_its_look() { + let ctx = Context::default(); + let place = Id::unique("orb"); + let job = OrbJob::new(copper(0.3), 200, Color32::BLACK); + let mut first = None; + run(&ctx, |ctx| first = OrbPreviews::texture(ctx, place, job.key, || job.clone())); + assert!(first.is_none(), "the first pass does not wait for the render"); + let sizes = draw_until_settled(&ctx, place, &job); + + // A fast render can bring both pictures between two frames, so only the full one is sure to show; the quick one never comes after it + let quick_then_full: &[[usize; 2]] = &[[50, 50], [200, 200]]; + assert!(sizes == quick_then_full || sizes == quick_then_full[1..], "the quick picture, if shown, then the full one: {sizes:?}"); + assert!(OrbPreviews::settled(&ctx)); + + // The same look again: drawn at once from the cache, nothing new to render + let mut again = None; + run(&ctx, |ctx| again = OrbPreviews::texture(ctx, place, job.key, || job.clone())); + assert_eq!(again.map(|texture| texture.size()), Some([200, 200])); + assert!(OrbPreviews::settled(&ctx), "a cached look renders nothing"); + + // A new look keeps the old picture on screen until its own arrives + let rougher = OrbJob::new(copper(0.8), 200, Color32::BLACK); + let mut meanwhile = None; + run(&ctx, |ctx| meanwhile = OrbPreviews::texture(ctx, place, rougher.key, || rougher.clone())); + assert!(meanwhile.is_some(), "the last picture stays while the new one renders"); + assert!(!OrbPreviews::settled(&ctx), "the new look is rendering"); + draw_until_settled(&ctx, place, &rougher); + assert!(OrbPreviews::settled(&ctx)); + } + + /// A dropped context lets go of its orb pictures and closes its worker's job channel: the idle worker holds no context + #[test] + fn a_dropped_context_frees_its_previews_while_the_worker_idles() { + // Long enough for the worker to finish its last job on a busy machine + const ATTEMPTS: usize = 2000; + const WAIT: Duration = Duration::from_millis(5); + let ctx = Context::default(); + let job = OrbJob::new(copper(0.3), 64, Color32::BLACK); + draw_until_settled(&ctx, Id::unique("orb"), &job); + let shared = ctx.data(|data| data.get_temp::(Id::unique("orb_previews"))).unwrap(); + let previews = Arc::downgrade(&shared); + drop(shared); + + drop(ctx); + + let freed = (0..ATTEMPTS).any(|_| { + let freed = previews.upgrade().is_none(); + if !freed { + std::thread::sleep(WAIT); + } + freed + }); + assert!(freed, "the worker kept the dropped context and its previews alive"); + } + + #[test] + fn a_newer_look_for_the_same_place_replaces_one_still_waiting() { + let job = |roughness: f32| OrbJob { place: Id::unique("orb"), ..OrbJob::new(copper(roughness), 64, Color32::BLACK) }; + let other = OrbJob { place: Id::unique("other"), ..OrbJob::new(copper(0.5), 64, Color32::BLACK) }; + let mut waiting = vec![job(0.1), other.clone(), job(0.2), job(0.3)]; + let dropped = newest_per_place(&mut waiting); + assert_eq!(dropped.len(), 2); + assert_eq!(waiting.iter().map(|job| job.key).collect::>(), vec![other.key, job(0.3).key]); + } + + #[test] + fn places_no_longer_drawn_let_go_of_their_last_picture_past_the_cap() { + let ctx = Context::default(); + let texture = ctx.load_texture("orb", ColorImage::filled([1, 1], Color32::BLACK), TextureOptions::LINEAR); + let mut previews = OrbPreviews::default(); + let places = MAX_SHOWN_PLACES as u64 + 10; + for pass in 0..places { + previews.shown.insert(Id::unique(("orb", pass)), (texture.clone(), pass)); + } + + previews.forget_old(); + + assert_eq!(previews.shown.len(), MAX_SHOWN_PLACES, "the cap holds for places too"); + assert!(!previews.shown.contains_key(&Id::unique(("orb", 0_u64))), "the least recently drawn place goes first"); + assert!(previews.shown.contains_key(&Id::unique(("orb", places - 1))), "the latest drawn place stays"); + } + + /// An orb of a fill whose base colour reads `image` under one name, the name a re-import keeps + fn image_orb(image: Arc) -> OrbJob { + let fill = Fill { sources: BTreeMap::from([(Channel::BaseColor, Source::image(REIMPORTED))]), ..Fill::default() }; + let images = HashMap::from([(REIMPORTED.to_owned(), image)]); + OrbJob::new(OrbMaterial::of_fill(&fill, &[Channel::BaseColor], &images), 64, Color32::BLACK) + } + + /// An image name imported twice + const REIMPORTED: &str = "grain"; + + #[test] + fn a_new_image_under_a_cached_ones_name_and_size_gets_its_own_picture() { + let ctx = Context::default(); + let place = Id::unique("orb"); + let image = Arc::new(ImageRes::new(2, 2, vec![[0.1; 4]; 4], false)); + let first = image_orb(Arc::clone(&image)); + draw_until_settled(&ctx, place, &first); + let first_key = first.key; + drop(first); + + // The cached picture holds the image weakly, so its address stays taken however the allocator reuses blocks + assert!(Arc::weak_count(&image) >= 1, "the cached picture keeps the image's address"); + drop(image); + + // Same name and size: the freed image's address must not come back to the cached picture's key + let second = image_orb(Arc::new(ImageRes::new(2, 2, vec![[0.9; 4]; 4], false))); + assert_ne!(second.key, first_key, "the new image's orb is drawn anew"); + } + + #[test] + fn small_orbs_skip_the_quick_picture() { + assert!(!OrbJob::new(copper(0.3), 24, Color32::BLACK).quick); + assert!(OrbJob::new(copper(0.3), 96, Color32::BLACK).quick); + } +} diff --git a/crates/ui-egui/src/orb_previews/orb_job.rs b/crates/ui-egui/src/orb_previews/orb_job.rs new file mode 100644 index 00000000..f14316cd --- /dev/null +++ b/crates/ui-egui/src/orb_previews/orb_job.rs @@ -0,0 +1,49 @@ +use std::hash::{DefaultHasher, Hash, Hasher}; + +#[cfg(not(target_arch = "wasm32"))] +use egui::Id; +use egui::{Color32, ColorImage}; + +use super::{QUICK_BELOW_PX, QUICK_DIVISOR}; +use crate::material_orb::render; +use crate::orb_material::OrbMaterial; + +/// One orb to render +#[derive(Clone, Debug)] +pub(crate) struct OrbJob { + pub(super) key: u64, + pub(super) material: OrbMaterial, + pub(super) side: usize, + pub(super) backdrop: Color32, + /// Where it is drawn: a newer job for the same place replaces an older one still waiting (the web renders each job at once) + #[cfg(not(target_arch = "wasm32"))] + pub(super) place: Id, + /// The quick picture is still to come + pub(super) quick: bool, +} + +impl OrbJob { + pub(crate) fn new(material: OrbMaterial, side: usize, backdrop: Color32) -> OrbJob { + OrbJob { + key: OrbJob::key_of(&material, side, backdrop), + material, + side, + backdrop, + #[cfg(not(target_arch = "wasm32"))] + place: Id::NULL, + quick: side >= QUICK_BELOW_PX, + } + } + + /// The cache key of `material`'s orb `side` pixels square on `backdrop`, without building the job + pub(crate) fn key_of(material: &OrbMaterial, side: usize, backdrop: Color32) -> u64 { + let mut hasher = DefaultHasher::new(); + (material.key(), side, backdrop.to_array()).hash(&mut hasher); + hasher.finish() + } + + pub(super) fn picture(&self) -> ColorImage { + let side = if self.quick { self.side / QUICK_DIVISOR } else { self.side }; + render(&self.material, side, self.backdrop) + } +} diff --git a/crates/ui-egui/src/orb_previews/orb_result.rs b/crates/ui-egui/src/orb_previews/orb_result.rs new file mode 100644 index 00000000..54666899 --- /dev/null +++ b/crates/ui-egui/src/orb_previews/orb_result.rs @@ -0,0 +1,14 @@ +use egui::ColorImage; + +/// What the worker answers +pub(super) enum OrbResult { + Picture { + key: u64, + full: bool, + image: ColorImage, + }, + /// A newer job for its place replaced it before it was finished + Dropped { + key: u64, + }, +} diff --git a/crates/ui-egui/src/orb_previews/picture.rs b/crates/ui-egui/src/orb_previews/picture.rs new file mode 100644 index 00000000..06a6d813 --- /dev/null +++ b/crates/ui-egui/src/orb_previews/picture.rs @@ -0,0 +1,14 @@ +use std::sync::Weak; + +use egui::TextureHandle; +use texturecraft_engine::compose::ImageRes; + +/// A cached picture +pub(super) struct Picture { + pub(super) texture: Option, + pub(super) full: bool, + /// The pass it was last drawn in + pub(super) drawn: u64, + /// The images it shows, so no new image reuses their addresses (and so their key) while it is cached + pub(super) _images: Vec>, +} diff --git a/crates/ui-egui/src/orb_previews/worker.rs b/crates/ui-egui/src/orb_previews/worker.rs new file mode 100644 index 00000000..ad7d8260 --- /dev/null +++ b/crates/ui-egui/src/orb_previews/worker.rs @@ -0,0 +1,73 @@ +use egui::Context; + +use super::{OrbJob, OrbResult, newest_per_place}; + +/// The thread that renders orbs +pub(super) struct Worker { + /// Each job comes with the context to repaint when its picture is ready + pub(super) jobs: std::sync::mpsc::Sender<(OrbJob, Context)>, + pub(super) results: std::sync::mpsc::Receiver, +} + +impl Worker { + pub(super) fn start() -> Option { + let (jobs, job_rx) = std::sync::mpsc::channel::<(OrbJob, Context)>(); + let (result_tx, results) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("texturecraft-material-orbs".into()).spawn(move || { + // Its own pool keeps orbs from queuing ahead of painting and compositing + 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-orb-{i}")).build(); + let mut waiting: Vec = Vec::new(); + let mut repaint: Option = None; + loop { + if waiting.is_empty() { + // Idle, the thread holds no context: the context owns the job sender, so a held one would keep both alive + drop(repaint.take()); + let Ok((job, ctx)) = job_rx.recv() else { break }; + waiting.push(job); + repaint = Some(ctx); + } + for (job, ctx) in job_rx.try_iter() { + waiting.push(job); + repaint = Some(ctx); + } + for key in newest_per_place(&mut waiting) { + if result_tx.send(OrbResult::Dropped { key }).is_err() { + return; + } + } + + // Every quick picture before any full one, so a list fills in at once + let next = waiting.iter().position(|job| job.quick).unwrap_or(0); + if next >= waiting.len() { + continue; + } + + let mut job = waiting.remove(next); + let image = match &pool { + Ok(pool) => pool.install(|| job.picture()), + Err(_) => job.picture(), + }; + let full = !job.quick; + if result_tx.send(OrbResult::Picture { key: job.key, full, image }).is_err() { + return; + } + + if let Some(ctx) = &repaint { + ctx.request_repaint(); + } + if !full { + job.quick = false; + waiting.push(job); + } + } + }); + match spawned { + Ok(_) => Some(Worker { jobs, results }), + Err(e) => { + log::warn!("could not start the material orb worker: {e}"); + None + } + } + } +} From bb4dd3799c4b52783c495f6f843e33fef249d198 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:27 +0000 Subject: [PATCH 021/153] Colour: the colour picker window and the Swatches row --- .../ui-egui/src/color_picker/color_model.rs | 26 + crates/ui-egui/src/color_picker/color_pick.rs | 35 ++ .../ui-egui/src/color_picker/color_space.rs | 41 ++ crates/ui-egui/src/color_picker/mod.rs | 116 ++++ .../ui-egui/src/color_picker/picker_state.rs | 95 ++++ .../ui-egui/src/color_picker/swatch_edit.rs | 8 + .../ui-egui/src/property_sheet/color_bar.rs | 336 +++++++++++ .../src/property_sheet/color_picker_rows.rs | 522 ++++++++++++++++++ 8 files changed, 1179 insertions(+) create mode 100644 crates/ui-egui/src/color_picker/color_model.rs create mode 100644 crates/ui-egui/src/color_picker/color_pick.rs create mode 100644 crates/ui-egui/src/color_picker/color_space.rs create mode 100644 crates/ui-egui/src/color_picker/mod.rs create mode 100644 crates/ui-egui/src/color_picker/picker_state.rs create mode 100644 crates/ui-egui/src/color_picker/swatch_edit.rs create mode 100644 crates/ui-egui/src/property_sheet/color_bar.rs create mode 100644 crates/ui-egui/src/property_sheet/color_picker_rows.rs diff --git a/crates/ui-egui/src/color_picker/color_model.rs b/crates/ui-egui/src/color_picker/color_model.rs new file mode 100644 index 00000000..b72a9331 --- /dev/null +++ b/crates/ui-egui/src/color_picker/color_model.rs @@ -0,0 +1,26 @@ +/// What the picker's three sliders edit +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum ColorModel { + #[default] + Hsv, + Rgb, +} + +impl ColorModel { + pub(crate) const ALL: [ColorModel; 2] = [ColorModel::Hsv, ColorModel::Rgb]; + + pub(crate) fn name(self) -> &'static str { + match self { + ColorModel::Hsv => "HSV", + ColorModel::Rgb => "RGB", + } + } + + /// The letters before the three sliders + pub(crate) fn letters(self) -> [&'static str; 3] { + match self { + ColorModel::Hsv => ["H", "S", "V"], + ColorModel::Rgb => ["R", "G", "B"], + } + } +} diff --git a/crates/ui-egui/src/color_picker/color_pick.rs b/crates/ui-egui/src/color_picker/color_pick.rs new file mode 100644 index 00000000..d26c2ba7 --- /dev/null +++ b/crates/ui-egui/src/color_picker/color_pick.rs @@ -0,0 +1,35 @@ +use egui::{Context, Id}; + +use super::SwatchEdit; + +/// What a colour bar did this frame: the colour picked (linear) and whether it continues the last edit, a click on its eyedropper, or a change to the swatches +#[derive(Clone, Copy, Debug)] +pub(crate) struct ColorPick { + /// The bar's id: an eyedropper pick for it is handed over with [`ColorPick::deliver`] + pub(crate) id: Id, + pub(crate) picked: Option<[f32; 3]>, + /// The pick continues a drag: it joins the last undo step + pub(crate) merge: bool, + pub(crate) eyedropper: bool, + pub(crate) swatch: Option, +} + +impl ColorPick { + pub(crate) fn none(id: Id) -> Self { + ColorPick { id, picked: None, merge: false, eyedropper: false, swatch: None } + } + + /// Hands the colour an eyedropper picked to the bar `target`, which reports it next frame + pub(crate) fn deliver(ctx: &Context, target: Id, linear: [f32; 3]) { + ctx.data_mut(|data| data.insert_temp(Self::delivery_id(target), linear)); + } + + /// The colour an eyedropper picked for the bar `target`, once + pub(crate) fn delivered(ctx: &Context, target: Id) -> Option<[f32; 3]> { + ctx.data_mut(|data| data.remove_temp::<[f32; 3]>(Self::delivery_id(target))) + } + + fn delivery_id(target: Id) -> Id { + target.with("eyedropped") + } +} diff --git a/crates/ui-egui/src/color_picker/color_space.rs b/crates/ui-egui/src/color_picker/color_space.rs new file mode 100644 index 00000000..f659f33d --- /dev/null +++ b/crates/ui-egui/src/color_picker/color_space.rs @@ -0,0 +1,41 @@ +use texturecraft_engine::texel::{linear_to_srgb, srgb_to_linear}; + +/// The space the picker shows a colour's values in; the fill always stores linear values +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum ColorSpace { + #[default] + Srgb, + Linear, +} + +impl ColorSpace { + pub(crate) const ALL: [ColorSpace; 2] = [ColorSpace::Srgb, ColorSpace::Linear]; + + pub(crate) fn name(self) -> &'static str { + match self { + ColorSpace::Srgb => "sRGB", + ColorSpace::Linear => crate::i18n::tr("Linear"), + } + } + + /// A linear colour's values in this space + pub(crate) fn shown(self, linear: [f32; 3]) -> [f32; 3] { + match self { + ColorSpace::Srgb => linear.map(linear_to_srgb), + ColorSpace::Linear => linear, + } + } + + /// The linear colour of values shown in this space + pub(crate) fn linear(self, shown: [f32; 3]) -> [f32; 3] { + match self { + ColorSpace::Srgb => shown.map(srgb_to_linear), + ColorSpace::Linear => shown, + } + } + + /// The screen's sRGB values for values shown in this space, so gradients paint the colours they pick + pub(crate) fn display(self, shown: [f32; 3]) -> [f32; 3] { + ColorSpace::Srgb.shown(self.linear(shown)) + } +} diff --git a/crates/ui-egui/src/color_picker/mod.rs b/crates/ui-egui/src/color_picker/mod.rs new file mode 100644 index 00000000..0a00fc72 --- /dev/null +++ b/crates/ui-egui/src/color_picker/mod.rs @@ -0,0 +1,116 @@ +//! The colour picker a colour bar opens: the space its values are shown in, the model its sliders edit, its memory between frames and what it hands back + +mod color_model; +mod color_pick; +mod color_space; +mod picker_state; +mod swatch_edit; + +pub(crate) use color_model::ColorModel; +pub(crate) use color_pick::ColorPick; +pub(crate) use color_space::ColorSpace; +pub(crate) use picker_state::PickerState; +pub(crate) use swatch_edit::SwatchEdit; + +/// Where the open picker window stood and the pass that drew it +fn window_id() -> egui::Id { + egui::Id::unique("color_picker_window") +} + +/// Records the open picker window's `face` this pass, so Escape and the popup it opened from treat it as on top of them +pub(crate) fn remember_window(ctx: &egui::Context, face: egui::Rect) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(window_id(), (face, pass))); +} + +/// The picker window closed this pass +pub(crate) fn forget_window(ctx: &egui::Context) { + ctx.data_mut(|data| data.remove::<(egui::Rect, u64)>(window_id())); +} + +/// The picker window drawn this pass or the last one, if a picker is open +pub(crate) fn open_window(ctx: &egui::Context) -> Option { + let (face, pass) = ctx.data(|data| data.get_temp::<(egui::Rect, u64)>(window_id()))?; + (pass.saturating_add(1) >= ctx.cumulative_pass_nr()).then_some(face) +} + +/// Set while the press that closed the picker is still held +fn closing_id() -> egui::Id { + egui::Id::unique("color_picker_closing") +} + +/// A press outside the picker closed it: until it is released the views take no paint or gizmo input from it +pub(crate) fn closed_by_press(ctx: &egui::Context) { + ctx.data_mut(|data| data.insert_temp(closing_id(), true)); +} + +/// Whether a press in a view must leave painting and the projection gizmos alone: a picker is open (the press only closes it), or the press that closed it is still held or just released (the release would paint a dab) +pub(crate) fn blocks_view_press(ctx: &egui::Context) -> bool { + if !ctx.input(|input| input.pointer.any_down() || input.pointer.any_released()) { + ctx.data_mut(|data| data.remove::(closing_id())); + } + open_window(ctx).is_some() || ctx.data(|data| data.get_temp::(closing_id())).unwrap_or(false) +} + +/// `rgb` (0..1 each) as 0..255 each, as the hex code and the copied values give it +pub(crate) fn eight_bit(rgb: [f32; 3]) -> [u8; 3] { + rgb.map(component_byte) +} + +/// One colour or coverage component (0..1, clamped) as 0..255 +pub(crate) fn component_byte(component: f32) -> u8 { + (component.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +/// `rgb` (0..1 each) as six hex digits, as the hex field shows it +pub(crate) fn hex(rgb: [f32; 3]) -> String { + let [red, green, blue] = eight_bit(rgb); + format!("{red:02X}{green:02X}{blue:02X}") +} + +/// A typed hex code (`#` optional, 6 or 3 digits) as 0..1 components; None when it isn't one +pub(crate) fn parse_hex(text: &str) -> Option<[f32; 3]> { + let text = text.trim(); + let digits = text.strip_prefix('#').unwrap_or(text); + + // Only hex digits: a sign ("+F" parses as a number) or a second `#` makes it no code + if !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + + let full: String = match digits.len() { + 3 => digits.chars().flat_map(|digit| [digit, digit]).collect(), + 6 => digits.to_owned(), + _ => return None, + }; + let channel = |at: usize| full.get(at..at + 2).and_then(|pair| u8::from_str_radix(pair, 16).ok()).map(|byte| f32::from(byte) / 255.0); + Some([channel(0)?, channel(2)?, channel(4)?]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hex_codes_read_back_what_they_show() { + assert_eq!(hex([1.0, 0.5, 0.0]), "FF8000"); + assert_eq!(parse_hex("#ff8000"), Some([1.0, 128.0 / 255.0, 0.0])); + assert_eq!(parse_hex("f80"), parse_hex("FF8800")); + assert_eq!(parse_hex("12345"), None); + assert_eq!(parse_hex("GG0000"), None); + assert_eq!(parse_hex("€€€"), None, "multi-byte text is not a code"); + assert_eq!(parse_hex("+F8000"), None, "a sign is not a digit"); + assert_eq!(parse_hex("##f80"), None, "one `#` at most"); + } + + #[test] + fn each_space_shows_and_reads_back_the_same_linear_colour() { + let linear = [0.2, 0.5, 0.9]; + for space in ColorSpace::ALL { + let back = space.linear(space.shown(linear)); + assert!(back.iter().zip(linear).all(|(a, b)| (a - b).abs() < 1e-4), "{space:?}: {back:?}"); + } + assert!(ColorSpace::Srgb.shown(linear)[0] > linear[0], "sRGB shows dark values brighter"); + assert_eq!(ColorSpace::Linear.shown(linear), linear); + } +} diff --git a/crates/ui-egui/src/color_picker/picker_state.rs b/crates/ui-egui/src/color_picker/picker_state.rs new file mode 100644 index 00000000..d6b90abf --- /dev/null +++ b/crates/ui-egui/src/color_picker/picker_state.rs @@ -0,0 +1,95 @@ +use egui::ecolor::hsv_from_rgb; + +use super::{ColorModel, ColorSpace}; + +/// One colour bar's picker between frames: open or not, the colour it opened on, and the hue and saturation a gray would lose +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct PickerState { + pub(crate) open: bool, + /// The colour when the picker opened (linear), shown beside the new one and restored by a click + pub(crate) before: [f32; 3], + /// The colour being edited (linear) + pub(crate) linear: [f32; 3], + /// Hue, saturation and value of the shown values, kept across grays and blacks + pub(crate) hsv: [f32; 3], + pub(crate) space: ColorSpace, + pub(crate) model: ColorModel, + /// Where its title bar's drag left the window's top left corner; None while it stands beside the panel + pub(crate) moved_to: Option, +} + +impl PickerState { + /// Follows `linear` when it changed outside the picker (undo, another panel), keeping the hue when it didn't + pub(crate) fn follow(&mut self, linear: [f32; 3]) { + if self.linear != linear { + self.set_linear(linear); + } + } + + /// Sets the colour from outside the hue field (typed, restored, picked), deriving hue, saturation and value again + pub(crate) fn set_linear(&mut self, linear: [f32; 3]) { + self.linear = linear; + let (hue, saturation, value) = hsv_from_rgb(self.shown()); + self.hsv = [hue, saturation, value]; + } + + /// Sets the colour from hue, saturation and value (field, strip, HSV sliders) + pub(crate) fn set_hsv(&mut self, hsv: [f32; 3]) { + self.hsv = hsv.map(|part| part.clamp(0.0, 1.0)); + let [hue, saturation, value] = self.hsv; + self.linear = self.space.linear(egui::ecolor::rgb_from_hsv((hue, saturation, value))); + } + + /// Shows the values in `space` from now on + pub(crate) fn set_space(&mut self, space: ColorSpace) { + let [hue, saturation, _] = self.hsv; + self.space = space; + self.set_linear(self.linear); + + // A gray keeps the hue it had and a black its saturation too, so raising Value brings the colour back + let [_, new_saturation, new_value] = self.hsv; + if new_saturation == 0.0 { + self.hsv[0] = hue; + } + if new_value == 0.0 { + self.hsv[1] = saturation; + } + } + + /// The colour's values in the shown space + pub(crate) fn shown(&self) -> [f32; 3] { + self.space.shown(self.linear) + } + + /// Opens on `linear`, which becomes the colour to go back to + pub(crate) fn open_on(&mut self, linear: [f32; 3]) { + self.open = true; + self.before = linear; + self.set_linear(linear); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_black_keeps_its_hue_and_saturation_through_a_colour_space_change() { + let mut state = PickerState::default(); + let blue = 2.0 / 3.0; + state.set_hsv([blue, 1.0, 0.0]); + state.set_space(ColorSpace::Linear); + assert_eq!(state.hsv, [blue, 1.0, 0.0], "black keeps the field's hue and saturation"); + state.set_hsv([state.hsv[0], state.hsv[1], 1.0]); + let [red, green, blue_part] = state.linear; + assert!(blue_part > 0.9 && red < 0.01 && green < 0.01, "raising Value brings blue back: {:?}", state.linear); + + // A gray keeps its hue but takes its own saturation; a colour is read again + state.set_hsv([0.25, 0.0, 0.5]); + state.set_space(ColorSpace::Srgb); + assert_eq!((state.hsv[0], state.hsv[1]), (0.25, 0.0)); + state.set_hsv([0.0, 1.0, 1.0]); + state.set_space(ColorSpace::Linear); + assert!(state.hsv[0].abs() < 1e-4 && (state.hsv[1] - 1.0).abs() < 1e-4, "red reads as red: {:?}", state.hsv); + } +} diff --git a/crates/ui-egui/src/color_picker/swatch_edit.rs b/crates/ui-egui/src/color_picker/swatch_edit.rs new file mode 100644 index 00000000..c2f4d7a0 --- /dev/null +++ b/crates/ui-egui/src/color_picker/swatch_edit.rs @@ -0,0 +1,8 @@ +/// A change the picker's Swatches row asks of the project's swatches +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum SwatchEdit { + /// The + chip: keep the picker's colour (linear) as a swatch + Add([f32; 3]), + /// A swatch's Remove (its right-click menu), by index + Remove(usize), +} diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs new file mode 100644 index 00000000..82fe8887 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -0,0 +1,336 @@ +//! A uniform colour's bar with its eyedropper, and the colour picker window it opens beside the panel + +use egui::{ + Align2, CornerRadius, CursorIcon, FontId, Id, Order, Pos2, Rect, Response, Role, Sense, Shadow, Stroke, StrokeKind, UiBuilder, Vec2, WidgetInfo, pos2, vec2, +}; +use egui_phosphor::regular as ic; + +use super::color_picker_rows::{FIELD_HEIGHT, FIELD_MIN_HEIGHT, hex_took_escape}; +use super::{PAD, PropertySheet}; +use crate::color_picker::{ColorModel, ColorPick, ColorSpace, PickerState}; +use crate::fill_material_panel::shown_color; +use crate::i18n::tr; +use crate::theme::HARD_SHADOW; + +/// Height of a colour bar +const COLOR_BAR_HEIGHT: f32 = 16.0; + +/// Room the bar leaves at the right edge for its eyedropper, and from the right edge to the eyedropper's centre +const EYEDROPPER_ROOM: f32 = 26.0; +const EYEDROPPER_INSET: f32 = 9.0; + +/// Size of the eyedropper's click target +const EYEDROPPER_TARGET: f32 = 18.0; + +/// Air between the panel and the picker standing beside it +const WINDOW_GAP: f32 = 6.0; + +/// Height of the picker's title bar and size of its title +const TITLE_HEIGHT: f32 = 26.0; +const TITLE_TEXT_SIZE: f32 = 11.0; + +/// Half the close glyph's ink width: its centre sits this far in from the right padding, so the ink ends where the content does +const CLOSE_INK_HALF_WIDTH: f32 = 4.0; + +/// Size of the close glyph and of its click target +const CLOSE_GLYPH_SIZE: f32 = 12.0; +const CLOSE_TARGET: f32 = 18.0; + +/// From the title bar to the picker's first row, so that row's control sits 10 below it like a card's under its top +const PICKER_TOP: f32 = 8.0; + +/// Air under the picker's last line, as under a card's last control +const PICKER_BOTTOM: f32 = 10.0; + +/// The picker's height before it was first measured, so it stays on screen beside a bar near the window's bottom +const PICKER_HEIGHT_GUESS: f32 = 340.0; + +/// Corner radius of a colour bar +const BAR_RADIUS: u8 = 3; + +/// Corner radius of the picker +const PICKER_RADIUS: u8 = 7; + +/// The picker's shadow: offset down-right, no blur +const PICKER_SHADOW: Shadow = Shadow { offset: [2, 4], blur: 0, spread: 0, color: HARD_SHADOW }; + +/// Where the space and model last picked are kept, so the next picker opens with them +const PREFERENCES_KEY: &str = "color_picker_preferences"; + +/// Where the size a resize left (width, field height) is kept, so every picker opens with it, in this run and the next +const SIZE_KEY: &str = "color_picker_size"; + +/// Narrowest the picker resizes to: its dropdowns, hex field and slider tracks keep their room +const PICKER_MIN_WIDTH: f32 = 240.0; + +/// Depth of the grip inside each edge (in the rows' side padding and the air under the last line), and side of a corner's grip (small enough to leave × its click) +const RESIZE_GRIP: f32 = 5.0; +const RESIZE_CORNER: f32 = 8.0; + +/// The picker state stored at `state_id`, else a closed picker +fn picker_state(ctx: &egui::Context, state_id: Id) -> PickerState { + ctx.data(|data| data.get_temp::(state_id)).unwrap_or_default() +} + +/// Opens `state` on `linear` in the colour space and model the user last picked in any picker +fn open_picker(ctx: &egui::Context, state: &mut PickerState, linear: [f32; 3]) { + let (space, model) = ctx.data(|data| data.get_temp::<(ColorSpace, ColorModel)>(Id::unique(PREFERENCES_KEY))).unwrap_or_default(); + state.space = space; + state.model = model; + state.open_on(linear); +} + +impl PropertySheet<'_> { + /// A uniform colour (linear): a bar across the card that opens the picker (with the project's `swatches`), and the eyedropper; `eyedropping` is the bar whose pick waits for its click + pub(crate) fn color_bar(&mut self, label: &str, linear: [f32; 3], eyedropping: Option, swatches: &[[f32; 3]]) -> ColorPick { + let center_y = self.take(super::ROW_HEIGHT).center().y; + let bar = Rect::from_min_max(pos2(self.left, center_y - COLOR_BAR_HEIGHT / 2.0), pos2(self.right - EYEDROPPER_ROOM, center_y + COLOR_BAR_HEIGHT / 2.0)); + self.color_bar_at(bar, self.right - EYEDROPPER_INSET, label, linear, eyedropping, swatches) + } + + /// [`Self::color_bar`] in the controls column, beside `label` + pub(crate) fn color_bar_led(&mut self, label: &str, linear: [f32; 3], eyedropping: Option, swatches: &[[f32; 3]]) -> ColorPick { + let (control, center_y) = self.row(label); + let bar = Rect::from_min_max( + pos2(control.left(), center_y - COLOR_BAR_HEIGHT / 2.0), + pos2(control.right() - EYEDROPPER_ROOM, center_y + COLOR_BAR_HEIGHT / 2.0), + ); + self.color_bar_at(bar, self.right - EYEDROPPER_INSET, label, linear, eyedropping, swatches) + } + + /// A colour bar drawn in `bar`, its eyedropper centred at `eyedropper_x` + pub(super) fn color_bar_at( + &mut self, + bar: Rect, + eyedropper_x: f32, + label: &str, + linear: [f32; 3], + eyedropping: Option, + swatches: &[[f32; 3]], + ) -> ColorPick { + let id = self.named_id("color_bar", label); + let response = self.ui.interact(bar, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, label)); + let tokens = self.tokens; + let border = if response.hovered() { tokens.accent } else { tokens.field_border }; + self.ui.painter().rect(bar, CornerRadius::same(BAR_RADIUS), shown_color(linear), Stroke::new(1.0, border), StrokeKind::Inside); + + let waiting = eyedropping == Some(id); + if waiting { + crate::screen_pick::SwatchColor::of_bar(self.ui.ctx(), linear); + } + let glyph = Rect::from_center_size(pos2(eyedropper_x, bar.center().y), vec2(EYEDROPPER_TARGET, EYEDROPPER_TARGET)); + let mut pick = ColorPick::none(id); + pick.eyedropper = self.eyedropper_at(glyph, waiting, tokens.text_dim); + self.drawn(bar.bottom()); + + let ctx = self.ui.ctx().clone(); + let state_id = id.with("picker"); + let mut state = picker_state(&ctx, state_id); + state.follow(linear); + if let Some(picked) = ColorPick::delivered(&ctx, id) { + state.set_linear(picked); + pick.picked = Some(picked); + } + if response.clicked() { + if state.open { + state.open = false; + } else { + open_picker(&ctx, &mut state, linear); + } + } + + if state.open { + let inside = self.picker_popup(&response, glyph, label, &mut state, waiting, swatches); + pick.picked = pick.picked.or(inside.picked); + pick.merge = inside.merge; + pick.eyedropper |= inside.eyedropper; + pick.swatch = inside.swatch; + } + ctx.data_mut(|data| data.insert_temp(state_id, state)); + pick + } + + /// The open picker: a window the panel's width until resized (its edges and corners drag its size, kept for every picker), its rows at its edges (the project's `swatches` last), titled `label`, standing beside the panel level with `bar` (its title bar drags it, × or Escape closes it, and so does a press off it, the bar and the bar's `eyedropper` unless an eyedropper pick waits); a space or model the user picks becomes the next picker's + fn picker_popup(&mut self, bar: &Response, eyedropper: Rect, label: &str, state: &mut PickerState, waiting: bool, swatches: &[[f32; 3]]) -> ColorPick { + let id = bar.id; + let ctx = self.ui.ctx().clone(); + let size_id = Id::unique(SIZE_KEY); + let kept = ctx.data_mut(|data| data.get_persisted::<[f32; 2]>(size_id)); + let [width, field_height] = kept.unwrap_or([self.right - self.left + 2.0 * PAD, FIELD_HEIGHT]); + let screen = ctx.content_rect(); + + // A kept size may come from a bigger screen or a damaged settings file (max/min also turn NaN into a bound) + let width = width.max(PICKER_MIN_WIDTH).min(screen.width().max(PICKER_MIN_WIDTH)); + let field_height = field_height.max(FIELD_MIN_HEIGHT).min(screen.height().max(FIELD_MIN_HEIGHT)); + let height_id = id.with("picker_height"); + let height = ctx.data(|data| data.get_temp::(height_id)).unwrap_or(PICKER_HEIGHT_GUESS + field_height - FIELD_HEIGHT); + let panel = Rect::from_x_y_ranges(self.ui.clip_rect().left().min(self.left - PAD)..=self.right + PAD, screen.y_range()); + let corner = state.moved_to.unwrap_or_else(|| beside(panel, bar.rect.top(), vec2(width, height), screen)); + + // The title bar stays on screen, so a drag can always bring the window back + let corner = pos2( + corner.x.clamp(screen.left(), (screen.right() - width).max(screen.left())), + corner.y.clamp(screen.top(), (screen.bottom() - TITLE_HEIGHT).max(screen.top())), + ); + + // A press that picks from one of the picker's own lists must not close it + let list_open = egui::Popup::is_any_open(&ctx); + let tokens = self.tokens; + let shown_in = (state.space, state.model); + + let shown = egui::Area::new(id.with("picker_area")).order(Order::Foreground).fixed_pos(corner).show(&ctx, |ui| { + let background = ui.painter().add(egui::Shape::Noop); + let title_bar = Rect::from_min_size(corner, vec2(width, TITLE_HEIGHT)); + let close = Rect::from_center_size(pos2(title_bar.right() - PAD - CLOSE_INK_HALF_WIDTH, title_bar.center().y), vec2(CLOSE_TARGET, CLOSE_TARGET)); + let drag = ui.interact(Rect::from_min_max(title_bar.min, pos2(close.left(), title_bar.bottom())), id.with("picker_title"), Sense::drag()); + drag.widget_info(|| WidgetInfo::labeled(Role::TitleBar, true, label)); + let drag = drag.on_hover_cursor(CursorIcon::Grab); + let closed = ui.interact(close, id.with("picker_close"), Sense::click()); + closed.widget_info(|| WidgetInfo::labeled(Role::Button, true, tr("Close"))); + let painter = ui.painter(); + painter.text( + pos2(title_bar.left() + PAD, title_bar.center().y), + Align2::LEFT_CENTER, + label, + FontId::proportional(TITLE_TEXT_SIZE), + tokens.text_dim, + ); + let close_color = if closed.hovered() { tokens.text } else { tokens.text_dim }; + painter.text(close.center(), Align2::CENTER_CENTER, ic::X, FontId::proportional(CLOSE_GLYPH_SIZE), close_color); + painter.hline(title_bar.x_range(), title_bar.bottom(), Stroke::new(1.0, tokens.separator)); + + let top = title_bar.bottom(); + let rows = Rect::from_min_max(pos2(corner.x, top + PICKER_TOP), pos2(corner.x + width, top + PICKER_TOP + screen.height())); + let (pick, bottom) = ui + .scope_builder(UiBuilder::new().max_rect(rows), |ui| { + PropertySheet::show(ui, id.with("picker_rows"), |sheet| { + let pick = sheet.color_picker_rows(state, waiting, swatches, field_height, id); + (pick, sheet.drawn_bottom) + }) + }) + .inner; + let face = Rect::from_min_max(corner, pos2(corner.x + width, bottom + PICKER_BOTTOM)); + let shadow = PICKER_SHADOW.as_shape(face, CornerRadius::same(PICKER_RADIUS)); + let frame = + egui::epaint::RectShape::new(face, CornerRadius::same(PICKER_RADIUS), tokens.chrome, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + ui.painter().set(background, egui::Shape::Vec(vec![shadow.into(), frame.into()])); + + // Registered after the rows and the title bar, so the grips win at the edges + let mut resize = None; + for (index, (grip, sides)) in grips(face).into_iter().enumerate() { + let cursor = resize_cursor(sides); + let response = ui.interact(grip, id.with(("picker_resize", index)), Sense::drag()).on_hover_cursor(cursor); + if response.dragged() { + ui.ctx().set_cursor_icon(cursor); + resize = Some((sides, response.drag_delta())); + } + } + (pick, face, drag.dragged().then(|| drag.drag_delta()), closed.clicked(), resize) + }); + let (pick, face, dragged, closed, resize) = shown.inner; + ctx.data_mut(|data| data.insert_temp(height_id, face.height())); + if (state.space, state.model) != shown_in { + ctx.data_mut(|data| data.insert_temp(Id::unique(PREFERENCES_KEY), (state.space, state.model))); + } + if let Some(delta) = dragged { + state.moved_to = Some(corner + delta); + } + if let Some((sides, delta)) = resize { + // Only the field grows taller: the other rows keep their pitch + let rows = face.height() - field_height; + let most = vec2(screen.width().max(PICKER_MIN_WIDTH), (screen.height() - rows).max(FIELD_MIN_HEIGHT)); + let (moved, size) = resized(corner, vec2(width, field_height), sides, delta, most); + + // A resized window stays where it was put instead of following the panel + state.moved_to = Some(moved); + ctx.data_mut(|data| data.insert_persisted(size_id, [size.x, size.y])); + } + + // Alt+drag orbits the camera, which keeps the picker open + let pressed_outside = ctx.input(|input| { + input.pointer.primary_pressed() + && !input.modifiers.alt + && input.pointer.interact_pos().is_some_and(|at| !face.contains(at) && !bar.rect.contains(at) && !eyedropper.contains(at)) + }); + + // The app leaves Escape to an open picker (menus.rs); Escape in the hex field ends the typing first (egui drops the field's focus before it hears the key) + let escape = ctx.input(|input| input.key_pressed(egui::Key::Escape)) + && ctx.memory(|memory| memory.focused().is_none_or(|focused| focused == bar.id)) + && !hex_took_escape(&ctx); + if closed || (!list_open && !waiting && (pressed_outside || escape)) { + state.open = false; + crate::color_picker::forget_window(&ctx); + if pressed_outside { + crate::color_picker::closed_by_press(&ctx); + } + } else { + crate::color_picker::remember_window(&ctx, face); + } + pick + } +} + +/// Top left corner of a window of `size` beside `panel` (left of it, or right of it when the screen ends first), level with `top` and on screen +fn beside(panel: Rect, top: f32, size: Vec2, screen: Rect) -> Pos2 { + let left_of = panel.left() - WINDOW_GAP - size.x; + let x = if left_of >= screen.left() { left_of } else { panel.right() + WINDOW_GAP }; + pos2(x, top.min(screen.bottom() - size.y).max(screen.top())) +} + +/// The eight resize grips inside `face`'s edges and corners, each with the sides it moves (-1 left/top, 1 right/bottom, 0 neither); corners last, so they win where they overlap an edge +fn grips(face: Rect) -> [(Rect, Vec2); 8] { + let edge = |sides: Vec2| { + let x = match sides.x { + x if x < 0.0 => face.left()..=face.left() + RESIZE_GRIP, + x if x > 0.0 => face.right() - RESIZE_GRIP..=face.right(), + _ => face.left()..=face.right(), + }; + let y = match sides.y { + y if y < 0.0 => face.top()..=face.top() + RESIZE_GRIP, + y if y > 0.0 => face.bottom() - RESIZE_GRIP..=face.bottom(), + _ => face.top()..=face.bottom(), + }; + (Rect::from_x_y_ranges(x, y), sides) + }; + let corner = |sides: Vec2| { + let x = if sides.x < 0.0 { face.left() } else { face.right() - RESIZE_CORNER }; + let y = if sides.y < 0.0 { face.top() } else { face.bottom() - RESIZE_CORNER }; + (Rect::from_min_size(pos2(x, y), vec2(RESIZE_CORNER, RESIZE_CORNER)), sides) + }; + [ + edge(vec2(-1.0, 0.0)), + edge(vec2(1.0, 0.0)), + edge(vec2(0.0, -1.0)), + edge(vec2(0.0, 1.0)), + corner(vec2(-1.0, -1.0)), + corner(vec2(1.0, -1.0)), + corner(vec2(-1.0, 1.0)), + corner(vec2(1.0, 1.0)), + ] +} + +/// The pointer over a grip that moves `sides` +fn resize_cursor(sides: Vec2) -> CursorIcon { + match (sides.x == 0.0, sides.y == 0.0) { + (false, true) => CursorIcon::ResizeHorizontal, + (true, false) => CursorIcon::ResizeVertical, + _ if sides.x == sides.y => CursorIcon::ResizeNwSe, + _ => CursorIcon::ResizeNeSw, + } +} + +/// The corner and size (width, field height) after a grip moving `sides` was dragged by `delta`, the size held between the least and `most`; a left or top edge moves the corner so the opposite edge stays put +fn resized(corner: Pos2, size: Vec2, sides: Vec2, delta: Vec2, most: Vec2) -> (Pos2, Vec2) { + let least = vec2(PICKER_MIN_WIDTH, FIELD_MIN_HEIGHT); + let mut corner = corner; + let mut size = size; + for axis in 0..2 { + let grown = (size[axis] + sides[axis] * delta[axis]).clamp(least[axis], most[axis]); + if sides[axis] < 0.0 { + corner[axis] += size[axis] - grown; + } + size[axis] = grown; + } + (corner, size) +} diff --git a/crates/ui-egui/src/property_sheet/color_picker_rows.rs b/crates/ui-egui/src/property_sheet/color_picker_rows.rs new file mode 100644 index 00000000..386037d1 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/color_picker_rows.rs @@ -0,0 +1,522 @@ +//! The colour picker's rows: its colour space, the saturation/value field beside the hue strip, before | after with the hex code and eyedropper, the model's three sliders, the working-space values and the project's swatches + +use egui::ecolor::{hsv_from_rgb, rgb_from_hsv}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use texturecraft_engine::core::MAX_SWATCHES; + +use super::slider::KNOB_RADIUS; +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, GLYPH_SIZE, GLYPH_TARGET, PAD, PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::color_picker::{ColorModel, ColorPick, ColorSpace, PickerState, SwatchEdit, eight_bit, hex, parse_hex}; +use crate::drawn_icon::DrawnIcon; +use crate::fill_material_panel::shown_color as screen_color; +use crate::i18n::tr; +use crate::theme::semibold; +use crate::widgets::gradient; + +/// Height of the saturation/value field and the hue strip until the window is resized, and the least a resize leaves them +pub(super) const FIELD_HEIGHT: f32 = 150.0; +pub(super) const FIELD_MIN_HEIGHT: f32 = 100.0; + +/// Air above and below the field, like a control's margin in its row +const FIELD_MARGIN: f32 = 2.0; + +/// Width of the hue strip at the right edge +const HUE_STRIP_WIDTH: f32 = 14.0; + +/// Air between the field and the hue strip +const FIELD_TO_STRIP: f32 = 8.0; + +/// Radius of the ring marking the colour in the field +const FIELD_KNOB_RADIUS: f32 = 6.0; + +/// How far the hue marker reaches past the strip's sides, and half its height +const HUE_MARKER_OVERHANG: f32 = 2.0; +const HUE_MARKER_HALF_HEIGHT: f32 = 3.0; + +/// Corner radius of the hue marker's outline: under its 3 px half height, so it stays a rounded bar +const HUE_MARKER_RADIUS: u8 = 2; + +/// Width of the before and of the after swatch +const SWATCH_WIDTH: f32 = 30.0; + +/// From the left edge to the hex field +const HEX_LEFT: f32 = 68.0; + +/// From the hex field to the right edge (the eyedropper's room): the hex field ends where the colour field above it does +const HEX_RIGHT_INSET: f32 = HUE_STRIP_WIDTH + FIELD_TO_STRIP; + +/// From the hex field's left edge to its `#`, and to its digits +const HASH_INSET: f32 = 8.0; +const DIGITS_INSET: f32 = 20.0; + +/// Passes after the hex field last had focus that a typed code still applies (egui reports a lost focus up to two passes late) +const FOCUS_LOOKBACK_PASSES: u64 = 2; + +/// Where the hex field notes the pass in which Escape ended its typing (that Escape does not close the picker) +const HEX_ESCAPE_KEY: &str = "color_picker_hex_escape"; + +/// From the right edge to the centre of the eyedropper and of the ⋯ menu +const EYEDROPPER_INSET: f32 = 7.0; +const MENU_INSET: f32 = 6.0; + +/// Size of the eyedropper's pipette +const PIPETTE_SIZE: f32 = 15.0; + +/// A dropdown is as wide as its value plus this (its padding and caret) +const DROPDOWN_ROOM: f32 = 34.0; + +/// Pitch of the three sliders (the stack rhythm's part rows) +const SLIDER_ROW: f32 = 22.0; + +/// From the left edge to a slider's track, and from its track to the right edge (the value's room) +const TRACK_LEFT: f32 = 18.0; +const TRACK_RIGHT_INSET: f32 = 44.0; + +/// Height of a slider's colour track +const TRACK_HEIGHT: f32 = 6.0; + +/// Width of a slider's typed value, and the decimals it shows +const VALUE_WIDTH: f32 = 40.0; +const SLIDER_DECIMALS: usize = 2; + +/// Height of the working-space line (the stack rhythm's label line) +const WORKING_LINE: f32 = 18.0; + +/// Air above and below the line between the working-space values and the swatches +const SWATCHES_RULE_AIR: f32 = 6.0; + +/// Height of the Swatches caption line, and the air between it and the chips +const SWATCHES_CAPTION: f32 = 18.0; +const SWATCHES_CAPTION_AIR: f32 = 2.0; + +/// Side of a swatch chip (a control's height), and the air between chips and between their rows +const SWATCH_CHIP: f32 = 24.0; +const SWATCH_CHIP_GAP: f32 = 6.0; + +/// Size of the ⋯ menu glyph: a point larger than a row's glyphs, as its dots are small +const MENU_GLYPH_SIZE: f32 = GLYPH_SIZE + 1.0; + +/// Corner radius of a swatch chip, and the size of the + chip's glyph +const SWATCH_CHIP_RADIUS: u8 = 4; +const PLUS_GLYPH_SIZE: f32 = 12.0; + +/// Ring strokes: the field's ring, the knobs' and the hue marker's outline +const RING_STROKE: f32 = 2.0; +const OUTLINE_STROKE: f32 = 1.5; + +impl PropertySheet<'_> { + /// The picker's rows, editing `state`, its field `field_height` tall and the project's `swatches` last; `eyedropping` lights the eyedropper while a pick waits for its click + pub(super) fn color_picker_rows( + &mut self, + state: &mut PickerState, + eyedropping: bool, + swatches: &[[f32; 3]], + field_height: f32, + id: egui::Id, + ) -> ColorPick { + let mut pick = ColorPick::none(id); + let mut edited: Option = None; + + self.space_row(state); + edited = edited.or(self.field_rows(state, field_height)); + let (restored, eyedropper) = self.before_after_row(state, eyedropping); + edited = edited.or(restored); + pick.eyedropper = eyedropper; + self.model_row(state); + edited = edited.or(self.model_sliders(state)); + self.working_line(state); + let (applied, swatch) = self.swatch_rows(state, swatches); + if let Some(color) = applied.filter(|color| *color != state.linear) { + state.set_linear(color); + edited = Some(false); + } + pick.swatch = swatch; + + if let Some(merge) = edited { + pick.picked = Some(state.linear); + pick.merge = merge; + } + pick + } + + /// The colour space: a dropdown as wide as its longest option, so the button keeps its width whichever is picked; a click in its list picks, a hover changes nothing + fn space_row(&mut self, state: &mut PickerState) { + let center_y = self.take(ROW_HEIGHT).center().y; + let longest = ColorSpace::ALL.iter().map(|space| self.text_width(space.name(), semibold(TEXT_SIZE))).fold(0.0, f32::max); + let button = Rect::from_min_size(pos2(self.left, center_y - CONTROL_HEIGHT / 2.0), vec2(longest + DROPDOWN_ROOM, CONTROL_HEIGHT)); + let response = self.dropdown_button(button, state.space.name(), None::); + self.drawn(button.bottom()); + let (picked, _) = self.hanging_list(&response, state.space, &ColorSpace::ALL, &|space: ColorSpace| space.name().to_owned(), None); + if let Some(space) = picked { + state.set_space(space); + } + } + + /// Saturation across and value up in the field, hue down the strip, both `height` tall; Some(merge) when dragged or clicked + fn field_rows(&mut self, state: &mut PickerState, height: f32) -> Option { + let block = self.take(height + 2.0 * FIELD_MARGIN); + let top = block.top() + FIELD_MARGIN; + let field = Rect::from_min_max(pos2(self.left, top), pos2(self.right - HUE_STRIP_WIDTH - FIELD_TO_STRIP, top + height)); + let strip = Rect::from_min_max(pos2(self.right - HUE_STRIP_WIDTH, top), pos2(self.right, top + height)); + let mut edited = None; + + let field_id = self.next_id(); + let response = self.ui.interact(field, field_id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::labeled(Role::Slider, true, tr("Saturation and value"))); + if let Some(at) = pressed_at(&response) { + let [hue, ..] = state.hsv; + let saturation = ((at.x - field.left()) / field.width()).clamp(0.0, 1.0); + let value = 1.0 - ((at.y - field.top()) / field.height()).clamp(0.0, 1.0); + state.set_hsv([hue, saturation, value]); + edited = Some(continues(&response)); + } + + let strip_id = self.next_id(); + let response = self.ui.interact(strip, strip_id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::labeled(Role::Slider, true, tr("Hue"))); + if let Some(at) = pressed_at(&response) { + let [_, saturation, value] = state.hsv; + state.set_hsv([((at.y - strip.top()) / strip.height()).clamp(0.0, 1.0), saturation, value]); + edited = Some(continues(&response)); + } + + let [hue, saturation, value] = state.hsv; + let space = state.space; + let painter = self.ui.painter(); + gradient(painter, field, |x, y| space.display(rgb_from_hsv((hue, x, 1.0 - y)))); + painter.circle_stroke(field.lerp_inside(vec2(saturation, 1.0 - value)), FIELD_KNOB_RADIUS, Stroke::new(RING_STROKE, Color32::WHITE)); + gradient(painter, strip, |_, y| rgb_from_hsv((y, 1.0, 1.0))); + let marker_y = strip.top() + hue * strip.height(); + let marker = Rect::from_min_max( + pos2(strip.left() - HUE_MARKER_OVERHANG, marker_y - HUE_MARKER_HALF_HEIGHT), + pos2(strip.right() + HUE_MARKER_OVERHANG, marker_y + HUE_MARKER_HALF_HEIGHT), + ); + painter.rect_stroke(marker, CornerRadius::same(HUE_MARKER_RADIUS), Stroke::new(OUTLINE_STROKE, Color32::WHITE), StrokeKind::Middle); + self.drawn(field.bottom()); + edited + } + + /// Before | after (a click on before restores it), the hex field and the eyedropper; Some(false) when restored or typed, and whether the eyedropper was clicked + fn before_after_row(&mut self, state: &mut PickerState, eyedropping: bool) -> (Option, bool) { + let center_y = self.take(ROW_HEIGHT).center().y; + let tokens = self.tokens; + let mut edited = None; + + let before = Rect::from_min_size(pos2(self.left, center_y - CONTROL_HEIGHT / 2.0), vec2(SWATCH_WIDTH, CONTROL_HEIGHT)); + let after = before.translate(vec2(SWATCH_WIDTH, 0.0)); + let before_id = self.next_id(); + let previous = tr("Previous color"); + let response = self.tip(self.ui.interact(before, before_id, Sense::click()), previous); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, previous)); + if response.clicked() && state.linear != state.before { + state.set_linear(state.before); + edited = Some(false); + } + let painter = self.ui.painter(); + painter.rect_filled(before, CornerRadius::ZERO, screen_color(state.before)); + painter.rect_filled(after, CornerRadius::ZERO, screen_color(state.linear)); + + let field = Rect::from_min_max( + pos2(self.left + HEX_LEFT, center_y - CONTROL_HEIGHT / 2.0), + pos2(self.right - HEX_RIGHT_INSET, center_y + CONTROL_HEIGHT / 2.0), + ); + if let Some(typed) = self.hex_field(field, state.shown()) { + state.set_linear(state.space.linear(typed)); + edited = Some(false); + } + + let glyph = Rect::from_center_size(pos2(self.right - EYEDROPPER_INSET, center_y), vec2(GLYPH_TARGET, GLYPH_TARGET)); + let eyedropper = self.eyedropper_at(glyph, eyedropping, tokens.text_dim); + self.drawn(before.bottom()); + (edited, eyedropper) + } + + /// The bare eyedropper glyph in `glyph` (accent while a pick waits); true when clicked + pub(super) fn eyedropper_at(&mut self, glyph: Rect, eyedropping: bool, idle: Color32) -> bool { + let id = self.next_id(); + let label = tr("Pick color"); + let response = self.tip(self.ui.interact(glyph, id, Sense::click()), label); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, eyedropping, label)); + let tokens = self.tokens; + let color = if eyedropping { + tokens.accent + } else if response.hovered() { + tokens.text + } else { + idle + }; + DrawnIcon::Pipette.paint(self.ui.painter(), glyph.center(), PIPETTE_SIZE, color); + response.clicked() + } + + /// The hex code of `shown` in a field; the values typed, once Enter or a click elsewhere ends an edit that changed the code + fn hex_field(&mut self, field: Rect, shown: [f32; 3]) -> Option<[f32; 3]> { + let id = self.next_id(); + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + painter.text(pos2(field.left() + HASH_INSET, field.center().y), Align2::LEFT_CENTER, "#", FontId::proportional(TEXT_SIZE), tokens.text_dim); + let digits = Rect::from_min_max(pos2(field.left() + DIGITS_INSET, field.top()), field.right_bottom()); + let text_id = id.with("typed"); + let opened_id = text_id.with("opened"); + let editing = self.ui.data(|data| data.get_temp::(text_id)); + + // Text left by a picker that closed mid-edit (its field no longer drawn, so never told it lost focus) is not shown again + let focused_pass_id = text_id.with("focused pass"); + let pass = self.ui.ctx().cumulative_pass_nr(); + if self.ui.memory(|memory| memory.has_focus(text_id)) { + self.ui.data_mut(|data| data.insert_temp(focused_pass_id, pass)); + } + let focused_pass = self.ui.data(|data| data.get_temp::(focused_pass_id)); + let focused = focused_pass.is_some_and(|focused_pass| pass.saturating_sub(focused_pass) <= FOCUS_LOOKBACK_PASSES); + if editing.is_some() && !focused { + self.ui.data_mut(|data| { + data.remove::(text_id); + data.remove::(opened_id); + }); + } + let editing = editing.filter(|_| focused); + + let Some(mut text) = editing else { + let response = self.ui.interact(digits, id, Sense::click()).on_hover_cursor(egui::CursorIcon::Text); + response.widget_info(|| WidgetInfo::labeled(Role::TextInput, true, tr("Hex color"))); + self.ui.painter().text(pos2(digits.left(), digits.center().y), Align2::LEFT_CENTER, hex(shown), semibold(TEXT_SIZE), tokens.text); + if response.clicked() { + self.ui.data_mut(|data| { + data.insert_temp(opened_id, hex(shown)); + data.insert_temp(text_id, hex(shown)); + }); + self.ui.memory_mut(|memory| memory.request_focus(text_id)); + } + return None; + }; + + let edit = egui::TextEdit::singleline(&mut text) + .id(text_id) + .font(semibold(TEXT_SIZE)) + .frame(egui::Frame::NONE) + .align(Align2::LEFT_CENTER) + .margin(vec2(0.0, 0.0)); + let response = self.ui.put(digits, edit); + if !response.lost_focus() { + self.ui.data_mut(|data| data.insert_temp(text_id, text)); + return None; + } + + let opened = self.ui.data_mut(|data| { + data.remove::(text_id); + data.remove_temp::(opened_id) + }); + if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + // Escape ends the typing only: the picker stays open + let pass = self.ui.ctx().cumulative_pass_nr(); + self.ui.data_mut(|data| data.insert_temp(egui::Id::unique(HEX_ESCAPE_KEY), pass)); + return None; + } + + // Left as it opened, the code is no edit: reading it back would round the colour to what the code shows, or write it over a colour changed meanwhile + let typed = parse_hex(&text)?; + let code = hex(typed); + (Some(&code) != opened.as_ref() && code != hex(shown)).then_some(typed) + } + + /// The model dropdown, sized to its value, and the ⋯ menu at the right edge; a click in its list picks, a hover changes nothing + fn model_row(&mut self, state: &mut PickerState) { + let center_y = self.take(ROW_HEIGHT).center().y; + let width = self.text_width(state.model.name(), semibold(TEXT_SIZE)) + DROPDOWN_ROOM; + let button = Rect::from_min_size(pos2(self.left, center_y - CONTROL_HEIGHT / 2.0), vec2(width, CONTROL_HEIGHT)); + let response = self.dropdown_button(button, state.model.name(), None::); + self.drawn(button.bottom()); + let (picked, _) = self.hanging_list(&response, state.model, &ColorModel::ALL, &|model: ColorModel| model.name().to_owned(), None); + if let Some(model) = picked { + state.model = model; + } + + let glyph = Rect::from_center_size(pos2(self.right - MENU_INSET, center_y), vec2(GLYPH_TARGET, GLYPH_TARGET)); + let menu_id = self.next_id(); + let more = tr("More"); + let response = self.ui.interact(glyph, menu_id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, more)); + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + self.ui.painter().text(glyph.center(), Align2::CENTER_CENTER, ic::DOTS_THREE, FontId::proportional(MENU_GLYPH_SIZE), color); + let shown = state.shown(); + egui::Popup::menu(&response).show(|ui| { + if ui.button(tr("Copy RGB values")).clicked() { + let [red, green, blue] = eight_bit(shown); + ui.copy_text(format!("{red}, {green}, {blue}")); + } + if ui.button(tr("Copy hex color")).clicked() { + ui.copy_text(format!("#{}", hex(shown))); + } + }); + } + + /// The model's three sliders: each track shows the colours it reaches; Some(merge) when one was dragged or typed + fn model_sliders(&mut self, state: &mut PickerState) -> Option { + let mut edited = None; + let parts = match state.model { + ColorModel::Hsv => state.hsv, + ColorModel::Rgb => state.shown(), + }; + for (index, letter) in state.model.letters().into_iter().enumerate() { + let row = self.take(SLIDER_ROW); + let center_y = row.center().y; + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, letter, semibold(TEXT_SIZE), tokens.text_dim); + let track = Rect::from_min_max( + pos2(self.left + TRACK_LEFT, center_y - TRACK_HEIGHT / 2.0), + pos2(self.right - TRACK_RIGHT_INSET, center_y + TRACK_HEIGHT / 2.0), + ); + let space = state.space; + let model = state.model; + gradient(self.ui.painter(), track, |x, _| space.display(model_color(model, parts, index, x))); + + let id = self.next_id(); + let reach = Rect::from_x_y_ranges(track.left() - KNOB_RADIUS..=track.right() + KNOB_RADIUS, row.y_range()); + let response = self.ui.interact(reach, id, Sense::click_and_drag()); + response.widget_info(|| WidgetInfo::slider(true, f64::from(parts.get(index).copied().unwrap_or_default()), letter)); + let mut part = parts.get(index).copied().unwrap_or_default(); + let mut changed = None; + if let Some(at) = pressed_at(&response) { + part = ((at.x - track.left()) / track.width()).clamp(0.0, 1.0); + changed = Some(continues(&response)); + } + if let Some(typed) = self.value_field_at(id, letter, self.right, VALUE_WIDTH, center_y, part, &(0.0..=1.0), SLIDER_DECIMALS, "") { + part = typed; + changed = Some(false); + } + let knob = pos2(track.left() + track.width() * part, center_y); + self.ui.painter().circle(knob, KNOB_RADIUS, tokens.panel, Stroke::new(OUTLINE_STROKE, Color32::WHITE)); + if let Some(merge) = changed { + set_part(state, index, part); + edited = edited.or(Some(merge)); + } + self.drawn(center_y + KNOB_RADIUS); + } + edited + } + + /// The working (linear) values of the colour, small and dim + fn working_line(&mut self, state: &PickerState) { + let center_y = self.take(WORKING_LINE).center().y; + let tokens = self.tokens; + let font = FontId::proportional(SMALL_TEXT_SIZE); + let painter = self.ui.painter(); + let label = painter.text(pos2(self.left, center_y), Align2::LEFT_CENTER, tr("Working color space"), font.clone(), tokens.text_dim); + let [red, green, blue] = state.linear; + painter.text(pos2(self.right, center_y), Align2::RIGHT_CENTER, format!("{red:.2} {green:.2} {blue:.2}"), font, tokens.text_dim); + self.drawn(label.bottom()); + } + + /// A line across the window, the Swatches caption, then the project's `swatches` as chips (wrapping) and the + chip that keeps the picker's colour; the swatch clicked, and an add or a removal (a swatch's right-click menu) + fn swatch_rows(&mut self, state: &PickerState, swatches: &[[f32; 3]]) -> (Option<[f32; 3]>, Option) { + let tokens = self.tokens; + self.space(SWATCHES_RULE_AIR); + let rule_y = self.cursor_y(); + self.ui.painter().hline((self.left - PAD)..=(self.right + PAD), rule_y, Stroke::new(1.0, tokens.separator)); + self.space(SWATCHES_RULE_AIR); + let caption = self.take(SWATCHES_CAPTION); + self.ui.painter().text(pos2(self.left, caption.center().y), Align2::LEFT_CENTER, tr("Swatches"), semibold(SMALL_TEXT_SIZE), tokens.text); + self.space(SWATCHES_CAPTION_AIR); + + let count = swatches.len().min(MAX_SWATCHES); + let pitch = SWATCH_CHIP + SWATCH_CHIP_GAP; + let per_row = (((self.right - self.left + SWATCH_CHIP_GAP) / pitch).floor() as usize).max(1); + let chips = count + 1; + let rows = chips.div_ceil(per_row); + let block = self.take(rows as f32 * pitch - SWATCH_CHIP_GAP); + let left = self.left; + let chip_at = |index: usize| { + let (row, column) = (index / per_row, index % per_row); + Rect::from_min_size(pos2(left + column as f32 * pitch, block.top() + row as f32 * pitch), vec2(SWATCH_CHIP, SWATCH_CHIP)) + }; + + let (mut applied, mut edit) = (None, None); + for (index, &color) in swatches.iter().take(MAX_SWATCHES).enumerate() { + let chip = chip_at(index); + // Keyed by its colour too: a chip whose swatch moved (the list changed under an open menu) closes that menu + let chip_id = self.next_id().with(color.map(f32::to_bits)); + let response = self.ui.interact(chip, chip_id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, format!("#{}", hex(state.space.shown(color))))); + let border = if response.hovered() { tokens.accent } else { Color32::TRANSPARENT }; + self.ui.painter().rect(chip, CornerRadius::same(SWATCH_CHIP_RADIUS), screen_color(color), Stroke::new(1.0, border), StrokeKind::Inside); + if response.clicked() { + applied = Some(color); + } + response.context_menu(|ui| { + if ui.button(tr("Remove swatch")).clicked() { + edit = Some(SwatchEdit::Remove(index)); + ui.close(); + } + }); + } + + let add = chip_at(count); + let room = count < MAX_SWATCHES; + let label = tr("Add swatch"); + let add_id = self.next_id(); + let response = self.tip(self.ui.interact(add, add_id, if room { Sense::click() } else { Sense::hover() }), label); + response.widget_info(|| WidgetInfo::labeled(Role::Button, room, label)); + let (border, glyph) = if response.hovered() && room { (tokens.accent, tokens.text) } else { (tokens.field_border, tokens.text_dim) }; + let painter = self.ui.painter(); + painter.rect_stroke(add, CornerRadius::same(SWATCH_CHIP_RADIUS), Stroke::new(1.0, border), StrokeKind::Inside); + painter.text(add.center(), Align2::CENTER_CENTER, ic::PLUS, FontId::proportional(PLUS_GLYPH_SIZE), glyph); + if room && response.clicked() { + edit = Some(SwatchEdit::Add(state.linear)); + } + self.drawn(block.bottom()); + (applied, edit) + } +} + +/// Whether Escape this pass ended typing in the open picker's hex field +pub(super) fn hex_took_escape(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp::(egui::Id::unique(HEX_ESCAPE_KEY))) == Some(ctx.cumulative_pass_nr()) +} + +/// Where the pointer presses or drags `response` this frame +fn pressed_at(response: &Response) -> Option { + response.interact_pointer_pos().filter(|_| response.dragged() || response.clicked()) +} + +/// A drag past its first frame continues the edit it started +fn continues(response: &Response) -> bool { + response.dragged() && !response.drag_started() +} + +/// The colour `parts` (in `model`) has with part `index` set to `x`, in the shown space; the hue track shows every hue at full strength +fn model_color(model: ColorModel, parts: [f32; 3], index: usize, x: f32) -> [f32; 3] { + let mut parts = if model == ColorModel::Hsv && index == 0 { [0.0, 1.0, 1.0] } else { parts }; + if let Some(part) = parts.get_mut(index) { + *part = x; + } + match model { + ColorModel::Hsv => rgb_from_hsv((parts[0], parts[1], parts[2])), + ColorModel::Rgb => parts, + } +} + +/// Sets part `index` of the colour in the picker's model +fn set_part(state: &mut PickerState, index: usize, part: f32) { + match state.model { + ColorModel::Hsv => { + let mut hsv = state.hsv; + if let Some(slot) = hsv.get_mut(index) { + *slot = part; + } + state.set_hsv(hsv); + } + ColorModel::Rgb => { + let mut shown = state.shown(); + if let Some(slot) = shown.get_mut(index) { + *slot = part; + } + let (hue, saturation, value) = hsv_from_rgb(shown); + state.linear = state.space.linear(shown); + state.hsv = [hue, saturation, value]; + } + } +} From b4692ab28f8cdd932fb8d2f24b2b67aacbe9a842 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:28 +0000 Subject: [PATCH 022/153] Colour: the eyedropper picks from anywhere on the screen --- Cargo.lock | 653 +++++++++++++++++- crates/ui-egui/Cargo.toml | 14 + crates/ui-egui/src/drawn_icon/distance.rs | 83 +++ crates/ui-egui/src/drawn_icon/invert.rs | 50 ++ crates/ui-egui/src/drawn_icon/mod.rs | 102 +++ crates/ui-egui/src/drawn_icon/pipette.rs | 94 +++ crates/ui-egui/src/id_color_pick.rs | 16 +- .../ui-egui/src/screen_pick/cursor_image.rs | 268 +++++++ .../ui-egui/src/screen_pick/cursor_texture.rs | 33 + .../src/screen_pick/eyedropper_pointer.rs | 188 +++++ crates/ui-egui/src/screen_pick/hook_state.rs | 28 + crates/ui-egui/src/screen_pick/keeper_args.rs | 134 ++++ crates/ui-egui/src/screen_pick/live_swatch.rs | 67 ++ crates/ui-egui/src/screen_pick/mod.rs | 221 ++++++ .../ui-egui/src/screen_pick/painted_cursor.rs | 60 ++ .../ui-egui/src/screen_pick/pick_outcome.rs | 10 + crates/ui-egui/src/screen_pick/pick_shared.rs | 53 ++ .../ui-egui/src/screen_pick/pixel_layout.rs | 70 ++ crates/ui-egui/src/screen_pick/portal.rs | 94 +++ .../src/screen_pick/premultiplied_argb.rs | 28 + .../ui-egui/src/screen_pick/release_wait.rs | 55 ++ crates/ui-egui/src/screen_pick/shown_disc.rs | 9 + .../ui-egui/src/screen_pick/swatch_color.rs | 49 ++ .../ui-egui/src/screen_pick/swatch_picture.rs | 149 ++++ crates/ui-egui/src/screen_pick/swatch_side.rs | 66 ++ .../ui-egui/src/screen_pick/windows_hook.rs | 189 +++++ crates/ui-egui/src/screen_pick/x11_grab.rs | 194 ++++++ 27 files changed, 2954 insertions(+), 23 deletions(-) create mode 100644 crates/ui-egui/src/drawn_icon/distance.rs create mode 100644 crates/ui-egui/src/drawn_icon/invert.rs create mode 100644 crates/ui-egui/src/drawn_icon/mod.rs create mode 100644 crates/ui-egui/src/drawn_icon/pipette.rs create mode 100644 crates/ui-egui/src/screen_pick/cursor_image.rs create mode 100644 crates/ui-egui/src/screen_pick/cursor_texture.rs create mode 100644 crates/ui-egui/src/screen_pick/eyedropper_pointer.rs create mode 100644 crates/ui-egui/src/screen_pick/hook_state.rs create mode 100644 crates/ui-egui/src/screen_pick/keeper_args.rs create mode 100644 crates/ui-egui/src/screen_pick/live_swatch.rs create mode 100644 crates/ui-egui/src/screen_pick/mod.rs create mode 100644 crates/ui-egui/src/screen_pick/painted_cursor.rs create mode 100644 crates/ui-egui/src/screen_pick/pick_outcome.rs create mode 100644 crates/ui-egui/src/screen_pick/pick_shared.rs create mode 100644 crates/ui-egui/src/screen_pick/pixel_layout.rs create mode 100644 crates/ui-egui/src/screen_pick/portal.rs create mode 100644 crates/ui-egui/src/screen_pick/premultiplied_argb.rs create mode 100644 crates/ui-egui/src/screen_pick/release_wait.rs create mode 100644 crates/ui-egui/src/screen_pick/shown_disc.rs create mode 100644 crates/ui-egui/src/screen_pick/swatch_color.rs create mode 100644 crates/ui-egui/src/screen_pick/swatch_picture.rs create mode 100644 crates/ui-egui/src/screen_pick/swatch_side.rs create mode 100644 crates/ui-egui/src/screen_pick/windows_hook.rs create mode 100644 crates/ui-egui/src/screen_pick/x11_grab.rs diff --git a/Cargo.lock b/Cargo.lock index f9292a97..34c2e112 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,7 +80,7 @@ dependencies = [ "futures-lite", "futures-util", "serde", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -132,6 +132,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "alloc-no-stdlib" version = "3.0.0" @@ -193,6 +202,22 @@ dependencies = [ "libc", ] +[[package]] +name = "annotate-snippets" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" +dependencies = [ + "anstyle", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "arboard" version = "3.6.1" @@ -235,6 +260,22 @@ dependencies = [ "libloading", ] +[[package]] +name = "ashpd" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ba377f1fb1e3972907220f1f8e7c0a45164580905c981d872c1fb90d921cbcc" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-util", + "getrandom 0.4.3", + "pipewire", + "serde", + "serde_repr", + "zbus 6.3.0", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -391,7 +432,7 @@ dependencies = [ "enumflags2", "serde", "static_assertions", - "zbus", + "zbus 5.19.0", "zbus-lockstep", "zbus-lockstep-macros", "zbus_names", @@ -406,7 +447,7 @@ checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" dependencies = [ "atspi-common", "serde", - "zbus", + "zbus 5.19.0", ] [[package]] @@ -433,6 +474,25 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "annotate-snippets", + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -628,7 +688,26 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-expr" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd44d82755fb9210fb10d9daf8dd7e522da0efe1d5f263cffc5db07725663ff" +dependencies = [ + "smallvec", + "target-lexicon", ] [[package]] @@ -652,6 +731,17 @@ dependencies = [ "libc", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + [[package]] name = "chrono" version = "0.4.45" @@ -666,6 +756,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "clipboard-win" version = "5.4.1" @@ -738,6 +839,12 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + [[package]] name = "core-foundation" version = "0.9.4" @@ -803,6 +910,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "craft-cms" version = "0.1.0" @@ -1307,6 +1423,61 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytemuck_derive", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 1.1.5", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.5", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + [[package]] name = "dunce" version = "1.0.5" @@ -1376,7 +1547,7 @@ dependencies = [ "bitflags 2.13.2", "emath", "epaint", - "itertools", + "itertools 0.15.0", "log", "nohash-hasher", "profiling", @@ -1753,6 +1924,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "fs-set-times" version = "0.20.3" @@ -1865,6 +2045,30 @@ dependencies = [ "slab", ] +[[package]] +name = "gbm" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" +dependencies = [ + "bitflags 2.13.2", + "drm 0.14.1", + "drm-fourcc", + "gbm-sys", + "libc", + "wayland-backend", + "wayland-server", +] + +[[package]] +name = "gbm-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" +dependencies = [ + "libc", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -1918,6 +2122,7 @@ dependencies = [ "js-sys", "libc", "r-efi 6.0.0", + "rand_core", "wasm-bindgen", ] @@ -1931,6 +2136,15 @@ dependencies = [ "weezl", ] +[[package]] +name = "gl" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404" +dependencies = [ + "gl_generator", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -1974,6 +2188,12 @@ dependencies = [ "vello_common", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -2176,6 +2396,12 @@ dependencies = [ "fearless_simd", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.3" @@ -2411,6 +2637,27 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "image" version = "0.25.10" @@ -2488,6 +2735,15 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.15.0" @@ -2683,6 +2939,54 @@ dependencies = [ "redox_syscall 0.9.4", ] +[[package]] +name = "libspa" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40" +dependencies = [ + "bitflags 2.13.2", + "cc", + "cookie-factory", + "libc", + "libspa-sys", + "nom 8.0.0", + "rustix 1.1.5", + "system-deps", +] + +[[package]] +name = "libspa-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924" +dependencies = [ + "bindgen", + "cc", + "system-deps", +] + +[[package]] +name = "libwayshot-xcap" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5" +dependencies = [ + "drm 0.15.0", + "gbm", + "gl", + "image", + "khronos-egl", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "tracing", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -2695,6 +2999,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2786,6 +3096,12 @@ dependencies = [ "glam 0.15.2", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2943,6 +3259,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -3064,6 +3390,18 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "objc2 0.6.5", + "objc2-core-graphics", + "objc2-core-media", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-cloud-kit" version = "0.2.2" @@ -3088,6 +3426,28 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + [[package]] name = "objc2-core-data" version = "0.2.2" @@ -3119,6 +3479,7 @@ checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags 2.13.2", "dispatch2", + "libc", "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", @@ -3148,6 +3509,34 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -3532,6 +3921,31 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pipewire" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c" +dependencies = [ + "bitflags 2.13.2", + "libc", + "libspa", + "libspa-sys", + "pipewire-sys", + "rustix 1.1.5", +] + +[[package]] +name = "pipewire-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0" +dependencies = [ + "bindgen", + "libspa-sys", + "system-deps", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3777,6 +4191,23 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "range-alloc" version = "0.1.5" @@ -3907,6 +4338,35 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -4323,10 +4783,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -4563,6 +5029,19 @@ dependencies = [ "windows", ] +[[package]] +name = "system-deps" +version = "7.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml", + "version-compare", +] + [[package]] name = "tar" version = "0.4.46" @@ -4573,6 +5052,12 @@ dependencies = [ "libc", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + [[package]] name = "tempfile" version = "3.27.0" @@ -4817,6 +5302,7 @@ dependencies = [ "js-sys", "log", "pollster 0.4.0", + "raw-window-handle", "rayon", "rfd", "serde", @@ -4829,6 +5315,10 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", + "winsafe", + "x11rb", + "xcap", + "zbus 5.19.0", "zip", ] @@ -5083,7 +5573,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -5196,6 +5686,18 @@ dependencies = [ "log", ] +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "urlencoding" version = "2.1.3" @@ -5281,6 +5783,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -5465,6 +5973,19 @@ dependencies = [ "quote", ] +[[package]] +name = "wayland-server" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" +dependencies = [ + "bitflags 2.13.2", + "downcast-rs", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + [[package]] name = "wayland-sys" version = "0.31.11" @@ -5472,7 +5993,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" dependencies = [ "dlib", + "libc", "log", + "memoffset", "once_cell", "pkg-config", ] @@ -5695,6 +6218,12 @@ dependencies = [ "web-sys", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi" version = "0.3.9" @@ -6189,6 +6718,49 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xcap" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e833d39f662982a09608f2550fd4036725f98d78738e40fa7206a26258b06384" +dependencies = [ + "ashpd", + "dispatch2", + "image", + "libwayshot-xcap", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "percent-encoding", + "pipewire", + "pollster 1.0.1", + "rand", + "scopeguard", + "serde", + "thiserror 2.0.21", + "url", + "widestring", + "windows", + "xcb", +] + +[[package]] +name = "xcb" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566" +dependencies = [ + "bitflags 2.13.2", + "libc", + "quick-xml 0.41.0", +] + [[package]] name = "xcursor" version = "0.3.11" @@ -6280,11 +6852,38 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow", - "zbus_macros", + "zbus_macros 5.19.0", "zbus_names", "zvariant", ] +[[package]] +name = "zbus" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros 6.3.0", + "zbus_utils", + "zcheapstr", + "zruntime", +] + [[package]] name = "zbus-lockstep" version = "0.5.2" @@ -6324,6 +6923,18 @@ dependencies = [ "zvariant_utils", ] +[[package]] +name = "zbus_macros" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_utils", +] + [[package]] name = "zbus_names" version = "4.3.4" @@ -6335,6 +6946,19 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus_utils" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] + [[package]] name = "zbus_xml" version = "5.2.1" @@ -6498,6 +7122,19 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zruntime" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72" +dependencies = [ + "futures-core", + "futures-io", + "rustix 1.1.5", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "zune-core" version = "0.5.3" diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 1c057d3b..5b3ed2d3 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -38,6 +38,20 @@ craft-ui = { workspace = true, features = ["native-windows"] } craft-update = { workspace = true } # Native file dialogs (file_dialogs.rs); the browser build has none. craft-dialogs = { workspace = true } +# Whether the app runs in a real window, where an eyedropper pick may take clicks outside it (screen_pick). +raw-window-handle = "0.6" + +# An eyedropper click outside the window (screen_pick): a low-level mouse hook and the eyedropper as the system pointer +# (winsafe, MIT) and one desktop pixel through GDI (xcap, Apache-2.0). +[target.'cfg(windows)'.dependencies] +winsafe = { version = "0.0.29", default-features = false, features = ["gdi", "user"] } +xcap = { version = "0.9", default-features = false } + +# The same on X11 (a pointer grab with the eyedropper pointer and one root-window pixel; x11rb, MIT OR Apache-2.0) and on Wayland (the desktop's colour +# picker portal; zbus, MIT). +[target.'cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))'.dependencies] +x11rb = { version = "0.13", features = ["render"] } +zbus = { version = "5.19", default-features = false, features = ["async-io", "blocking-api"] } # build.rs: the interface faces lose their Private Use Area, where the icon font draws (the # versions craft-libs' craft-fonts-build subsets with). diff --git a/crates/ui-egui/src/drawn_icon/distance.rs b/crates/ui-egui/src/drawn_icon/distance.rs new file mode 100644 index 00000000..7b85c112 --- /dev/null +++ b/crates/ui-egui/src/drawn_icon/distance.rs @@ -0,0 +1,83 @@ +//! Signed distances to the simple shapes the drawn icons are built from, in the icon's unit square (y down), negative inside + +/// A point or a direction in the icon's unit square +pub(crate) type Point = [f32; 2]; + +/// The distance from `point` to a convex polygon with `corners` in either order; squared off past its corners, so outlines stay sharp +pub(crate) fn convex_polygon(point: Point, corners: &[Point]) -> f32 { + let Some(&first) = corners.first() else { return f32::INFINITY }; + + let count = corners.len() as f32; + let centre = corners.iter().fold([0.0, 0.0], |sum, corner| [sum[0] + corner[0] / count, sum[1] + corner[1] / count]); + let next = corners.iter().skip(1).chain(std::iter::once(&first)); + + // A repeated corner (a list that closes on its first corner) has no edge, and its zero normal would read as on the outline + let edges: Vec<(Point, Point, f32)> = corners + .iter() + .zip(next) + .map(|(from, to)| (*from, [to[0] - from[0], to[1] - from[1]])) + .map(|(from, edge)| (from, edge, edge[0].hypot(edge[1]))) + .filter(|(_, _, length)| *length > f32::EPSILON) + .collect(); + if edges.len() < POLYGON_MIN_EDGES { + return f32::INFINITY; + } + + edges + .into_iter() + .map(|(from, edge, length)| { + let normal = [edge[1] / length, -edge[0] / length]; + let side = dot(sub(point, from), normal); + if dot(sub(centre, from), normal) > 0.0 { -side } else { side } + }) + .fold(f32::NEG_INFINITY, f32::max) +} + +/// Fewer edges than a triangle's enclose nothing +const POLYGON_MIN_EDGES: usize = 3; + +/// The distance from `point` to the axis-aligned rectangle from `min` to `max` +pub(crate) fn rectangle(point: Point, min: Point, max: Point) -> f32 { + convex_polygon(point, &[min, [max[0], min[1]], max, [min[0], max[1]]]) +} + +/// The distance from `point` to the disc around `centre` +pub(crate) fn disc(point: Point, centre: Point, radius: f32) -> f32 { + let offset = sub(point, centre); + offset[0].hypot(offset[1]) - radius +} + +/// `from` minus `to`, per axis +pub(crate) fn sub(from: Point, to: Point) -> Point { + [from[0] - to[0], from[1] - to[1]] +} + +/// The dot product of `a` and `b` +pub(crate) fn dot(a: Point, b: Point) -> f32 { + a[0] * b[0] + a[1] * b[1] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_rectangle_is_negative_inside_and_its_edge_distance_outside() { + assert!((rectangle([0.5, 0.5], [0.0, 0.0], [1.0, 1.0]) + 0.5).abs() < 1e-6, "the centre is half a side in"); + assert!((rectangle([1.25, 0.5], [0.0, 0.0], [1.0, 1.0]) - 0.25).abs() < 1e-6, "beside an edge"); + let reversed = convex_polygon([1.25, 0.5], &[[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]); + assert!((reversed - 0.25).abs() < 1e-6, "either winding order"); + assert_eq!(convex_polygon([0.0, 0.0], &[]), f32::INFINITY, "no corners, no ink"); + assert!((disc([0.0, 2.0], [0.0, 0.0], 1.5) - 0.5).abs() < 1e-6); + } + + #[test] + fn a_corner_list_that_closes_on_its_first_corner_draws_the_same_polygon() { + let open = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; + let closed = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]]; + for point in [[0.5, 0.5], [0.25, 0.75], [1.25, 0.5]] { + assert!((convex_polygon(point, &closed) - convex_polygon(point, &open)).abs() < 1e-6, "{point:?}"); + } + assert_eq!(convex_polygon([0.0, 0.0], &[[0.0, 0.0], [1.0, 0.0], [0.0, 0.0]]), f32::INFINITY, "a line encloses no ink"); + } +} diff --git a/crates/ui-egui/src/drawn_icon/invert.rs b/crates/ui-egui/src/drawn_icon/invert.rs new file mode 100644 index 00000000..51bd0810 --- /dev/null +++ b/crates/ui-egui/src/drawn_icon/invert.rs @@ -0,0 +1,50 @@ +//! The invert icon: a square, its left half clear and its right half solid, an arrow pointing out of each half + +use super::distance::{self, Point}; + +/// The frame's outline width and where its stroke's middle runs +const STROKE: f32 = 0.08; +const FRAME: [Point; 2] = [[0.13, 0.13], [0.87, 0.87]]; + +/// Where the halves meet, and the arrows' middle line +const MIDDLE: f32 = 0.5; + +/// An arrow's shaft (half thickness, length from the middle), its head (half height, from the middle to its base and to its point) +const SHAFT_HALF: f32 = 0.06; +const SHAFT_LENGTH: f32 = 0.16; +const HEAD_HALF: f32 = 0.17; +const HEAD_BASE: f32 = 0.12; +const HEAD_POINT: f32 = 0.29; + +/// The distance from `point` to the icon's ink: the left arrow inked on the clear half, the right one cut out of the solid half (black becomes white and white becomes black) +pub(crate) fn glyph(point: Point) -> f32 { + let frame = distance::rectangle(point, FRAME[0], FRAME[1]).abs() - STROKE / 2.0; + let solid_half = distance::rectangle(point, [MIDDLE, FRAME[0][1]], FRAME[1]); + frame.min(solid_half).max(-arrow(point, 1.0)).min(arrow(point, -1.0)) +} + +/// The distance from `point` to the arrow pointing from the middle toward `side` (1 right, -1 left) +fn arrow(point: Point, side: f32) -> f32 { + let x = |from_middle: f32| MIDDLE + side * from_middle; + let (shaft_end, base, tip) = (x(SHAFT_LENGTH), x(HEAD_BASE), x(HEAD_POINT)); + let shaft = distance::rectangle(point, [MIDDLE.min(shaft_end), MIDDLE - SHAFT_HALF], [MIDDLE.max(shaft_end), MIDDLE + SHAFT_HALF]); + let head = distance::convex_polygon(point, &[[base, MIDDLE - HEAD_HALF], [tip, MIDDLE], [base, MIDDLE + HEAD_HALF]]); + shaft.min(head) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_left_half_is_clear_with_an_inked_arrow_the_right_solid_with_a_cut_one() { + let ink = |x: f32, y: f32| glyph([x, y]) < 0.0; + + assert!(!ink(0.3, 0.25) && ink(0.7, 0.25), "left half clear, right half solid"); + assert!(ink(0.13, 0.5) && ink(0.5, 0.13) && ink(0.87, 0.87), "the frame closes the square"); + assert!(ink(0.25, 0.5) && ink(0.4, 0.5), "the left arrow is ink, point and shaft"); + assert!(!ink(0.75, 0.5) && !ink(0.6, 0.5), "the right arrow is cut out of the solid half"); + assert!(!ink(0.25, 0.3) && ink(0.75, 0.3), "each head narrows toward its point"); + assert!(!ink(0.03, 0.5) && !ink(0.5, 0.97), "nothing past the frame"); + } +} diff --git a/crates/ui-egui/src/drawn_icon/mod.rs b/crates/ui-egui/src/drawn_icon/mod.rs new file mode 100644 index 00000000..f42e29f9 --- /dev/null +++ b/crates/ui-egui/src/drawn_icon/mod.rs @@ -0,0 +1,102 @@ +//! Icons the icon font has no fitting glyph for, drawn in code from signed distances + +mod distance; +mod invert; +pub(crate) mod pipette; + +pub(crate) use distance::Point; + +/// The largest side an icon is rendered at, in pixels +const MAX_SIDE: u32 = 256; + +/// An icon drawn in code: rendered once per pixel size into a white texture and tinted where it is drawn, so it is as sharp as a font glyph at any scale +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum DrawnIcon { + /// The eyedropper: a pipette, tip at the bottom left + Pipette, + /// A square half clear, half solid, an arrow out of each half + Invert, +} + +impl DrawnIcon { + /// The distance from `point` (in the icon's unit square, y down) to the icon's ink, negative inside + pub(crate) fn distance(self, point: Point) -> f32 { + match self { + DrawnIcon::Pipette => pipette::glyph(point), + DrawnIcon::Invert => invert::glyph(point), + } + } + + /// How much of each pixel the icon covers when it is `side` pixels square, rows top first + pub(crate) fn coverage(self, side: u32) -> Vec { + let scale = side as f32; + (0..side * side) + .map(|index| { + let point = [((index % side) as f32 + 0.5) / scale, ((index / side) as f32 + 0.5) / scale]; + ((0.5 - self.distance(point) * scale).clamp(0.0, 1.0) * 255.0).round() as u8 + }) + .collect() + } + + /// Draws the icon `size` points square centred on `center` in `color`, on whole screen pixels + pub(crate) fn paint(self, painter: &egui::Painter, center: egui::Pos2, size: f32, color: egui::Color32) { + let pixels_per_point = painter.ctx().pixels_per_point(); + let side = ((size * pixels_per_point).round() as u32).clamp(1, MAX_SIDE); + let pixels = side as f32; + let min = ((center.to_vec2() * pixels_per_point) - egui::Vec2::splat(pixels / 2.0)).round() / pixels_per_point; + let rect = egui::Rect::from_min_size(min.to_pos2(), egui::Vec2::splat(pixels / pixels_per_point)); + let whole = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)); + painter.image(self.texture(painter.ctx(), side).id(), rect, whole, color); + } + + /// The icon `side` pixels square as a white texture with its coverage as alpha, rendered once per size + fn texture(self, ctx: &egui::Context, side: u32) -> egui::TextureHandle { + let id = egui::Id::unique(("drawn_icon", self, side)); + if let Some(texture) = ctx.data(|data| data.get_temp::(id)) { + return texture; + } + + let rgba: Vec = self.coverage(side).into_iter().flat_map(|alpha| [u8::MAX, u8::MAX, u8::MAX, alpha]).collect(); + let image = egui::ColorImage::from_rgba_unmultiplied([side as usize; 2], &rgba); + let texture = ctx.load_texture(format!("drawn_icon_{self:?}_{side}"), image, egui::TextureOptions::LINEAR); + ctx.data_mut(|data| data.insert_temp(id, texture.clone())); + texture + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_icon_is_painted_as_one_tinted_texture_on_whole_pixels() { + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = ui.painter(); + DrawnIcon::Invert.paint(painter, egui::pos2(10.3, 20.6), 14.0, egui::Color32::RED); + DrawnIcon::Invert.paint(painter, egui::pos2(40.0, 20.0), 14.0, egui::Color32::GREEN); + }); + let shapes: Vec = output.shapes.iter().map(|clipped| clipped.shape.clone()).collect(); + output.drop_without_applying_deltas(); + let meshes: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Mesh(mesh) = shape { Some(mesh.clone()) } else { None }).collect(); + + assert_eq!(meshes.len(), 2, "one textured quad per icon: {shapes:?}"); + let [first, second] = [&meshes[0], &meshes[1]]; + assert_eq!(first.texture_id, second.texture_id, "the texture is rendered once per size"); + let bounds = first.calc_bounds(); + assert_eq!((bounds.min, bounds.size()), (egui::pos2(3.0, 14.0), egui::vec2(14.0, 14.0)), "snapped to whole pixels"); + assert!(first.vertices.iter().all(|vertex| vertex.color == egui::Color32::RED), "tinted"); + } + + #[test] + fn coverage_is_full_inside_the_ink_and_clear_outside() { + let side = 32; + let invert = DrawnIcon::Invert.coverage(side); + let at = |x: f32, y: f32| invert.get(((y * side as f32) as u32 * side + (x * side as f32) as u32) as usize).copied(); + + assert_eq!(invert.len(), (side * side) as usize); + assert_eq!(at(0.7, 0.25), Some(u8::MAX), "the solid half"); + assert_eq!(at(0.3, 0.25), Some(0), "the clear half"); + assert_eq!(at(0.02, 0.02), Some(0), "outside the frame"); + } +} diff --git a/crates/ui-egui/src/drawn_icon/pipette.rs b/crates/ui-egui/src/drawn_icon/pipette.rs new file mode 100644 index 00000000..2ab0aae8 --- /dev/null +++ b/crates/ui-egui/src/drawn_icon/pipette.rs @@ -0,0 +1,94 @@ +//! The eyedropper: a pipette lying from its tip at the bottom left to its rubber bulb at the top right + +use std::f32::consts::FRAC_1_SQRT_2; + +use super::distance::{self, Point, dot, sub}; + +/// The tip's point in the unit square +const TIP: Point = [0.1, 0.9]; + +/// From the tip toward the bulb, and across the pipette, as unit directions +const ALONG: Point = [FRAC_1_SQRT_2, -FRAC_1_SQRT_2]; +const ACROSS: Point = [FRAC_1_SQRT_2, FRAC_1_SQRT_2]; + +/// The width of the tube's outline +pub(crate) const STROKE: f32 = 0.08; + +/// The tube's outline as `(along, across)` from the tip: a narrow tip widening into the straight tube, through the stroke's middle +const TUBE: [Point; 6] = [[0.0, -0.03], [0.18, -0.07], [0.62, -0.07], [0.62, 0.07], [0.18, 0.07], [0.0, 0.03]]; + +/// The collar between the tube and the bulb, wider than both +const COLLAR: [Point; 2] = [[0.62, -0.24], [0.7, 0.24]]; + +/// The bulb: straight from inside the collar (touching shapes leave a seam) to its round end's centre, as wide as that end +const BULB_FROM: f32 = 0.66; +const BULB_END: f32 = 0.93; +const BULB_RADIUS: f32 = 0.19; + +/// The distance from `point` to the glyph's ink: the tube's outline (hollow, so it reads as glass), the collar and the bulb; the collar and the slim tube under a fatter bulb tell a pipette from a baster +pub(crate) fn glyph(point: Point) -> f32 { + let local = local(point); + let tube = distance::convex_polygon(local, &TUBE).abs() - STROKE / 2.0; + tube.min(head(local)) +} + +/// The distance from `point` to the whole pipette's outer edge, the tube filled in: the pointer's white +pub(crate) fn silhouette(point: Point) -> f32 { + let local = local(point); + let tube = distance::convex_polygon(local, &TUBE) - STROKE / 2.0; + tube.min(head(local)) +} + +/// The collar and the bulb, in the pipette's own `(along, across)` frame +fn head(local: Point) -> f32 { + let collar = distance::rectangle(local, COLLAR[0], COLLAR[1]); + let bulb = distance::rectangle(local, [BULB_FROM, -BULB_RADIUS], [BULB_END, BULB_RADIUS]).min(distance::disc(local, [BULB_END, 0.0], BULB_RADIUS)); + collar.min(bulb) +} + +/// `point` as `(along, across)` from the tip +fn local(point: Point) -> Point { + let offset = sub(point, TIP); + [dot(offset, ALONG), dot(offset, ACROSS)] +} + +/// `(along, across)` from the tip as a point in the unit square +#[cfg(test)] +pub(crate) fn square(along: f32, across: f32) -> Point { + [TIP[0] + ALONG[0] * along + ACROSS[0] * across, TIP[1] + ALONG[1] * along + ACROSS[1] * across] +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The pipette's full width at `along` from the tip, sampled across it + fn width(along: f32) -> f32 { + let steps = 400; + let inked = (0..=steps).filter(|step| silhouette(square(along, -0.3 + 0.6 * *step as f32 / steps as f32)) <= 0.0).count(); + 0.6 * inked as f32 / steps as f32 + } + + #[test] + fn a_slim_tube_then_a_collar_wider_than_the_bulb() { + let (tip, tube, collar, bulb) = (width(0.02), width(0.4), width(0.66), width(0.85)); + + assert!(tip < tube, "the tip narrows: {tip} < {tube}"); + assert!(tube * 1.5 < bulb, "the bulb is far fatter than the tube: {tube} vs {bulb}"); + assert!(collar > bulb, "the collar sticks out past the bulb: {collar} vs {bulb}"); + } + + #[test] + fn the_glyphs_tube_is_hollow_and_its_head_solid() { + let tube_middle = square(0.4, 0.0); + assert!(glyph(tube_middle) > 0.0, "the glass tube shows the ground inside its outline"); + assert!(silhouette(tube_middle) < 0.0, "the pointer fills it"); + assert!(glyph(square(0.4, 0.07)) < 0.0, "the tube's outline is ink"); + assert!(glyph(square(0.85, 0.0)) < 0.0 && glyph(square(0.66, 0.2)) < 0.0, "bulb and collar are solid"); + let seam = (0..=40).map(|step| glyph(square(0.7, -0.15 + 0.3 * step as f32 / 40.0))).fold(f32::NEG_INFINITY, f32::max); + assert!(seam < -0.02, "no seam where the collar meets the bulb: {seam}"); + for corner in [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]] { + assert!(silhouette(corner) > 0.0, "the pipette stays inside its square: {corner:?}"); + } + } +} diff --git a/crates/ui-egui/src/id_color_pick.rs b/crates/ui-egui/src/id_color_pick.rs index 4ada66c8..f45cc2a0 100644 --- a/crates/ui-egui/src/id_color_pick.rs +++ b/crates/ui-egui/src/id_color_pick.rs @@ -7,9 +7,6 @@ use texturecraft_engine::{StackTarget, ViewMode}; use crate::TextureCraftApp; use crate::state::Mode; -/// Height in points of the eyedropper drawn as the pointer while picking -const EYEDROPPER_SIZE: f32 = 20.0; - /// A color selection waiting for a click, and the view to return to once it comes #[derive(Clone, Copy, Debug, PartialEq)] pub struct IdColorPick { @@ -57,18 +54,7 @@ impl IdColorPick { /// An eyedropper in place of the pointer while it is over `rect`, its tip on the hotspot pub fn draw_cursor(ui: &egui::Ui, rect: egui::Rect) { - let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|pointer| rect.contains(*pointer)) else { return }; - - ui.ctx().set_cursor_icon(egui::CursorIcon::None); - - // The glyph's tip is its bottom-left corner; a dark outline keeps it readable on any ID color - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("id_color_pick_cursor"))); - let font = egui::FontId::proportional(EYEDROPPER_SIZE); - let glyph = egui_phosphor::regular::EYEDROPPER; - for offset in [egui::vec2(-1.0, 0.0), egui::vec2(1.0, 0.0), egui::vec2(0.0, -1.0), egui::vec2(0.0, 1.0)] { - painter.text(pointer + offset, egui::Align2::LEFT_BOTTOM, glyph, font.clone(), egui::Color32::from_black_alpha(220)); - } - painter.text(pointer, egui::Align2::LEFT_BOTTOM, glyph, font, egui::Color32::WHITE); + crate::screen_pick::paint_cursor(ui.ctx(), Some(rect), None); } /// Ends pick mode once its effect is no longer selected or painting mode is left diff --git a/crates/ui-egui/src/screen_pick/cursor_image.rs b/crates/ui-egui/src/screen_pick/cursor_image.rs new file mode 100644 index 00000000..06eed9a8 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/cursor_image.rs @@ -0,0 +1,268 @@ +//! The eyedropper pointer an armed pick shows everywhere: the panels' pipette icon (tip at the bottom left, bulb at the top +//! right) in white with a dark outline so it reads on any colour, its glass tube's inside dark like the glyph's, the same picture +//! in the app and, where the system lets the app set the pointer, over other apps; its hotspot is the tip's last pixel, so the +//! pixel under the tip is the one picked. The pointer is a system pointer's cell (32 pixels at 100 %) with the pipette drawn +//! in its bottom-left part, about as tall as the system's arrow in its cell, so it reads at the size every other pointer has + +use super::swatch_picture::{disc_pixel, over, pipette_pixel}; +use super::{SwatchSide, swatch_reach, swatch_unit}; +use crate::drawn_icon::pipette; + +/// The outline's width in pixels at the smallest pointer; larger pointers scale it +const OUTLINE_PX: f32 = 1.0; +/// The pointer size the outline width is given for +const OUTLINE_SIZE: f32 = 24.0; +/// The coverage from which a pixel counts as ink for the hotspot +const INK_ALPHA: u8 = 128; +/// A `.cur` file's header (6 bytes) and its one picture's entry (16 bytes) +#[cfg(any(windows, test))] +const CUR_HEADER_BYTES: u32 = 22; +/// The `.cur` file type in its header (an `.ico` file says 1) +#[cfg(any(windows, test))] +const CUR_TYPE: u16 = 2; +/// A `BITMAPINFOHEADER`'s size +#[cfg(any(windows, test))] +const BITMAP_HEADER_BYTES: u32 = 40; +/// The `.cur` picture's colour depth: 8-bit blue, green, red and alpha +#[cfg(any(windows, test))] +const CUR_BITS_PER_PIXEL: u16 = 32; +/// A bitmap's mask rows are padded to whole 32-bit words +#[cfg(any(windows, test))] +const MASK_WORD_BITS: u32 = 32; +/// A mask byte's first pixel is its high bit +#[cfg(any(windows, test))] +const MASK_FIRST_BIT: u8 = 0x80; +/// The part of the pointer's cell the pipette's square takes (the system's arrow is about 20 pixels tall in its 32-pixel cell) +const GLYPH_SHARE: f32 = 0.625; +/// The smallest and largest pointer drawn, in pixels +pub(super) const SIZES: std::ops::RangeInclusive = 8..=256; +/// The largest picture with a colour disc made, in pixels (the largest pointer the systems take) +pub(super) const MAX_PICTURE_PX: u32 = 256; + +/// A square pointer picture in straight-alpha RGBA rows, top row first, with the pixel that is the pointer's position +#[derive(Clone, Debug, PartialEq)] +pub struct CursorImage { + pub size: u32, + pub rgba: Vec, + pub hotspot: [u32; 2], +} + +impl CursorImage { + /// The eyedropper in a pointer cell `size` pixels square (clamped to a sane range), the pipette in its bottom-left part + pub fn eyedropper(size: u32) -> Self { + let size = CursorImage::clamped_size(size); + let scale = (size as f32 * GLYPH_SHARE).round(); + let top = size as f32 - scale; + let outline = OUTLINE_PX * (scale / OUTLINE_SIZE).max(1.0); + let mut rgba = Vec::with_capacity((size * size * 4) as usize); + for y in 0..size { + for x in 0..size { + let point = [(x as f32 + 0.5) / scale, (y as f32 + 0.5 - top) / scale]; + let inside = pipette::silhouette(point) * scale; + let fill = (0.5 - inside).clamp(0.0, 1.0).min((0.5 - pipette::glyph(point) * scale).clamp(0.0, 1.0)); + let alpha = (0.5 - (inside - outline)).clamp(0.0, 1.0); + let grey = (fill * 255.0).round() as u8; + rgba.extend_from_slice(&[grey, grey, grey, (alpha * 255.0).round() as u8]); + } + } + let hotspot = tip(&rgba, size); + CursorImage { size, rgba, hotspot } + } + + /// The eyedropper in a `cell`-pixel pointer with a disc of `color` (8-bit sRGB) on `side` of its tip; its hotspot is the tip + pub fn eyedropper_with_swatch(cell: u32, color: [u8; 3], side: SwatchSide) -> Self { + let pipette = CursorImage::eyedropper(cell); + let unit = swatch_unit(cell); + let reach = swatch_reach(unit); + let [tip_x, tip_y] = pipette.hotspot.map(|edge| edge as f32 + 0.5); + let [offset_x, offset_y] = side.offset(); + let center = [tip_x + offset_x * unit, tip_y + offset_y * unit]; + + // The picture spans the pipette's cell and the disc, as a square + let left = (center[0] - reach).floor().min(0.0); + let top = (center[1] - reach).floor().min(0.0); + let right = (center[0] + reach).ceil().max(pipette.size as f32); + let bottom = (center[1] + reach).ceil().max(pipette.size as f32); + let side_px = (right - left).max(bottom - top) as u32; + if side_px > MAX_PICTURE_PX && cell > 1 { + let smaller = (cell as f32 * MAX_PICTURE_PX as f32 / side_px as f32).floor() as u32; + return CursorImage::eyedropper_with_swatch(smaller.min(cell - 1), color, side); + } + + let mut rgba = Vec::with_capacity((side_px * side_px * 4) as usize); + for y in 0..side_px { + for x in 0..side_px { + let [cell_x, cell_y] = [x as f32 + left, y as f32 + top]; + let under = pipette_pixel(&pipette, cell_x, cell_y); + let distance = ((cell_x + 0.5 - center[0]).powi(2) + (cell_y + 0.5 - center[1]).powi(2)).sqrt(); + rgba.extend_from_slice(&over(disc_pixel(distance, unit, color), under)); + } + } + + let hotspot = [pipette.hotspot[0] + (-left) as u32, pipette.hotspot[1] + (-top) as u32]; + CursorImage { size: side_px, rgba, hotspot } + } + + /// A pointer size kept to the range drawn + pub fn clamped_size(size: u32) -> u32 { + size.clamp(*SIZES.start(), *SIZES.end()) + } + + /// The picture as a Windows `.cur` file: 32-bit colour with alpha, its hotspot in the file's header + #[cfg(any(windows, test))] + pub fn cur_file(&self) -> Vec { + let side = self.size; + let mask_row = side.div_ceil(MASK_WORD_BITS) * (MASK_WORD_BITS / u8::BITS); + let pixel_bytes = side * side * 4; + let image_bytes = BITMAP_HEADER_BYTES + pixel_bytes + mask_row * side; + let mut file = Vec::with_capacity((CUR_HEADER_BYTES + image_bytes) as usize); + + // The file's header: one cursor picture, a byte size of 0 standing for 256 + for word in [0_u16, CUR_TYPE, 1] { + file.extend_from_slice(&word.to_le_bytes()); + } + let byte_side = u8::try_from(side).unwrap_or(0); + file.extend_from_slice(&[byte_side, byte_side, 0, 0]); + for word in self.hotspot.map(|edge| u16::try_from(edge).unwrap_or(0)) { + file.extend_from_slice(&word.to_le_bytes()); + } + file.extend_from_slice(&image_bytes.to_le_bytes()); + file.extend_from_slice(&CUR_HEADER_BYTES.to_le_bytes()); + + // The bitmap's header: twice the height, the colour picture over its mask + let side_signed = i32::try_from(side).unwrap_or(0); + for word in [BITMAP_HEADER_BYTES as i32, side_signed, side_signed * 2] { + file.extend_from_slice(&word.to_le_bytes()); + } + file.extend_from_slice(&1_u16.to_le_bytes()); + file.extend_from_slice(&CUR_BITS_PER_PIXEL.to_le_bytes()); + for word in [0, pixel_bytes + mask_row * side, 0, 0, 0, 0] { + file.extend_from_slice(&word.to_le_bytes()); + } + + // Rows bottom up: blue, green, red, alpha; then the mask, set where the picture is clear + for row in self.rgba.chunks_exact(side as usize * 4).rev() { + for &[red, green, blue, alpha] in row.as_chunks::<4>().0 { + file.extend_from_slice(&[blue, green, red, alpha]); + } + } + for row in self.rgba.chunks_exact(side as usize * 4).rev() { + let mut bits = vec![0_u8; mask_row as usize]; + for (x, &[.., alpha]) in row.as_chunks::<4>().0.iter().enumerate() { + if alpha == 0 + && let Some(byte) = bits.get_mut(x / u8::BITS as usize) + { + *byte |= MASK_FIRST_BIT >> (x % u8::BITS as usize); + } + } + file.extend_from_slice(&bits); + } + file + } + + /// The alpha of the pixel at `(x, y)`, none outside the picture + pub fn alpha(&self, x: u32, y: u32) -> Option { + let index = (y.checked_mul(self.size)?.checked_add(x)? as usize).checked_mul(4)?.checked_add(3)?; + (x < self.size).then(|| self.rgba.get(index).copied()).flatten() + } +} + +/// The ink pixel furthest toward the bottom-left corner: the pipette's tip +fn tip(rgba: &[u8], size: u32) -> [u32; 2] { + let ink = rgba.as_chunks::<4>().0.iter().enumerate().filter(|(_, [.., alpha])| *alpha >= INK_ALPHA); + let corner = ink.map(|(index, _)| [index as u32 % size, index as u32 / size]).max_by_key(|&[x, y]| (i64::from(y) - i64::from(x), y)); + corner.unwrap_or([0, size.saturating_sub(1)]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_hotspot_is_the_tips_last_ink_pixel_at_every_size() { + for size in [16, 24, 32, 48, 64] { + let image = CursorImage::eyedropper(size); + let [hx, hy] = image.hotspot; + + assert!(image.alpha(hx, hy).is_some_and(|alpha| alpha >= INK_ALPHA), "{size}: the hotspot pixel is ink"); + assert!(hx < size / 4 && hy >= size * 3 / 4, "{size}: the tip is at the bottom left: {:?}", image.hotspot); + for y in 0..size { + for x in 0..size { + let ink = image.alpha(x, y).is_some_and(|alpha| alpha >= INK_ALPHA); + let further = i64::from(y) - i64::from(x) > i64::from(hy) - i64::from(hx); + assert!(!(ink && further), "{size}: ink at ({x}, {y}) lies beyond the tip"); + } + } + } + } + + #[test] + fn the_pipette_is_white_inside_a_dark_outline_on_a_clear_ground() { + let image = CursorImage::eyedropper(32); + let pixel = |x: u32, y: u32| image.rgba.get(((y * 32 + x) * 4) as usize..((y * 32 + x) * 4 + 4) as usize).map(<[u8]>::to_vec); + + let [bulb_x, bulb_y] = pipette::square(0.85, 0.0).map(|edge| (edge * 20.0) as u32); + assert_eq!(pixel(bulb_x, bulb_y + 12), Some(vec![255, 255, 255, 255]), "the bulb is white"); + assert_eq!(pixel(31, 31).and_then(|pixel| pixel.get(3).copied()), Some(0), "the bottom-right corner is clear"); + let [hx, hy] = image.hotspot; + assert!(pixel(hx, hy).and_then(|pixel| pixel.first().copied()).is_some_and(|grey| grey < 128), "the tip's edge is the dark outline"); + assert_eq!(CursorImage::eyedropper(0).size, 8, "a degenerate size is clamped"); + } + + #[test] + fn the_pipette_is_as_tall_as_the_systems_arrow_in_its_cell_at_every_size() { + for size in [32, 48, 64] { + let image = CursorImage::eyedropper(size); + let ink: Vec<[u32; 2]> = + (0..size).flat_map(|y| (0..size).map(move |x| [x, y])).filter(|&[x, y]| image.alpha(x, y).is_some_and(|a| a > 0)).collect(); + let span = |axis: usize| { + let along = ink.iter().map(|pixel| pixel[axis]); + along.clone().max().unwrap_or(0) - along.min().unwrap_or(0) + 1 + }; + let most = (size as f32 * 0.69).ceil() as u32; + + assert_eq!(image.size, size, "the pointer's cell is the system pointer's size"); + assert!(span(0) <= most && span(1) <= most, "{size}: the pipette takes {}x{} of the cell, at most {most}", span(0), span(1)); + assert!(span(0) >= size / 2 && span(1) >= size / 2, "{size}: and still reads: {}x{}", span(0), span(1)); + } + } + + #[test] + fn the_pointer_is_the_panels_pipette_white_with_its_glass_tube_hollow() { + let size = 48; + let image = CursorImage::eyedropper(size); + let glyph_px = (size as f32 * GLYPH_SHARE).round() as u32; + let top = size - glyph_px; + let glyph = crate::drawn_icon::DrawnIcon::Pipette.coverage(glyph_px); + let at = |[x, y]: [f32; 2]| ((y * glyph_px as f32) as u32 + top, (x * glyph_px as f32) as u32); + let grey = |point: [f32; 2]| { + let (row, column) = at(point); + image.rgba.get(((row * size + column) * 4) as usize).copied() + }; + + let tube = pipette::square(0.4, 0.0); + assert!(grey(tube).is_some_and(|grey| grey < 64), "the tube's inside is dark, as the glyph leaves it clear"); + assert!(image.alpha(at(tube).1, at(tube).0).is_some_and(|alpha| alpha == u8::MAX), "and still opaque, so the pointer reads"); + assert_eq!(grey(pipette::square(0.85, 0.0)), Some(u8::MAX), "the bulb is white"); + for (index, coverage) in glyph.iter().enumerate() { + let (row, column) = (index as u32 / glyph_px + top, index as u32 % glyph_px); + let alpha = image.alpha(column, row).unwrap_or(0); + assert!(*coverage == 0 || alpha > 0, "every pixel of the glyph's ink is part of the pointer ({index})"); + } + } + + #[test] + fn the_cur_files_hotspot_is_the_tip_and_its_pixel_is_ink() { + let image = CursorImage::eyedropper(32); + let file = image.cur_file(); + let word = |at: usize| file.get(at..at + 2).map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]])); + + assert_eq!([word(2), word(4)], [Some(CUR_TYPE), Some(1)], "one cursor picture"); + assert_eq!([word(10), word(12)], [Some(image.hotspot[0] as u16), Some(image.hotspot[1] as u16)], "the hotspot is the tip"); + assert_eq!(file.len(), (CUR_HEADER_BYTES + BITMAP_HEADER_BYTES) as usize + 32 * 32 * 4 + 4 * 32, "header, bitmap header, colour rows and mask rows"); + let [hx, hy] = image.hotspot; + let bottom_up_row = (31 - hy) as usize; + let alpha = file.get((CUR_HEADER_BYTES + BITMAP_HEADER_BYTES) as usize + (bottom_up_row * 32 + hx as usize) * 4 + 3).copied(); + assert!(alpha.is_some_and(|alpha| alpha >= INK_ALPHA), "the file's hotspot pixel is the tip's ink: {alpha:?}"); + } +} diff --git a/crates/ui-egui/src/screen_pick/cursor_texture.rs b/crates/ui-egui/src/screen_pick/cursor_texture.rs new file mode 100644 index 00000000..104dc59a --- /dev/null +++ b/crates/ui-egui/src/screen_pick/cursor_texture.rs @@ -0,0 +1,33 @@ +use super::{CursorImage, SwatchSide}; + +/// What a pointer picture shows: its cell in pixels and the colour disc's colour and side, if any +pub(super) type CursorLook = (u32, Option<([u8; 3], SwatchSide)>); + +/// The eyedropper picture uploaded for one look, kept between frames +#[derive(Clone)] +pub(super) struct CursorTexture { + pub(super) texture: egui::TextureHandle, + look: CursorLook, + pub(super) size: u32, + pub(super) hotspot: [u32; 2], +} + +impl CursorTexture { + /// The eyedropper picture for `look`, uploaded again only when the look changes (the disc's colour, its side, the pixel size) + pub(super) fn for_look(ctx: &egui::Context, look: CursorLook) -> Self { + let id = egui::Id::unique("eyedropper_cursor_texture"); + if let Some(cursor) = ctx.data(|data| data.get_temp::(id)).filter(|cursor| cursor.look == look) { + return cursor; + } + + let image = match look { + (cell, Some((color, side))) => CursorImage::eyedropper_with_swatch(cell, color, side), + (cell, None) => CursorImage::eyedropper(cell), + }; + let pixels = egui::ColorImage::from_rgba_unmultiplied([image.size as usize; 2], &image.rgba); + let texture = ctx.load_texture("eyedropper_cursor", pixels, egui::TextureOptions::NEAREST); + let cursor = CursorTexture { texture, look, size: image.size, hotspot: image.hotspot }; + ctx.data_mut(|data| data.insert_temp(id, cursor.clone())); + cursor + } +} diff --git a/crates/ui-egui/src/screen_pick/eyedropper_pointer.rs b/crates/ui-egui/src/screen_pick/eyedropper_pointer.rs new file mode 100644 index 00000000..cf2fb663 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/eyedropper_pointer.rs @@ -0,0 +1,188 @@ +//! Windows: while an eyedropper pick waits for a click outside the app, the system's pointers are the eyedropper over every app +//! and monitor. A keeper process (this program started with `KEEPER_ARG`) swaps them and puts the user's own back when the pick +//! ends, and also when the app goes away for any reason: it watches the app's process, so the system pointer is never left +//! changed. The keeper is started with the system's start-up feedback off: Windows otherwise shows its "app starting" pointer +//! (an arrow with a busy circle) over every app for up to seven seconds after a program starts, until the program first calls +//! `GetMessage`, which a keeper never does, and that pointer showed instead of the eyedropper. Once the keeper has kept the +//! user's pointers and shown the eyedropper, the app swaps in the eyedropper with its live colour disc; the keeper still puts +//! the user's own back + +use std::sync::atomic::{AtomicU64, Ordering}; + +use winsafe::guard::{CloseHandleGuard, CloseHandlePiGuard, DestroyCursorGuard}; +use winsafe::prelude::Handle; +use winsafe::{HEVENT, HINSTANCE, HPROCESS, IdOcrStr, SIZE, STARTUPINFO, co}; + +use super::CursorImage; +use super::keeper_args::KeeperArgs; + +/// How long the app waits for the keeper to put the user's pointers back, in milliseconds +const RESTORE_WAIT_MS: u32 = 2_000; +/// How often the keeper looks whether the app still runs, in milliseconds +const WATCH_MS: u32 = 50; + +/// The system pointers other apps show; the animated busy pointers stay as they are (a copy would keep one frame) +const POINTERS: [co::OCR; 11] = [ + co::OCR::NORMAL, + co::OCR::IBEAM, + co::OCR::CROSS, + co::OCR::UP, + co::OCR::SIZENWSE, + co::OCR::SIZENESW, + co::OCR::SIZEWE, + co::OCR::SIZENS, + co::OCR::SIZEALL, + co::OCR::NO, + co::OCR::HAND, +]; + +/// The keeper's exit code for a command line it can't read +const EXIT_BAD_ARGS: i32 = 2; +/// The keeper's exit code when the app's process, its event or the eyedropper can't be had +const EXIT_UNAVAILABLE: i32 = 1; + +/// Each pick's own stop event +static NEXT_PICK: AtomicU64 = AtomicU64::new(0); + +/// The eyedropper as the system pointer, until this is dropped +pub(super) struct EyedropperPointer { + keeper: CloseHandlePiGuard, + stop: CloseHandleGuard, + /// The event the keeper sets once it has kept the user's pointers, held so it lives as long as the pick + _shown: CloseHandleGuard, + /// That event's name + pub(super) shown_event: String, + /// The system's pointer cell at the app window's density, in pixels + pub(super) cell: u32, +} + +impl EyedropperPointer { + /// Starts the keeper for a window at `dpi` dots per inch; `None` leaves the system pointer as it is + pub(super) fn show(dpi: u32) -> Option { + let program = std::env::current_exe().ok()?; + let parent = std::process::id(); + + // The pick's stop event, and the event the keeper sets once it has kept the user's pointers + let stop_name = format!("Local\\texturecraft-eyedropper-{parent}-{}", NEXT_PICK.fetch_add(1, Ordering::Relaxed)); + let stop = HEVENT::CreateEvent(None, true, false, Some(&stop_name)).ok()?; + let args = KeeperArgs { parent, stop: stop_name, dpi }; + let shown_event = args.shown_event(); + let shown = HEVENT::CreateEvent(None, true, false, Some(&shown_event)).ok()?; + + let cell = args.pointer_px(winsafe::GetSystemMetricsForDpi(co::SM::CXCURSOR, dpi).ok()); + let command_line = args.command_line(program.to_str()?); + + let mut startup = STARTUPINFO::default(); + + // No "app starting" pointer for the keeper: it shows no window and never asks for input + startup.dwFlags = co::STARTF::FORCEOFFFEEDBACK; + let keeper = winsafe::CreateProcess(None, Some(&command_line), None, None, false, co::CREATE::NO_WINDOW, &[], None, &mut startup); + Some(EyedropperPointer { keeper: keeper.ok()?, stop, _shown: shown, shown_event, cell }) + } +} + +impl Drop for EyedropperPointer { + fn drop(&mut self) { + // Waited for (at most RESTORE_WAIT_MS): windows_hook::run starts the next pick's keeper only after the user's pointers are back + let _ = self.stop.SetEvent(); + let _ = self.keeper.hProcess.WaitForSingleObject(Some(RESTORE_WAIT_MS)); + } +} + +/// Shows `image` as every swapped system pointer (only once the keeper has kept the user's own); whether it could +pub(super) fn swap_in(image: &CursorImage) -> bool { + let Some(picture) = load(image) else { return false }; + + swap_all(&picture); + true +} + +/// The keeper process's work and exit code: the eyedropper as the system pointer until the pick ends or the app is gone +pub fn keep_pointer() -> i32 { + let Some(keeper) = KeeperArgs::parse_os(std::env::args_os().skip(2)) else { return EXIT_BAD_ARGS }; + let Ok(app) = HPROCESS::OpenProcess(co::PROCESS::SYNCHRONIZE, false, keeper.parent) else { return EXIT_UNAVAILABLE }; + let Ok(stop) = HEVENT::NULL.OpenEvent(co::EVENT_RIGHTS::SYNCHRONIZE, false, &keeper.stop) else { return EXIT_UNAVAILABLE }; + if ended(stop.WaitForSingleObject(Some(0))) { + return 0; + } + + let size = keeper.pointer_px(winsafe::GetSystemMetricsForDpi(co::SM::CXCURSOR, keeper.dpi).ok()); + let Some(eyedropper) = load(&CursorImage::eyedropper(size)) else { return EXIT_UNAVAILABLE }; + let originals: Vec<_> = POINTERS.iter().filter_map(|&pointer| Some((pointer, current(pointer)?))).collect(); + + // A pointer whose copy failed could never be put back: the user's pointers then stay as they are + if !every_pointer_kept(originals.len()) { + return EXIT_UNAVAILABLE; + } + + swap_all(&eyedropper); + + // The app may change the picture from now on: the user's own pointers are kept + if let Ok(shown) = HEVENT::NULL.OpenEvent(co::EVENT_RIGHTS::MODIFY_STATE, false, &keeper.shown_event()) { + let _ = shown.SetEvent(); + } + + // Ends when the app sets the stop event (the pick ended) or its process ends (closed, killed, crashed) + while !ended(stop.WaitForSingleObject(Some(0))) && !ended(app.WaitForSingleObject(Some(WATCH_MS))) {} + + // The user's own pointers back; the system owns each one it took + for (pointer, mut original) in originals { + if original.SetSystemCursor(pointer).is_ok() { + let _ = original.leak(); + } + } + + 0 +} + +/// Whether a copy of each pointer swapped was kept (`kept` copies), so each can be put back +fn every_pointer_kept(kept: usize) -> bool { + kept == POINTERS.len() +} + +/// `picture` as each of the system pointers other apps show +fn swap_all(picture: &DestroyCursorGuard) { + for pointer in POINTERS { + if let Ok(mut copy) = picture.CopyCursor() + && copy.SetSystemCursor(pointer).is_ok() + { + // The system owns the copy now + let _ = copy.leak(); + } + } +} + +/// Whether a wait says its object is signalled (or can't be waited on, which ends the keeper just as well) +fn ended(wait: winsafe::SysResult) -> bool { + !matches!(wait, Ok(co::WAIT::TIMEOUT)) +} + +/// A copy of the system pointer `pointer` as it is now +fn current(pointer: co::OCR) -> Option { + let mut shared = HINSTANCE::NULL.LoadImageCursor(IdOcrStr::Ocr(pointer), SIZE::default(), co::LR::SHARED | co::LR::DEFAULTSIZE).ok()?; + let copy = shared.CopyCursor().ok(); + + // A shared pointer belongs to the system and is never destroyed + let _ = shared.leak(); + copy +} + +/// `image` as a Windows pointer (loaded from a `.cur` file, the one safe way to make a coloured pointer) +fn load(image: &CursorImage) -> Option { + let file = std::env::temp_dir().join(format!("texturecraft-eyedropper-{}.cur", std::process::id())); + std::fs::write(&file, image.cur_file()).ok()?; + let loaded = HINSTANCE::NULL.LoadImageCursor(IdOcrStr::from_str(&file.to_string_lossy()), SIZE::default(), co::LR::LOADFROMFILE); + let _ = std::fs::remove_file(&file); + loaded.ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pointers_are_swapped_only_when_each_one_can_be_put_back() { + assert!(every_pointer_kept(POINTERS.len()), "every pointer kept: the eyedropper shows"); + assert!(!every_pointer_kept(POINTERS.len() - 1), "one copy failed: the user's pointers stay as they are"); + } +} diff --git a/crates/ui-egui/src/screen_pick/hook_state.rs b/crates/ui-egui/src/screen_pick/hook_state.rs new file mode 100644 index 00000000..f328fb6e --- /dev/null +++ b/crates/ui-egui/src/screen_pick/hook_state.rs @@ -0,0 +1,28 @@ +use std::sync::Arc; +use std::sync::mpsc::Sender; + +use winsafe::POINT; + +use super::release_wait::ReleaseWait; +use super::{PickOutcome, PickShared}; + +/// The running pick the hook procedure reports to (a hook procedure has no context of its own) +pub(super) struct HookState { + /// Which pick this is: a pick that ends after the next one started leaves the next one's state alone + pub(super) generation: u64, + pub(super) shared: Arc, + pub(super) outcomes: Sender, + pub(super) ctx: egui::Context, + /// Where the press it took was: the hook's thread reads that pixel once the hook procedure has answered + pub(super) pending_pick: Option, + /// The wait for the release of the press it took, which is taken too + pub(super) release_wait: Option, + pub(super) done: bool, +} + +impl HookState { + /// Pick `generation`'s state before any click + pub(super) fn new(generation: u64, shared: Arc, outcomes: Sender, ctx: egui::Context) -> Self { + HookState { generation, shared, outcomes, ctx, pending_pick: None, release_wait: None, done: false } + } +} diff --git a/crates/ui-egui/src/screen_pick/keeper_args.rs b/crates/ui-egui/src/screen_pick/keeper_args.rs new file mode 100644 index 00000000..8ffc2e56 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/keeper_args.rs @@ -0,0 +1,134 @@ +//! The pointer keeper's command line on Windows: whose pick it serves (the app's process id), the event that ends the pick and +//! the dots per inch of the app's window, which size the eyedropper pointer as the system sizes its own pointers there + +#[cfg(any(windows, test))] +use std::ffi::OsString; + +#[cfg(any(windows, test))] +use super::cursor_image::SIZES; + +/// The argument that starts this program as the pointer keeper +pub const KEEPER_ARG: &str = "--eyedropper-pointer"; + +/// The screen density of a system pointer's nominal size (32 pixels at 100 %) +pub(crate) const BASE_DPI: u32 = 96; +/// The nominal pointer cell at `BASE_DPI` +#[cfg(any(windows, test))] +const BASE_POINTER_PX: u32 = 32; +/// The densest screen taken from a command line (Windows scales to 500 %) +#[cfg(any(windows, test))] +const MAX_DPI: u32 = BASE_DPI * 5; + +/// The shown event's name after the stop event's +#[cfg(any(windows, test))] +const SHOWN_SUFFIX: &str = "-shown"; +/// The longest stop event name taken (the app's are about 50 characters): with its suffix it stays under the system's 260 +#[cfg(any(windows, test))] +const MAX_EVENT_NAME_LEN: usize = 200; + +/// What a pointer keeper is started with +#[cfg(any(windows, test))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct KeeperArgs { + /// The app's process: the keeper puts the user's pointers back when it ends, however it ends + pub parent: u32, + /// The name of the event the app sets when the pick ends + pub stop: String, + /// The app window's dots per inch + pub dpi: u32, +} + +#[cfg(any(windows, test))] +impl KeeperArgs { + /// The whole command line that starts `program` as this keeper (Windows paths hold no quotes) + pub fn command_line(&self, program: &str) -> String { + format!("\"{program}\" {KEEPER_ARG} {} {} {}", self.parent, self.stop, self.dpi) + } + + /// The keeper's arguments after `KEEPER_ARG`, or `None` for anything else + pub fn parse(args: &[String]) -> Option { + let [parent, stop, dpi] = args else { return None }; + let stop = stop.clone(); + let usable_name = !stop.is_empty() + && stop.len() <= MAX_EVENT_NAME_LEN + && stop.chars().all(|character| character.is_ascii_alphanumeric() || "\\-_".contains(character)); + let dpi = dpi.parse::().ok().filter(|dpi| *dpi > 0)?.min(MAX_DPI); + + Some(KeeperArgs { parent: parent.parse().ok()?, stop: usable_name.then_some(stop)?, dpi }) + } + + /// The keeper's arguments after `KEEPER_ARG` as the system gives them; `None` also for one that is not Unicode (no panic) + pub fn parse_os(args: impl IntoIterator) -> Option { + let args = args.into_iter().map(|arg| arg.into_string().ok()).collect::>>()?; + Self::parse(&args) + } + + /// The name of the event the keeper sets once the eyedropper shows: from then on the app may change the pointer's picture + pub fn shown_event(&self) -> String { + format!("{}{SHOWN_SUFFIX}", self.stop) + } + + /// The pointer cell in pixels: the system's own pointer size at this density (`system`, where it says), else 32 scaled + pub fn pointer_px(&self, system: Option) -> u32 { + let scaled = BASE_POINTER_PX * self.dpi / BASE_DPI; + system.and_then(|px| u32::try_from(px).ok()).filter(|px| SIZES.contains(px)).unwrap_or(scaled) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(line: &[&str]) -> Vec { + line.iter().map(|arg| (*arg).to_owned()).collect() + } + + #[test] + fn the_keeper_reads_back_the_command_line_the_app_writes() { + let keeper = KeeperArgs { parent: 4120, stop: "Local\\texturecraft-eyedropper-4120-3".into(), dpi: 144 }; + let line = keeper.command_line("C:\\Program Files\\TextureCraft\\texturecraft.exe"); + let after_arg = line.split_once(KEEPER_ARG).map(|(_, rest)| rest.split_whitespace().map(str::to_owned).collect::>()); + + assert!(line.starts_with("\"C:\\Program Files\\TextureCraft\\texturecraft.exe\" "), "the program's path is quoted: {line}"); + assert_eq!(after_arg.and_then(|rest| KeeperArgs::parse(&rest)), Some(keeper.clone())); + assert_eq!(keeper.shown_event(), "Local\\texturecraft-eyedropper-4120-3-shown", "the shown event is the pick's own"); + } + + #[test] + fn a_hostile_command_line_starts_no_keeper() { + assert_eq!(KeeperArgs::parse(&args(&[])), None); + assert_eq!(KeeperArgs::parse(&args(&["12", "stop"])), None, "too few"); + assert_eq!(KeeperArgs::parse(&args(&["12", "stop", "96", "x"])), None, "too many"); + assert_eq!(KeeperArgs::parse(&args(&["-1", "stop", "96"])), None, "no such process"); + assert_eq!(KeeperArgs::parse(&args(&["12", "stop", "0"])), None, "no density"); + assert_eq!(KeeperArgs::parse(&args(&["12", "a b", "96"])), None, "an event name with a space"); + assert_eq!(KeeperArgs::parse(&args(&["12", "stop", "99999"])).map(|keeper| keeper.dpi), Some(MAX_DPI), "capped"); + } + + #[test] + fn a_command_line_argument_that_is_not_unicode_starts_no_keeper() { + #[cfg(unix)] + let not_unicode = std::os::unix::ffi::OsStringExt::from_vec(vec![0xFF]); + #[cfg(windows)] + let not_unicode = std::os::windows::ffi::OsStringExt::from_wide(&[0xD800]); + let line = |stop: OsString| [OsString::from("12"), stop, OsString::from("96")]; + + assert_eq!(KeeperArgs::parse_os(line(not_unicode)), None, "refused, not a panic"); + assert_eq!( + KeeperArgs::parse_os(line(OsString::from("stop"))), + Some(KeeperArgs { parent: 12, stop: "stop".into(), dpi: 96 }), + "plain arguments read as they are" + ); + } + + #[test] + fn the_pointer_is_the_systems_pointer_size_at_the_windows_density() { + let at = |dpi| KeeperArgs { parent: 1, stop: "s".into(), dpi }; + + assert_eq!(at(96).pointer_px(Some(32)), 32, "the system's size wins"); + assert_eq!(at(144).pointer_px(Some(48)), 48); + assert_eq!(at(144).pointer_px(None), 48, "else 32 pixels at 100 %, scaled"); + assert_eq!(at(120).pointer_px(Some(0)), 40, "a size the system can't mean is not taken"); + assert_eq!(at(96).pointer_px(Some(100_000)), 32); + } +} diff --git a/crates/ui-egui/src/screen_pick/live_swatch.rs b/crates/ui-egui/src/screen_pick/live_swatch.rs new file mode 100644 index 00000000..8d03b410 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/live_swatch.rs @@ -0,0 +1,67 @@ +//! Windows: the eyedropper's colour disc over other apps, part of the system pointer's picture, so it moves with the pointer +//! itself; each refresh reads the one desktop pixel under the tip and swaps in a new picture only when its colour or side changed + +use std::time::Duration; + +use winsafe::guard::CloseHandleGuard; +use winsafe::prelude::Handle; +use winsafe::{HEVENT, HMONITOR, POINT, co}; + +use super::eyedropper_pointer::swap_in; +use super::windows_hook::{over_own_window, screen_pixel, waiting}; +use super::{CursorImage, PickShared, SwatchSide, pick_shared::over_windows, swatch_reach, swatch_unit}; + +/// How often the disc reads the colour under the tip (one display frame at 60 Hz) +const REFRESH: Duration = Duration::from_millis(16); + +/// The disc the system pointer shows now +pub(super) struct LiveSwatch { + /// Set once the keeper has kept the user's pointers: no picture is swapped in before, or theirs would be lost + keeper_ready: CloseHandleGuard, + /// The system's pointer cell, in pixels + cell: u32, + shown: Option<([u8; 3], SwatchSide)>, +} + +impl LiveSwatch { + /// Keeps the disc on the colour under the tip until pick `generation` ends (`shown_event` names the keeper's ready event) + pub(super) fn follow(shown_event: &str, cell: u32, shared: &PickShared, generation: u64) { + let Ok(keeper_ready) = HEVENT::NULL.OpenEvent(co::EVENT_RIGHTS::SYNCHRONIZE, false, shown_event) else { return }; + + let mut swatch = LiveSwatch { keeper_ready, cell, shown: None }; + while waiting(shared, generation) { + swatch.refresh(shared); + std::thread::sleep(REFRESH); + } + } + + /// Shows the colour under the tip in the pointer's disc, while the pointer is off the app (the app draws its own there) + fn refresh(&mut self, shared: &PickShared) { + let Ok(point) = winsafe::GetCursorPos() else { return }; + if over_own_window(point) || over_windows(&shared.windows(), point.x, point.y) { + return; + } + + if !matches!(self.keeper_ready.WaitForSingleObject(Some(0)), Ok(co::WAIT::OBJECT_0)) { + return; + } + + let Some(color) = screen_pixel(point) else { return }; + + let look = (color, side(point, self.cell)); + if self.shown != Some(look) && swap_in(&CursorImage::eyedropper_with_swatch(self.cell, look.0, look.1)) { + self.shown = Some(look); + } + } +} + +/// The side of the tip whose disc stays on the monitor the pointer is on +fn side(point: POINT, cell: u32) -> SwatchSide { + let unit = swatch_unit(cell); + let tip = [point.x as f32 + 0.5, point.y as f32 + 0.5]; + let Ok(info) = HMONITOR::MonitorFromPoint(point, co::MONITOR::DEFAULTTONEAREST).GetMonitorInfo() else { return SwatchSide::BelowRight }; + + let screen = info.rcMonitor; + let bounds = [screen.left, screen.top, screen.right, screen.bottom].map(|edge| edge as f32); + SwatchSide::fitting(tip, unit, swatch_reach(unit), bounds) +} diff --git a/crates/ui-egui/src/screen_pick/mod.rs b/crates/ui-egui/src/screen_pick/mod.rs new file mode 100644 index 00000000..b7a2f1fb --- /dev/null +++ b/crates/ui-egui/src/screen_pick/mod.rs @@ -0,0 +1,221 @@ +//! Eyedropper picks outside the app: while a colour bar's eyedropper waits, a left click anywhere on the desktop (another app, a +//! reference picture on another monitor) reads the one screen pixel under it at that moment. Nothing records the screen, and +//! clicks on the app's own windows keep picking from the model. Where the system allows neither, the pick stays on the model; +//! while a pick waits the pointer is the eyedropper, drawn over the app's window and, where the system allows, over every app + +mod cursor_image; +mod cursor_texture; +#[cfg(windows)] +mod eyedropper_pointer; +#[cfg(windows)] +mod hook_state; +mod keeper_args; +#[cfg(windows)] +mod live_swatch; +mod painted_cursor; +mod pick_outcome; +mod pick_shared; +#[cfg(all(unix, not(target_os = "macos")))] +mod pixel_layout; +#[cfg(all(unix, not(target_os = "macos")))] +mod portal; +#[cfg(all(unix, not(target_os = "macos")))] +mod premultiplied_argb; +#[cfg(any(windows, test))] +mod release_wait; +#[cfg(all(unix, not(target_os = "macos")))] +mod shown_disc; +mod swatch_color; +mod swatch_picture; +mod swatch_side; +#[cfg(windows)] +mod windows_hook; +#[cfg(all(unix, not(target_os = "macos")))] +mod x11_grab; + +use std::sync::Arc; +use std::sync::mpsc::{self, Receiver, Sender}; + +pub use cursor_image::CursorImage; +#[cfg(windows)] +pub use eyedropper_pointer::keep_pointer; +pub use keeper_args::KEEPER_ARG; +pub use painted_cursor::paint as paint_cursor; +pub use pick_outcome::PickOutcome; +pub(crate) use pick_shared::PickShared; +pub(crate) use swatch_color::SwatchColor; +pub use swatch_picture::{swatch_reach, swatch_unit}; +pub use swatch_side::SwatchSide; + +use crate::TextureCraftApp; +use crate::color_picker::ColorPick; + +/// A running eyedropper pick's wait for a click outside the app, for the colour bar `bar` +pub struct ScreenPick { + bar: egui::Id, + outcomes: Receiver, + shared: Arc, + /// Whether the app losing the focus ends the pick (not while the desktop's own picker has it) + ends_on_focus_loss: bool, +} + +impl ScreenPick { + fn start(bar: egui::Id, ctx: &egui::Context) -> Self { + let (sender, outcomes) = mpsc::channel(); + let shared = Arc::new(PickShared::default()); + + let waiting = Arc::clone(&shared); + let dpi = window_dpi(ctx); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("eyedropper".into()).spawn(move || wait_for_click(&waiting, sender, ctx, dpi)); + if let Err(error) = spawned { + log::warn!("the eyedropper picks on the model only: {error}"); + } + + ScreenPick { bar, outcomes, shared, ends_on_focus_loss: ends_on_focus_loss() } + } + + /// A pick for `bar` whose click outside the app already ended as `outcome` (tests and agents stand in for the system) + pub fn ended(bar: egui::Id, outcome: PickOutcome) -> Self { + let (sender, outcomes) = mpsc::channel(); + let _ = sender.send(outcome); + ScreenPick { bar, outcomes, shared: Arc::default(), ends_on_focus_loss: true } + } + + /// A pick for `bar` still waiting for its click outside the app (tests stand in for the system) + pub fn waiting(bar: egui::Id) -> Self { + let (_, outcomes) = mpsc::channel(); + ScreenPick { bar, outcomes, shared: Arc::default(), ends_on_focus_loss: true } + } + + /// Tells the waiting thread where the app's windows are and whether the pointer is over one of them + fn share_windows(&self, ctx: &egui::Context) { + let viewports = ctx.input(|input| input.raw.viewports.clone()); + let windows = viewports.values().filter_map(physical_rect).collect(); + self.shared.set_windows(windows); + #[cfg(all(unix, not(target_os = "macos")))] + { + let pointer_inside = viewports.keys().any(|id| ctx.input_for(*id, |input| input.pointer.has_pointer())); + self.shared.set_pointer_outside(!pointer_inside); + } + } +} + +impl Drop for ScreenPick { + fn drop(&mut self) { + self.shared.stop(); + } +} + +/// Starts or ends the wait for a click outside the app with the eyedropper pick, and hands a colour picked there to its bar +pub(crate) fn sync(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(bar) = app.picking_color else { + app.screen_pick = None; + return; + }; + + if app.screen_pick.as_ref().is_none_or(|pick| pick.bar != bar) { + // The last pick stops before the next starts, so its pointer goes back first + drop(app.screen_pick.take()); + app.screen_pick = app.screen_picking.then(|| ScreenPick::start(bar, ctx)); + } + + let Some(pick) = app.screen_pick.as_ref() else { return }; + + pick.share_windows(ctx); + match pick.outcomes.try_recv() { + Ok(PickOutcome::Picked(color)) => { + ColorPick::deliver(ctx, bar, color.map(egui::ecolor::linear_f32_from_gamma_u8)); + app.picking_color = None; + app.screen_pick = None; + } + Ok(PickOutcome::Cancelled) => { + app.picking_color = None; + app.screen_pick = None; + } + + // The pick stays on the model; the finished wait is kept so it does not start again + Ok(PickOutcome::Unavailable) | Err(_) => { + // Another app came forward (Alt+Tab, the Start menu): the pick ends there and the pointer is the user's again + if pick.ends_on_focus_loss && ctx.input(|input| input.viewport().focused) == Some(false) { + app.picking_color = None; + app.screen_pick = None; + } + } + } +} + +/// Whether the app losing the focus ends a pick here (not on Wayland, where the desktop's colour picker takes the focus) +fn ends_on_focus_loss() -> bool { + cfg!(windows) || (cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("WAYLAND_DISPLAY").is_none()) +} + +/// The highest window DPI read, far past any display, so a broken scale cannot size a huge pointer +const MAX_WINDOW_DPI: f32 = 4096.0; + +/// The app window's dots per inch, which size the eyedropper as the system's pointers are sized there +fn window_dpi(ctx: &egui::Context) -> u32 { + let scale = ctx.input(|input| input.viewport().native_pixels_per_point).filter(|scale| scale.is_finite() && *scale > 0.0); + (scale.unwrap_or(1.0) * keeper_args::BASE_DPI as f32).round().clamp(1.0, MAX_WINDOW_DPI) as u32 +} + +/// A window's outer rectangle as `[left, top, right, bottom]` in physical screen pixels, where the system reports one +fn physical_rect(viewport: &egui::ViewportInfo) -> Option<[i32; 4]> { + let rect = viewport.outer_rect?; + let scale = viewport.native_pixels_per_point?; + let edges = [rect.left(), rect.top(), rect.right(), rect.bottom()].map(|edge| edge * scale); + if edges.iter().any(|edge| !edge.is_finite()) { + return None; + } + + Some(edges.map(|edge| edge.round() as i32)) +} + +/// The system's way to read a click outside the app, on the pick's own thread +fn wait_for_click(shared: &Arc, outcomes: Sender, ctx: egui::Context, dpi: u32) { + #[cfg(windows)] + windows_hook::run(shared, outcomes, ctx, dpi); + #[cfg(not(windows))] + let _ = dpi; + + #[cfg(all(unix, not(target_os = "macos")))] + if std::env::var_os("WAYLAND_DISPLAY").is_some() { + portal::run(shared, &outcomes, &ctx); + } else if x11_grab::run(shared, &outcomes, &ctx).is_none() { + let _ = outcomes.send(PickOutcome::Unavailable); + } + + // macOS: reading another app's pixels needs the screen-recording permission; the pick stays on the model + #[cfg(not(any(windows, all(unix, not(target_os = "macos")))))] + { + let _ = (shared, ctx); + let _ = outcomes.send(PickOutcome::Unavailable); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_window_reports_its_rectangle_in_physical_pixels() { + let viewport = egui::ViewportInfo { + outer_rect: Some(egui::Rect::from_min_size(egui::pos2(-960.0, 100.0), egui::vec2(800.0, 600.0))), + native_pixels_per_point: Some(1.5), + ..Default::default() + }; + + assert_eq!(physical_rect(&viewport), Some([-1440, 150, -240, 1050])); + assert_eq!(physical_rect(&egui::ViewportInfo::default()), None, "no position (Wayland): no rectangle"); + } + + #[test] + fn a_click_is_the_apps_own_only_on_one_of_its_windows() { + let windows = [[0, 0, 100, 50], [-300, 0, -100, 200]]; + + assert!(pick_shared::over_windows(&windows, 0, 0)); + assert!(pick_shared::over_windows(&windows, -101, 199)); + assert!(!pick_shared::over_windows(&windows, 100, 10), "the right edge is outside"); + assert!(!pick_shared::over_windows(&windows, 500, 500)); + } +} diff --git a/crates/ui-egui/src/screen_pick/painted_cursor.rs b/crates/ui-egui/src/screen_pick/painted_cursor.rs new file mode 100644 index 00000000..320921b1 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/painted_cursor.rs @@ -0,0 +1,60 @@ +//! The eyedropper pointer over the app's own window: the system's pointer is hidden there and the eyedropper picture is drawn +//! one screen pixel per picture pixel, its hotspot pixel on the screen pixel the pointer is in, with the colour disc beside it + +use super::cursor_texture::CursorTexture; +use super::{SwatchSide, swatch_reach, swatch_unit}; + +/// The pointer cell's size in points (a system pointer's 32 pixels at 100 %) +const CURSOR_POINTS: f32 = 32.0; + +/// Draws the eyedropper in place of the pointer over the app (and, given `area`, inside it), a disc of `swatch` (sRGB) by its tip +pub fn paint(ctx: &egui::Context, area: Option, swatch: Option<[u8; 3]>) { + let Some(pointer) = ctx.pointer_hover_pos().filter(|pointer| area.is_none_or(|area| area.contains(*pointer))) else { return }; + + ctx.set_cursor_icon(egui::CursorIcon::None); + let pixels_per_point = ctx.pixels_per_point(); + let cell = (CURSOR_POINTS * pixels_per_point).round() as u32; + let side = swatch.map(|color| (color, disc_side(ctx.content_rect(), pointer, pixels_per_point, cell))); + let cursor = CursorTexture::for_look(ctx, (cell, side)); + let rect = placement(pointer, pixels_per_point, cursor.size, cursor.hotspot); + + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Debug, egui::Id::unique("eyedropper_cursor"))); + let whole_texture = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)); + painter.image(cursor.texture.id(), rect, whole_texture, egui::Color32::WHITE); +} + +/// Where a `size`-pixel pointer picture goes, in points, so its `hotspot` pixel covers the screen pixel `pointer` is in +pub(crate) fn placement(pointer: egui::Pos2, pixels_per_point: f32, size: u32, hotspot: [u32; 2]) -> egui::Rect { + let pixel = (pointer.to_vec2() * pixels_per_point).floor(); + let min = (pixel - egui::vec2(hotspot[0] as f32, hotspot[1] as f32)) / pixels_per_point; + egui::Rect::from_min_size(min.to_pos2(), egui::Vec2::splat(size as f32 / pixels_per_point)) +} + +/// The side of the tip whose disc stays inside the window `screen` (in points) for a pointer at `pointer` +fn disc_side(screen: egui::Rect, pointer: egui::Pos2, pixels_per_point: f32, cell: u32) -> SwatchSide { + let unit = swatch_unit(cell); + let tip = (pointer.to_vec2() * pixels_per_point).floor() + egui::vec2(0.5, 0.5); + let bounds = [screen.left(), screen.top(), screen.right(), screen.bottom()].map(|edge| edge * pixels_per_point); + SwatchSide::fitting([tip.x, tip.y], unit, swatch_reach(unit), bounds) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::screen_pick::CursorImage; + + #[test] + fn the_hotspot_pixel_covers_the_pixel_the_pointer_is_in() { + for (pointer, pixels_per_point) in [(egui::pos2(100.3, 40.9), 1.0), (egui::pos2(100.3, 40.9), 1.5), (egui::pos2(7.0, 3.25), 2.0)] { + let image = CursorImage::eyedropper((CURSOR_POINTS * pixels_per_point).round() as u32); + let rect = placement(pointer, pixels_per_point, image.size, image.hotspot); + let texel = egui::vec2(1.0, 1.0) / pixels_per_point; + let hot_min = rect.min + egui::vec2(image.hotspot[0] as f32, image.hotspot[1] as f32) * texel; + let hot = egui::Rect::from_min_size(hot_min, texel); + + assert!(hot.contains(pointer), "{pixels_per_point}x: the tip's pixel {hot:?} holds the pointer {pointer:?}"); + let screen_pixel = (hot.min.to_vec2() * pixels_per_point).round(); + assert_eq!(screen_pixel, (pointer.to_vec2() * pixels_per_point).floor(), "{pixels_per_point}x: whole screen pixels"); + } + } +} diff --git a/crates/ui-egui/src/screen_pick/pick_outcome.rs b/crates/ui-egui/src/screen_pick/pick_outcome.rs new file mode 100644 index 00000000..3228e81e --- /dev/null +++ b/crates/ui-egui/src/screen_pick/pick_outcome.rs @@ -0,0 +1,10 @@ +/// How an eyedropper pick outside the app ended +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PickOutcome { + /// The click landed outside the app: the 8-bit sRGB colour of the one screen pixel under it + Picked([u8; 3]), + /// The system picker was dismissed (Escape in it): the pick ends with nothing changed + Cancelled, + /// This system cannot read the screen: the pick stays a pick on the model + Unavailable, +} diff --git a/crates/ui-egui/src/screen_pick/pick_shared.rs b/crates/ui-egui/src/screen_pick/pick_shared.rs new file mode 100644 index 00000000..9fa7a692 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/pick_shared.rs @@ -0,0 +1,53 @@ +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// What the frame loop tells the thread that waits for a click outside the app +#[derive(Default)] +pub(crate) struct PickShared { + /// The pick ended in the app (Escape, a click on the model, its eyedropper again) + stop: AtomicBool, + /// The app's windows as `[left, top, right, bottom]` in physical screen pixels, where clicks stay the app's own + windows: Mutex>, + /// The pointer is over none of the app's windows + #[cfg(all(unix, not(target_os = "macos")))] + pointer_outside: AtomicBool, +} + +impl PickShared { + pub(crate) fn stop(&self) { + self.stop.store(true, Ordering::Relaxed); + } + + #[cfg(any(windows, all(unix, not(target_os = "macos"))))] + pub(crate) fn stopped(&self) -> bool { + self.stop.load(Ordering::Relaxed) + } + + pub(crate) fn set_windows(&self, windows: Vec<[i32; 4]>) { + if let Ok(mut known) = self.windows.lock() { + *known = windows; + } + } + + /// The app's windows, or none while they are unknown (a system without global window positions) + #[cfg(any(windows, all(unix, not(target_os = "macos")), test))] + pub(crate) fn windows(&self) -> Vec<[i32; 4]> { + self.windows.lock().map(|known| known.clone()).unwrap_or_default() + } + + #[cfg(all(unix, not(target_os = "macos")))] + pub(crate) fn set_pointer_outside(&self, outside: bool) { + self.pointer_outside.store(outside, Ordering::Relaxed); + } + + #[cfg(all(unix, not(target_os = "macos")))] + pub(crate) fn pointer_outside(&self) -> bool { + self.pointer_outside.load(Ordering::Relaxed) + } +} + +/// Whether the screen pixel `(x, y)` lies on one of `windows` +#[cfg(any(windows, all(unix, not(target_os = "macos")), test))] +pub(crate) fn over_windows(windows: &[[i32; 4]], x: i32, y: i32) -> bool { + windows.iter().any(|&[left, top, right, bottom]| x >= left && x < right && y >= top && y < bottom) +} diff --git a/crates/ui-egui/src/screen_pick/pixel_layout.rs b/crates/ui-egui/src/screen_pick/pixel_layout.rs new file mode 100644 index 00000000..89e4db61 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/pixel_layout.rs @@ -0,0 +1,70 @@ +/// How the X server lays out one pixel of a `ZPixmap` image +#[derive(Clone, Copy, Debug)] +pub(crate) struct PixelLayout { + pub(crate) bits_per_pixel: u8, + pub(crate) least_significant_first: bool, + /// The red, green and blue masks of the root window's visual + pub(crate) masks: [u32; 3], +} + +impl PixelLayout { + /// The 8-bit colour of the first pixel in `data`, or `None` for a layout other than 24 or 32 bits per pixel + pub(crate) fn decode(&self, data: &[u8]) -> Option<[u8; 3]> { + let bytes = match self.bits_per_pixel { + 24 => 3, + 32 => 4, + _ => return None, + }; + let pixel = data.get(..bytes)?; + let value = if self.least_significant_first { + pixel.iter().rev().fold(0_u32, |value, byte| (value << 8) | u32::from(*byte)) + } else { + pixel.iter().fold(0_u32, |value, byte| (value << 8) | u32::from(*byte)) + }; + Some(self.masks.map(|mask| channel(value, mask))) + } +} + +/// The channel `mask` selects in `value`, scaled to 8 bits +fn channel(value: u32, mask: u32) -> u8 { + if mask == 0 { + return 0; + } + + let shift = mask.trailing_zeros(); + let max = mask >> shift; + let raw = (value & mask) >> shift; + u8::try_from(u64::from(raw) * 255 / u64::from(max)).unwrap_or(u8::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + + const RGB_MASKS: [u32; 3] = [0x00ff_0000, 0x0000_ff00, 0x0000_00ff]; + + #[test] + fn a_32_bit_pixel_reads_in_the_servers_byte_order() { + let little = PixelLayout { bits_per_pixel: 32, least_significant_first: true, masks: RGB_MASKS }; + let big = PixelLayout { least_significant_first: false, ..little }; + + assert_eq!(little.decode(&[0x30, 0x20, 0x10, 0x00]), Some([0x10, 0x20, 0x30])); + assert_eq!(big.decode(&[0x00, 0x10, 0x20, 0x30]), Some([0x10, 0x20, 0x30])); + } + + #[test] + fn narrow_masks_scale_to_8_bits() { + let rgb565 = PixelLayout { bits_per_pixel: 24, least_significant_first: true, masks: [0xf800, 0x07e0, 0x001f] }; + + assert_eq!(rgb565.decode(&[0xff, 0xff, 0x00]), Some([255, 255, 255])); + assert_eq!(rgb565.decode(&[0x1f, 0x00, 0x00]), Some([0, 0, 255])); + } + + #[test] + fn an_unknown_layout_or_short_data_reads_nothing() { + let layout = PixelLayout { bits_per_pixel: 16, least_significant_first: true, masks: RGB_MASKS }; + + assert_eq!(layout.decode(&[0, 0, 0, 0]), None); + assert_eq!(PixelLayout { bits_per_pixel: 32, ..layout }.decode(&[0, 0]), None); + } +} diff --git a/crates/ui-egui/src/screen_pick/portal.rs b/crates/ui-egui/src/screen_pick/portal.rs new file mode 100644 index 00000000..adecf393 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/portal.rs @@ -0,0 +1,94 @@ +//! Wayland: an app cannot read the screen or see clicks on other windows, so once the pointer leaves the app's windows the +//! desktop's own colour picker (the xdg-desktop-portal Screenshot.PickColor call) takes the click and reports the colour + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::mpsc::Sender; +use std::time::Duration; + +use zbus::blocking::{Connection, Proxy}; +use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; + +use super::{PickOutcome, PickShared}; + +/// How often the thread checks whether the pointer has left the app +const POLL: Duration = Duration::from_millis(30); +const PORTAL: &str = "org.freedesktop.portal.Desktop"; +const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; +/// The token that names this app's request, so its answer can be awaited before the call is made +const TOKEN: &str = "texturecraft_eyedropper"; +/// The portal's answer code for a pick the user made +const RESPONSE_SUCCESS: u32 = 0; +/// The portal's answer code for a pick the user cancelled; any other code is the desktop's own failure +const RESPONSE_CANCELLED: u32 = 1; + +/// Waits for the pointer to leave the app's windows, then lets the desktop's picker take one click +pub(super) fn run(shared: &Arc, outcomes: &Sender, ctx: &egui::Context) { + while !shared.pointer_outside() { + if shared.stopped() { + return; + } + + std::thread::sleep(POLL); + } + + // The pick may have ended in the same poll the pointer left: no desktop picker for it + if shared.stopped() { + return; + } + + let outcome = pick_color().unwrap_or(PickOutcome::Unavailable); + let _ = outcomes.send(outcome); + ctx.request_repaint(); +} + +fn pick_color() -> Option { + let connection = Connection::session().ok()?; + let sender = connection.unique_name()?.trim_start_matches(':').replace('.', "_"); + let request_path = format!("{PORTAL_PATH}/request/{sender}/{TOKEN}"); + let request = Proxy::new(&connection, PORTAL, request_path, "org.freedesktop.portal.Request").ok()?; + let mut responses = request.receive_signal("Response").ok()?; + + let screenshot = Proxy::new(&connection, PORTAL, PORTAL_PATH, "org.freedesktop.portal.Screenshot").ok()?; + let options = HashMap::from([("handle_token", Value::from(TOKEN))]); + let _handle: OwnedObjectPath = screenshot.call("PickColor", &("", options)).ok()?; + + let answer = responses.next()?; + let (code, results): (u32, HashMap) = answer.body().deserialize().ok()?; + if let Some(ended) = ended_without_colour(code) { + return Some(ended); + } + + let (red, green, blue): (f64, f64, f64) = results.get("color")?.try_clone().ok()?.try_into().ok()?; + Some(PickOutcome::Picked([red, green, blue].map(to_byte))) +} + +/// How a portal answer of `code` ends the pick when it brings no colour: a cancel ends it, a failure leaves the pick on the model +fn ended_without_colour(code: u32) -> Option { + match code { + RESPONSE_SUCCESS => None, + RESPONSE_CANCELLED => Some(PickOutcome::Cancelled), + _ => Some(PickOutcome::Unavailable), + } +} + +/// A portal colour component (sRGB, 0 to 1) as 8 bits +fn to_byte(component: f64) -> u8 { + if component.is_nan() { + return 0; + } + + (component.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_cancel_code_ends_the_pick_and_a_failure_keeps_it_on_the_model() { + assert_eq!(ended_without_colour(RESPONSE_SUCCESS), None, "a pick goes on to its colour"); + assert_eq!(ended_without_colour(RESPONSE_CANCELLED), Some(PickOutcome::Cancelled)); + assert_eq!(ended_without_colour(2), Some(PickOutcome::Unavailable), "the desktop's own failure"); + } +} diff --git a/crates/ui-egui/src/screen_pick/premultiplied_argb.rs b/crates/ui-egui/src/screen_pick/premultiplied_argb.rs new file mode 100644 index 00000000..81f5604c --- /dev/null +++ b/crates/ui-egui/src/screen_pick/premultiplied_argb.rs @@ -0,0 +1,28 @@ +//! X11: a pointer picture's pixels as the server takes them + +/// Straight-alpha RGBA pixels as the premultiplied 32-bit ARGB a pointer picture is sent in, in the server's byte order +pub(crate) fn premultiplied_argb(rgba: &[u8], least_significant_first: bool) -> Vec { + let mut data = Vec::with_capacity(rgba.len()); + for &[red, green, blue, alpha] in rgba.as_chunks::<4>().0 { + let [red, green, blue] = [red, green, blue].map(|value| u8::try_from(u16::from(value) * u16::from(alpha) / 255).unwrap_or(u8::MAX)); + if least_significant_first { + data.extend_from_slice(&[blue, green, red, alpha]); + } else { + data.extend_from_slice(&[alpha, red, green, blue]); + } + } + data +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pointer_pixel_is_sent_premultiplied_in_the_servers_byte_order() { + let rgba = [255, 128, 0, 128, 10, 20, 30, 0]; + + assert_eq!(premultiplied_argb(&rgba, true), vec![0, 64, 128, 128, 0, 0, 0, 0]); + assert_eq!(premultiplied_argb(&rgba, false), vec![128, 128, 64, 0, 0, 0, 0, 0]); + } +} diff --git a/crates/ui-egui/src/screen_pick/release_wait.rs b/crates/ui-egui/src/screen_pick/release_wait.rs new file mode 100644 index 00000000..2bf02689 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/release_wait.rs @@ -0,0 +1,55 @@ +//! Windows: when the wait for the release of the press a pick took ends, decided apart from the system's calls + +use std::time::{Duration, Instant}; + +/// How long a release is waited for when the button state never showed the taken press down: longer than any click +const UNSEEN_PRESS_GRACE: Duration = Duration::from_secs(1); + +/// The wait for the release of the press a pick took, so the window under it sees no half click +#[derive(Clone, Copy, Debug)] +pub(super) struct ReleaseWait { + pressed_at: Instant, + /// The system's button state has shown the button down since the press + seen_down: bool, +} + +impl ReleaseWait { + /// The wait for the release of a press taken at `pressed_at` + pub(super) fn new(pressed_at: Instant) -> Self { + ReleaseWait { pressed_at, seen_down: false } + } + + /// Whether the wait is over at `now` with the button physically `button_down` (a removed hook never sees the release) + pub(super) fn over(&mut self, button_down: bool, now: Instant) -> bool { + if button_down { + self.seen_down = true; + return false; + } + + // A taken press may never reach the button state: the button reads up from the start + self.seen_down || now.saturating_duration_since(self.pressed_at) >= UNSEEN_PRESS_GRACE + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_release_the_hook_never_saw_ends_the_wait_once_the_button_is_up() { + let pressed_at = Instant::now(); + let mut wait = ReleaseWait::new(pressed_at); + + assert!(!wait.over(true, pressed_at), "the button is still down: the release is still to come"); + assert!(wait.over(false, pressed_at), "the button is up again: its release went past a removed hook"); + } + + #[test] + fn a_press_the_button_state_never_showed_ends_the_wait_after_a_grace() { + let pressed_at = Instant::now(); + let mut wait = ReleaseWait::new(pressed_at); + + assert!(!wait.over(false, pressed_at), "the taken press may not reach the button state: its release is still to come"); + assert!(wait.over(false, pressed_at + UNSEEN_PRESS_GRACE), "the wait never outlasts the grace"); + } +} diff --git a/crates/ui-egui/src/screen_pick/shown_disc.rs b/crates/ui-egui/src/screen_pick/shown_disc.rs new file mode 100644 index 00000000..a7d645af --- /dev/null +++ b/crates/ui-egui/src/screen_pick/shown_disc.rs @@ -0,0 +1,9 @@ +use x11rb::protocol::xproto::Cursor; + +use super::SwatchSide; + +/// The disc the X grab's pointer shows now and that pointer +pub(super) struct ShownDisc { + pub(super) look: ([u8; 3], SwatchSide), + pub(super) pointer: Cursor, +} diff --git a/crates/ui-egui/src/screen_pick/swatch_color.rs b/crates/ui-egui/src/screen_pick/swatch_color.rs new file mode 100644 index 00000000..238145b4 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/swatch_color.rs @@ -0,0 +1,49 @@ +/// The eyedropper disc's colour over the app: what a click there leaves the bar holding (the model under it, else the bar's own) +pub struct SwatchColor; + +/// Where this frame's colour on the model is kept, with the pass it was read in +const MODEL_KEY: &str = "eyedropper_swatch_model"; +/// Where the waiting bar's colour is kept +const BAR_KEY: &str = "eyedropper_swatch_bar"; + +impl SwatchColor { + /// The model's base colour (linear) under the pointer this frame + pub(crate) fn over_model(ctx: &egui::Context, linear: [f32; 3]) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(MODEL_KEY), (pass, linear))); + } + + /// The colour (linear) of the bar whose eyedropper waits + pub(crate) fn of_bar(ctx: &egui::Context, linear: [f32; 3]) { + ctx.data_mut(|data| data.insert_temp(egui::Id::unique(BAR_KEY), linear)); + } + + /// The disc's colour this frame as 8-bit sRGB, none before the waiting bar has been drawn + pub(crate) fn shown(ctx: &egui::Context) -> Option<[u8; 3]> { + let pass = ctx.cumulative_pass_nr(); + let model = ctx.data(|data| data.get_temp::<(u64, [f32; 3])>(egui::Id::unique(MODEL_KEY))); + let bar = ctx.data(|data| data.get_temp::<[f32; 3]>(egui::Id::unique(BAR_KEY))); + chosen(model, pass, bar) + } +} + +/// The model's colour if it was read in pass `pass`, else the bar's, as 8-bit sRGB +fn chosen(model: Option<(u64, [f32; 3])>, pass: u64, bar: Option<[f32; 3]>) -> Option<[u8; 3]> { + let linear = model.filter(|(read, _)| *read == pass).map(|(_, linear)| linear).or(bar)?; + Some(linear.map(egui::ecolor::gamma_u8_from_linear_f32)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_disc_shows_the_model_under_the_pointer_and_else_the_bars_own_colour() { + let (red, blue) = ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]); + + assert_eq!(chosen(None, 3, None), None, "nothing before the bar is drawn"); + assert_eq!(chosen(Some((3, blue)), 3, Some(red)), Some([0, 0, 255]), "the model under the pointer"); + assert_eq!(chosen(Some((2, blue)), 3, Some(red)), Some([255, 0, 0]), "off the model: the bar's own colour, a click there keeps it"); + assert_eq!(chosen(None, 3, Some([0.5; 3])), Some([188; 3]), "shown as the screen shows it (sRGB)"); + } +} diff --git a/crates/ui-egui/src/screen_pick/swatch_picture.rs b/crates/ui-egui/src/screen_pick/swatch_picture.rs new file mode 100644 index 00000000..b9a300d7 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/swatch_picture.rs @@ -0,0 +1,149 @@ +//! The eyedropper pointer's colour disc, drawn beside the pipette's tip by `CursorImage::eyedropper_with_swatch`: a disc of the +//! colour under the tip in a crisp white outline and a faint dark outer ring, so it reads on white and on black alike; one +//! picture, so the disc moves with the pointer itself and never lags or flickers + +use super::CursorImage; +use crate::color_picker::component_byte; + +/// The pointer cell the disc's sizes are given for (a system pointer at 100 %), in pixels +const NOMINAL_CELL_PX: f32 = 32.0; +/// The coloured disc's radius at the nominal cell (the disc with its outline is 40 pixels across) +const FILL_RADIUS_PX: f32 = 18.0; +/// The white outline's width at the nominal cell +const OUTLINE_PX: f32 = 2.0; +/// The dark outer ring's width at the nominal cell +const RING_PX: f32 = 1.0; +/// The least the ring is wide in pixels, so a small pointer's disc still has its edge on white +const MIN_RING_PX: f32 = 1.0; +/// How dark the outer ring is: faint, only enough to edge the white outline on a white ground +const RING_ALPHA: f32 = 0.45; + +/// Pixels to a nominal pointer pixel for a `cell`-pixel pointer +pub fn swatch_unit(cell: u32) -> f32 { + CursorImage::clamped_size(cell) as f32 / NOMINAL_CELL_PX +} + +/// How far the disc reaches from its centre with its outline and ring, in pixels, `unit` pixels to a nominal pixel +pub fn swatch_reach(unit: f32) -> f32 { + (FILL_RADIUS_PX + OUTLINE_PX + RING_PX) * unit +} + +/// The pipette's pixel at `(x, y)` of its cell, clear outside it +pub(super) fn pipette_pixel(pipette: &CursorImage, x: f32, y: f32) -> [u8; 4] { + if x < 0.0 || y < 0.0 { + return [0; 4]; + } + + let (x, y) = (x as u32, y as u32); + if x >= pipette.size || y >= pipette.size { + return [0; 4]; + } + + let index = ((y * pipette.size + x) * 4) as usize; + pipette.rgba.get(index..index + 4).and_then(|pixel| pixel.try_into().ok()).unwrap_or([0; 4]) +} + +/// The disc's straight-alpha pixel `distance` pixels from its centre: the colour, the white outline round it, the faint ring +pub(super) fn disc_pixel(distance: f32, unit: f32, color: [u8; 3]) -> [u8; 4] { + let fill_radius = FILL_RADIUS_PX * unit; + let outline_radius = fill_radius + OUTLINE_PX * unit; + let ring_radius = outline_radius + (RING_PX * unit).max(MIN_RING_PX); + + // Each edge's coverage over the pixel's width, for smooth edges + let coverage = |radius: f32| (radius - distance + 0.5).clamp(0.0, 1.0); + + let ring = [0, 0, 0, component_byte(RING_ALPHA * coverage(ring_radius))]; + let outline = over([u8::MAX, u8::MAX, u8::MAX, component_byte(coverage(outline_radius))], ring); + over([color[0], color[1], color[2], component_byte(coverage(fill_radius))], outline) +} + +/// `top` over `bottom`, both straight-alpha RGBA +pub(super) fn over(top: [u8; 4], bottom: [u8; 4]) -> [u8; 4] { + let top_alpha = f32::from(top[3]) / 255.0; + let bottom_alpha = f32::from(bottom[3]) / 255.0 * (1.0 - top_alpha); + let alpha = top_alpha + bottom_alpha; + if alpha <= 0.0 { + return [0; 4]; + } + + let mix = |channel: usize| component_byte((f32::from(top[channel]) * top_alpha + f32::from(bottom[channel]) * bottom_alpha) / alpha / 255.0); + [mix(0), mix(1), mix(2), component_byte(alpha)] +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::screen_pick::SwatchSide; + use crate::screen_pick::cursor_image::MAX_PICTURE_PX; + + fn pixel(image: &CursorImage, x: u32, y: u32) -> [u8; 4] { + pipette_pixel(image, x as f32, y as f32) + } + + /// The disc's centre in `image` for `side`, from its hotspot + fn disc_center(image: &CursorImage, side: SwatchSide, unit: f32) -> [u32; 2] { + let [dx, dy] = side.offset(); + [(image.hotspot[0] as f32 + 0.5 + dx * unit) as u32, (image.hotspot[1] as f32 + 0.5 + dy * unit) as u32] + } + + #[test] + fn the_disc_shows_the_colour_in_a_white_outline_and_a_faint_dark_ring() { + let color = [200, 40, 90]; + let image = CursorImage::eyedropper_with_swatch(32, color, SwatchSide::BelowRight); + let [cx, cy] = disc_center(&image, SwatchSide::BelowRight, 1.0); + + assert_eq!(pixel(&image, cx, cy), [200, 40, 90, 255], "the colour fills the disc"); + assert_eq!(pixel(&image, cx + 19, cy), [255, 255, 255, 255], "a white outline round it"); + let ring = pixel(&image, cx + 21, cy); + assert!(ring[0] < 64 && ring[3] > 30 && ring[3] < 128, "a faint dark ring outside the outline: {ring:?}"); + assert_eq!(pixel(&image, cx + 22, cy)[3], 0, "and nothing past it"); + let blended = pixel(&image, cx + 18, cy); + assert!(blended[1] > 40 && blended[1] < 255 && blended[3] == 255, "the colour blends into the outline: {blended:?}"); + } + + #[test] + fn the_disc_is_40_pixels_across_at_100_percent_and_scales_with_the_pointer() { + for (cell, unit) in [(32, 1.0), (48, 1.5), (64, 2.0)] { + let image = CursorImage::eyedropper_with_swatch(cell, [10, 200, 10], SwatchSide::BelowRight); + let [cx, cy] = disc_center(&image, SwatchSide::BelowRight, unit); + + // The faint ring stays below this alpha; the outline and the colour reach it + let across = (0..image.size).filter(|&x| pixel(&image, x, cy)[3] >= 160).count(); + + let expected = 40.0 * unit; + assert!((across as f32 - expected).abs() <= 1.0, "{cell}: {across} px across, want {expected}"); + assert_eq!(pixel(&image, cx, cy)[1], 200); + } + } + + #[test] + fn the_disc_covers_neither_the_picked_pixel_nor_the_pipette_on_any_side() { + for cell in [24, 32, 48, 64] { + let plain = CursorImage::eyedropper(cell); + let unit = swatch_unit(cell); + for side in SwatchSide::ALL { + let image = CursorImage::eyedropper_with_swatch(cell, [255, 0, 255], side); + let shift = [image.hotspot[0] - plain.hotspot[0], image.hotspot[1] - plain.hotspot[1]]; + let [cx, cy] = disc_center(&image, side, unit); + let reach = swatch_reach(unit); + + for y in 0..image.size { + for x in 0..image.size { + let in_disc = ((x as f32 + 0.5 - cx as f32).powi(2) + (y as f32 + 0.5 - cy as f32).powi(2)).sqrt() <= reach + 1.0; + let pipette_ink = x >= shift[0] && y >= shift[1] && plain.alpha(x - shift[0], y - shift[1]).is_some_and(|alpha| alpha > 0); + assert!(!(in_disc && pipette_ink), "{cell} {side:?}: the disc covers the pipette at ({x}, {y})"); + } + } + assert_eq!(pixel(&image, image.hotspot[0], image.hotspot[1]), pixel(&plain, plain.hotspot[0], plain.hotspot[1]), "{cell} {side:?}"); + } + } + } + + #[test] + fn a_huge_pointer_still_fits_the_largest_picture() { + let image = CursorImage::eyedropper_with_swatch(256, [1, 2, 3], SwatchSide::AboveRight); + + assert!(image.size <= MAX_PICTURE_PX, "{}", image.size); + assert!(image.alpha(image.hotspot[0], image.hotspot[1]).is_some_and(|alpha| alpha > 0), "the hotspot is still the tip"); + } +} diff --git a/crates/ui-egui/src/screen_pick/swatch_side.rs b/crates/ui-egui/src/screen_pick/swatch_side.rs new file mode 100644 index 00000000..1159f150 --- /dev/null +++ b/crates/ui-egui/src/screen_pick/swatch_side.rs @@ -0,0 +1,66 @@ +/// Where the eyedropper's colour disc sits beside the pointer's tip: below right unless a screen edge would cut it +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SwatchSide { + BelowRight, + BelowLeft, + AboveLeft, + /// Past the pipette's bulb, so the disc never covers the pipette (only in a bottom-left corner) + AboveRight, +} + +/// The distance from the tip to the disc's centre at a 32-pixel pointer, in pixels: clear of the picked pixel and the pipette +const DISC_OFFSET_PX: f32 = 22.0; +/// How far right of the tip the disc's centre sits above the pipette, clear of its bulb +const PAST_BULB_PX: f32 = 44.0; + +impl SwatchSide { + /// Every side, in the order tried: the pipette points up right from its tip, so the disc moves round it the other way + pub(crate) const ALL: [SwatchSide; 4] = [SwatchSide::BelowRight, SwatchSide::BelowLeft, SwatchSide::AboveLeft, SwatchSide::AboveRight]; + + /// The disc's centre from the tip's pixel centre at a 32-pixel pointer, in pixels (y down) + pub fn offset(self) -> [f32; 2] { + match self { + SwatchSide::BelowRight => [DISC_OFFSET_PX, DISC_OFFSET_PX], + SwatchSide::BelowLeft => [-DISC_OFFSET_PX, DISC_OFFSET_PX], + SwatchSide::AboveLeft => [-DISC_OFFSET_PX, -DISC_OFFSET_PX], + SwatchSide::AboveRight => [PAST_BULB_PX, -DISC_OFFSET_PX], + } + } + + /// The first side whose disc (`reach` px, `unit` px per nominal px) by `tip` stays in `bounds` (left, top, right, bottom) + pub fn fitting(tip: [f32; 2], unit: f32, reach: f32, bounds: [f32; 4]) -> Self { + let [left, top, right, bottom] = bounds; + let fits = |side: &SwatchSide| { + let [dx, dy] = side.offset(); + let [x, y] = [tip[0] + dx * unit, tip[1] + dy * unit]; + x - reach >= left && x + reach <= right && y - reach >= top && y + reach <= bottom + }; + Self::ALL.into_iter().find(fits).unwrap_or(SwatchSide::BelowRight) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SCREEN: [f32; 4] = [0.0, 0.0, 1920.0, 1080.0]; + + #[test] + fn the_disc_flips_away_from_the_edge_it_would_cross() { + let reach = 21.0; + + assert_eq!(SwatchSide::fitting([900.0, 500.0], 1.0, reach, SCREEN), SwatchSide::BelowRight); + assert_eq!(SwatchSide::fitting([1900.0, 500.0], 1.0, reach, SCREEN), SwatchSide::BelowLeft, "the right edge"); + assert_eq!(SwatchSide::fitting([900.0, 1070.0], 1.0, reach, SCREEN), SwatchSide::AboveLeft, "the bottom edge"); + assert_eq!(SwatchSide::fitting([1915.0, 1075.0], 1.0, reach, SCREEN), SwatchSide::AboveLeft, "the bottom-right corner"); + assert_eq!(SwatchSide::fitting([5.0, 1075.0], 1.0, reach, SCREEN), SwatchSide::AboveRight, "the bottom-left corner"); + assert_eq!(SwatchSide::fitting([900.0, 1050.0], 2.0, reach * 2.0, SCREEN), SwatchSide::AboveLeft, "a bigger pointer flips sooner"); + } + + #[test] + fn a_monitor_left_of_the_main_one_has_its_own_edges() { + let left_monitor = [-1280.0, 0.0, 0.0, 1024.0]; + + assert_eq!(SwatchSide::fitting([-10.0, 300.0], 1.0, 21.0, left_monitor), SwatchSide::BelowLeft); + } +} diff --git a/crates/ui-egui/src/screen_pick/windows_hook.rs b/crates/ui-egui/src/screen_pick/windows_hook.rs new file mode 100644 index 00000000..83bf44eb --- /dev/null +++ b/crates/ui-egui/src/screen_pick/windows_hook.rs @@ -0,0 +1,189 @@ +//! Windows: a low-level mouse hook on its own thread takes a left click outside the app's windows (the click never reaches the +//! window under it), and the thread then reads the one pixel under it from the desktop through GDI; clicks on the app's own +//! windows pass on. The system pointer is the eyedropper with its colour disc until the wait ends + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::Sender; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Instant; + +use winsafe::prelude::Handle; +use winsafe::{HHOOK, HINSTANCE, HWND, MSG, POINT, co}; + +use super::eyedropper_pointer::EyedropperPointer; +use super::hook_state::HookState; +use super::live_swatch::LiveSwatch; +use super::pick_shared::over_windows; +use super::release_wait::ReleaseWait; +use super::{PickOutcome, PickShared}; + +/// How often the hook thread wakes to see whether the pick ended in the app, in milliseconds +const STOP_CHECK_MS: u32 = 50; +/// The id asked for the stop-check timer (a thread timer gets its id from the system, which returns it) +const STOP_CHECK_TIMER_ID: usize = 1; + +static HOOK: Mutex> = Mutex::new(None); +static GENERATION: AtomicU64 = AtomicU64::new(0); +/// Held from showing the eyedropper until the user's pointers are back: a pick's keeper never copies the last one's eyedropper +static ONE_POINTER_KEEPER: Mutex<()> = Mutex::new(()); + +/// Waits on this thread for a left click outside the app until it lands or `shared` stops the pick (`dpi` sizes the pointer) +pub(super) fn run(shared: &Arc, outcomes: Sender, ctx: egui::Context, dpi: u32) { + // Taken before this pick's state goes in: the last pick's hook reports to its own state until it is gone + let keeper_turn = ONE_POINTER_KEEPER.lock().unwrap_or_else(PoisonError::into_inner); + + let unavailable = outcomes.clone(); + let generation = GENERATION.fetch_add(1, Ordering::Relaxed); + if let Ok(mut hook) = HOOK.lock() { + *hook = Some(HookState::new(generation, Arc::clone(shared), outcomes, ctx.clone())); + } + + // A pick the app ended while the last one was finishing shows no pointer + if shared.stopped() { + clear_state(generation); + return; + } + + // Before the hook: while it is in place this thread must keep reading messages, or every mouse move on the desktop stalls + let pointer = EyedropperPointer::show(dpi); + let Ok(module) = HINSTANCE::GetModuleHandle(None) else { return finish_unavailable(generation, &unavailable, &ctx) }; + let Ok(mut hook) = HHOOK::SetWindowsHookEx(co::WH::MOUSE_LL, mouse_hook, Some(&module), None) else { + return finish_unavailable(generation, &unavailable, &ctx); + }; + + // A thread timer wakes GetMessage so the loop sees a stop and a taken press; the hook procedure runs inside GetMessage + let Ok(timer) = HWND::NULL.SetTimer(STOP_CHECK_TIMER_ID, STOP_CHECK_MS, None) else { + // Without it a stop in the app would leave the hook in place until the next click + let _ = hook.UnhookWindowsHookEx(); + return finish_unavailable(generation, &unavailable, &ctx); + }; + + let mut message = MSG::default(); + + // The disc follows on a thread of its own: this one must answer the hook at once, or every mouse move stalls + let disc = pointer.as_ref().map(|pointer| (pointer.shown_event.clone(), pointer.cell)); + std::thread::scope(|scope| { + if let Some((shown_event, cell)) = &disc { + let follow = std::thread::Builder::new().name("eyedropper disc".into()); + let _ = follow.spawn_scoped(scope, || LiveSwatch::follow(shown_event, *cell, shared, generation)); + } + while waiting(shared, generation) && matches!(winsafe::GetMessage(&mut message, None, 0, 0), Ok(true)) { + deliver_pick(generation); + } + + // Unhooked before the scope joins the disc thread: no message is read from here on, and the desktop's mouse waits on a hook + let _ = hook.UnhookWindowsHookEx(); + let _ = HWND::NULL.KillTimer(timer); + + // A press and its release can both come in one wait for a message; the state's end stops the disc thread too + deliver_pick(generation); + clear_state(generation); + }); + + // The user's own pointers are back before the next pick's keeper may start + drop(pointer); + drop(keeper_turn); +} + +/// Ends pick `generation` where no hook can be set: the pick stays on the model +fn finish_unavailable(generation: u64, outcomes: &Sender, ctx: &egui::Context) { + clear_state(generation); + let _ = outcomes.send(PickOutcome::Unavailable); + ctx.request_repaint(); +} + +/// Takes pick `generation`'s state away, if the hook still holds it +fn clear_state(generation: u64) { + if let Ok(mut hook) = HOOK.lock() + && hook.as_ref().is_some_and(|state| state.generation == generation) + { + *hook = None; + } +} + +/// Reads and sends the pixel under the press pick `generation` took, once, out of the hook procedure and its lock +fn deliver_pick(generation: u64) { + let Some((point, outcomes, ctx)) = take_pending_pick(generation) else { return }; + + let outcome = screen_pixel(point).map_or(PickOutcome::Unavailable, PickOutcome::Picked); + let _ = outcomes.send(outcome); + ctx.request_repaint(); +} + +/// The press pick `generation` took and not yet read, with where to send its colour +fn take_pending_pick(generation: u64) -> Option<(POINT, Sender, egui::Context)> { + let mut hook = HOOK.lock().ok()?; + let state = hook.as_mut().filter(|state| state.generation == generation)?; + let point = state.pending_pick.take()?; + Some((point, state.outcomes.clone(), state.ctx.clone())) +} + +/// Whether pick `generation` still waits: for its click until the app ends the pick, then for the release of the press it took +pub(super) fn waiting(shared: &PickShared, generation: u64) -> bool { + let Ok(mut hook) = HOOK.lock() else { return false }; + let Some(state) = hook.as_mut().filter(|state| state.generation == generation) else { return false }; + + // A hook the system removed never sees the release: the button being up ends that wait + if state.release_wait.as_mut().is_some_and(|release_wait| release_wait.over(pick_button_down(), Instant::now())) { + state.release_wait = None; + } + + state.release_wait.is_some() || (!state.done && !shared.stopped()) +} + +/// Whether the button that sends left clicks is physically down (the system reports the physical buttons, swapped or not) +fn pick_button_down() -> bool { + let button = if winsafe::GetSystemMetrics(co::SM::SWAPBUTTON) != 0 { co::VK::RBUTTON } else { co::VK::LBUTTON }; + winsafe::GetAsyncKeyState(button) +} + +extern "system" fn mouse_hook(code: i32, wparam: usize, lparam: isize) -> isize { + // A negative code must go straight to the next hook + if code >= 0 && take(wparam) { + return 1; + } + + winsafe::CallNextHookEx(code, wparam, lparam) +} + +/// Whether the mouse message `message` is the pick's own: a left press outside the app (noted, then taken) or its release +fn take(message: usize) -> bool { + let Ok(mut hook) = HOOK.lock() else { return false }; + let Some(state) = hook.as_mut() else { return false }; + + let message = u32::try_from(message).unwrap_or_default(); + if message == co::WM::LBUTTONUP.raw() && state.release_wait.is_some() { + state.release_wait = None; + return true; + } + + if message != co::WM::LBUTTONDOWN.raw() || state.done { + return false; + } + + let Ok(point) = winsafe::GetCursorPos() else { return false }; + if over_own_window(point) || over_windows(&state.shared.windows(), point.x, point.y) { + return false; + } + + // Only noted here: the system removes a hook that answers too slowly, so the pixel is read after this returns + state.pending_pick = Some(point); + state.release_wait = Some(ReleaseWait::new(Instant::now())); + state.done = true; + true +} + +/// Whether the window under `point` belongs to this process (the app's main window, a floating panel, a dialog) +pub(super) fn over_own_window(point: POINT) -> bool { + HWND::WindowFromPoint(point).is_some_and(|window| window.GetWindowThreadProcessId().1 == winsafe::GetCurrentProcessId()) +} + +/// The colour of the one desktop pixel at `point` (physical pixels across every monitor: the app is per-monitor DPI aware) +pub(super) fn screen_pixel(point: POINT) -> Option<[u8; 3]> { + let monitor = xcap::Monitor::from_point(point.x, point.y).ok()?; + let x = u32::try_from(point.x.checked_sub(monitor.x().ok()?)?).ok()?; + let y = u32::try_from(point.y.checked_sub(monitor.y().ok()?)?).ok()?; + let pixel = monitor.capture_region(x, y, 1, 1).ok()?; + let [red, green, blue, _] = pixel.get_pixel_checked(0, 0)?.0; + Some([red, green, blue]) +} diff --git a/crates/ui-egui/src/screen_pick/x11_grab.rs b/crates/ui-egui/src/screen_pick/x11_grab.rs new file mode 100644 index 00000000..664b8e8e --- /dev/null +++ b/crates/ui-egui/src/screen_pick/x11_grab.rs @@ -0,0 +1,194 @@ +//! X11: while the pointer is off the app's windows the pointer is grabbed, so a left click there comes to the app instead of the +//! window under it, and the one root-window pixel under it is read; over the app's windows the grab lets go and clicks stay the app's; +//! the grab shows the eyedropper pointer, so the pointer is the eyedropper over every other window too, with a disc of the one +//! root-window pixel under its tip, read again each poll and swapped in only when its colour or side changed + +use std::sync::Arc; +use std::sync::mpsc::Sender; +use std::time::Duration; + +use x11rb::connection::Connection; +use x11rb::protocol::Event; +use x11rb::protocol::render::{ConnectionExt as _, CreatePictureAux, PictType, Pictformat}; +use x11rb::protocol::xproto::{ConnectionExt, CreateGCAux, Cursor, EventMask, GrabMode, GrabStatus, ImageFormat, ImageOrder, Window}; +use x11rb::rust_connection::RustConnection; + +use super::pick_shared::over_windows; +use super::pixel_layout::PixelLayout; +use super::premultiplied_argb::premultiplied_argb; +use super::shown_disc::ShownDisc; +use super::{CursorImage, PickOutcome, PickShared, SwatchSide, swatch_reach, swatch_unit}; + +/// How often the pointer's place is checked against the app's windows +const POLL: Duration = Duration::from_millis(15); +/// The X pointer button a left click presses +const LEFT_BUTTON: u8 = 1; +/// The pointer size where the desktop names none (`XCURSOR_SIZE`), in pixels +const DEFAULT_POINTER_PX: u32 = 24; +/// The largest pointer sent in one request, in pixels +const MAX_POINTER_PX: u32 = 64; +/// The colour depth of a pointer picture with alpha +const ARGB_DEPTH: u8 = 32; +/// That format's alpha, red, green and blue shifts (8 bits each, alpha highest) and each one's mask +const ARGB_SHIFTS: [u16; 4] = [24, 16, 8, 0]; +const CHANNEL_MASK: u16 = 0xff; +/// The RENDER extension version that brought coloured pointers (`CreateCursor`), as major and minor +const RENDER_CURSOR_VERSION: (u32, u32) = (0, 5); + +/// Waits for a left click off the app's windows until it lands or `shared` stops the pick; `None` when there is no X server +pub(super) fn run(shared: &Arc, outcomes: &Sender, ctx: &egui::Context) -> Option<()> { + let (connection, screen) = x11rb::connect(None).ok()?; + let root_screen = connection.setup().roots.get(screen)?; + let (root, root_size) = (root_screen.root, [root_screen.width_in_pixels, root_screen.height_in_pixels]); + let layout = pixel_layout(&connection, screen)?; + let argb = argb_format(&connection); + let cell = pointer_px(); + let pointer_shape = argb.and_then(|argb| make_pointer(&connection, root, argb, &CursorImage::eyedropper(cell))).unwrap_or(x11rb::NONE); + + let mut disc: Option = None; + let mut grabbed = false; + let mut pressed = false; + while pressed || !shared.stopped() { + // Held off the app's windows and while the taken press is down; a failed query returns, and the closed connection ends the grab + let pointer = connection.query_pointer(root).ok()?.reply().ok()?; + let windows = shared.windows(); + let outside = !windows.is_empty() && !over_windows(&windows, pointer.root_x.into(), pointer.root_y.into()); + if outside && !grabbed && !shared.stopped() { + grabbed = grab(&connection, root, disc.as_ref().map_or(pointer_shape, |disc| disc.pointer)); + } else if !outside && grabbed && !pressed { + grabbed = !ungrab(&connection); + } + + // The grab's pointer shows the pixel under its tip + if grabbed + && let Some(argb) = argb + && let Some(color) = root_pixel(&connection, root, layout, pointer.root_x, pointer.root_y) + { + let tip = [f32::from(pointer.root_x) + 0.5, f32::from(pointer.root_y) + 0.5]; + let unit = swatch_unit(cell); + let side = SwatchSide::fitting(tip, unit, swatch_reach(unit), [0.0, 0.0, f32::from(root_size[0]), f32::from(root_size[1])]); + follow(&connection, root, argb, cell, (color, side), &mut disc); + } + + while let Ok(Some(event)) = connection.poll_for_event() { + match event { + Event::ButtonPress(press) if grabbed && press.detail == LEFT_BUTTON && !pressed => { + let picked = root_pixel(&connection, root, layout, press.root_x, press.root_y); + let _ = outcomes.send(picked.map_or(PickOutcome::Unavailable, PickOutcome::Picked)); + ctx.request_repaint(); + pressed = true; + } + Event::ButtonRelease(release) if pressed && release.detail == LEFT_BUTTON => { + ungrab(&connection); + return Some(()); + } + _ => {} + } + } + + std::thread::sleep(POLL); + } + + if grabbed { + ungrab(&connection); + } + Some(()) +} + +/// Shows `look` in the held grab's pointer when it differs from the disc shown now, freeing the pointer it replaces +fn follow(connection: &RustConnection, root: Window, argb: Pictformat, cell: u32, look: ([u8; 3], SwatchSide), disc: &mut Option) { + if disc.as_ref().is_some_and(|disc| disc.look == look) { + return; + } + + let Some(pointer) = make_pointer(connection, root, argb, &CursorImage::eyedropper_with_swatch(cell, look.0, look.1)) else { return }; + + let _ = connection.change_active_pointer_grab(pointer, x11rb::CURRENT_TIME, grab_mask()); + if let Some(old) = disc.replace(ShownDisc { look, pointer }) { + let _ = connection.free_cursor(old.pointer); + } + let _ = connection.flush(); +} + +/// The pointer events a grab takes +fn grab_mask() -> EventMask { + EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE +} + +/// The desktop's pointer size (`XCURSOR_SIZE`), in pixels +fn pointer_px() -> u32 { + let size = std::env::var("XCURSOR_SIZE").ok().and_then(|size| size.trim().parse().ok()).unwrap_or(DEFAULT_POINTER_PX); + size.min(MAX_POINTER_PX) +} + +/// Takes the pointer, showing `pointer_shape` over every window while it is held +fn grab(connection: &RustConnection, root: Window, pointer_shape: Cursor) -> bool { + let Ok(cookie) = connection.grab_pointer(false, root, grab_mask(), GrabMode::ASYNC, GrabMode::ASYNC, x11rb::NONE, pointer_shape, x11rb::CURRENT_TIME) + else { + return false; + }; + + cookie.reply().is_ok_and(|reply| reply.status == GrabStatus::SUCCESS) +} + +/// Lets go of the pointer; whether the server took the request +fn ungrab(connection: &RustConnection) -> bool { + connection.ungrab_pointer(x11rb::CURRENT_TIME).is_ok() && connection.flush().is_ok() +} + +/// The server's 32-bit picture format with alpha that coloured pointers are made from, where it has one +fn argb_format(connection: &RustConnection) -> Option { + connection.render_query_version(RENDER_CURSOR_VERSION.0, RENDER_CURSOR_VERSION.1).ok()?.reply().ok()?; + let formats = connection.render_query_pict_formats().ok()?.reply().ok()?; + let argb = formats.formats.iter().find(|format| { + let direct = format.direct; + format.type_ == PictType::DIRECT + && format.depth == ARGB_DEPTH + && [direct.alpha_shift, direct.red_shift, direct.green_shift, direct.blue_shift] == ARGB_SHIFTS + && [direct.alpha_mask, direct.red_mask, direct.green_mask, direct.blue_mask] == [CHANNEL_MASK; 4] + })?; + Some(argb.id) +} + +/// `image` as an X pointer with its hotspot, where the server can show one (freed with the connection) +fn make_pointer(connection: &RustConnection, root: Window, argb: Pictformat, image: &CursorImage) -> Option { + let side = u16::try_from(image.size).ok()?; + let [hot_x, hot_y] = image.hotspot.map(|edge| u16::try_from(edge).unwrap_or_default()); + let least_significant_first = connection.setup().image_byte_order == ImageOrder::LSB_FIRST; + + let pixmap = connection.generate_id().ok()?; + connection.create_pixmap(ARGB_DEPTH, pixmap, root, side, side).ok()?; + let gc = connection.generate_id().ok()?; + connection.create_gc(gc, pixmap, &CreateGCAux::new()).ok()?; + let data = premultiplied_argb(&image.rgba, least_significant_first); + connection.put_image(ImageFormat::Z_PIXMAP, pixmap, gc, side, side, 0, 0, 0, ARGB_DEPTH, &data).ok()?; + let picture = connection.generate_id().ok()?; + connection.render_create_picture(picture, pixmap, argb, &CreatePictureAux::new()).ok()?; + let cursor = connection.generate_id().ok()?; + + // Checked: a pointer the server refused would make every grab fail + let made = connection.render_create_cursor(cursor, picture, hot_x, hot_y).ok()?.check().is_ok(); + let _ = connection.render_free_picture(picture); + let _ = connection.free_gc(gc); + let _ = connection.free_pixmap(pixmap); + made.then_some(cursor) +} + +/// How the root window's pixels are laid out on `screen` +fn pixel_layout(connection: &RustConnection, screen: usize) -> Option { + let setup = connection.setup(); + let root = setup.roots.get(screen)?; + let format = setup.pixmap_formats.iter().find(|format| format.depth == root.root_depth)?; + let visual = root.allowed_depths.iter().flat_map(|depth| depth.visuals.iter()).find(|visual| visual.visual_id == root.root_visual)?; + Some(PixelLayout { + bits_per_pixel: format.bits_per_pixel, + least_significant_first: setup.image_byte_order == ImageOrder::LSB_FIRST, + masks: [visual.red_mask, visual.green_mask, visual.blue_mask], + }) +} + +/// The colour of the one root-window pixel at `(x, y)` (the root spans every monitor, in physical pixels) +fn root_pixel(connection: &RustConnection, root: Window, layout: PixelLayout, x: i16, y: i16) -> Option<[u8; 3]> { + let image = connection.get_image(ImageFormat::Z_PIXMAP, root, x, y, 1, 1, u32::MAX).ok()?.reply().ok()?; + layout.decode(&image.data) +} From 4c8cd40c3d2f5aff59f95c8dcdc810cc833005d5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:47 +0000 Subject: [PATCH 023/153] Effects: a content effect blends each channel on its own --- crates/engine/src/commands.rs | 3 + crates/engine/tests/it/content_effects.rs | 152 +++++++++++++++++++--- 2 files changed, 139 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 3692499c..b8da2ca6 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -113,12 +113,15 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_cmds::specs()); v.extend(crate::fill_material_cmds::specs()); v.extend(crate::fill_reset_cmds::specs()); + v.extend(crate::folder_cmds::specs()); v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); v.extend(crate::mask_export::specs()); + v.extend(crate::add_mask_cmds::specs()); v.extend(crate::color_selection_cmds::specs()); v.extend(crate::effect_clipboard::specs()); + v.extend(crate::effect_blending_cmds::specs()); v.extend(crate::tool_cmds::specs()); v.extend(crate::brush_preset_cmds::specs()); v.extend(crate::path_tool::specs()); diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index 4b761fc8..525296b3 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -21,12 +21,12 @@ fn center(s: &mut Session, c: Channel) -> [f32; 3] { s.caches[0].composite.value(c, (hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32) } -fn close(a: [f32; 3], b: [f32; 3]) -> bool { - (0..3).all(|i| (a[i] - b[i]).abs() < 2e-3) +fn close(color: [f32; 3], expected: [f32; 3]) -> bool { + color.iter().zip(expected).all(|(component, wanted)| (component - wanted).abs() < 2e-3) } -fn id(v: Value, key: &str) -> u64 { - v[key].as_u64().unwrap() +fn id(reply: Value, key: &str) -> u64 { + reply[key].as_u64().unwrap() } #[test] @@ -34,38 +34,53 @@ fn content_effects_commands_inspect_and_round_trip() { let mut s = session(); let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer"); let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "hue": 1.0 / 3.0})).unwrap(), "effect"); + assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor)); assert!(s.doc.project.layer(LayerId(layer)).unwrap().mask.is_none(), "content effects don't create a mask"); assert_eq!(s.target, StackTarget::Effect(LayerId(hsl))); - // Mask-only effects refuse the content, unknown targets are errors. + // Mask-only effects refuse the content, unknown targets are errors assert!(execute(&mut s, "effect.add.generator", &json!({"target": "content"})).is_err()); assert!(execute(&mut s, "effect.add.filter", &json!({"target": "nope"})).is_err()); + execute(&mut s, "effect.set", &json!({"effect": hsl, "hue": 0.0, "lightness": -1.0})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), [0.0; 3])); + execute(&mut s, "effect.set", &json!({"effect": hsl, "visible": false})).unwrap(); - // A content fill effect, edited through layer.fill.set. + // A content fill effect, edited through layer.fill.set let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect"); + assert!(close(center(&mut s, Channel::Roughness), [0.7; 3])); assert!(close(center(&mut s, Channel::BaseColor), [1.0, 0.0, 0.0]), "channels without a source stay"); + execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "value": 0.9})).unwrap(); + assert!(close(center(&mut s, Channel::Roughness), [0.9; 3])); + execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "enabled": false})).unwrap(); + assert!(close(center(&mut s, Channel::Roughness), [0.2; 3])); assert!(execute(&mut s, "layer.fill.set", &json!({"effect": hsl, "channel": "roughness", "value": 0.5})).is_err(), "not a fill effect"); - // Inspect shows the content stack; the project survives a save/load round trip. + // Inspect shows the content stack; the project survives a save/load round trip let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); - let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer).unwrap().clone(); - let kinds: Vec<&str> = row["contentEffects"].as_array().unwrap().iter().map(|e| e["kind"].as_str().unwrap()).collect(); + let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); + let kinds: Vec<&str> = row["contentEffects"].as_array().unwrap().iter().map(|effect| effect["kind"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["HSL Perceptive", "Fill"], "{row}"); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); execute(&mut s, "layer.select", &json!({"layer": layer, "target": fill})).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": fill})).unwrap(); + assert_eq!(s.target, StackTarget::Content); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layer(LayerId(layer)).unwrap().content_effects.len(), 2); } @@ -104,14 +119,14 @@ fn anchor_points_in_masks_record_the_mask_for_layers_above() { execute(&mut s, "effect.add.fill", &json!({"value": 0.4})).unwrap(); let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"target": "mask", "name": "Wear"})).unwrap(), "effect"); let layer = s.doc.project.layer(LayerId(low)).unwrap(); - assert!(layer.mask.as_ref().unwrap().effects.iter().any(|e| e.id.0 == anchor), "in the mask"); + assert!(layer.mask.as_ref().unwrap().effects.iter().any(|effect| effect.id.0 == anchor), "in the mask"); assert!(layer.content_effects.is_empty(), "not on the content"); // Without a target (or with no params at all) it still goes on the content, as before let content = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); - assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|e| e.id.0 == content)); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|effect| effect.id.0 == content)); let bare = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); - assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|e| e.id.0 == bare)); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|effect| effect.id.0 == bare)); // Folders take anchors in their masks only let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); @@ -179,6 +194,50 @@ fn anchor_effects_added_through_instance_validate_against_source() { assert!(session.doc.project.layer(LayerId(source)).unwrap().mask.is_none()); } +#[test] +fn mask_anchor_points_feed_layers_above_and_folders_take_them() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + let name = s.doc.project.layer(LayerId(low)).unwrap().name.clone(); + + // No target (or null params) still goes on the content, named after the layer + let content = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|effect| effect.id.0 == content)); + assert_eq!(s.doc.project.effect(LayerId(content)).unwrap().1.name, name); + execute(&mut s, "effect.add.fill", &json!({"layer": low, "target": "mask", "value": 0.4})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low, "target": "mask"})).unwrap(), "effect"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.effect(LayerId(anchor)).is_none() && s.doc.project.layer(LayerId(low)).unwrap().mask.is_some(), "one undo step"); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + let mask = s.doc.project.layer(LayerId(low)).unwrap().mask.clone().unwrap(); + let added = mask.effects.iter().find(|effect| effect.id.0 == anchor); + assert_eq!(added.map(|effect| effect.name.clone()), Some(format!("{name} mask"))); + assert!(execute(&mut s, "effect.add.anchor", &json!({"layer": low, "target": "nope"})).is_err()); + + // A layer above reads the mask's gray (0.4) in any channel: the same as a uniform 0.4 mask + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let reader = id(execute(&mut s, "effect.add.fill", &json!({"anchor": anchor, "anchorChannel": "baseColor"})).unwrap(), "effect"); + let anchored = center(&mut s, Channel::BaseColor); + execute(&mut s, "effect.set", &json!({"effect": reader, "value": 0.4})).unwrap(); + assert!(close(anchored, center(&mut s, Channel::BaseColor)), "{anchored:?}"); + execute(&mut s, "effect.set", &json!({"effect": reader, "anchor": anchor, "anchorChannel": "roughness"})).unwrap(); + assert!(close(anchored, center(&mut s, Channel::BaseColor)), "every channel reads the gray"); + + // Inspect lists what reads an anchor point + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(&format!("\"references\":[{{\"effect\":{reader},\"layer\":{top}}}]")), "{inspect}"); + + // Folders take mask anchor points, not content ones + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + assert!(execute(&mut s, "effect.add.anchor", &json!({"layer": folder})).is_err(), "a folder has no content stack"); + let folder_anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap(), "effect"); + let folder_mask = s.doc.project.layer(LayerId(folder)).unwrap().mask.clone().unwrap(); + assert!(folder_mask.effects.iter().any(|effect| effect.id.0 == folder_anchor)); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); +} + #[test] fn painting_into_a_content_paint_effect() { let mut s = session(); @@ -204,7 +263,7 @@ fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.2})).unwrap(), "effect"); - let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|e| e.id.0).collect::>(); + let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|effect| effect.id.0).collect::>(); assert!(close(center(&mut s, Channel::Roughness), [0.2; 3]), "the fill covers the paint"); // To the bottom, the paint shows again; an index past the end means the top. execute(&mut s, "effect.move", &json!({"effect": fill, "index": 0})).unwrap(); @@ -234,7 +293,7 @@ fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { let a = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(), "effect"); let b = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); execute(&mut s, "effect.move", &json!({"effect": b, "index": 0})).unwrap(); - let mask: Vec = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|e| e.id.0).collect(); + let mask: Vec = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id.0).collect(); assert_eq!(mask, [b, a]); } @@ -260,7 +319,7 @@ fn effects_copy_and_paste_between_layers_and_stacks() { execute(&mut s, "effect.copy", &json!({"effect": inv})).unwrap(); execute(&mut s, "layer.select", &json!({"layer": high, "target": pasted})).unwrap(); let again = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); - let order: Vec = s.doc.project.layer(LayerId(high)).unwrap().content_effects.iter().map(|e| e.id.0).collect(); + let order: Vec = s.doc.project.layer(LayerId(high)).unwrap().content_effects.iter().map(|effect| effect.id.0).collect(); assert_eq!(order, [pasted, again, inv]); // A generator goes on a mask (made for it) even with the content selected; asking for the // content is an error. Cut removes the original. @@ -272,7 +331,7 @@ fn effects_copy_and_paste_between_layers_and_stacks() { assert!(execute(&mut s, "effect.paste", &json!({"target": "content"})).is_err()); execute(&mut s, "effect.paste", &Value::Null).unwrap(); let mask = &s.doc.project.layer(LayerId(low)).unwrap().mask; - assert!(mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Generator(_))))); + assert!(mask.as_ref().is_some_and(|mask| mask.effects.iter().any(|effect| matches!(effect.kind, EffectKind::Generator(_))))); // A fill reading an anchor point needs one below its new layer. execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); @@ -428,3 +487,64 @@ fn mask_fill_can_use_an_image_source() { execute(&mut session, "effect.set", &json!({"effect": fill, "value": 0.25})).unwrap(); assert!(matches!(fill_source(&session, fill), Source::Uniform(v) if (v[0] - 0.25).abs() < 1e-6), "{:?}", fill_source(&session, fill)); } + +/// A content levels remaps the one channel it affects (Base color when added); levels saved before the choice remap every channel; Clamp stops values past the input handles at the output ends +#[test] +fn content_levels_remap_the_channel_they_affect() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.8, 0.8], "roughness": 0.8})).unwrap(), "layer"); + let levels_effect = id(execute(&mut s, "effect.add.levels", &json!({"target": "content", "outHigh": 0.5})).unwrap(), "effect"); + let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"affects\":\"baseColor\""), "{inspected}"); + assert!(close(center(&mut s, Channel::BaseColor), [0.4; 3]), "{:?}", center(&mut s, Channel::BaseColor)); + assert!((center(&mut s, Channel::Roughness)[0] - 0.8).abs() < 1e-3, "roughness is not what it remaps"); + + execute(&mut s, "effect.set", &json!({"effect": levels_effect, "affects": "roughness"})).unwrap(); + assert!((center(&mut s, Channel::BaseColor)[0] - 0.8).abs() < 1e-3); + assert!((center(&mut s, Channel::Roughness)[0] - 0.4).abs() < 1e-3); + assert!(execute(&mut s, "effect.set", &json!({"effect": levels_effect, "affects": "normal"})).is_err(), "levels pass normal maps through"); + assert!(execute(&mut s, "effect.set", &json!({"effect": levels_effect, "affects": "nope"})).is_err()); + + // Levels saved before the choice: every channel + if let Some(EffectKind::Levels(levels)) = s.doc.project.effect_mut(LayerId(levels_effect)).map(|effect| &mut effect.kind) { + levels.affects = None; + } + for visible in [false, true] { + execute(&mut s, "effect.set", &json!({"effect": levels_effect, "visible": visible})).unwrap(); + } + assert!((center(&mut s, Channel::BaseColor)[0] - 0.4).abs() < 1e-3); + assert!((center(&mut s, Channel::Roughness)[0] - 0.4).abs() < 1e-3); + + // Past the white input handle: on, it stops at the output end; off, it carries on + execute(&mut s, "effect.set", &json!({"effect": levels_effect, "affects": "baseColor", "inHigh": 0.6, "outHigh": 0.6, "clamp": true})).unwrap(); + assert!((center(&mut s, Channel::BaseColor)[0] - 0.6).abs() < 1e-3, "{:?}", center(&mut s, Channel::BaseColor)); + execute(&mut s, "effect.set", &json!({"effect": levels_effect, "clamp": false})).unwrap(); + assert!((center(&mut s, Channel::BaseColor)[0] - 0.8).abs() < 1e-3, "0.8 is a third past 0.6: {:?}", center(&mut s, Channel::BaseColor)); + + // A mask's levels remap its one value + execute(&mut s, "mask.add.black", &json!({"layer": layer})).unwrap(); + assert!(execute(&mut s, "effect.add.levels", &json!({"target": "mask", "affects": "roughness"})).is_err()); + let mask_levels = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": mask_levels, "affects": "roughness"})).is_err()); +} + +/// A colour channel's histogram counts each component and the luminance on their own +#[test] +fn a_color_histogram_has_its_components_and_luminance() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let levels = id(execute(&mut s, "effect.add.levels", &json!({"target": "content"})).unwrap(), "effect"); + + let histogram = execute(&mut s, "effect.histogram", &json!({"effect": levels, "bins": 4})).unwrap(); + let roughness = execute(&mut s, "effect.histogram", &json!({"effect": levels, "channel": "roughness"})).unwrap(); + + let counts = |bins: &Value| bins.as_array().unwrap().iter().map(|count| count.as_u64().unwrap()).collect::>(); + let components: Vec> = histogram["components"].as_array().unwrap().iter().map(counts).collect(); + let [red, green, blue] = &components[..] else { panic!("three components: {components:?}") }; + let texels = red.last().copied().unwrap(); + assert!(texels > 0); + assert_eq!([red, green, blue], [&vec![0, 0, 0, texels], &vec![texels, 0, 0, 0], &vec![texels, 0, 0, 0]]); + assert_eq!(counts(&histogram["luminance"]), vec![0, texels, 0, 0], "red's luminance is 0.3"); + assert_eq!(counts(&histogram["bins"]), vec![2 * texels, 0, 0, texels]); + assert!(roughness.get("components").is_none(), "one value has no components"); +} From 32f848c7c59e6de6f794b971ff49cb1cf72f05e5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:12 +0000 Subject: [PATCH 024/153] Fills: engine evaluation, commands and the remaining tests for the Fill tab --- Cargo.lock | 1 + apps/texturecraft/Cargo.toml | 4 + apps/texturecraft/src/main.rs | 55 +- crates/automation/src/render.rs | 2 +- crates/compose/src/eval.rs | 802 +++++++++++++----- crates/compose/src/fill_copy.rs | 34 + crates/compose/src/lib.rs | 14 +- crates/compose/src/store.rs | 200 ++++- crates/compose/src/tile_pattern.rs | 2 +- crates/compose/tests/cache_and_instances.rs | 33 +- crates/core/src/backface.rs | 23 + crates/core/src/depth_culling.rs | 23 + crates/core/src/lib.rs | 23 +- crates/core/src/project.rs | 12 +- crates/core/src/projector.rs | 40 + crates/core/src/saved_projection.rs | 30 + crates/core/src/shape_crop.rs | 27 + crates/engine/src/commands.rs | 2 + crates/engine/src/filter_lib.rs | 2 +- crates/engine/src/inspect.rs | 65 +- crates/engine/src/layer_cmds.rs | 343 ++++++-- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_cmds.rs | 26 +- crates/engine/src/materials.rs | 12 +- crates/engine/src/pbr_cmds.rs | 13 +- crates/engine/src/resource_cmds.rs | 4 +- crates/engine/src/session.rs | 4 + crates/engine/src/smart_masks.rs | 3 +- crates/engine/src/thumbs.rs | 29 +- crates/engine/src/view_cmds.rs | 121 +-- crates/engine/tests/it/main.rs | 6 +- crates/engine/tests/it/painter_gaps.rs | 55 +- crates/engine/tests/it/tile_generator.rs | 4 +- crates/engine/tests/it/user_smart_mask.rs | 5 +- crates/geom/src/mesh.rs | 20 + crates/paint/src/brush.rs | 15 +- crates/paint/src/pickup.rs | 7 +- crates/render/tests/headless.rs | 4 +- crates/ui-egui/src/dock.rs | 680 ++++++++------- crates/ui-egui/src/exact_entry_open.rs | 5 + crates/ui-egui/src/gpu.rs | 2 +- crates/ui-egui/src/gray_slider.rs | 5 +- crates/ui-egui/src/i18n.rs | 21 + crates/ui-egui/src/lib.rs | 79 +- crates/ui-egui/src/past_end.rs | 10 + crates/ui-egui/src/placement.rs | 9 + crates/ui-egui/src/properties_popup.rs | 16 +- crates/ui-egui/src/render_mode/tests.rs | 4 +- crates/ui-egui/src/resolution_band.rs | 138 +++ crates/ui-egui/src/shelf_preview.rs | 4 +- crates/ui-egui/src/theme.rs | 20 + crates/ui-egui/src/thumbs.rs | 14 +- crates/ui-egui/src/viewport.rs | 384 ++------- crates/ui-egui/src/widgets.rs | 78 +- crates/ui-egui/tests/it/decal_proportions.rs | 113 --- crates/ui-egui/tests/it/decal_symmetry.rs | 106 --- crates/ui-egui/tests/it/effect_decal.rs | 65 -- .../tests/it/fill_projection_section.rs | 102 --- crates/ui-egui/tests/it/fill_support.rs | 52 ++ crates/ui-egui/tests/it/filter_support.rs | 51 ++ crates/ui-egui/tests/it/main.rs | 8 +- crates/ui-egui/tests/it/panel_header.rs | 25 + crates/ui-egui/tests/it/polygon_fill.rs | 19 + crates/ui-egui/tests/it/project_config.rs | 8 +- crates/ui-egui/tests/it/properties_popup.rs | 83 +- crates/ui-egui/tests/it/shelf_drop.rs | 6 +- crates/ui-egui/tests/it/symmetry.rs | 6 +- crates/ui-egui/tests/ui_snapshots.rs | 472 ++++++++++- 68 files changed, 3111 insertions(+), 1541 deletions(-) create mode 100644 crates/compose/src/fill_copy.rs create mode 100644 crates/core/src/backface.rs create mode 100644 crates/core/src/depth_culling.rs create mode 100644 crates/core/src/projector.rs create mode 100644 crates/core/src/saved_projection.rs create mode 100644 crates/core/src/shape_crop.rs create mode 100644 crates/ui-egui/src/exact_entry_open.rs create mode 100644 crates/ui-egui/src/past_end.rs create mode 100644 crates/ui-egui/src/placement.rs create mode 100644 crates/ui-egui/src/resolution_band.rs delete mode 100644 crates/ui-egui/tests/it/decal_proportions.rs delete mode 100644 crates/ui-egui/tests/it/decal_symmetry.rs delete mode 100644 crates/ui-egui/tests/it/effect_decal.rs delete mode 100644 crates/ui-egui/tests/it/fill_projection_section.rs create mode 100644 crates/ui-egui/tests/it/fill_support.rs create mode 100644 crates/ui-egui/tests/it/filter_support.rs diff --git a/Cargo.lock b/Cargo.lock index a06f2619..f9292a97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4604,6 +4604,7 @@ dependencies = [ "craft-update", "eframe", "egui", + "egui_kittest", "image", "log", "rfd", diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index e3fb936a..cab8493e 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -38,5 +38,9 @@ craft-update = { workspace = true } [target.'cfg(target_os = "macos")'.dependencies] craft-menu = { workspace = true } +[dev-dependencies] +# The pointer-hold test drives the windowed app's frames (src/main.rs) +egui_kittest = { version = "0.37", features = ["eframe"] } + [build-dependencies] winresource = "0.1" diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index ec60c58c..3a768c2b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -164,12 +164,15 @@ impl eframe::App for Shell { self.app.save(storage); } - fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw: &mut egui::RawInput) { + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { // winit gives the window its caption back when it changes the window's flags (maximize, // restore, …): take it off again before the frame is laid out. if let Some(guard) = self.window_frame.as_mut() { guard(); } + + // The app's own hook: a drag holding the pointer reads its moves from it + self.app.raw_input_hook(ctx, raw); } fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { @@ -388,4 +391,54 @@ mod tests { std::fs::remove_file(&ron_path).unwrap(); assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); } + + /// How far the test's drag moves the mouse in one frame, in points + const DRAG_STEP: egui::Vec2 = egui::vec2(80.0, 0.0); + + /// Points within which a put-back lands on the press point (the system rounds it to whole pixels) + const PUT_BACK_REACH: f32 = 1.0; + + /// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window + fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec) -> Vec { + let ctx = harness.ctx.clone(); + let mut raw = harness.input_mut().clone(); + raw.events.extend(events); + eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw); + *harness.input_mut() = raw; + harness.step(); + harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default() + } + + /// Holding the fill's preview square in the window holds the system's pointer: put back to the press point every frame, or locked where the system locks it + #[test] + fn the_window_holds_the_pointer_while_the_preview_square_is_held() { + let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1])); + let mut harness = builder.build_eframe(|cc| Shell { + app: TextureCraftApp::new(cc, session), + window_frame: None, + #[cfg(target_os = "macos")] + movable: None, + }); + harness.run_steps(4); + let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone(); + harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap(); + harness.run_steps(2); + + let pad = egui_kittest::kittest::Queryable::get_by_label(&harness, "Move on model").rect().center(); + let press = egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + let pressed = window_frame(&mut harness, vec![egui::Event::PointerMoved(pad), press]); + let locked = pressed.contains(&egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked)); + + // A locked pointer stays still and the system reports only its raw motion + let mut moves = vec![egui::Event::MouseMoved(DRAG_STEP)]; + if !locked { + moves.push(egui::Event::PointerMoved(pad + DRAG_STEP)); + } + let moved = window_frame(&mut harness, moves); + let put_back = moved.iter().any(|command| matches!(command, egui::ViewportCommand::CursorPosition(to) if to.distance(pad) <= PUT_BACK_REACH)); + assert!(locked || put_back, "the window puts the pointer back where the press began, so it never leaves: {moved:?}"); + let seen = harness.ctx.input(|input| input.pointer.latest_pos()); + assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}"); + } } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 8e809021..588f1752 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -285,7 +285,7 @@ mod tests { mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1)); let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap(); assert_eq!(session.caches.len(), 2); - session.images.insert("red".into(), Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true })); + session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true))); execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap(); let camera = session.camera; let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 }; diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 8bb323e9..adbf91ae 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -15,18 +15,29 @@ use texturecraft_core::{ blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; +use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; +use crate::fill_copies::FillCopies; +use crate::fill_copy::FillCopy; +use crate::fill_place::FillPlace; use crate::held_fields::HeldFields; -use crate::pattern::{Coords, decal_uv_symmetric, image_samples, pattern_pixels, procedural_in, world_noise}; +use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, procedural_in, world_noise}; use crate::pattern_context::PatternContext; -use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; +use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::projector_depth::ProjectorDepth; +use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; const NCH: usize = Channel::ALL.len(); +/// Coverage past which a symmetric fill's remaining copies would not show under the ones above +const COVERED: f32 = 0.9999; + +/// Share of an image's longer side a step to the next texel may jump before it counts as a UV seam +const SEAM_JUMP_SHARE: f32 = 0.25; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; @@ -211,8 +222,16 @@ struct ChanPlan<'a> { } enum Content<'a> { - Paint { preview: bool }, - Fill(&'a Fill), + Paint { + preview: bool, + }, + Fill { + fill: Box>, + /// Its projector's depth map when it culls by depth + depth: Option>, + /// Whether it covers every texel (see [`covers_every_texel`]), so no texel asks + covers_all: bool, + }, Group(Vec>), } @@ -228,6 +247,10 @@ struct EffectPlan<'a> { curvature_sizes: Option>, /// A filtered mask stage retained because an anchor above it records that stage. filtered_mask: Option<&'a Field>, + /// The projector's depth map of a fill or material effect that culls by depth + depth: Option>, + /// Whether a fill or material effect covers every texel (see [`covers_every_texel`]), so no texel asks + covers_all: bool, } struct MaskPlan<'a> { @@ -969,7 +992,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset. +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset fn finish_generator(generator: &Generator, ramp: f32) -> f32 { let value = generator.global.apply(ramp); let value = if generator.invert { 1.0 - value } else { value }; @@ -1063,10 +1086,9 @@ struct Node<'a> { content: Content<'a>, chans: Vec>, mask: Option>, - /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an - /// anchor with visible effects above it) with its content cut after `k` visible effects. + /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an anchor with visible effects above it) with its content cut after `k` visible effects anchors: Vec<(LayerId, Option)>, - /// The node or one of its children records an anchor. + /// The node or one of its children records an anchor has_anchor: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). @@ -1088,6 +1110,12 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), _ => None, }; + let (depth, covers_all) = match &effect.kind { + EffectKind::Fill { projection, sampling, .. } | EffectKind::Material(Fill { projection, sampling, .. }) => { + fill_coverage(inp, projection, *sampling) + } + _ => (None, false), + }; EffectPlan { id: effect.id, kind: &effect.kind, @@ -1097,6 +1125,8 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y preview: previews(inp, target), curvature_sizes, filtered_mask: None, + depth, + covers_all, } }) .collect() @@ -1145,6 +1175,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } @@ -1188,7 +1219,9 @@ fn plan_node<'a>( .collect::>(); let content = match &layer.kind { LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, - LayerKind::Fill(f) => Content::Fill(f), + LayerKind::Fill(f) => { + let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); + } LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), // `content_layer` already followed instance links @@ -1256,7 +1289,7 @@ fn blend_chan(c: &ChanPlan, mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; if c.comps == 3 { blend3(mode, a, b) } else { [blend1(mode, a[0], b[0]); 3] } } -/// Lay value `p` with weight `a` over a straight value and coverage (premultiplied "over"). +/// Lay value `p` with weight `a` over a straight value and coverage (premultiplied "over") fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f32) -> ([f32; 3], f32) { if a <= 0.0 { return (v, cov); @@ -1266,8 +1299,29 @@ fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f3 (mix3(v, b, a / nc.max(1e-5)), nc) } -/// The plain UV projection a decal's frame coordinates are sampled through. -const DECAL_UV: Projection = Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }; +/// Whether a fill placed by `proj` repeats past its tile both ways, so no texel falls outside it (tri-planar never ends) +fn repeats_everywhere(proj: &Projection, sampling: Sampling) -> bool { + sampling.wrap.repeats() == (true, true) || matches!(proj, Projection::Triplanar { .. }) +} + +/// Whether a fill placed by `proj` covers every texel: it repeats, nothing crops or culls it and it is not framed on the surface +fn covers_every_texel(proj: &Projection, sampling: Sampling, depth: Option<&ProjectorDepth>) -> bool { + let framed = matches!(proj, Projection::Planar { placed: Some(_), .. } | Projection::Warp { .. }); + let depth_culled = depth.is_some() && proj.depth_culling().is_some(); + !framed && !depth_culled && repeats_everywhere(proj, sampling) && projector_covers_all(proj) +} + +/// A fill's projector depth (None: not culled by depth) and whether it covers every texel +fn fill_coverage(inp: &Inputs, projection: &Projection, sampling: Sampling) -> (Option>, bool) { + let depth = ProjectorDepth::of(inp.mesh, inp.bounds, projection); + let covers_all = covers_every_texel(projection, sampling, depth.as_deref()); + (depth, covers_all) +} + +/// Whether a fill placed by `proj` is sampled once per copy of `sampling`'s symmetry +fn takes_symmetry(proj: &Projection, sampling: Sampling) -> bool { + sampling.symmetry.on && proj.takes_symmetry() +} /// Per-texel context. struct Texel<'a, 'b> { @@ -1285,6 +1339,8 @@ struct Texel<'a, 'b> { anchors: Vec<(LayerId, Acc, bool)>, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, + /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip + copy: Option, } /// What a layer contributes (its mask, its content value and coverage per channel): evaluated @@ -1369,29 +1425,142 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(c) = self.coords { return c; } + + #[cfg(test)] + tests::COORDS_LOOKUPS.with(|count| count.set(count.get() + 1)); + let g = self.inp.gbuf; - let i = (self.y * g.width + self.x) as usize; - let (lo, hi) = self.inp.bounds; - let center = (lo + hi) * 0.5; - let r = ((hi - lo).length() * 0.5).max(1e-4); - let mut c = match g.surface(self.inp.mesh, i) { - Some(s) => Coords { uv: s.uv, pos: (s.pos - center) / r, nrm: s.nrm }, - None => Coords { uv: Vec2::new((self.x as f32 + 0.5) / g.width as f32, (self.y as f32 + 0.5) / g.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + let c = match self.surface((self.y * g.width + self.x) as usize) { + Some(s) => self.coords_of(s), + None => self.tile_uv(Coords { + uv: Vec2::new((self.x as f32 + 0.5) / g.width as f32, (self.y as f32 + 0.5) / g.height as f32), + pos: Vec3::ZERO, + nrm: Vec3::Y, + }), }; - // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile). + self.coords = Some(c); + c + } + + /// The coordinates projections see at surface `s`: its UV, and its position in mesh radii from the mesh's centre + #[inline(always)] + fn coords_of(&self, s: Surface) -> Coords { + let (center, radius) = mesh_frame(self.inp.bounds); + self.tile_uv(Coords { uv: s.uv, pos: (s.pos - center) / radius, nrm: s.nrm }) + } + + /// `c` with its UV moved out of the atlas on a UV-tiled set, so projections see the mesh's own UVs (patterns repeat per tile) + #[inline(always)] + fn tile_uv(&self, mut c: Coords) -> Coords { if let Ok(set) = self.inp.project.texture_set(self.inp.ts) && let Some(grid) = set.tile_grid() { c.uv = Vec2::from(set.from_atlas(&grid, c.uv.to_array())); } - self.coords = Some(c); c } - /// World position of this texel (None when uncovered). + /// The coordinates of texel (`x`, `y`) through `proj`, uncached (None when uncovered) + fn projected_at(&self, proj: &Projection, x: u32, y: u32) -> Option { + let g = self.inp.gbuf; + if x >= g.width || y >= g.height { + return None; + } + + let s = self.surface((y * g.width + x) as usize)?; + let c = self.coords_of(s); + if proj.frame().is_none() { + return Some(c); + } + + let (center, _) = mesh_frame(self.inp.bounds); + framed_cover(proj, s.pos, s.nrm, center).map(|(uv, _)| Coords { uv, ..c }) + } + + /// Image texels one surface texel spans at each of `samples`, from the next texel across and down (1 at a seam) + fn footprints(&self, proj: &Projection, samples: &[(Vec2, f32); 3], image: &ImageRes) -> [f32; 3] { + let size = Vec2::new(image.width as f32, image.height as f32); + let mut out = [1.0f32; 3]; + for (dx, dy) in [(1, 0), (0, 1)] { + let Some(next) = self.projected_at(proj, self.x + dx, self.y + dy) else { continue }; + for ((footprint, (uv, _)), (next_uv, _)) in out.iter_mut().zip(samples).zip(self.image_uvs(proj, &next)) { + let span = ((next_uv - *uv) * size).length(); + + // A jump across more of the image than this is a UV seam, not the texel's size + if span.is_finite() && span < size.max_element() * SEAM_JUMP_SHARE { + *footprint = footprint.max(span); + } + } + } + out + } + + /// World position of this texel as the fill copy being sampled sees it (None when uncovered) fn world(&self) -> Option { - let i = (self.y * self.inp.gbuf.width + self.x) as usize; - self.inp.gbuf.surface(self.inp.mesh, i).map(|s| s.pos) + self.surface((self.y * self.inp.gbuf.width + self.x) as usize).map(|s| s.pos) + } + + /// The surface at G-buffer index `i`, as the fill copy being sampled sees it + #[inline(always)] + fn surface(&self, i: usize) -> Option { + let mut s = self.inp.gbuf.surface(self.inp.mesh, i)?; + if let Some(copy) = self.copy { + s.pos = copy.point(s.pos); + s.nrm = copy.normal(s.nrm); + s.geo_nrm = copy.normal(s.geo_nrm); + } + Some(s) + } + + /// Where `proj` reads images at `coords`, turned over as the fill copy being sampled says + fn image_uvs(&self, proj: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { + let samples = image_samples(proj, coords); + match self.copy { + Some(copy) => samples.map(|(uv, weight)| (copy.uv(uv), weight)), + None => samples, + } + } + + /// A fill's value and coverage through `proj`, from `one` (which samples it once): with `sampling`'s symmetry on, every copy of the projection is sampled and the copies are laid over each other, the texel's own copy on top + fn symmetric(&mut self, proj: &Projection, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { + // Most fills have no symmetry: they are sampled directly and never pay for the surface lookup + if !takes_symmetry(proj, sampling) { + return one(self); + } + + self.symmetric_copies(sampling, one) + } + + /// [`Texel::symmetric`] with symmetry on: every copy sampled and laid over the others + fn symmetric_copies(&mut self, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { + let Some(world) = self.inp.gbuf.surface(self.inp.mesh, (self.y * self.inp.gbuf.width + self.x) as usize).map(|surface| surface.pos) else { + return one(self); + }; + + let (center, radius) = mesh_frame(self.inp.bounds); + let cached = self.coords.take(); + let mut value = [0.0f32; 3]; + let mut cover = 0.0f32; + for copy in FillCopies::new(&sampling.symmetry, world, center, radius) { + self.copy = Some(copy); + self.coords = None; + let (copy_value, copy_cover) = one(self); + let weight = copy_cover.clamp(0.0, 1.0) * (1.0 - cover); + for (total, part) in value.iter_mut().zip(copy_value) { + *total += part * weight; + } + cover += weight; + if cover >= COVERED { + break; + } + } + self.copy = None; + self.coords = cached; + if cover <= 0.0 { + return ([0.0; 3], 0.0); + } + + (value.map(|v| v / cover), cover) } fn baked(&self, m: BakedMap) -> Option { @@ -1402,33 +1571,90 @@ impl<'a, 'b> Texel<'a, 'b> { 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 - /// position in the decal's frame (then sampled as UVs) and the decal's coverage. - fn projected<'p>(&mut self, proj: &'p Projection) -> (Coords, &'p Projection, f32) { + /// Where `proj` samples this texel: its coordinates, or for a projection from a frame on the surface (placed planar, warp) its place in the frame, and how much backface culling and the shape crop let through + fn projected(&mut self, proj: &Projection) -> (Coords, f32) { let c = self.coords(); - let (lo, hi) = self.inp.bounds; - let center = (lo + hi) * 0.5; - match proj { - Projection::Decal(d) => match self.world().and_then(|p| decal_uv_symmetric(d, p, c.nrm, center)) { - Some((uv, w)) => (Coords { uv, ..c }, &DECAL_UV, w), - None => (c, &DECAL_UV, 0.0), - }, - _ => (c, proj, 1.0), + if proj.frame().is_none() { + return (c, 1.0); + } + + let (center, _) = mesh_frame(self.inp.bounds); + + match self.world().and_then(|p| framed_cover(proj, p, c.nrm, center)) { + Some((uv, cover)) => (Coords { uv, ..c }, cover), + None => (c, 0.0), } } - /// How much a fill projected by `proj` covers this texel: 1, or for a decal its frame - /// coverage times the alpha of its first image source. - fn cover<'s>(&mut self, mut sources: impl Iterator, proj: &Projection) -> f32 { - if !matches!(proj, Projection::Decal(_)) { - return 1.0; + /// `place`'s fill at this texel in channel `ch`, every symmetric copy laid over each other when its symmetry is on + #[inline(always)] + fn fill_place_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { + // Without symmetry the fill is sampled directly: through `symmetric`'s closure a plain fill composites about 8% slower + if takes_symmetry(&place.fill.projection, place.fill.sampling) { + self.symmetric(&place.fill.projection, place.fill.sampling, |texel| texel.fill_texel(place, source, ch)) + } else { + self.fill_texel(place, source, ch) } - let (c, _, w) = self.projected(proj); + } + + /// `place`'s fill sampled once at this texel: its value in channel `ch` (`source`, else the channel's default) and its coverage + #[inline(always)] + fn fill_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { + let FillPlace { fill, depth, covers_all } = place; + let value = match source { + Some(source) => self.source(source, &fill.projection, fill.sampling, ch.kind()), + None => ch.default_value(), + }; + let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), &fill.projection, fill.sampling, depth) }; + (value, cover) + } + + /// How much a fill projected by `proj` covers this texel: [`Texel::shape_cover`], then depth culling through the projector's `depth` map + fn cover<'s>(&mut self, sources: impl Iterator, proj: &Projection, sampling: Sampling, depth: Option<&ProjectorDepth>) -> f32 { + #[cfg(test)] + tests::COVER_CALLS.with(|count| count.set(count.get() + 1)); + + let cover = self.shape_cover(sources, proj, sampling); + match depth.zip(proj.depth_culling()) { + Some((depth, culling)) if cover > 0.0 => cover * self.world().map_or(1.0, |p| depth.cover(p, culling.hardness)), + _ => cover, + } + } + + /// How much a fill projected by `proj` covers this texel: wrap, shape crop and backface culling, and a cropped framed projection's image alpha + fn shape_cover<'s>(&mut self, mut sources: impl Iterator, proj: &Projection, sampling: Sampling) -> f32 { + let (Projection::Planar { projector, placed: Some(_), .. } | Projection::Warp { projector, .. }) = proj else { + // Repeating with nothing cropped or culled, a fill covers every texel without looking up where the texel is + if repeats_everywhere(proj, sampling) && projector_covers_all(proj) { + return 1.0; + } + + let coords = self.coords(); + return self.tile_cover(proj, &coords, sampling) * projector_cover(proj, &coords); + }; + + let (c, cover) = self.projected(proj); + if projector.crop == ShapeCrop::ExtendsOutside { + return cover * self.tile_cover(proj, &c, sampling); + } + + // Cropped to its shape, a framed projection takes the shape of its image too let image = sources.find_map(|s| match s { Source::Image { name, .. } => self.inp.images.get(name), _ => None, }); - w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) + let samples = self.image_uvs(proj, &c); + let [(uv, _), ..] = samples; + + // The shape is read over the footprint the image's colour is, so a shrunk image's coverage matches its averaged colour + let alpha = image.map_or(1.0, |img| { + let [footprint, ..] = match sampling.filtering { + Filtering::BilinearHq => self.footprints(proj, &samples, img), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; + img.sample_filtered(uv.x, uv.y, sampling, footprint)[3].clamp(0.0, 1.0) + }); + cover * alpha * self.tile_cover(proj, &c, sampling) } /// The stack value anchor point `anchor` recorded for `channel` (the channel default for an @@ -1443,8 +1669,20 @@ impl<'a, 'b> Texel<'a, 'b> { self.anchors.iter().rev().find(|(id, ..)| *id == anchor).is_some_and(|(_, _, mask)| *mask) } + /// 1 where a fill placed by `proj` at `coords` lands inside its 0..1 tile on every axis `sampling.wrap` does not repeat, else 0 + fn tile_cover(&self, proj: &Projection, coords: &Coords, sampling: Sampling) -> f32 { + if repeats_everywhere(proj, sampling) { + return 1.0; + } + + let (across, down) = sampling.wrap.repeats(); + let [(uv, _), ..] = self.image_uvs(proj, coords); + let inside = |t: f32, repeats: bool| repeats || (0.0..1.0).contains(&t); + if inside(uv.x, across) && inside(uv.y, down) { 1.0 } else { 0.0 } + } + /// The value `source` gives this texel through `projection`, read as a channel of `kind` - fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + fn source(&mut self, source: &Source, projection: &Projection, sampling: Sampling, kind: ChannelKind) -> [f32; 3] { match source { Source::Uniform(value) => *value, @@ -1457,7 +1695,7 @@ impl<'a, 'b> Texel<'a, 'b> { texturecraft_core::gradient(ramp, lightness).unwrap_or_default() } Source::Procedural { pattern, low, high, ramp } => { - let (coords, projection, _) = self.projected(projection); + let (coords, _) = self.projected(projection); let pixels = if pattern.resolution.can_reduce() { let uv_tile = self.inp.tile_res_at(self.x, self.y); let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(uv_tile, |set| set.resolution); @@ -1476,10 +1714,15 @@ impl<'a, 'b> Texel<'a, 'b> { Source::Image { name, normal_format } => { let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; - let (coords, projection, _) = self.projected(projection); + let (coords, _) = self.projected(projection); + let samples = self.image_uvs(projection, &coords); + let footprints = match sampling.filtering { + Filtering::BilinearHq => self.footprints(projection, &samples, image), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; let mut sum = [0.0f32; 4]; - for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { - for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + for ((uv, weight), footprint) in samples.into_iter().zip(footprints).filter(|((_, weight), _)| *weight > 0.0) { + for (total, value) in sum.iter_mut().zip(image.sample_filtered(uv.x, uv.y, sampling, footprint)) { *total += value * weight; } } @@ -1575,7 +1818,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { match generator.inputs.get(&map) { - Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]), + // Generator inputs have no sampling setting: they read as projects saved before sampling choices did + Some(source) => Some(self.source(source, &Projection::default(), Sampling::SAVED_BEFORE, ChannelKind::Scalar)[0]), None => self.baked(map), } } @@ -1672,9 +1916,15 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity; } } - EffectKind::Fill { 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::Fill { source, projection, sampling } => { + let once = |texel: &mut Self| { + let fill = texel.source(source, projection, *sampling, ChannelKind::Scalar); + let cover = if effect.covers_all { 1.0 } else { texel.cover(std::iter::once(source), projection, *sampling, effect.depth.as_deref()) }; + (fill, cover) + }; + // Sampled directly without symmetry, as `Texel::fill_place_texel` is + let ([fill, ..], cover) = if takes_symmetry(projection, *sampling) { self.symmetric(projection, *sampling, once) } else { once(self) }; + value += (blend1(effect.blend, value, fill) - value) * opacity * cover; } EffectKind::Generator(generator) => { let generated = self.generator(generator, effect.curvature_sizes.as_deref()); @@ -1712,56 +1962,55 @@ impl<'a, 'b> Texel<'a, 'b> { value.clamp(0.0, 1.0) } - /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` - /// layer (`acc` then holds the stack below it). + /// Composite `nodes` over `acc`, recording anchors; true when it reached the `stop` layer (`acc` then holds the stack below it) fn eval(&mut self, nodes: &[Node], acc: &mut Acc) -> bool { - for n in nodes { - if self.stop == Some(n.id) { + for node in nodes { + if self.stop == Some(node.id) { return true; } - let m = self.tape_mask(n); - match &n.content { + let mask = self.tape_mask(node); + match &node.content { // Masked-out groups still run when they record anchors or hold the stop layer - Content::Group(children) if m > 0.0 || n.has_anchor || self.stop.is_some() => { + Content::Group(children) if mask > 0.0 || node.has_anchor || self.stop.is_some() => { let mut inner = *acc; if self.eval(children, &mut inner) { return true; } - if m > 0.0 { - mix_group(acc, &inner, &n.chans, m); + if mask > 0.0 { + mix_group(acc, &inner, &node.chans, mask); } } - Content::Fill(_) | Content::Paint { .. } if m > 0.0 => { - let before = if n.anchors.iter().any(|a| a.1.is_some()) { Some(*acc) } else { None }; - for c in &n.chans { - if let Some((v, cov)) = self.tape_content(&n.content, c) { - apply(acc, c, v, cov, m); + Content::Fill { .. } | Content::Paint { .. } if mask > 0.0 => { + let before = if node.anchors.iter().any(|(_, cut)| cut.is_some()) { Some(*acc) } else { None }; + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.tape_content(&node.content, chan_plan) { + apply(acc, chan_plan, value, coverage, mask); } } // Anchors inside the content stack read the stack cut at that point - for (a, cut) in &n.anchors { - let rec = match (cut, before) { - (Some(k), Some(mut b)) => { - for c in &n.chans { - if let Some((v, cov)) = self.content_to(&n.content, c, *k) { - apply(&mut b, c, v, cov, m); + for (anchor, cut) in &node.anchors { + let recorded = match (cut, before) { + (Some(cut), Some(mut cut_acc)) => { + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.content_to(&node.content, chan_plan, *cut) { + apply(&mut cut_acc, chan_plan, value, coverage, mask); } } - b + cut_acc } _ => *acc, }; - self.anchors.push((*a, rec, false)); + self.anchors.push((*anchor, recorded, false)); } continue; } _ => {} } - for (a, _) in &n.anchors { - self.anchors.push((*a, *acc, false)); + for (anchor, _) in &node.anchors { + self.anchors.push((*anchor, *acc, false)); } } false @@ -1859,8 +2108,7 @@ impl<'a, 'b> Texel<'a, 'b> { k.and_then(|k| allowed.get(k).copied()).unwrap_or(true) } - /// Record the anchors of the stack below layer `id` (`full` is the planned stack), to - /// evaluate that layer on its own. + /// Record the anchors of the stack below layer `id` (`full` is the planned stack), to evaluate that layer on its own fn anchors_below(&mut self, full: &[Node], id: LayerId) { self.anchors.clear(); self.stop = Some(id); @@ -1869,41 +2117,36 @@ impl<'a, 'b> Texel<'a, 'b> { self.stop = None; } - /// Straight value and coverage of one channel of a paint or fill layer at this texel - /// (content effects and live stroke preview included). None where the layer is empty. + /// Straight value and coverage of one channel of a paint or fill layer at this texel (content effects and live stroke preview included); None where the layer is empty fn content(&mut self, content: &Content, c: &ChanPlan) -> Option<([f32; 3], f32)> { self.content_to(content, c, usize::MAX) } - /// [`Texel::content`] with only the first `end` visible content effects. - fn content_to(&mut self, content: &Content, c: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> { - let start = c.start.filter(|(k, _)| *k < end); - let (mut v, mut cov, skip) = match start.and_then(|(k, f)| f.get(self.x, self.y).map(|d| (k, d))) { - Some((k, d)) => { - let px = |i: usize| d.get(i).copied().unwrap_or(0.0); - ([px(0), px(1), px(2)], px(3), k + 1) + /// [`Texel::content`] with only the first `end` visible content effects + fn content_to(&mut self, content: &Content, chan_plan: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> { + let start = chan_plan.start.filter(|(stage, _)| *stage < end); + let (mut value, mut coverage, skip) = match start.and_then(|(stage, field)| field.get(self.x, self.y).map(|texel| (stage, texel))) { + Some((stage, texel)) => { + let component = |i: usize| texel.get(i).copied().unwrap_or(0.0); + ([component(0), component(1), component(2)], component(3), stage + 1) } None => { - let (v, cov) = match content { - Content::Fill(f) => { - let ch = Channel::ALL.get(c.ch).copied()?; - // A channel without a source fills with its default (no clone per texel). - let v = match f.sources.get(&ch) { - Some(s) => self.source(s, &f.projection, ch.kind()), - None => ch.default_value(), - }; - (v, self.cover(f.sources.values(), &f.projection)) + let (value, coverage) = match content { + Content::Fill { fill, depth, covers_all } => { + let ch = Channel::ALL.get(chan_plan.ch).copied()?; + let source = fill.sources.get(&ch); + self.fill_place_texel(FillPlace { fill, depth: depth.as_deref(), covers_all: *covers_all }, source, ch) } - Content::Paint { preview } => self.painted(c.data.as_deref(), c, *preview), + Content::Paint { preview } => self.painted(chan_plan.data.as_deref(), chan_plan, *preview), Content::Group(_) => return None, }; - (v, cov, 0) + (value, coverage, 0) } }; - for e in c.effects.iter().take(end).skip(skip) { - (v, cov) = self.content_effect(e, c, v, cov); + for effect in chan_plan.effects.iter().take(end).skip(skip) { + (value, coverage) = self.content_effect(effect, chan_plan, value, coverage); } - (cov > 0.0).then_some((v, cov.min(1.0))) + (coverage > 0.0).then_some((value, coverage.min(1.0))) } /// Straight value and coverage of painted data of one channel (premultiplied values plus @@ -1962,37 +2205,36 @@ impl<'a, 'b> Texel<'a, 'b> { (v, cov.min(1.0)) } - /// Apply one content effect to a channel's straight value and coverage. - fn content_effect(&mut self, e: &EffectPlan, c: &ChanPlan, v: [f32; 3], cov: f32) -> ([f32; 3], f32) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + /// Apply one content effect to a channel's straight value and coverage + fn content_effect(&mut self, effect: &EffectPlan, chan_plan: &ChanPlan, value: [f32; 3], coverage: f32) -> ([f32; 3], f32) { + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (p, pc) = self.painted(e.data.as_deref(), c, e.preview); - over(c, e.blend, v, cov, p, pc * o) + let (painted, painted_coverage) = self.painted(effect.data.as_deref(), chan_plan, effect.preview); + over(chan_plan, effect.blend, value, coverage, painted, painted_coverage * opacity) } - EffectKind::Material(f) => match Channel::ALL.get(c.ch).and_then(|ch| f.sources.get(ch).map(|s| (*ch, s))) { - Some((ch, s)) => { - let p = self.source(s, &f.projection, ch.kind()); - let w = o * self.cover(f.sources.values(), &f.projection); - over(c, e.blend, v, cov, p, w) + EffectKind::Material(fill) => match Channel::ALL.get(chan_plan.ch).and_then(|ch| fill.sources.get(ch).map(|source| (*ch, source))) { + Some((ch, source)) => { + let place = FillPlace { fill, depth: effect.depth.as_deref(), covers_all: effect.covers_all }; + let (material_value, weight) = self.fill_place_texel(place, Some(source), ch); + over(chan_plan, effect.blend, value, coverage, material_value, weight * opacity) } - None => (v, cov), + None => (value, coverage), }, - EffectKind::Levels(l) => (mix3(v, per_unit(c.kind, v, |x| l.apply(x)), o), cov), - // Baked lighting reads the texel's normal and occlusion, and lights the base color only. - EffectKind::Filter(f @ Filter::BakedLighting { .. }) => match Channel::ALL.get(c.ch) { + // Baked lighting reads the texel's normal and occlusion, and lights the base color only + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let nrm = self.coords().nrm.to_array(); let k = f.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); (mix3(v, v.map(|x| (x * k).clamp(0.0, 1.0)), o), cov) } - _ => (v, cov), + _ => (value, coverage), }, - // Neighbourhood filters come precomputed through `ChanPlan::start`. - EffectKind::Filter(f) => (f.point(c.kind, v).map_or(v, |out| mix3(v, out, o)), cov), - // Anchors are recorded by `eval`; mask-only effects leave content as it is. + // Neighbourhood filters come precomputed through `ChanPlan::start` + EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), + // Anchors are recorded by `eval`; mask-only effects leave content as it is EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => { - (v, cov) + (value, coverage) } } } @@ -2625,12 +2867,10 @@ fn mask_tile<'a>( }) } -/// Tiles [`effect_histogram`] samples at most (a million texels). +/// Tiles [`effect_histogram`] samples at most (a million texels) const HISTOGRAM_TILES: usize = 256; -/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which -/// keeps the cost flat up to 8K. The stride is odd: a power of two would divide the row length -/// and sample the same few columns. +/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which keeps the cost flat up to 8K; the stride is odd, as a power of two would divide the row length and sample the same few columns fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> { let all = all_tiles(width, height); let stride = all.len().div_ceil(HISTOGRAM_TILES).max(1) | 1; @@ -2812,9 +3052,8 @@ mod tests { Fixture { project, mesh, gbuf, pixels: PixelStore::default(), baked: BakedMaps::default() } } - fn run(f: &Fixture, preview: Option<&StrokePreview>) -> Composite { - let images = Default::default(); - let inp = Inputs { + fn inputs<'a>(f: &'a Fixture, images: &'a ImageStore, preview: Option<&'a StrokePreview>) -> Inputs<'a> { + Inputs { project: &f.project, ts: 0, mesh: &f.mesh, @@ -2823,14 +3062,21 @@ mod tests { baked: &f.baked, block_scales: f.project.texture_sets[0].block_scales(), preview, - images: &images, + images, bounds: f.mesh.bounds(), - }; + } + } + + fn run_with_images(f: &Fixture, preview: Option<&StrokePreview>, images: &ImageStore) -> Composite { let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64); - composite_tiles(&inp, &mut out, &all_tiles(64, 64)); + composite_tiles(&inputs(f, images, preview), &mut out, &all_tiles(64, 64)); out } + fn run(f: &Fixture, preview: Option<&StrokePreview>) -> Composite { + run_with_images(f, preview, &ImageStore::default()) + } + #[test] fn procedural_resolution_uses_each_uv_tiles_scale() { let mut fixture = fixture(); @@ -2877,6 +3123,58 @@ mod tests { (0..3).all(|i| (a[i] - b[i]).abs() < 2e-4) } + thread_local! { + /// How many times a texel looked up its place on the surface on this thread + pub(super) static COORDS_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many times a texel worked out how much of it a fill covers on this thread + pub(super) static COVER_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// What `counter` counts while `fixture` composites, on one thread so the count sees every texel + fn count_while_compositing(counter: &'static std::thread::LocalKey>, fixture: &Fixture) -> usize { + let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap(); + pool.install(|| { + counter.with(|count| count.set(0)); + run(fixture, None); + counter.with(std::cell::Cell::get) + }) + } + + /// How many texels looked up their place on the surface while `fixture` composites + fn coords_lookups(fixture: &Fixture) -> usize { + count_while_compositing(&COORDS_LOOKUPS, fixture) + } + + #[test] + fn a_repeating_uniform_fill_covers_every_texel_without_looking_up_where_it_is() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + assert_eq!(coords_lookups(&f), 0, "a uniform fill that repeats needs no texel's place, as before fills could crop"); + + // Not repeating, it crops to its tile, so it has to know where each texel lands + let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; + fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(coords_lookups(&f) > 0); + } + + /// How many times a texel worked out a fill's coverage while `fixture` composites + fn cover_calls(fixture: &Fixture) -> usize { + count_while_compositing(&COVER_CALLS, fixture) + } + + #[test] + fn a_fill_covering_every_texel_is_decided_once_per_tile_not_per_texel() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + assert_eq!(cover_calls(&f), 0, "a repeating fill with nothing cropped or culled covers every texel, so no texel asks"); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [1.0, 0.0, 0.0])); + + // Not repeating, it crops to its tile, so each texel works its coverage out + let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; + fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(cover_calls(&f) > 0); + } + #[test] fn retained_filter_buffers_release_after_the_last_tile() { for resolution in [128, 512] { @@ -3026,7 +3324,11 @@ mod tests { 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], ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }, )); f.project.layer_mut(id).unwrap().mask = Some(mask); let out = run(&f, None); @@ -3076,7 +3378,11 @@ mod tests { let pattern = Procedural::new(ProceduralKind::Checker); mask.effects.push(Effect::new( effect, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }, )); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); @@ -3106,6 +3412,7 @@ mod tests { EffectKind::Fill { source: Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default(), + sampling: Default::default(), }, )); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); @@ -3172,11 +3479,16 @@ mod tests { 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, ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::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 }] { @@ -3199,7 +3511,10 @@ mod tests { 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() })); + mask.effects.push(Effect::new( + fixture.project.alloc_id(), + EffectKind::Fill { source: checker.clone(), projection: Projection::default(), sampling: Default::default() }, + )); for filter in filters { mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter.clone()))); } @@ -3318,7 +3633,8 @@ mod tests { let (mut fixture, layer) = ridge_fixture(100); let mut row_with = |blur: f32| { let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; - let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }); + let below = + Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }); let mut generator = ridge_generator(); generator.global.blur = blur; let mut lighten = generator_effect(&mut fixture, generator); @@ -3390,6 +3706,22 @@ mod tests { assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}"); } + #[test] + fn a_generator_input_image_reads_plain_bilinear_as_saved_projects_did() { + // Every fourth column white: a texel centre reads between two black columns, a mip level a quarter gray + const SIZE: u32 = 256; + let striped = (0..SIZE * SIZE).map(|i| if (i % SIZE).is_multiple_of(4) { [1.0; 4] } else { [0.0, 0.0, 0.0, 1.0] }).collect(); + let images: ImageStore = [("ao".to_string(), Arc::new(crate::store::ImageRes::new(SIZE, SIZE, striped, false)))].into_iter().collect(); + let mut generator = Generator::new(GeneratorKind::Dirt); + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("ao")); + let fixture = fixture(); + let inp = inputs(&fixture, &images, None); + + let read = Texel::new(&inp, 20, 20, 0, 0.0).generator_input(&generator, BakedMap::AmbientOcclusion); + + assert_eq!(read, Some(0.0)); + } + #[test] fn curvature_detail_noise_keeps_flat_areas_neutral() { let mut fixture = fixture(); @@ -3431,14 +3763,20 @@ mod tests { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); assert!(!stack_reads_neighbours(&f.project, 0)); + let mut mask = Mask::new(MaskBackground::White); let eid = f.project.alloc_id(); mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(stack_reads_neighbours(&f.project, 0)); + f.project.layer_mut(id).unwrap().mask = None; + assert!(!stack_reads_neighbours(&f.project, 0)); + content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0 })); + assert!(stack_reads_neighbours(&f.project, 0)); } @@ -3451,7 +3789,11 @@ mod tests { let (e1, e2) = (f.project.alloc_id(), f.project.alloc_id()); mask.effects.push(Effect::new( e1, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, + EffectKind::Fill { + source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }, )); f.project.layer_mut(id).unwrap().mask = Some(mask.clone()); let hard: Vec = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect(); @@ -3513,7 +3855,7 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [1.0, 0.0, 1.0])); assert!(close(out.value(Channel::Roughness, 5, 5), [0.8; 3])); - // Hidden effects are skipped and opacity fades an effect. + // Hidden effects are skipped and opacity fades an effect let fx = &mut f.project.layer_mut(id).unwrap().content_effects; fx[0].visible = false; fx[1].opacity = 0.5; @@ -3529,6 +3871,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::White); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5 }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.75; 3])); } @@ -3580,12 +3923,15 @@ soft {soft:?}" let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 })); let out = run(&f, None); let vals: Vec = (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| out.value(Channel::Roughness, x, y)[0]).collect(); + assert!(vals.iter().all(|v| (0.0..=1.0).contains(v))); assert!(vals.iter().filter(|v| **v > 0.5).count() > 64 && vals.iter().filter(|v| **v < 0.01).count() > 64, "{vals:?}"); + f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != edges); content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 })); let warped = run(&f, None); let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2)); + assert!(differs, "the warp moves the checker"); // Point filters @@ -3661,8 +4007,10 @@ soft {soft:?}" // Facing the light adds illumination; facing away keeps ambient only let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 }); assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}"); + let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 }); assert!(close(away, [0.2; 3]), "{away:?}"); + let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5 }; assert_eq!(f.baked_light([0.0, 1.0, 0.0], 0.2), Some(0.6), "half the occlusion"); assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); @@ -3711,19 +4059,8 @@ soft {soft:?}" assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3]), "channels without a source stay untouched"); // Flattening bakes in the content effects - let images = Default::default(); - let inp = Inputs { - project: &f.project, - ts: 0, - mesh: &f.mesh, - 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(), - }; + let images = ImageStore::default(); + let inp = inputs(&f, &images, None); let flat = flatten_layer(&inp, id, &all_tiles(64, 64)).unwrap(); assert!(flat.iter().all(|(c, _, _)| *c == Channel::Roughness)); let (_, _, data) = flat.iter().find(|(_, t, _)| *t == (0, 0)).unwrap(); @@ -3742,26 +4079,30 @@ soft {soft:?}" let top = fill_layer(&mut f.project, [1.0; 3], 0.5); let mut mask = Mask::new(MaskBackground::Black); let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(top).unwrap().mask = Some(mask.clone()); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // The field pre-pass reads anchors under blur, preserving flat height mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); f.project.layer_mut(top).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // An anchor above its reader is not evaluated yet, so it reads the channel default f.project.move_layer(low, 1).unwrap(); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } - /// A white fill layer on top whose mask reads `anchor` (any channel: a mask anchor is gray). + /// A white fill layer on top whose mask reads `anchor` (any channel: a mask anchor is gray) fn anchor_reader(fixture: &mut Fixture, anchor: LayerId) -> LayerId { let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); let mut mask = Mask::new(MaskBackground::Black); let source = Source::Anchor { anchor, channel: Channel::Roughness, ramp: Vec::new() }; - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); + mask.effects + .push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); fixture.project.layer_mut(top).unwrap().mask = Some(mask); top } @@ -3772,9 +4113,11 @@ soft {soft:?}" let low = fill_layer(&mut fixture.project, [0.0; 3], 0.5); let (gray, anchor, full) = (fixture.project.alloc_id(), fixture.project.alloc_id(), fixture.project.alloc_id()); let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(gray, EffectKind::Fill { source: Source::Uniform([0.4; 3]), projection: Projection::default() })); + mask.effects + .push(Effect::new(gray, EffectKind::Fill { source: Source::Uniform([0.4; 3]), projection: Projection::default(), sampling: Default::default() })); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); - mask.effects.push(Effect::new(full, EffectKind::Fill { source: Source::Uniform([1.0; 3]), projection: Projection::default() })); + mask.effects + .push(Effect::new(full, EffectKind::Fill { source: Source::Uniform([1.0; 3]), projection: Projection::default(), sampling: Default::default() })); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); anchor_reader(&mut fixture, anchor); @@ -3785,11 +4128,13 @@ soft {soft:?}" mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.4; 3]), "{color:?}"); // An empty paint layer still records its mask anchor for the layer above fixture.project.layer_mut(low).unwrap().kind = LayerKind::Paint; let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); } @@ -3802,13 +4147,17 @@ soft {soft:?}" let anchor = fixture.project.alloc_id(); let mut mask = Mask::new(MaskBackground::Black); let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() })); + mask.effects.push(Effect::new( + fixture.project.alloc_id(), + EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }, + )); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0 }))); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); fixture.project.layer_mut(lower).unwrap().mask = Some(mask.clone()); let reader = anchor_reader(&mut fixture, anchor); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let expected = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); + assert!(expected.iter().any(|value| *value > 0.1 && *value < 0.9), "the anchor records a softened checker"); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0 }))); @@ -3901,14 +4250,14 @@ soft {soft:?}" } } - #[test] - fn decal_fills_cover_only_their_frame_and_image_alpha() { - let mut f = fixture(); - let s = f.gbuf.surface(&f.mesh, 32 * 64 + 32).unwrap(); - let d = texturecraft_core::Decal { - center: s.pos.to_array(), - normal: s.nrm.to_array(), - up: s.nrm.any_orthonormal_vector().to_array(), + /// A fixture under a decal fill of image "decal" framed on the plane's middle, its projection changed by `change` + fn decal_fixture(change: impl FnOnce(&mut Fill)) -> Fixture { + let mut fixture = fixture(); + let surface = fixture.gbuf.surface(&fixture.mesh, 32 * 64 + 32).unwrap(); + let frame = texturecraft_core::Decal { + center: surface.pos.to_array(), + normal: surface.nrm.to_array(), + up: surface.nrm.any_orthonormal_vector().to_array(), size: [1.0, 1.0], rotation: 0.0, offset: [0.0; 2], @@ -3916,33 +4265,35 @@ soft {soft:?}" symmetry: None, flip: [false; 2], }; - let id = f.project.alloc_id(); - let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + let id = fixture.project.alloc_id(); + let mut fill = Fill { projection: Projection::decal(frame), ..Fill::default() }; fill.sources.insert(Channel::BaseColor, Source::image("decal")); - f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); - let composite = |alpha: f32| { - let img = crate::store::ImageRes { width: 2, height: 2, rgba: vec![[1.0, 0.0, 0.0, alpha]; 4], srgb: false }; - let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect(); - let inp = Inputs { - project: &f.project, - ts: 0, - mesh: &f.mesh, - 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(), - }; - let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64); - composite_tiles(&inp, &mut out, &all_tiles(64, 64)); - out - }; - let out = composite(1.0); - assert!(close(out.value(Channel::BaseColor, 32, 32), [1.0, 0.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 32, 32)); - assert!(close(out.value(Channel::BaseColor, 2, 2), [0.5; 3]), "outside the frame"); + change(&mut fill); + fixture.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + fixture + } + + /// `f` composited with `image` as its "decal" image + fn composite_with_decal(f: &Fixture, image: crate::store::ImageRes) -> Composite { + let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(image))].into_iter().collect(); + run_with_images(f, None, &images) + } + + /// Texels of a 64 x 64 composite whose base colour is not the fixture's grey + fn decal_texels(out: &Composite) -> Vec<[f32; 3]> { + (0..64 * 64).map(|i| out.value(Channel::BaseColor, i % 64, i / 64)).filter(|v| !close(*v, [0.5; 3])).collect() + } + + #[test] + fn decal_fills_cover_only_their_frame_and_image_alpha() { + let fixture = decal_fixture(|_| {}); + let composite = |alpha: f32| composite_with_decal(&fixture, crate::store::ImageRes::new(2, 2, vec![[1.0, 0.0, 0.0, alpha]; 4], false)); + + let opaque = composite(1.0); let half = composite(0.5); + + assert!(close(opaque.value(Channel::BaseColor, 32, 32), [1.0, 0.0, 0.0]), "{:?}", opaque.value(Channel::BaseColor, 32, 32)); + assert!(close(opaque.value(Channel::BaseColor, 2, 2), [0.5; 3]), "outside the frame"); assert!(close(half.value(Channel::BaseColor, 32, 32), [0.75, 0.25, 0.25]), "the image alpha shapes the decal"); } @@ -3955,17 +4306,12 @@ soft {soft:?}" let mut project = Project::new("t", "builtin:cube"); project.texture_sets.push(TextureSet::new("Cube", 0, 64)); let id = project.alloc_id(); - let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + let mut fill = Fill { projection: Projection::decal(d), ..Fill::default() }; fill.sources.insert(Channel::BaseColor, Source::image("decal")); project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); // Top left red, top right blue, bottom left green, bottom right yellow - let img = crate::store::ImageRes { - width: 2, - height: 2, - rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], - srgb: false, - }; + let img = crate::store::ImageRes::new(2, 2, vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], false); let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img.clone()))].into_iter().collect(); let pixels = PixelStore::default(); let baked = BakedMaps::default(); @@ -4131,19 +4477,19 @@ soft {soft:?}" flip: [false; 2], }; let id = f.project.alloc_id(); - let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + let mut fill = Fill { projection: Projection::decal(d), ..Fill::default() }; fill.sources.insert(Channel::BaseColor, Source::image("decal")); f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); // Left half red, right half blue - let img = crate::store::ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]], srgb: false }; + let img = crate::store::ImageRes::new(2, 1, vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]], false); let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect(); let texel = |f: &Fixture, flip: [bool; 2]| { let mut project = f.project.clone(); if let Ok(layer) = project.layer_mut(id) && let LayerKind::Fill(fill) = &mut layer.kind { - fill.projection = Projection::Decal(texturecraft_core::Decal { flip, ..d }); + fill.projection = Projection::decal(texturecraft_core::Decal { flip, ..d }); } let inp = Inputs { project: &project, @@ -4166,6 +4512,56 @@ soft {soft:?}" assert!(close(texel(&f, [false, true]), [1.0, 0.0, 0.0]), "Flip V leaves the left half"); } + #[test] + fn a_cropped_frames_image_alpha_turns_with_its_image() { + let f = decal_fixture(|fill| { + if let Projection::Planar { uv, .. } = &mut fill.projection { + uv.rotation = 180.0; + } + }); + + // Opaque red on the left half, see-through green on the right + let half = (0..8 * 8).map(|i| if i % 8 < 4 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0, 0.0] }).collect(); + let shown = decal_texels(&composite_with_decal(&f, crate::store::ImageRes::new(8, 8, half, false))); + + assert!(!shown.is_empty(), "the red half shows"); + assert!(shown.iter().all(|v| v[1] < 0.75), "the see-through green half stays hidden once turned (a seam texel blends some in): {shown:?}"); + } + + #[test] + fn a_shrunk_cropped_frames_coverage_averages_its_image_alpha_as_its_colour_does() { + let f = decal_fixture(|fill| fill.sampling.filtering = Filtering::BilinearHq); + + // Red columns a texel wide, opaque and see-through in turn, far finer than the frame's texels; not a power of two, so a full-size read lands anywhere between two columns + const SIZE: u32 = 1000; + let stripes = (0..SIZE * SIZE).map(|i| [1.0, 0.0, 0.0, if i % 2 == 0 { 1.0 } else { 0.0 }]).collect(); + let shown = decal_texels(&composite_with_decal(&f, crate::store::ImageRes::new(SIZE, SIZE, stripes, false))); + + assert!(!shown.is_empty(), "the frame shows"); + let half = [0.75, 0.25, 0.25]; + assert!( + shown.iter().all(|v| v.iter().zip(half).all(|(got, want)| (got - want).abs() < 0.05)), + "every texel is half covered, as its averaged stripes are: {shown:?}" + ); + } + + #[test] + fn a_cropped_frame_with_wrap_none_shows_one_image_however_it_tiles() { + let opaque = || crate::store::ImageRes::new(2, 2, vec![[1.0, 0.0, 0.0, 1.0]; 4], false); + let once = decal_texels(&composite_with_decal(&decal_fixture(|_| {}), opaque())).len(); + let tiled = decal_fixture(|fill| { + fill.sampling.wrap = texturecraft_core::UvWrap::None; + if let Projection::Planar { uv, .. } = &mut fill.projection { + uv.tiling = [2.0, 2.0]; + } + }); + + let quarter = decal_texels(&composite_with_decal(&tiled, opaque())).len(); + + assert!(once > 0, "the frame shows"); + assert!(quarter.abs_diff(once / 4) <= once / 16, "tiled twice with no wrap, one image fills a quarter of the frame: {quarter} of {once}"); + } + #[test] fn anchors_read_colors_as_gray_in_fill_layers() { let mut f = fixture(); @@ -4230,8 +4626,10 @@ soft {soft:?}" let low = fill_layer(&mut f.project, [0.0; 3], 0.5); let anchor = f.project.alloc_id(); let mut mask = Mask::new(MaskBackground::Black); - mask.effects - .push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source: Source::Uniform([gray; 3]), projection: Projection::default() })); + mask.effects.push(Effect::new( + f.project.alloc_id(), + EffectKind::Fill { source: Source::Uniform([gray; 3]), projection: Projection::default(), sampling: Default::default() }, + )); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); f.project.layer_mut(low).unwrap().mask = Some(mask); let id = f.project.alloc_id(); diff --git a/crates/compose/src/fill_copy.rs b/crates/compose/src/fill_copy.rs new file mode 100644 index 00000000..12753d28 --- /dev/null +++ b/crates/compose/src/fill_copy.rs @@ -0,0 +1,34 @@ +//! One copy of a symmetric fill's projection: the mirror or turn a texel samples it through + +use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; + +/// One copy of a fill's projection: a texel at a point shows what the projection gives at [`FillCopy::point`] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FillCopy { + turn: Mat3, + pivot: Vec3, + flip: [bool; 2], +} + +impl FillCopy { + /// A copy sampling the projection at `pivot + turn * (point - pivot)`, its image turned over across and down as `flip` says + pub fn new(turn: Mat3, pivot: Vec3, flip: [bool; 2]) -> FillCopy { + FillCopy { turn, pivot, flip } + } + + /// The surface point the projection is sampled at for a texel at world point `point` + pub fn point(&self, point: Vec3) -> Vec3 { + self.pivot + self.turn * (point - self.pivot) + } + + /// The normal the projection sees for a texel whose normal is `normal` + pub fn normal(&self, normal: Vec3) -> Vec3 { + self.turn * normal + } + + /// `uv` in the copy's image, turned over across and down as its Flip copy says + pub fn uv(&self, uv: Vec2) -> Vec2 { + let [across, down] = self.flip; + Vec2::new(if across { 1.0 - uv.x } else { uv.x }, if down { 1.0 - uv.y } else { uv.y }) + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 39b00656..25548ab5 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)] +pub mod axis_frame; mod baked_maps; pub mod below; mod curvature_size_level; @@ -14,24 +15,33 @@ pub mod curvature_sizes; pub mod display; pub mod eval; mod fabric; +pub mod fill_copies; +pub mod fill_copy; +mod fill_place; +pub mod frame_placement; mod fur_lock; mod held_fields; mod image_identity; +pub mod mip_level; mod organic; pub mod pattern; mod pattern_context; +pub mod projector_cover; +pub mod projector_depth; +pub mod projector_view; pub mod solo; pub mod store; pub mod thumb; +pub mod tile_length; mod tile_pattern; mod tile_random_stream; mod timber; +pub mod warp; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use eval::{ - BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, - effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, + covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; pub use pattern_context::PatternContext; pub use solo::solo_project; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 1370c0c0..43d9b19a 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -2,10 +2,13 @@ //! maps. Everything is copy-on-write, so cloning the store for undo is cheap. use std::collections::HashMap; +use std::sync::OnceLock; -use texturecraft_core::{Channel, ChannelKind, LayerId}; +use texturecraft_core::{Channel, ChannelKind, Filtering, LayerId, Sampling}; use texturecraft_texel::{TileImage, from_u16, from_u16_signed}; +use crate::mip_level::MipLevel; + /// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per /// component (height stored signed). #[derive(Clone, Debug, Default)] @@ -66,16 +69,54 @@ pub struct ImageRes { pub rgba: Vec<[f32; 4]>, /// 8/16-bit images are sRGB-encoded; color channels linearize them. pub srgb: bool, + /// Halved copies of the image, built on first use by [`Filtering::BilinearHq`] + pub mips: OnceLock>, } /// Image resources by name. pub type ImageStore = HashMap>; +/// Image levels below the full image at most: a 64k image halves 16 times to 1 texel +const MAX_MIP_LEVELS: usize = 16; + +/// Texel (`x`, `y`) of `rgba`; an axis that does not `repeat` (across, down) stops at its edge +pub(crate) fn texel_of(rgba: &[[f32; 4]], width: u32, height: u32, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] { + let (w, h) = (width.max(1) as i64, height.max(1) as i64); + let x = if repeat.0 { x.rem_euclid(w) } else { x.clamp(0, w - 1) }; + let y = if repeat.1 { y.rem_euclid(h) } else { y.clamp(0, h - 1) }; + let i = (y * w + x) as usize; + rgba.get(i).copied().unwrap_or([0.0; 4]) +} + +/// Bilinear sample of `rgba` (texture coordinates, v down), wrapping around on the axes that `repeat` +fn bilinear(rgba: &[[f32; 4]], width: u32, height: u32, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] { + // Texel centres sit half a texel in from the texel's corner + let texel_x = u * width as f32 - 0.5; + let texel_y = v * height as f32 - 0.5; + let (left, top) = (texel_x.floor() as i64, texel_y.floor() as i64); + let (across, down) = (texel_x - texel_x.floor(), texel_y - texel_y.floor()); + + // A huge coordinate saturates to the last texel instead of overflowing past it + let (right, bottom) = (left.saturating_add(1), top.saturating_add(1)); + let texel = |x, y| texel_of(rgba, width, height, x, y, repeat); + let (top_left, top_right) = (texel(left, top), texel(right, top)); + let (bottom_left, bottom_right) = (texel(left, bottom), texel(right, bottom)); + let mut blended = [0.0; 4]; + for k in 0..4 { + let upper = top_left[k] + (top_right[k] - top_left[k]) * across; + let lower = bottom_left[k] + (bottom_right[k] - bottom_left[k]) * across; + blended[k] = upper + (lower - upper) * down; + } + blended +} + impl ImageRes { - fn texel(&self, x: i64, y: i64) -> [f32; 4] { - let (w, h) = (self.width.max(1) as i64, self.height.max(1) as i64); - let i = (y.rem_euclid(h) * w + x.rem_euclid(w)) as usize; - self.rgba.get(i).copied().unwrap_or([0.0; 4]) + pub fn new(width: u32, height: u32, rgba: Vec<[f32; 4]>, srgb: bool) -> ImageRes { + ImageRes { width, height, rgba, srgb, mips: OnceLock::new() } + } + + fn texel(&self, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] { + texel_of(&self.rgba, self.width, self.height, x, y, repeat) } /// Bilinear sample with wrap-around (texture coordinates, v down). @@ -83,17 +124,144 @@ impl ImageRes { if !u.is_finite() || !v.is_finite() { return [0.0; 4]; } - let fx = u * self.width as f32 - 0.5; - let fy = v * self.height as f32 - 0.5; - let (x0, y0) = (fx.floor() as i64, fy.floor() as i64); - let (tx, ty) = (fx - fx.floor(), fy - fy.floor()); - let (a, b, c, d) = (self.texel(x0, y0), self.texel(x0 + 1, y0), self.texel(x0, y0 + 1), self.texel(x0 + 1, y0 + 1)); - let mut out = [0.0; 4]; - for k in 0..4 { - let top = a[k] + (b[k] - a[k]) * tx; - let bot = c[k] + (d[k] - c[k]) * tx; - out[k] = top + (bot - top) * ty; + bilinear(&self.rgba, self.width, self.height, u, v, (true, true)) + } + + /// The texel under (`u`, `v`), on the axes that do not `repeat` the edge texel past the edge + fn nearest(&self, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] { + self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat) + } + + /// The halved levels, built the first time they are asked for + fn mips(&self) -> &[MipLevel] { + self.mips.get_or_init(|| { + let mut levels: Vec = Vec::new(); + let (mut w, mut h) = (self.width, self.height); + while (w > 1 || h > 1) && levels.len() < MAX_MIP_LEVELS { + let next = match levels.last() { + Some(level) => MipLevel::halve(&level.rgba, level.width, level.height), + None => MipLevel::halve(&self.rgba, w, h), + }; + (w, h) = (next.width, next.height); + levels.push(next); + } + levels + }) + } + + /// Sample at (`u`, `v`) with `sampling`; `footprint` = image texels per surface texel (1 or less = not shrunk) + pub fn sample_filtered(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> [f32; 4] { + if !u.is_finite() || !v.is_finite() { + return [0.0; 4]; + } + + let repeat = sampling.wrap.repeats(); + let full = |u: f32, v: f32| bilinear(&self.rgba, self.width, self.height, u, v, repeat); + match sampling.filtering { + Filtering::Nearest => self.nearest(u, v, repeat), + Filtering::BilinearSharp => full(u, v), + Filtering::BilinearHq => { + // Not shrunk: the full image alone, without building mips it does not read + if !(footprint.is_finite() && footprint > 1.0) { + return full(u, v); + } + + let lod = footprint.log2(); + + // Level 0 is the full image, level n the nth mip (the smallest past the last) + let mips = self.mips(); + let level = |index: usize| match index.checked_sub(1) { + None => full(u, v), + Some(mip_index) => { + mips.get(mip_index).or(mips.last()).map_or_else(|| full(u, v), |mip| bilinear(&mip.rgba, mip.width, mip.height, u, v, repeat)) + } + }; + let finer_level = lod.floor() as usize; + let toward_coarser = lod - lod.floor(); + let finer = level(finer_level); + if toward_coarser <= 0.0 { + return finer; + } + + let coarser = level(finer_level + 1); + [0, 1, 2, 3].map(|component| finer[component] + (coarser[component] - finer[component]) * toward_coarser) + } } - out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::UvWrap; + + #[test] + fn a_huge_texture_coordinate_samples_without_overflowing() { + let image = ImageRes::new(2, 2, vec![[0.5; 4]; 4], false); + + let sampled = image.sample(1e30, -1e30); + + assert_eq!(sampled, [0.5; 4]); + } + + /// A 4 × 1 image of columns 0, 1, 2, 3 + fn ramp() -> ImageRes { + ImageRes::new(4, 1, (0..4).map(|column| [column as f32; 4]).collect(), false) + } + + fn sampling(filtering: Filtering, wrap: UvWrap) -> Sampling { + Sampling { filtering, wrap, ..Sampling::default() } + } + + #[test] + fn nearest_reads_the_texel_under_the_point_and_wraps_or_stops_at_the_edge() { + let image = ramp(); + + let inside = image.sample_filtered(0.6, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0); + let wrapped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0); + let stopped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::None), 1.0); + + assert_eq!(inside, [2.0; 4]); + assert_eq!(wrapped, [0.0; 4], "past the right edge a repeating image starts again"); + assert_eq!(stopped, [3.0; 4], "past the right edge a single image keeps its last column"); + } + + #[test] + fn a_bilinear_read_past_a_single_images_edge_blends_no_far_side_texel() { + let image = ramp(); + + let repeating = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::Repeat), 1.0); + let single = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::None), 1.0); + + assert!(repeating[0] < 3.0, "the far side's 0 blends in: {repeating:?}"); + assert_eq!(single, [3.0; 4]); + } + + #[test] + fn high_quality_bilinear_reads_the_mip_the_footprint_asks_for() { + let image = ramp(); + let hq = sampling(Filtering::BilinearHq, UvWrap::Repeat); + + let full = image.sample_filtered(0.375, 0.5, hq, 1.0); + let halved = image.sample_filtered(0.25, 0.5, hq, 2.0); + let quartered = image.sample_filtered(0.375, 0.5, hq, 4.0); + let past_the_last = image.sample_filtered(0.375, 0.5, hq, 64.0); + let between = image.sample_filtered(0.875, 0.5, hq, 2.0_f32.sqrt()); + + assert_eq!(full, [1.0; 4], "a footprint of 1 reads the full image at column 1's centre"); + assert_eq!(halved, [0.5; 4], "level 1's first texel averages columns 0 and 1"); + assert_eq!(quartered, [1.5; 4], "a 1-texel level holds the mean"); + assert_eq!(past_the_last, quartered, "a footprint past the last level reads the last one"); + assert!(between[0] > 2.0 && between[0] < 3.0, "half a level blends the full image's 3 and level 1's 2: {between:?}"); + } + + #[test] + fn an_unshrunk_high_quality_read_builds_no_mips() { + let image = ramp(); + + let full = image.sample_filtered(0.375, 0.5, sampling(Filtering::BilinearHq, UvWrap::Repeat), 1.0); + + assert_eq!(full, [1.0; 4]); + assert!(image.mips.get().is_none(), "a footprint of 1 reads only the full image"); } } diff --git a/crates/compose/src/tile_pattern.rs b/crates/compose/src/tile_pattern.rs index c756072f..2fcaf208 100644 --- a/crates/compose/src/tile_pattern.rs +++ b/crates/compose/src/tile_pattern.rs @@ -599,7 +599,7 @@ mod tests { fn halves(left: f32, right: f32) -> std::sync::Arc { let size = 8; let rgba = (0..size * size).map(|texel| if texel % size < size / 2 { [left, left, left, 1.0] } else { [right, right, right, 1.0] }).collect(); - std::sync::Arc::new(ImageRes { width: size as u32, height: size as u32, rgba, srgb: false }) + std::sync::Arc::new(ImageRes::new(size as u32, size as u32, rgba, false)) } #[test] diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 08f971be..406d8480 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -77,7 +77,10 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { let l = Layer::new(inner, "inner", fill(&[(Channel::Metallic, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), &Channel::DEFAULT_SET); f.project.insert_layer(0, l, Some(group), true).unwrap(); let mut blurred = Mask::new(MaskBackground::Black); - blurred.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + blurred.effects.push(effect( + f, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 }))); let top = add(f, 0, LayerKind::Paint, Some(blurred)); let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES)); @@ -203,7 +206,7 @@ fn mask_with_height_follows_the_layer_height() { let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3], ramp: Vec::new() }; let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None); let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() })); + mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(id).unwrap().mask = Some(mask); let plain = reference(&f, 0); f.project.layer_mut(id).unwrap().height_mask = HeightMask { enabled: true, contrast: 1.0, offset: 0.0 }; @@ -290,7 +293,10 @@ fn nested_stack(f: &mut Fixture) -> Nested { let inner = put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None); let mut checker = Mask::new(MaskBackground::Black); - checker.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default() })); + checker.effects.push(effect( + f, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); let g2 = group(f, Some(g1), BlendMode::Passthrough, 1.0, Some(checker)); let mask = generator_mask(f, GeneratorKind::Direction, Some(16.0)); put(f, 0, Some(g2), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), Some(mask)); @@ -412,7 +418,7 @@ fn anchor_readers_fall_back_to_full_evaluation() { f.project.layer_mut(n.base).unwrap().content_effects.push(anchor); // A mask above the hot layer reads the stack below it - let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default() }); + let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() }); f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(reader); for hot in [n.deep, n.top] { assert!(check_cached(&f, 0, hot).is_empty(), "anchors read the stack: nothing cached"); @@ -556,7 +562,10 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { None, ); let mut slope = Mask::new(MaskBackground::Black); - slope.effects.push(effect(&mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + slope.effects.push(effect( + &mut f, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 }))); let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope)); let top = add(&mut f, 0, LayerKind::Paint, None); @@ -685,7 +694,10 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { // Pattern detail exposes any missing blur field let mut blurred = Mask::new(MaskBackground::Black); - blurred.effects.push(effect(&mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() })); + blurred.effects.push(effect( + &mut fixture, + EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, + )); blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred)); @@ -762,7 +774,7 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() { pattern.tile.get_or_insert_with(Box::default).background_image = Some("plate".into()); fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); - let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)); let mut images = ImageStore::default(); let baked = Default::default(); let tiles = all_tiles(RES, RES); @@ -800,7 +812,7 @@ fn cached_stack_tracks_referenced_images_only() { let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") }; fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() }); - let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)); let mut images = ImageStore::default(); let baked = Default::default(); let tiles = all_tiles(RES, RES); @@ -860,7 +872,7 @@ fn generator_input_image_changes_invalidate_stack_key() { *generator = Generator::new(GeneratorKind::Dirt); generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used")); - let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let image = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)); let mut images = ImageStore::default(); images.insert("used".into(), image(0.1)); let baked = Default::default(); @@ -869,13 +881,16 @@ fn generator_input_image_changes_invalidate_stack_key() { let original = key(&images); images.insert("unrelated".into(), image(0.5)); + assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged"); let old_image = Arc::downgrade(&images["used"]); images.insert("used".into(), image(0.9)); + assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels"); assert!(key(&images) != original, "replacing a generator input must invalidate the cache"); images.remove("used"); + assert!(key(&images) != original, "removing a generator input must invalidate the cache"); } diff --git a/crates/core/src/backface.rs b/crates/core/src/backface.rs new file mode 100644 index 00000000..7e312fca --- /dev/null +++ b/crates/core/src/backface.rs @@ -0,0 +1,23 @@ +//! Backface culling of planar and cylindrical projections + +use serde::{Deserialize, Serialize}; + +/// Faces turned more than `angle` degrees from the projection get none of it, faded softer as `hardness` drops +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Backface { + pub on: bool, + pub angle: f32, + pub hardness: f32, +} + +impl Backface { + /// The angle culling may take, in degrees from facing the projector + pub const ANGLE_RANGE: std::ops::RangeInclusive = 0.0..=180.0; +} + +impl Default for Backface { + fn default() -> Self { + Backface { on: false, angle: 90.0, hardness: 0.5 } + } +} diff --git a/crates/core/src/depth_culling.rs b/crates/core/src/depth_culling.rs new file mode 100644 index 00000000..31038f83 --- /dev/null +++ b/crates/core/src/depth_culling.rs @@ -0,0 +1,23 @@ +//! Depth culling of planar and warp projections + +use serde::{Deserialize, Serialize}; + +/// Surfaces hidden from the projector behind other surfaces get none of the projection, faded softer as `hardness` drops +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct DepthCulling { + pub on: bool, + pub hardness: f32, +} + +impl DepthCulling { + /// What a new planar or warp projection starts with + pub const NEW: DepthCulling = DepthCulling { on: true, hardness: 0.75 }; +} + +impl Default for DepthCulling { + /// Off, as for every projection saved before depth culling existed + fn default() -> Self { + DepthCulling { on: false, ..DepthCulling::NEW } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ec27f3cb..3797e2a5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -7,15 +7,27 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod backface; pub mod bake; pub mod blend; mod block_scales; pub mod channel; +pub mod depth_culling; mod env_alignment; +pub mod fill_symmetry; pub mod layer; pub mod project; +pub mod projector; +mod saved_decal; +mod saved_projection; mod shadow_mode; +pub mod shape_crop; +pub mod symmetry_kind; +/// A full turn, in degrees +pub const FULL_TURN_DEGREES: f32 = 360.0; + +pub use backface::Backface; pub use bake::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, @@ -25,16 +37,19 @@ pub use bake::{ }; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use depth_culling::DepthCulling; +pub use fill_symmetry::FillSymmetry; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, - PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, - TileSymmetry, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, + GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; +pub use projector::Projector; +pub use shape_crop::ShapeCrop; +pub use symmetry_kind::SymmetryKind; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum CoreError { diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ce14606b..7bbb1aa5 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -314,6 +314,14 @@ pub struct DisplaySettings { pub ior: f32, /// Depth of field of the viewport and the path tracer (thin lens). pub dof: DepthOfField, + /// The selected fill's projection gizmos show in the 3D view (the Projection row's eye) + #[serde(skip_serializing_if = "is_shown")] + pub projection_gizmos: bool, +} + +/// Whether a view flag is at its default, shown (saved projects then stay as they were) +fn is_shown(shown: &bool) -> bool { + *shown } /// A thin-lens camera's depth of field (Display settings: focus distance and aperture). @@ -403,6 +411,7 @@ impl Default for DisplaySettings { scatter_radius: 0.1, ior: 1.5, dof: DepthOfField::default(), + projection_gizmos: true, } } } @@ -816,12 +825,13 @@ mod tests { let mut top = paint(&mut p, "y"); let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; top.mask = Some(Mask { - effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })], + effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })], ..Mask::new(MaskBackground::Black) }); p.insert_layer(0, top, Some(id), false).unwrap(); let json = serde_json::to_string(&p).unwrap(); let back: Project = serde_json::from_str(&json).unwrap(); + assert_eq!(back, p); assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id)); diff --git a/crates/core/src/projector.rs b/crates/core/src/projector.rs new file mode 100644 index 00000000..ba0b5459 --- /dev/null +++ b/crates/core/src/projector.rs @@ -0,0 +1,40 @@ +//! The 3D projection settings shared by tri-planar, planar, spherical and cylindrical projections + +use serde::{Deserialize, Serialize}; + +use crate::{Backface, DepthCulling, ShapeCrop}; + +/// Rotation (degrees about X, then Y, then Z) and per-axis scale of a 3D projection's shape; default = unchanged +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Projector { + pub rotation: [f32; 3], + pub scale: [f32; 3], + pub crop: ShapeCrop, + pub backface: Backface, + /// Planar and warp projections only + pub depth: DepthCulling, +} + +impl Default for Projector { + fn default() -> Self { + Projector { rotation: [0.0; 3], scale: [1.0; 3], crop: ShapeCrop::default(), backface: Backface::default(), depth: DepthCulling::default() } + } +} + +impl Projector { + /// The settings a new planar or warp projection starts with: depth culled + pub fn depth_culled() -> Projector { + Projector { depth: DepthCulling::NEW, ..Projector::default() } + } + + /// Whether it is the default, which projections saved before it existed load as (not saved then) + pub fn is_default(&self) -> bool { + *self == Projector::default() + } + + /// Whether it turns or stretches the projection at all + pub fn turns(&self) -> bool { + self.rotation != [0.0; 3] || self.scale != [1.0; 3] + } +} diff --git a/crates/core/src/saved_projection.rs b/crates/core/src/saved_projection.rs new file mode 100644 index 00000000..d748ed02 --- /dev/null +++ b/crates/core/src/saved_projection.rs @@ -0,0 +1,30 @@ +//! Reading and writing saved projections, including decals in the shape saved before they were planar projections placed on the surface + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::saved_decal::SavedDecal; +use crate::{Decal, Projection}; + +/// A projection as saved: today's, or a decal from before decals were planar projections +#[derive(Deserialize)] +enum SavedProjection { + Decal(Decal), + #[serde(untagged)] + Current(Projection), +} + +/// Serde hook for projection fields: an older decal loads as the planar projection that looks the same +pub(crate) fn load<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(match SavedProjection::deserialize(deserializer)? { + SavedProjection::Decal(frame) => Projection::decal(frame), + SavedProjection::Current(projection) => projection, + }) +} + +/// Serde hook for projection fields: a planar projection with a decal's look saves as a decal, so earlier versions still read a decal +pub(crate) fn save(projection: &Projection, serializer: S) -> Result { + match projection { + Projection::Planar { placed: Some(frame), .. } if *projection == Projection::decal(*frame) => SavedDecal::Decal(frame).serialize(serializer), + _ => projection.serialize(serializer), + } +} diff --git a/crates/core/src/shape_crop.rs b/crates/core/src/shape_crop.rs new file mode 100644 index 00000000..d0be4dd2 --- /dev/null +++ b/crates/core/src/shape_crop.rs @@ -0,0 +1,27 @@ +//! How far a 3D projection reaches past its shape + +use serde::{Deserialize, Serialize}; + +/// Whether a projection reaches past its shape (planar frame, tri-planar box, sphere, cylinder) +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum ShapeCrop { + #[default] + ExtendsOutside, + Cropped, +} + +impl ShapeCrop { + pub const ALL: [ShapeCrop; 2] = [ShapeCrop::Cropped, ShapeCrop::ExtendsOutside]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + ShapeCrop::ExtendsOutside => "extendsOutside", + ShapeCrop::Cropped => "cropped", + } + } + + pub fn from_id(id: &str) -> Option { + ShapeCrop::ALL.into_iter().find(|crop| crop.id() == id) + } +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index b0e5332f..32451af5 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -111,6 +111,7 @@ pub fn command_specs() -> &'static [CommandSpec] { let mut v = Vec::new(); v.extend(crate::view_cmds::edit_specs()); v.extend(crate::layer_cmds::specs()); + v.extend(crate::fill_reset_cmds::specs()); v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); @@ -142,6 +143,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::smart_masks::specs()); v.extend(crate::filter_lib::specs()); v.extend(crate::decal_cmds::specs()); + v.extend(crate::warp_cmds::specs()); v.extend(crate::text_cmds::specs()); v }) diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 45aace1c..2430b0dd 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -151,7 +151,7 @@ fn mat_finish(id: &str) -> Option { }; let pattern = Procedural { scale, ..Procedural::new(kind) }; - let mut fill = Fill { projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, ..Fill::default() }; + let mut fill = Fill { projection: Projection::triplanar(), ..Fill::default() }; fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3], ramp: Vec::new() }); fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3], ramp: Vec::new() }); Some(fill) diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 8fb0a3d8..f1c82a32 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, Generator, Layer, LayerKind, NormalFormat, Projection, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Sampling, Source}; use crate::Session; use crate::session::StackTarget; @@ -11,19 +11,20 @@ fn source_json(source: &Source) -> Value { match source { Source::Uniform(value) => json!({ "uniform": value }), Source::Procedural { pattern, low, high, ramp } => { - let mut report = json!({ - "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high + let mut out = json!({ + "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, + "balance": pattern.balance, "invert": pattern.invert, "low": low, "high": high }); if !pattern.resolution.is_default() { - report["resolution"] = + out["resolution"] = json!({ "mode": format!("{:?}", pattern.resolution.mode), "custom": pattern.resolution.custom, "factor": pattern.resolution.factor }); } if let Some(tile) = &pattern.tile { - report["tile"] = crate::procedural_params::tile_report(tile); + out["tile"] = crate::procedural_params::tile_report(tile); } - with_ramp(report, ramp) + with_ramp(out, ramp) } Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }), Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }), @@ -31,29 +32,38 @@ fn source_json(source: &Source) -> Value { } } -/// `v` with the gradient map stops of its source as `colors`, when it has any. -fn with_ramp(mut v: Value, ramp: &[[f32; 3]]) -> Value { +/// `out` with the gradient map stops of its source as `colors`, when it has any +fn with_ramp(mut out: Value, ramp: &[[f32; 3]]) -> Value { if !ramp.is_empty() { - v["colors"] = json!(ramp); + out["colors"] = json!(ramp); } - v + out } -fn fill_json(f: &Fill) -> Value { - let mut v = json!({ - "projection": f.projection.label(), - "sources": f.sources.iter().map(|(c, s)| (c.id().to_string(), source_json(s))).collect::>(), - }); - if let Projection::Decal(d) = &f.projection { - v["decal"] = json!(d); +fn fill_json(fill: &Fill) -> Value { + let sources = fill.sources.iter().map(|(channel, source)| (channel.id().to_string(), source_json(source))); + let mut out = json!({ "sources": sources.collect::>() }); + placement_json(&fill.projection, &fill.sampling, &mut out); + if let Some(link) = &fill.link { + out["link"] = json!(link); } - if let Some(link) = &f.link { - v["link"] = json!(link); - } - v + out } -/// A mask or content (`content`) effect. +/// Where a fill lands and how it reads its sources: the projection, its frame when placed on the surface, and the sampling +fn placement_json(projection: &Projection, sampling: &Sampling, out: &mut Value) { + out["projection"] = json!(projection.label()); + out["projectionSettings"] = json!(projection); + out["filtering"] = json!(sampling.filtering.id()); + out["wrap"] = json!(sampling.wrap.id()); + out["scaleMode"] = json!(sampling.scale.id()); + out["symmetry"] = json!(sampling.symmetry); + if let Some(frame) = projection.placed() { + out["decal"] = json!(frame); + } +} + +/// A mask or content (`content`) effect 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()); @@ -74,7 +84,10 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { } 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::Fill { source, projection, sampling } => { + out["source"] = source_json(source); + placement_json(projection, sampling, &mut out); + } EffectKind::Material(fill) => out["fill"] = fill_json(fill), EffectKind::Filter(filter) => { out["filter"] = json!(filter); @@ -89,7 +102,7 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { out } -/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them. +/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail 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, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast }); if !generator.resolution.is_default() { @@ -160,7 +173,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { v } -/// The layer stack of texture set `ts`, top → bottom (as displayed). +/// The layer stack of texture set `ts`, top → bottom (as displayed) pub fn stack(s: &Session, ts: usize) -> Value { let Some(set) = s.doc.project.texture_sets.get(ts) else { return Value::Null }; json!(set.stack.iter().rev().filter_map(|id| s.doc.project.layers.get(id)).map(|l| layer_json(s, l, 0)).collect::>()) @@ -201,7 +214,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { }) } -/// The whole session. +/// The whole session pub fn session(session: &Session) -> Value { let texture_set = session.ts(); json!({ diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 56d2fc2e..4c8b209f 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -13,6 +13,23 @@ use crate::commands::{ use crate::layer_selection::{batch_param, ids_json}; use crate::{EngineError, Result, Session, cmd, session::StackTarget}; +/// One full turn, in degrees (the brush's, so every angle wraps on the same turn) +pub(crate) use texturecraft_paint::FULL_TURN_DEGREES; + +/// The smallest scale or tiling a fill's placement takes +pub const MIN_SCALE: f32 = 0.001; +/// The largest scale, tiling or offset a fill's placement takes +pub const MAX_PLACEMENT: f32 = 1000.0; + +/// The command [`fill_set`] runs as +const FILL_SET: &str = "layer.fill.set"; + +/// How far a warp's corner may be pulled from the frame's centre, in frame sizes +const MAX_CORNER_REACH: f32 = 100.0; + +/// The largest Projection Depth, in lengths of the frame's longer side +pub(crate) const MAX_PROJECTION_DEPTH: f32 = 100.0; + pub fn specs() -> Vec { vec![ cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint), @@ -491,15 +508,7 @@ fn blending_set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's -/// (`effect`). -#[derive(Clone, Copy)] -enum FillTarget { - Layer(LayerId), - Effect(LayerId), -} - -fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { +pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { match u64p(p, "effect").map(LayerId) { Some(e) => match s.doc.project.effect(e) { Some((_, x)) if matches!(x.kind, EffectKind::Material(_)) => Ok(FillTarget::Effect(e)), @@ -509,44 +518,49 @@ fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { } } -fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { +pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { match target { FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind { LayerKind::Fill(f) => Ok(f), _ => Err(EngineError::Other("not a fill layer".into())), }, - FillTarget::Effect(e) => match s.doc.project.effect_mut(e).map(|x| &mut x.kind) { + FillTarget::Effect(effect) => match s.doc.project.effect_mut(effect).map(|found| &mut found.kind) { Some(EffectKind::Material(f)) => Ok(f), _ => Err(EngineError::Other("not a content fill effect".into())), }, } } +/// How the fill at `target` is projected and sampled: every fill has both +pub(crate) fn placement_mut(s: &mut Session, target: FillTarget) -> Result<(&mut Projection, &mut Sampling)> { + let fill = fill_mut(s, target)?; + Ok((&mut fill.projection, &mut fill.sampling)) +} + fn fill_set(session: &mut Session, params: &Value) -> Result { - const CMD: &str = "layer.fill.set"; - let target = fill_target(session, params, CMD)?; - let channel = channel_param(CMD, params, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?; + let target = fill_target(session, params, FILL_SET)?; + let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off let solo = boolp(params, "solo") == Some(true); let enabled = if solo { Some(true) } else { boolp(params, "enabled") }; - let normal_format = normal_format_param(CMD, params)?; + let normal_format = normal_format_param(FILL_SET, params)?; let colors = ramp_param(params, channel)?; let init_ramp = boolp(params, "gradientMap") == Some(true); if init_ramp && colors.is_some() { - return Err(bad(CMD, "give `gradientMap` or `colors`, not both")); + return Err(bad(FILL_SET, "give `gradientMap` or `colors`, not both")); } let source = fill_source_from(session, params, (target, channel), normal_format)?; if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp { return Err(bad( - CMD, + FILL_SET, "give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`", )); } if normal_format.is_some() && source.as_ref().is_some_and(|source| !matches!(source, Source::Image { .. })) { - return Err(bad(CMD, "`normalFormat` goes with `image` or alone")); + return Err(bad(FILL_SET, "`normalFormat` goes with `image` or alone")); } // Changing only the normal format or gradient stops leaves the layer channel on or off @@ -558,7 +572,7 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { if let (None, Some(format)) = (&source, normal_format) { match fill.sources.get_mut(&channel) { Some(Source::Image { normal_format, .. }) => *normal_format = format, - _ => return Err(bad(CMD, "`normalFormat` needs an image on the channel")), + _ => return Err(bad(FILL_SET, "`normalFormat` needs an image on the channel")), } } @@ -601,6 +615,18 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { Ok(Value::Null) } +/// The procedural source `params` ask for with `low`/`high` already parsed: a pattern of the same kind as `current` keeps what `params` do not give; another kind starts from its defaults +fn procedural_from(params: &Value, kind: ProceduralKind, current: Option<&Source>, [low, high]: [Option<[f32; 3]>; 2]) -> Result { + let (mut pattern, current_low, current_high) = match current { + Some(Source::Procedural { pattern, low, high, .. }) if pattern.kind == kind => (pattern.clone(), *low, *high), + _ => (Procedural::new(kind), [0.0; 3], [1.0; 3]), + }; + + crate::procedural_params::pattern_basics_from(params, &mut pattern); + crate::procedural_params::pattern_settings_from(FILL_SET, params, &mut pattern)?; + Ok(Source::Procedural { pattern, low: low.unwrap_or(current_low), high: high.unwrap_or(current_high), ramp: Vec::new() }) +} + /// The source `params` give fill channel `channel` of `target`, or None when they only switch it or set its image's normal format fn fill_source_from( session: &mut Session, @@ -608,27 +634,15 @@ fn fill_source_from( (target, channel): (FillTarget, Channel), normal_format: Option, ) -> Result> { - const CMD: &str = "layer.fill.set"; - let low = color_param(CMD, params, "low")?.unwrap_or([0.0; 3]); - let high = color_param(CMD, params, "high")?.unwrap_or([1.0; 3]); - let uniform = color_param(CMD, params, "color")?.or(color_param(CMD, params, "value")?); + let low = color_param(FILL_SET, params, "low")?; + let high = color_param(FILL_SET, params, "high")?; + let uniform = color_param(FILL_SET, params, "color")?.or(color_param(FILL_SET, params, "value")?); if let Some(name) = strp(params, "procedural") { - let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?; - let mut pattern = Procedural::new(kind); - crate::procedural_params::pattern_basics_from(params, &mut pattern); - - // A pattern of the same kind keeps its resolution and Tile Generator settings - let current = fill_mut(session, target)?.sources.get(&channel); - if let Some(Source::Procedural { pattern: current, .. }) = current - && current.kind == kind - { - pattern.resolution = current.resolution; - pattern.tile = current.tile.clone(); - } - - crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; - return Ok(Some(Source::Procedural { pattern, low, high, ramp: Vec::new() })); + let kind = ProceduralKind::parse(name).ok_or_else(|| bad(FILL_SET, format!("unknown procedural `{name}`")))?; + // A pattern of the same kind keeps what `params` do not give; another kind starts from its defaults + let current = fill_mut(session, target)?.sources.get(&channel).cloned(); + return Ok(Some(procedural_from(params, kind, current.as_ref(), [low, high])?)); } if let Some(color) = uniform { @@ -644,9 +658,9 @@ fn fill_source_from( FillTarget::Layer(id) => Some(id), FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), }; - let reader = reader.ok_or_else(|| bad(CMD, "the fill is not in a layer"))?; - let anchor_channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(channel); - return Ok(Some(crate::mask_cmds::anchor_source(session, CMD, reader, LayerId(anchor), anchor_channel)?)); + let reader = reader.ok_or_else(|| bad(FILL_SET, "the fill is not in a layer"))?; + let anchor_channel = channel_param(FILL_SET, params, "anchorChannel")?.unwrap_or(channel); + return Ok(Some(crate::mask_cmds::anchor_source(session, FILL_SET, reader, LayerId(anchor), anchor_channel)?)); } if !crate::procedural_params::has_pattern_settings(params) { @@ -655,12 +669,12 @@ fn fill_source_from( // Pattern settings alone edit the channel's current pattern let Some(Source::Procedural { pattern, low, high, .. }) = fill_mut(session, target)?.sources.get(&channel) else { - return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings")); + return Err(bad(FILL_SET, "the channel has no pattern: give `procedural` with its settings")); }; let mut pattern = pattern.clone(); crate::procedural_params::pattern_basics_from(params, &mut pattern); - crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; + crate::procedural_params::pattern_settings_from(FILL_SET, params, &mut pattern)?; Ok(Some(Source::Procedural { pattern, low: *low, high: *high, ramp: Vec::new() })) } @@ -731,83 +745,236 @@ fn with_ramp(channel: Channel, current: Option<&Source>, source: Option, Ok(Some(source)) } -/// Parse projection settings, retaining unspecified fields when the projection kind stays the same. -pub(crate) fn projection_from(params: &Value, command: &str, current: Option<&Projection>) -> Result { - projection_from_fields(params, command, current, true) +/// A new fill's projection of kind `id` (`uv`, `uvTile`, `triplanar`, `planar`, `spherical`, `cylindrical`, or a `warp` from frame `fit`) +pub(crate) fn new_projection(id: &str, fit: impl FnOnce() -> Decal) -> Option { + match id { + "warp" => Some(Projection::warp(fit())), + _ => new_unframed_projection(id), + } } -/// A procedural mask can assign the command's scale to its pattern instead of its projection. -pub(crate) fn projection_from_fields(params: &Value, command: &str, current: Option<&Projection>, read_scale: bool) -> Result { - const MIN_SCALE: f32 = 0.001; - const MAX_SCALE: f32 = 1000.0; - const MAX_OFFSET: f32 = 1000.0; - const DEFAULT_SHARPNESS: f32 = 8.0; - const MAX_SHARPNESS: f32 = 64.0; +/// The ids [`new_unframed_projection`] takes, one per kind +pub(crate) const UNFRAMED_PROJECTION_IDS: [&str; 6] = ["uv", "uvTile", "triplanar", "planar", "spherical", "cylindrical"]; - let named = match strp(params, "projection") { +/// A new fill's projection of kind `id`, any kind but a warp (which needs a frame) +pub(crate) fn new_unframed_projection(id: &str) -> Option { + let projection = match id { + "uv" => Projection::default(), + "uvTile" => Projection::UvTile, + "triplanar" | "tri-planar" => Projection::triplanar(), + "planar" => Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: Default::default(), projector: Projector::depth_culled(), placed: None }, + "spherical" => Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() }, + "cylindrical" => { + Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES } + } + _ => return None, + }; + Some(projection) +} + +/// The projection `p` asks for: fields it does not give keep their values from `current` when that is of the same kind (or `p` names no kind), and the kind's defaults otherwise; a new warp starts from frame `fit` +pub(crate) fn projection_from(p: &Value, cmd: &str, current: Option<&Projection>, fit: impl FnOnce() -> Decal) -> Result { + let named = match strp(p, "projection") { None => None, - Some("uv") => Some(Projection::default()), - Some("triplanar" | "tri-planar") => Some(Projection::Triplanar { scale: 1.0, sharpness: DEFAULT_SHARPNESS, offset: [0.0; 3] }), - Some("planar") => Some(Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3] }), - Some("spherical") => Some(Projection::Spherical { scale: 1.0 }), - Some("cylindrical") => Some(Projection::Cylindrical { scale: 1.0, axis: 1 }), - Some(other) => return Err(bad(command, format!("unknown projection `{other}`"))), + Some("warp") if matches!(current, Some(Projection::Warp { .. })) => current.cloned(), + Some(id) => Some(new_projection(id, fit).ok_or_else(|| bad(cmd, format!("unknown projection `{id}`")))?), }; let mut projection = match (named, current) { (Some(named), Some(current)) if std::mem::discriminant(&named) == std::mem::discriminant(current) => current.clone(), (Some(named), _) => named, (None, current) => current.cloned().unwrap_or_default(), }; + let scale = floats::<2>(p, "scale", MIN_SCALE, MAX_PLACEMENT); + let tiling = floats::<2>(p, "tiling", MIN_SCALE, MAX_PLACEMENT); + let rotation = f32p(p, "rotation").map(|degrees| degrees.rem_euclid(FULL_TURN_DEGREES)); + let axis = u64p(p, "axis").map(|axis| axis.min(2) as u8); - let new_scale = if read_scale { floats::<2>(params, "scale", MIN_SCALE, MAX_SCALE) } else { None }; - let new_axis = u64p(params, "axis").map(|axis| axis.min(2) as u8); + // The UV transformations of a 3D projection: tiling, rotation and an offset across the surface + let place = |uv: &mut UvTransform| { + uv.tiling = tiling.unwrap_or(uv.tiling); + uv.rotation = rotation.unwrap_or(uv.rotation); + uv.offset = floats(p, "uvOffset", -MAX_PLACEMENT, MAX_PLACEMENT).unwrap_or(uv.offset); + }; + + // The 3D projection settings: the projector's offset, turn and per-axis scale + let projector_offset = floats::<3>(p, "offset", -MAX_PLACEMENT, MAX_PLACEMENT); + let crop = match strp(p, "shapeCrop") { + None => None, + Some(id) => Some(ShapeCrop::from_id(id).ok_or_else(|| bad(cmd, format!("unknown shapeCrop `{id}`: cropped or extendsOutside")))?), + }; + let turn = |projector: &mut Projector| { + projector.rotation = floats(p, "projectorRotation", -FULL_TURN_DEGREES, FULL_TURN_DEGREES).unwrap_or(projector.rotation); + projector.scale = floats(p, "projectorScale", -MAX_PLACEMENT, MAX_PLACEMENT).map_or(projector.scale, |scale| scale.map(signed_scale)); + projector.crop = crop.unwrap_or(projector.crop); + projector.backface.on = p.get("backfaceCulling").and_then(Value::as_bool).unwrap_or(projector.backface.on); + projector.backface.angle = f32p(p, "backfaceAngle").map_or(projector.backface.angle, |angle| clamp_to(angle, &Backface::ANGLE_RANGE)); + projector.backface.hardness = f32p(p, "backfaceHardness").map_or(projector.backface.hardness, |hardness| hardness.clamp(0.0, 1.0)); + projector.depth.on = p.get("depthCulling").and_then(Value::as_bool).unwrap_or(projector.depth.on); + projector.depth.hardness = f32p(p, "depthCullingHardness").map_or(projector.depth.hardness, |hardness| hardness.clamp(0.0, 1.0)); + }; match &mut projection { - Projection::Uv { scale, rotation, offset } => { - *scale = new_scale.unwrap_or(*scale); - *rotation = f32p(params, "rotation").map_or(*rotation, |degrees| degrees.rem_euclid(360.0)); - *offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset); + Projection::Uv { scale: uv_scale, rotation: uv_rotation, offset } => { + // A UV projection's scale is its tiling + *uv_scale = tiling.or(scale).unwrap_or(*uv_scale); + *uv_rotation = rotation.unwrap_or(*uv_rotation); + *offset = floats(p, "offset", -MAX_PLACEMENT, MAX_PLACEMENT).unwrap_or(*offset); } - Projection::Triplanar { scale, sharpness, offset } => { - *scale = new_scale.map_or(*scale, |axes| axes[0]); - *sharpness = f32p(params, "sharpness").map_or(*sharpness, |value| value.clamp(1.0, MAX_SHARPNESS)); - *offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset); + Projection::UvTile => {} + Projection::Triplanar { scale: projection_scale, sharpness, offset, uv, projector } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *sharpness = f32p(p, "sharpness").map_or(*sharpness, |given| clamp_to(given, &Projection::TRIPLANAR_SHARPNESS_RANGE)); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); } - Projection::Planar { scale, axis, offset } => { - *scale = new_scale.map_or(*scale, |axes| axes[0]); - *axis = new_axis.unwrap_or(*axis); - *offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset); + Projection::Planar { scale: projection_scale, axis: projection_axis, offset, uv, projector, .. } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *projection_axis = axis.unwrap_or(*projection_axis); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); } - Projection::Spherical { scale } => *scale = new_scale.map_or(*scale, |axes| axes[0]), - Projection::Cylindrical { scale, axis } => { - *scale = new_scale.map_or(*scale, |axes| axes[0]); - *axis = new_axis.unwrap_or(*axis); + Projection::Spherical { scale: projection_scale, uv, offset, projector } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); } - Projection::Decal(_) => {} - } + Projection::Cylindrical { scale: projection_scale, axis: projection_axis, uv, offset, projector, angle } => { + *projection_scale = scale.map_or(*projection_scale, |across| across[0]); + *angle = f32p(p, "angle").map_or(*angle, |given| clamp_to(given, &Projection::CYLINDER_ANGLE_RANGE)); + *projection_axis = axis.unwrap_or(*projection_axis); + *offset = projector_offset.unwrap_or(*offset); + place(uv); + turn(projector); + } + Projection::Warp { corners, depth, uv, projector, .. } => { + // A warp has no scale or offset of its own: its frame places it, so they would change nothing + if p.get("scale").is_some() || p.get("offset").is_some() { + return Err(bad(cmd, "a warp is placed by its frame: set frameOffset or frameScale with layer.decal.set")); + } + *corners = warp_corners(p, cmd)?.unwrap_or(*corners); + *depth = f32p(p, "projectionDepth").map_or(*depth, |given| given.clamp(0.0, MAX_PROJECTION_DEPTH)); + place(uv); + turn(projector); + } + } Ok(projection) } -/// `key` as `N` finite numbers clamped to `lo..=hi`: an array of `N`, or one number for all. +/// `value` held within `range` +fn clamp_to(value: f32, range: &std::ops::RangeInclusive) -> f32 { + value.clamp(*range.start(), *range.end()) +} + +/// The projection `params` asks for, as [`projection_from`]; without `read_scale` its `scale` is left out (a procedural mask's scale is its pattern's) +pub(crate) fn projection_from_fields( + params: &Value, + command: &str, + current: Option<&Projection>, + read_scale: bool, + fit: impl FnOnce() -> Decal, +) -> Result { + let mut placement = params.clone(); + if !read_scale && let Some(fields) = placement.as_object_mut() { + fields.remove("scale"); + } + projection_from(&placement, command, current, fit) +} + +/// The `warpCorners` param: four [across, up] corners in frame sizes from the frame's centre, finite and within reach of the frame (None when not given) +fn warp_corners(p: &Value, cmd: &str) -> Result> { + let Some(given) = p.get("warpCorners") else { return Ok(None) }; + + let malformed = || bad(cmd, "warpCorners is four [across, up] pairs of finite numbers"); + let list = given.as_array().filter(|list| list.len() == 4).ok_or_else(malformed)?; + let mut corners = Projection::FRAME_CORNERS; + for (corner, value) in corners.iter_mut().zip(list) { + let pair = value.as_array().filter(|pair| pair.len() == 2).ok_or_else(malformed)?; + for (axis, number) in corner.iter_mut().zip(pair) { + let reach = number.as_f64().map(|number| number as f32).filter(|number| number.is_finite()).ok_or_else(malformed)?; + *axis = reach.clamp(-MAX_CORNER_REACH, MAX_CORNER_REACH); + } + } + Ok(Some(corners)) +} + +/// `current` with the `filtering`, `wrap`, `scaleMode` and symmetry params applied +pub(crate) fn sampling_from(p: &Value, cmd: &str, current: Sampling) -> Result { + let mut sampling = current; + if let Some(id) = strp(p, "filtering") { + sampling.filtering = Filtering::from_id(id).ok_or_else(|| bad(cmd, format!("unknown filtering `{id}`: bilinearHq, bilinearSharp or nearest")))?; + } + if let Some(id) = strp(p, "wrap") { + sampling.wrap = UvWrap::from_id(id).ok_or_else(|| bad(cmd, format!("unknown wrap `{id}`: repeat, repeatHorizontally, repeatVertically or none")))?; + } + if let Some(id) = strp(p, "scaleMode") { + sampling.scale = ScaleMode::from_id(id).ok_or_else(|| bad(cmd, format!("unknown scaleMode `{id}`: tiling or physicalSize")))?; + } + sampling.symmetry = symmetry_from(p, cmd, sampling.symmetry)?; + Ok(sampling) +} + +/// `current` with the `symmetry`, `symmetryType`, `symmetryAxis`, `flipCopy`, `axisPosition`, `symmetryCount` and `angleSpan` params applied +fn symmetry_from(p: &Value, cmd: &str, current: FillSymmetry) -> Result { + let mut symmetry = current; + symmetry.on = boolp(p, "symmetry").unwrap_or(symmetry.on); + if let Some(id) = strp(p, "symmetryType") { + symmetry.kind = SymmetryKind::from_id(id).ok_or_else(|| bad(cmd, format!("unknown symmetryType `{id}`: mirror or radial")))?; + } + if let Some(given) = p.get("symmetryAxis").filter(|given| !given.is_null()) { + // An index or the letter tool.brush takes for its own symmetry axis + let axis = match given { + Value::String(letter) => ["x", "y", "z"].iter().position(|name| letter.eq_ignore_ascii_case(name)).and_then(|index| u8::try_from(index).ok()), + index => index.as_u64().and_then(|index| u8::try_from(index).ok()).filter(|index| *index <= FillSymmetry::LAST_AXIS), + }; + symmetry.axis = axis.ok_or_else(|| bad(cmd, "symmetryAxis is 0 (X), 1 (Y) or 2 (Z), or \"x\", \"y\" or \"z\""))?; + } + if let Some(flips) = p.get("flipCopy") { + let [Some(across), Some(down)] = flips.as_array().map(Vec::as_slice).unwrap_or_default().iter().map(Value::as_bool).collect::>()[..] else { + return Err(bad(cmd, "flipCopy is [u, v], two booleans")); + }; + + symmetry.flip = [across, down]; + } + let reach = FillSymmetry::REACH; + symmetry.position = floats(p, "axisPosition", -reach, reach).unwrap_or(symmetry.position); + if let Some(count) = u64p(p, "symmetryCount") { + let (fewest, most) = (u64::from(*FillSymmetry::COUNTS.start()), u64::from(*FillSymmetry::COUNTS.end())); + symmetry.count = u32::try_from(count.clamp(fewest, most)).unwrap_or(*FillSymmetry::COUNTS.start()); + } + symmetry.span = f32p(p, "angleSpan").map_or(symmetry.span, |span| clamp_to(span, &FillSymmetry::SPANS)); + Ok(symmetry) +} + +/// `value` as one axis of a projector's scale: its size kept within [`MIN_SCALE`]..[`MAX_PLACEMENT`] on its own side, so a mirrored axis stays mirrored +pub fn signed_scale(value: f32) -> f32 { + value.signum() * value.abs().clamp(MIN_SCALE, MAX_PLACEMENT) +} + +/// `key` as `N` finite numbers clamped to `lo..=hi`: an array of `N`, or one number for all fn floats(p: &Value, key: &str, lo: f32, hi: f32) -> Option<[f32; N]> { - let one = |x: &Value| x.as_f64().map(|f| f as f32).filter(|f| f.is_finite()).map(|f| f.clamp(lo, hi)); + let number = |value: &Value| value.as_f64().map(|given| given as f32).filter(|given| given.is_finite()).map(|given| given.clamp(lo, hi)); match p.get(key)? { - Value::Array(a) if a.len() == N => { + Value::Array(list) if list.len() == N => { let mut out = [0.0; N]; - for (o, x) in out.iter_mut().zip(a) { - *o = one(x)?; + for (slot, value) in out.iter_mut().zip(list) { + *slot = number(value)?; } Some(out) } - v => one(v).map(|f| [f; N]), + value => number(value).map(|given| [given; N]), } } fn fill_projection(s: &mut Session, p: &Value) -> Result { let target = fill_target(s, p, "layer.fill.projection")?; + let mesh = s.mesh.clone(); s.edit("Fill projection", |s| { - let fill = fill_mut(s, target)?; - fill.projection = projection_from(p, "layer.fill.projection", Some(&fill.projection))?; + let (projection, sampling) = placement_mut(s, target)?; + *projection = projection_from(p, "layer.fill.projection", Some(projection), || crate::warp_cmds::fitted_frame(&mesh))?; + *sampling = sampling_from(p, "layer.fill.projection", *sampling)?; Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c1c8f9ab..4d25b237 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -19,6 +19,7 @@ pub mod effect_clipboard; pub mod file_cmds; pub mod fill_hit_test; pub mod fill_mode; +pub mod fill_reset_cmds; pub mod filter_lib; mod frame_target; pub mod inspect; @@ -76,6 +77,7 @@ mod uv_stroke_state; mod uv_symmetry; pub mod uv_tile_cmds; pub mod view_cmds; +pub mod warp_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; pub use bake_preview::{BakePreview, PreviewShow}; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index adc124f8..ac1db3f5 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Add fill", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}", + "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?; filtering?: bilinearHq|bilinearSharp|nearest; wrap?: repeat|repeatHorizontally|repeatVertically|none}", has_layer, add_fill ), @@ -295,16 +295,18 @@ fn image_source(session: &Session, command: &str, name: &str) -> Result fn add_fill(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.add.fill"; + let sampling = crate::layer_cmds::sampling_from(params, CMD, Sampling::default())?; let blend = blend_param(CMD, params, "blend")?.unwrap_or(BlendMode::Normal); let layer = layer_param(session, CMD, params)?; if content_target(params, CMD)? { let mut fill = crate::layer_cmds::fill_from(CMD, params)?; + fill.sampling = sampling; if fill.sources.is_empty() { fill.sources = session.doc.project.layer(layer)?.channels.keys().map(|channel| (*channel, Source::uniform_of(*channel))).collect(); } - fill.projection = projection_from(params, CMD, None)?; + fill.projection = projection_from(params, CMD, None, || crate::warp_cmds::fitted_frame(&session.mesh))?; return push_effect(session, params, EffectKind::Material(fill), blend); } @@ -327,9 +329,9 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { // A scalar controls pattern frequency, while a two-axis scale places the new mask let pattern_scale = matches!(source, Source::Procedural { .. }) && params.get("scale").is_some_and(Value::is_number); - let projection = projection_from_fields(params, CMD, None, !pattern_scale)?; + let projection = projection_from_fields(params, CMD, None, !pattern_scale, || crate::warp_cmds::fitted_frame(&session.mesh))?; - push_effect(session, params, EffectKind::Fill { source, projection }, blend) + push_effect(session, params, EffectKind::Fill { source, projection, sampling }, blend) } /// Apply `params` to `generator`, using `command` in errors @@ -613,6 +615,7 @@ fn set(session: &mut Session, params: &Value) -> Result { }; let swaps_filter = swapped.is_some(); + let mesh = session.mesh.clone(); session.edit("Edit effect", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; if let Some((kind, label)) = swapped { @@ -667,7 +670,7 @@ fn set(session: &mut Session, params: &Value) -> Result { // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, - EffectKind::Fill { source, projection } => { + EffectKind::Fill { source, projection, .. } => { // `uniform` picks the source, so it outranks settings that would edit the current pattern let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none()); if let Some(anchor) = anchor { @@ -684,9 +687,16 @@ fn set(session: &mut Session, params: &Value) -> Result { *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } - // Pattern edits keep the mask's existing projection scale - let read_scale = !matches!(source, Source::Procedural { .. }); - *projection = projection_from_fields(params, CMD, Some(projection), read_scale)?; + // While the fill reads a pattern, `scale` is the pattern's and leaves the projection alone + let mut placement = params.clone(); + if matches!(source, Source::Procedural { .. }) + && let Some(fields) = placement.as_object_mut() + { + fields.remove("scale"); + } + + // Preserve projection fields that the edit does not supply + *projection = projection_from(&placement, CMD, Some(&*projection), || crate::warp_cmds::fitted_frame(&mesh))?; } EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, EffectKind::Compare { tolerance, .. } => { diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index f91efe86..62c36dd2 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -210,8 +210,8 @@ impl Builder<'_> { fn fill(&mut self, name: &str, sources: Sources) -> Layer { let id = self.p.alloc_id(); let enabled: Vec = sources.iter().map(|(c, _)| *c).filter(|c| self.channels.contains(c)).collect(); - let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }; - Layer::new(id, name, LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &enabled) + let projection = Projection::triplanar(); + Layer::new(id, name, LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, ..Fill::default() }), &enabled) } /// A fill masked by smart mask preset `mask` (inverted: present where the preset is not). @@ -782,8 +782,12 @@ pub fn brush_values(id: &str) -> Option> { /// `scale` (the same fill evaluation a layer with that material uses). pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f32) -> Layer { let channels: Vec = sources.iter().map(|(channel, _)| *channel).collect(); - let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3] }; - Layer::new(id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &channels) + let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() }; + Layer::new( + id, + "Brush material", + &channels, + ) } /// Where [`apply_at`] puts a material. diff --git a/crates/engine/src/pbr_cmds.rs b/crates/engine/src/pbr_cmds.rs index a9635f49..d5b3d4aa 100644 --- a/crates/engine/src/pbr_cmds.rs +++ b/crates/engine/src/pbr_cmds.rs @@ -358,7 +358,8 @@ pub fn common_name(files: &[String]) -> Option { // Parameters and sources (native) -fn options(cmd: &str, p: &Value) -> Result { +/// The import options in `p`; a warp projection is fitted to `mesh` +fn options(cmd: &str, p: &Value, mesh: &texturecraft_geom::Mesh) -> Result { let normal_format = match strp(p, "normalFormat") { None | Some("auto") => None, Some("openGl" | "opengl") => Some(NormalFormat::OpenGl), @@ -377,7 +378,7 @@ fn options(cmd: &str, p: &Value) -> Result { Ok(PbrOptions { name: strp(p, "name").filter(|name| !name.trim().is_empty()).map(str::to_string), normal_format, - projection: crate::layer_cmds::projection_from(p, cmd, None)?, + projection: crate::layer_cmds::projection_from(p, cmd, None, || crate::warp_cmds::fitted_frame(mesh))?, choose, }) } @@ -414,7 +415,7 @@ mod native; #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let cmd = "file.importPbrFolder"; - let mut options = options(cmd, p)?; + let mut options = options(cmd, p, &s.mesh)?; let found = native::find(cmd, p)?; if options.name.is_none() { options.name = found.name.clone(); @@ -425,7 +426,7 @@ fn import(s: &mut Session, p: &Value) -> Result { #[cfg(not(target_arch = "wasm32"))] fn scan(s: &mut Session, p: &Value) -> Result { let cmd = "file.scanPbrFolder"; - let options = options(cmd, p)?; + let options = options(cmd, p, &s.mesh)?; let found = native::find(cmd, p)?; let set = detect_with(&found.files, &options.choose)?; let mut reply = report(&set, options.normal_format); @@ -440,8 +441,8 @@ fn scan(s: &mut Session, p: &Value) -> Result { } #[cfg(target_arch = "wasm32")] -fn import(_: &mut Session, p: &Value) -> Result { - let _ = options("file.importPbrFolder", p)?; +fn import(s: &mut Session, p: &Value) -> Result { + let _ = options("file.importPbrFolder", p, &s.mesh)?; Err(EngineError::Other("file paths are not available in the browser".into())) } diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 3cdc0d5e..d20a81e5 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -42,7 +42,7 @@ pub(crate) const MAX_BYTES: usize = 512 << 20; pub(crate) const EXR_SIGNATURE: &[u8] = &[0x76, 0x2f, 0x31, 0x01]; pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { - Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb }) + Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb)) } impl Session { @@ -307,7 +307,7 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?; let name = resolve_resource_name(s, raw_name)?; let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor); - let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?; + let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None, || crate::warp_cmds::fitted_frame(&s.mesh))?; let ts = s.ts(); let label = std::path::Path::new(&name).file_stem().and_then(|n| n.to_str()).unwrap_or("Image").to_string(); let layer_name = s.doc.project.next_layer_name(ts, &label); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index b493a8b6..8a036f72 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -496,6 +496,10 @@ impl Session { let source = Arc::new(mesh); let mesh = tiled_mesh(&source, &doc.project); + + // Depth maps built for the mesh this one replaces must not be taken for its own + texturecraft_compose::projector_depth::ProjectorDepth::forget_all(); + let bvh = Bvh::new(&mesh); let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (bounds_min, bounds_max) = mesh.bounds(); diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 0529b0b8..8c7a2791 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -93,7 +93,8 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind { EffectKind::Fill { source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, - projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, + projection: Projection::triplanar(), + sampling: Default::default(), } } diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index 811a742f..bd6bdd13 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -203,6 +203,10 @@ pub struct ThumbService { queue: VecDeque, in_flight: HashSet<(u64, ThumbTarget)>, wanted: HashSet, + /// Asked for after this frame's poll (a panel drawn after the Layers panel): wanted again next frame + late: HashSet, + /// Whether this frame's poll has run + polled: bool, gbufs: GbufCache, #[cfg(not(target_arch = "wasm32"))] worker: Option, @@ -227,6 +231,8 @@ impl Default for ThumbService { queue: VecDeque::new(), in_flight: HashSet::new(), wanted: HashSet::new(), + late: HashSet::new(), + polled: false, gbufs: GbufCache::default(), #[cfg(not(target_arch = "wasm32"))] worker: None, @@ -243,9 +249,10 @@ impl ThumbService { ThumbService::default() } - /// Start of a frame: forget what the last frame asked for and notice document changes. + /// Start of a frame: forget what the last frame asked for (but what it asked for after its poll) and notice document changes pub fn begin_frame(&mut self, session: &Session, now: f64) { - self.wanted.clear(); + self.wanted = std::mem::take(&mut self.late); + self.polled = false; let texture_set = session.ts(); if self.seen == Some(session.revision) && self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id) @@ -290,6 +297,9 @@ impl ThumbService { /// picture is missing or out of date. pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView { self.wanted.insert(target); + if self.polled { + self.late.insert(target); + } self.tick = self.tick.wrapping_add(1); let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation); let checked = self.checked(session); @@ -316,6 +326,7 @@ impl ThumbService { /// End of a frame: collect results, discard unrequested rows, and dispatch new work. /// Returns whether another frame is needed, including to display newly collected pictures. pub fn poll(&mut self, session: &Session) -> bool { + self.polled = true; let changed = self.collect(); self.queue.retain(|target| self.wanted.contains(target)); self.dispatch(); @@ -517,6 +528,20 @@ mod tests { assert!(!service.poll(&session), "an idle cache must stop repainting"); } + #[test] + fn a_picture_asked_for_after_the_poll_renders_at_the_next_one() { + let session = test_session().unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (mut service, jobs, _results) = held_worker(); + service.begin_frame(&session, 0.0); + service.poll(&session); + service.get(&session, target); + + service.begin_frame(&session, 0.1); + service.poll(&session); + assert_eq!(jobs.try_recv().map(|job| job.target).ok(), Some(target), "the late request is dispatched, not dropped"); + } + #[test] fn a_stopped_worker_retries_visible_targets_inline() { let session = test_session().unwrap(); diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index e8161c8e..fc85fd59 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -10,6 +10,9 @@ use crate::frame_target::FrameTarget; use crate::session::ViewMode; use crate::{Result, Session, cmd}; +/// The farthest depth-of-field focus distance, in world units +const MAX_FOCUS_DISTANCE: f32 = 1e6; + pub fn specs() -> Vec { vec![ cmd!( @@ -68,7 +71,7 @@ pub fn specs() -> Vec { "Display settings", [], None, - "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}", + "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}, projectionGizmos? (the selected fill's projection gizmos show in the 3D view)}", always, display ), @@ -270,10 +273,10 @@ fn orbit(s: &mut Session, p: &Value) -> Result { } fn display(s: &mut Session, p: &Value) -> Result { - let tm = match strp(p, "toneMapping") { + let tone_mapping = match strp(p, "toneMapping") { Some("linear") => Some(ToneMapping::Linear), Some("aces") | Some("acesFilmic") => Some(ToneMapping::AcesFilmic), - Some(o) => return Err(bad("display.set", format!("unknown tone mapping `{o}`"))), + Some(other) => return Err(bad("display.set", format!("unknown tone mapping `{other}`"))), None => None, }; let shadow_mode = match strp(p, "shadowMode") { @@ -284,77 +287,80 @@ fn display(s: &mut Session, p: &Value) -> Result { Some(id) => Some(EnvAlignment::parse(id).ok_or_else(|| bad("display.set", format!("unknown environment alignment `{id}` (world or camera)")))?), None => None, }; - let env = strp(p, "environment").map(str::to_string); - if let Some(name) = env.as_deref().and_then(|e| e.strip_prefix(texturecraft_core::project::ENV_RESOURCE_PREFIX)) + let environment = strp(p, "environment").map(str::to_string); + if let Some(name) = environment.as_deref().and_then(|picked| picked.strip_prefix(texturecraft_core::project::ENV_RESOURCE_PREFIX)) && !s.images.contains_key(name) { return Err(bad("display.set", format!("no image resource `{name}` (import it with resource.import)"))); } - if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) { - return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); + if let Some(unknown) = + environment.as_deref().filter(|picked| !picked.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(picked)) + { + return Err(bad("display.set", format!("unknown environment `{unknown}`: one of {}, or resource:", ENVIRONMENTS.join(", ")))); } let scatter_color = color_param("display.set", p, "scatterColor")?; - let d = &mut s.doc.project.display; - if let Some(e) = env { - d.environment = e; + let settings = &mut s.doc.project.display; + if let Some(picked) = environment { + settings.environment = picked; } - for (k, slot, lo, hi) in [ - ("exposure", &mut d.env_exposure, -10.0, 10.0), - ("blur", &mut d.env_blur, 0.0, 1.0), - ("rotation", &mut d.env_rotation, -360.0, 360.0), - ("opacity", &mut d.env_opacity, 0.0, 1.0), - ("fov", &mut d.fov, 5.0, 150.0), - ("aoIntensity", &mut d.ao_intensity, 0.0, 1.0), - ("bloom", &mut d.bloom, 0.0, 1.0), - ("vignette", &mut d.vignette, 0.0, 1.0), - ("sharpen", &mut d.sharpen, 0.0, 1.0), - ("grain", &mut d.grain, 0.0, 1.0), - ("scatterRadius", &mut d.scatter_radius, 0.0, 1.0), - ("ior", &mut d.ior, 1.0, 3.0), - ("shadowOpacity", &mut d.shadow_opacity, 0.0, 1.0), + for (key, slot, lowest, highest) in [ + ("exposure", &mut settings.env_exposure, -10.0, 10.0), + ("blur", &mut settings.env_blur, 0.0, 1.0), + ("rotation", &mut settings.env_rotation, -360.0, 360.0), + ("opacity", &mut settings.env_opacity, 0.0, 1.0), + ("fov", &mut settings.fov, 5.0, 150.0), + ("aoIntensity", &mut settings.ao_intensity, 0.0, 1.0), + ("bloom", &mut settings.bloom, 0.0, 1.0), + ("vignette", &mut settings.vignette, 0.0, 1.0), + ("sharpen", &mut settings.sharpen, 0.0, 1.0), + ("grain", &mut settings.grain, 0.0, 1.0), + ("scatterRadius", &mut settings.scatter_radius, 0.0, 1.0), + ("ior", &mut settings.ior, 1.0, 3.0), + ("shadowOpacity", &mut settings.shadow_opacity, 0.0, 1.0), ] { - if let Some(v) = f32p(p, k) { - *slot = v.clamp(lo, hi); + if let Some(value) = f32p(p, key) { + *slot = value.clamp(lowest, highest); } } - if let Some(t) = tm { - d.tone_mapping = t; + if let Some(picked) = tone_mapping { + settings.tone_mapping = picked; } - if let Some(c) = scatter_color { - d.scatter_color = c.map(|v| v.clamp(0.0, 1.0)); + if let Some(color) = scatter_color { + settings.scatter_color = color.map(|component| component.clamp(0.0, 1.0)); } - if let Some(b) = boolp(p, "shadows") { - d.shadows = b; + if let Some(on) = boolp(p, "shadows") { + settings.shadows = on; } if let Some(mode) = shadow_mode { - d.shadow_mode = mode; + settings.shadow_mode = mode; } if let Some(alignment) = alignment { - d.env_alignment = alignment; + settings.env_alignment = alignment; } if let Some(dof) = p.get("dof") { - if let Some(b) = boolp(dof, "enabled") { - d.dof.enabled = b; + if let Some(on) = boolp(dof, "enabled") { + settings.dof.enabled = on; } - if let Some(v) = f32p(dof, "focusDistance") { - d.dof.focus_distance = v.clamp(0.0, 1e6); + if let Some(distance) = f32p(dof, "focusDistance") { + settings.dof.focus_distance = distance.clamp(0.0, MAX_FOCUS_DISTANCE); } - if let Some(v) = f32p(dof, "aperture") { - d.dof.aperture = v.clamp(0.0, 1.0); + if let Some(aperture) = f32p(dof, "aperture") { + settings.dof.aperture = aperture.clamp(0.0, 1.0); } } - for (k, slot) in [ - ("postEffects", &mut d.post_effects), - ("taa", &mut d.taa), - ("specGloss", &mut d.spec_gloss), - ("parallax", &mut d.parallax), - ("displacement", &mut d.displacement), - ("soloUnlit", &mut d.solo_unlit), + for (key, slot) in [ + ("postEffects", &mut settings.post_effects), + ("taa", &mut settings.taa), + ("specGloss", &mut settings.spec_gloss), + ("parallax", &mut settings.parallax), + ("displacement", &mut settings.displacement), + ("soloUnlit", &mut settings.solo_unlit), + ("projectionGizmos", &mut settings.projection_gizmos), ] { - if let Some(b) = boolp(p, k) { - *slot = b; + if let Some(on) = boolp(p, key) { + *slot = on; } } @@ -519,4 +525,21 @@ mod tests { execute(&mut s, "file.removeUnused", &Value::Null).unwrap(); assert!(s.doc.resources.contains_key(&name), "the environment's image counts as used"); } + + #[test] + fn the_projection_gizmos_hide_per_project_and_old_projects_show_them() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let shown = serde_json::to_value(&s.doc.project.display).unwrap(); + assert!(s.doc.project.display.projection_gizmos && shown.get("projection_gizmos").is_none(), "shown by default and saved as before: {shown}"); + + let hidden = execute(&mut s, "display.set", &json!({"projectionGizmos": false})).unwrap(); + assert!(!s.doc.project.display.projection_gizmos); + assert_eq!(hidden["projection_gizmos"], json!(false), "hidden is saved with the project"); + assert!(s.history_labels().is_empty(), "a view flag is no undo step"); + + let reopened: texturecraft_core::project::DisplaySettings = serde_json::from_value(hidden).unwrap(); + assert!(!reopened.projection_gizmos, "a saved project opens with its gizmos hidden"); + let old: texturecraft_core::project::DisplaySettings = serde_json::from_value(shown).unwrap(); + assert!(old.projection_gizmos, "a project saved before the flag shows them"); + } } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index d88166e5..11a5b7f0 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,6 +13,9 @@ mod content_effects; mod export_colour_space; mod export_file_types; mod export_maps; +mod fill_patterns; +mod fill_projections; +mod fill_sampling; mod filter_swap; mod filters; mod frame_selection; @@ -36,6 +39,7 @@ mod polygon_fill; mod project_recovery; mod sample; mod solo; +mod symmetry; mod thumbs; mod tile_generator; mod tool_availability; @@ -44,5 +48,3 @@ mod tools; mod udim; mod user_smart_mask; mod uv_strokes; - -mod symmetry; diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 37b8e601..4ad6c736 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -3,7 +3,7 @@ //! maps from images and fill projection transforms, through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Source}; +use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Projector, Source}; use texturecraft_engine::geom::NO_TRI; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; @@ -80,33 +80,44 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); + assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); + execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it. + // A gradient map recolors the content; effect.set edits it and inspect shows it let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); + execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); + execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped. + // Posterize on the mask; its steps are clamped let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0)); - // Material finishes fill the content's roughness and height. + + // Material finishes fill the content's roughness and height let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); + assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - // A directional blur, slope blur and warp composite without trouble on a sphere. + + // A directional blur, slope blur and warp composite without trouble on a sphere for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"radius": 30})), @@ -182,7 +193,7 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { let layer = id(r.clone(), "layer"); assert!((r["decal"]["size"][1].as_f64().unwrap() - 0.5).abs() < 1e-6); let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - assert!(matches!(f.projection, Projection::Decal(_))); + assert!(matches!(f.projection, Projection::Planar { placed: Some(_), .. })); assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the decal shows where it was placed"); assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and only there"); @@ -198,8 +209,7 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { assert_eq!(r["decal"]["offset"], json!([0.0, 0.0]), "re-placing resets the offset"); assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); - assert!(inspect.contains("Decal projection") && inspect.contains("\"rotation\":45"), "inspect shows the decal"); - + assert!(inspect.contains("Planar projection") && inspect.contains("\"decal\"") && inspect.contains("\"rotation\":45"), "inspect shows the decal"); // Not a decal; one undo step per edit let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err()); @@ -210,7 +220,10 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { /// The decal of mask fill effect `effect` fn effect_decal(s: &Session, effect: LayerId) -> Decal { - let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &s.doc.project.effect(effect).unwrap().1.kind else { panic!("a decal fill effect") }; + let EffectKind::Fill { projection: Projection::Planar { placed: Some(decal), .. }, .. } = &s.doc.project.effect(effect).unwrap().1.kind else { + panic!("a decal fill effect") + }; + *decal } @@ -244,7 +257,7 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // The layer decal is untouched by all of it let LayerKind::Fill(f) = &s.doc.project.layer(layer_decal).unwrap().kind else { panic!("a fill layer") }; - assert!(matches!(&f.projection, Projection::Decal(d) if d.size[1] == 0.5 && d.rotation == 0.0)); + assert!(matches!(&f.projection, Projection::Planar { placed: Some(d), .. } if d.size[1] == 0.5 && d.rotation == 0.0)); // Errors: unknown effect, an effect that is not a decal, an effect of another layer assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err()); @@ -272,7 +285,7 @@ fn decals_keep_the_image_aspect_and_flip_their_image() { assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra"); let size = |s: &mut Session| { let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(d) = &f.projection else { panic!("a decal") }; + let Projection::Planar { placed: Some(d), .. } = &f.projection else { panic!("a decal") }; (d.size, d.flip) }; @@ -501,7 +514,9 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() { let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); let masked = id(added.clone(), "layer"); let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); - assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. }))); + assert!( + matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Planar { placed: Some(_), .. }, .. })) + ); assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); @@ -676,9 +691,17 @@ fn fill_projection_edits_keep_what_they_do_not_change() { assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 3.0], rotation: 30.0, offset: [0.25, 0.5] }, "the same kind keeps its fields; a bad offset is ignored"); set(&mut s, json!({"projection": "triplanar", "offset": [1, 2, 3]})).unwrap(); set(&mut s, json!({"sharpness": 100})).unwrap(); - assert_eq!(proj(&s), Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0] }, "a new kind starts from its defaults"); + assert_eq!( + proj(&s), + Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0], uv: Default::default(), projector: Default::default() }, + "a new kind starts from its defaults" + ); set(&mut s, json!({"projection": "planar", "axis": 7, "offset": [1e9, 0, 0]})).unwrap(); - assert_eq!(proj(&s), Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0] }, "hostile values are clamped"); + assert_eq!( + proj(&s), + Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0], uv: Default::default(), projector: Projector::depth_culled(), placed: None }, + "hostile values are clamped" + ); assert!(set(&mut s, json!({"projection": "hexagonal"})).is_err()); // The offset moves the pattern: a UV offset changes what the composite shows. set(&mut s, json!({"projection": "uv", "scale": 1})).unwrap(); @@ -747,7 +770,7 @@ fn red_on_minus_x(s: &mut Session, inside: impl Fn(f32, f32) -> bool) -> usize { fn decal_of(s: &Session, layer: LayerId) -> texturecraft_engine::core::Decal { let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = fill.projection else { panic!("a decal") }; + let Projection::Planar { placed: Some(decal), .. } = fill.projection else { panic!("a decal") }; decal } @@ -906,7 +929,7 @@ fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited let image = session.import_resource_bytes("decal.png", png(4, 4, |_, _| [255; 4])).unwrap(); let layer = id(execute(&mut session, "layer.add.decal", &json!({"image": image, "symmetry": "x"})).unwrap(), "layer"); let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer).unwrap().kind else { panic!("expected fill") }; - let Projection::Decal(decal) = &mut fill.projection else { panic!("expected decal") }; + let Projection::Planar { placed: Some(decal), .. } = &mut fill.projection else { panic!("expected decal") }; decal.symmetry.as_mut().unwrap().axis = u8::MAX; let bytes = session.to_project_bytes().unwrap(); diff --git a/crates/engine/tests/it/tile_generator.rs b/crates/engine/tests/it/tile_generator.rs index 3a027e96..445facdf 100644 --- a/crates/engine/tests/it/tile_generator.rs +++ b/crates/engine/tests/it/tile_generator.rs @@ -177,7 +177,7 @@ fn a_pattern_scale_edit_leaves_the_mask_fills_projection_alone() { execute(&mut session, "effect.set", &json!({"effect": effect, "scale": 3.0})).unwrap(); let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; - let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection } = &edited.kind else { panic!("the fill reads a pattern") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection, .. } = &edited.kind else { panic!("the fill reads a pattern") }; assert_eq!(pattern.scale, 3.0); assert_eq!(*projection, Projection::default(), "the projection keeps its scale"); } @@ -205,7 +205,7 @@ fn a_new_procedural_mask_uses_scalar_scale_only_for_the_pattern() { let effect = LayerId(added["effect"].as_u64().unwrap()); let (_, effect) = session.doc.project.effect(effect).unwrap(); - let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection } = &effect.kind else { panic!("expected a procedural mask fill") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection, .. } = &effect.kind else { panic!("expected a procedural mask fill") }; assert_eq!(pattern.scale, 3.0); assert_eq!(*projection, Projection::default(), "UV placement must not multiply pattern frequency a second time"); } diff --git a/crates/engine/tests/it/user_smart_mask.rs b/crates/engine/tests/it/user_smart_mask.rs index 04fce3a6..72916dcb 100644 --- a/crates/engine/tests/it/user_smart_mask.rs +++ b/crates/engine/tests/it/user_smart_mask.rs @@ -33,7 +33,7 @@ fn multi_effect_mask(s: &mut Session) -> (LayerId, String) { let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap(); for effect in &mut mask.effects { if effect.id.0 == fill { - effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default() }; + effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default(), sampling: Default::default() }; } } let size = s.doc.project.texture_set(0).unwrap().resolution; @@ -169,6 +169,7 @@ fn effects_reading_an_anchor_of_the_mask_follow_it() { effect.kind = EffectKind::Fill { source: Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() }, projection: Default::default(), + sampling: Default::default(), }; } } @@ -197,7 +198,7 @@ fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() { for (project, id) in [(&mut file.project, holder), (&mut s.doc.project, source)] { let mask = project.layer_mut(id).unwrap().mask.as_mut().unwrap(); let fill = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Fill { .. })).unwrap(); - fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default() }; + fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default(), sampling: Default::default() }; } assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask")); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 1d01fe6c..bf68e50b 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -369,6 +369,18 @@ impl Mesh { .collect() } + /// Mesh units one UV unit covers on material `m`'s triangles: sqrt(surface area / UV area), None without UV area + pub fn uv_density(&self, m: usize) -> Option { + let (mut surface, mut uv_area) = (0.0_f32, 0.0_f32); + for [a, b, c] in self.triangles_of(m).filter_map(|t| self.tri(t)) { + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; + surface += (*pb - *pa).cross(*pc - *pa).length() * 0.5; + uv_area += (*ub - *ua).perp_dot(*uc - *ua).abs() * 0.5; + } + (uv_area > f32::EPSILON && surface.is_finite()).then(|| (surface / uv_area).sqrt()) + } + /// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other /// materials are duplicated first, so the other triangles keep their UVs. pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) { @@ -595,6 +607,14 @@ mod tests { assert_eq!(m.bounds_of_material(1), None); } + #[test] + fn uv_density_is_mesh_units_per_uv_unit() { + assert_eq!(quad().uv_density(0), Some(1.0)); + let plane = crate::primitives::plane(3.0, 4).uv_density(0).unwrap(); + assert!((plane - 3.0).abs() < 1e-4, "{plane}"); + assert_eq!(quad().uv_density(1), None, "no triangles of that material"); + } + #[test] fn wire_edges_leave_out_polygon_diagonals() { let mut m = quad(); diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index dd55d182..2cb62488 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -181,8 +181,8 @@ fn full_turn() -> f32 { FULL_TURN_DEGREES } -/// [`Symmetry::angle_span`] of a full turn -pub const FULL_TURN_DEGREES: f32 = 360.0; +// A full turn is the angle span every crate measures turns against +pub use texturecraft_core::FULL_TURN_DEGREES; /// Most radial copies a brush paints pub const MAX_RADIAL_COPIES: u8 = 32; @@ -445,7 +445,7 @@ mod tests { #[test] fn image_alpha_follows_the_image_and_is_zero_outside() { // Left half white, right half black (2×1 image, sampled at texel centers) - let img = ImageRes { width: 2, height: 1, rgba: vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], srgb: true }; + let img = ImageRes::new(2, 1, vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], true); let shape = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params: AlphaParams::default(), level: 0 }; assert!(shape.sample(-0.5, 0.0, 0.5, 0) > 0.99); assert!(shape.sample(0.5, 0.0, 0.5, 0) < 0.01); @@ -483,12 +483,7 @@ mod tests { #[test] fn default_parameters_reproduce_every_alpha_exactly() { - let img = ImageRes { - width: 3, - height: 2, - rgba: vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]], - srgb: true, - }; + let img = ImageRes::new(3, 2, vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]], true); let library = crate::alphas::library().first().map(|alpha| alpha.image()); let kinds = BrushAlpha::ALL.map(|alpha| Shape { alpha, image: None, library: None, params: AlphaParams::default(), level: 0 }); for shape in kinds.into_iter().chain([ @@ -522,7 +517,7 @@ mod tests { #[test] fn sizes_apply_to_image_and_library_alphas_too() { - let img = ImageRes { width: 1, height: 1, rgba: vec![[1.0; 4]], srgb: true }; + let img = ImageRes::new(1, 1, vec![[1.0; 4]], true); let params = AlphaParams { size_x: 0.5, ..AlphaParams::default() }; let image = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params, level: 0 }; assert_eq!((image.sample(0.4, 0.0, 0.5, 0) > 0.99, image.sample(0.6, 0.0, 0.5, 0)), (true, 0.0)); diff --git a/crates/paint/src/pickup.rs b/crates/paint/src/pickup.rs index c70c1f92..6d61b073 100644 --- a/crates/paint/src/pickup.rs +++ b/crates/paint/src/pickup.rs @@ -366,7 +366,12 @@ mod tests { let mut project = Project::new("test", "builtin:plane"); project.texture_sets.push(TextureSet::new("Set", 0, size)); let id = project.alloc_id(); - let fill = Fill { sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(), projection: Default::default(), link: None }; + let fill = Fill { + sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(), + projection: Default::default(), + sampling: Default::default(), + link: None, + }; let mut layer = Layer::new(id, "fill", LayerKind::Fill(fill), &[Channel::Roughness]); layer.mask = Some(Mask::new(MaskBackground::White)); project.insert_layer(0, layer, None, false).unwrap(); diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index e4ddad39..39ab2e2b 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -765,7 +765,7 @@ fn imported_hdr_environment_lights_the_ball() { // A procedural HDR: a hot orange sky over a dim blue ground (values far above 1). let (w, hh) = (256u32, 128u32); let rgba = (0..w * hh).map(|i| if i / w < hh / 2 { [12.0, 4.0, 1.0, 1.0] } else { [0.02, 0.05, 0.2, 1.0] }).collect(); - let sky = ImageRes { width: w, height: hh, rgba, srgb: false }; + let sky = ImageRes::new(w, hh, rgba, false); h.renderer.set_environment(&h.device, &h.queue, "resource:sky.hdr", Some(&sky)); let lit = render(&mut h, &frame, "env_hdr_resource"); assert_ne!(lit.px, base.px, "the imported environment changes the lighting"); @@ -1081,7 +1081,7 @@ fn spot_environment(dir: texturecraft_geom::glam::Vec3) -> ImageRes { if d.dot(dir) > 0.5 { [6.0, 6.0, 6.0, 1.0] } else { [0.02, 0.02, 0.02, 1.0] } }) .collect(); - ImageRes { width: w, height: hh, rgba, srgb: false } + ImageRes::new(w, hh, rgba, false) } #[test] diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 6256973b..70c4f246 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -18,6 +18,8 @@ use crate::TextureCraftApp; use crate::filter_slot::SLOT_HEIGHT; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; +use crate::past_end::PastEnd; +use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; @@ -147,6 +149,12 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { } } +/// Gap between the layer toolbar and the layer rows +const LAYER_TOOLBAR_GAP: f32 = 2.0; + +/// Least height of the drop space under the layer rows, so a drop to the bottom always has a target +const BOTTOM_DROP_MIN_HEIGHT: f32 = 24.0; + pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); @@ -204,10 +212,11 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { return; } - ui.add_space(2.0); - let ts = app.session.ts(); - let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); - let now = ui.input(|i| i.time); + ui.add_space(LAYER_TOOLBAR_GAP); + let set = app.session.ts(); + let stack: Vec = + app.session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.iter().rev().copied().collect()).unwrap_or_default(); + let now = ui.input(|input| input.time); app.layer_panel.begin(&app.session, now); egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { let mut count = 0; @@ -217,27 +226,28 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { // Empty space keeps the selection and drops below the rows let free = ui.available_height(); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if free.is_finite() { free.max(24.0) } else { 24.0 }), Sense::hover()); - if let Some(dragged) = dnd_release::(&resp) { - let bottom = app.session.doc.project.texture_sets.get(ts).and_then(|t| t.stack.first().copied()); + let drop_height = if free.is_finite() { free.max(BOTTOM_DROP_MIN_HEIGHT) } else { BOTTOM_DROP_MIN_HEIGHT }; + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), drop_height), Sense::hover()); + if let Some(dragged) = dnd_release::(&response) { + let bottom = app.session.doc.project.texture_sets.get(set).and_then(|texture_set| texture_set.stack.first().copied()); if let Some(layers) = selection_with(app, LayerId(*dragged)) { app.run("layer.move", json!({"layers": layers, "index": 0})); - } else if bottom.map(|b| b.0) != Some(*dragged) { + } else if bottom.map(|bottom| bottom.0) != Some(*dragged) { app.run("layer.move", json!({"layer": *dragged, "index": 0})); } } - match dnd_release::(&resp).map(|d| d.asset.clone()) { - Some(Asset::Material(m)) => { - app.run("material.apply", json!({"material": m, "index": 0})); + match dnd_release::(&response).map(|drag| drag.asset.clone()) { + Some(Asset::Material(material)) => { + app.run("material.apply", json!({"material": material, "index": 0})); } Some(Asset::Library(path)) => { app.run("material.load", json!({"path": path, "index": 0})); } _ => {} } - let material = resp.dnd_hover_payload::().is_some_and(|d| d.asset.is_material()); - if resp.dnd_hover_payload::().is_some() || material { - ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tokens.accent)); + let material = response.dnd_hover_payload::().is_some_and(|drag| drag.asset.is_material()); + if response.dnd_hover_payload::().is_some() || material { + ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(DROP_STROKE, tokens.accent)); } }); select_all_layers(app, ui); @@ -455,6 +465,9 @@ const GROUP_HEADER_LABEL_FONT_SIZE: f32 = 10.5; const ALTERNATE_LAYER_SHADE: f32 = 0.45; /// Maximum layer-tree nesting shown by the dock const MAX_LAYER_TREE_DEPTH: usize = 12; + +/// Width of the drop indicators: the line above a row and the outline round it or its mask +const DROP_STROKE: f32 = 2.0; /// Checkerboard cells along each thumbnail edge const THUMB_CHECKER_CELLS: usize = 4; /// Keep the group label and count readable when the panel is narrow @@ -671,18 +684,20 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name)) }); - let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); + // Only what the row draws of the mask (whether it is on, its background, its effect count): no clone per row per frame + let mask = + project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()).map(|mask| (mask.enabled, mask.background, mask.effects.len())); let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; - if let Some(mask) = &mask { + if let Some((mask_enabled, mask_background, mask_effect_count)) = mask { let mask_target = selected && !targets_content(app); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); - if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask.enabled) { - let white = mask.background == texturecraft_engine::core::MaskBackground::White; + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask_enabled) { + let white = mask_background == texturecraft_engine::core::MaskBackground::White; painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); - if !mask.effects.is_empty() { + if mask_effect_count > 0 { painter.text( mask_rect.center(), egui::Align2::CENTER_CENTER, @@ -693,7 +708,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); - if !mask.enabled { + if !mask_enabled { painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } let mask_response = ui @@ -769,7 +784,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize LayerKind::Group { .. } => "Folder", LayerKind::Instance { .. } => "Instance", }); - let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |mask| mask.effects.len()); + let effects = layer.content_effects.len() + mask.map_or(0, |(_, _, count)| count); let subtitle = match (source, effects) { (Some(source), _) => format!("{kind} · {} {source}", ic::LINK_SIMPLE), (None, 0) => kind.to_string(), @@ -1378,27 +1393,33 @@ fn blending_options_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) } }); } +/// Least width of a layer row's right-click menu, wide enough for its longest item and shortcut +const CONTEXT_MENU_MIN_WIDTH: f32 = 230.0; + +/// Side and corner radius of a colour tag square in the layer row's right-click menu +const TAG_SWATCH_SIZE: f32 = 16.0; +const TAG_SWATCH_RADIUS: f32 = 2.0; fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { - let tk = Tokens::get(ui.ctx()); - ui.set_min_width(230.0); - let lid = layer.id.0; + let tokens = Tokens::get(ui.ctx()); + ui.set_min_width(CONTEXT_MENU_MIN_WIDTH); + let layer_id = layer.id.0; let keymap = app.ui.keymap.clone(); // On one of several selected layers, remove, duplicate and group act on all of them let several = selection_with(app, layer.id); - let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, p: Value, enabled: bool| { - let mut b = egui::Button::new(label); - if let Some(sc) = crate::keymap::shortcut_of(&keymap, id) { - b = b.shortcut_text(sc); + let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, params: Value, enabled: bool| { + let mut button = egui::Button::new(label); + if let Some(shortcut) = crate::keymap::shortcut_of(&keymap, id) { + button = button.shortcut_text(shortcut); } - if ui.add_enabled(enabled, b).clicked() { + if ui.add_enabled(enabled, button).clicked() { let batch = matches!(id, "layer.remove" | "layer.duplicate" | "layer.group"); match several.as_ref().filter(|_| batch) { Some(layers) => app.run(id, json!({"layers": layers})), None => { - app.run("layer.select", json!({"layer": lid})); - app.run(id, p) + app.run("layer.select", json!({"layer": layer_id})); + app.run(id, params) } }; ui.close(); @@ -1407,19 +1428,19 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { // An instance edits its source mask until it gets its own let project = &app.session.doc.project; - let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.is_some()); + let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|owner| owner.mask.is_some()); // A switched-off mask has no values to export - let mask_on = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.as_ref().is_some_and(|m| m.enabled)); - run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": lid}), layer.mask.is_none()); - run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": lid}), layer.mask.is_none()); - run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": lid}), true); + let mask_on = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|owner| owner.mask.as_ref().is_some_and(|mask| mask.enabled)); + run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": layer_id}), layer.mask.is_none()); + run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": layer_id}), layer.mask.is_none()); + run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": layer_id}), true); ui.separator(); - run(app, ui, tr("Toggle mask"), "mask.toggle", json!({"layer": lid}), has_mask); - run(app, ui, tr("Invert mask background"), "mask.invertBackground", json!({"layer": lid}), has_mask); - run(app, ui, tr("Invert mask"), "mask.invert", json!({"layer": lid}), has_mask); - run(app, ui, tr("Clear mask"), "mask.clear", json!({"layer": lid}), has_mask); - run(app, ui, tr("Remove mask"), "mask.remove", json!({"layer": lid}), has_mask); + run(app, ui, tr("Toggle mask"), "mask.toggle", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Invert mask background"), "mask.invertBackground", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Invert mask"), "mask.invert", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Clear mask"), "mask.clear", json!({"layer": layer_id}), has_mask); + run(app, ui, tr("Remove mask"), "mask.remove", json!({"layer": layer_id}), has_mask); #[cfg(not(target_arch = "wasm32"))] if ui.add_enabled(mask_on, egui::Button::new(tr("Export mask to file..."))).clicked() { export_mask_file(app, layer); @@ -1430,57 +1451,63 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { ui.close(); } geometry_mask_menu(app, ui, layer); + ui.separator(); solo_menu(app, ui, layer.id); ui.separator(); - run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": lid}), !layer.is_group()); + run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": layer_id}), !layer.is_group()); #[cfg(not(target_arch = "wasm32"))] if ui.button(tr("Create smart material")).clicked() { let file = crate::library_dir().join(format!("{}.tcmat", texturecraft_engine::formats::sanitize_resource_name(&layer.name))); - if let Some(r) = app.run("material.save", json!({"layer": lid, "path": file.display().to_string(), "name": layer.name})) { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Smart material saved to {path}", &[("path", &p)]), false); + if let Some(saved) = app.run("material.save", json!({"layer": layer_id, "path": file.display().to_string(), "name": layer.name})) { + let path = saved.get("path").and_then(|path| path.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Smart material saved to {path}", &[("path", &path)]), false); app.library = None; } ui.close(); } #[cfg(not(target_arch = "wasm32"))] if ui.add_enabled(has_mask, egui::Button::new(tr("Create smart mask"))).clicked() { - app.run("layer.select", json!({"layer": lid})); + app.run("layer.select", json!({"layer": layer_id})); crate::smart_mask_menu::save(app, layer, &crate::library_dir()); ui.close(); } ui.separator(); - run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true); - run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true); + run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": layer_id}), true); + run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": layer_id}), true); let paste_layer = crate::menus::enabled(app, "layer.paste"); let paste_effect = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer); run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect); let paste_instance = crate::menus::enabled(app, "layer.pasteInstance"); run(app, ui, tr("Paste as instance"), "layer.pasteInstance", json!({}), paste_instance); - run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": lid}), true); - run(app, ui, tr("Instantiate across texture sets"), "layer.instantiateAll", json!({"layer": lid}), app.session.set_count() > 1); - run(app, ui, tr("Copy to all texture sets"), "layer.instantiateAll", json!({"layer": lid, "copy": true}), app.session.set_count() > 1); - run(app, ui, tr("Remove layer(s)"), "layer.remove", json!({"layer": lid}), true); - run(app, ui, tr("Group layer(s)"), "layer.group", json!({"layer": lid}), true); + run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": layer_id}), true); + let many_sets = app.session.set_count() > 1; + run(app, ui, tr("Instantiate across texture sets"), "layer.instantiateAll", json!({"layer": layer_id}), many_sets); + run(app, ui, tr("Copy to all texture sets"), "layer.instantiateAll", json!({"layer": layer_id, "copy": true}), many_sets); + run(app, ui, tr("Remove layer(s)"), "layer.remove", json!({"layer": layer_id}), true); + run(app, ui, tr("Group layer(s)"), "layer.group", json!({"layer": layer_id}), true); blending_options_menu(app, ui, layer); + + // Colour tags: none (crossed out), then each tag colour ui.separator(); ui.horizontal(|ui| { - let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, tk.text_dim), egui::StrokeKind::Inside); - ui.painter().line_segment([r.left_bottom(), r.right_top()], Stroke::new(1.0, tk.danger)); - if resp.clicked() { - app.run("layer.colorTag", json!({"layer": lid})); + let swatch_size = vec2(TAG_SWATCH_SIZE, TAG_SWATCH_SIZE); + let (swatch, response) = ui.allocate_exact_size(swatch_size, Sense::click()); + ui.painter().rect_stroke(swatch, TAG_SWATCH_RADIUS, Stroke::new(1.0, tokens.text_dim), egui::StrokeKind::Inside); + ui.painter().line_segment([swatch.left_bottom(), swatch.right_top()], Stroke::new(1.0, tokens.danger)); + if response.clicked() { + app.run("layer.colorTag", json!({"layer": layer_id})); } - for (i, c) in TAG_COLORS.iter().enumerate() { - let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - ui.painter().rect_filled(r, 2.0, *c); - if resp.clicked() { - app.run("layer.colorTag", json!({"layer": lid, "tag": i})); + for (tag, color) in TAG_COLORS.iter().enumerate() { + let (swatch, response) = ui.allocate_exact_size(swatch_size, Sense::click()); + ui.painter().rect_filled(swatch, TAG_SWATCH_RADIUS, *color); + if response.clicked() { + app.run("layer.colorTag", json!({"layer": layer_id, "tag": tag})); } } }); + ui.separator(); effect_menu(app, ui, layer); } @@ -1488,90 +1515,126 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { // --------------------------------------------------------------------------------------------- // Texture set settings +/// Size of a channel's remove button, and of the room Base color keeps for one +const CHANNEL_REMOVE_SIZE: f32 = 18.0; + +/// The sizes a texture set and each of its UV tiles can take +const TEXTURE_SET_RESOLUTIONS: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192]; + +/// Air between the General properties grid's columns and rows +const GENERAL_GRID_SPACING: egui::Vec2 = vec2(8.0, 6.0); + +/// Air above the Channels and Mesh maps captions +const SECTION_GAP: f32 = 8.0; + +/// Air between the channel list and the height and normal settings +const CHANNEL_SETTINGS_GAP: f32 = 6.0; + +/// Range of the Height to normal strength slider +const HEIGHT_STRENGTH_RANGE: std::ops::RangeInclusive = 0.0..=10.0; + +/// A mesh map row's colour square, its corner radius, the size of its file name and of its menu's dots +const MESH_MAP_SWATCH_SIZE: f32 = 26.0; +const MESH_MAP_SWATCH_RADIUS: f32 = 2.0; +const MESH_MAP_FILE_TEXT_SIZE: f32 = 10.5; +const MESH_MAP_MENU_ICON_SIZE: f32 = 13.0; + pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let ts = app.session.ts(); - let Some(set) = app.session.doc.project.texture_sets.get(ts).cloned() else { return }; + let tokens = Tokens::get(ui.ctx()); + let set_index = app.session.ts(); + let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; egui::ScrollArea::vertical().id_salt("tss").show(ui, |ui| { ui.label(caption(tr("General properties"))); - egui::Grid::new("tss_grid").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| { + egui::Grid::new("tss_grid").num_columns(2).spacing(GENERAL_GRID_SPACING).show(ui, |ui| { ui.label(tr("Name")); - ui.label(RichText::new(&set.name).color(tk.text_strong)); + ui.label(RichText::new(&set.name).color(tokens.text_strong)); ui.end_row(); + ui.label(tr("Size")); egui::ComboBox::from_id_salt("ts_size").selected_text(format!("{}", set.resolution)).show_ui(ui, |ui| { - for r in [256u32, 512, 1024, 2048, 4096, 8192] { - if ui.selectable_label(r == set.resolution, format!("{r}")).clicked() { - app.start_resize(ts, r); + for resolution in TEXTURE_SET_RESOLUTIONS { + if ui.selectable_label(resolution == set.resolution, format!("{resolution}")).clicked() { + app.start_resize(set_index, resolution); } } }); ui.end_row(); + ui.label(tr("UV tiles (UDIM)")); let mut tiled = !set.uv_tiles.is_empty(); if ui.checkbox(&mut tiled, "").changed() { - app.run("textureSet.uvTiles", json!({"ts": ts, "enabled": tiled})); + app.run("textureSet.uvTiles", json!({"ts": set_index, "enabled": tiled})); } ui.end_row(); - // Each tile's own size (per-tile resolution). + + // Each tile's own size for &udim in &set.uv_tiles { - let r = set.tile_resolution(udim); - ui.label(RichText::new(format!(" {udim}")).color(tk.text_dim)); - egui::ComboBox::from_id_salt(("ts_tile", udim)).selected_text(format!("{r}")).show_ui(ui, |ui| { - for v in [256u32, 512, 1024, 2048, 4096, 8192] { - if ui.selectable_label(v == r, format!("{v}")).clicked() { - app.run("textureSet.tile.resolution", json!({"ts": ts, "tile": udim, "resolution": v})); + let tile_resolution = set.tile_resolution(udim); + ui.label(RichText::new(format!(" {udim}")).color(tokens.text_dim)); + egui::ComboBox::from_id_salt(("ts_tile", udim)).selected_text(format!("{tile_resolution}")).show_ui(ui, |ui| { + for resolution in TEXTURE_SET_RESOLUTIONS { + if ui.selectable_label(resolution == tile_resolution, format!("{resolution}")).clicked() { + app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": udim, "resolution": resolution})); } } }); ui.end_row(); } + ui.label(tr("Shader instance")); ui.label(tr("Main shader")); ui.end_row(); }); - ui.add_space(8.0); + + ui.add_space(SECTION_GAP); ui.horizontal(|ui| { ui.label(caption(tr("Channels"))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.menu_button(tr("Add channel"), |ui| { - for c in Channel::ALL { - if !set.has_channel(c) && ui.button(tr(c.label())).clicked() { - app.run("textureSet.channel.add", json!({"ts": ts, "channel": c.id()})); + for channel in Channel::ALL { + if !set.has_channel(channel) && ui.button(tr(channel.label())).clicked() { + app.run("textureSet.channel.add", json!({"ts": set_index, "channel": channel.id()})); ui.close(); } } }); }); }); - for (c, f) in &set.channels { + + for (channel, format) in &set.channels { ui.horizontal(|ui| { - ui.label(RichText::new(tr(c.label())).strong()); + ui.label(RichText::new(tr(channel.label())).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if *c != Channel::BaseColor && icon_button(ui, ic::X, tr("Remove channel"), false, 18.0).clicked() { - app.run("textureSet.channel.remove", json!({"ts": ts, "channel": c.id()})); + // Base color can't be removed: its × room stays, so every format ends on one column + if *channel == Channel::BaseColor { + ui.allocate_exact_size(vec2(CHANNEL_REMOVE_SIZE, CHANNEL_REMOVE_SIZE), Sense::hover()); + } else if icon_button(ui, ic::X, tr("Remove channel"), false, CHANNEL_REMOVE_SIZE).clicked() { + app.run("textureSet.channel.remove", json!({"ts": set_index, "channel": channel.id()})); } - ui.label(RichText::new(f.label()).color(tk.text_dim)); + ui.label(RichText::new(format.label()).color(tokens.text_dim)); }); }); } - ui.add_space(6.0); - let mut hs = set.height_strength; - if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2) { - app.run("textureSet.settings", json!({"ts": ts, "heightStrength": hs, "merge": merge})); + + ui.add_space(CHANNEL_SETTINGS_GAP); + let mut height_strength = set.height_strength; + if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut height_strength, HEIGHT_STRENGTH_RANGE, 2) { + app.run("textureSet.settings", json!({"ts": set_index, "heightStrength": height_strength, "merge": merge})); } + let directx = app.session.doc.project.normal_format == texturecraft_engine::core::NormalFormat::DirectX; combo(ui, tr("Normal map format"), if directx { "DirectX" } else { "OpenGL" }, |ui| { for (id, label, on) in [("openGl", "OpenGL", !directx), ("directX", "DirectX", directx)] { if ui.selectable_label(on, label).clicked() && !on { - app.run("textureSet.settings", json!({"ts": ts, "normalFormat": id})); + app.run("textureSet.settings", json!({"ts": set_index, "normalFormat": id})); } } }) .on_hover_text(tr( "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", )); - ui.add_space(8.0); + + ui.add_space(SECTION_GAP); ui.horizontal(|ui| { ui.label(caption(tr("Mesh maps"))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -1580,37 +1643,39 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - for m in BakedMap::ALL { - let present = app.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&m)); + for map in BakedMap::ALL { + let present = app.session.doc.baked.get(&set_index).is_some_and(|baked| baked.maps.contains_key(&map)); let row = ui.horizontal(|ui| { - let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover()); - ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button }); + let (swatch, _) = ui.allocate_exact_size(vec2(MESH_MAP_SWATCH_SIZE, MESH_MAP_SWATCH_SIZE), Sense::hover()); + ui.painter().rect_filled(swatch, MESH_MAP_SWATCH_RADIUS, if present { mesh_map_color(map) } else { tokens.button }); ui.vertical(|ui| { - ui.label(RichText::new(tr(crate::i18n::baked_map_label(m))).strong()); + ui.label(RichText::new(tr(crate::i18n::baked_map_label(map))).strong()); ui.label( - RichText::new(if present { format!("{}_{}", set.name, m.id()) } else { tr("Missing (bake to create)").into() }) - .size(10.5) - .color(tk.text_dim), + RichText::new(if present { format!("{}_{}", set.name, map.id()) } else { tr("Missing (bake to create)").into() }) + .size(MESH_MAP_FILE_TEXT_SIZE) + .color(tokens.text_dim), ); }); - // An image resource instead of a bake, or no map. + + // An image resource instead of a bake, or no map ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { + ui.menu_button(RichText::new(ic::DOTS_THREE).size(MESH_MAP_MENU_ICON_SIZE), |ui| { if let Some(name) = image_menu(app, ui) { - app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); } ui.separator(); if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() { - app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": m.id()})); + app.run("textureSet.meshMap.clear", json!({"ts": set_index, "map": map.id()})); ui.close(); } }); }); }); - // A shelf image dropped on the row becomes this mesh map. - let resp = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); - if let Some(name) = image_drop(ui, &resp) { - app.run("textureSet.meshMap.set", json!({"ts": ts, "map": m.id(), "image": name})); + + // A shelf image dropped on the row becomes this mesh map + let response = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); + if let Some(name) = image_drop(ui, &response) { + app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); } } }); @@ -1696,7 +1761,7 @@ mod image_menu_tests { // The menu reads decoded images; fixture bytes are never imported or decoded for index in 0..image_count { let name = format!("image-{index:04}.png"); - let image = ImageRes { width: 32, height: 32, rgba: vec![[index as f32 / image_count as f32, 0.5, 0.25, 1.0]; 32 * 32], srgb: false }; + let image = ImageRes::new(32, 32, vec![[index as f32 / image_count as f32, 0.5, 0.25, 1.0]; 32 * 32], false); session.doc.resources.insert(name.clone(), Arc::new(vec![0])); session.images.insert(name, Arc::new(image)); } @@ -1754,10 +1819,9 @@ mod image_menu_tests { } } -/// An image from the Assets panel dropped on `resp`, outlined while one hovers it. Other assets -/// are left for the drop targets around it. +/// An image from the Assets panel dropped on `resp`, outlined while one hovers it; other assets are left for the drop targets around it pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { - if !resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { + if !resp.dnd_hover_payload::().is_some_and(|drag| matches!(drag.asset, Asset::Texture(_))) { return None; } @@ -1822,6 +1886,12 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); + let scope = SectionScope::Docked; + if let Some(tabs) = properties_fill_tabs(app) { + crate::property_sheet::section_tabs(ui, scope, 0, &tabs); + } + let area = egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]); + crate::property_sheet::in_scope(ui, scope, |ui| properties_scrolled(app, ui, area, PastEnd::Always)); } /// What the docked Properties list keeps its own scroll place for: the selected layer and the part of it edited, none for the tool @@ -1834,6 +1904,35 @@ fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> { app.session.selected_layer().map(|layer| (layer, app.session.target)) } +/// The sections in `area`, leaving the solid bar's room even without it, so the bar coming in refits no row (flipped it every frame) +pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::ScrollArea, past_end: PastEnd) { + let sheet_width = (ui.available_width() - ui.spacing().scroll.allocated_width()).max(0.0); + area.show(ui, |ui| { + ui.set_max_width(sheet_width); + crate::property_sheet::forget_sections(ui); + properties_contents(app, ui); + + // Blank space under the rows lets the last section's top reach the top of the list, as the reference panel scrolls + let scrolls = ui.min_rect().height() > ui.clip_rect().height(); + if past_end == PastEnd::Always || scrolls { + ui.add_space(crate::property_sheet::room_past_end(ui)); + } + }); +} + + if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { + return None; + } + + let project = &app.session.doc.project; + match app.session.target { + StackTarget::Content => { + let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; + } + _ => None, + } +} + /// Room around the Properties rows not yet laid out by the property sheet: the sheet's side padding, so both start under the panel's name const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::PAD as i8, 4); @@ -1859,6 +1958,8 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), (Some(layer), StackTarget::Effect(effect)) => legacy_body(ui, |ui| effect_properties(app, ui, layer, effect)), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => legacy_body(ui, |ui| fill_properties(app, ui, layer)), + (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() => legacy_body(ui, |ui| { ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); }), @@ -1923,26 +2024,51 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { }); } +/// Height of the brush preview over the tool's properties, and its corner radius +const BRUSH_PREVIEW_HEIGHT: f32 = 88.0; +const BRUSH_PREVIEW_CORNER_RADIUS: f32 = 2.0; + +/// The preview stroke: its segments, its margin from the preview's left (each side of its half), its wave's phase span in radians and its swing +const PREVIEW_STROKE_STEPS: usize = 40; +const PREVIEW_STROKE_MARGIN: f32 = 14.0; +const PREVIEW_STROKE_WAVE: f32 = 9.0; +const PREVIEW_STROKE_SWING: f32 = 18.0; + +/// The preview stroke's width: [`PREVIEW_STROKE_WIDTH_SCALE`] points for each [`PREVIEW_SIZE_UNIT`] of brush size, kept inside [`PREVIEW_STROKE_WIDTH`] +const PREVIEW_SIZE_UNIT: f32 = 0.25; +const PREVIEW_STROKE_WIDTH_SCALE: f32 = 60.0; +const PREVIEW_STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=30.0; + +/// Faintest the preview stroke draws, so a low flow or opacity still shows +const PREVIEW_STROKE_MIN_ALPHA: u8 = 30; + +/// Radius of the preview's material sphere, and the colour it shows when the tool has no base colour +const PREVIEW_SPHERE_RADIUS: f32 = 36.0; +const PREVIEW_FALLBACK_BASE_COLOR: [f32; 3] = [0.8; 3]; + +/// Gap between the brush preview and the tab buttons +const BRUSH_PREVIEW_GAP: f32 = 4.0; + fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { 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 (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); let painter = ui.painter(); - painter.rect_filled(rect, 2.0, tokens.viewport); + painter.rect_filled(rect, BRUSH_PREVIEW_CORNER_RADIUS, 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)); + for step in 0..=PREVIEW_STROKE_STEPS { + let fraction = step as f32 / PREVIEW_STROKE_STEPS as f32; + let x = rect.left() + PREVIEW_STROKE_MARGIN + fraction * (half_width - 2.0 * PREVIEW_STROKE_MARGIN); + points.push(pos2(x, rect.center().y + (fraction * PREVIEW_STROKE_WAVE).sin() * PREVIEW_STROKE_SWING)); } - let stroke_width = (brush.size / 0.25 * 60.0).clamp(2.0, 30.0); + let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); 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); + let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); + ui.add_space(BRUSH_PREVIEW_GAP); ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; @@ -2517,6 +2643,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { material_controls(app, ui); } +/// Space between the tool's channel chips and the first channel value +const CHIPS_GAP: f32 = 4.0; + /// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. /// The Material tab and the Smudge panel both draw these, so they share one set of flags. fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { @@ -2539,7 +2668,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let channels = material_channel_chips(app, ui); - ui.add_space(4.0); + ui.add_space(CHIPS_GAP); if !targets_content(app) { let mut gray = app.session.tool.mask_value; @@ -2582,6 +2711,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { } } } + if app.session.tool.tool == Tool::Eraser { ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim)); } @@ -2589,13 +2719,16 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let LayerKind::Fill(fill) = &layer.kind else { return }; - if let Some(link) = &fill.link { - link_properties(app, ui, layer.id, link); - ui.add_space(6.0); - } let on: Vec = layer.channels.keys().copied().collect(); - ui.label(caption(tr("Fill"))); - fill_editor(app, ui, fill, &json!({"layer": layer.id.0}), &on, layer.id); + PropertySheet::show(ui, ("fill_sheet", layer.id.0), |sheet| { + }); + legacy_body(ui, |ui| { + if let Some(link) = &fill.link { + link_properties(app, ui, layer.id, link); + ui.add_space(6.0); + } + fill_editor(app, ui, fill, &json!({"layer": layer.id.0}), &on, layer.id); + }); } /// A MaterialCraft material's presets and exposed inputs; edits store the value and re-cook the @@ -2719,11 +2852,11 @@ fn link_param_editor(ui: &mut Ui, layer: LayerId, p: &LinkParam) -> Option Value { - let mut params = base.clone(); - if let (Some(fields), Value::Object(extra)) = (params.as_object_mut(), extra) { - fields.extend(extra); + let mut merged = base.clone(); + if let (Some(fields), Value::Object(extra_fields)) = (merged.as_object_mut(), extra) { + fields.extend(extra_fields); } - params + merged } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). @@ -2815,12 +2948,6 @@ const FILL_CHANNELS_GAP: f32 = 4.0; /// Projection and sources of a fill layer or fill effect (`base`) for its enabled channels; `reader` owns it fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, enabled_channels: &[Channel], reader: LayerId) { let salt = base.to_string(); - if let Projection::Decal(decal) = &fill.projection { - decal_editor(app, ui, decal, base, reader); - } else { - projection_editor(app, ui, &fill.projection, "layer.fill.projection", base, &salt); - } - 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(); @@ -2849,6 +2976,9 @@ 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; +/// Slider range of a fill's UV offset and world offset, one texture or mesh width either way +const FILL_OFFSET_RANGE: std::ops::RangeInclusive = -1.0..=1.0; + /// 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; @@ -2887,53 +3017,135 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, projection: &Projec // One id per fill so each keeps its own open or closed state section(ui, &format!("sec_fill_transform{salt}"), tr("UV transformations"), true, |ui| { - projection_transform(ui, projection, &mut edit); + projection_transform(ui, projection, salt, &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 +/// Width of the lock button between a pair of sliders +const PAIR_LOCK_WIDTH: f32 = 22.0; + +/// Height of the lock button, which sits level with the sliders' tracks at the bottom of the pair +const PAIR_LOCK_HEIGHT: f32 = 18.0; + +/// Size of the lock button's icon +const PAIR_LOCK_ICON_SIZE: f32 = 14.0; + +/// Height of one slider: its value row over its track +const PAIR_SLIDER_HEIGHT: f32 = 34.0; + +/// Two sliders side by side under `label` (across and down), locked together while `lock` is given and set (the second greyed); the pair once one is edited, with [`slider_edit`]'s `merge` +fn pair_sliders( + ui: &mut Ui, + label: &str, + mut values: [f32; 2], + range: std::ops::RangeInclusive, + decimals: usize, + lock: Option<&mut bool>, +) -> Option<([f32; 2], bool)> { + let mut edited = None; + ui.label(label); + + let locked = lock.as_deref().copied().unwrap_or(false); + let lock_width = if lock.is_some() { PAIR_LOCK_WIDTH } else { ui.spacing().item_spacing.x }; + let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), PAIR_SLIDER_HEIGHT), Sense::hover()); + let half = ((rect.width() - lock_width) / 2.0).max(1.0); + let left = egui::Rect::from_min_size(rect.min, egui::vec2(half, rect.height())); + let right = egui::Rect::from_min_size(egui::pos2(rect.right() - half, rect.top()), egui::vec2(half, rect.height())); + let slot = |ui: &mut Ui, area: egui::Rect| ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Min))); + + if let Some(merge) = slider_edit(&mut slot(ui, left), "", &mut values[0], range.clone(), decimals) { + if locked { + values[1] = values[0]; } - Projection::Decal(_) => return, + edited = Some(merge); + } + + if let Some(lock) = lock { + let middle = + egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.bottom() - PAIR_LOCK_HEIGHT / 2.0), egui::vec2(PAIR_LOCK_WIDTH, PAIR_LOCK_HEIGHT)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(middle).layout(egui::Layout::centered_and_justified(egui::Direction::LeftToRight))); + let icon = if *lock { ic::LOCK_SIMPLE } else { ic::LOCK_SIMPLE_OPEN }; + if icon_button(&mut child, icon, tr("Lock the two values together"), *lock, PAIR_LOCK_ICON_SIZE).clicked() { + *lock = !*lock; + if *lock && values[1] != values[0] { + values[1] = values[0]; + edited = Some(false); + } + } + } + + let mut second = slot(ui, right); + second.add_enabled_ui(!locked, |ui| { + if let Some(merge) = slider_edit(ui, "", &mut values[1], range.clone(), decimals) { + edited = Some(merge); + } + }); + + edited.map(|merge| (values, merge)) +} + +/// A projection's UV transformations: tiling across and down (locked together until unlocked), rotation and offset; a 3D projection's scale and world offset too +fn projection_transform(ui: &mut Ui, projection: &Projection, salt: &str, edit: &mut impl FnMut(Value)) { + let (tiling, rotation, offset, offset_key) = match projection { + Projection::Uv { scale, rotation, offset } => (*scale, *rotation, *offset, "offset"), + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => (uv.tiling, uv.rotation, uv.offset, "uvOffset"), + Projection::UvTile => return, }; - if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, FILL_SCALE_RANGE, 2) { - edit(json!({"scale": scale, "merge": merge})); + + let lock_id = ui.make_persistent_id(("fill_tiling_lock", salt)); + let mut locked = ui.data(|data| data.get_temp::(lock_id)).unwrap_or(tiling[0] == tiling[1]); + let was_locked = locked; + if let Some((edited, merge)) = pair_sliders(ui, tr("Tiling"), tiling, FILL_SCALE_RANGE, 2, Some(&mut locked)) { + edit(json!({"tiling": edited, "merge": merge})); + } + if locked != was_locked { + ui.data_mut(|data| data.insert_temp(lock_id, locked)); + } + + let mut rotation_degrees = rotation; + 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((edited, merge)) = pair_sliders(ui, tr("Offset"), offset, FILL_OFFSET_RANGE, 2, None) { + edit(json!({offset_key: edited, "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, FILL_ROTATION_DEGREES_RANGE, 0) { - edit(json!({"rotation": rotation_degrees, "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, .. } => { + Projection::Triplanar { scale, offset, .. } | Projection::Planar { scale, offset, .. } => { + world_scale(ui, *scale, edit); 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(_) => {} + Projection::Spherical { scale, .. } | Projection::Cylindrical { scale, .. } => world_scale(ui, *scale, edit), + Projection::Uv { .. } | Projection::UvTile | Projection::Warp { .. } => {} } } -/// A slider per offset component ("Offset U", …): the whole offset once one is edited, with -/// [`slider_edit`]'s `merge`. -fn offset_sliders(ui: &mut Ui, axes: [&str; N], mut v: [f32; N]) -> Option<([f32; N], bool)> { +/// A 3D projection's scale: how many times its pattern fits across the mesh +fn world_scale(ui: &mut Ui, scale: f32, edit: &mut impl FnMut(Value)) { + let mut scale = scale; + if let Some(merge) = slider_edit(ui, tr("Scale"), &mut scale, FILL_SCALE_RANGE, 2) { + edit(json!({"scale": scale, "merge": merge})); + } +} + +/// A slider per offset component ("Offset U", …): the whole offset once one is edited, with [`slider_edit`]'s `merge` +fn offset_sliders(ui: &mut Ui, axes: [&str; N], mut values: [f32; N]) -> Option<([f32; N], bool)> { let mut edit = None; - for (axis, x) in axes.iter().zip(v.iter_mut()) { - edit = edit.or(slider_edit(ui, &trf("Offset {axis}", &[("axis", axis)]), x, -1.0..=1.0, 2)); + for (axis, value) in axes.iter().zip(values.iter_mut()) { + edit = edit.or(slider_edit(ui, &trf("Offset {axis}", &[("axis", axis)]), value, FILL_OFFSET_RANGE, 2)); } - edit.map(|merge| (v, merge)) + + edit.map(|merge| (values, merge)) } -/// The axis a planar or cylindrical projection runs along: the one picked, if any. +/// The axis a planar or cylindrical projection runs along: the one picked, if any fn axis_combo(ui: &mut Ui, axis: u8) -> Option { let mut picked = None; combo(ui, tr("Axis"), ["X", "Y", "Z"].get(usize::from(axis)).copied().unwrap_or("Z"), |ui| { @@ -2946,107 +3158,6 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option { picked } -/// A decal's frame: place it with a click in the 3D view, then size, turn and shift it. `base` is the -/// `{layer}` or `{effect}` holding it (a mask fill effect's decal edits like a layer's); `layer` is the reader. -fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base: &Value, layer: LayerId) { - // What a placing click or the stack selection names: the effect when the decal is a mask effect's - let holder = base.get("effect").and_then(Value::as_u64).map_or(layer, LayerId); - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Decal"))); - let placing = app.placing_decal == Some(holder); - let label = format!("{} {}", ic::CROSSHAIR, if placing { tr("Click the mesh to place the decal") } else { tr("Place on the surface") }); - if ui.selectable_label(placing, label).on_hover_text(tr("The next click in the 3D view moves the decal there")).clicked() { - app.placing_decal = if placing { None } else { Some(holder) }; - } - let (lo, hi) = app.session.mesh.bounds(); - let diag = (hi - lo).length().max(1e-3); - let mut v = [d.size[0], d.size[1], d.rotation, d.offset[0], d.offset[1], d.depth]; - let rows = [ - (tr("Width"), diag * 0.01..=diag * 2.0), - (tr("Height"), diag * 0.01..=diag * 2.0), - (tr("Rotation (degrees)"), 0.0..=360.0), - (tr("Offset right"), -diag..=diag), - (tr("Offset up"), -diag..=diag), - (tr("Depth"), diag * 0.005..=diag), - ]; - let mut edit = None; - for (row, ((label, range), x)) in rows.into_iter().zip(v.iter_mut()).enumerate() { - edit = edit.or(slider_edit(ui, label, x, range, 3).map(|merge| (row, merge))); - } - - // The lock is a setting of the editor, not of the decal: every decal starts locked - let keep_id = ui.scope_id().with(("decal_keep_proportions", holder.0)); - let mut keep = ui.ctx().data(|data| data.get_temp::(keep_id)).unwrap_or(true); - if ui.checkbox(&mut keep, tr("Keep proportions")).on_hover_text(tr("Width and height follow each other by the image's aspect")).changed() { - ui.ctx().data_mut(|data| data.insert_temp(keep_id, keep)); - if keep { - app.run("layer.decal.set", with(base, json!({"keepProportions": true}))); - } - } - let mut flip = d.flip; - let flipped = ui.horizontal(|ui| ui.checkbox(&mut flip[0], tr("Flip U")).changed() | ui.checkbox(&mut flip[1], tr("Flip V")).changed()).inner; - if flipped { - app.run("layer.decal.set", with(base, json!({"flipU": flip[0], "flipV": flip[1]}))); - } - if let Some((row, merge)) = edit { - // Locked: the edited side sets the other (a height sets the width, anything else the height) - let size = if keep && row == 1 { json!(v[1]) } else { json!([v[0], v[1]]) }; - app.run( - "layer.decal.set", - with(base, json!({"size": size, "keepProportions": keep && row < 2, "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5], "merge": merge})), - ); - } - decal_symmetry_editor(app, ui, d, base); - ui.label( - RichText::new(tr("The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.")) - .size(10.5) - .color(tk.text_dim), - ); -} - -/// The decal's mirrored copy on the other side of the mesh: the axis it is mirrored across and how its image is flipped -fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, decal: &Decal, base: &Value) { - let axes = ["X", "Y", "Z"]; - let axis = decal.symmetry.map(|symmetry| usize::from(symmetry.axis)); - let mut picked = None; - combo(ui, tr("Mirror across"), axis.and_then(|axis| axes.get(axis).copied()).unwrap_or_else(|| tr("Off")), |ui| { - if ui.selectable_label(axis.is_none(), tr("Off")).clicked() && axis.is_some() { - picked = Some(json!({"symmetry": "off"})); - } - for (i, name) in axes.into_iter().enumerate() { - if ui.selectable_label(axis == Some(i), name).clicked() && axis != Some(i) { - picked = Some(json!({"symmetry": name.to_ascii_lowercase()})); - } - } - }); - - if let Some(symmetry) = decal.symmetry { - let flips = [(DecalFlip::None, tr("None"), "none"), (DecalFlip::U, "U", "u"), (DecalFlip::V, "V", "v")]; - let current = flips.iter().find(|flip| flip.0 == symmetry.flip).map_or("", |flip| flip.1); - combo(ui, tr("Flip the copy's image"), current, |ui| { - for (flip, name, id) in flips { - if ui.selectable_label(flip == symmetry.flip, name).clicked() && flip != symmetry.flip { - picked = Some(json!({"symmetryFlip": id})); - } - } - }); - } - - if let Some(symmetry) = decal.symmetry { - // The plane moves within the mesh, as the symmetry popup's axis position does - let (lo, hi) = app.session.mesh.bounds(); - let limit = ((hi - lo) * 0.5)[usize::from(symmetry.axis.min(2))]; - let mut offset = symmetry.offset; - if let Some(merge) = slider_edit(ui, tr("Axis position"), &mut offset, -limit..=limit, 2) { - picked = Some(json!({"symmetryOffset": offset, "merge": merge})); - } - } - - if let Some(change) = picked { - app.run("layer.decal.set", with(base, change)); - } -} - /// Space a fill channel's color swatch leaves at the group's right edge const CHANNEL_SWATCH_MARGIN: f32 = 4.0; /// Width of a pattern's low and high swatches @@ -3191,10 +3302,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe let id = effect_id.0; + // Property sheets keep the panel's own edges; only the rows not yet laid out by one get the legacy margin match &effect.kind { - EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), - EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), - EffectKind::Fill { source, projection } => { + EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), + EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); let target = crate::fill_source_target::FillSourceTarget::Mask { effect: id }; @@ -3232,21 +3343,17 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } Source::Image { .. } => { - if let Projection::Decal(decal) = projection { - decal_editor(app, ui, decal, &json!({"effect": id}), layer.id); - } else { - projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); - } + projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); } } if anchors.is_empty() { ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); } - } + }), EffectKind::Material(fill) => { - ui.label(caption(tr("Fill"))); let enabled: Vec = fill.sources.keys().copied().collect(); - fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id); + PropertySheet::show(ui, ("fill_effect_sheet", id), |sheet| { + }); } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); @@ -3256,8 +3363,8 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.") }; ui.label(RichText::new(text).color(tokens.text_dim)); - } - EffectKind::Paint => { + }), + EffectKind::Paint => legacy_body(ui, |ui| { let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { tr("Paint on the mesh to edit the layer content.") } else { @@ -3267,8 +3374,8 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - } - EffectKind::Path(paths) => { + }), + EffectKind::Path(paths) => legacy_body(ui, |ui| { ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) .color(tokens.text_dim), @@ -3292,12 +3399,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } + }), } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), other => { ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); - } + }), } } diff --git a/crates/ui-egui/src/exact_entry_open.rs b/crates/ui-egui/src/exact_entry_open.rs new file mode 100644 index 00000000..67abc1b5 --- /dev/null +++ b/crates/ui-egui/src/exact_entry_open.rs @@ -0,0 +1,5 @@ +//! The Levels editor's mark that its exact-entry fields are shown + +/// Marks the exact-entry fields as shown; they appear on a handle's double-click or Enter and close when typing ends +#[derive(Clone, Copy)] +pub(crate) struct ExactEntryOpen; diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 51464449..60e5a7b4 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -640,7 +640,7 @@ mod tests { assert!(gpu.sync(&mut s, None, None, 0, 0.0).image_aux.is_empty()); assert!(gpu.aux_image.is_none()); - let replacement = Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true }); + let replacement = Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true)); s.images.insert(name.clone(), replacement); execute(&mut s, "viewport.view", &json!({"mode": "image", "image": name})).unwrap(); let updated = gpu.sync(&mut s, Some(AuxView::Image), None, 0, 0.0); diff --git a/crates/ui-egui/src/gray_slider.rs b/crates/ui-egui/src/gray_slider.rs index 0ea4dfd2..eac04af1 100644 --- a/crates/ui-egui/src/gray_slider.rs +++ b/crates/ui-egui/src/gray_slider.rs @@ -21,7 +21,10 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option &'static str { + use texturecraft_engine::core::Filtering; + match filtering { + Filtering::BilinearHq => n_("Bilinear | HQ"), + Filtering::BilinearSharp => n_("Bilinear | Sharp"), + Filtering::Nearest => n_("Nearest"), + } +} + +/// Whether a fill repeats past its tile, as the UV Wrap combo names it +pub(crate) fn wrap_label(wrap: texturecraft_engine::core::UvWrap) -> &'static str { + use texturecraft_engine::core::UvWrap; + match wrap { + UvWrap::None => n_("None"), + UvWrap::RepeatHorizontally => n_("Repeat horizontally"), + UvWrap::RepeatVertically => n_("Repeat vertically"), + UvWrap::Repeat => n_("Repeat"), + } +} + /// Display labels belong to the UI; the model exposes only map identities pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'static str { use texturecraft_engine::core::BakedMap; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 90519b44..0a9ad4d2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -28,10 +28,14 @@ pub mod export_templates; mod export_window; #[cfg(not(target_arch = "wasm32"))] pub mod file_dialogs; +mod fill_panel; +mod fill_pictures; mod fill_source_slot; mod fill_source_target; +mod fill_symmetry_panel; mod filter_slot; pub mod fonts; +mod frame_gizmo; mod generator_panel; pub mod gpu; mod gray_slider; @@ -54,6 +58,8 @@ mod mask_preview_image; mod material_preview_image; pub mod menus; mod mesh_export_options; +mod move_hold; +pub mod move_on_model; mod name_error; mod named_layout; pub mod named_layouts; @@ -63,12 +69,16 @@ mod nav_view; pub mod new_project_advanced; mod orb_shape; pub mod parity; +mod past_end; mod path_hit; mod path_surface_cache; mod pattern_panel; mod pattern_target; pub mod pbr_import; +mod placement; +mod pointer_lock; mod popup_drag; +mod preview_dots; mod preview_image; mod preview_request; mod preview_worker; @@ -76,6 +86,10 @@ pub mod profile; #[cfg(not(target_arch = "wasm32"))] mod project_config; pub mod project_form; +mod projection_gizmo; +mod projection_kind; +mod projection_preview; +mod projector_outline; pub mod properties_popup; mod property_sheet; mod query_field; @@ -88,6 +102,7 @@ mod resource_picker_choice; mod resource_picker_item; mod resource_picker_tab; mod resource_picker_tile; +mod round_gizmo; mod running_bake; pub mod saved_search; mod screen_color_pick; @@ -122,6 +137,7 @@ mod uv_tile_grid; mod uv_view_map; mod view_mode_picker; pub mod viewport; +mod warp_checker; pub mod web_files; pub mod widgets; pub mod windows; @@ -236,8 +252,8 @@ pub struct TextureCraftApp { pub last_paint_point: Option, /// The last finished 2D stroke's endpoint, scoped to its mesh and texture set for Shift+click lines pub last_paint_uv: Option, - /// The decal layer the next click in the 3D view places. - pub placing_decal: Option, + /// The fill whose Move on model button is held down: dragging slides its projection, Shift or the right button turns it, the wheel scales it + pub moving_on_model: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, /// The color selection the next click in the 3D or 2D view picks an ID color for @@ -344,7 +360,7 @@ impl TextureCraftApp { render: render_mode::RenderView::default(), last_paint_point: None, last_paint_uv: None, - placing_decal: None, + moving_on_model: None, properties_popup: None, picking_id_color: None, picking_symmetry_plane: false, @@ -925,6 +941,13 @@ struct CameraGlide { const GLIDE_SECONDS: f64 = 0.35; +/// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames) +const FRAME_AVERAGE_KEEP: f32 = 0.9; +/// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason +const UI_SCALE_APPLIED: std::ops::RangeInclusive = 0.5..=3.0; +/// Zoom factors closer than this are the same zoom (float noise), so the zoom is not set again each frame +const SAME_ZOOM_TOLERANCE: f32 = 1e-3; + impl TextureCraftApp { /// Advance the camera glide by one frame. fn step_camera_glide(&mut self, ctx: &egui::Context) { @@ -953,6 +976,11 @@ impl TextureCraftApp { } impl eframe::App for TextureCraftApp { + /// A drag that holds the pointer reads the pointer's moves as moves of a pointer no screen edge stops + fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { + pointer_lock::rewrite(ctx, raw_input); + } + /// The browser never tells eframe the page is closing, so save often there. fn auto_save_interval(&self) -> std::time::Duration { std::time::Duration::from_secs(if cfg!(target_arch = "wasm32") { 5 } else { 30 }) @@ -966,13 +994,14 @@ impl eframe::App for TextureCraftApp { } fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - let t0 = now_ms(); - let now = ctx.input(|i| i.time); - let dt = (now - self.last_time) as f32; - if dt > 0.0 { - self.fps = self.fps * 0.9 + (1.0 / dt) * 0.1; + let logic_start_ms = now_ms(); + let now = ctx.input(|input| input.time); + let frame_seconds = (now - self.last_time) as f32; + if frame_seconds > 0.0 { + self.fps = self.fps * FRAME_AVERAGE_KEEP + (1.0 / frame_seconds) * (1.0 - FRAME_AVERAGE_KEEP); } self.last_time = now; + let style = (self.ui.prefs.brightness, self.ui.prefs.accent); if self.styled != Some(style) { theme::apply(ctx, style.0, style.1); @@ -980,16 +1009,17 @@ impl eframe::App for TextureCraftApp { } self.step_camera_glide(ctx); self.ui.prefs.apply_resource_limits(); + control::poll(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.run_file_dialog_answers(); web_files::poll(self); - let dropped = ctx.input(|i| i.raw.dropped_files.clone()); + let dropped = ctx.input(|input| input.raw.dropped_files.clone()); // A folder, a zip or several PBR maps dropped together open the PBR import dialog #[cfg(not(target_arch = "wasm32"))] let consumed = if !dropped.is_empty() { - let paths: Vec = dropped.iter().map(|f| f.path().to_path_buf()).collect(); + let paths: Vec = dropped.iter().map(|file| file.path().to_path_buf()).collect(); pbr_import::dropped(self, &paths) } else { Vec::new() @@ -1009,13 +1039,14 @@ impl eframe::App for TextureCraftApp { self.thumbs.sync_images(&self.session.images, self.session.revision); // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) - let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); + let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; } self.focused = focused; - let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0); - if (ctx.zoom_factor() - scale).abs() > 1e-3 { + + let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end()); + if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] @@ -1029,17 +1060,19 @@ impl eframe::App for TextureCraftApp { self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); #[cfg(not(target_arch = "wasm32"))] updates_ui::tick(self, ctx); + self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); + move_on_model::end_when_gone(self, ctx); // The Path tool's curve repaints (a preview while placed) as its points, brush or material change - if let Err(e) = self.session.path_live() { + if let Err(error) = self.session.path_live() { self.session.cancel_path(); - self.toast(e.to_string(), true); + self.toast(error.to_string(), true); } profile::drive(self, ctx); - self.toasts.retain(|t| t.until > now); - self.profiler.logic_ms = (now_ms() - t0) as f32; + self.toasts.retain(|toast| toast.until > now); + self.profiler.logic_ms = (now_ms() - logic_start_ms) as f32; // Last, so it sees every close request this frame's work made windows::close_request(self, ctx); @@ -1048,7 +1081,7 @@ impl eframe::App for TextureCraftApp { #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); - let started_ms = now_ms(); + let ui_start_ms = now_ms(); // Baking and rendering need a project (a saved layout may start in one of them) if !self.session.project_open { @@ -1088,10 +1121,12 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] self.file_dialogs.show_pending(frame); - let ended_ms = now_ms(); - let elapsed_ms = (ended_ms - started_ms) as f32; - self.ui_ms = if self.ui_ms == 0.0 { elapsed_ms } else { self.ui_ms * 0.9 + elapsed_ms * 0.1 }; - self.profiler.end_frame(ended_ms, elapsed_ms); + pointer_lock::settle(&ctx); + + let end_ms = now_ms(); + let ui_frame_ms = (end_ms - ui_start_ms) as f32; + self.ui_ms = if self.ui_ms == 0.0 { ui_frame_ms } else { self.ui_ms * FRAME_AVERAGE_KEEP + ui_frame_ms * (1.0 - FRAME_AVERAGE_KEEP) }; + self.profiler.end_frame(end_ms, ui_frame_ms); } } diff --git a/crates/ui-egui/src/past_end.rs b/crates/ui-egui/src/past_end.rs new file mode 100644 index 00000000..22851ad6 --- /dev/null +++ b/crates/ui-egui/src/past_end.rs @@ -0,0 +1,10 @@ +//! How far a Properties list scrolls past its last row + +/// When a Properties list leaves blank space under its rows so its last section's top can reach the top of the list +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum PastEnd { + /// Always, as the docked panel: even when every section fits + Always, + /// Only once the rows no longer fit, as a popup sized to its rows + WhenScrolling, +} diff --git a/crates/ui-egui/src/placement.rs b/crates/ui-egui/src/placement.rs new file mode 100644 index 00000000..925e616b --- /dev/null +++ b/crates/ui-egui/src/placement.rs @@ -0,0 +1,9 @@ +//! Where a fill's tiles land, as the window preview draws them + +/// How the fill's image is laid on its tile: tiles across and down, rotation in degrees, offset in tiles (rotate, scale, then offset) +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Placement { + pub tiling: [f32; 2], + pub rotation: f32, + pub offset: [f32; 2], +} diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 305c8bb6..341fda86 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -3,6 +3,7 @@ use egui::{PointerButton, Pos2, Rect, Ui}; use crate::TextureCraftApp; +use crate::property_sheet::SectionScope; use crate::state::Mode; use crate::theme::Tokens; @@ -34,7 +35,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: let free = app.ui.mode == Mode::Painting && app.properties_popup.is_none() && !app.session.stroke_active() - && app.placing_decal.is_none() + && app.moving_on_model.is_none() && !gesture_key_held && !crate::viewport::focus_picking(ui.ctx()) && ui.input(|input| input.modifiers.is_none()); @@ -50,6 +51,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: /// 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, @@ -73,7 +75,17 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { 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)); + + // The docked panel's jump tabs on the top edge stay put while the sections scroll under them + let scope = SectionScope::Popup; + if let Some(tabs) = crate::dock::properties_fill_tabs(app) { + crate::property_sheet::section_tabs(ui, scope, ui.style().visuals.menu_corner_radius.nw, &tabs); + } + crate::property_sheet::in_scope(ui, scope, |ui| { + // A popup that fits its rows keeps its size; one that scrolls goes on until its last section's top + let area = egui::ScrollArea::vertical().id_salt("properties_popup_scroll"); + crate::dock::properties_scrolled(app, ui, area, crate::past_end::PastEnd::WhenScrolling); + }); }); }); } diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index d7145208..d8f7ada3 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -41,14 +41,14 @@ fn environment_cache_retains_source_identity_until_replaced() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); app.session.doc.project.display.environment = "resource:environment".into(); - let source = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]; 2], srgb: false }); + let source = Arc::new(ImageRes::new(2, 1, vec![[1.0, 0.0, 0.0, 1.0]; 2], false)); let original_source = Arc::downgrade(&source); app.session.images.insert("environment".into(), source); let first_key = gpu_scene_key(&app.session); let first = super::trace_scene(&app).env; assert!(Arc::ptr_eq(&first, &super::trace_scene(&app).env), "unchanged images reuse the decoded environment"); - let replacement = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[0.0, 1.0, 0.0, 1.0]; 2], srgb: false }); + let replacement = Arc::new(ImageRes::new(2, 1, vec![[0.0, 1.0, 0.0, 1.0]; 2], false)); app.session.images.insert("environment".into(), replacement.clone()); assert!(original_source.upgrade().is_none(), "replacing the resource releases its decoded pixels immediately"); diff --git a/crates/ui-egui/src/resolution_band.rs b/crates/ui-egui/src/resolution_band.rs new file mode 100644 index 00000000..c2794eb1 --- /dev/null +++ b/crates/ui-egui/src/resolution_band.rs @@ -0,0 +1,138 @@ +//! The Resolution of a cooked source, Relative (follows the texture set) or Fixed, each size pictured against the texture set's: a material's band, a procedural slot's row + +use egui::{CornerRadius, Painter, Rect, Stroke, StrokeKind, vec2}; +use texturecraft_engine::core::{CookResolution, MAX_RESOLUTION}; + +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::theme::Tokens; + +/// Side of the grey square (this source) for factors 1/8 … ×8, as a share of the picture's side +const RATIO_SIDES: [f32; 7] = [0.12, 0.22, 0.32, 0.46, 0.66, 0.84, 1.0]; + +/// Side of the accent outline (the texture set) as a share of the picture's side +const TEXTURE_SET_SIDE: f32 = 0.42; + +/// The smallest fixed size the list offers +const SMALLEST_FIXED: u32 = 256; + +/// The Relative side of the Relative | Fixed switch +const RELATIVE_MODE: usize = 0; + +/// The Fixed side of the Relative | Fixed switch +const FIXED_MODE: usize = 1; + +/// The Resolution band (folded: picture and size); returns the resolution picked +pub(crate) fn resolution_band(sheet: &mut PropertySheet<'_>, current: CookResolution, texture_set: u32) -> Option { + let tokens = Tokens::get(sheet.ui.ctx()); + let size = current.size(texture_set); + let relative = matches!(current, CookResolution::Relative(_)); + let picture = |painter: &Painter, rect: Rect| ratio_picture(painter, rect, factor_of(size, texture_set), relative, &tokens); + if !sheet.band_pictured(tr("Resolution"), false, &format!("{size} × {size}"), &picture).open { + return None; + } + + let modes = [tr("Relative"), tr("Fixed")]; + let mode_picture = |painter: &Painter, rect: Rect, index: usize| ratio_picture(painter, rect, 0, index == RELATIVE_MODE, &tokens); + let switched = sheet.picture_switch(&modes, if relative { RELATIVE_MODE } else { FIXED_MODE }, &mode_picture).map(|mode| { + if mode == RELATIVE_MODE { + // Fixed → Relative keeps the nearest factor the texture set can cook at + let factor = factor_of(size, texture_set); + if fits(texture_set, factor) { CookResolution::Relative(factor) } else { CookResolution::TEXTURE_SET } + } else { + CookResolution::Fixed(size) + } + }); + + let picked = if let CookResolution::Relative(factor) = current { + let factors = || fitting_factors(texture_set); + let name = |factor: i8| format!("{} · {}", factor_name(factor), CookResolution::Relative(factor).size(texture_set)); + let draw = |painter: &Painter, rect: Rect, factor: i8| ratio_picture(painter, rect, factor, true, &tokens); + sheet.dropdown_built(tr("Size"), factor, factors, name, Some(&draw)).0.map(CookResolution::Relative) + } else { + let draw = |painter: &Painter, rect: Rect, size: u32| ratio_picture(painter, rect, factor_of(size, texture_set), false, &tokens); + sheet.dropdown_built(tr("Size"), size, fixed_sizes, |size| format!("{size} × {size}"), Some(&draw)).0.map(CookResolution::Fixed) + }; + switched.or(picked) +} + +/// The Resolution row of a procedural slot's card: one list with the texture set's factors under Relative and fixed sizes under Fixed; returns the resolution picked +pub(crate) fn resolution_row(sheet: &mut PropertySheet<'_>, current: CookResolution, texture_set: u32) -> Option { + let tokens = Tokens::get(sheet.ui.ctx()); + let name = |resolution: CookResolution| match resolution { + CookResolution::Relative(factor) => format!("{} · {}", factor_name(factor), resolution.size(texture_set)), + CookResolution::Fixed(size) => format!("{size} × {size}"), + }; + let draw = |painter: &Painter, rect: Rect, resolution: CookResolution| { + let related = matches!(resolution, CookResolution::Relative(_)); + ratio_picture(painter, rect, factor_of(resolution.size(texture_set), texture_set), related, &tokens); + }; + let groups = || { + let relative: Vec = fitting_factors(texture_set).map(CookResolution::Relative).collect(); + let fixed: Vec = fixed_sizes().map(CookResolution::Fixed).collect(); + [(tr("Relative"), relative), (tr("Fixed"), fixed)] + }; + sheet.grouped_dropdown(tr("Resolution"), current, groups, name, &draw) +} + +/// The factors the texture set can cook at, smallest first +fn fitting_factors(texture_set: u32) -> impl Iterator { + CookResolution::FACTORS.filter(move |factor| fits(texture_set, *factor)) +} + +/// The sizes a fixed resolution offers, smallest first +fn fixed_sizes() -> impl Iterator { + std::iter::successors(Some(SMALLEST_FIXED), |size| size.checked_mul(2)).take_while(|size| *size <= MAX_RESOLUTION) +} + +/// Whether the texture set's size times 2^`factor` can be cooked +fn fits(texture_set: u32, factor: i8) -> bool { + let shift = u32::from(factor.unsigned_abs()); + let size = if factor >= 0 { 1u32.checked_shl(shift).and_then(|scale| texture_set.checked_mul(scale)) } else { texture_set.checked_shr(shift) }; + size.is_some_and(CookResolution::cookable) +} + +/// The factor (a power of two, within the list's) from the texture set's size to `size` +fn factor_of(size: u32, texture_set: u32) -> i8 { + let steps = i64::from(size.max(1).ilog2()) - i64::from(texture_set.max(1).ilog2()); + let (low, high) = (CookResolution::FACTORS.start(), CookResolution::FACTORS.end()); + i8::try_from(steps.clamp(i64::from(*low), i64::from(*high))).unwrap_or_default() +} + +/// A factor's name in the list: 1/8 … Texture set … ×8 (a factor outside the list, from a loaded project, is named as its nearest end) +fn factor_name(factor: i8) -> String { + match factor.clamp(*CookResolution::FACTORS.start(), *CookResolution::FACTORS.end()) { + 0 => tr("Texture set").to_owned(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs()), + positive => format!("×{}", 1u32 << positive), + } +} + +/// This source (grey square) against the texture set (accent outline, when the size follows it) +fn ratio_picture(painter: &Painter, rect: Rect, factor: i8, related: bool, tokens: &Tokens) { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + let step = usize::try_from(i32::from(factor) - i32::from(*CookResolution::FACTORS.start())).unwrap_or_default(); + let side = RATIO_SIDES.get(step).copied().unwrap_or(1.0) * rect.width(); + painter.rect_filled(Rect::from_center_size(rect.center(), vec2(side, side)), CornerRadius::ZERO, tokens.text_dim); + if related { + let side = TEXTURE_SET_SIDE * rect.width(); + painter.rect_stroke(Rect::from_center_size(rect.center(), vec2(side, side)), CornerRadius::ZERO, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } +} + +#[cfg(test)] +mod tests { + use super::{factor_name, factor_of, fits}; + + #[test] + fn factors_name_and_fit_the_texture_set() { + assert_eq!([-3, -1, 1, 3].map(factor_name), ["1/8", "1/2", "×2", "×8"]); + assert_eq!((factor_of(1024, 2048), factor_of(8192, 128), factor_of(0, 2048)), (-1, 3, -3)); + assert!(fits(2048, 2) && !fits(2048, 3) && !fits(256, -2)); + } + + #[test] + fn a_factor_outside_the_list_is_named_as_its_nearest_end() { + assert_eq!([i8::MIN, i8::MAX].map(factor_name), ["1/8", "×8"]); + } +} diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index a2ae0528..3f3b75e2 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -164,7 +164,7 @@ mod tests { #[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 image = ImageRes::new(4, 2, vec![[0.8, 0.4, 0.2, 1.0]; 8], true); let previews = [ ShelfPreview::Material(MATERIALS[0].id), ShelfPreview::Filter(FILTERS[0].id), @@ -201,7 +201,7 @@ mod tests { #[test] fn saved_brush_preview_uses_its_project_image_alpha() { let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; - let transparent = Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[1.0, 1.0, 1.0, 0.0]; 4], srgb: false }); + let transparent = Arc::new(ImageRes::new(2, 2, vec![[1.0, 1.0, 1.0, 0.0]; 4], false)); let preview = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings.clone()), image: Some(transparent) }; assert!(preview.image(64).is_some_and(|image| image.pixels.iter().all(|pixel| pixel.r() == 0))); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 41b14eb7..2c2b045d 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -293,6 +293,9 @@ pub fn semibold(size: f32) -> FontId { /// The semibold family: Inter SemiBold, the regular font without it. pub(crate) const SEMIBOLD: &str = "ui-semibold"; +/// Colour of the hard, unblurred shadow under the panel's own popups (pickers, menus, tips) +pub(crate) const HARD_SHADOW: Color32 = Color32::from_rgb(12, 14, 18); + /// The app's fonts: Inter (regular and semibold) when built with craft-fonts, egui's defaults /// otherwise, egui's monospace face for values, and the Phosphor icon font (`fonts::UiFonts` /// adds CJK). @@ -384,6 +387,23 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) { }); } +/// X, Y and Z as the view corner, the symmetry manipulator and the 3D fields show them +pub const AXIS_COLORS: [Color32; 3] = [Color32::from_rgb(0xd8, 0x60, 0x4f), Color32::from_rgb(0x6c, 0xbc, 0x5a), Color32::from_rgb(0x5a, 0x8c, 0xe0)]; + +/// An axis arrow's shaft as the symmetry manipulator and the projection gizmos draw it: its width, the dark halo under it and the halo's extra width (points at the default size) +pub const SHAFT_WIDTH: f32 = 2.2; +pub const SHAFT_HALO: Color32 = Color32::from_black_alpha(128); +pub const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; + +/// The axes' letters, as the Axis switches and the 3D fields' tags show them +pub const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; + +/// `from` moved `amount` of the way to `to` in gamma space, opaque +pub(crate) fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { + let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount).round().clamp(0.0, 255.0) as u8; + Color32::from_rgb(mix(from.r(), to.r()), mix(from.g(), to.g()), mix(from.b(), to.b())) +} + /// A section caption inside a panel: semibold in the strong colour, as written (no capitals). pub fn caption(text: &str) -> egui::RichText { egui::RichText::new(text).font(semibold(12.5)).strong() diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 098f3638..ecfa8b14 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -435,7 +435,7 @@ mod tests { let path = PathBuf::from("changed-alpha.tcbrush"); let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; thumbs.saved_brush_previews.insert(path.clone(), (Some(settings), None, 0)); - let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let image = |value| Arc::new(ImageRes::new(2, 2, vec![[value; 4]; 4], false)); let mut images: ImageStore = [("alpha.png".into(), image(0.2))].into(); let old_preview = thumbs.saved_brush_preview(&path, &images); @@ -522,8 +522,8 @@ mod tests { let first_path = PathBuf::from("first.tcbrush"); let second_path = PathBuf::from("second.tcbrush"); let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() }; - let old_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[1.0; 4]; IMAGE_TEXELS], srgb: false }); - let other_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.5; 4]; IMAGE_TEXELS], srgb: false }); + let old_image = Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[1.0; 4]; IMAGE_TEXELS], false)); + let other_image = Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[0.5; 4]; IMAGE_TEXELS], false)); let old_weak = Arc::downgrade(&old_image); let other_weak = Arc::downgrade(&other_image); assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::() > 0.0); @@ -544,7 +544,7 @@ mod tests { Arc::strong_count(&images["alpha.png"]) ); - let replacement = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.0; 4]; IMAGE_TEXELS], srgb: false }); + let replacement = Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[0.0; 4]; IMAGE_TEXELS], false)); images.insert("alpha.png".into(), replacement); drop(thumbs.saved_brush_preview(&first_path, &images)); assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image"); @@ -558,7 +558,7 @@ mod tests { fn replacing_an_image_rebuilds_its_preview() { let context = egui::Context::default(); let mut thumbs = Thumbs::default(); - let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false }); + let image = |value| Arc::new(ImageRes::new(2, 2, vec![[value; 4]; 4], false)); let first_image = image(0.2); let replacement_image = image(0.8); @@ -575,7 +575,7 @@ mod tests { let mut images = ImageStore::new(); for index in 0..3 { let name = format!("image-{index}"); - images.insert(name, Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[index as f32; 4]; 4], srgb: false })); + images.insert(name, Arc::new(ImageRes::new(2, 2, vec![[index as f32; 4]; 4], false))); } for (name, image) in &images { @@ -595,7 +595,7 @@ mod tests { assert!(after_pixel_bytes < before_pixel_bytes); assert!(thumbs.images.contains_key("image-2")); - images.insert("image-3".into(), Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[0.7; 4]; 4], srgb: false })); + images.insert("image-3".into(), Arc::new(ImageRes::new(2, 2, vec![[0.7; 4]; 4], false))); drop(thumbs.image(&context, "image-3", &images["image-3"])); thumbs.sync_images(&images, 2); assert_eq!(thumbs.images.len(), 2); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 97edafed..159fdecc 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -18,6 +18,7 @@ use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::path_hit::PathHit; use crate::path_surface_cache::{PathSurfaceCache, SurfaceCurve}; +use crate::projection_gizmo::ShownGizmo; use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; @@ -731,7 +732,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let local = |pointer: egui::Pos2| Vec2::new(pointer.x - rect.left(), pointer.y - rect.top()); let adjusting = brush_drag(app, ui, &response); let ctrl = ui.input(|input| input.modifiers.ctrl); - let navigating = !adjusting && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); + + // A held Move on model button owns the pointer and the wheel until it lets go: the camera, brush and gizmos keep still + let holding = crate::move_on_model::holding(app, ui.ctx()); + let navigating = !adjusting && !holding && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); // Navigation; S + drag moves the projection stencil instead, below let delta = ui.input(|input| input.pointer.delta()); @@ -740,8 +744,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); - if stencil_drag || adjusting { - // The stencil or the brush changes instead of the camera + if stencil_drag || adjusting || holding { + // The stencil, the brush or the held Move on model button changes instead of the camera } else if response.dragged_by(PointerButton::Middle) { app.camera_glide = None; app.session.camera.pan(delta.x / size.y, delta.y / size.y); @@ -774,7 +778,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.orbit_snap = None; } - if response.hovered() { + if response.hovered() && !holding { size_brush_by_ctrl_wheel(app, ui); if ui.input(|input| input.multi_touch().is_none()) { let pinch = trackpad_pinch(ui); @@ -868,32 +872,12 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // A dismissing click cannot paint or place a decal through the rail popup let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx()); - // Decal placement: a click moves the decal being placed there, unless it dismisses a waiting image drop's menu - let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); - if let Some(target) = placing { - ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); - if !alt - && !rail_popup - && !DecalDrop::blocks_input(ui.ctx()) - && response.clicked_by(PointerButton::Primary) - && let Some(pointer) = response.interact_pointer_pos() - { - let (at, viewport) = (local(pointer), app.session.viewport); - let mut params = json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]}); - - // The id is a decal layer's or a mask fill effect's - params[if app.session.doc.project.effect(target).is_some() { "effect" } else { "layer" }] = json!(target.0); - app.run("layer.decal.set", params); - app.placing_decal = None; - } - } - crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + let popup = app.properties_popup.is_some() || rail_popup; // A pending ID color pick takes the next click instead of the brush - let picking_id_color = app.picking_id_color.is_some(); - if picking_id_color { + if picking { crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); if !alt && response.clicked_by(PointerButton::Primary) @@ -904,26 +888,29 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - // 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() - && !picking_id_color - && touch.is_none() - && !DecalDrop::blocks_input(ui.ctx()) - && decal_input(app, ui, &response, rect); + // The selected fill's frame (planar, warp) or round projector (tri-planar, spherical, cylindrical): only a press on one of its handles moves it + let gizmo_free = + !adjusting && !alt && !holding && !s_held && !v_held && !focus_pick && !popup && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()); + let gizmo = ShownGizmo::of(app, rect); + let frame_drag = gizmo_free && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref()); + + // Alt (or another mode) taking the pointer mid-drag ends the drag: let go of Alt, it must not resume from where it began before the camera moved + if !gizmo_free { + ShownGizmo::let_go(ui.ctx()); + } + + // A drag moved the projection: its handles and outline show where it is now + let gizmo = if frame_drag { ShownGizmo::of(app, rect) } else { gizmo }; + + let projection_drag = frame_drag || holding; let plane_pick = !popup && !s_held && !v_held && !focus_pick - && placing.is_none() - && !picking_id_color + && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()) - && !decal_drag + && !projection_drag && crate::symmetry::plane_pick_input(app, ui, &response, rect); let symmetry_drag = !alt && !plane_pick @@ -932,16 +919,19 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !v_held && !focus_pick && !popup - && placing.is_none() - && !picking_id_color + && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()) - && !decal_drag + && !projection_drag && crate::symmetry::manipulator_input(app, ui, &response, rect); // A handle owns a new click, but a stroke already under way must still finish over it let symmetry_handle = !app.session.stroke_active() && crate::symmetry::manipulator_hovered(app, ui, rect); + // A projection gizmo's handle owns a press that began on it through its release (the pointer may have left it by then) + let began_on_handle = handle_press(ui.ctx(), |at| gizmo.as_ref().is_some_and(|gizmo| gizmo.on_handle(rect, at))); + let gizmo_handle = gizmo_free && !app.session.stroke_active() && began_on_handle; + // Painting let painting = tool_acts(app) && !popup @@ -950,13 +940,13 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !s_held && !v_held && !focus_pick - && placing.is_none() - && !picking_id_color + && !picking && touch.is_none() - && !decal_drag + && !projection_drag && !plane_pick && !symmetry_drag && !symmetry_handle + && !gizmo_handle && !DecalDrop::blocks_input(ui.ctx()); let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; @@ -1034,6 +1024,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && (app.session.tool.tool != Tool::Path || adjusting) && !crate::symmetry::manipulator_hovered(app, ui, rect) && app.picking_id_color.is_none() + && app.moving_on_model.is_none() + && !ShownGizmo::hovered(ui, rect, gizmo.as_ref()) && 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) { @@ -1063,7 +1055,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } crate::symmetry::overlay(app, ui, rect, symmetry_cursor); stencil_overlay(app, ui, rect); - decal_overlay(app, ui, rect); + if let Some(gizmo) = &gizmo { + gizmo.overlay(app, ui, rect); + } brush_readout(app, ui, &response, adjusting); if app.session.quick_mask.editing && app.picking_id_color.is_none() { ui.painter_at(rect).text( @@ -1099,237 +1093,6 @@ fn bake_visualization(app: &TextureCraftApp) -> Option egui::CursorIcon { - match self { - DecalGrab::Move => egui::CursorIcon::Move, - DecalGrab::Scale => egui::CursorIcon::ResizeNwSe, - DecalGrab::Rotate if dragging => egui::CursorIcon::Grabbing, - DecalGrab::Rotate => egui::CursorIcon::Grab, - } - } -} - -/// A decal handle being dragged (kept in egui's memory between frames) -#[derive(Clone, Copy, Debug)] -struct DecalDrag { - layer: texturecraft_engine::core::LayerId, - /// The mask fill effect holding the decal, when it was placed as a mask - effect: Option, - grab: DecalGrab, - /// Where the drag started, the decal's center on screen and the decal then - from: Pos2, - center: Pos2, - start: texturecraft_engine::core::Decal, - /// The drag made its undo step: later updates merge into it - stepped: bool, -} - -fn decal_drag_id() -> egui::Id { - egui::Id::unique("tc_decal_drag") -} - -/// Screen distance from the top edge to the rotation handle (points). -const DECAL_KNOB: f32 = 24.0; - -/// The selected decal (a decal layer's content, or a mask decal effect) as the 3D view shows it -struct DecalFrame { - layer: texturecraft_engine::core::LayerId, - /// The selected mask fill effect holding the decal, when it was placed as a mask - effect: Option, - decal: texturecraft_engine::core::Decal, - /// Top left, top right, bottom right, bottom left - corners: [Pos2; 4], - center: Pos2, - /// The middle of the top edge and the rotation handle above it - top: Pos2, - knob: Pos2, -} - -impl DecalFrame { - /// The selected decal: its layer (the mask's owner for an effect), the mask fill effect holding it when placed as a mask, and the decal - fn selected( - app: &TextureCraftApp, - ) -> Option<(texturecraft_engine::core::LayerId, Option, texturecraft_engine::core::Decal)> { - use texturecraft_engine::StackTarget; - use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; - - if app.ui.mode != crate::state::Mode::Painting { - return None; - } - - let layers = &app.session.doc.project; - let selected = app.session.selected_layer()?; - match app.session.target { - StackTarget::Content => { - let layer = layers.content_layer(selected)?; - let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; - - Some((layer.id, None, *decal)) - } - StackTarget::Effect(effect) => { - // Only the selected layer's effective mask may supply a decal frame, including an instance's inherited mask - let owner = layers.mask_owner(selected); - let mask = layers.layer(owner).ok()?.mask.as_ref()?; - let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; - let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; - - Some((owner, Some(effect), *decal)) - } - StackTarget::Mask => None, - } - } - - fn of(app: &TextureCraftApp, rect: Rect) -> Option { - use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; - - let (layer, effect, decal) = Self::selected(app)?; - let decal = &decal; - let [top_left, top_right, bottom_right, bottom_left] = decal_corners(decal)?.map(|corner| project(app, rect, corner)); - let corners = [top_left?, top_right?, bottom_right?, bottom_left?]; - let center = project(app, rect, decal_axes(decal)?.0)?; - let top = corners[0].lerp(corners[1], 0.5); - let knob = top + (top - center).normalized() * DECAL_KNOB; - Some(DecalFrame { layer, effect, decal: *decal, corners, center, top, knob }) - } - - /// The handle under screen point `p`. - fn grab(&self, p: Pos2) -> Option { - if self.knob.distance(p) <= HANDLE_GRAB { - return Some(DecalGrab::Rotate); - } - if self.corners.iter().any(|c| c.distance(p) <= HANDLE_GRAB) { - return Some(DecalGrab::Scale); - } - // Inside the (convex) frame: on the same side of every edge. - let side = |i: usize| { - let (a, b) = (self.corners[i], self.corners[(i + 1) % 4]); - (b - a).x * (p - a).y - (b - a).y * (p - a).x - }; - let s = [side(0), side(1), side(2), side(3)]; - (s.iter().all(|v| *v >= 0.0) || s.iter().all(|v| *v <= 0.0)).then_some(DecalGrab::Move) - } -} - -/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates live); returns whether a decal drag owns the pointer -fn decal_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, rect: Rect) -> bool { - let ctx = ui.ctx(); - let frame = DecalFrame::of(app, rect); - let on_frame = |drag: &DecalDrag| frame.as_ref().is_some_and(|frame| frame.layer == drag.layer && frame.effect == drag.effect); - let mut drag = ctx.data(|data| data.get_temp::(decal_drag_id())).filter(on_frame); - if resp.drag_started_by(PointerButton::Primary) - && let (Some(frame), Some(from)) = (&frame, ctx.input(|input| input.pointer.press_origin())) - && let Some(grab) = frame.grab(from) - { - drag = Some(DecalDrag { layer: frame.layer, effect: frame.effect, grab, from, center: frame.center, start: frame.decal, stepped: false }); - } - - let Some(mut drag) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { - ctx.data_mut(|data| data.remove::(decal_drag_id())); - if let (Some(frame), Some(hover)) = (&frame, resp.hover_pos()) - && let Some(grab) = frame.grab(hover) - { - ctx.set_cursor_icon(grab.cursor(false)); - } - return false; - }; - - ctx.set_cursor_icon(drag.grab.cursor(true)); - if let Some(pointer) = resp.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) { - let mut params = match drag.grab { - DecalGrab::Move => { - let target = drag.center + (pointer - drag.from) - rect.left_top(); - let viewport = app.session.viewport; - json!({"x": target.x, "y": target.y, "viewport": [viewport.x, viewport.y]}) - } - DecalGrab::Scale => { - let scale = (pointer - drag.center).length() / (drag.from - drag.center).length().max(1.0); - json!({"size": [drag.start.size[0] * scale, drag.start.size[1] * scale]}) - } - DecalGrab::Rotate => { - // Screen y points down: counter-clockwise angles turn the decal's right toward its up - let angle = |offset: egui::Vec2| (-offset.y).atan2(offset.x).to_degrees(); - json!({"rotation": drag.start.rotation + angle(pointer - drag.center) - angle(drag.from - drag.center)}) - } - }; - params["layer"] = json!(drag.layer.0); - if let Some(effect) = drag.effect { - params["effect"] = json!(effect.0); - } - params["merge"] = json!(drag.stepped); - // Off the mesh while moving: the decal waits where it is - drag.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); - } - ctx.data_mut(|data| data.insert_temp(decal_drag_id(), drag)); - true -} - -/// The frame of the selected decal layer over the 3D view with its handles (and a hint while -/// placing it): outline, corner handles, the rotation handle and the projection direction. -fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { - if app.ui.mode != crate::state::Mode::Painting { - return; - } - - let tk = Tokens::get(ui.ctx()); - - // Placing follows the selection: another layer or effect selected stops it - let selected_decal = DecalFrame::selected(app).map(|(layer, effect, _)| effect.unwrap_or(layer)); - if app.placing_decal.is_some() && app.placing_decal != selected_decal { - app.placing_decal = None; - } - let painter = ui.painter_at(rect); - let hint_at = rect.left_top() + vec2(12.0, 40.0); - if app.placing_decal.is_some() { - let hint = tr("Click the mesh to place the decal"); - painter.text(hint_at, egui::Align2::LEFT_TOP, hint, egui::FontId::proportional(12.0), tk.viewport_accent); - } - let Some(f) = DecalFrame::of(app, rect) else { return }; - let active = ui.ctx().data(|d| d.get_temp::(decal_drag_id())).map(|d| d.grab); - let hovered = ui.ctx().pointer_hover_pos().filter(|h| rect.contains(*h)).and_then(|h| f.grab(h)); - if app.placing_decal.is_none() && (hovered.is_some() || active.is_some()) { - let hint = tr("Drag the frame to move the decal, a corner to scale it, the round handle to turn it"); - painter.text(hint_at, egui::Align2::LEFT_TOP, hint, egui::FontId::proportional(12.0), tk.viewport_text); - } - let shadow = Stroke::new(3.0, Color32::from_black_alpha(140)); - let mut outline = f.corners.to_vec(); - outline.push(f.corners[0]); - let frame_color = if active == Some(DecalGrab::Move) || hovered == Some(DecalGrab::Move) { tk.viewport_accent } else { Color32::from_white_alpha(220) }; - for stroke in [shadow, Stroke::new(1.2, frame_color)] { - painter.add(egui::Shape::dashed_line(&outline, stroke, 6.0, 4.0)); - } - - // The projection direction from the center - if let Some((o, _, _, n)) = texturecraft_engine::compose::pattern::decal_axes(&f.decal) - && let Some(tip) = project(app, rect, o + n * f.decal.size[0].max(f.decal.size[1]) * 0.25) - { - painter.line_segment([f.center, tip], shadow); - painter.line_segment([f.center, tip], Stroke::new(1.4, tk.viewport_accent)); - } - painter.circle(f.center, 3.5, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(180))); - - // Handles: white, the one under the pointer or being dragged in the accent color - let fill = |g: DecalGrab| if active == Some(g) || (active.is_none() && hovered == Some(g)) { tk.viewport_accent } else { Color32::WHITE }; - let edge = Stroke::new(1.0, Color32::from_black_alpha(200)); - painter.line_segment([f.top, f.knob], shadow); - painter.line_segment([f.top, f.knob], Stroke::new(1.4, Color32::from_white_alpha(220))); - painter.circle(f.knob, 5.0, fill(DecalGrab::Rotate), edge); - for c in f.corners { - painter.rect(Rect::from_center_size(c, vec2(8.0, 8.0)), 1.0, fill(DecalGrab::Scale), edge, egui::StrokeKind::Middle); - } -} - /// Draw the projection stencil in Paint Mode fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { if !tool_acts(app) || app.session.tool.tool != Tool::Projection { @@ -1369,6 +1132,17 @@ pub(crate) fn project(app: &TextureCraftApp, rect: Rect, point: Vec3) -> Option< Some(pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height())) } +/// The camera ray through screen point `p` of the 3D view `rect` +pub(crate) fn view_ray(app: &TextureCraftApp, rect: Rect, p: Pos2) -> texturecraft_engine::geom::Ray { + let ndc = Vec2::new((p.x - rect.left()) / rect.width() * 2.0 - 1.0, 1.0 - (p.y - rect.top()) / rect.height() * 2.0); + app.session.camera.ray(ndc, rect.width() / rect.height().max(1.0)) +} + +/// Whether the window lost the focus (Alt+Tab): egui keeps a held button down with no release to come, so a drag ends here as on a release +pub(crate) fn focus_lost(ctx: &egui::Context) -> bool { + ctx.input(|input| input.viewport().focused == Some(false) || input.events.iter().any(|event| matches!(event, egui::Event::WindowFocused(false)))) +} + /// Control point and curve grab radius (points) const HANDLE_GRAB: f32 = 8.0; /// Opacity of the selected layer's other stored paths @@ -1967,6 +1741,30 @@ fn scale_brush_by_wheel(app: &mut TextureCraftApp, scroll: f32) { brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } +/// Whether the press under way, or released this frame, began on a projection handle (`on_handle`); with no press, whether the pointer is on one +fn handle_press(ctx: &egui::Context, on_handle: impl Fn(Pos2) -> bool) -> bool { + let id = egui::Id::unique(HANDLE_PRESS_ID); + let (pressed, down, released, origin, hover) = ctx.input(|input| { + let pointer = &input.pointer; + (pointer.any_pressed(), pointer.any_down(), pointer.any_released(), pointer.press_origin(), pointer.hover_pos()) + }); + + // Kept from the press frame: egui forgets the press origin on the release frame, where a short drift still makes a click + if pressed { + let on = origin.is_some_and(&on_handle); + ctx.data_mut(|data| data.insert_temp(id, on)); + } + let kept = ctx.data(|data| data.get_temp::(id)).filter(|_| down || released); + if !down { + ctx.data_mut(|data| data.remove::(id)); + } + + kept.unwrap_or_else(|| (if down { origin } else { hover }).is_some_and(on_handle)) +} + +/// Where [`handle_press`] keeps whether the press began on a handle +const HANDLE_PRESS_ID: &str = "projection_handle_press"; + /// Ctrl (Cmd on macOS) + drag changes the brush instead of painting: true while it applies (see `adjust_brush`) fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) -> bool { // Ctrl+Shift+left is not a brush change: it is left to the snapped straight line @@ -2253,7 +2051,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } app.ui.uv_zoom = new_zoom; } - if response.hovered() { + + // A held Move on model button takes the wheel + if response.hovered() && app.moving_on_model.is_none() { size_brush_by_ctrl_wheel(app, ui); let scroll = wheel_scroll(ui, shift); if scroll != 0.0 && shift && wheel_sizes_brush(app) { @@ -2857,7 +2657,7 @@ mod tests { harness.state_mut().run("layer.add.decal", json!({"image": image, "channel": "mask", "size": 0.5})).unwrap(); harness.run_steps(2); assert_eq!(harness.state().session.ts(), 0); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some()); harness } @@ -2883,7 +2683,7 @@ mod tests { for texture_set in [0, 1] { let mut harness = decal_frame_app(false); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; execute(session, "textureSet.select", &json!({"ts": texture_set})).unwrap(); @@ -2896,14 +2696,14 @@ mod tests { assert_eq!(session.ts(), texture_set); assert_eq!(session.selected_layer().unwrap().0, other.as_u64().unwrap()); assert_eq!(session.target, StackTarget::Effect(effect), "the failed selection leaves the previous effect target"); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "a stale effect must not show a decal frame"); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "a stale effect must not show a decal frame"); drag_decal_handle(&mut harness, original.corners[1], original.center + (original.corners[1] - original.center) * 1.5); - drag_decal_handle(&mut harness, original.knob, original.knob + vec2(40.0, 0.0)); + drag_decal_handle(&mut harness, original.center, original.center + vec2(40.0, 0.0)); let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind; assert!( - matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Decal(decal), .. } if *decal == original.decal) + matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Planar { placed: Some(decal), .. }, .. } if *decal == original.decal) ); } } @@ -2915,7 +2715,7 @@ mod tests { use texturecraft_engine::execute; let mut harness = decal_frame_app(false); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); @@ -2925,12 +2725,12 @@ mod tests { assert_eq!(session.ts(), 1); assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); - let inherited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let inherited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal)); drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5); - let edited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let edited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source"); } @@ -2941,7 +2741,7 @@ mod tests { use texturecraft_engine::execute; let mut harness = decal_frame_app(false); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); @@ -2950,7 +2750,7 @@ mod tests { assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "an override hides the source's mask decal"); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "an override hides the source's mask decal"); } #[test] @@ -2964,14 +2764,14 @@ mod tests { std::fs::create_dir_all(&directory).unwrap(); let mut harness = decal_frame_app(true); - let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let original = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); harness.run_steps(6); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some()); harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap(); let session = &mut harness.state_mut().session; @@ -2980,7 +2780,7 @@ mod tests { assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err()); harness.run_steps(6); - assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none()); + assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none()); harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap(); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index ef2455a1..9891dcc8 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -21,6 +21,18 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI slider_inner(ui, label, value, range, decimals).0 } +/// For an editor `id` drawn every frame: `Some(merge)` when it `changed`, merge true for a press's later changes (one undo step per drag; typing never merges) +pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { + let held = ui.input(|input| input.pointer.any_down()); + if !held { + // The press is over: the next one starts its own undo step + ui.data_mut(|data| data.remove_temp::(id)); + return changed.then_some(false); + } + + changed.then(|| ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(id), true))) +} + /// [`slider`] for a value re-read from the document every frame: `Some(merge)` on every frame /// that changes `value` (live while dragging, a click on the track, a typed value). `merge` is /// true for the later changes of one drag, so the edit that applies them (with the command's @@ -29,16 +41,28 @@ pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::R slider_inner(ui, label, value, range, decimals).1 } +/// Least width of a slider's value field, wide enough for a short number +const SLIDER_VALUE_MIN_WIDTH: f32 = 44.0; + +/// Height of a slider's track row +const SLIDER_TRACK_HEIGHT: f32 = 14.0; + +/// From the track row's sides to the track's ends, so the knob stays inside the row +const SLIDER_TRACK_INSET: f32 = 5.0; + +/// Thickness of a slider's rail and its knob's radius +const SLIDER_RAIL_WIDTH: f32 = 2.0; +const SLIDER_KNOB_RADIUS: f32 = 4.5; + /// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { - const MIN_VALUE_WIDTH: f32 = 44.0; let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) - .fold(MIN_VALUE_WIDTH, f32::max); + .fold(SLIDER_VALUE_MIN_WIDTH, f32::max); let mut edit = None; let field = ui .horizontal(|ui| { @@ -58,7 +82,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std .frame(egui::Frame::NONE), ); if response.has_focus() { - ui.data_mut(|data| data.insert_temp(id, text.clone())); + ui.data_mut(|data| data.insert_temp(id, text)); } else { ui.data_mut(|data| data.remove_temp::(id)); @@ -85,14 +109,10 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std } fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { - const TRACK_HEIGHT: f32 = 14.0; - const TRACK_INSET: f32 = 5.0; - const TRACK_WIDTH: f32 = 2.0; - const KNOB_RADIUS: f32 = 4.5; let (minimum, maximum) = (*range.start(), *range.end()); let width = ui.available_width(); let (field, mut edit) = value_header(ui, label, value, range, decimals); - let (rect, mut response) = ui.allocate_exact_size(vec2(width, TRACK_HEIGHT), Sense::click_and_drag()); + let (rect, mut response) = ui.allocate_exact_size(vec2(width, SLIDER_TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); ui.memory_mut(|memory| memory.surrender_focus(field)); @@ -100,25 +120,26 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang if edit.is_some() { response.mark_changed(); } + + let mut moved = false; if (response.dragged() || response.clicked()) && let Some(pointer) = response.interact_pointer_pos() { - let fraction = ((pointer.x - rect.left() - TRACK_INSET) / (rect.width() - TRACK_INSET * 2.0).max(1.0)).clamp(0.0, 1.0); + let fraction = ((pointer.x - rect.left() - SLIDER_TRACK_INSET) / (rect.width() - 2.0 * SLIDER_TRACK_INSET).max(1.0)).clamp(0.0, 1.0); let next = minimum + (maximum - minimum) * fraction; if (next - *value).abs() > f32::EPSILON { *value = next; response.mark_changed(); - - // Later frames of one drag share its undo step - edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); + moved = true; } } - if response.drag_stopped() || response.clicked() { - ui.data_mut(|data| data.remove_temp::(response.id)); - } + + // Later frames of one drag share its undo step, and a drag wins over typing in the same frame + edit = press_edit(ui, response.id, moved).or(edit); let fraction = if maximum > minimum { ((*value - minimum) / (maximum - minimum)).clamp(0.0, 1.0) } else { 0.0 }; - track(ui, &response, rect.left() + TRACK_INSET..=rect.right() - TRACK_INSET, rect.center().y, fraction, TRACK_WIDTH, KNOB_RADIUS); + let track_ends = rect.left() + SLIDER_TRACK_INSET..=rect.right() - SLIDER_TRACK_INSET; + track(ui, &response, track_ends, rect.center().y, fraction, SLIDER_RAIL_WIDTH, SLIDER_KNOB_RADIUS); (response, edit) } @@ -474,22 +495,25 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool changed } -/// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh. +/// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { - const N: u32 = 24; + /// Cells across and down: fine enough that a hue strip's six ramps read smooth + const GRID_CELLS: u32 = 24; + let mut mesh = egui::Mesh::default(); - for j in 0..=N { - for i in 0..=N { - let (x, y) = (i as f32 / N as f32, j as f32 / N as f32); - let [r, g, b] = rgb(x, y).map(|c| (c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + for j in 0..=GRID_CELLS { + for i in 0..=GRID_CELLS { + let (x, y) = (i as f32 / GRID_CELLS as f32, j as f32 / GRID_CELLS as f32); + let [r, g, b] = rgb(x, y).map(|component| (component.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b)); } } - for j in 0..N { - for i in 0..N { - let k = j * (N + 1) + i; - mesh.add_triangle(k, k + 1, k + N + 1); - mesh.add_triangle(k + 1, k + N + 2, k + N + 1); + for j in 0..GRID_CELLS { + for i in 0..GRID_CELLS { + let top_left = j * (GRID_CELLS + 1) + i; + let bottom_left = top_left + GRID_CELLS + 1; + mesh.add_triangle(top_left, top_left + 1, bottom_left); + mesh.add_triangle(top_left + 1, bottom_left + 1, bottom_left); } } painter.add(mesh); diff --git a/crates/ui-egui/tests/it/decal_proportions.rs b/crates/ui-egui/tests/it/decal_proportions.rs deleted file mode 100644 index aa267486..00000000 --- a/crates/ui-egui/tests/it/decal_proportions.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! A decal's Width and Height keep the image's proportions, and Flip U / Flip V mirror its image - -use egui::accesskit::Role; -use egui_kittest::Harness; -use egui_kittest::kittest::{Queryable, by}; -use serde_json::json; -use texturecraft_engine::core::{Decal, LayerId, LayerKind, Projection}; -use texturecraft_ui_egui::TextureCraftApp; - -/// Frames for a click or a typed value to reach the document and the panel -const SETTLE_FRAMES: usize = 3; - -/// The longest text a side's number field shows, cleared before typing a value -const FIELD_TEXT_LIMIT: usize = 12; - -/// The sample app with a decal of a twice-as-wide-as-tall image selected, and its layer -fn app_with_decal() -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut png = Vec::new(); - image::RgbaImage::from_pixel(8, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - let name = session.import_resource_bytes("wide.png", png).unwrap(); - let placed = texturecraft_engine::execute( - &mut session, - "layer.add.decal", - &json!({"image": name, "position": [0.0, 0.0, 0.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0], "size": [0.8, 0.4]}), - ) - .unwrap(); - let layer = LayerId(placed["layer"].as_u64().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 decal(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Decal { - let LayerKind::Fill(fill) = &harness.state().session.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; - *decal -} - -/// Type `value` into the number field of the row labelled `label` and confirm it -fn type_side(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { - let field = |harness: &Harness<'_, TextureCraftApp>| { - let row = harness.get_by_label(label).rect().center().y; - harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).map(|node| node.rect().center()).unwrap() - }; - harness.drag_at(field(harness)); - harness.drop_at(field(harness)); - harness.run_steps(2); - harness.key_press(egui::Key::End); - for _ in 0..FIELD_TEXT_LIMIT { - harness.key_press(egui::Key::Backspace); - harness.run_steps(1); - } - for character in value.chars() { - harness.get_all(by().role(Role::TextInput)).find(|node| node.is_focused()).unwrap().type_text(&character.to_string()); - harness.run_steps(1); - } - harness.key_press(egui::Key::Enter); - harness.run_steps(SETTLE_FRAMES); -} - -#[test] -fn width_and_height_follow_each_other_by_the_image_aspect() { - let (mut harness, layer) = app_with_decal(); - - type_side(&mut harness, "Width", "0.6"); - assert_eq!(decal(&harness, layer).size, [0.6, 0.3], "the width sets the height"); - - type_side(&mut harness, "Height", "0.1"); - assert_eq!(decal(&harness, layer).size, [0.2, 0.1], "the height sets the width"); -} - -#[test] -fn unticking_keep_proportions_frees_each_side() { - let (mut harness, layer) = app_with_decal(); - harness.get_by_label("Keep proportions").click(); - harness.run_steps(SETTLE_FRAMES); - - type_side(&mut harness, "Width", "0.6"); - assert_eq!(decal(&harness, layer).size, [0.6, 0.4], "only the width changes"); - - // Ticking it again fits the height to the width, in one undo step - let steps = harness.state().session.history_labels().len(); - harness.get_by_label("Keep proportions").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).size, [0.6, 0.3]); - assert_eq!(harness.state().session.history_labels().len(), steps + 1); -} - -#[test] -fn flip_toggles_mirror_the_image_and_undo_one_step_at_a_time() { - let (mut harness, layer) = app_with_decal(); - assert_eq!(decal(&harness, layer).flip, [false, false]); - - harness.get_by_label("Flip U").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [true, false]); - - harness.get_by_label("Flip V").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [true, true]); - - harness.get_by_label("Flip U").click(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [false, true], "Flip U toggles back and leaves Flip V"); - - texturecraft_engine::execute(&mut harness.state_mut().session, "edit.undo", &json!({})).unwrap(); - harness.run_steps(SETTLE_FRAMES); - assert_eq!(decal(&harness, layer).flip, [true, true]); -} diff --git a/crates/ui-egui/tests/it/decal_symmetry.rs b/crates/ui-egui/tests/it/decal_symmetry.rs deleted file mode 100644 index e97a24a8..00000000 --- a/crates/ui-egui/tests/it/decal_symmetry.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! The decal editor's Mirror across and Flip controls set the decal's mirrored copy - -use egui::accesskit::Role; -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_engine::core::{DecalFlip, LayerKind, Projection}; -use texturecraft_ui_egui::TextureCraftApp; - -/// Tall enough that Properties shows the whole decal editor without scrolling -const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1700.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; - -fn red_png() -> Vec { - let mut out = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); - out -} - -/// The app with a new decal layer selected in Properties, and its layer id -fn app_with_decal() -> (Harness<'static, TextureCraftApp>, u64) { - let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); - let image = session.import_resource_bytes("logo.png", red_png()).unwrap(); - let placed = json!({"image": image, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "size": 0.3}); - let layer = texturecraft_engine::execute(&mut session, "layer.add.decal", &placed).unwrap()["layer"].as_u64().unwrap(); - - 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(STARTUP_FRAMES); - (harness, layer) -} - -fn offset_of(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> f32 { - let project = &harness.state().session.doc.project; - let LayerKind::Fill(fill) = &project.layer(texturecraft_engine::core::LayerId(layer)).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; - decal.symmetry.expect("a mirrored copy").offset -} - -fn symmetry_of(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> Option<(u8, DecalFlip)> { - let project = &harness.state().session.doc.project; - let LayerKind::Fill(fill) = &project.layer(texturecraft_engine::core::LayerId(layer)).unwrap().kind else { panic!("a fill layer") }; - let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; - decal.symmetry.map(|symmetry| (symmetry.axis, symmetry.flip)) -} - -/// Opens the combo showing `current` and picks `choice` in its menu -fn pick(harness: &mut Harness<'_, TextureCraftApp>, current: &str, choice: &str) { - harness.get_all_by_role(Role::ComboBox).find(|combo| combo.value().as_deref() == Some(current)).expect("the combo").click(); - harness.run_steps(SETTLE_FRAMES); - harness.get_all_by_label(choice).last().expect("the menu entry").click(); - harness.run_steps(SETTLE_FRAMES); -} - -#[test] -fn the_mirror_axis_and_flip_are_set_from_the_decal_editor() { - let (mut harness, layer) = app_with_decal(); - assert!(harness.query_by_label("Mirror across").is_some()); - assert!(harness.query_by_label("Flip the copy's image").is_none(), "the flip needs a copy to flip"); - assert_eq!(symmetry_of(&harness, layer), None); - - pick(&mut harness, "Off", "X"); - assert_eq!(symmetry_of(&harness, layer), Some((0, DecalFlip::None))); - assert!(harness.query_by_label("Flip the copy's image").is_some()); - - pick(&mut harness, "None", "V"); - assert_eq!(symmetry_of(&harness, layer), Some((0, DecalFlip::V))); - - pick(&mut harness, "X", "Z"); - assert_eq!(symmetry_of(&harness, layer), Some((2, DecalFlip::V)), "a new axis keeps the flip"); - - pick(&mut harness, "Z", "Off"); - assert_eq!(symmetry_of(&harness, layer), None); - assert!(harness.query_by_label("Flip the copy's image").is_none()); -} - -#[test] -fn the_axis_position_slider_moves_the_mirror_plane() { - let (mut harness, layer) = app_with_decal(); - assert!(harness.query_by_label("Axis position").is_none(), "the position needs a copy to place"); - pick(&mut harness, "Off", "Y"); - assert_eq!(offset_of(&harness, layer), 0.0); - - // Press near the track's left end, drag toward its middle and right, release there - let label_rect = harness.get_by_label("Axis position").rect(); - let y = label_rect.bottom() + 10.0; - harness.drag_at(egui::pos2(label_rect.left() + 20.0, y)); - harness.run_steps(2); - harness.hover_at(egui::pos2(label_rect.left() + 120.0, y)); - harness.run_steps(2); - harness.drop_at(egui::pos2(label_rect.left() + 120.0, y)); - harness.run_steps(SETTLE_FRAMES); - assert!(offset_of(&harness, layer).abs() > 0.01, "the dragged position applies: {}", offset_of(&harness, layer)); - assert_eq!(symmetry_of(&harness, layer).map(|symmetry| symmetry.0), Some(1), "the axis is kept"); -} diff --git a/crates/ui-egui/tests/it/effect_decal.rs b/crates/ui-egui/tests/it/effect_decal.rs deleted file mode 100644 index 101fac1c..00000000 --- a/crates/ui-egui/tests/it/effect_decal.rs +++ /dev/null @@ -1,65 +0,0 @@ -//! A decal held by a mask fill effect has the same editor as a layer's decal: sliders and the placing click - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_engine::core::{Decal, EffectKind, LayerId, Projection}; -use texturecraft_ui_egui::TextureCraftApp; - -/// The sample session with a new decal mask fill effect selected, and that effect's id -fn selected_mask_decal() -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let image = { - let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); - session.import_resource_bytes("decal.png", png).unwrap() - }; - let placed = json!({"image": image, "channel": "mask", "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "size": 0.5}); - let effect = LayerId(texturecraft_engine::execute(&mut session, "layer.add.decal", &placed).unwrap()["maskEffect"].as_u64().unwrap()); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); - (harness, effect) -} - -fn decal(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Decal { - match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { - EffectKind::Fill { projection: Projection::Decal(decal), .. } => *decal, - _ => panic!("a decal fill effect"), - } -} - -#[test] -fn the_width_slider_resizes_a_mask_effects_decal_in_one_undo_step() { - let (mut harness, effect) = selected_mask_decal(); - - // Free width and height: with Keep proportions (on by default) the height would follow - harness.get_by_label("Keep proportions").click(); - harness.run_steps(2); - let before = decal(&harness, effect); - let steps = harness.state().session.history_labels().len(); - - let label_rect = harness.get_by_label("Width").rect(); - let y = label_rect.bottom() + 10.0; - harness.drag_at(egui::pos2(label_rect.left() + 10.0, y)); - harness.run_steps(2); - harness.hover_at(egui::pos2(label_rect.left() + 150.0, y)); - harness.run_steps(2); - harness.drop_at(egui::pos2(label_rect.left() + 150.0, y)); - harness.run_steps(3); - - let after = decal(&harness, effect); - assert!(after.size[0] > before.size[0], "the dragged width applies: {} -> {}", before.size[0], after.size[0]); - assert_eq!(after.size[1], before.size[1]); - assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); - harness.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(decal(&harness, effect), before); -} - -#[test] -fn place_on_the_surface_stays_armed_for_a_mask_effects_decal() { - let (mut harness, effect) = selected_mask_decal(); - harness.get_by_label_contains("Place on the surface").click(); - harness.run_steps(3); - assert_eq!(harness.state().placing_decal, Some(effect), "the click arms placing for the effect, not its layer"); -} diff --git a/crates/ui-egui/tests/it/fill_projection_section.rs b/crates/ui-egui/tests/it/fill_projection_section.rs deleted file mode 100644 index 983f1bc5..00000000 --- a/crates/ui-egui/tests/it/fill_projection_section.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! 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; - -/// 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(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(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(STARTUP_FRAMES); - (harness, layer) -} - -fn toggle_section(harness: &mut Harness<'_, TextureCraftApp>) { - harness.get_by_label("UV transformations").click(); - harness.run_steps(SETTLE_FRAMES); -} - -#[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()); - - 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] -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(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(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()); -} diff --git a/crates/ui-egui/tests/it/fill_support.rs b/crates/ui-egui/tests/it/fill_support.rs new file mode 100644 index 00000000..6adf3212 --- /dev/null +++ b/crates/ui-egui/tests/it/fill_support.rs @@ -0,0 +1,52 @@ +//! What the fill screens' tests share: the sample app with a new fill selected, the fill as the document holds it, and real pointer clicks on its controls + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Fill, LayerId, LayerKind}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::click_at; +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// The app `window` big with a new fill layer (`settings` given to layer.add.fill, then projected as `projection`) selected in Properties, `tab` clicked, and the layer's id +pub(crate) fn fill_app(settings: Value, projection: Option<&str>, tab: Option<&str>, window: egui::Vec2) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &settings).unwrap(); + let layer = added["layer"].as_u64().unwrap(); + if let Some(projection) = projection { + texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); + } + let mut harness = Harness::builder().with_size(window).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(STARTUP_FRAMES); + if let Some(tab) = tab { + click_node(&mut harness, Role::Tab, tab); + } + (harness, LayerId(layer)) +} + +/// The fill layer as the document holds it +pub(crate) fn fill_of(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Fill { + match &harness.state().session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.clone(), + other => panic!("not a fill: {other:?}"), + } +} + +/// A real pointer click in the middle of the `role` named `label`, then frames for the edit to show +pub(crate) fn click_node(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + let at = harness.get_by_role_and_label(role, label).rect().center(); + click_at(harness, at); + harness.run_steps(SETTLE_FRAMES); +} + +/// A real pointer click in the middle of the widget named `label`, whatever its role +pub(crate) fn click_label(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + let at = harness.get_by_label(label).rect().center(); + click_at(harness, at); + harness.run_steps(SETTLE_FRAMES); +} diff --git a/crates/ui-egui/tests/it/filter_support.rs b/crates/ui-egui/tests/it/filter_support.rs new file mode 100644 index 00000000..912e2017 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_support.rs @@ -0,0 +1,51 @@ +//! Helpers the filter panel tests share + +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; + +/// A real pointer click at `pos`: move there, press, one frame, release, then frames for the edit to show +pub(crate) fn click_at(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(pos)); + harness.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(3); +} + +/// A press at `from`, a drag to `to` in steps and a release, as the pointer does it +pub(crate) fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) { + let steps: Vec = (1..=DRAG_STEPS).map(|step| from + (to - from) * (step as f32 / DRAG_STEPS as f32)).collect(); + drag_through(harness, from, &steps); +} + +/// A press at `from`, a move to each of `steps` (one frame each) and a release at the last, as the pointer does it +pub(crate) fn drag_through(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, steps: &[egui::Pos2]) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(from)); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + for step in steps { + harness.event(egui::Event::PointerMoved(*step)); + harness.run_steps(1); + } + let to = steps.last().copied().unwrap_or(from); + harness.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); +} + +/// How far a slider's track runs inside its rect at each end (the knob's radius) +const SLIDER_TRACK_INSET: f32 = 5.0; + +/// The point at `share` (0..1) along slider `track`'s track: 0 is the range's start, 1 its end +pub(crate) fn along(track: egui::Rect, share: f32) -> egui::Pos2 { + egui::pos2(track.left() + SLIDER_TRACK_INSET + (track.width() - 2.0 * SLIDER_TRACK_INSET) * share, track.center().y) +} + +/// Moves a drag makes on its way, one frame each, so a press makes several changes +const DRAG_STEPS: usize = 4; + +/// The undo steps the session holds now +pub(crate) fn undo_depth(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 2b938e89..be8a4c26 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -13,11 +13,8 @@ mod close_unsaved; mod color_picker; mod color_selection_editor; mod curvature_generator; -mod decal_proportions; -mod decal_symmetry; mod display_environment; mod display_post_effects; -mod effect_decal; mod effect_rows; mod effect_sliders; mod empty_start; @@ -29,7 +26,9 @@ mod export_settings; mod export_template_guards; mod file_dialogs; mod fill_channel_image; -mod fill_projection_section; +mod fill_projection_rows; +mod fill_support; +mod fill_symmetry_rows; mod filter_picker; mod frame_selection; mod generator_panel; @@ -92,6 +91,7 @@ mod view2d_tiles; mod view_mode_picker; mod window_menu_684; +mod filter_support; mod stencil; mod symmetry; mod symmetry_2d; diff --git a/crates/ui-egui/tests/it/panel_header.rs b/crates/ui-egui/tests/it/panel_header.rs index 6485f50a..588732e3 100644 --- a/crates/ui-egui/tests/it/panel_header.rs +++ b/crates/ui-egui/tests/it/panel_header.rs @@ -235,3 +235,28 @@ fn a_tab_menus_panel_names_keep_their_plain_layout() { assert!(!padded.is_empty(), "the menu paints the Layers entry"); assert!(padded.iter().all(|height| *height == 0.0), "the Layers entry is padded to {padded:?}"); } + +/// Where the label on `name`'s row and to its right ends, for each label named `name` +fn row_ends(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Vec { + let names = harness.get_all_by_role_and_label(Role::Label, name).map(|node| node.rect()); + names + .filter_map(|name| { + let on_row = harness.get_all_by_role(Role::Label).map(|node| node.rect()); + on_row.filter(|rect| rect.left() > name.right() && (rect.center().y - name.center().y).abs() < 1.0).map(|rect| rect.right()).reduce(f32::max) + }) + .collect() +} + +/// Texture Set Settings keeps Base color's remove room, so its format ends where the other channels' formats do (it ended 24 px right) +#[test] +fn every_channels_format_ends_on_one_column() { + let mut harness = app(); + let settings = tab_rect(&harness, "Texture Set Settings"); + click_at(&mut harness, settings.center()); + harness.run_steps(SETTLE_FRAMES); + + let base_color = row_ends(&harness, "Base color"); + let roughness = row_ends(&harness, "Roughness"); + + assert!(base_color.len() == 1 && base_color == roughness, "Base color's format ends at {base_color:?}, Roughness's at {roughness:?}"); +} diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index ab50cb53..5a923224 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -158,3 +158,22 @@ fn polygon_fill_snapshots() { harness.run_steps(6); harness.render().unwrap().save(directory.join("polygon-fill-mask-2d.png")).unwrap(); } + +/// A Properties body not yet on the property sheet starts under the panel's name, at the sheet's side padding (it started 4 px left of it) +#[test] +fn the_polygon_fill_body_starts_under_the_properties_name() { + let mut harness = polygon_fill_app(); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(2); + + let painted_left = |wanted: &dyn Fn(&str) -> bool| { + harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if wanted(text.galley.text()) => Some(text.pos.x), + _ => None, + }) + }; + let caption = painted_left(&|text| text == "POLYGON FILL"); + let header = painted_left(&|text| text.starts_with("PROPERTIES")); + + assert!(caption.is_some() && caption == header, "the body starts at {caption:?}, the header name at {header:?}"); +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 1371e05b..a2cd6187 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -17,6 +17,10 @@ const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 const FORMAT_HINT: &str = "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export"; const TITLE: &str = "Project configuration"; +/// The window sits at the middle of the 1600-point-wide screen and is 560 points wide +const WINDOW_MIDDLE_X: f32 = 800.0; +const WINDOW_HALF_WIDTH: f32 = 280.0; + fn temp_dir(test: &str) -> TempDir { TempDir::new(test) } @@ -178,7 +182,9 @@ fn the_window_follows_the_reference_layout() { "Physical size", "Working color space", ]; - let top = |label: &str| h.get_all_by_label(label).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min); + // Only the window's own rows: a dock panel may show the same text (the fill's Scale switch offers Physical size) + let in_window = |node: &egui_kittest::Node<'_>| (node.rect().center().x - WINDOW_MIDDLE_X).abs() <= WINDOW_HALF_WIDTH; + let top = |label: &str| h.get_all_by_label(label).filter(in_window).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min); for labels in order.windows(2) { assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]); } diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 8d3b413f..fcc33f66 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -1,18 +1,46 @@ //! 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::{Event, Key, Modifiers, PointerButton, Pos2, Role, vec2}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, 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}; +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// A common laptop window +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Tall enough that the docked list ends before a fill's MATERIAL caption reaches its top +const JUMP_TAB_WINDOW: egui::Vec2 = egui::vec2(1600.0, 1300.0); + +/// Width of the docked jump tab strip, from its Fill tab across its other two +const DOCKED_STRIP_WIDTH: f32 = 300.0; + +/// Frames for a jump tab's scroll to land +const JUMP_FRAMES: usize = 4; + +/// Frames for a selection made through the engine to show +const SELECT_FRAMES: usize = 3; + +/// Pointer moves a drag makes between its press and its release +const DRAG_MOVES: usize = 4; + 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_sized(WINDOW_SIZE) +} + +/// The sample project's app in a window of `size`, speaking English +fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(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(STARTUP_FRAMES); harness } @@ -30,7 +58,7 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, 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); + harness.run_steps(SETTLE_FRAMES); } /// Drag with `button` from `from` by `by` in a few moves while `modifiers` are held @@ -38,14 +66,14 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: 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(DRAG_STEP_FRAMES); + for step in 1..=DRAG_MOVES { + harness.hover_at(from + by * (step as f32 / DRAG_MOVES as f32)); 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); + harness.run_steps(SETTLE_FRAMES); } #[test] @@ -144,16 +172,49 @@ fn it_shows_what_the_properties_panel_shows() { 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:?}"); + let projected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": fill, "projection": "uv"})); + assert!(projected.is_ok(), "{projected:?}"); 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("UV projection"), "a selected fill shows its fill settings"); assert!(!in_popup("Minimum size (%)"), "not the brush's"); } +/// Whether the jump tab `name` inside `area` is the lit one +fn tab_lit(harness: &Harness<'_, TextureCraftApp>, area: egui::Rect, name: &str) -> bool { + let tab = harness.get_all_by_role_and_label(Role::Tab, name).find(|tab| area.contains_rect(tab.rect())); + tab.unwrap_or_else(|| panic!("a {name} tab in {area:?}")).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_panel() { + let mut harness = harness_sized(JUMP_TAB_WINDOW); + let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": fill, "projection": "uv"})).unwrap(); + harness.run_steps(SELECT_FRAMES); + + 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 docked_fill = harness.get_all_by_role_and_label(Role::Tab, "Fill").map(|tab| tab.rect()).find(|tab| !popup.contains_rect(*tab)).unwrap(); + + let docked = egui::Rect::from_min_max(docked_fill.min, docked_fill.max + vec2(DOCKED_STRIP_WIDTH, 0.0)); + let in_popup = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); + assert!(tab_lit(&harness, popup, "Fill"), "it opens on Fill"); + assert!(in_popup(&harness, "UV projection")); + + harness.run_steps(JUMP_FRAMES); + + assert!(is_open(&harness), "a tab click keeps it open"); + assert!(!tab_lit(&harness, popup, "Fill")); + assert!(tab_lit(&harness, docked, "Fill"), "the docked panel keeps its own place"); +} + #[test] fn bake_and_render_modes_never_open_it() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 56e57f62..848064c3 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -249,13 +249,11 @@ fn changing_the_camera_cancels_a_drop_with_stale_view_coordinates() { } #[test] -fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { +fn the_click_that_closes_the_drop_menu_paints_nothing_and_adds_no_undo_step() { let (mut harness, position) = drop_image(Some(1)); let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); harness.run_steps(2); - let decal_layer = harness.state().session.selected_layer().unwrap(); - harness.state_mut().placing_decal = Some(decal_layer); let image = import_white_image(&mut harness); drop_asset(&mut harness, Asset::Texture(image), position); @@ -281,7 +279,7 @@ fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { harness.run_steps(2); assert!(!menu_open(&harness, position)); - assert_eq!(harness.state().session.history_labels().len(), history, "the decal wasn't moved"); + assert_eq!(harness.state().session.history_labels().len(), history, "the closing click painted nothing"); } #[test] diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index 030e709a..d148d41f 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -19,13 +19,15 @@ const AXIS_PROBE: f32 = 0.05; const ON_THE_SHAFT: f32 = 40.0; const DRAG_DISTANCE: f32 = 60.0; +/// Window wide enough that the top bar shows every paint control, Symmetry's included, with Properties at its least width +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1760.0, 960.0); + /// A point inside the 3D view near its lower left corner, clear of the mesh and the popup (points from the corner) const VIEW_CORNER_INSET: f32 = 40.0; fn app_harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(1024, 256).unwrap(); - let mut harness = - Harness::builder().with_size(egui::vec2(1760.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 7462516b..804cf5fc 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -816,48 +816,22 @@ fn mask_fill_image_snapshot() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(6); - harness.get_by_value("Uniform value").click(); + // The Grayscale slot opens the source picker; its search finds the image + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.event(egui::Event::Text("checker".into())); harness.run_steps(3); save(&mut harness, &output_dir, "mask-fill-image-menu"); - harness.get_by_role_and_label(egui::Role::Button, &name).click(); + harness.get_by_role_and_label(egui::Role::ListBoxOption, &name).click(); harness.run_steps(4); let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; assert_eq!(*source, Source::image(name)); - assert!(harness.query_by_label("Projection").is_some(), "image projection is editable"); + assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); save(&mut harness, &output_dir, "mask-fill-image-selected"); } -#[test] -#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn tile_generator_gradient_map_snapshot() { - use serde_json::json; - use texturecraft_engine::execute; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - execute( - &mut session, - "layer.fill.set", - &json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}), - ) - .unwrap(); - - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.dock.focus(Panel::Properties); - harness.run_steps(6); - harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me(); - harness.run_steps(30); - - assert!(harness.query_by_label_contains("Add color").is_some()); - save(&mut harness, &output_dir, "tile-generator-gradient-map"); -} - /// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered #[test] #[ignore] @@ -887,6 +861,35 @@ fn panel_header_snapshots() { save(&mut harness, &output_dir, "panel-header-close-hovered"); } +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn tile_generator_gradient_map_snapshot() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + execute( + &mut session, + "layer.fill.set", + &json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}), + ) + .unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me(); + harness.run_steps(30); + + assert!(harness.query_by_label_contains("Add color").is_some()); + save(&mut harness, &output_dir, "tile-generator-gradient-map"); +} + /// Edit > Settings: the three pages and a compact window at 150% scale #[test] #[ignore] @@ -957,3 +960,408 @@ fn default_layout_snapshots() { harness.hover_at(egui::pos2(properties_close.center().x - 120.0, properties_close.min.y - 6.0)); save(&mut harness, &output_dir, "default-layout-split-hovered"); } + +#[test] +#[ignore] +fn fill_reset_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "tiling": [2.0, 2.0], "filtering": "nearest"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("fill-reset-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + let reset = harness.get_by_label("Fill: Reset to defaults").rect().center(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "fill-reset-hovered"); + + // The band sits under the fold at this height: scroll Properties down to it + harness.hover_at(reset); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -110.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }); + harness.run_steps(3); + let edges = harness.get_by_label("Restore defaults").rect().center(); + harness.hover_at(edges); + save(&mut harness, &output_dir, "fill-reset-band-hovered"); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 110.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }); + harness.run_steps(3); + harness.get_by_label("Fill: Reset to defaults").click(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "fill-reset-at-defaults"); +} + +#[test] +#[ignore] +fn fill_properties_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute( + &mut session, + "layer.fill.projection", + &json!({"layer": layer, "tiling": [2.0, 2.0], "rotation": 30.0, "offset": [0.25, 0.0], "wrap": "repeat", "filtering": "bilinearHq"}), + ) + .unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("fill-uv-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + + // A UV pad drag right, held mid-way: the ring stays in the middle, the filled dot and the checker go right; then a dot past the edge + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "offset": [0.0, 0.0]})).unwrap(); + harness.run_steps(2); + let pad = harness.get_by_label("Move on model").rect().center(); + harness.event(egui::Event::PointerMoved(pad)); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=20 { + harness.event(egui::Event::PointerMoved(pad + egui::vec2(6.0 * step as f32, 0.0))); + harness.run_steps(1); + } + save(&mut harness, &output_dir, "fill-uv-pad-dragged-right"); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "offset": [-1.6, 0.6]})).unwrap(); + save(&mut harness, &output_dir, "fill-uv-dot-past-edge"); + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "offset": [0.25, 0.0]})).unwrap(); + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + for (shown, hover, name) in [ + ("UV projection", "Planar projection", "fill-uv-projection-open"), + ("Bilinear | HQ", "Nearest", "fill-uv-filtering-open"), + ("Repeat", "Repeat horizontally", "fill-uv-wrap-open"), + ] { + harness.get_by_label(shown).click(); + harness.run_steps(2); + harness.get_by_label(hover).hover(); + save(&mut harness, &output_dir, name); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + } + harness.get_by_label("Physical size").click(); + save(&mut harness, &output_dir, "fill-uv-physical"); + harness.get_by_label("Link").click(); + save(&mut harness, &output_dir, "fill-uv-physical-unlinked"); + + // Screen 02: every other projection, with the lists that open from its new rows + let cases = [ + ("spherical", json!({}), "fill-spherical"), + ("cylindrical", json!({"scaleMode": "physicalSize"}), "fill-cylindrical"), + ("cylindrical", json!({"angle": 120.0, "backfaceCulling": true}), "fill-cylindrical-angle"), + ("triplanar", json!({"scaleMode": "physicalSize"}), "fill-triplanar"), + ("planar", json!({"scaleMode": "physicalSize", "backfaceCulling": true, "shapeCrop": "cropped"}), "fill-planar"), + ("warp", json!({"scaleMode": "physicalSize", "warpCorners": [[-0.55, 0.48], [0.56, 0.6], [0.48, -0.55], [-0.45, -0.45]]}), "fill-warp"), + // The image's Rotation turns the checker inside the frame + ("warp", json!({"scaleMode": "tiling", "tiling": [2.0, 2.0], "rotation": 30.0}), "fill-warp-rotated"), + ("uvTile", json!({}), "fill-uvtile"), + ]; + for (kind, settings, name) in cases { + let session = &mut harness.state_mut().session; + execute(session, "layer.fill.projection", &json!({"layer": layer, "projection": kind})).unwrap(); + let mut settings = settings; + settings["layer"] = layer.clone(); + execute(session, "layer.fill.projection", &settings).unwrap(); + save(&mut harness, &output_dir, name); + } + + // The preview square is Move on model's pad: lit on hover and while held + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Move on model").hover(); + save(&mut harness, &output_dir, "fill-planar-pad-hover"); + let pad = harness.get_by_label("Move on model").rect().center(); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + save(&mut harness, &output_dir, "fill-planar-pad-held"); + harness.event(egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + + // A slid projector: the object stays put, the ring marks Offset 0 and the filled dot where the projector went + for (kind, offset, name) in [("planar", [0.3, 0.15, 0.0], "fill-planar-slid"), ("spherical", [0.5, 0.3, 0.0], "fill-spherical-slid")] { + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": kind, "offset": offset})).unwrap(); + save(&mut harness, &output_dir, name); + } + + // The Projection row's eye: hovered, then the gizmos hidden + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar", "offset": [0.0, 0.0, 0.0]})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Hide projection gizmos").hover(); + save(&mut harness, &output_dir, "fill-planar-eye-hover"); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Hide projection gizmos").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "fill-planar-eye-hidden"); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Show projection gizmos").click(); + harness.run_steps(2); + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "uvTile"})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Fill (Match per UV Tile)").click(); + harness.run_steps(2); + harness.get_by_label("Warp projection").hover(); + save(&mut harness, &output_dir, "fill-uvtile-projection-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + let session = &mut harness.state_mut().session; + + // Tri-planar's Shape crop sits highest in the panel: its list opens in view + execute(session, "layer.fill.projection", &json!({"layer": layer, "projection": "triplanar"})).unwrap(); + harness.run_steps(2); + harness.get_by_label("Extends Outside Shape").click(); + harness.run_steps(2); + harness.get_by_label("Cropped to Shape").hover(); + save(&mut harness, &output_dir, "fill-triplanar-crop-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + + // The shape previews take their colours from the theme + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("fill-triplanar-{name}")); + } +} + +/// Screen 03: a planar fill's Symmetry section off, mirrored (a moved Y plane with U flipped), radial (6 over a full turn, 4 over half a turn, also in the dark and light themes), its Type list open, and a UV fill's greyed switch +#[test] +#[ignore] +fn fill_symmetry_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Symmetry").click(); + let cases = [ + (json!({}), "symmetry-off"), + (json!({"symmetry": true}), "symmetry-mirror"), + (json!({"symmetryAxis": 1, "axisPosition": [0.0, 0.4, 0.0], "flipCopy": [true, false]}), "symmetry-mirror-y"), + (json!({"symmetryType": "radial", "symmetryAxis": 2, "axisPosition": 0, "flipCopy": [false, false]}), "symmetry-radial"), + (json!({"symmetryCount": 4, "angleSpan": 180}), "symmetry-radial-half"), + ]; + for (settings, name) in cases { + let mut settings = settings; + settings["layer"] = layer.clone(); + execute(&mut harness.state_mut().session, "layer.fill.projection", &settings).unwrap(); + save(&mut harness, &output_dir, name); + } + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("symmetry-radial-half-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.get_by_role_and_label(egui::Role::ComboBox, "Radial symmetry").click(); + harness.run_steps(2); + harness.get_by_label("Mirror symmetry").hover(); + save(&mut harness, &output_dir, "symmetry-type-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::RadioButton, "X").hover(); + save(&mut harness, &output_dir, "symmetry-axis-hover"); + + execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Symmetry").click(); + harness.run_steps(4); + harness.get_by_label("Not available with UV projection").hover(); + save(&mut harness, &output_dir, "symmetry-uv"); +} + +/// The culling rows' i on a planar fill: each one hovered with its tooltip, in the medium theme, then the Depth culling one in the dark and light themes +#[test] +#[ignore] +fn info_icon_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "planar"})).unwrap(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "scaleMode": "physicalSize", "backfaceCulling": true})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + + // The test's stand-in arrow would hide the hovered i + harness.set_render_cursor(false); + harness.run_steps(4); + let tips = [ + ("Paints only the surface the projector sees first; parts hidden behind it stay unpainted.", "depth"), + ("Leaves out faces turned away from the projector, so the fill doesn't run onto their back.", "backface"), + ]; + for (tip, name) in tips { + let info = harness.get_by_label(tip).rect().center(); + harness.hover_at(info); + harness.run_steps(60); + save(&mut harness, &output_dir, &format!("info-{name}-medium")); + } + let info = harness.get_by_label(tips[0].0).rect().center(); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.hover_at(info); + harness.run_steps(60); + save(&mut harness, &output_dir, &format!("info-depth-{name}")); + } +} + +/// The right-click Properties popup on a UV fill: its jump tabs with Symmetry hovered, Material clicked, then wheeled up to Symmetry; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn popup_tabs_snapshots() { + use egui::{Event, Modifiers, PointerButton}; + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.set_render_cursor(false); + harness.run_steps(4); + + let at = harness.state().viewport_rect.center() - egui::vec2(200.0, 250.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + harness.run_steps(4); + let popup = harness.ctx.memory(|memory| memory.area_rect(texturecraft_ui_egui::properties_popup::area_id())).unwrap(); + let tab = |harness: &Harness<'_, TextureCraftApp>, name: &str| { + harness.get_all_by_role_and_label(egui::accesskit::Role::Tab, name).map(|tab| tab.rect()).find(|tab| popup.contains_rect(*tab)).unwrap().center() + }; + let symmetry = tab(&harness, "Symmetry"); + harness.hover_at(symmetry); + harness.run_steps(4); + save(&mut harness, &output_dir, "popup-tabs-fill-medium"); + + let material = tab(&harness, "Material"); + harness.hover_at(material); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: material, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + harness.run_steps(60); + save(&mut harness, &output_dir, "popup-tabs-material-medium"); + + harness.hover_at(popup.center()); + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 260.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }); + harness.run_steps(6); + save(&mut harness, &output_dir, "popup-tabs-symmetry-medium"); + + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("popup-tabs-symmetry-{name}")); + } + } +} + +/// The Properties panel at its minimum width (the right column dragged as narrow as it goes), on the Fill tab's widest row (3D projection settings) and on a filter +#[test] +#[ignore] +fn properties_min_width_snapshot() { + use craft_ui::docking::Node; + use craft_ui::layout::SplitSize; + use serde_json::json; + use texturecraft_engine::execute; + use texturecraft_ui_egui::docking::Dock; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + let settings = json!({"layer": layer, "projection": "planar", "scaleMode": "physicalSize", "backfaceCulling": true, "shapeCrop": "cropped"}); + execute(&mut session, "layer.fill.projection", &settings).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + let mut workspace = harness.state().ui.dock.workspace().clone(); + let Some(Node::Split { second, .. }) = workspace.layout.root.as_mut() else { panic!("default columns") }; + let Node::Split { size, .. } = second.as_mut() else { panic!("viewport and right column") }; + *size = SplitSize::FixedSecond(0.0); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("properties-min-width-planar-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "colorMatch"})).unwrap(); + save(&mut harness, &output_dir, "properties-min-width-filter"); +} + +/// The docked Properties list of a fill whose sections all fit, scrolled to its end: MATERIAL at the top, blank space under it +#[test] +#[ignore] +fn sheet_scroll_end_snapshots() { + use egui::{Event, Modifiers}; + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.set_render_cursor(false); + harness.run_steps(4); + save(&mut harness, &output_dir, "sheet-end-top-medium"); + + let strip = harness.get_by_role_and_label(egui::accesskit::Role::Tab, "Fill").rect(); + harness.hover_at(strip.center_bottom() + egui::vec2(0.0, 100.0)); + for _ in 0..40 { + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -120.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + harness.step(); + } + harness.run_steps(30); + save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); +} From b5b99d6fd3ba97d69b69ce4304e47eb4019e89f4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:29 +0000 Subject: [PATCH 025/153] Fills: Material and colour commands, panels and tests --- apps/texturecraft/src/main.rs | 7 + crates/compose/src/eval.rs | 15 +- crates/compose/tests/cache_and_instances.rs | 2 +- crates/core/src/cook_resolution.rs | 58 ++ crates/core/src/layer.rs | 100 +++- crates/core/src/lib.rs | 8 +- crates/core/src/project.rs | 18 +- crates/core/src/randomized_seed.rs | 14 + crates/engine/src/commands.rs | 2 + crates/engine/src/fill_alpha.rs | 65 +++ crates/engine/src/fill_material_cmds.rs | 154 +++++ crates/engine/src/inspect.rs | 4 + crates/engine/src/layer_cmds.rs | 34 +- crates/engine/src/lib.rs | 3 + crates/engine/src/material_lib.rs | 7 +- crates/engine/src/materials.rs | 46 +- crates/engine/src/painting.rs | 13 +- crates/engine/src/swatch_cmds.rs | 48 ++ crates/engine/tests/it/fill_alpha_source.rs | 66 +++ crates/engine/tests/it/fill_whole_material.rs | 155 +++++ crates/engine/tests/it/filter_support.rs | 44 ++ crates/engine/tests/it/main.rs | 4 + crates/engine/tests/it/materialcraft_link.rs | 84 ++- crates/engine/tests/it/painter_gaps.rs | 20 +- crates/engine/tests/it/swatches.rs | 36 ++ crates/engine/tests/session.rs | 85 +++ crates/paint/src/pickup.rs | 1 + crates/ui-egui/src/dock.rs | 353 +++-------- crates/ui-egui/src/exact_entry_open.rs | 5 - crates/ui-egui/src/fill_panel.rs | 11 + crates/ui-egui/src/fill_pictures.rs | 1 - crates/ui-egui/src/generator_panel.rs | 2 +- crates/ui-egui/src/lib.rs | 41 +- crates/ui-egui/src/menus.rs | 17 +- crates/ui-egui/src/pattern_panel.rs | 29 +- crates/ui-egui/src/projection_preview.rs | 1 + crates/ui-egui/src/properties_popup.rs | 11 +- .../ui-egui/src/property_sheet/button_icon.rs | 10 + crates/ui-egui/src/property_sheet/choice.rs | 14 + crates/ui-egui/src/property_sheet/group.rs | 64 ++ .../src/property_sheet/material_rows.rs | 113 ++++ crates/ui-egui/src/property_sheet/mod.rs | 16 + .../ui-egui/src/property_sheet/ramp_edit.rs | 10 + crates/ui-egui/src/property_sheet/row.rs | 6 + crates/ui-egui/src/property_sheet/slider.rs | 25 + crates/ui-egui/src/property_sheet/slot.rs | 221 +++++++ .../src/property_sheet/slot_response.rs | 15 + .../src/property_sheet/switch_control.rs | 115 +++- crates/ui-egui/src/property_sheet/tests.rs | 533 +++++++++++++++++ .../src/property_sheet/tests/gallery.rs | 37 ++ crates/ui-egui/src/rail_popup.rs | 11 +- crates/ui-egui/src/round_gizmo.rs | 24 + crates/ui-egui/src/shelf.rs | 11 - crates/ui-egui/src/state.rs | 9 + crates/ui-egui/src/symmetry/plane_pick.rs | 25 + crates/ui-egui/src/theme.rs | 63 +- crates/ui-egui/src/toolbar.rs | 69 ++- crates/ui-egui/src/viewport.rs | 76 ++- crates/ui-egui/src/widgets.rs | 12 +- crates/ui-egui/tests/brush_cursor_2d.rs | 14 + .../tests/it/color_selection_editor.rs | 12 +- crates/ui-egui/tests/it/fill_channel_image.rs | 41 +- crates/ui-egui/tests/it/gradient_map_menu.rs | 55 -- crates/ui-egui/tests/it/layers_panel.rs | 40 ++ crates/ui-egui/tests/it/main.rs | 48 +- crates/ui-egui/tests/it/properties_popup.rs | 65 ++- crates/ui-egui/tests/it/properties_scroll.rs | 193 ++++++ crates/ui-egui/tests/it/rename_anchor.rs | 2 +- .../ui-egui/tests/it/tile_generator_panel.rs | 9 +- crates/ui-egui/tests/ui_snapshots.rs | 552 +++++++++++++++--- docs/control-protocol.md | 48 +- 71 files changed, 3525 insertions(+), 597 deletions(-) create mode 100644 crates/core/src/cook_resolution.rs create mode 100644 crates/core/src/randomized_seed.rs create mode 100644 crates/engine/src/fill_alpha.rs create mode 100644 crates/engine/src/fill_material_cmds.rs create mode 100644 crates/engine/src/swatch_cmds.rs create mode 100644 crates/engine/tests/it/fill_alpha_source.rs create mode 100644 crates/engine/tests/it/fill_whole_material.rs create mode 100644 crates/engine/tests/it/filter_support.rs create mode 100644 crates/engine/tests/it/swatches.rs delete mode 100644 crates/ui-egui/src/exact_entry_open.rs create mode 100644 crates/ui-egui/src/property_sheet/material_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/ramp_edit.rs create mode 100644 crates/ui-egui/src/property_sheet/slot_response.rs delete mode 100644 crates/ui-egui/tests/it/gradient_map_menu.rs create mode 100644 crates/ui-egui/tests/it/properties_scroll.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 4af56d84..0ebd5e94 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -196,6 +196,13 @@ fn main() { if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } + + // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument + #[cfg(windows)] + if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) { + std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer()); + } + let args = match parse_args() { Ok(Some(a)) => a, Ok(None) => return, diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 5dedc593..1b90a147 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -230,6 +230,7 @@ enum Content<'a> { Paint { preview: bool, }, + /// A fill (with the Scale and Rotation of the folders around it laid on) Fill { fill: Box>, /// Its projector's depth map when it culls by depth @@ -321,13 +322,14 @@ enum Op { Slope { scale: f32, seed: u32 }, } -/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]) fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } /// Below this a coverage weight counts as no coverage at all. const MIN_COVERAGE_WEIGHT: f32 = 1e-6; + /// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. const FILTER_SIZE_RESOLUTION: f32 = 2048.0; /// The smallest radius a filter runs at, in texels. @@ -1098,9 +1100,10 @@ struct Node<'a> { content: Content<'a>, chans: Vec>, mask: Option>, - /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an anchor with visible effects above it) with its content cut after `k` visible effects + /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an + /// anchor with visible effects above it) with its content cut after `k` visible effects. anchors: Vec<(LayerId, Option)>, - /// The node or one of its children records an anchor + /// The node or one of its children records an anchor. has_anchor: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). @@ -1188,11 +1191,12 @@ fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids` +/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are +/// planned when `kids`. #[allow(clippy::too_many_arguments)] fn plan_node<'a>( inp: &EvaluationInputs<'a>, @@ -2243,8 +2247,9 @@ impl<'a, 'b> Texel<'a, 'b> { // Baked lighting reads the texel's normal and occlusion, and lights the base color only EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { - let nrm = self.coords().nrm.to_array(); let factor = filter.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); + let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); + let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) } _ => (value, coverage), diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 4ec0863e..e8c4270c 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -667,7 +667,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { // Changing the hot mask must invalidate the retained fields let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); - mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); + let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap(); let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); diff --git a/crates/core/src/cook_resolution.rs b/crates/core/src/cook_resolution.rs new file mode 100644 index 00000000..3b4f8942 --- /dev/null +++ b/crates/core/src/cook_resolution.rs @@ -0,0 +1,58 @@ +//! The size a cooked source (a MaterialCraft material's maps) is made at + +use serde::{Deserialize, Serialize}; + +use crate::layer::OutputResolution; +use crate::{MAX_RESOLUTION, MIN_RESOLUTION}; + +/// How big a source is cooked: relative to its texture set (following it when it changes) or a fixed size +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CookResolution { + /// The texture set's resolution times 2 to this power + Relative(i8), + /// Pixels across + Fixed(u32), +} + +impl CookResolution { + /// The texture set's own resolution (Auto) + pub const TEXTURE_SET: CookResolution = CookResolution::Relative(0); + + /// Powers of two a relative size may scale the texture set's by, as a generator's output resolution does + pub const FACTORS: std::ops::RangeInclusive = OutputResolution::FACTORS; + + /// Pixels across for a texture set `set` pixels across: a power of two the engine can cook, else the texture set's size + pub fn size(self, set: u32) -> u32 { + let size = match self { + CookResolution::Relative(factor) => { + let factor = factor.clamp(*Self::FACTORS.start(), *Self::FACTORS.end()); + if factor >= 0 { set.saturating_mul(1 << factor) } else { set >> factor.unsigned_abs() } + } + CookResolution::Fixed(size) => size, + }; + if Self::cookable(size) { size } else { set } + } + + /// Whether maps may be cooked `size` pixels across + pub fn cookable(size: u32) -> bool { + size.is_power_of_two() && (MIN_RESOLUTION..=MAX_RESOLUTION).contains(&size) + } +} + +#[cfg(test)] +mod tests { + use super::CookResolution; + + #[test] + fn sizes_follow_the_texture_set_and_stay_cookable() { + assert_eq!(CookResolution::TEXTURE_SET.size(2048), 2048); + assert_eq!(CookResolution::Relative(-1).size(2048), 1024); + assert_eq!(CookResolution::Relative(2).size(1024), 4096); + assert_eq!(CookResolution::Relative(3).size(2048), 2048, "16384 is past the largest cook"); + assert_eq!(CookResolution::Relative(i8::MIN).size(1024), 128); + assert_eq!(CookResolution::Fixed(512).size(2048), 512); + assert_eq!(CookResolution::Fixed(300).size(2048), 2048); + assert_eq!(CookResolution::Fixed(u32::MAX).size(2048), 2048); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 34664b03..1f8f731d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -710,6 +710,9 @@ pub struct Fill { /// Set when the sources are maps cooked from a MaterialCraft material. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option>, + /// The built-in material (shelf id) the sources were set from as one whole material; cleared when a channel's source changes on its own + #[serde(default, skip_serializing_if = "Option::is_none")] + pub material: Option, } /// A MaterialCraft material behind a fill (from a `.mcmat` portable material): its channel @@ -730,6 +733,22 @@ pub struct MaterialLink { pub inputs: Vec, /// Size the maps were cooked at (pixels across). pub size: u32, + /// Size to cook at; `None` cooks at the texture set's resolution + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resolution: Option, + /// The output a channel reads, where it is not the output named like the channel + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub mapping: BTreeMap, + /// The image resource of each output of the last cook, by output id. Empty in projects saved before channels could be mapped: there each channel's source is its own output + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub outputs: BTreeMap, +} + +impl MaterialLink { + /// The output channel `c` reads + pub fn output_of(&self, c: Channel) -> &str { + self.mapping.get(&c).map_or(c.id(), String::as_str) + } } /// An exposed input of a linked material. Values keep MaterialCraft's typed form, @@ -767,6 +786,22 @@ impl Fill { pub fn source(&self, c: Channel) -> Source { self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c)) } + + /// The image resource of each output of the linked material's last cook, by output id (empty without a link). Links saved before channels could be mapped list their channels' own outputs + pub fn link_outputs(&self) -> BTreeMap { + let Some(link) = &self.link else { return BTreeMap::new() }; + if !link.outputs.is_empty() { + return link.outputs.clone(); + } + + self.sources + .iter() + .filter_map(|(c, s)| match s { + Source::Image { name, .. } => Some((link.output_of(*c).to_string(), name.clone())), + _ => None, + }) + .collect() + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -1327,10 +1362,9 @@ impl Filter { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum EffectKind { - /// Painted grayscale (mask) or material (content) pixels keyed by the effect id. + /// Painted grayscale (mask) or material (content) pixels keyed by the effect id Paint, - /// A path sublayer: pixels keyed by the effect id like [`EffectKind::Paint`], but painted - /// only from its stored paths and repainted whenever one is added, edited or removed. + /// A path sublayer: pixels keyed by the effect id like [`EffectKind::Paint`], but painted only from its stored paths and repainted whenever one is added, edited or removed Path(Vec), /// A uniform or procedural grayscale fill. Fill { @@ -1625,6 +1659,33 @@ mod tests { assert!(d.apply(0.7).is_finite()); } + #[test] + fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { + let fills = [ + r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#, + r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#, + r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":1.0}}}"#, + ]; + for saved in fills { + let loaded: Fill = serde_json::from_str(saved).unwrap(); + + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); + } + + let effects = [ + r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, + r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, + ]; + for saved in effects { + let loaded: EffectKind = serde_json::from_str(saved).unwrap(); + + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); + } + } + #[test] fn hsl_adjust_shifts_hue_saturation_and_lightness() { let close = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-4); @@ -1658,12 +1719,17 @@ mod tests { assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); + let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); + let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); + assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); + let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); @@ -1721,7 +1787,6 @@ mod tests { generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); - generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); assert!(generator_layer.reads_anchor()); @@ -1767,33 +1832,6 @@ mod tests { } } - #[test] - fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { - let fills = [ - r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#, - r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#, - r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#, - r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#, - r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#, - r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":1.0}}}"#, - ]; - for saved in fills { - let loaded: Fill = serde_json::from_str(saved).unwrap(); - - assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); - } - - let effects = [ - r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, - r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, - ]; - for saved in effects { - let loaded: EffectKind = serde_json::from_str(saved).unwrap(); - - assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); - } - } - #[test] fn procedural_kinds_parse_labels_and_saved_names() { for kind in ProceduralKind::ALL { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index be8338bc..1c877b7b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,12 +12,14 @@ pub mod bake; pub mod blend; mod block_scales; pub mod channel; +pub mod cook_resolution; pub mod depth_culling; mod env_alignment; pub mod fill_symmetry; pub mod layer; pub mod project; pub mod projector; +pub mod randomized_seed; mod saved_decal; mod saved_projection; mod shadow_mode; @@ -37,6 +39,7 @@ pub use bake::{ }; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use cook_resolution::CookResolution; pub use depth_culling::DepthCulling; pub use fill_symmetry::FillSymmetry; pub use layer::{ @@ -46,10 +49,11 @@ pub use layer::{ TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, }; pub use project::{ - AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, - Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, + AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat, + NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; pub use projector::Projector; +pub use randomized_seed::RandomizedSeed; pub use shape_crop::ShapeCrop; pub use symmetry_kind::SymmetryKind; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 7b6c92c2..df5aa54a 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -15,6 +15,9 @@ pub const FORMAT_VERSION: u32 = 3; /// First format whose baked bent normal maps are in tangent space pub const TANGENT_BENT_NORMAL_VERSION: u32 = 3; +/// Most colour swatches a project keeps +pub const MAX_SWATCHES: usize = 64; + /// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; @@ -439,6 +442,9 @@ pub struct Project { /// Saved and imported cameras (the viewport's default camera is not in the list). #[serde(default)] pub cameras: Vec, + /// The project's colour swatches (linear RGB), in the order they were added; projects without any save none + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub swatches: Vec<[f32; 3]>, } impl Project { @@ -455,6 +461,7 @@ impl Project { next_id: 1, display: DisplaySettings::default(), cameras: Vec::new(), + swatches: Vec::new(), } } @@ -757,17 +764,23 @@ mod tests { let gid = p.alloc_id(); let g = Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &Channel::DEFAULT_SET); p.insert_layer(0, g, Some(a), false).unwrap(); + assert_eq!(p.texture_sets[0].stack, vec![a, gid, b]); + p.move_above(b, Some(gid), true).unwrap(); + assert_eq!(p.texture_sets[0].stack, vec![a, gid]); assert_eq!(p.layer(gid).unwrap().children(), &[b]); assert_eq!(p.locate(b), Some((0, Some(gid), 0))); assert!(p.move_above(gid, Some(b), true).is_err(), "a group cannot go inside itself"); + p.validate().unwrap(); let removed = p.remove_layer(gid).unwrap(); + assert_eq!(removed, vec![gid, b]); assert_eq!(p.texture_sets[0].stack, vec![a]); assert!(p.layer(b).is_err()); + p.validate().unwrap(); } @@ -853,15 +866,18 @@ mod tests { let a = p.insert_layer(0, a, None, false).unwrap(); let inst = Layer::new(p.alloc_id(), "a", LayerKind::Instance { source: a }, &[]); let inst = p.insert_layer(1, inst, None, false).unwrap(); + assert_eq!(p.content_layer(inst).map(|l| l.id), Some(a)); assert_eq!(p.sets_drawing(a), vec![0, 1]); assert_eq!(p.sets_drawing(inst), vec![1]); + p.validate().unwrap(); - // A folder holding an instance of itself draws itself. + // A folder holding an instance of itself draws itself let gid = p.alloc_id(); p.insert_layer(1, Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &[]), None, false).unwrap(); let loop_id = p.alloc_id(); p.insert_layer(1, Layer::new(loop_id, "g", LayerKind::Instance { source: gid }, &[]), Some(gid), true).unwrap(); + assert_eq!(p.instance_cycle(), Some(loop_id)); assert!(p.validate().is_err()); assert!(p.content_layer(LayerId(999)).is_none()); diff --git a/crates/core/src/randomized_seed.rs b/crates/core/src/randomized_seed.rs new file mode 100644 index 00000000..222fe9df --- /dev/null +++ b/crates/core/src/randomized_seed.rs @@ -0,0 +1,14 @@ +//! One seed a folder's Randomize seeds changed, kept on the folder so its Contents reset can put it back + +use serde::{Deserialize, Serialize}; + +use crate::layer::LayerId; + +/// A seed inside a folder that the folder's Randomize seeds changed: the `index`-th seed of layer `layer` (its fill's, then its content and mask effects', in stack order) went from `before` to `after` +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RandomizedSeed { + pub layer: LayerId, + pub index: u32, + pub before: u32, + pub after: u32, +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 32451af5..3692499c 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -111,6 +111,7 @@ pub fn command_specs() -> &'static [CommandSpec] { let mut v = Vec::new(); v.extend(crate::view_cmds::edit_specs()); v.extend(crate::layer_cmds::specs()); + v.extend(crate::fill_material_cmds::specs()); v.extend(crate::fill_reset_cmds::specs()); v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); @@ -124,6 +125,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::view_cmds::specs()); v.extend(crate::solo::specs()); v.extend(crate::camera_cmds::specs()); + v.extend(crate::swatch_cmds::specs()); v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); diff --git a/crates/engine/src/fill_alpha.rs b/crates/engine/src/fill_alpha.rs new file mode 100644 index 00000000..3ce4f6af --- /dev/null +++ b/crates/engine/src/fill_alpha.rs @@ -0,0 +1,65 @@ +//! A library alpha as a fill source: the source picker's Alphas put the alpha's picture in the project as an image resource the channel reads + +use std::sync::Arc; + +use texturecraft_paint::alphas::{self, LibraryAlpha}; + +use crate::resource_cmds::decoded; +use crate::{EngineError, Result, Session}; + +/// Resource names of library alphas start with this, so the picker and the slot can tell them from imported images +const PREFIX: &str = "alpha_"; +/// Resource names of library alphas end with this: they are stored as PNG +const EXTENSION: &str = ".png"; +/// Samples per pixel side when the alpha is rendered, for smooth edges +const SUPERSAMPLING: usize = 2; + +/// The resource name a library alpha takes in a project +pub fn resource_name(alpha: &LibraryAlpha) -> String { + texturecraft_formats::sanitize_resource_name(&format!("{PREFIX}{}{EXTENSION}", alpha.id)) +} + +/// The library alpha resource `name` holds, if it is one (library ids are safe resource names already, so a name is matched without building one) +pub fn library_alpha_of(name: &str) -> Option<&'static LibraryAlpha> { + let id = name.strip_prefix(PREFIX)?.strip_suffix(EXTENSION)?; + alphas::library().iter().find(|alpha| alpha.id == id) +} + +impl Session { + /// Puts library alpha `alpha` in the project as an image resource unless it is there already, inside the caller's edit; returns its name + pub(crate) fn add_library_alpha(&mut self, alpha: &LibraryAlpha) -> Result { + let name = resource_name(alpha); + if self.doc.resources.contains_key(&name) { + return Ok(name); + } + + let bytes = png(alpha)?; + let image = texturecraft_formats::decode_image(&bytes).map_err(|error| EngineError::Other(format!("{name}: {error}")))?; + self.doc.resources.insert(name.clone(), Arc::new(bytes)); + self.images.insert(name.clone(), decoded(image)); + Ok(name) + } +} + +/// The alpha's picture as a 16-bit grayscale PNG at the library's base size +fn png(alpha: &LibraryAlpha) -> Result> { + let size = alphas::BASE; + let side = u32::try_from(size).map_err(|_| EngineError::Other("alpha size out of range".into()))?; + texturecraft_formats::mcmat::mesh_map_png(side, 1, &alpha.render(size, SUPERSAMPLING)) + .map_err(|error| EngineError::Other(format!("alpha {}: {error}", alpha.id))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_library_alpha_is_found_by_the_resource_name_it_takes() { + for alpha in alphas::library() { + let name = resource_name(alpha); + assert_eq!(name, format!("{PREFIX}{}{EXTENSION}", alpha.id), "the id is a safe resource name as it is"); + assert_eq!(library_alpha_of(&name).map(|found| &found.id), Some(&alpha.id)); + } + assert!(library_alpha_of("alpha_.png").is_none()); + } +} diff --git a/crates/engine/src/fill_material_cmds.rs b/crates/engine/src/fill_material_cmds.rs new file mode 100644 index 00000000..2248e9b3 --- /dev/null +++ b/crates/engine/src/fill_material_cmds.rs @@ -0,0 +1,154 @@ +//! A fill's whole material: set every channel of a fill layer or content fill effect from one built-in material at once + +use std::collections::BTreeMap; + +use serde_json::Value; +use texturecraft_core::{Channel, EffectKind, Fill, LayerKind, Project, Source}; + +use crate::commands::{CommandSpec, bad, has_layer, strp}; +use crate::layer_cmds::{FillTarget, fill_mut, fill_target}; +use crate::materials::{Builder, MATERIALS, SmartMaterial, build, find}; +use crate::{EngineError, Result, Session, cmd}; + +/// The command [`set_material`] runs as +const CMD: &str = "layer.fill.material"; + +pub fn specs() -> Vec { + vec![cmd!( + "layer.fill.material", + "Set fill material", + [], + None, + "{layer? | effect?: content fill effect id, material: built-in material id (not a smart material) | null (back to the channels' defaults)} — sets every channel the material writes, turns those channels on and the others off; the projection stays", + has_layer, + set_material + )] +} + +/// The built-in materials a fill can hold whole: the plain ones (smart materials are folders of layers) +pub fn whole_materials() -> impl Iterator { + MATERIALS.iter().filter(|material| !material.smart) +} + +fn set_material(s: &mut Session, p: &Value) -> Result { + let target = fill_target(s, p, CMD)?; + let material = material_param(p)?; + let set = target_set(s, target)?; + if holds(s, target, set, material)? { + return Ok(Value::Null); + } + + let Some(found) = material else { + s.edit("Clear fill material", |s| { + let edited = fill_mut(s, target)?; + edited.material = None; + match target { + // A fill effect changes a channel while it has a source: its channels stay on, at their defaults + FillTarget::Effect(_) => edited.sources.iter_mut().for_each(|(channel, source)| *source = Source::uniform_of(*channel)), + } + Ok(()) + })?; + return Ok(Value::Null); + }; + + s.edit(&format!("Set fill material {}", found.label), |s| { + let sources = material_sources(&mut s.doc.project, set, found)?; + let edited = fill_mut(s, target)?; + edited.sources = sources; + edited.material = Some(found.id.to_string()); + let written: Vec = edited.sources.keys().copied().collect(); + if let FillTarget::Layer(id) = target { + let layer = s.doc.project.layer_mut(id)?; + layer.channels.retain(|channel, _| written.contains(channel)); + for channel in written { + layer.channels.entry(channel).or_default(); + } + } + Ok(()) + })?; + Ok(Value::Null) +} + +/// The `material` param: a plain built-in material, or `None` for null +fn material_param(p: &Value) -> Result> { + match p.get("material") { + Some(Value::Null) => Ok(None), + Some(_) => { + let id = strp(p, "material").ok_or_else(|| bad(CMD, "`material` is a material id or null"))?; + let found = find(id).ok_or_else(|| bad(CMD, format!("unknown material `{id}`")))?; + if found.smart { + return Err(bad(CMD, format!("`{}` is a smart material (a folder of layers): add it from the shelf with material.apply", found.id))); + } + + Ok(Some(found)) + } + None => Err(bad(CMD, "`material` is required: a material id or null")), + } +} + +/// Whether the fill at `target` (in texture set `set`) already holds `material` whole (or, for `None`, no material and its channels' defaults), so setting it changes nothing +fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMaterial>) -> Result { + let (fill, layer_channels) = match target { + FillTarget::Layer(id) => { + let layer = s.doc.project.layer(id)?; + let LayerKind::Fill(fill) = &layer.kind else { return Err(bad(CMD, "not a fill layer")) }; + (fill, Some(&layer.channels)) + } + FillTarget::Effect(id) => match s.doc.project.effect(id).map(|(_, found)| &found.kind) { + Some(EffectKind::Material(fill)) => (fill, None), + _ => return Err(bad(CMD, "not a content fill effect")), + }, + }; + if fill.material.as_deref() != material.map(|found| found.id) { + return Ok(false); + } + + // A channel set on its own clears the material; one turned off or back on keeps it, so an effect (whose sources are its channels) compares them whole + Ok(match (material, layer_channels) { + (Some(_), Some(channels)) => channels.len() == fill.sources.len() && fill.sources.keys().all(|channel| channels.contains_key(channel)), + (Some(found), None) => fill.sources == material_sources(&mut s.doc.project.clone(), set, found)?, + (None, Some(_)) => fill.sources.is_empty(), + (None, None) => fill.sources.iter().all(|(channel, source)| *source == Source::uniform_of(*channel)), + }) +} + +/// The texture set the fill `target` paints in, whichever set is selected +fn target_set(s: &Session, target: FillTarget) -> Result { + let owner = match target { + FillTarget::Layer(id) => id, + }; + s.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0))) +} + +/// The sources `material` writes in texture set `set`: its fill's channels the set has (the built fill's ids are taken from `project`) +fn material_sources(project: &mut Project, set: usize, material: &SmartMaterial) -> Result> { + let channels = project.texture_set(set)?.channel_list(); + let fill = whole_fill(project, material, &channels)?; + Ok(fill.sources.into_iter().filter(|(channel, _)| channels.contains(channel)).collect()) +} + +/// The one unmasked fill a plain material is made of +fn whole_fill(project: &mut Project, material: &SmartMaterial, channels: &[Channel]) -> Result { + let layers = build(&mut Builder { p: project, channels: channels.to_vec() }, material.id)?; + match <[_; 1]>::try_from(layers) { + Ok([layer]) if layer.mask.is_none() => match layer.kind { + LayerKind::Fill(fill) => Ok(fill), + _ => Err(EngineError::Other(format!("material `{}` is not a fill", material.id))), + }, + _ => Err(EngineError::Other(format!("material `{}` is more than one fill", material.id))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_whole_material_is_one_unmasked_fill() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let channels = s.doc.project.texture_set(s.ts()).map(|set| set.channel_list()).unwrap_or_default(); + for material in whole_materials() { + assert!(whole_fill(&mut s.doc.project, material, &channels).is_ok(), "{}", material.id); + } + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index f1c82a32..3f16e843 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -47,6 +47,9 @@ fn fill_json(fill: &Fill) -> Value { if let Some(link) = &fill.link { out["link"] = json!(link); } + if let Some(material) = &fill.material { + out["material"] = json!(material); + } out } @@ -236,6 +239,7 @@ pub fn session(session: &Session) -> Value { "bakePreview": crate::bake_preview::preview_json(session), "camera": crate::view_cmds::camera_json(session), "display": session.doc.project.display, + "swatches": session.doc.project.swatches, "history": { "undo": session.undo_label(), "redo": session.redo_label(), "depth": session.history_labels().len() }, "memoryBytes": session.memory().total(), "pendingTiles": session.pending_tiles(), diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 86fd4a55..a490b39a 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -512,11 +512,18 @@ fn blending_set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Which fill `layer.fill.*` edits: a fill layer's (`layer`), a content fill effect's (`effect`) or a mask fill effect's (`effect`: one grayscale source, no channels or material) +#[derive(Clone, Copy)] +pub(crate) enum FillTarget { + Layer(LayerId), + Effect(LayerId), + Mask(LayerId), +} + pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { match u64p(p, "effect").map(LayerId) { - Some(e) => match s.doc.project.effect(e) { - Some((_, x)) if matches!(x.kind, EffectKind::Material(_)) => Ok(FillTarget::Effect(e)), - _ => Err(bad(cmd, format!("{} is not a content fill effect", e.0))), + Some(effect) => match s.doc.project.effect(effect).map(|(_, found)| &found.kind) { + Some(EffectKind::Material(_)) => Ok(FillTarget::Effect(effect)), }, None => Ok(FillTarget::Layer(content_param(s, cmd, p)?)), } @@ -544,6 +551,7 @@ pub(crate) fn placement_mut(s: &mut Session, target: FillTarget) -> Result<(&mut fn fill_set(session: &mut Session, params: &Value) -> Result { let target = fill_target(session, params, FILL_SET)?; + let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off @@ -557,10 +565,15 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { } let source = fill_source_from(session, params, (target, channel), normal_format)?; + // A library alpha that became the source joins the project's images + let library_alpha = match &source { + Some(Source::Image { name, .. }) => crate::fill_alpha::library_alpha_of(name).filter(|_| strp(params, "image").is_none()), + _ => None, + }; if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp { return Err(bad( FILL_SET, - "give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`", + "give `color`, `value`, `procedural`, `image`, `alpha`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`", )); } @@ -571,6 +584,9 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { // Changing only the normal format or gradient stops leaves the layer channel on or off let touches_channel = source.is_some() || enabled.is_some(); session.edit("Set fill", |session| { + if let Some(alpha) = library_alpha { + session.add_library_alpha(alpha)?; + } let fill = fill_mut(session, target)?; // `normalFormat` alone: the convention of the channel's image @@ -581,6 +597,11 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { } } + // A channel set on its own (its source or its gradient map): the sources are no longer one whole material + if source.is_some() || colors.is_some() || init_ramp { + fill.material = None; + } + let current = fill.sources.get(&channel); let colors = if init_ramp { initial_ramp(channel, source.as_ref(), current)? } else { colors }; let source = with_ramp(channel, current, source, colors)?; @@ -658,6 +679,11 @@ fn fill_source_from( return Ok(Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() })); } + if let Some(name) = strp(params, "alpha") { + let alpha = alphas::find(name).ok_or_else(|| bad(FILL_SET, format!("unknown alpha `{name}`")))?; + return Ok(Some(Source::Image { name: crate::fill_alpha::resource_name(alpha), normal_format: normal_format.unwrap_or_default() })); + } + if let Some(anchor) = u64p(params, "anchor") { let reader = match target { FillTarget::Layer(id) => Some(id), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4d25b237..a8173320 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,7 +17,9 @@ pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; +pub mod fill_alpha; pub mod fill_hit_test; +pub mod fill_material_cmds; pub mod fill_mode; pub mod fill_reset_cmds; pub mod filter_lib; @@ -66,6 +68,7 @@ mod session_log; pub mod set_cmds; pub mod smart_masks; mod solo; +pub mod swatch_cmds; pub mod template_cmds; pub mod text_cmds; pub mod thumbs; diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 5931761e..8a1c2f77 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -46,11 +46,16 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, if let LayerKind::Fill(fill) = &layer.kind { out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string)); - out.extend(fill.link.as_ref().map(|link| link.package.clone())); + if let Some(link) = &fill.link { + out.push(link.package.clone()); + out.extend(link.outputs.values().cloned()); + } } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.kind.images_read().map(str::to_string)); } + for child in layer.children() { images_used(project, *child, out, depth + 1); } diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 5b8c1c7d..287c7cc8 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -787,6 +787,7 @@ pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f3 id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None }), + LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None, material: None }), &channels, ) } @@ -814,35 +815,44 @@ pub fn apply(s: &mut Session, id: &str) -> Result { /// [`apply`] at `place` (one undo step). pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { - let m = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?; - let label = format!("Add {}", m.label); + let material = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?; + let label = format!("Add {}", material.label); s.edit(&label, |s| { let ts = s.ts(); let mut channels = s.doc.project.texture_set(ts)?.channel_list(); // Lobe channels the material uses join the texture set (other channels it lacks are skipped) - let missing: Vec = Channel::LOBES.into_iter().filter(|c| !channels.contains(c)).collect(); - let layers = build(&mut Builder { p: &mut s.doc.project, channels: [channels.clone(), missing.clone()].concat() }, m.id)?; - for c in missing.into_iter().filter(|c| layers.iter().any(|l| l.channels.contains_key(c))) { - crate::set_cmds::add_channel(s, ts, c)?; - channels.push(c); + let missing: Vec = Channel::LOBES.into_iter().filter(|channel| !channels.contains(channel)).collect(); + let layers = build(&mut Builder { p: &mut s.doc.project, channels: [channels.clone(), missing.clone()].concat() }, material.id)?; + for channel in missing.into_iter().filter(|channel| layers.iter().any(|layer| layer.channels.contains_key(channel))) { + crate::set_cmds::add_channel(s, ts, channel)?; + channels.push(channel); } + let top = if layers.len() == 1 { - let l = layers.into_iter().next().ok_or_else(|| EngineError::Other("empty material".into()))?; - crate::layer_cmds::insert_selected(s, l)? + let mut layer = layers.into_iter().next().ok_or_else(|| EngineError::Other("empty material".into()))?; + + // A plain material's fill remembers it, so its Material side names it + if !material.smart + && let LayerKind::Fill(fill) = &mut layer.kind + { + fill.material = Some(material.id.to_string()); + } + + crate::layer_cmds::insert_selected(s, layer)? } else { - let gid = s.doc.project.alloc_id(); - let mut group = Layer::new(gid, m.label, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); - for c in group.channels.values_mut() { - *c = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; + let folder_id = s.doc.project.alloc_id(); + for blend in folder.channels.values_mut() { + *blend = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; } - let gid = crate::layer_cmds::insert_selected(s, group)?; - for l in layers { - s.doc.project.insert_layer(ts, l, Some(gid), true)?; + let folder_id = crate::layer_cmds::insert_selected(s, folder)?; + for layer in layers { + s.doc.project.insert_layer(ts, layer, Some(folder_id), true)?; } - s.select_one(ts, gid); - gid + s.select_one(ts, folder_id); + folder_id }; + place.apply(s, top)?; Ok(top) }) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 62010b50..42909bd9 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -665,6 +665,14 @@ impl Session { /// Material 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 picked = self.color_at(screen, viewport)?; + self.tool.values.extend(&picked); + self.tool.material = None; + Ok(picked) + } + + /// The composited value of every channel on the surface under `screen`, changing nothing (an eyedropper's read) + pub fn color_at(&self, screen: Vec2, viewport: Vec2) -> Result> { let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; let texture_set = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); let cache = self.caches.get(texture_set).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; @@ -674,10 +682,7 @@ impl Session { let tile = (x / texturecraft_texel::TILE, y / texturecraft_texel::TILE); let source = self.document_composite(texture_set, &[tile]).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; - let picked: BTreeMap<_, _> = source.channels.keys().map(|&channel| (channel, source.value(channel, x, y))).collect(); - self.tool.values.extend(&picked); - self.tool.material = None; - Ok(picked) + Ok(source.channels.keys().map(|&channel| (channel, source.value(channel, x, y))).collect()) } /// The stroke canvas alpha of the active stroke (for overlays and tests). diff --git a/crates/engine/src/swatch_cmds.rs b/crates/engine/src/swatch_cmds.rs new file mode 100644 index 00000000..2237f7db --- /dev/null +++ b/crates/engine/src/swatch_cmds.rs @@ -0,0 +1,48 @@ +//! The project's colour swatches: the row under the colour picker, saved with the project + +use serde_json::{Value, json}; +use texturecraft_core::MAX_SWATCHES; + +use crate::commands::{CommandSpec, always, bad, color_param, u64p}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!("swatch.list", "Swatches", [], None, "{}", always, |s, _| Ok(list(s))), + cmd!("swatch.add", "Add swatch", [], None, "{color: [r, g, b] (linear 0..1) | \"#rrggbb\"}", always, add), + cmd!("swatch.remove", "Remove swatch", [], None, "{index}", has_swatches, remove), + ] +} + +fn has_swatches(s: &Session) -> std::result::Result<(), String> { + if s.doc.project.swatches.is_empty() { Err("the project has no swatches".into()) } else { Ok(()) } +} + +fn list(s: &Session) -> Value { + json!({ "swatches": s.doc.project.swatches }) +} + +/// Adds `color` (clamped to 0..1) after the project's last swatch +fn add(s: &mut Session, p: &Value) -> Result { + let color = color_param("swatch.add", p, "color")?.ok_or_else(|| bad("swatch.add", "`color` is required: [r, g, b] or \"#rrggbb\""))?; + if s.doc.project.swatches.len() >= MAX_SWATCHES { + return Err(bad("swatch.add", format!("a project keeps at most {MAX_SWATCHES} swatches; remove one first"))); + } + + let color = color.map(|part| part.clamp(0.0, 1.0)); + s.edit("Add swatch", |s| { + s.doc.project.swatches.push(color); + Ok(json!({ "index": s.doc.project.swatches.len() - 1, "color": color })) + }) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let index = u64p(p, "index") + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < s.doc.project.swatches.len()) + .ok_or_else(|| bad("swatch.remove", "`index` must name a swatch (see swatch.list)"))?; + s.edit("Remove swatch", |s| { + let color = s.doc.project.swatches.remove(index); + Ok(json!({ "removed": color })) + }) +} diff --git a/crates/engine/tests/it/fill_alpha_source.rs b/crates/engine/tests/it/fill_alpha_source.rs new file mode 100644 index 00000000..6c3e7dd3 --- /dev/null +++ b/crates/engine/tests/it/fill_alpha_source.rs @@ -0,0 +1,66 @@ +//! A library alpha as a fill channel's source through `layer.fill.set {alpha}`: its picture becomes one image resource the channel reads + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; +use texturecraft_engine::fill_alpha::{library_alpha_of, resource_name}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::paint::alphas; +use texturecraft_engine::{Session, execute}; + +fn fill() -> (Session, LayerId) { + let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + (session, layer) +} + +fn source(session: &Session, layer: LayerId, channel: Channel) -> Source { + match &session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.source(channel), + other => panic!("not a fill: {other:?}"), + } +} + +#[test] +fn an_alpha_becomes_the_channels_image_once_and_its_set_is_one_undo_step() { + let (mut session, layer) = fill(); + let scratches = alphas::find("scratches").unwrap(); + let name = resource_name(scratches); + let set = |session: &mut Session, channel: &str, alpha: &str| { + execute(session, "layer.fill.set", &json!({"layer": layer.0, "channel": channel, "alpha": alpha})).unwrap(); + }; + set(&mut session, "roughness", "Scratches"); + + assert_eq!(source(&session, layer, Channel::Roughness), Source::image(name.clone())); + assert!(session.doc.resources.contains_key(&name), "the alpha's picture is a project resource, so the project saves it"); + let image = session.images.get(&name).expect("the channel's image is decoded"); + assert_eq!((image.width, image.height), (alphas::BASE as u32, alphas::BASE as u32)); + assert_eq!(library_alpha_of(&name).map(|alpha| alpha.id.as_str()), Some("scratches"), "the slot can name the alpha it came from"); + assert!(library_alpha_of("scratches.png").is_none(), "an imported image is not a library alpha"); + + // One undo takes the source and the resource back together + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(source(&session, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness)); + assert!(!session.doc.resources.contains_key(&name), "undo takes the resource back with the source"); + + // The same alpha on a second channel reads the same resource + set(&mut session, "roughness", "Scratches"); + let count = session.doc.resources.len(); + set(&mut session, "metallic", "scratches"); + + assert_eq!(source(&session, layer, Channel::Metallic), Source::image(name.clone())); + assert_eq!(session.doc.resources.len(), count); +} + +#[test] +fn an_unknown_alpha_changes_nothing() { + let (mut session, layer) = fill(); + let before = session.doc.resources.len(); + assert!(execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "alpha": "no such alpha"})).is_err()); + + assert_eq!(source(&session, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness)); + assert_eq!(session.doc.resources.len(), before); + + // No undo step either: the next undo takes back the added layer + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(session.doc.project.layer(layer).is_err(), "the refused set added no undo step"); +} diff --git a/crates/engine/tests/it/fill_whole_material.rs b/crates/engine/tests/it/fill_whole_material.rs new file mode 100644 index 00000000..b444a3fb --- /dev/null +++ b/crates/engine/tests/it/fill_whole_material.rs @@ -0,0 +1,155 @@ +//! A fill holding one whole built-in material: set, saved, cleared back to its channels' defaults, on a fill layer or a content fill effect + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, LayerKind, Source}; +use texturecraft_engine::{Session, execute, geom::primitives}; + +fn session() -> Session { + Session::new_project("Whole material", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +fn layer(v: Value) -> u64 { + v["layer"].as_u64().unwrap() +} + +fn fill(s: &Session, id: u64) -> texturecraft_engine::core::Fill { + match &s.doc.project.layer(LayerId(id)).unwrap().kind { + LayerKind::Fill(fill) => fill.clone(), + _ => panic!("not a fill"), + } +} + +fn channels(s: &Session, id: u64) -> Vec { + s.doc.project.layer(LayerId(id)).unwrap().channels.keys().copied().collect() +} + +#[test] +fn a_fill_takes_one_whole_material_names_it_and_forgets_it_once_a_channel_is_set_alone() { + let mut s = session(); + let id = layer(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap()); + execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "opacity", "value": 0.5})).unwrap(); + let projection = fill(&s, id).projection; + let saved: Value = serde_json::to_value(fill(&s, id)).unwrap(); + assert!(saved.get("material").is_none(), "a fill without a whole material saves as before"); + + execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "copper_hammered"})).unwrap(); + let copper = fill(&s, id); + assert_eq!(copper.material.as_deref(), Some("copper_hammered")); + assert!(matches!(copper.source(Channel::BaseColor), Source::Procedural { .. }), "the material's base colour"); + assert_eq!(copper.source(Channel::Metallic), Source::Uniform([1.0; 3])); + assert_eq!(channels(&s, id), [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height], "the material's channels on, opacity off"); + assert_eq!(copper.projection, projection, "the fill keeps its projection"); + assert_eq!(execute(&mut s, "project.inspect", &json!({})).unwrap().to_string().matches("\"material\":\"copper_hammered\"").count(), 1); + + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(fill(&reopened, id).material.as_deref(), Some("copper_hammered"), "saved with the project"); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(fill(&s, id).material, None, "one undo step"); + assert_eq!(fill(&s, id).source(Channel::BaseColor), Source::Uniform([1.0, 0.0, 0.0])); + execute(&mut s, "edit.redo", &json!({})).unwrap(); + + execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "metallic", "enabled": false})).unwrap(); + assert!(fill(&s, id).material.is_some(), "turning a channel off keeps the material"); + execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "roughness", "value": 0.3})).unwrap(); + assert_eq!(fill(&s, id).material, None, "a channel set on its own is no longer the whole material"); + + execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "Steel"})).unwrap(); + execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": null})).unwrap(); + let cleared = fill(&s, id); + assert_eq!((cleared.material, cleared.sources.len()), (None, 0), "null: back to the channels' defaults"); + + // A content fill effect takes the material too + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "layer.fill.material", &json!({"effect": effect, "material": "gold_polished"})).unwrap(); + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("\"material\":\"gold_polished\"")); + + // The shelf names a plain material's fill; a smart one is no whole material + let shelf = layer(execute(&mut s, "material.apply", &json!({"material": "brass"})).unwrap()); + assert_eq!(fill(&s, shelf).material.as_deref(), Some("brass")); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "steel_painted_worn"})).is_err(), "smart"); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "nope"})).is_err()); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id})).is_err(), "material is required"); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": 7})).is_err()); +} + +#[test] +fn a_fill_in_another_texture_set_takes_the_channels_of_its_own_set() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + let other = layer(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()); + s.doc.project.texture_sets[1].channels.retain(|(channel, _)| *channel != Channel::Metallic); + execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap(); + + execute(&mut s, "layer.fill.material", &json!({"layer": other, "material": "copper_hammered"})).unwrap(); + + assert!(!channels(&s, other).contains(&Channel::Metallic), "set 1 has no metallic channel: {:?}", channels(&s, other)); + assert!(channels(&s, other).contains(&Channel::BaseColor)); +} + +/// The fill of content fill effect `effect` +fn effect_fill(s: &Session, effect: u64) -> texturecraft_engine::core::Fill { + match &s.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Material(fill) => fill.clone(), + other => panic!("not a content fill: {other:?}"), + } +} + +#[test] +fn clearing_a_content_fill_effects_material_lays_its_channels_defaults() { + let mut s = crate::filter_support::facing_session(); + execute(&mut s, "layer.add.fill", &json!({"roughness": 0.2})).unwrap(); + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "layer.fill.material", &json!({"effect": effect, "material": "gold_polished"})).unwrap(); + let material_channels: Vec = effect_fill(&s, effect).sources.keys().copied().collect(); + + execute(&mut s, "layer.fill.material", &json!({"effect": effect, "material": null})).unwrap(); + + let cleared = effect_fill(&s, effect); + assert_eq!(cleared.material, None); + assert_eq!(cleared.sources.keys().copied().collect::>(), material_channels, "the material's channels stay on"); + assert!(cleared.sources.iter().all(|(channel, source)| *source == Source::uniform_of(*channel)), "at their defaults"); + let roughness = crate::filter_support::center(&mut s, Channel::Roughness)[0]; + assert!((roughness - Channel::Roughness.default_value()[0]).abs() < 0.01, "the effect still lays the default roughness: {roughness}"); +} + +#[test] +fn setting_the_material_a_fill_already_holds_adds_no_undo_step() { + let mut s = session(); + let id = layer(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()); + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + let steps = s.history_labels().len(); + + for target in [json!({"layer": id}), json!({"effect": effect})] { + for material in [json!("gold_polished"), Value::Null] { + let mut params = target.clone(); + params["material"] = material; + execute(&mut s, "layer.fill.material", ¶ms).unwrap(); + execute(&mut s, "layer.fill.material", ¶ms).unwrap(); + } + } + + assert_eq!(s.history_labels().len(), steps + 4, "one step per change, none for a repeat"); +} + +#[test] +fn setting_the_material_again_brings_back_a_content_fill_effects_channel_turned_off() { + let mut s = session(); + layer(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()); + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + let gold = json!({"effect": effect, "material": "gold_polished"}); + execute(&mut s, "layer.fill.material", &gold).unwrap(); + let whole = effect_fill(&s, effect).sources; + + for off_and_on in [vec![false], vec![false, true]] { + for enabled in off_and_on { + execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "roughness", "enabled": enabled})).unwrap(); + } + assert_ne!(effect_fill(&s, effect).sources, whole, "roughness is off or back at its default"); + + execute(&mut s, "layer.fill.material", &gold).unwrap(); + + assert_eq!(effect_fill(&s, effect).sources, whole, "the material's roughness is back"); + } +} diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs new file mode 100644 index 00000000..eb585ba3 --- /dev/null +++ b/crates/engine/tests/it/filter_support.rs @@ -0,0 +1,44 @@ +//! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite + +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; + +/// The texture set side the filter tests paint on +pub(crate) const SIZE: u32 = 128; + +/// The viewport's side in pixels when a test reads the texel under its center +const VIEWPORT_SIDE: f32 = 400.0; + +/// A sphere on a `SIZE` texture set, rendered once +pub(crate) fn session() -> Session { + let mut s = sized_session(SIZE); + s.update(); + s +} + +/// A sphere on a texture set of side `size`, not yet rendered +pub(crate) fn sized_session(size: u32) -> Session { + Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, size).unwrap() +} + +/// A session whose camera looks straight at the sphere, so the viewport center reads one texel (see [`center`]) +pub(crate) fn facing_session() -> Session { + let mut s = session(); + s.viewport = Vec2::splat(VIEWPORT_SIDE); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// The UV under the viewport center +pub(crate) fn center_uv(s: &mut Session) -> Vec2 { + s.update(); + s.pick(Vec2::splat(VIEWPORT_SIDE / 2.0), s.viewport).unwrap().uv +} + +/// Composited value of `channel` under the viewport center +pub(crate) fn center(s: &mut Session, channel: Channel) -> [f32; 3] { + let uv = center_uv(s); + s.caches[0].composite.value(channel, (uv.x * SIZE as f32) as u32, (uv.y * SIZE as f32) as u32) +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11a5b7f0..bae8985c 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,9 +13,12 @@ mod content_effects; mod export_colour_space; mod export_file_types; mod export_maps; +mod fill_alpha_source; mod fill_patterns; mod fill_projections; mod fill_sampling; +mod fill_whole_material; +mod filter_support; mod filter_swap; mod filters; mod frame_selection; @@ -39,6 +42,7 @@ mod polygon_fill; mod project_recovery; mod sample; mod solo; +mod swatches; mod symmetry; mod thumbs; mod tile_generator; diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index ea361a89..d9052f04 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use texturecraft_engine::compose::BakedMaps; -use texturecraft_engine::core::{BakedMap, Channel, LayerId, LayerKind, NormalFormat, Source}; +use texturecraft_engine::core::{BakedMap, Channel, CookResolution, LayerId, LayerKind, NormalFormat, Source}; use texturecraft_engine::formats::mcmat::mesh_map_png; use texturecraft_engine::geom::primitives; use texturecraft_engine::link_cmds::{CookedMap, CookedMaterial, LinkMemoryBudget}; @@ -187,6 +187,88 @@ fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 1.0})); } +/// A channel can read another output of the material; the choice survives re-cooks, undo and saving, and links saved before it existed map their channels too +#[test] +fn channels_read_the_output_they_are_mapped_to() { + let mut s = session(); + let id = install(&mut s); + let map = |s: &mut Session, output: &str| execute(s, "material.link.map", &json!({"layer": id.0, "channel": "roughness", "output": output})); + assert!(map(&mut s, "curvature").is_err(), "outputs the material lacks are errors"); + assert!(execute(&mut s, "material.link.map", &json!({"layer": id.0, "output": "roughness"})).is_err()); + + // Roughness reads the ambient occlusion output (all white) + map(&mut s, "ambientOcclusion").unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3); + assert_eq!(link(&s, id).output_of(Channel::Roughness), "ambientOcclusion"); + let saved = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(link(&saved, id), link(&s, id)); + s.apply_link_cook(id, &cooked(0.75, 0.5), false).unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3, "a re-cook keeps the mapping"); + map(&mut s, "roughness").unwrap(); + assert!((roughness(&mut s) - 0.75).abs() < 2e-3); + assert!(link(&s, id).mapping.is_empty(), "a channel's own output is no mapping"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3); + + // A link saved before mappings (no outputs list) maps from its channels' maps + let mut old = session(); + let id = install(&mut old); + if let LayerKind::Fill(fill) = &mut old.doc.project.layer_mut(id).unwrap().kind { + let link = fill.link.as_mut().unwrap(); + link.outputs.clear(); + let saved = serde_json::to_value(&**link).unwrap(); + assert!(saved.get("outputs").is_none() && saved.get("mapping").is_none() && saved.get("resolution").is_none(), "{saved}"); + } + execute(&mut old, "material.link.map", &json!({"layer": id.0, "channel": "roughness", "output": "ambientOcclusion"})).unwrap(); + assert!((roughness(&mut old) - 1.0).abs() < 2e-3); + assert!(link(&old, id).outputs.contains_key("roughness"), "the unmapped output stays listed"); + let kept = old.doc.resources.len(); + execute(&mut old, "file.removeUnused", &Value::Null).unwrap(); + assert_eq!(old.doc.resources.len(), kept, "outputs no channel reads are kept"); +} + +/// The cook size: relative sizes follow the texture set, a fixed size is stored and cooked at +#[test] +fn materials_cook_at_their_picked_resolution() { + let mut s = session(); + let id = install(&mut s); + let size = |s: &Session| s.link_job(id, &serde_json::Map::new()).unwrap().size; + let pick = |s: &mut Session, mut size: Value| { + size["layer"] = json!(id.0); + size["cook"] = json!(false); + execute(s, "material.link.resolution", &size) + }; + assert_eq!(size(&s), 128); + pick(&mut s, json!({"fixed": 1024})).unwrap(); + assert_eq!((link(&s, id).resolution, size(&s)), (Some(CookResolution::Fixed(1024)), 1024)); + pick(&mut s, json!({"relative": 2})).unwrap(); + assert_eq!(size(&s), 512); + let steps = s.history_labels().len(); + pick(&mut s, json!({"relative": 2})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "the size it already has adds no step"); + for bad in [ + json!({"fixed": 300}), + json!({"fixed": 64}), + json!({"fixed": 16384}), + json!({"relative": 4}), + json!({"relative": "x"}), + json!({}), + json!({"relative": 1, "fixed": 256}), + ] { + assert!(pick(&mut s, bad.clone()).is_err(), "{bad}"); + } + pick(&mut s, json!({"relative": 0})).unwrap(); + assert_eq!((link(&s, id).resolution, size(&s)), (None, 128)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&s), 512); + + // A hostile project's size falls back to the texture set's + if let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(id).unwrap().kind { + fill.link.as_mut().unwrap().resolution = Some(CookResolution::Fixed(u32::MAX)); + } + assert_eq!(size(&s), 128); +} + #[test] fn duplicates_keep_their_maps_and_mesh_maps_feed_inputs() { let mut session = session(); diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 26fcb753..6c4be47f 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -80,44 +80,33 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); - assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); - execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it + // A gradient map recolors the content; effect.set edits it and inspect shows it. let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); - execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); - assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); - let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); - assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); - execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped + // Posterize on the mask; its steps are clamped. let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); - assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0)); - - // Material finishes fill the content's roughness and height + // Material finishes fill the content's roughness and height. let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); - assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - - // A directional blur, slope blur and warp composite without trouble on a sphere + // A directional blur, slope blur and warp composite without trouble on a sphere. for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"radius": 30})), @@ -133,7 +122,6 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); execute(&mut s, "effect.add.filter", &p).unwrap(); } - assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite())); } diff --git a/crates/engine/tests/it/swatches.rs b/crates/engine/tests/it/swatches.rs new file mode 100644 index 00000000..6e6b026a --- /dev/null +++ b/crates/engine/tests/it/swatches.rs @@ -0,0 +1,36 @@ +use serde_json::json; +use texturecraft_engine::{Session, execute, geom::primitives}; + +fn session() -> Session { + Session::new_project("Swatches", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +#[test] +fn swatches_are_added_saved_with_the_project_removed_and_undone() { + let mut s = session(); + let plain = s.to_project_bytes().unwrap(); + let saved: serde_json::Value = serde_json::to_value(&s.doc.project).unwrap(); + assert!(saved.get("swatches").is_none(), "a project without swatches saves as before"); + + execute(&mut s, "swatch.add", &json!({"color": [0.8, 0.25, 0.07]})).unwrap(); + let added = execute(&mut s, "swatch.add", &json!({"color": [2.0, -1.0, 0.5]})).unwrap(); + assert_eq!(added["index"], 1); + assert_eq!(s.doc.project.swatches, vec![[0.8, 0.25, 0.07], [1.0, 0.0, 0.5]], "kept in order, clamped to 0..1"); + assert_eq!(execute(&mut s, "project.inspect", &json!({})).unwrap()["swatches"][1], json!([1.0, 0.0, 0.5])); + + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.swatches, s.doc.project.swatches, "saved per project"); + assert!(Session::from_project_bytes(&plain).unwrap().doc.project.swatches.is_empty()); + + execute(&mut s, "swatch.remove", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc.project.swatches, vec![[1.0, 0.0, 0.5]]); + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc.project.swatches.len(), 2, "a removal is one undo step"); + + assert!(execute(&mut s, "swatch.add", &json!({})).is_err(), "a colour is required"); + assert!(execute(&mut s, "swatch.remove", &json!({"index": 2})).is_err(), "no such swatch"); + while s.doc.project.swatches.len() < texturecraft_core::MAX_SWATCHES { + execute(&mut s, "swatch.add", &json!({"color": "#336699"})).unwrap(); + } + assert!(execute(&mut s, "swatch.add", &json!({"color": "#336699"})).is_err(), "the list is capped"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index f776f46a..36b45d1f 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, command_specs, execute}; @@ -183,6 +184,24 @@ fn polygon_fill_and_color_picker() { assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}"); } +#[test] +fn color_at_reads_the_surface_without_changing_the_brush() { + let mut s = session(); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.polygonFill", &Value::Null).unwrap(); + execute(&mut s, "tool.fillMode", &json!({"mode": "mesh"})).unwrap(); + execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).unwrap(); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.2})).unwrap(); + let viewport = s.viewport; + + let read = s.color_at(Vec2::new(200.0, 200.0), viewport).unwrap(); + + let surface = read.get(&Channel::Roughness).unwrap(); + assert!((surface[0] - 0.9).abs() < 0.01, "{surface:?}"); + let brush = s.tool.values.get(&Channel::Roughness).unwrap(); + assert!((brush[0] - 0.2).abs() < 0.01, "the brush keeps its own value: {brush:?}"); +} + #[test] fn polygon_fill_boxes_survive_hostile_params() { let hostile = [ @@ -247,6 +266,56 @@ fn panic_hunt() { } } +/// A 4 × 4 gray PNG, the image the hunted decals project +fn gray_png() -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +#[test] +fn panic_hunt_frames_and_transforms() { + let mut s = session(); + let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); + let planar = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "layer.fill.projection", &json!({"layer": planar, "projection": "planar"})).unwrap(); + let warp = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "layer.fill.projection", &json!({"layer": warp, "projection": "warp"})).unwrap(); + let decal = execute(&mut s, "layer.add.decal", &json!({"image": image, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap(); + let mask_effect = decal["maskEffect"].as_u64().unwrap(); + s.update(); + + let hostile_values = + [json!(1e30), json!(-1e30), json!(0), json!(null), json!("x"), json!([]), json!([1e30, -1e30]), json!([0, 0, 0]), json!([-1e30, 1e30, 0, 5])]; + let targets = [json!({"layer": planar}), json!({"layer": warp}), json!({"effect": mask_effect})]; + let keys = ["frameOffset", "frameRotation", "frameScale", "size", "offset", "depth", "rotation", "up"]; + for target in &targets { + for key in keys { + for value in &hostile_values { + let mut params = target.clone(); + params[key] = value.clone(); + hunt_refused_changes_nothing(&mut s, "layer.decal.set", ¶ms); + } + } + } + + for target in &targets { + for command in ["layer.fill.resetFrame", "layer.fill.resetProjection"] { + let _ = execute(&mut s, command, target); + s.update(); + } + } +} + +/// Run `command` with `params` and render; refused, it must leave the project and the undo history as they were +fn hunt_refused_changes_nothing(s: &mut Session, command: &str, params: &Value) { + let (before, steps) = (s.doc.project.clone(), s.history_labels().len()); + if execute(s, command, params).is_err() { + assert!(s.doc.project == before && s.history_labels().len() == steps, "a refused {command} {params} changes nothing"); + } + s.update(); +} + /// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ /// between the two, so every command that takes a colour says which form is which. #[test] @@ -872,3 +941,19 @@ fn blending_set_gives_each_channel_its_own_mode_and_opacity_in_one_undo_step() { execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"baseColor": {"opacity": 2.0}, "roughness": {"opacity": -1.0}}})).unwrap(); assert_eq!((read(&s)[&Channel::BaseColor].opacity, read(&s)[&Channel::Roughness].opacity), (1.0, 0.0), "opacity is clamped"); } + +#[test] +fn a_new_session_forgets_the_projector_depth_maps_built_before_it() { + use texturecraft_engine::compose::projector_depth::ProjectorDepth; + use texturecraft_engine::core::{Projection, Projector, UvTransform}; + + let mesh = primitives::sphere(1.0, 16, 8); + let projection = + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None }; + let built = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); + + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + + let after = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); + assert!(!std::sync::Arc::ptr_eq(&built, &after), "a mesh sharing the old one's fingerprint must not take its map"); +} diff --git a/crates/paint/src/pickup.rs b/crates/paint/src/pickup.rs index 6d61b073..b0161e4b 100644 --- a/crates/paint/src/pickup.rs +++ b/crates/paint/src/pickup.rs @@ -371,6 +371,7 @@ mod tests { projection: Default::default(), sampling: Default::default(), link: None, + material: None, }; let mut layer = Layer::new(id, "fill", LayerKind::Fill(fill), &[Channel::Roughness]); layer.mask = Some(Mask::new(MaskBackground::White)); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index dd2a06d3..fe8fd68d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -15,7 +15,6 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; -use crate::filter_slot::SLOT_HEIGHT; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::past_end::PastEnd; @@ -24,7 +23,7 @@ use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, section_with_reset, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; /// 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"; @@ -133,6 +132,12 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { // --------------------------------------------------------------------------------------------- // Layers +/// Gap between the layer toolbar and the layer rows +const LAYER_TOOLBAR_GAP: f32 = 2.0; + +/// Least height of the drop space under the layer rows, so a drop to the bottom always has a target +const BOTTOM_DROP_MIN_HEIGHT: f32 = 24.0; + /// The add-mask commands, for the selected layer or (`row`) the layer whose mask slot was clicked. fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { let enabled = row.is_some() || app.session.selected_layer().is_some(); @@ -149,12 +154,6 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { } } -/// Gap between the layer toolbar and the layer rows -const LAYER_TOOLBAR_GAP: f32 = 2.0; - -/// Least height of the drop space under the layer rows, so a drop to the bottom always has a target -const BOTTOM_DROP_MIN_HEIGHT: f32 = 24.0; - pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); @@ -1923,6 +1922,7 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: /// The tabs over the panel when it shows a fill layer's sections, which they jump between pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 2]> { +pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 3]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } @@ -1932,6 +1932,7 @@ pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static s StackTarget::Content => { let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(crate::fill_panel::fill_tabs) + matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false)) } _ => None, } @@ -2070,6 +2071,8 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { 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(PREVIEW_STROKE_MIN_ALPHA))))); let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + + // The sphere sits in the middle of the preview's right half crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); ui.add_space(BRUSH_PREVIEW_GAP); @@ -2649,6 +2652,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { /// Space between the tool's channel chips and the first channel value const CHIPS_GAP: f32 = 4.0; +/// Room right of the tool's colour swatch, like a linked material's +const TOOL_SWATCH_RIGHT_MARGIN: f32 = LINK_SWATCH_RIGHT_MARGIN; + /// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. /// The Material tab and the Smudge panel both draw these, so they share one set of flags. fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { @@ -2691,7 +2697,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { ChannelKind::Color => { ui.horizontal(|ui| { ui.label(tr(channel.label())); - if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) { + if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - TOOL_SWATCH_RIGHT_MARGIN) { app.session.tool.values.insert(channel, value); app.session.tool.material = None; } @@ -2725,133 +2731,66 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let on: Vec = layer.channels.keys().copied().collect(); PropertySheet::show(ui, ("fill_sheet", layer.id.0), |sheet| { crate::fill_panel::placement_sections(app, sheet, fill, &json!({"layer": layer.id.0}), layer.id); - }); - legacy_body(ui, |ui| { - if let Some(link) = &fill.link { - link_properties(app, ui, layer.id, link); - ui.add_space(6.0); - } - fill_editor(app, ui, fill, &json!({"layer": layer.id.0}), &on, layer.id); + crate::fill_panel::fill_sheet(app, sheet, fill, &json!({"layer": layer.id.0}), &on, layer.id); }); } -/// A MaterialCraft material's presets and exposed inputs; edits store the value and re-cook the -/// maps on a worker thread (desktop only: cooking runs MaterialCraft's command line). -fn link_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, link: &MaterialLink) { - let tk = Tokens::get(ui.ctx()); - let base = json!({"layer": layer.0, "cook": false}); - ui.label(caption(tr("MaterialCraft material"))); - ui.horizontal(|ui| { - ui.label(RichText::new(&link.name).strong()); - ui.label(RichText::new(trf("Cooked at {size} px", &[("size", &link.size)])).size(10.0).color(tk.text_dim)); - if app.link_cooks.iter().any(|c| c.layer == layer) { - ui.spinner(); - } - }); - let editable = cfg!(not(target_arch = "wasm32")); - ui.add_enabled_ui(editable, |ui| { - if !link.presets.is_empty() { - combo(ui, tr("Preset"), "", |ui| { - for p in &link.presets { - if ui.selectable_label(false, &p.name).clicked() && app.run("material.link.preset", with(&base, json!({"name": p.name}))).is_some() { - app.cook_link(layer); - } - } - }); - } - let mut group = ""; - for p in &link.params { - if p.group != group && !p.group.is_empty() { - ui.label(RichText::new(p.group.to_uppercase()).size(10.0).strong().color(tk.text_dim)); - } - group = &p.group; - if let Some(v) = link_param_editor(ui, layer, p) - && app.run("material.link.set", with(&base, json!({"id": p.id, "value": v}))).is_some() - { - app.cook_link(layer); - } - } - }); - if !editable { - ui.label(RichText::new(tr("Parameters change in the desktop app, with MaterialCraft installed")).size(10.0).color(tk.text_dim)); +/// Writes the material's package to a temporary file and opens it in MaterialCraft +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn open_link_in_materialcraft(app: &mut TextureCraftApp, layer: LayerId, link: &texturecraft_engine::core::MaterialLink) { + let ext = texturecraft_engine::link_cmds::source_extension(&link.package); + let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let opened = app + .session + .link_package(layer) + .and_then(|package| std::fs::write(&path, package.as_slice()).map_err(|err| texturecraft_engine::EngineError::Other(err.to_string()))) + .and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); + match opened { + Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false), + Err(e) => app.toast(e.to_string(), true), } - #[cfg(not(target_arch = "wasm32"))] - ui.horizontal(|ui| { - if ui.button(tr("Re-cook")).clicked() { - app.cook_link(layer); - } - if ui.button(tr("Open in MaterialCraft")).clicked() { - let ext = texturecraft_engine::link_cmds::source_extension(&link.package); - let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); - let opened = app - .session - .link_package(layer) - .and_then(|b| std::fs::write(&path, b.as_slice()).map_err(|e| texturecraft_engine::EngineError::Other(e.to_string()))) - .and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); - match opened { - Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false), - Err(e) => app.toast(e.to_string(), true), - } - } - }); } -/// The editor of one linked-material input; returns its new value when an edit completes. -fn link_param_editor(ui: &mut Ui, layer: LayerId, p: &LinkParam) -> Option { - let t = p.default.get("t").and_then(Value::as_str).unwrap_or(""); - let v = p.value.get("v").unwrap_or(&Value::Null); - let num = |x: &Value| x.as_f64().unwrap_or(0.0) as f32; - let (lo, hi) = if p.max > p.min { (p.min, p.max) } else { (0.0, 1.0) }; - // A slider edit completes when the drag ends, on a click or a typed value. - let edit = |ui: &mut Ui, label: &str, x: f32, decimals: usize| { - let mut y = x; - let r = slider(ui, label, &mut y, lo.min(x)..=hi.max(x), decimals); - (r.drag_stopped() || (!r.dragged() && y != x)).then_some(y) - }; - match t { - "bool" => { - let mut b = v.as_bool().unwrap_or(num(v) != 0.0); - ui.checkbox(&mut b, &p.label).changed().then(|| json!(b)) - } - "enum" if !p.options.is_empty() => { - let cur = num(v).max(0.0) as usize; - let mut pick = None; - combo(ui, &p.label, p.options.get(cur).map_or("", String::as_str), |ui| { - for (i, o) in p.options.iter().enumerate() { - if ui.selectable_label(i == cur, o).clicked() { - pick = Some(json!(i)); - } - } - }); - pick - } - "float" | "int" | "enum" => edit(ui, &p.label, num(v), if t == "float" { 2 } else { 0 }).map(|y| json!(y)), - "color" => { - let a = v.as_array().map(|a| a.iter().map(num).collect::>()).unwrap_or_default(); - let mut rgb = [0, 1, 2].map(|i| a.get(i).copied().unwrap_or(1.0)); - let mut out = None; - ui.horizontal(|ui| { - ui.label(&p.label); - if color_swatch(ui, &format!("link_{}_{}", layer.0, p.id), &mut rgb, ui.available_width() - 4.0) { - out = Some(json!([rgb[0], rgb[1], rgb[2], a.get(3).copied().unwrap_or(1.0)])); - } - }); - out - } - _ => { - // Vectors: one slider per component. - let mut a: Vec = v.as_array().map(|a| a.iter().map(num).collect()).unwrap_or_default(); - let decimals = if t == "int2" { 0 } else { 2 }; - let mut changed = false; - for (x, axis) in a.iter_mut().zip(["x", "y", "z", "w"]) { - if let Some(y) = edit(ui, &format!("{} {axis}", p.label), *x, decimals) { - *x = y; - changed = true; - } - } - changed.then(|| json!(a)) +/// Room the colour swatch of a linked-material input leaves at the row's right +const LINK_SWATCH_RIGHT_MARGIN: f32 = 4.0; + +/// The editor of a linked-material colour or vector input (the sheet draws the other kinds): the new value and whether it continues a colour drag +pub(crate) fn link_param_editor(ui: &mut Ui, layer: LayerId, param: &LinkParam) -> Option<(Value, bool)> { + let kind = param.default.get("t").and_then(Value::as_str).unwrap_or(""); + let value = param.value.get("v").unwrap_or(&Value::Null); + let number = |item: &Value| item.as_f64().unwrap_or(0.0) as f32; + let (low, high) = if param.max > param.min { (param.min, param.max) } else { (0.0, 1.0) }; + + if kind == "color" { + let components = value.as_array().map(|items| items.iter().map(number).collect::>()).unwrap_or_default(); + let mut rgb = [0, 1, 2].map(|index| components.get(index).copied().unwrap_or(1.0)); + let swatch_id = format!("link_{}_{}", layer.0, param.id); + let changed = ui + .horizontal(|ui| { + ui.label(¶m.label); + color_swatch(ui, &swatch_id, &mut rgb, ui.available_width() - LINK_SWATCH_RIGHT_MARGIN) + }) + .inner; + + // The picker changes the colour every frame of a drag: those frames share one undo step + let merge = press_edit(ui, ui.make_persistent_id((swatch_id.as_str(), "press")), changed)?; + return Some((json!([rgb[0], rgb[1], rgb[2], components.get(3).copied().unwrap_or(1.0)]), merge)); + } + + // Vectors: one slider per component; an edit applies when the drag ends, on a click or a typed value + let mut components: Vec = value.as_array().map(|items| items.iter().map(number).collect()).unwrap_or_default(); + let decimals = if kind == "int2" { 0 } else { 2 }; + let mut changed = false; + for (component, axis) in components.iter_mut().zip(["x", "y", "z", "w"]) { + let current = *component; + let response = slider(ui, &format!("{} {axis}", param.label), component, low.min(current)..=high.max(current), decimals); + if response.drag_stopped() || (!response.dragged() && *component != current) { + changed = true; + } else { + *component = current; } } + changed.then(|| (json!(components), false)) } /// `base` with the fields of `extra` added @@ -2864,8 +2803,7 @@ pub(crate) fn with(base: &Value, extra: Value) -> Value { } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). -pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { - let project = &app.session.doc.project; +pub(crate) fn anchors_below(project: &texturecraft_engine::core::Project, reader: LayerId) -> Vec<(LayerId, String)> { let Some((texture_set, _, _)) = project.locate(reader) else { return Vec::new() }; project .walk(texture_set) @@ -2892,13 +2830,18 @@ pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(Laye /// Anchor choices for an effect, valid for its owner and recorded below the displayed instance pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> { - let owner = app.session.doc.project.effect(effect).map_or(layer, |(owner, _)| owner); - let owner_anchors = anchors_below(app, owner); + project_effect_anchors_below(&app.session.doc.project, layer, effect) +} + +/// [`effect_anchors_below`] in `project` +pub(crate) fn project_effect_anchors_below(project: &texturecraft_engine::core::Project, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> { + let owner = project.effect(effect).map_or(layer, |(owner, _)| owner); + let owner_anchors = anchors_below(project, owner); if owner == layer { return owner_anchors; } - let displayed_anchors = anchors_below(app, layer); + let displayed_anchors = anchors_below(project, layer); owner_anchors.into_iter().filter(|(id, _)| displayed_anchors.iter().any(|(displayed, _)| id == displayed)).collect() } @@ -3162,121 +3105,6 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option { picked } -/// Space a fill channel's color swatch leaves at the group's right edge -const CHANNEL_SWATCH_MARGIN: f32 = 4.0; -/// Width of a pattern's low and high swatches -const PATTERN_RANGE_SWATCH_WIDTH: f32 = 60.0; -/// Size of the gradient map menu icon beside the fill source slot -const FILL_CHANNEL_MENU_ICON_SIZE: f32 = 13.0; -const GRADIENT_MAP_HINT: &str = n_("Colors the procedural or anchor from dark to light through color stops"); - -/// The source slot, source settings and gradient map of one fill channel -fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, channel: Channel, anchors: &[(LayerId, String)], salt: &str) { - let tokens = Tokens::get(ui.ctx()); - let set = |extra: Value| with(base, with(&json!({"channel": channel.id()}), extra)); - let default_source = Source::uniform_of(channel); - let source = fill.sources.get(&channel).unwrap_or(&default_source); - let is_color = channel.kind() == ChannelKind::Color; - let group = ui.group(|ui| { - let slot = crate::fill_source_target::FillSourceTarget::Channel { base: base.clone(), channel }; - if is_color { - ui.allocate_ui_with_layout(vec2(ui.available_width(), SLOT_HEIGHT), egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(RichText::new(ic::DOTS_THREE).size(FILL_CHANNEL_MENU_ICON_SIZE), |ui| gradient_map_item(app, ui, source, &set)) - .response - .on_hover_text(tr(GRADIENT_MAP_HINT)); - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label()))); - }); - }); - } else { - crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label()))); - } - - match source { - Source::Uniform(value) if is_color => { - let mut value = *value; - if color_swatch(ui, &format!("fill_{salt}_{}", channel.id()), &mut value, ui.available_width() - CHANNEL_SWATCH_MARGIN) { - app.run("layer.fill.set", set(json!({"color": value}))); - } - } - Source::Uniform(value) => { - let mut value = value[0]; - let range = if channel.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 }; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, range, 2) { - app.run("layer.fill.set", set(json!({"value": value, "merge": merge}))); - } - } - Source::Procedural { pattern, low, high, ramp } => { - let target = crate::pattern_target::PatternTarget { - command: "layer.fill.set", - base: with(base, json!({"channel": channel.id(), "low": low, "high": high})), - salt: format!("{salt}_{}", channel.id()), - }; - crate::pattern_panel::pattern_properties(app, ui, &target, pattern); - if is_color && ramp.is_empty() { - let (mut low, mut high) = (*low, *high); - let mut changed = false; - ui.horizontal(|ui| { - ui.label(tr("Low")); - changed |= color_swatch(ui, &format!("lo_{salt}_{}", channel.id()), &mut low, PATTERN_RANGE_SWATCH_WIDTH); - ui.label(tr("High")); - changed |= color_swatch(ui, &format!("hi_{salt}_{}", channel.id()), &mut high, PATTERN_RANGE_SWATCH_WIDTH); - }); - if changed { - crate::pattern_panel::send(app, &target, pattern, json!({"low": low, "high": high})); - } - } - } - Source::Image { name, normal_format } => { - ui.label(trf("Image: {name}", &[("name", name)])); - if channel.kind() == ChannelKind::NormalMap { - let mut directx = *normal_format == texturecraft_engine::core::NormalFormat::DirectX; - let toggle = ui - .checkbox(&mut directx, tr("DirectX normal map")) - .on_hover_text(tr("Flips the image's green channel, for normal maps made with Y pointing down")); - if toggle.changed() { - app.run("layer.fill.set", set(json!({"normalFormat": if directx { "directX" } else { "openGl" }}))); - } - } - } - Source::Anchor { anchor, channel: anchored, .. } => { - ui.label(RichText::new(anchor_label(app, *anchor, *anchored)).color(tokens.text_dim)); - } - } - - if is_color && !source.ramp().is_empty() { - ramp_editor(app, ui, source.ramp(), &format!("ramp_{salt}_{}", channel.id()), &set); - } - }); - - // A shelf image dropped on the channel becomes its source - if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { - app.run("layer.fill.set", set(json!({"image": name}))); - } -} - -/// The Gradient Map item beside a color channel's source slot: turns the color stops of its -/// procedural (starting from its low and high, so the look holds) or anchor on, or off. -fn gradient_map_item(app: &mut TextureCraftApp, ui: &mut Ui, source: &Source, set: &impl Fn(Value) -> Value) { - let can = matches!(source, Source::Procedural { .. } | Source::Anchor { .. }); - let on = !source.ramp().is_empty(); - let hint = tr(GRADIENT_MAP_HINT); - let item = ui.add_enabled_ui(can, |ui| ui.selectable_label(on, tr("Gradient Map"))).inner; - if item.on_hover_text(hint).on_disabled_hover_text(hint).clicked() { - let params = if on { json!({ "colors": [] }) } else { json!({ "gradientMap": true }) }; - app.run("layer.fill.set", set(params)); - ui.close(); - } -} - -/// The color stops of a fill channel's gradient map. -fn ramp_editor(app: &mut TextureCraftApp, ui: &mut Ui, ramp: &[[f32; 3]], salt: &str, set: &impl Fn(Value) -> Value) { - let mut stops = ramp.to_vec(); - if gradient_stops(ui, salt, &mut stops) { - app.run("layer.fill.set", set(json!({ "colors": stops }))); - } -} - /// Swatches for gradient map stops (dark to light) with Add color and Remove last; true when /// they changed. fn gradient_stops(ui: &mut Ui, salt: &str, stops: &mut Vec<[f32; 3]>) -> bool { @@ -3313,11 +3141,23 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); - let target = crate::fill_source_target::FillSourceTarget::Mask { effect: id }; - let slot = ui.scope(|ui| crate::fill_source_slot::show(app, ui, &target, source, (&anchors, tr("Grayscale")))).response; + let project = &app.session.doc.project; + } + Source::Uniform(_) => tr("Uniform value").to_string(), + Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), + }; - // The slot accepts image drops from the Assets panel - if let Some(name) = image_drop(ui, &slot.interact(Sense::hover())) { + }); + } + }); + crate::menus::invoke(app, &ctx, "resource.import"); + } + }; + app.run("effect.set", params); + } + + // The source selector accepts image drops from the Assets panel + if let Some(name) = image_drop(ui, &source_response.interact(Sense::hover())) { app.run("effect.set", json!({"effect": id, "image": name})); } @@ -3328,10 +3168,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } - Source::Procedural { pattern, .. } => { - let target = crate::pattern_target::PatternTarget { command: "effect.set", base: json!({"effect": id}), salt: format!("mask_fill_{id}") }; - crate::pattern_panel::pattern_properties(app, ui, &target, pattern); - } Source::Anchor { anchor, .. } if anchor_in_mask(app, *anchor) => { let note = if mask_anchor_enabled(app, *anchor) == Some(false) { tr("Off") } else { tr("A mask anchor reads as its mask's gray.") }; ui.label(RichText::new(note).color(tokens.text_dim)); @@ -3350,6 +3186,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe Source::Image { .. } => { projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); } + Source::Procedural { pattern, .. } => { + let target = crate::pattern_target::PatternTarget { command: "effect.set", base: json!({"effect": id}), salt: format!("mask_fill_{id}") }; + crate::pattern_panel::pattern_properties(app, ui, &target, pattern); + } } if anchors.is_empty() { ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); @@ -3359,6 +3199,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe let enabled: Vec = fill.sources.keys().copied().collect(); PropertySheet::show(ui, ("fill_effect_sheet", id), |sheet| { crate::fill_panel::placement_sections(app, sheet, fill, &json!({"effect": id}), layer.id); + crate::fill_panel::fill_sheet(app, sheet, fill, &json!({"effect": id}), &enabled, layer.id); }); legacy_body(ui, |ui| fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id)); } diff --git a/crates/ui-egui/src/exact_entry_open.rs b/crates/ui-egui/src/exact_entry_open.rs deleted file mode 100644 index 67abc1b5..00000000 --- a/crates/ui-egui/src/exact_entry_open.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! The Levels editor's mark that its exact-entry fields are shown - -/// Marks the exact-entry fields as shown; they appear on a handle's double-click or Enter and close when typing ends -#[derive(Clone, Copy)] -pub(crate) struct ExactEntryOpen; diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs index 88aef1be..7f740796 100644 --- a/crates/ui-egui/src/fill_panel.rs +++ b/crates/ui-egui/src/fill_panel.rs @@ -8,6 +8,7 @@ use serde_json::{Value, json}; use texturecraft_engine::compose::frame_placement; use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length}; use texturecraft_engine::core::{Backface, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; +use texturecraft_engine::core::{Backface, Channel, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE}; use texturecraft_engine::paint::FULL_TURN_DEGREES; @@ -78,6 +79,10 @@ const SCALE_FIELD_SPEED: f32 = 0.01; /// The tabs over a fill's Properties, each jumping to its section pub(crate) fn fill_tabs() -> [(&'static str, &'static str); 2] { [(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry"))] +/// The tabs over a fill's Properties, each jumping to its section: a mask fill's last section is its Grayscale, a fill layer's its Material +pub(crate) fn fill_tabs(grayscale: bool) -> [(&'static str, &'static str); 3] { + let last = if grayscale { (ic::SQUARE_HALF, tr("Grayscale")) } else { (ic::CIRCLE_HALF, tr("Material")) }; + [(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry")), last] } /// Which fill a `base` addresses, (layer, effect), as the salt of its rows' widget state @@ -107,6 +112,12 @@ fn mesh_size(app: &TextureCraftApp, ctx: &egui::Context) -> MeshSize { size } +/// A fill's whole Properties: the Fill section, the Symmetry section, then the Material section with one slot per channel that is on +pub(crate) fn fill_sheet(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { + placement_sections(app, sheet, fill, base, reader); + crate::fill_material_panel::material_section(app, sheet, fill, base, on, reader); +} + /// The Fill section (with its reset) and the Symmetry section of the fill at `base`: a fill layer's, a content fill effect's or a mask fill's pub(crate) fn placement_sections(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, reader: LayerId) { // The section reset: projection, placement, sampling and culling back to a new fill's in one undo step diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 5a9fa0d7..43b0a9d5 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -370,7 +370,6 @@ mod tests { use super::*; - /// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another #[test] fn the_ring_spaces_its_copies_as_the_engine_does() { let symmetry = FillSymmetry { on: true, kind: SymmetryKind::Radial, count: 6, span: 720.0, ..FillSymmetry::OFF }; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 9a6dfae1..962914b1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -326,7 +326,7 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 }); }); combo(ui, tr("Source"), current.clone(), |ui| { - let anchors = anchors_below(app, layer); + let anchors = anchors_below(&app.session.doc.project, layer); if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 283013a9..2206f55e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,22 +16,23 @@ pub mod bake_presets; mod bake_report; mod bake_scene; mod color_management; +mod color_picker; mod color_selection_editor; pub mod control; mod decal_drop; mod display_settings; pub mod dock; pub mod docking; +mod drawn_icon; mod environment_picker; mod export_panel; pub mod export_templates; mod export_window; #[cfg(not(target_arch = "wasm32"))] pub mod file_dialogs; +mod fill_material_panel; mod fill_panel; mod fill_pictures; -mod fill_source_slot; -mod fill_source_target; mod fill_symmetry_panel; mod filter_slot; pub mod fonts; @@ -55,6 +56,7 @@ mod line_snap; mod list_action; pub mod log_panel; mod mask_preview_image; +mod material_orb; mod material_preview_image; pub mod menus; mod mesh_export_options; @@ -67,6 +69,9 @@ mod nav_button; pub mod nav_buttons; mod nav_view; pub mod new_project_advanced; +mod orb_environment; +mod orb_material; +pub mod orb_previews; mod orb_shape; pub mod parity; mod past_end; @@ -75,6 +80,8 @@ mod path_surface_cache; mod pattern_panel; mod pattern_target; pub mod pbr_import; +mod picker_group; +mod picker_tab; mod placement; mod pointer_lock; mod popup_drag; @@ -95,17 +102,15 @@ mod property_sheet; mod query_field; mod rail_popup; pub mod render_mode; +mod resolution_band; mod resource_panel; mod resource_picker; -mod resource_picker_anchor; -mod resource_picker_choice; mod resource_picker_item; -mod resource_picker_tab; -mod resource_picker_tile; mod round_gizmo; mod running_bake; pub mod saved_search; mod screen_color_pick; +pub mod screen_pick; mod section_page; pub mod settings_window; pub mod shader_settings; @@ -117,15 +122,19 @@ pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; pub mod shelf_view; +mod slot_thumbnail; #[cfg(not(target_arch = "wasm32"))] mod smart_mask_menu; mod soft_box; +mod source_choice; +mod source_slot; pub mod state; mod surface_paint_point; pub mod symmetry; pub mod theme; pub mod thumbs; mod tile_edits; +mod tile_picture; pub mod titlebar; pub mod toolbar; pub mod ui_state_store; @@ -262,6 +271,12 @@ pub struct TextureCraftApp { pub picking_id_color: Option, /// Whether the next click on the model places the symmetry planes (Pick point in the symmetry settings) pub picking_symmetry_plane: bool, + /// The colour bar whose eyedropper waits for a click on the model or, outside the app, on the screen + pub picking_color: Option, + /// That eyedropper pick's wait for a click outside the app + pub screen_pick: Option, + /// Whether an eyedropper pick also takes a click outside the app (only with a real window: never in tests) + pub screen_picking: bool, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -367,6 +382,12 @@ impl TextureCraftApp { properties_popup: None, picking_id_color: None, picking_symmetry_plane: false, + picking_color: None, + screen_pick: None, + #[cfg(not(target_arch = "wasm32"))] + screen_picking: raw_window_handle::HasWindowHandle::window_handle(cc).is_ok(), + #[cfg(target_arch = "wasm32")] + screen_picking: false, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, @@ -612,7 +633,8 @@ impl TextureCraftApp { return false; }; - let resized = self.session.doc.project.texture_set(set).is_ok_and(|set| set.resolution != c.size); + // A cook for another size than the layer's picked or texture set resolution is redone + let resized = self.session.link_size(c.layer).is_ok_and(|now| now != c.size); let baked = self.session.baked(set); let stale = resized || c.baked_inputs.iter().any(|input| !input.is_current(baked)); done.push((c.layer, c.values.clone(), stale, result)); @@ -1066,6 +1088,7 @@ impl eframe::App for TextureCraftApp { self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); + screen_pick::sync(self, ctx); move_on_model::end_when_gone(self, ctx); // The Path tool's curve repaints (a preview while placed) as its points, brush or material change @@ -1124,6 +1147,10 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] self.file_dialogs.show_pending(frame); + // Last, so no widget's pointer replaces it: an armed eyedropper is the pointer over the whole window + if self.picking_color.is_some() { + screen_pick::paint_cursor(&ctx, None, screen_pick::SwatchColor::shown(&ctx)); + } pointer_lock::settle(&ctx); let end_ms = now_ms(); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7ec42c75..3e40db15 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -471,8 +471,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { input.events.extend(aliases); }); - // Escape closes a dropdown before Properties, the rail popup, color picking or the stroke + // Escape closes a dropdown before an eyedropper pick, the colour picker window, Properties, the rail popup, the ID colour pick or the stroke let popup_open = egui::Popup::is_any_open(ctx); + let picker_open = crate::color_picker::open_window(ctx).is_some(); let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); #[cfg(not(target_arch = "wasm32"))] @@ -511,6 +512,8 @@ 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); } + // The open list or the picker window closes on this Escape itself + let escape_is_free = !popup_open && !picker_open; if confirming_reset { // Its keys were handled before the shortcuts ran } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { @@ -523,15 +526,17 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.picking_color = None; + } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; - } else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); - } else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_symmetry_plane = false; - } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.cancel_path(); } diff --git a/crates/ui-egui/src/pattern_panel.rs b/crates/ui-egui/src/pattern_panel.rs index 7afe7662..0d570bce 100644 --- a/crates/ui-egui/src/pattern_panel.rs +++ b/crates/ui-egui/src/pattern_panel.rs @@ -31,19 +31,34 @@ pub(crate) fn pattern_properties(app: &mut TextureCraftApp, ui: &mut Ui, target: Some(tile) => tile_parameters(app, ui, target, pattern, tile), None => pattern_parameters(app, ui, target, pattern), } - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Restore defaults")).clicked() { - restore_defaults(app, target, pattern); - } - }); - }); + restore_row(app, ui, target, pattern); }); if let Some(tile) = pattern.tile.as_deref() { section(ui, &id("inputs"), tr("Image inputs"), false, |ui| image_inputs(app, ui, target, pattern, tile)); } } +/// A Tile Generator under a slot whose rows already show its scale, contrast, seed and resolution: its own parameters and image inputs +pub(crate) fn tile_generator_sections(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural, tile: &TileGenerator) { + let id = |name: &str| format!("pattern_{name}_{}", target.salt); + section(ui, &id("parameters"), tr("Parameters"), true, |ui| { + tile_parameters(app, ui, target, pattern, tile); + restore_row(app, ui, target, pattern); + }); + section(ui, &id("inputs"), tr("Image inputs"), false, |ui| image_inputs(app, ui, target, pattern, tile)); +} + +/// Restore defaults, on the right +fn restore_row(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + restore_defaults(app, target, pattern); + } + }); + }); +} + /// Sends `pattern` again (its kind, scale, seed, contrast, balance and invert) with `extra` to its fill pub(crate) fn send(app: &mut TextureCraftApp, target: &PatternTarget, pattern: &Procedural, extra: Value) { let mut params = target.base.clone(); diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs index 37992c63..18a8bc60 100644 --- a/crates/ui-egui/src/projection_preview.rs +++ b/crates/ui-egui/src/projection_preview.rs @@ -17,6 +17,7 @@ use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; use rayon::prelude::*; use crate::projector_outline::ProjectorOutline; +use crate::slot_thumbnail::FULL_UV; use crate::theme::Tokens; mod preview_shape; diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 4e4d2f34..4f70d16a 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -49,18 +49,19 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: } } -/// Draws the open popup and closes it on a press outside it or when the app leaves Painting +/// Draws the open popup and closes it on a press outside it (but not an eyedropper pick's) 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) { + let in_picker = |at: egui::Pos2| crate::color_picker::open_window(ctx).is_some_and(|picker| picker.contains(at)); + let outside = pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at)) && !in_picker(at)); + + // A press in one of the popup's own dropdowns or its colour picker window lands outside its area; an eyedropper pick's click on the model hands its colour back to the popup + if outside && !egui::Popup::is_any_open(ctx) && app.picking_color.is_none() { app.properties_popup = Some(PropertiesPopup::Closing); } } diff --git a/crates/ui-egui/src/property_sheet/button_icon.rs b/crates/ui-egui/src/property_sheet/button_icon.rs index be97a317..5ed4fb73 100644 --- a/crates/ui-egui/src/property_sheet/button_icon.rs +++ b/crates/ui-egui/src/property_sheet/button_icon.rs @@ -1,10 +1,14 @@ //! What a full-width button shows before its words: an icon font glyph or an icon drawn in code +use crate::drawn_icon::DrawnIcon; + /// A full-width button's icon #[derive(Clone, Copy, Debug)] pub(crate) enum ButtonIcon<'a> { /// A glyph of the icon font Glyph(&'a str), + /// An icon the font has no fitting glyph for + Drawn(DrawnIcon), } impl<'a> From<&'a str> for ButtonIcon<'a> { @@ -12,3 +16,9 @@ impl<'a> From<&'a str> for ButtonIcon<'a> { ButtonIcon::Glyph(glyph) } } + +impl From for ButtonIcon<'_> { + fn from(icon: DrawnIcon) -> Self { + ButtonIcon::Drawn(icon) + } +} diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs index 15d3d03f..5ce08fe6 100644 --- a/crates/ui-egui/src/property_sheet/choice.rs +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -134,6 +134,20 @@ impl PropertySheet<'_> { response } + /// [`Self::dropdown`] whose list holds its options in groups, each under its caption, built only while the list is open; returns the picked option + pub(crate) fn grouped_dropdown<'g, T: Copy + PartialEq, Groups: IntoIterator)>>( + &mut self, + label: &str, + current: T, + groups: impl FnOnce() -> Groups, + name: impl Fn(T) -> String, + picture: ChoicePicture<'_, T>, + ) -> Option { + let response = self.dropdown_row(RowLead::label(label), current, &name, Some(picture)); + let captioned = || groups().into_iter().map(|(caption, options)| (Some(caption), options)); + self.hanging_groups(&response, current, captioned, &name, Some(picture)).0 + } + /// Paints a dropdown's button in `rect` and returns its response pub(super) fn dropdown_button(&mut self, rect: Rect, value: &str, picture: Option) -> Response { self.dropdown_button_led(rect, value, |painter| match picture { diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index 09ff1a4c..2e93f4af 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -3,6 +3,7 @@ use egui_phosphor::regular as ic; use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; use super::{BandResponse, GROUP_GAP, PropertySheet, TEXT_SIZE}; +use super::{BandResponse, GROUP_GAP, OpenCard, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; use crate::theme::semibold; /// Draws a band's picture in its rect @@ -33,12 +34,20 @@ const BAND_PICTURE_AIR: f32 = 8.0; /// A band's reset button click square const BAND_RESET_TARGET: f32 = 20.0; +/// How far a title's text reaches below its centre +const TITLE_HALF_LINE: f32 = 7.0; + impl PropertySheet<'_> { /// A top-level group across the whole panel with a caret and a reset (`Some(changed)`) or a value; a click folds it pub(crate) fn band(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>) -> BandResponse { self.band_drawn(title, default_open, reset, value, None) } + /// [`Self::band`] whose value is led by a picture (Resolution: the size against the texture set's) + pub(crate) fn band_pictured(&mut self, title: &str, default_open: bool, value: &str, picture: BandPicture<'_>) -> BandResponse { + self.band_drawn(title, default_open, None, Some(value), Some(picture)) + } + fn band_drawn(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>, picture: Option>) -> BandResponse { if self.card.is_none() { self.space(GROUP_GAP); @@ -109,12 +118,67 @@ impl PropertySheet<'_> { BandResponse { open, reset: reset_clicked } } + /// A group's fold state kept under `id`, flipped by a click on `hit` (answering as `title`); returns whether it is open + fn fold_toggle(&mut self, id: egui::Id, hit: Rect, title: &str, default_open: bool) -> bool { + let mut open = self.ui.data(|data| data.get_temp::(id)).unwrap_or(default_open); + let response = self.ui.interact(hit, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title)); + if response.clicked() { + open = !open; + self.ui.data_mut(|data| data.insert_temp(id, open)); + } + open + } + + /// A row of `rect`'s height across the open card, out to its bled edges + pub(super) fn bled_row(&self, rect: Rect) -> Rect { + Rect::from_min_max(pos2(self.left - CARD_BLEED, rect.top()), pos2(self.right + CARD_BLEED, rect.bottom())) + } + /// Ends [`Self::hold_card`] and closes the held card pub(crate) fn release_card(&mut self) { self.held = false; self.close_card(); } + /// Starts a card with no name row: a slot card, whose slot is its top row; inside a held card it joins that card + pub(crate) fn open_card(&mut self) { + if self.held && self.card.is_some() { + return; + } + + if self.card.is_none() && self.air_at != Some(self.cursor_y()) && !self.empty { + self.space(GROUP_GAP); + } + self.close_card(); + let face = self.ui.painter().add(Shape::Noop); + self.card = Some(OpenCard { top: self.cursor_y(), face }); + self.drawn_bottom = self.cursor_y(); + } + + /// A folded group inside a card: its bold name, the value it holds (dim) and a caret. Returns whether it is open + pub(crate) fn fold(&mut self, title: &str, value: Option<&str>, default_open: bool) -> bool { + let id = self.named_id("fold", title); + let rect = self.take(ROW_HEIGHT); + let open = self.fold_toggle(id, Rect::from_x_y_ranges(self.left..=self.right, rect.y_range()), title, default_open); + + let tokens = self.tokens; + let center_y = rect.center().y; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + if let Some(value) = value { + self.ui.painter().text( + pos2(self.right - BAND_VALUE_INSET, center_y), + Align2::RIGHT_CENTER, + value, + FontId::proportional(TEXT_SIZE), + tokens.text_dim, + ); + } + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + self.drawn(center_y + TITLE_HALF_LINE); + open + } + /// Ends the open card (not a held one: [`Self::release_card`] ends that): its face reaches [`CARD_PADDING`] below what its rows painted pub(crate) fn close_card(&mut self) { if self.held { diff --git a/crates/ui-egui/src/property_sheet/material_rows.rs b/crates/ui-egui/src/property_sheet/material_rows.rs new file mode 100644 index 00000000..14fc9b40 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/material_rows.rs @@ -0,0 +1,113 @@ +//! The Material section's own rows: the orb beside the Material | Channels switch and a uniform channel's gray ramp + +use std::ops::RangeInclusive; + +use egui::{Color32, Mesh, Painter, Rect, Sense, Vec2, pos2, vec2}; + +use super::ramp_edit::RampEdit; +use super::slider::KNOB_RADIUS; +use super::track::Track; +use super::{CONTROL_HEIGHT, GLYPH_TARGET, PropertySheet, ROW_HEIGHT}; +use crate::drawn_icon::DrawnIcon; + +/// Side of the material's orb +const ORB_SIZE: f32 = 90.0; + +/// Air between the orb and the switch beside it +const ORB_TO_SWITCH: f32 = 12.0; + +/// Air under the orb +const ORB_AIR: f32 = 14.0; + +/// From the right edge to the end of a ramp's track, where its value and invert glyph sit +const RAMP_END_INSET: f32 = 56.0; + +/// From the right edge to a ramp's value: where the linked Tiling and Offset values end +const RAMP_VALUE_INSET: f32 = super::preview_block::LINK_ROOM; + +/// From the right edge to a ramp's invert glyph's centre +const INVERT_INSET: f32 = 8.0; + +/// Width of a ramp's typed value +const RAMP_VALUE_WIDTH: f32 = 34.0; + +/// Height of a ramp's track +const RAMP_HEIGHT: f32 = 4.0; + +/// Size of the invert glyph +const INVERT_GLYPH_SIZE: f32 = 14.0; + +/// The gaps between the widgets of a card's own body +const CARD_ITEM_SPACING: Vec2 = vec2(8.0, 4.0); + +impl PropertySheet<'_> { + /// The material's orb with the Material | Channels switch beside it (none without `options`); returns the segment clicked when it was not the chosen one + pub(crate) fn orb_switch(&mut self, orb: &dyn Fn(&Painter, Rect), options: &[&str], selected: usize) -> Option { + let rect = self.take(ORB_SIZE); + let square = Rect::from_min_size(pos2(self.left, rect.top()), vec2(ORB_SIZE, ORB_SIZE)); + orb(self.ui.painter(), square); + let switch = Rect::from_min_max( + pos2(square.right() + ORB_TO_SWITCH, square.center().y - CONTROL_HEIGHT / 2.0), + pos2(self.right, square.center().y + CONTROL_HEIGHT / 2.0), + ); + let picked = if options.is_empty() { None } else { self.segments(switch, options, selected, super::switch_control::untinted, None) }; + self.drawn(square.bottom()); + self.space(ORB_AIR); + picked + } + + /// A uniform gray channel: a black-to-white ramp across the card (fills from the middle when `range` is signed), its value and the invert glyph + pub(crate) fn ramp(&mut self, label: &str, value: &mut f32, range: RangeInclusive) -> RampEdit { + let row = self.take(ROW_HEIGHT); + let center_y = row.center().y; + let id = self.next_id(); + let track = + Track { start: self.left + KNOB_RADIUS, end: self.right - RAMP_END_INSET, center_y, zero: (*range.start() < 0.0).then_some(0.0), ramp: true }; + let ramp = Rect::from_min_max(pos2(track.start, center_y - RAMP_HEIGHT / 2.0), pos2(track.end, center_y + RAMP_HEIGHT / 2.0)); + self.ui.painter().add(gray_ramp(ramp)); + let dragged = self.track(id, label, &track, value, &range); + let typed = self.value_field_at(id, label, self.right - RAMP_VALUE_INSET, RAMP_VALUE_WIDTH, center_y, *value, &range, 2, ""); + + let glyph = Rect::from_center_size(pos2(self.right - INVERT_INSET, center_y), vec2(GLYPH_TARGET, GLYPH_TARGET)); + let invert_id = self.next_id(); + let tip = crate::i18n::tr("Invert"); + let response = self.tip(self.ui.interact(glyph, invert_id, Sense::click()), tip); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + DrawnIcon::Invert.paint(self.ui.painter(), glyph.center(), INVERT_GLYPH_SIZE, color); + self.drawn(center_y + KNOB_RADIUS); + RampEdit { changed: Self::apply_typed(value, typed, dragged), invert: response.clicked() } + } + + /// Controls the sheet has no row for yet, laid out by egui between the panel's edges + pub(crate) fn embed(&mut self, body: impl FnOnce(&mut egui::Ui) -> R) -> R { + let width = self.right - self.left; + let top = self.cursor_y(); + let inner = self.ui.horizontal(|ui| { + ui.add_space(self.left - ui.cursor().left()); + ui.vertical(|ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing = CARD_ITEM_SPACING; + body(ui) + }) + .inner + }); + let bottom = inner.response.rect.bottom().max(top); + self.empty = false; + self.drawn(bottom); + inner.inner + } +} + +/// A horizontal black-to-white ramp filling `rect` +fn gray_ramp(rect: Rect) -> Mesh { + let mut mesh = Mesh::default(); + mesh.colored_vertex(rect.left_top(), Color32::BLACK); + mesh.colored_vertex(rect.right_top(), Color32::WHITE); + mesh.colored_vertex(rect.right_bottom(), Color32::WHITE); + mesh.colored_vertex(rect.left_bottom(), Color32::BLACK); + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + mesh +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index e5c97ea2..c3786b5c 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -4,22 +4,27 @@ mod axis_rows; mod band_response; mod button_icon; mod choice; +mod color_bar; +mod color_picker_rows; mod eye_toggle; mod group; mod hold_pad; mod info_icon; +mod material_rows; mod number_field; mod open_card; mod preview_block; mod preview_edit; mod preview_lower; mod preview_size; +mod ramp_edit; mod row; mod row_lead; mod section_tabs; mod sheet_measure; mod slider; mod slot; +mod slot_response; mod stack_slider; mod switch_control; mod tooltip; @@ -37,6 +42,11 @@ pub(crate) use preview_lower::PreviewLower; pub(crate) use preview_size::PreviewSize; pub(crate) use row_lead::RowLead; pub(crate) use section_tabs::{SectionScope, forget_sections, full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box}; +pub(crate) use section_tabs::{ + SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, + full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box, +}; +pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; @@ -93,9 +103,15 @@ const ICON_SIZE: f32 = 12.0; const ROW_PICTURE_SIZE: f32 = 18.0; const ROW_PICTURE_AIR: f32 = 8.0; +/// The click square of a glyph button inside a row +const GLYPH_TARGET: f32 = 18.0; + /// How far above and below a row's centre a slider track or a typed value takes the pointer const ROW_HIT_HALF_HEIGHT: f32 = 10.0; +/// Size of a row's glyph button glyphs (eyedropper, remove, arrow) +const GLYPH_SIZE: f32 = 13.0; + /// Corner radius of dropdowns, fields and buttons const CONTROL_RADIUS: u8 = 4; diff --git a/crates/ui-egui/src/property_sheet/ramp_edit.rs b/crates/ui-egui/src/property_sheet/ramp_edit.rs new file mode 100644 index 00000000..db1e61dd --- /dev/null +++ b/crates/ui-egui/src/property_sheet/ramp_edit.rs @@ -0,0 +1,10 @@ +//! What a uniform channel's ramp row did + +/// What a uniform channel's ramp row did this frame +pub(crate) struct RampEdit { + /// `Some(merge)` when the value changed, `merge` true for a drag's later steps + pub(crate) changed: Option, + + /// The invert glyph was clicked + pub(crate) invert: bool, +} diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index 28af9dd7..bd1f5cc4 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -56,6 +56,12 @@ const RESET_AT_DEFAULT_OPACITY: f32 = 0.4; const SECTION_RESET_INSET: f32 = RESET_ICON_SIZE / 2.0; impl PropertySheet<'_> { + /// A section caption in capitals, a hairline above a later one; `menu` adds the ≡ button + pub(crate) fn section(&mut self, title: &str, menu: bool) -> Option { + let text = self.tokens.text; + self.section_in(title, menu, text) + } + /// [`Self::section`] with the round section reset at the caption's right end: faint and inert at the defaults (`changed` false); returns whether it was clicked pub(crate) fn section_reset(&mut self, title: &str, changed: bool) -> bool { let text = self.tokens.text; diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 9ce3760a..08f7eb58 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -30,6 +30,16 @@ const DIAL_ZERO_DEGREES: f32 = 90.0; const DIAL_AIR: f32 = 6.0; impl PropertySheet<'_> { + /// A bounded number; `Some(merge)` when `value` changed, `merge` true for a drag's later steps + pub(crate) fn slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + self.slider_with_suffix(label, value, range, decimals, "") + } + + /// [`Self::slider`] with a unit after the value ("°", "%") + pub(crate) fn slider_with_suffix(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize, suffix: &str) -> Option { + self.slider_led(RowLead::label(label), value, range, decimals, suffix) + } + /// [`Self::slider_with_suffix`] led by `lead` (a picture row, a child setting) pub(crate) fn slider_led(&mut self, lead: RowLead<'_>, value: &mut f32, range: RangeInclusive, decimals: usize, suffix: &str) -> Option { let (control, center_y) = self.row_with(lead); @@ -40,6 +50,21 @@ impl PropertySheet<'_> { Self::apply_typed(value, typed, dragged) } + /// A signed range: fills from zero and marks it with a tick + pub(crate) fn signed_slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + self.centered_slider(label, value, range, 0.0, decimals) + } + + /// A range whose middle `centre` leaves things as they are: fills from it and marks it with a tick, like a signed range + pub(crate) fn centered_slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, centre: f32, decimals: usize) -> Option { + let (control, center_y) = self.row(label); + let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(centre), ramp: false }; + let dragged = self.track(id, label, &track, value, &range); + let typed = self.value_field(id, label, center_y, *value, &range, decimals, ""); + Self::apply_typed(value, typed, dragged) + } + /// An angle in degrees: the track, then a small dial just before the value pub(crate) fn angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { self.angle_led(RowLead::label(label), degrees, range) diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index fe2cef24..5bdfb324 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,6 +1,59 @@ use egui::{CornerRadius, FontId, Sense, Stroke, StrokeKind, pos2}; +use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; +use egui_phosphor::regular as ic; use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; +use super::switch_control::PILL_SIZE; +use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, SlotResponse, TEXT_SIZE}; +use crate::theme::semibold; + +/// Air between a slot card's top and its slot row +const SLOT_CARD_TOP: f32 = 6.0; + +/// Height of a slot row +const SLOT_HEIGHT: f32 = 36.0; + +/// Size of a slot's thumbnail +pub(super) const THUMB_SIZE: f32 = 26.0; + +/// Air between the thumbnail and the slot's name +const THUMB_TO_NAME: f32 = 10.0; + +/// Size of a slot's source line +const SOURCE_TEXT_SIZE: f32 = 10.0; + +/// The slot's name line above its centre and its source line below it +const NAME_ABOVE_CENTER: f32 = 7.0; +const SOURCE_BELOW_CENTER: f32 = 8.0; + +/// The square a slot's end glyph sits in +const SLOT_GLYPH_BOX: f32 = 18.0; + +/// The extra margin the on/off pill answers clicks in +const TOGGLE_HIT_MARGIN: f32 = 3.0; + +/// The seed's dice glyph size +const DICE_ICON_SIZE: f32 = 14.0; + +/// From the right edge to the slot toggle's centre +const SLOT_TOGGLE_INSET: f32 = 11.0; + +/// From the right edge to the × with a toggle beside it, and without +const CLEAR_INSET_WITH_TOGGLE: f32 = 40.0; +const CLEAR_INSET: f32 = 6.0; + +/// Distance between the × and the ⟲ left of it +const RESET_STEP: f32 = 22.0; + +/// Size of the slot's × and ⟲ glyphs +const SLOT_ICON_SIZE: f32 = 12.0; + +/// From the seed field's right edge to its value's right end +const SEED_VALUE_INSET: f32 = 8.0; + +/// Room the seed's dice button takes at the row's end, and the button's width +const DICE_ROOM: f32 = 34.0; +const DICE_WIDTH: f32 = 28.0; /// Air between a full-width button's icon and its words const BUTTON_ICON_GAP: f32 = 8.0; @@ -9,6 +62,103 @@ const BUTTON_ICON_GAP: f32 = 8.0; const BUTTON_ICON_SIZE: f32 = 14.0; impl PropertySheet<'_> { + /// Opens a slot card with its top row: thumbnail, name over source, then ⟲, × and the toggle on the right; the row opens the source list + pub(crate) fn slot( + &mut self, + thumbnail: &dyn Fn(&Painter, Rect), + name: &str, + source: &str, + on: Option<&mut bool>, + clear: bool, + reset: bool, + ) -> SlotResponse { + self.open_card(); + self.space(SLOT_CARD_TOP); + self.slot_row(thumbnail, name, source, on, clear, reset.then_some(true)) + } + + /// [`Self::slot`]'s row inside the card open now (an input a mode adds, under that mode), not a card of its own + pub(crate) fn slot_in_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, clear: bool) -> SlotResponse { + self.slot_row(thumbnail, name, source, None, clear, None) + } + + /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list + fn slot_row( + &mut self, + thumbnail: &dyn Fn(&Painter, Rect), + name: &str, + source: &str, + on: Option<&mut bool>, + clear: bool, + reset: Option, + ) -> SlotResponse { + let rect = self.take(SLOT_HEIGHT); + let center_y = rect.top() + SLOT_HEIGHT / 2.0; + let enabled = on.as_deref().copied().unwrap_or(true); + let has_toggle = on.is_some(); + let thumb = Rect::from_min_size(pos2(self.left, center_y - THUMB_SIZE / 2.0), vec2(THUMB_SIZE, THUMB_SIZE)); + let clear_x = self.right - if has_toggle { CLEAR_INSET_WITH_TOGGLE } else { CLEAR_INSET }; + let reset_x = if clear { clear_x - RESET_STEP } else { clear_x }; + + // The whole row across the card picks the source, so its list hangs at the card's width; the glyphs on the right take their clicks first + let row = self.bled_row(rect); + let pick_id = self.next_id(); + let pick = self.ui.interact(row, pick_id, Sense::click()); + pick.widget_info(|| egui::WidgetInfo { current_text_value: Some(source.to_owned()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) }); + let mut result = SlotResponse { pick, clear: false, reset: false, toggled: false }; + + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + thumbnail(&painter, thumb); + painter.rect_stroke( + thumb, + CornerRadius::ZERO, + Stroke::new(1.0, if result.pick.hovered() { tokens.accent } else { tokens.field_border }), + StrokeKind::Inside, + ); + let text_x = thumb.right() + THUMB_TO_NAME; + let (name_font, name_color) = if enabled { (semibold(TEXT_SIZE), tokens.text) } else { (FontId::proportional(TEXT_SIZE), tokens.text_dim) }; + painter.text(pos2(text_x, center_y - NAME_ABOVE_CENTER), Align2::LEFT_CENTER, name, name_font, name_color); + painter.text(pos2(text_x, center_y + SOURCE_BELOW_CENTER), Align2::LEFT_CENTER, source, FontId::proportional(SOURCE_TEXT_SIZE), tokens.text_dim); + + for (shown, live, x, glyph, tip, slot) in [ + (clear, true, clear_x, ic::X, crate::i18n::n_("Clear"), &mut result.clear), + (reset.is_some(), reset.unwrap_or(false), reset_x, ic::CLOCK_COUNTER_CLOCKWISE, crate::i18n::n_("Restore defaults"), &mut result.reset), + ] { + if !shown { + continue; + } + + let glyph_rect = Rect::from_center_size(pos2(x, center_y), Vec2::splat(SLOT_GLYPH_BOX)); + let id = self.next_id(); + + // At the defaults the ⟲ is faint and inert, as on a band: a click there picks the source like the rest of the row + let response = if live { + self.tip(self.ui.interact(glyph_rect, id, Sense::click()), crate::i18n::tr(tip)) + } else { + self.ui.interact(glyph_rect, id, Sense::hover()) + }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, live, crate::i18n::tr(tip))); + *slot = live && response.clicked(); + let color = self.reset_glyph_color(live, response.hovered(), tokens.text); + painter.text(glyph_rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(SLOT_ICON_SIZE), color); + } + + if let Some(on) = on { + let pill = Rect::from_center_size(pos2(self.right - SLOT_TOGGLE_INSET, center_y), PILL_SIZE); + let id = self.next_id(); + let response = self.ui.interact(pill.expand(TOGGLE_HIT_MARGIN), id, Sense::click()); + if response.clicked() { + *on = !*on; + result.toggled = true; + } + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *on, name)); + self.pill(pill.center(), *on, true); + } + self.drawn(thumb.bottom()); + result + } + /// A full-width button: centred icon and words pub(crate) fn button<'a>(&mut self, icon: impl Into>, text: &str) -> egui::Response { self.button_lit(icon, text, false) @@ -52,6 +202,7 @@ impl PropertySheet<'_> { let galley = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(BUTTON_ICON_SIZE), color); (galley.size().x, Some(galley)) } + ButtonIcon::Drawn(_) => (BUTTON_ICON_SIZE, None), }; let text_galley = painter.layout_no_wrap(text.to_owned(), font, color); let total = icon_width + BUTTON_ICON_GAP + text_galley.size().x; @@ -59,8 +210,78 @@ impl PropertySheet<'_> { if let Some(galley) = icon_galley { painter.galley(pos2(x, button.center().y - galley.size().y / 2.0), galley, color); } + if let ButtonIcon::Drawn(drawn) = icon { + drawn.paint(painter, pos2(x + icon_width / 2.0, button.center().y), BUTTON_ICON_SIZE, color); + } painter.galley(pos2(x + icon_width + BUTTON_ICON_GAP, button.center().y - text_galley.size().y / 2.0), text_galley, color); self.drawn(button.bottom()); response } + + /// A seed: its field (click to type) and the dice button, which picks a new one. Returns true when the seed changed + pub(crate) fn seed(&mut self, label: &str, seed: &mut u32) -> bool { + let (control, center_y) = self.row(label); + let field = Rect::from_min_max(control.min, pos2(self.right - DICE_ROOM, control.bottom())); + let dice = Rect::from_min_max(pos2(self.right - DICE_WIDTH, control.top()), control.max); + + let id = self.next_id(); + let typing_id = id.with("typed"); + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + painter.rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + + // The value sits right like every number; the box lights on hover and goes accent while typing + let mut changed = false; + if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { + let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(field.left() + SEED_VALUE_INSET, field.right() - SEED_VALUE_INSET, center_y, edit); + painter.rect_stroke(field, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + + if response.lost_focus() { + let untouched = self.end_typing(typing_id, &text); + if let Ok(typed) = text.trim().parse::() + && !untouched + && typed != *seed + && !self.ui.input(|input| input.key_pressed(egui::Key::Escape)) + { + *seed = typed; + changed = true; + } + } else { + self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + } + } else { + self.skip_typing_edit(); + let response = self.ui.interact(field, id, Sense::click()).on_hover_cursor(egui::CursorIcon::Text); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", &label)]))); + painter.text(pos2(field.right() - SEED_VALUE_INSET, center_y), Align2::RIGHT_CENTER, seed.to_string(), semibold(TEXT_SIZE), tokens.text); + + if response.hovered() { + painter.rect_stroke(field, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + if response.clicked() { + self.start_typing(typing_id, seed.to_string()); + } + } + + // The dice picks the next seed + let dice_id = self.next_id(); + let dice_response = self.tip(self.ui.interact(dice, dice_id, Sense::click()), crate::i18n::tr("Random")); + painter.rect( + dice, + CornerRadius::same(CONTROL_RADIUS), + if dice_response.hovered() { tokens.row_hover } else { tokens.button }, + Stroke::new(1.0, tokens.button_border), + StrokeKind::Inside, + ); + painter.text(dice.center(), Align2::CENTER_CENTER, ic::DICE_FIVE, FontId::proportional(DICE_ICON_SIZE), tokens.text); + dice_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::i18n::tr("Random"))); + + if dice_response.clicked() { + changed = true; + } + changed + } +} + } diff --git a/crates/ui-egui/src/property_sheet/slot_response.rs b/crates/ui-egui/src/property_sheet/slot_response.rs new file mode 100644 index 00000000..7fac7e34 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot_response.rs @@ -0,0 +1,15 @@ +/// What a slot card's top row did this frame +#[derive(Clone, Debug)] +pub(crate) struct SlotResponse { + /// The slot's row: a click opens the source list hanging from it (see [`super::PropertySheet::hanging_list`]) + pub(crate) pick: egui::Response, + + /// The × was clicked: back to a uniform source + pub(crate) clear: bool, + + /// The ⟲ was clicked: restore the slot's defaults + pub(crate) reset: bool, + + /// The slot's toggle was flipped + pub(crate) toggled: bool, +} diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 03677ab4..c8210d11 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -32,25 +32,35 @@ const PILL_RADIUS: u8 = 6; const TOGGLE_KNOB_RADIUS: f32 = 4.0; const TOGGLE_KNOB_TRAVEL: f32 = 4.5; +/// Air after a toggle's label, before the column the panel's toggles line up on +const TOGGLE_LABEL_AIR: f32 = 10.0; + +/// From that column to the pill's centre: the pill starts on the column +const TOGGLE_CENTER_OFFSET: f32 = PILL_SIZE.x / 2.0; + /// From one of a pair's toggles to the next, and from its name to its pill's centre const PAIR_PITCH: f32 = 76.0; const PAIR_NAME_TO_PILL: f32 = 32.0; -/// Width of a focused control's outline in points -const FOCUS_OUTLINE_WIDTH: f32 = 2.0; +/// Height of a channel pill, and the air between pills +const CHANNEL_PILL_HEIGHT: f32 = 22.0; +const CHANNEL_PILL_GAP: f32 = 4.0; + +/// Corner radius of a channel pill: half its height, so its ends are round +const CHANNEL_PILL_RADIUS: u8 = 11; + +/// Air under the channel strip +const CHANNEL_STRIP_AIR: f32 = 6.0; + +/// The least air around a channel pill's name before the names shrink a point +const PILL_TEXT_AIR: f32 = 10.0; + +/// No tint for any segment: the chosen word keeps the text colour +pub(super) fn untinted(_index: usize) -> &'static [Color32] { + &[] +} impl PropertySheet<'_> { - pub(super) fn paint_control_focus(&self, response: &Response) { - if response.has_focus() { - self.ui.painter().rect_stroke( - response.rect, - CornerRadius::same(CONTROL_RADIUS), - Stroke::new(FOCUS_OUTLINE_WIDTH, self.tokens.text_strong), - StrokeKind::Inside, - ); - } - } - /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { self.switch_tinted(label, options, selected, &[]) @@ -81,6 +91,20 @@ impl PropertySheet<'_> { self.dropdown_built(label, selected, || 0..options.len(), name, None).0 } + /// A row's control box, `CONTROL_HEIGHT` tall, from the left padding to the right one + pub(super) fn wide_row(&mut self) -> Rect { + let row = self.take(ROW_HEIGHT); + let center_y = row.center().y; + self.drawn(center_y + super::CONTROL_HEIGHT / 2.0); + Rect::from_x_y_ranges(self.left..=self.right, (center_y - super::CONTROL_HEIGHT / 2.0)..=(center_y + super::CONTROL_HEIGHT / 2.0)) + } + + /// A boxed switch across the whole panel (a mode switch at the top of a group), each word led by its picture; returns the picked index + pub(crate) fn picture_switch(&mut self, options: &[&str], selected: usize, picture: SegmentPicture<'_>) -> Option { + let control = self.wide_row(); + self.segments(control, options, selected, untinted, Some(picture)) + } + /// A boxed switch's box and segments in `control`, the chosen word in the colours `tints` gives its index (none: the text colour); returns the segment clicked when it was not the chosen one pub(super) fn segments<'t>( &mut self, @@ -136,6 +160,27 @@ impl PropertySheet<'_> { picked } + /// An on/off beside its label; every toggle in a panel lines up past the longest toggle label + pub(crate) fn toggle(&mut self, label: &str, on: &mut bool) -> bool { + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + let label_x = self.left + self.lead_shift(); + self.paint_info(center_y); + let font = FontId::proportional(TEXT_SIZE); + let label_end = label_x - self.left + self.text_width(label, font.clone()) + TOGGLE_LABEL_AIR; + self.seen.toggle_label_end = self.seen.toggle_label_end.max(label_end); + + let column = (self.column() - self.left).max(self.used.toggle_label_end).max(label_end); + let pill = Rect::from_center_size(pos2(self.left + column + TOGGLE_CENTER_OFFSET, center_y), PILL_SIZE); + let clicked = self.toggle_hit(Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + + let text = self.tokens.text; + self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, label, font, text); + self.pill(pill.center(), *on, true); + self.drawn(center_y + PILL_SIZE.y / 2.0); + clicked + } + /// A culling row on the panel's grid: its name on the label column, its picture where the controls start with the switch after it, a pending i at the row's right end pub(crate) fn picture_toggle(&mut self, picture: RowPicture<'_>, label: &str, on: &mut bool) -> bool { let rect = self.take(ROW_HEIGHT); @@ -209,6 +254,50 @@ impl PropertySheet<'_> { painter.rect(Rect::from_center_size(center, PILL_SIZE), CornerRadius::same(PILL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); painter.circle_filled(pos2(knob_x, center.y), TOGGLE_KNOB_RADIUS, knob); } + + /// The channel strip: one pill per channel; returns the clicked index and whether Alt (solo) was held + pub(crate) fn channel_pills(&mut self, names: &[&str], on: &[bool]) -> Option<(usize, bool)> { + let rect = self.take(CHANNEL_PILL_HEIGHT); + let count = names.len().max(1) as f32; + let width = (self.right - self.left - (count - 1.0) * CHANNEL_PILL_GAP) / count; + let size = if names.iter().all(|name| self.text_width(name, semibold(SMALL_TEXT_SIZE)) + PILL_TEXT_AIR <= width) { + SMALL_TEXT_SIZE + } else { + SMALL_TEXT_SIZE - 1.0 + }; + + let tokens = self.tokens; + let mut clicked = None; + for (index, name) in names.iter().enumerate() { + let pill = Rect::from_min_size(pos2(self.left + index as f32 * (width + CHANNEL_PILL_GAP), rect.top()), vec2(width, CHANNEL_PILL_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(pill, id, Sense::click()); + if response.clicked() { + clicked = Some((index, self.ui.input(|input| input.modifiers.alt))); + } + + let enabled = on.get(index).copied().unwrap_or(false); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, enabled, *name)); + let (fill, border, color, font) = if enabled { + (tokens.accent_dim, tokens.accent, tokens.text, semibold(size)) + } else { + (tokens.field, tokens.field_border, tokens.text_dim, FontId::proportional(size)) + }; + let painter = self.ui.painter(); + painter.rect( + pill, + CornerRadius::same(CHANNEL_PILL_RADIUS), + if response.hovered() && !enabled { tokens.row_hover } else { fill }, + Stroke::new(1.0, border), + StrokeKind::Inside, + ); + painter.text(pill.center(), Align2::CENTER_CENTER, *name, font, color); + } + self.drawn(rect.bottom()); + self.space(CHANNEL_STRIP_AIR); + self.air_at = Some(self.cursor_y()); + clicked + } } /// `word` laid out with its letters split as evenly as they go between the colours of `runs` diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 11b20f48..2cc6c702 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1,6 +1,7 @@ use egui::{Color32, CornerRadius, Painter, Rect}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable as _; +use egui_phosphor::regular as ic; use super::number_field::shown_number; use super::{NumberField, PropertySheet}; @@ -18,6 +19,9 @@ const PANEL_WIDTH: f32 = 300.0; /// The harness window: the panel plus room on its right for popups and tips, tall enough for the whole gallery unscrolled const HARNESS_SIZE: egui::Vec2 = egui::vec2(PANEL_WIDTH + 260.0, 1000.0); +/// The i of the gallery's Depth Culling row +const DEPTH_CULLING_TIP: &str = "Paints only the surface the projector sees first"; + fn swatch(color: Color32) -> impl Fn(&Painter, Rect) { move |painter: &Painter, rect: Rect| { painter.rect_filled(rect, CornerRadius::ZERO, color); @@ -38,6 +42,10 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { egui::Frame::NONE.fill(panel).show(ui, |ui| { ui.set_width(PANEL_WIDTH); PropertySheet::show(ui, "gallery", |sheet| { + sheet.section("Fill", true); + if let Some(scale) = sheet.switch("Scale", &["Tiling", "Physical size"], state.scale) { + state.scale = scale; + } if let Some(picked) = sheet .dropdown( "Filtering", @@ -50,6 +58,24 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { { state.filtering = picked; } + if let Some(merge) = sheet.slider("Hardness", &mut state.hardness, 0.0..=1.0, 2) { + state.hardness_merges.push(merge); + } + sheet.signed_slider("Offset", &mut state.offset, -1.0..=1.0, 2); + sheet.angle("Rotation", &mut state.rotation, 0.0..=360.0); + let names = ["Projection Extends Outside Shape", "Projection Is Cropped To Shape"]; + if let Some(picked) = sheet + .dropdown( + "A label wider than the column's cap", + state.long_choice, + &[0, 1], + |index| names.get(index).copied().unwrap_or_default().to_owned(), + None, + ) + .0 + { + state.long_choice = picked; + } let reset = sheet.band("3D projection settings", true, Some(state.position != [0.0; 3]), None); if reset.reset { @@ -71,6 +97,32 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { state.position_merges.push(merge); } } + + sheet.toggle("Wrap", &mut state.wrap); + sheet.toggle("Shape Crop", &mut state.crop); + sheet.info(DEPTH_CULLING_TIP); + sheet.picture_toggle(&swatch(Color32::from_gray(160)), "Depth Culling", &mut state.depth_culling); + sheet.picture_toggle(&swatch(Color32::from_gray(100)), "Backface Culling", &mut state.backface_culling); + sheet.slot(&swatch(Color32::from_rgb(0xb0, 0x5a, 0x3a)), "Base color", "Uniform color", Some(&mut state.channel_on), false, false); + sheet.slider("Value", &mut state.channel_value, 0.0..=1.0, 2); + + sheet.section("Filter", false); + if let Some((index, _)) = sheet.channel_pills(&["Color", "Metal", "Rough", "Normal", "Height"], &state.channels) + && let Some(on) = state.channels.get_mut(index) + { + *on = !*on; + } + let band = sheet.band("Parameters", true, None, Some("3")); + if band.open { + sheet.signed_slider("Horizontal", &mut state.offset, -1.0..=1.0, 2); + if sheet.fold("Attributes", Some("Default"), false) { + sheet.button(ic::DOT, "No attributes"); + } + sheet.seed("Seed", &mut state.seed); + if sheet.button(ic::DICE_FIVE, "Randomize seeds").clicked() { + state.randomized += 1; + } + } }); }); } @@ -89,6 +141,85 @@ fn gallery_harness(brightness: Brightness, gallery_state: Gallery) -> Harness<'s harness } +#[test] +fn toggles_switches_and_pills_change_their_state() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let at = harness.get_by_label("Shape Crop").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Physical size").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Normal").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + assert!(harness.state().crop); + assert_eq!(harness.state().scale, 1); + assert_eq!(harness.state().channels, [true, true, true, true, true]); +} + +#[test] +fn keyboard_focus_is_visible_on_switches_toggles_and_channel_pills() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for brightness in [Brightness::MediumDark, Brightness::Light] { + let mut harness = builder(brightness).build_ui(|ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "keyboard", |sheet| { + sheet.switch("Scale", &["Tiling", "Physical size"], 0); + sheet.toggle("Shape Crop", &mut false); + sheet.channel_pills(&["Normal"], &[true]); + }); + }); + harness.run_steps(3); + + for label in ["Tiling", "Physical size", "Shape Crop", "Normal"] { + harness.key_press(egui::Key::Tab); + harness.run_steps(2); + + let node = harness.get_by_label(label); + assert!(node.is_focused(), "{label} receives keyboard focus"); + + let rect = node.rect(); + assert!( + harness.output().shapes.iter().any(|clipped| { + matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.stroke.width > 1.0 && shape.rect.center().distance(rect.center()) < 1.0) + }), + "{label} paints a visible focus outline" + ); + } + } +} + +/// A toggle's pill starts on the controls column, where a dropdown's button starts (it sat 3 px in) +#[test] +fn a_toggles_pill_starts_where_a_dropdown_starts() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let dropdown = harness.get_by_label("Bilinear | HQ").rect(); + + // The toggle's hit area ends with its pill + let pill_left = harness.get_by_label("Shape Crop").rect().right() - super::switch_control::PILL_SIZE.x; + assert_eq!(pill_left, dropdown.left(), "the pill starts at {pill_left}, the dropdown at {}", dropdown.left()); +} + +/// A culling row sits on the panel's grid like a plain toggle: its name on the label column, its picture and switch where the controls start, its i at the row's end +#[test] +fn a_culling_row_reads_name_then_picture_and_switch_with_its_i_at_the_end() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let culling = harness.get_by_label("Depth Culling").rect(); + let plain = harness.get_by_label("Wrap").rect(); + let info = harness.get_by_label(DEPTH_CULLING_TIP).rect(); + assert_eq!(culling.left(), plain.left(), "the name starts where a plain toggle's does: {culling:?} vs {plain:?}"); + assert!(info.left() > culling.right(), "the i sits after the switch, at the row's end: {info:?} vs {culling:?}"); + + let was = harness.state().depth_culling; + let at = harness.get_by_label("Depth Culling").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert_ne!(harness.state().depth_culling, was, "a click on the row flips it"); +} + /// Two culling rows, the second named past the label column fn culling_rows(ui: &mut egui::Ui, on: &mut [bool; 2]) { let panel = Tokens::get(ui.ctx()).panel; @@ -191,6 +322,86 @@ fn click_at(harness: &mut Harness<'_, State>, at: egui::Pos2) { harness.run_steps(1); } +/// Clicks at `at`, then types `text` into the field that opened and presses Enter +fn type_at(harness: &mut Harness<'_, Gallery>, at: egui::Pos2, text: &str) { + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + harness.get_by_role(egui::Role::TextInput).type_text(text); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); +} + +#[test] +fn a_click_on_a_value_or_the_seed_selects_it_so_typing_replaces_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let value = harness.get_by_label("Hardness value").rect(); + type_at(&mut harness, value.center(), "0.4"); + assert_eq!(harness.state().hardness, 0.4, "the slider's value is replaced, not appended to"); + + let seed = harness.get_by_label("Seed value").rect(); + type_at(&mut harness, seed.center(), "77"); + assert_eq!(harness.state().seed, 77, "the seed is replaced, not appended to"); +} + +/// Clicks at `at` to type, then presses Enter without typing +fn open_and_leave_at(harness: &mut Harness<'_, Gallery>, at: egui::Pos2) { + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_some(), "a click at {at:?} opens the value to type"); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_none(), "Enter closes the value at {at:?}"); +} + +/// A value opened to type and left as it opened is not an edit: no undo step, and its hidden digits are not rounded away +#[test] +fn a_value_opened_and_left_untyped_changes_nothing() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 0.333, position: [1.2345, 0.0, 0.0], ..Gallery::default() }); + let hardness = harness.get_by_label("Hardness value").rect(); + let position = harness.get_by_label("Position X").rect(); + + open_and_leave_at(&mut harness, hardness.center()); + open_and_leave_at(&mut harness, position.center()); + + assert_eq!(harness.state().hardness, 0.333, "the slider keeps its unrounded value"); + assert!(harness.state().hardness_merges.is_empty(), "the slider reports no edit: {:?}", harness.state().hardness_merges); + assert_eq!(harness.state().position[0], 1.2345, "the number field keeps its unrounded value"); + assert!(harness.state().position_merges.is_empty(), "the number field reports no edit: {:?}", harness.state().position_merges); +} + +/// A value opened to type and left untyped while something else changed it (an agent's command) keeps the newer value: no edit, no undo step +#[test] +fn a_value_left_untyped_keeps_a_change_made_while_it_was_open() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 0.333, position: [1.2345, 0.0, 0.0], ..Gallery::default() }); + for (newer_seed, label) in (1..).zip(["Hardness value", "Position X", "Seed value"]) { + let at = harness.get_by_label(label).rect().center(); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_some(), "{label}: the click opens the value to type"); + + // Changed elsewhere while the field is open, then Enter without typing + harness.state_mut().hardness = 0.9; + harness.state_mut().position[0] = 0.5; + harness.state_mut().seed = newer_seed; + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_none(), "{label}: Enter closes the value"); + assert_eq!(harness.state().hardness, 0.9, "{label}: the slider keeps the newer value"); + assert_eq!(harness.state().position[0], 0.5, "{label}: the number field keeps the newer value"); + assert_eq!(harness.state().seed, newer_seed, "{label}: the seed keeps the newer value"); + } + assert!(harness.state().hardness_merges.is_empty(), "the slider reports no edit: {:?}", harness.state().hardness_merges); + assert!(harness.state().position_merges.is_empty(), "the number field reports no edit: {:?}", harness.state().position_merges); +} + /// A reason too long for its caption's row is cut with "…", and hovering it shows it whole #[test] fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { @@ -211,6 +422,87 @@ fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole"); } +/// A typed value that lands on the current one is no edit: one past the end kept at the end, or the same number written another way +#[test] +fn a_typed_value_equal_to_the_current_one_changes_nothing() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 1.0, ..Gallery::default() }); + let hardness = harness.get_by_label("Hardness value").rect(); + type_at(&mut harness, hardness.center(), "5"); + assert_eq!(harness.state().hardness, 1.0, "a value past the end is kept at the end"); + assert!(harness.state().hardness_merges.is_empty(), "kept at the value it had, it reports no edit: {:?}", harness.state().hardness_merges); + + harness.state_mut().hardness = 0.75; + harness.run_steps(1); + type_at(&mut harness, hardness.center(), ".750"); + assert_eq!(harness.state().hardness, 0.75); + assert!(harness.state().hardness_merges.is_empty(), "the same number written another way reports no edit: {:?}", harness.state().hardness_merges); +} + +/// A value just under zero opens to type as it reads, without a minus sign +#[test] +fn a_value_just_under_zero_opens_without_a_minus_sign() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: -0.001, ..Gallery::default() }); + let hardness = harness.get_by_label("Hardness value").rect(); + harness.drag_at(hardness.center()); + harness.drop_at(hardness.center()); + harness.run_steps(2); + assert_eq!(harness.get_by_role(egui::Role::TextInput).value().as_deref(), Some("0.00")); +} + +#[test] +fn a_drag_merges_after_its_first_step_and_a_click_does_not() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let track = harness.get_by_label("Hardness").rect(); + harness.drag_at(track.center()); + harness.run(); + harness.hover_at(track.center() + egui::vec2(20.0, 0.0)); + harness.run(); + harness.hover_at(track.center() + egui::vec2(40.0, 0.0)); + harness.run(); + harness.drop_at(track.center() + egui::vec2(40.0, 0.0)); + harness.run(); + let drag_merges = harness.state().hardness_merges.clone(); + + let click = track.left_center() + egui::vec2(20.0, 0.0); + harness.drag_at(click); + harness.drop_at(click); + harness.run(); + + assert!(drag_merges.len() >= 2, "the drag changes the value more than once: {drag_merges:?}"); + assert_eq!(drag_merges.first(), Some(&false), "the drag's first change starts an undo step: {drag_merges:?}"); + assert!(drag_merges.iter().skip(1).all(|merge| *merge), "later changes continue it: {drag_merges:?}"); + let merges = &harness.state().hardness_merges; + assert_eq!(merges.len(), drag_merges.len() + 1, "the click changes the value once: {merges:?}"); + assert_eq!(merges.last(), Some(&false), "the click starts its own undo step: {merges:?}"); +} + +/// A drag whose first frames change nothing (the knob held at its end) still starts its own undo step with its first change +#[test] +fn a_drag_pressed_past_the_tracks_end_starts_an_undo_step_with_its_first_change() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 1.0, ..Gallery::default() }); + let track = harness.get_by_label("Hardness").rect(); + let past_end = track.right_center() - egui::vec2(1.0, 0.0); + harness.drag_at(past_end); + harness.run(); + harness.hover_at(past_end + egui::vec2(20.0, 0.0)); + harness.run(); + harness.hover_at(track.center()); + harness.run(); + harness.hover_at(track.center() - egui::vec2(20.0, 0.0)); + harness.run(); + harness.drop_at(track.center() - egui::vec2(20.0, 0.0)); + harness.run(); + + let merges = &harness.state().hardness_merges; + assert!(merges.len() >= 2, "the drag changes the value more than once: {merges:?}"); + assert_eq!(merges.first(), Some(&false), "the first real change starts an undo step: {merges:?}"); + assert!(merges.iter().skip(1).all(|merge| *merge), "later changes continue it: {merges:?}"); +} + /// A number field held still until egui starts its drag, then moved, starts its own undo step with its first change #[test] fn a_number_field_held_still_then_dragged_starts_an_undo_step_with_its_first_change() { @@ -234,6 +526,82 @@ fn a_number_field_held_still_then_dragged_starts_an_undo_step_with_its_first_cha assert!(merges.iter().skip(1).all(|merge| *merge), "later moves continue it: {merges:?}"); } +#[test] +fn the_label_column_fits_the_widest_short_label_and_long_labels_stack() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let hardness = harness.get_by_label("Hardness").rect(); + let filtering = harness.get_by_label("Bilinear | HQ").rect(); + let crop = harness.get_by_label("Projection Extends Outside Shape").rect(); + + let column = filtering.left(); + assert!((hardness.left() - column).abs() < 0.5, "sliders start on the controls column"); + assert!(crop.left() < column, "a label wider than the cap stacks above a full-width control"); +} + +#[test] +fn reset_restores_the_band_and_the_seed_dice_steps_deterministically() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let at = harness.get_by_label("Random").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Restore defaults").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Randomize seeds").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + assert_eq!(harness.state().seed, next_seed(1234)); + assert_eq!(harness.state().position, [0.0; 3]); + assert_eq!(harness.state().randomized, 1); +} + +/// The gallery in every theme, closed and with a list open, for comparing with the mockups +#[test] +#[ignore] +fn property_sheet_gallery_snapshots() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + let mut harness = builder(brightness).with_pixels_per_point(2.0).wgpu().build_ui_state(gallery, Gallery::default()); + harness.run_steps(4); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}.png"))).unwrap(); + + let at = harness.get_by_label("Bilinear | HQ").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + harness.get_by_label("Bilinear | Sharp").hover(); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-list-open.png"))).unwrap(); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + + // A value: the grey line on hover, then typing on that line in accent; the seed's box lights the same way + let value = harness.get_by_label("Hardness value").rect().center(); + harness.hover_at(value); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-value-hover.png"))).unwrap(); + harness.drag_at(value); + harness.drop_at(value); + harness.run_steps(2); + harness.get_by_role(egui::Role::TextInput).type_text("0.4"); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-value-typing.png"))).unwrap(); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + let seed = harness.get_by_label("Seed value").rect().center(); + harness.hover_at(seed); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-seed-hover.png"))).unwrap(); + harness.drag_at(seed); + harness.drop_at(seed); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-seed-typing.png"))).unwrap(); + } +} + #[test] fn a_number_field_reads_zero_without_a_minus_sign() { assert_eq!(shown_number(-0.0, 0), "0"); @@ -243,3 +611,168 @@ fn a_number_field_reads_zero_without_a_minus_sign() { assert_eq!(shown_number(-1.25, 2), "-1.25"); assert_eq!(shown_number(2.5, 1), "2.5"); } + +/// Folds keep their own open state when a fold above them comes and goes (the state follows the name, not the row's place) +#[test] +fn a_fold_keeps_its_state_when_rows_above_it_come_and_go() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let folds = |ui: &mut egui::Ui, extra_shown: &mut bool| { + PropertySheet::show(ui, "folds", |sheet| { + if *extra_shown && sheet.fold("Extra", None, true) { + sheet.button(ic::DOT, "Extra rows"); + } + if sheet.fold("Edges", None, true) { + sheet.button(ic::DOT, "Edge rows"); + } + if sheet.fold("Parameters", None, false) { + sheet.button(ic::DOT, "Parameter rows"); + } + }); + }; + let mut harness = builder(Brightness::MediumDark).build_ui_state(folds, true); + harness.run_steps(2); + let at = harness.get_by_label("Edges").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_label("Edge rows").is_none()); + + *harness.state_mut() = false; + harness.run_steps(2); + + assert!(harness.query_by_label("Edge rows").is_none(), "Edges stays folded"); + assert!(harness.query_by_label("Parameter rows").is_none(), "Parameters stays folded"); +} + +/// Two colour bars, one under the other, each opening its own picker +fn two_color_bars(ui: &mut egui::Ui) { + PropertySheet::show(ui, "color_bars", |sheet| { + sheet.color_bar("Bar A", [0.2, 0.4, 0.6], None, &[]); + sheet.color_bar("Bar B", [0.6, 0.4, 0.2], None, &[]); + }); +} + +/// The colour space picked in one picker is the one the next picker opens in, even for a bar drawn before it all along +#[test] +fn the_next_picker_opens_in_the_colour_space_last_picked() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui(two_color_bars); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Bar B").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::ComboBox, "sRGB").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Linear").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::ComboBox, "Linear").is_some(), "Bar B's picker shows Linear"); + + let at = harness.get_by_role_and_label(egui::Role::Button, "Close").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Bar A").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + assert!(harness.query_by_role_and_label(egui::Role::TitleBar, "Bar A").is_some(), "Bar A's picker is open"); + assert!(harness.query_by_role_and_label(egui::Role::ComboBox, "Linear").is_some(), "Bar A's picker opens in Linear"); +} + +/// A colour bar's picker stays open when a colour bar above it comes and goes (its state follows its name, not its place) +#[test] +fn a_color_bars_picker_stays_open_when_a_row_above_it_goes_away() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let bars = |ui: &mut egui::Ui, extra_shown: &mut bool| { + PropertySheet::show(ui, "color_bars", |sheet| { + if *extra_shown { + sheet.color_bar("Extra", [0.5; 3], None, &[]); + } + sheet.color_bar("Tint", [0.2, 0.4, 0.6], None, &[]); + }); + }; + let mut harness = builder(Brightness::MediumDark).build_ui_state(bars, true); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Tint").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::TitleBar, "Tint").is_some(), "the picker opened"); + + *harness.state_mut() = false; + harness.run_steps(2); + + assert!(harness.query_by_role_and_label(egui::Role::TitleBar, "Tint").is_some(), "the picker stays open"); +} + +/// A fold under a later section, before that section's first band, keeps its state when a band of the section above comes and goes +#[test] +fn a_fold_before_a_sections_first_band_keeps_its_state_when_the_band_above_goes_away() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let sections = |ui: &mut egui::Ui, band_shown: &mut bool| { + PropertySheet::show(ui, "sections", |sheet| { + sheet.section("First", false); + if *band_shown && sheet.band("Band", true, None, None).open { + sheet.button(ic::DOT, "Band rows"); + } + sheet.section("Second", false); + if sheet.fold("Edges", None, true) { + sheet.button(ic::DOT, "Edge rows"); + } + }); + }; + let mut harness = builder(Brightness::MediumDark).build_ui_state(sections, true); + harness.run_steps(2); + let at = harness.get_by_label("Edges").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_label("Edge rows").is_none()); + + *harness.state_mut() = false; + harness.run_steps(2); + + assert!(harness.query_by_label("Edge rows").is_none(), "Edges stays folded"); +} + +/// The colour picker's hex field ends where the colour field above it ends (it ended 4 px short) +#[test] +fn the_pickers_hex_field_ends_on_the_colour_fields_right_edge() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui(two_color_bars); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Bar A").rect().center(); + + click_at(&mut harness, at); + harness.run_steps(2); + + let field = harness.get_by_role_and_label(egui::Role::Slider, "Saturation and value").rect(); + let hex = harness.get_by_role_and_label(egui::Role::TextInput, "Hex color").rect(); + assert_eq!(hex.right(), field.right(), "the hex field ends at {}, the colour field at {}", hex.right(), field.right()); +} + +/// A linked Tiling and Offset block over a ramp +fn ramp_under_tiling(ui: &mut egui::Ui, state: &mut ([f32; 2], [f32; 2], bool, f32)) { + let (tiling, offset, linked, gray) = state; + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "ramp", |sheet| { + let size = super::PreviewSize { label: "Tiling", values: tiling, range: 0.0..=10.0, typed: 0.0..=100.0, decimals: 2, linked }; + let lower = super::PreviewLower::Offset { values: offset, range: 0.0..=1.0, typed: -10.0..=10.0 }; + sheet.preview_block(&swatch(Color32::from_gray(128)), size, lower); + sheet.ramp("Grayscale", gray, 0.0..=1.0); + }); + }); +} + +/// A ramp's value ends on the linked Tiling and Offset values above it (it ended 2 px right of them) +#[test] +fn a_ramps_value_ends_on_the_linked_tiling_value() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui_state(ramp_under_tiling, ([1.0; 2], [0.0; 2], true, 0.5)); + + harness.run_steps(3); + + let tiling = harness.get_by_label("Tiling value").rect(); + let ramp = harness.get_by_label("Grayscale value").rect(); + assert_eq!(ramp.right(), tiling.right(), "the ramp's value ends at {}, Tiling's at {}", ramp.right(), tiling.right()); +} diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs index b1774512..2332a36b 100644 --- a/crates/ui-egui/src/property_sheet/tests/gallery.rs +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -3,15 +3,52 @@ use super::Filtering; /// The gallery's controls, with the values they last set +/// Every control of the shared set once, with the values the gallery last set pub(super) struct Gallery { + pub(super) scale: usize, pub(super) filtering: Filtering, + pub(super) hardness: f32, + pub(super) hardness_merges: Vec, + pub(super) offset: f32, + pub(super) rotation: f32, pub(super) position: [f32; 3], pub(super) position_merges: Vec, pub(super) linked: bool, + pub(super) wrap: bool, + pub(super) crop: bool, + pub(super) depth_culling: bool, + pub(super) backface_culling: bool, + pub(super) channel_on: bool, + pub(super) channels: [bool; 5], + pub(super) channel_value: f32, + pub(super) seed: u32, + pub(super) randomized: u32, + pub(super) long_choice: usize, } impl Default for Gallery { fn default() -> Self { Gallery { filtering: Filtering::BilinearHq, position: [0.0, 1.25, -0.5], position_merges: Vec::new(), linked: true } + Gallery { + scale: 0, + filtering: Filtering::BilinearHq, + hardness: 0.75, + hardness_merges: Vec::new(), + offset: -0.25, + rotation: 30.0, + position: [0.0, 1.25, -0.5], + position_merges: Vec::new(), + linked: true, + wrap: true, + crop: false, + depth_culling: true, + backface_culling: false, + channel_on: true, + channels: [true, true, true, false, true], + channel_value: 0.8, + seed: 1234, + randomized: 0, + long_choice: 0, + } } } diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index c54113d0..a590761a 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -161,7 +161,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }; let shown = ctx.memory(|memory| memory.area_rect(area_id())); - if closed_by_input(ctx, shown, strip) { + + // An eyedropper pick's click on the model hands its colour back to the popup + if app.picking_color.is_none() && closed_by_input(ctx, shown, strip) { app.ui.rail_panel = None; let held = ctx.input(|input| input.pointer.any_down()); ctx.data_mut(|data| data.insert_temp(area_id().with("closing"), held)); @@ -212,12 +214,13 @@ fn placement(ctx: &egui::Context, strip: Rect, icon: Rect) -> (Pos2, f32) { (Pos2::new(right, icon.top()), width) } -/// A press outside the popup and the rail, unless in one of the popup's own dropdowns +/// A press outside the popup and the rail, unless in one of the popup's own dropdowns or its colour picker window fn closed_by_input(ctx: &egui::Context, shown: Option, strip: Rect) -> bool { let pressed_at = ctx.input(|input| input.pointer.press_origin().filter(|_| input.pointer.any_pressed())); - // A press on the rail is left to its icons, which switch or close the popup themselves - let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at))); + // A press on the rail is left to its icons, which switch or close the popup themselves; one in the popup's colour picker window stays in the popup + let in_picker = |at: Pos2| crate::color_picker::open_window(ctx).is_some_and(|picker| picker.contains(at)); + let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at)) && !in_picker(at)); outside && !egui::Popup::is_any_open(ctx) } diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index f017b9ba..94a73684 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -426,6 +426,7 @@ pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, gizmo: &RoundG #[cfg(test)] pub(crate) mod tests { use egui::{Modifiers, PointerButton, vec2}; + use egui_kittest::kittest::Queryable; use texturecraft_engine::core::{Fill, LayerId, LayerKind, Projection, Projector}; use super::*; @@ -815,6 +816,29 @@ pub(crate) mod tests { harness.run_steps(2); } + /// A plain left press on the projector's handle while a colour picker is open only closes the picker: no stroke, no slide, and the press after it works again + #[test] + fn a_press_that_closes_the_colour_picker_neither_paints_nor_slides() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let before = projection(&harness, layer); + let from = gizmo(&harness).center; + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(2); + assert!(crate::color_picker::open_window(&harness.ctx).is_some(), "the picker is open"); + let steps = harness.state().session.history_labels().len(); + + drag(&mut harness, from, from + vec2(40.0, 0.0), Modifiers::NONE); + assert!(crate::color_picker::open_window(&harness.ctx).is_none(), "the press closed the picker"); + assert_eq!(projection(&harness, layer), before, "and slid nothing"); + assert_eq!(harness.state().session.history_labels().len(), steps, "nor made an undo step"); + + drag(&mut harness, from, from + vec2(40.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "the next press slides again"); + } + /// A tri-planar fill selected while the quick mask is edited with the Paint tool: brushes act and the projector shows fn quick_mask_paint_app() -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { let (mut harness, layer) = fill_app("triplanar"); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 05e687ff..3416a106 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -413,17 +413,6 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.add_space(SECTION_GAP); } -/// The distinct categories of `items`, in order of first appearance. -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) { - out.push(c); - } - } - out -} - /// Read the user's saved smart materials (desktop library folder and the added library locations) unless they are already listed #[cfg(not(target_arch = "wasm32"))] fn scan_library(app: &mut TextureCraftApp) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c5dffbc9..e2a36d40 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -471,6 +471,11 @@ fn default_wireframe_opacity() -> f32 { 40.0 } +/// The Layers panel's channel list starts on Material, so the Material tab's orb shows the whole material +fn default_layer_material_view() -> bool { + true +} + /// Settings that start on, for saved states that predate them fn default_true() -> bool { true @@ -524,6 +529,9 @@ pub struct UiState { pub uv_rotation: f32, /// Channel whose blending the layer rows show. pub layer_channel: Channel, + /// The Layers panel's channel list is on Material: the Material tab's orb shows the whole material, else `layer_channel` alone + #[serde(default = "default_layer_material_view")] + pub layer_material_view: bool, pub shelf_filter: String, /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] @@ -701,6 +709,7 @@ impl Default for UiState { uv_rotation: 0.0, layer_channel: Channel::BaseColor, blend_clipboard: None, + layer_material_view: true, shelf_filter: String::new(), shelf_tab: 0, shelf_path: Vec::new(), diff --git a/crates/ui-egui/src/symmetry/plane_pick.rs b/crates/ui-egui/src/symmetry/plane_pick.rs index 4dfcde97..de1bb98a 100644 --- a/crates/ui-egui/src/symmetry/plane_pick.rs +++ b/crates/ui-egui/src/symmetry/plane_pick.rs @@ -83,4 +83,29 @@ mod tests { assert_eq!(offset, [0.5, 0.25, 3.0], "x is picked minus center, y is untouched, z is clamped to the mesh"); } + + /// Escape closes an open colour picker first and leaves Pick point armed; the next Escape cancels Pick point + #[test] + fn escape_closes_an_open_colour_picker_before_it_cancels_pick_point() { + use egui_kittest::kittest::Queryable; + + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = crate::frame_gizmo::tests::fill_app("triplanar"); + harness.state_mut().session.tool.brush.symmetry.x = true; + harness.state_mut().picking_symmetry_plane = true; + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(2); + assert!(crate::color_picker::open_window(&harness.ctx).is_some(), "the picker is open"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + assert!(crate::color_picker::open_window(&harness.ctx).is_none(), "Escape closed the picker"); + assert!(harness.state().picking_symmetry_plane, "and left Pick point armed"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + assert!(!harness.state().picking_symmetry_plane, "the next Escape cancels Pick point"); + } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 05b2eb8f..33f94c62 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -397,12 +397,45 @@ pub const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; /// The axes' letters, as the Axis switches and the 3D fields' tags show them pub const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; +/// Cyan, magenta and yellow: the opposites of [`AXIS_COLORS`] at the same brightness (Color Balance's color names) +pub const OPPOSITE_COLORS: [Color32; 3] = [Color32::from_rgb(0x52, 0xb8, 0xc4), Color32::from_rgb(0xc4, 0x6a, 0xc8), Color32::from_rgb(0xd2, 0xb8, 0x52)]; + /// `from` moved `amount` of the way to `to` in gamma space, opaque pub(crate) fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount).round().clamp(0.0, 255.0) as u8; Color32::from_rgb(mix(from.r(), to.r()), mix(from.g(), to.g()), mix(from.b(), to.b())) } +/// Least contrast a tinted color name keeps against its background (the WCAG ratio for normal text: the names are regular 12 pt lettering) +const TINT_MIN_CONTRAST: f32 = 4.5; + +/// How finely [`legible_tint`] walks from the tint to the text colour: a tenth of the way at a time keeps as much of the tint as reads +const TINT_STEPS: u8 = 10; + +/// `tint` moved toward `text` just enough to read on `background` (Color Balance's yellow and cyan names on a light card); a tint that already reads stays as it is +pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color32 { + (0..=TINT_STEPS) + .map(|step| tint.lerp_to_gamma(text, f32::from(step) / f32::from(TINT_STEPS))) + .find(|color| contrast_ratio(*color, background) >= TINT_MIN_CONTRAST) + .unwrap_or(text) +} + +/// WCAG's flare term, added to both luminances so black still has a ratio +const WCAG_FLARE: f32 = 0.05; + +/// The WCAG contrast ratio of two opaque colors (1..21) +fn contrast_ratio(a: Color32, b: Color32) -> f32 { + let luminance = |color: Color32| { + let linear = egui::Rgba::from(color); + + // Rec. 709 luminance + 0.2126 * linear.r() + 0.7152 * linear.g() + 0.0722 * linear.b() + }; + let (first, second) = (luminance(a), luminance(b)); + let (high, low) = (first.max(second), first.min(second)); + (high + WCAG_FLARE) / (low + WCAG_FLARE) +} + /// A section caption inside a panel: semibold in the strong colour, as written (no capitals). pub fn caption(text: &str) -> egui::RichText { egui::RichText::new(text).font(semibold(12.5)).strong() @@ -412,6 +445,23 @@ pub fn caption(text: &str) -> egui::RichText { mod tests { use super::*; + #[test] + fn tint_names_reach_normal_text_contrast_and_a_tint_that_already_reads_stays_as_it_is() { + for theme in [Brightness::Light, Brightness::MediumLight, Brightness::MediumDark, Brightness::Dark] { + let tokens = Tokens::for_brightness(theme); + for tint in OPPOSITE_COLORS.into_iter().chain(AXIS_COLORS) { + let shown = legible_tint(tint, tokens.row, tokens.text); + assert!(contrast_ratio(shown, tokens.row) >= TINT_MIN_CONTRAST, "{theme:?} {tint:?} -> {shown:?}"); + if contrast_ratio(tint, tokens.row) >= TINT_MIN_CONTRAST { + assert_eq!(shown, tint, "{theme:?}: a tint that already reads stays as it is"); + } + } + } + + let light = Tokens::for_brightness(Brightness::Light); + assert_ne!(legible_tint(OPPOSITE_COLORS[2], light.row, light.text), OPPOSITE_COLORS[2], "yellow darkens on a light card"); + } + #[test] fn settings_round_trip_and_unknown_values_load_the_defaults() { for b in Brightness::ALL { @@ -429,18 +479,7 @@ mod tests { #[test] fn every_brightness_and_accent_reads() { - // Relative luminance (WCAG) and contrast ratio. - let lum = |c: Color32| { - let ch = |v: u8| { - let v = f32::from(v) / 255.0; - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } - }; - 0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b()) - }; - let contrast = |a: Color32, b: Color32| { - let (x, y) = (lum(a), lum(b)); - (x.max(y) + 0.05) / (x.min(y) + 0.05) - }; + let contrast = contrast_ratio; for b in Brightness::ALL { for a in Accent::ALL { let t = Tokens::for_brightness(b).with_accent(a); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index dc2f3453..84fd39e4 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -7,11 +7,12 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::docking::Panel; +use crate::drawn_icon::DrawnIcon; use crate::i18n::{tr, trf}; 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, icon_dropdown_button, icon_dropdown_button_width}; +use crate::widgets::{bar_slider, drawn_icon_button, 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; @@ -260,31 +261,54 @@ 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; + // Slider widths: the longer-named Size and Stroke opacity get more room, Lazy mouse's Distance less + const WIDE_SLIDER_WIDTH: f32 = 110.0; + const SLIDER_WIDTH: f32 = 100.0; + const NARROW_SLIDER_WIDTH: f32 = 90.0; + + /// The sliders show fractions as percentages + const PERCENT: f32 = 100.0; + + /// Size's track, in percent of the largest brush + const SIZE_PERCENT_RANGE: std::ops::RangeInclusive = 0.05..=100.0; + + /// Spacing's track, in percent of the brush's diameter + const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=200.0; + + /// Lazy mouse Distance's track, in pixels + const LAZY_DISTANCE_RANGE_PX: std::ops::RangeInclusive = 1.0..=200.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())); + if tool == Tool::ColorPicker { + let (icon, response) = ui.allocate_exact_size(vec2(TOOL_ICON_SIZE, TOOL_ICON_SIZE), egui::Sense::hover()); + DrawnIcon::Pipette.paint(ui.painter(), icon.center(), TOOL_ICON_SIZE, tokens.text_strong); + response.on_hover_text(tr(tool.label())); + } else { + 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 size = brush.size / MAX_BRUSH_SIZE * PERCENT; + if bar_slider(ui, tr("Size"), &mut size, SIZE_PERCENT_RANGE, WIDE_SLIDER_WIDTH).changed() { + brush.size = (size / PERCENT * 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 flow = brush.flow * PERCENT; + if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=PERCENT, SLIDER_WIDTH).changed() { + brush.flow = flow / PERCENT; } - 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 opacity = brush.opacity * PERCENT; + if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=PERCENT, WIDE_SLIDER_WIDTH).changed() { + brush.opacity = opacity / PERCENT; } - 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; + let mut spacing = brush.spacing * PERCENT; + if bar_slider(ui, tr("Spacing"), &mut spacing, SPACING_PERCENT_RANGE, SLIDER_WIDTH).changed() { + brush.spacing = spacing / PERCENT; } ui.separator(); @@ -294,7 +318,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } if lazy_on { let mut distance = brush.lazy; - if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { + if bar_slider(ui, tr("Distance"), &mut distance, LAZY_DISTANCE_RANGE_PX, NARROW_SLIDER_WIDTH).changed() { brush.lazy = distance; } } @@ -309,9 +333,9 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) 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); + let mut strength = app.session.tool.smudge_strength * PERCENT; + if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=PERCENT, SLIDER_WIDTH).changed() { + app.session.tool.smudge_strength = (strength / PERCENT).clamp(0.0, 1.0); } } @@ -456,7 +480,12 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (usable, usable && app.session.tool.tool == tool) } }; - let button = ui.add_enabled_ui(usable, |ui| icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE)).inner; + let button = ui + .add_enabled_ui(usable, |ui| match tool { + Tool::ColorPicker => drawn_icon_button(ui, DrawnIcon::Pipette, &hint, selected, SHELF_BUTTON_SIZE), + _ => icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE), + }) + .inner; if button.on_disabled_hover_text(tr(tool.label())).clicked() && app.ui.mode == Mode::Painting { app.run("tool.select", json!({"tool": tool.id()})); } @@ -502,7 +531,7 @@ const RAIL_ICON_SIZE: f32 = 26.0; const RAIL_ICON_GAP: f32 = 4.0; /// Padding inside the rail's card around its icons, as the tool shelf's -const RAIL_CARD_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); +const RAIL_CARD_PADDING: egui::Margin = SHELF_PADDING; /// The icon rail: the rail panels that are not in the dock (Export first), each opening its popup pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a58be4de..c2e92805 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -874,18 +874,36 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); - let popup = app.properties_popup.is_some() || rail_popup; + // A press that closes an open colour picker only closes it: it neither paints nor moves a projection + let picker = crate::color_picker::blocks_view_press(ui.ctx()); + let popup = app.properties_popup.is_some() || rail_popup || picker; - // A pending ID color pick takes the next click instead of the brush let picking = app.picking_id_color.is_some(); + // A pending ID color pick or eyedropper takes the next click instead of the brush + let picking = app.picking_id_color.is_some() || app.picking_color.is_some(); if picking { - crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + // The eyedropper's own pointer is drawn over the whole window (screen_pick) + if app.picking_color.is_none() { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + } + + // The eyedropper's disc shows the colour a click here would pick + if app.picking_color.is_some() + && let Some(hover) = response.hover_pos() + && let Ok(values) = app.session.color_at(local(hover), app.session.viewport) + && let Some(color) = values.get(&texturecraft_engine::core::Channel::BaseColor) + { + crate::screen_pick::SwatchColor::over_model(ui.ctx(), *color); + } if !alt && response.clicked_by(PointerButton::Primary) && let Some(position) = response.interact_pointer_pos() { let (pixel, viewport) = (local(position), app.session.viewport); - crate::id_color_pick::IdColorPick::pick_at(app, json!({"x": pixel.x, "y": pixel.y, "viewport": [viewport.x, viewport.y]})); + match app.picking_color { + Some(bar) => eyedrop(app, ui.ctx(), bar, pixel, viewport), + None => crate::id_color_pick::IdColorPick::pick_at(app, json!({"x": pixel.x, "y": pixel.y, "viewport": [viewport.x, viewport.y]})), + } } } @@ -1025,6 +1043,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && (app.session.tool.tool != Tool::Path || adjusting) && !crate::symmetry::manipulator_hovered(app, ui, rect) && app.picking_id_color.is_none() + && app.picking_color.is_none() && app.moving_on_model.is_none() && !ShownGizmo::hovered(ui, rect, gizmo.as_ref()) && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } @@ -2121,11 +2140,13 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !projection_hint && app.properties_popup.is_none() && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) + && !crate::color_picker::blocks_view_press(ui.ctx()) && !alt && !adjusting && !v_held && !picking_id_color && !app.picking_symmetry_plane + && app.picking_color.is_none() && !DecalDrop::blocks_input(ui.ctx()); let mut fill_box = None; if painting && path_tool { @@ -2230,7 +2251,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Match the 3D view's stamp size and hardness - let show_brush_cursor = tool_acts(app) && !alt && !v_held; + let show_brush_cursor = tool_acts(app) && !alt && !v_held && app.picking_color.is_none(); let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)); if show_brush_cursor && !path_tool @@ -2422,6 +2443,16 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t painter.add(egui::Shape::mesh(mesh)); } +/// Hands the base colour on the model at `pixel` to the colour bar `bar` and ends its eyedropper pick; a click off the model ends it too +fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel: Vec2, viewport: Vec2) { + app.picking_color = None; + let Ok(values) = app.session.color_at(pixel, viewport) else { return }; + + if let Some(color) = values.get(&texturecraft_engine::core::Channel::BaseColor) { + crate::color_picker::ColorPick::deliver(ctx, bar, *color); + } +} + #[cfg(test)] mod tests { use super::*; @@ -2593,6 +2624,41 @@ mod tests { assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view"); } + /// A click in the 2D view while a colour bar's eyedropper waits paints nothing: the pick keeps waiting, as over the 3D view + #[test] + fn a_waiting_eyedropper_keeps_a_2d_view_click_from_painting() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(4); + + // The 2D view fills the window's middle: there the sample's UV islands are (the shelf drop tests click the same point) + let on_the_uvs = pos2(700.0, 420.0); + let steps = harness.state().session.history_labels().len(); + let bar = egui::Id::unique("a colour bar"); + harness.state_mut().picking_color = Some(bar); + + click(&mut harness, on_the_uvs); + assert_eq!(harness.state().session.history_labels().len(), steps, "the click painted nothing"); + assert_eq!(harness.state().picking_color, Some(bar), "the eyedropper still waits"); + + harness.state_mut().picking_color = None; + click(&mut harness, on_the_uvs); + assert_eq!(harness.state().session.undo_label(), Some("Polygon fill"), "without a pick the same click paints"); + } + + /// Press and release the primary button at `at` + fn click(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + } + #[test] fn stored_surfaces_release_after_a_frame_without_paths() { // Hold the language lock while drawing the harness diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 93bb6b5a..b38010f6 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -4,6 +4,7 @@ use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle}; use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2}; +use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; use crate::theme::Tokens; @@ -191,6 +192,15 @@ 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) } +/// An `icon_button` showing an icon drawn in code +pub(crate) fn drawn_icon_button(ui: &mut Ui, icon: DrawnIcon, tooltip: &str, selected: bool, size: f32) -> Response { + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(tooltip, vec2(size, size), &style) + .selected(selected) + .show(ui, |ui, rect, color| icon.paint(ui.painter(), rect.center(), size * ICON_SCALE, color)) + .on_hover_text(tooltip) +} + /// Icon glyph size as a fraction of the button height const ICON_SCALE: f32 = 0.62; @@ -496,7 +506,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool } /// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh -fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { +pub(crate) fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { /// Cells across and down: fine enough that a hue strip's six ramps read smooth const GRID_CELLS: u32 = 24; diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index d56067e4..7185890e 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -160,3 +160,17 @@ fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { harness.event(Event::ModifiersChanged(egui::Modifiers::NONE)); harness.run_steps(2); } + +#[test] +fn a_waiting_eyedropper_hides_the_2d_brush_outline() { + let mut harness = harness(); + harness.state_mut().picking_color = Some(egui::Id::unique("a colour bar")); + let pointer = egui::pos2(800.0, 480.0); + harness.hover_at(pointer); + harness.run_steps(3); + assert!(rings_at(&harness, pointer).is_empty(), "no brush outline under the eyedropper (its own pointer is drawn instead)"); + + harness.state_mut().picking_color = None; + harness.run_steps(3); + assert_eq!(rings_at(&harness, pointer).len(), 1, "without a pick the outline is back"); +} diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 4278b0b3..97ce9790 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -64,12 +64,14 @@ fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { harness.run_steps(3); } -/// Whether the last frame drew the eyedropper glyph with its tip at `pointer` +/// Whether the pointer at `pointer` is the drawn eyedropper: the system pointer hidden and a picture painted under it fn eyedropper_at(harness: &Harness<'_, TextureCraftApp>, pointer: Pos2) -> bool { - harness.output().shapes.iter().any(|clipped| match &clipped.shape { - egui::Shape::Text(text) => text.galley.text() == egui_phosphor::regular::EYEDROPPER && (text.pos.x - pointer.x).abs() < 1.0, - _ => false, - }) + let output = harness.output(); + output.platform_output.cursor_icon == egui::CursorIcon::None + && output.shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Mesh(mesh) => mesh.texture_id != egui::TextureId::default() && mesh.calc_bounds().expand(1.0).contains(pointer), + _ => false, + }) } fn pick_color_label() -> String { diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index b03a4440..c39610c9 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -1,4 +1,4 @@ -//! A fill channel takes an image resource from its source picker +//! A fill channel takes an image resource from its slot's source picker use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -11,13 +11,14 @@ fn roughness<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Nod harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness") } -/// Opens the source picker of the Roughness channel from its slot -fn open_roughness_source_picker(harness: &mut Harness<'_, TextureCraftApp>) { - // Allow the scroll animation to finish before the click - roughness(harness).scroll_to_me(); - harness.run_steps(30); - roughness(harness).click(); +/// Opens the Roughness slot's source picker on the Material tab and types `search` into its search field, which has the focus +fn open_roughness_source_menu(harness: &mut Harness<'_, TextureCraftApp>, search: &str) { + click_node(harness, egui::Role::Tab, "Material"); harness.run_steps(3); + click_node(harness, egui::Role::ComboBox, "Roughness"); + harness.run_steps(2); + harness.event(egui::Event::Text(search.into())); + harness.run_steps(2); } #[test] @@ -34,8 +35,8 @@ fn a_fill_channel_takes_an_image_from_its_source_picker() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_picker(&mut harness); - harness.get_by_role_and_label(egui::Role::Button, &name).click(); + open_roughness_source_menu(&mut harness, "rough"); + click_node(&mut harness, egui::Role::ListBoxOption, &name); harness.run_steps(3); let LayerKind::Fill(fill) = &harness.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; @@ -59,7 +60,8 @@ fn the_source_picker_offers_only_images_that_were_decoded() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_picker(&mut harness); + // Both names match the search, so only the decoded one may show + open_roughness_source_menu(&mut harness, "png"); assert!(harness.query_by_label(&name).is_some(), "a decoded image is offered"); assert!(harness.query_by_label("broken.png").is_none(), "an image that did not decode is not"); @@ -131,7 +133,8 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.run_steps(30); harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); harness.run_steps(3); - harness.get_by_role_and_label(egui::Role::Button, &image_name).click(); + harness.event(egui::Event::Text("mask".into())); + harness.run_steps(2); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; @@ -148,14 +151,14 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { assert_eq!(harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").value().as_deref(), Some(image_name.as_str()), "the slot names the image"); harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); harness.run_steps(3); - harness.get_by_role_and_label(egui::Role::Button, "Uniform value").click(); + harness.run_steps(2); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { source: Source::Uniform(_), .. })); } -/// An image on a fill's Normal channel offers a DirectX toggle that flips its green. +/// An image on a fill's Normal channel offers OpenGL | DirectX in its Attributes; DirectX flips its green #[test] fn a_normal_image_can_be_marked_directx() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -169,9 +172,17 @@ fn a_normal_image_can_be_marked_directx() { h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); - h.get_by_label("DirectX normal map").scroll_to_me(); + click_node(&mut h, egui::Role::Tab, "Material"); + h.run_steps(3); + + // The normal image's convention sits in the slot's folded Attributes + h.get_by_role_and_label(egui::Role::Button, "Attributes").scroll_to_me(); + + // The scroll animates for about twenty frames h.run_steps(30); - h.get_by_label("DirectX normal map").click(); + click_node(&mut h, egui::Role::Button, "Attributes"); + h.run_steps(3); + click_node(&mut h, egui::Role::RadioButton, "DirectX"); h.run_steps(3); let LayerKind::Fill(fill) = &h.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; diff --git a/crates/ui-egui/tests/it/gradient_map_menu.rs b/crates/ui-egui/tests/it/gradient_map_menu.rs deleted file mode 100644 index a19e6cb5..00000000 --- a/crates/ui-egui/tests/it/gradient_map_menu.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! The Gradient Map item of a fill's Base color source menu turns color stops on and off. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_engine::core::{Channel, LayerId, LayerKind}; -use texturecraft_ui_egui::TextureCraftApp; - -/// The Base color channel's name in Properties (the rightmost "Base color" label). -fn base_color<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - h.get_all_by_label("Base color").max_by(|a, b| a.rect().right().total_cmp(&b.rect().right())).unwrap() -} - -/// Opens the Base color source menu and clicks its Gradient Map item. -fn click_gradient_map(h: &mut Harness<'_, TextureCraftApp>) { - base_color(h).scroll_to_me(); - - // The scroll animates for about twenty frames - h.run_steps(30); - let row = base_color(h).rect().center().y; - let menu = h.get_all_by_label(egui_phosphor::regular::DOTS_THREE).find(|n| (n.rect().center().y - row).abs() < 6.0).unwrap(); - let at = menu.rect().center(); - menu.click(); - h.run_steps(2); - - // The filter of the same name may show elsewhere (the shelf): the menu's item is the nearest - let item = h.get_all_by_label("Gradient Map").min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at))).unwrap(); - item.click(); - h.run_steps(3); -} - -fn ramp(h: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Vec<[f32; 3]> { - let LayerKind::Fill(fill) = &h.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; - fill.source(Channel::BaseColor).ramp().to_vec() -} - -#[test] -fn the_base_color_menu_turns_a_procedural_gradient_map_on_and_off() { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let out = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - let layer = LayerId(out["layer"].as_u64().unwrap()); - let set = json!({"layer": layer.0, "channel": "baseColor", "procedural": "Clouds", "low": [0.0, 0.25, 0.5], "high": [1.0, 0.75, 0.5]}); - texturecraft_engine::execute(&mut session, "layer.fill.set", &set).unwrap(); - let mut h = 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 - h.state_mut().ui.prefs.language = "en".into(); - h.run_steps(4); - - // The stops start at low, halfway and high, so the fill looks the same until they change - click_gradient_map(&mut h); - assert_eq!(ramp(&h, layer), vec![[0.0, 0.25, 0.5], [0.5; 3], [1.0, 0.75, 0.5]]); - click_gradient_map(&mut h); - assert!(ramp(&h, layer).is_empty(), "the item turns the stops off again"); -} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index e346617a..90f4c1d8 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -9,6 +9,8 @@ use texturecraft_engine::core::{Channel, LayerId}; use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; +use crate::SETTLE_FRAMES; + fn id(v: Value, key: &str) -> u64 { v[key].as_u64().unwrap() } @@ -413,3 +415,41 @@ fn alt_click_on_the_content_thumbnail_leaves_the_view_alone() { alt_click(&mut h, at); assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material); } + +/// Pointer moves of the opacity cell drag, one per frame +const OPACITY_DRAG_MOVES: usize = 4; + +/// How far left each move of the opacity cell drag goes, in points +const OPACITY_DRAG_STEP: f32 = 10.0; + +/// A drag on a row's opacity cell is one undo step, however many frames it spans +#[test] +fn dragging_a_row_opacity_adds_one_undo_step() { + let (mut h, layer) = harness(); + let row = h.get_by_label("Masked fill").rect(); + let cell = h.get_all_by_role(egui::accesskit::Role::SpinButton).map(|node| node.rect()).find(|cell| row.contains(cell.center())).unwrap(); + let opacity = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].blend(Channel::BaseColor).unwrap().opacity; + let (before, steps) = (opacity(&h), h.state().session.history_labels().len()); + + // A leftward drag lowers it from 100 %, a frame per move as a real drag arrives + let from = cell.center(); + h.hover_at(from); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + let step_left = |step: usize| from - egui::vec2(OPACITY_DRAG_STEP * step as f32, 0.0); + for step in 1..=OPACITY_DRAG_MOVES { + h.hover_at(step_left(step)); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { + pos: step_left(OPACITY_DRAG_MOVES), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(SETTLE_FRAMES); + + assert!(opacity(&h) < before, "the drag lowers the opacity: {}", opacity(&h)); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "every frame of the drag merges into one step"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index be8a4c26..8b642d36 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -26,13 +26,14 @@ mod export_settings; mod export_template_guards; mod file_dialogs; mod fill_channel_image; +mod fill_material_rows; mod fill_projection_rows; mod fill_support; mod fill_symmetry_rows; mod filter_picker; +mod filter_support; mod frame_selection; mod generator_panel; -mod gradient_map_menu; mod help_menu_664; mod history_panel; mod import_resources; @@ -60,6 +61,7 @@ mod popup_press_close; mod project_config; mod properties_min_width; mod properties_popup; +mod properties_scroll; mod rail; mod reference_order; mod rename_anchor; @@ -78,10 +80,12 @@ mod side_panels; mod skew_paint; mod smudge_channels; mod snapped_lines; +mod source_picker; mod split_divider; mod temp_dir; mod template_invert; mod templates_681; +mod tile_generator_panel; mod tool_availability; mod tool_settings_saved; mod toolbar; @@ -91,11 +95,9 @@ mod view2d_tiles; mod view_mode_picker; mod window_menu_684; -mod filter_support; mod stencil; mod symmetry; mod symmetry_2d; -mod tile_generator_panel; /// eframe's in-memory storage, shared by the tests that save and restore the UI state #[path = "../../src/ui_state_store/memory_storage.rs"] @@ -121,6 +123,40 @@ const SETTLE_FRAMES: usize = 3; /// Frames between the moves of a drag, and between a press and its release const DRAG_STEP_FRAMES: usize = 2; +/// Frames for an input that redraws Properties (another selection, source or operator) to show +const REDRAW_FRAMES: usize = 4; + +/// One wheel notch over the view, in points +const WHEEL_NOTCH: f32 = 60.0; + +/// How far left of a list's button a click lands, clear of the list and its popup +const OUTSIDE_OFFSET: f32 = 400.0; + +/// A Properties list that `open` opens (returning its button's rect) leaves the view its wheel, and closes on Escape and on a click outside +fn assert_list_leaves_the_wheel_and_closes(harness: &mut Harness<'_, TextureCraftApp>, open: impl Fn(&mut Harness<'_, TextureCraftApp>) -> egui::Rect) { + open(harness); + assert!(egui::Popup::is_any_open(&harness.ctx), "the list opens"); + let distance = harness.state().session.camera.distance; + harness.hover_at(harness.state().viewport_rect.center()); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, WHEEL_NOTCH), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(REDRAW_FRAMES); + assert_ne!(harness.state().session.camera.distance, distance, "the wheel over the view zooms with the list open"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(!egui::Popup::is_any_open(&harness.ctx), "Escape closes the list"); + + let button = open(harness); + click_at(harness, egui::pos2(button.min.x - OUTSIDE_OFFSET, button.min.y)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a click outside closes the list"); +} + /// Presses and releases the primary button at `at` without moving, as a pointer click does fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { harness.hover_at(at); @@ -132,6 +168,12 @@ fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { harness.run_steps(SETTLE_FRAMES); } +/// Clicks the middle of the widget with `role` and `label` through the pointer +fn click_widget(harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str) { + let at = harness.get_by_role_and_label(role, label).rect().center(); + click_at(harness, at); +} + /// The close button nearest the right of a docked panel's `title` (its tab or header title), on the same row fn panel_close_button(harness: &Harness<'_, TextureCraftApp>, title: egui::Rect) -> egui::Rect { harness diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 3ff215b7..d6db3fb2 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -29,6 +29,12 @@ const SELECT_FRAMES: usize = 3; /// Pointer moves a drag makes between its press and its release const DRAG_MOVES: usize = 4; +/// Frames for a scroll to a popup row to finish its animation +const SCROLL_FRAMES: usize = 25; + +/// How far left of the popup a click lands on the model +const MODEL_LEFT_OF_POPUP: f32 = 60.0; + fn harness() -> Harness<'static, TextureCraftApp> { harness_sized(WINDOW_SIZE) } @@ -214,11 +220,14 @@ fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_pane let symmetry = harness.get_all_by_role_and_label(Role::Tab, "Symmetry").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); click(&mut harness, PointerButton::Primary, symmetry); + let material = harness.get_all_by_role_and_label(Role::Tab, "Material").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); + click(&mut harness, PointerButton::Primary, material); harness.run_steps(JUMP_FRAMES); - assert!(is_open(&harness), "a tab click keeps it open"); assert!(!in_popup(&harness, "UV projection"), "the list jumped down to SYMMETRY"); assert!(tab_lit(&harness, popup, "Symmetry"), "the section in view is lit"); + assert!(!in_popup(&harness, "UV projection"), "the list jumped down to MATERIAL"); + assert!(tab_lit(&harness, popup, "Material"), "the section in view is lit"); assert!(!tab_lit(&harness, popup, "Fill")); assert!(tab_lit(&harness, docked, "Fill"), "the docked panel keeps its own place"); } @@ -235,3 +244,57 @@ fn bake_and_render_modes_never_open_it() { assert_eq!(harness.state().properties_popup, None, "{mode:?}"); } } + +#[test] +fn the_colour_picker_opened_in_the_popup_takes_its_presses_and_the_first_escape() { + let mut harness = harness(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2]})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let in_popup = |rect: egui::Rect| popup.x_range().contains(rect.center().x); + harness.get_all_by_role_and_label(Role::Button, "Base color").find(|node| in_popup(node.rect())).unwrap().scroll_to_me(); + + harness.run_steps(SCROLL_FRAMES); + let button = harness.get_all_by_role_and_label(Role::Button, "Base color").find(|node| in_popup(node.rect())).unwrap().rect(); + click(&mut harness, PointerButton::Primary, button.center()); + let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); + + click(&mut harness, PointerButton::Primary, title.center()); + assert!(is_open(&harness), "a press in the picker window stays in the popup"); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "and keeps the picker open"); + + harness.key_press(Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the first Escape closes the picker"); + assert!(is_open(&harness), "and leaves the popup open"); + harness.key_press(Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(!is_open(&harness), "the next Escape closes the popup"); +} + +#[test] +fn an_eyedropper_pick_from_the_popup_keeps_the_popup_open_for_its_colour() { + let mut harness = harness(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2]})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + 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 = |rect: egui::Rect| popup.x_range().contains(rect.center().x); + harness.get_all_by_role_and_label(Role::Button, "Pick color").find(|node| in_popup(node.rect())).unwrap().scroll_to_me(); + + harness.run_steps(SCROLL_FRAMES); + let button = harness.get_all_by_role_and_label(Role::Button, "Pick color").find(|node| in_popup(node.rect())).unwrap().rect(); + click(&mut harness, PointerButton::Primary, button.center()); + assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model"); + + // The model's middle, left of the popup + let model = egui::pos2(popup.left() - MODEL_LEFT_OF_POPUP, center.y); + click(&mut harness, PointerButton::Primary, model); + assert!(harness.state().picking_color.is_none(), "the click on the model picks"); + assert!(is_open(&harness), "and leaves the popup open for the picked colour"); +} diff --git a/crates/ui-egui/tests/it/properties_scroll.rs b/crates/ui-egui/tests/it/properties_scroll.rs new file mode 100644 index 00000000..e3c45785 --- /dev/null +++ b/crates/ui-egui/tests/it/properties_scroll.rs @@ -0,0 +1,193 @@ +//! The docked Properties list keeps its scroll place per layer: selecting another layer and coming back lands where it was; it scrolls +//! until its last section's top reaches the top of the list + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::{Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, REDRAW_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, click_widget}; + +/// Short enough that a fill's Properties scrolls +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1000.0); + +/// Tall enough that a fill's three sections fit in the list without scrolling +const TALL_WINDOW: egui::Vec2 = egui::vec2(1600.0, 2400.0); + +/// Short enough that a fill's MATERIAL section alone is taller than the list +const SHORT_WINDOW: egui::Vec2 = egui::vec2(1600.0, 600.0); + +/// Wheel steps, in points, and how many reach the end of any fill's list +const WHEEL_NOTCH: f32 = 120.0; +const WHEEL_NOTCHES_TO_END: usize = 40; + +/// Frames for the wheel's smoothed scroll to settle +const WHEEL_SETTLE_FRAMES: usize = 30; + +/// A row's height and the air under the last one: the most a list scrolled to its rows' end shows below them +const ROW_AND_AIR: f32 = 40.0; + +/// From the tab strip down into the list, where the wheel is turned +const INTO_LIST: f32 = 100.0; + +/// How far a hairline may sit from the list's top: it snaps to whole pixels, the list's top need not (the old jump was 4 px low) +const HAIRLINE_SNAP: f32 = 1.0; + +/// The app with two UV fills ("Fill A", "Fill B") and a folder ("Folder", a short panel), Fill A selected +fn harness() -> Harness<'static, TextureCraftApp> { + harness_sized(WINDOW_SIZE) +} + +/// [`harness`] in a window of `size` +fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "layer.add.group", &json!({"name": "Folder"})).unwrap(); + for name in ["Fill B", "Fill A"] { + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "layer.rename", &json!({"layer": layer, "name": name})).unwrap(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + } + + let mut harness = Harness::builder().with_size(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(STARTUP_FRAMES); + harness +} + +/// Selects the Layers panel row labelled `name` by clicking it +fn select_row(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + let at = harness.get_by_label(name).rect().center(); + click_at(harness, at); + harness.run_steps(REDRAW_FRAMES); +} + +/// Whether the docked jump tab `name` is the lit one, i.e. its section is in view +fn tab_lit(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + harness.get_by_role_and_label(Role::Tab, name).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn coming_back_to_a_layer_lands_where_its_properties_were_scrolled() { + lands_where_each_layer_was_scrolled(harness()); +} + +#[test] +fn a_greyed_polygon_fill_tool_keeps_each_layers_own_place() { + // Polygon fill can't fill a fill layer, so the layer's own sheet shows, and it keeps its own place as with any tool + let mut harness = harness(); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(REDRAW_FRAMES); + lands_where_each_layer_was_scrolled(harness); +} + +/// Scrolls Fill A down to MATERIAL, then checks a folder in between keeps it there and Fill B keeps its own place, the top +fn lands_where_each_layer_was_scrolled(mut harness: Harness<'_, TextureCraftApp>) { + select_row(&mut harness, "Fill A"); + assert!(tab_lit(&harness, "Fill"), "a fill never shown starts at the top"); + + click_widget(&mut harness, Role::Tab, "Material"); + harness.run_steps(REDRAW_FRAMES); + assert!(tab_lit(&harness, "Material"), "the jump scrolled down to MATERIAL"); + + select_row(&mut harness, "Folder"); + assert!(harness.query_by_role_and_label(Role::Tab, "Material").is_none(), "a folder shows no fill tabs"); + + select_row(&mut harness, "Fill A"); + assert!(tab_lit(&harness, "Material"), "Fill A is back where it was scrolled"); + assert!(!tab_lit(&harness, "Fill")); + + select_row(&mut harness, "Fill B"); + assert!(tab_lit(&harness, "Fill"), "another fill keeps its own place: the top"); +} + +/// Turns the wheel down over the docked list until it can scroll no further +fn wheel_to_end(harness: &mut Harness<'_, TextureCraftApp>) { + let strip = harness.get_by_role_and_label(Role::Tab, "Fill").rect(); + harness.hover_at(strip.center_bottom() + egui::vec2(0.0, INTO_LIST)); + for _ in 0..WHEEL_NOTCHES_TO_END { + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -WHEEL_NOTCH), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.step(); + } + harness.run_steps(WHEEL_SETTLE_FRAMES); +} + +/// Top of the docked list's `label` combo box (a fill's first row) +fn combo_top(harness: &Harness<'_, TextureCraftApp>, label: &str) -> f32 { + harness.get_by_role_and_label(Role::ComboBox, label).rect().top() +} + +/// Bottom of a new fill's last row: the Height source card's slider +fn last_row_bottom(harness: &Harness<'_, TextureCraftApp>) -> f32 { + harness.get_by_role_and_label(Role::Slider, "Height").rect().bottom() +} + +#[test] +fn a_list_whose_sections_all_fit_still_scrolls_its_last_section_to_the_top() { + let mut harness = harness_sized(TALL_WINDOW); + select_row(&mut harness, "Fill A"); + let list_top = harness.get_by_role_and_label(Role::Tab, "Fill").rect().bottom(); + assert!(last_row_bottom(&harness) < TALL_WINDOW.y, "every section fits in the list"); + + wheel_to_end(&mut harness); + assert!(tab_lit(&harness, "Material"), "the wheel brought MATERIAL to the top"); + assert!(!tab_lit(&harness, "Fill")); + assert!(combo_top(&harness, "UV projection") < list_top, "FILL scrolled out above the list"); + + select_row(&mut harness, "Folder"); + select_row(&mut harness, "Fill A"); + assert!(tab_lit(&harness, "Material"), "coming back keeps the place past the rows' end"); +} + +#[test] +fn a_last_section_taller_than_the_list_scrolls_to_its_real_end() { + let mut harness = harness_sized(SHORT_WINDOW); + select_row(&mut harness, "Fill A"); + let strip = harness.get_by_role_and_label(Role::Tab, "Fill").rect(); + let bar = harness.get_all_by_role(Role::ScrollBar).map(|bar| bar.rect()).find(|bar| bar.top() >= strip.top() && bar.left() > strip.left()); + let list_bottom = bar.unwrap().bottom(); + assert!(last_row_bottom(&harness) > SHORT_WINDOW.y, "the list's rows run below the window"); + + wheel_to_end(&mut harness); + let last_bottom = last_row_bottom(&harness); + assert!(tab_lit(&harness, "Material")); + assert!(last_bottom <= list_bottom, "the last row came into view"); + assert!(list_bottom - last_bottom < ROW_AND_AIR, "no blank space past a section taller than the list"); +} + +/// A jump tab lands its section's hairline on the list's top (egui's top-aligned scroll stopped one item spacing short, 4 px low) +#[test] +fn a_jump_lands_the_sections_hairline_on_the_lists_top() { + let mut harness = harness(); + select_row(&mut harness, "Fill A"); + + click_widget(&mut harness, Role::Tab, "Material"); + harness.run_steps(WHEEL_SETTLE_FRAMES); + + // The caption's clip is the list's view; its hairline is the last line drawn above it in that view + let shapes = &harness.output().shapes; + let caption = shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == "MATERIAL" => Some((clipped.clip_rect, text.pos.y)), + _ => None, + }); + let Some((list, caption_y)) = caption else { panic!("a MATERIAL caption") }; + let hairline = shapes + .iter() + .filter(|clipped| clipped.clip_rect == list) + .filter_map(|clipped| match &clipped.shape { + egui::Shape::LineSegment { points, .. } if points[0].y == points[1].y && points[0].y < caption_y => Some(points[0].y), + _ => None, + }) + .reduce(f32::max); + + assert!(hairline.is_some_and(|y| (y - list.top()).abs() < HAIRLINE_SNAP), "the hairline at {hairline:?}, the list's top at {}", list.top()); +} diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index f8ee1763..244c7f7b 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -208,7 +208,7 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { h.run_steps(3); let label = format!("Low / mask / {}", effect_name(&h, anchor)); - h.get_by_role_and_label(Role::Button, &label).click(); + h.get_by_role_and_label(Role::ListBoxOption, &label).click(); h.run_steps(3); let Source::Anchor { anchor: read, .. } = reader_source(&h, high) else { panic!("the fill reads an anchor: {:?}", reader_source(&h, high)) }; diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 40bfaa04..5613ca7d 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -47,11 +47,16 @@ fn pattern(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Procedura } } -/// Opens the mask fill's source picker from its Grayscale slot and clicks the tile labelled `tile` +/// Frames for a scroll to bring a control into view (it animates) +const SCROLL_FRAMES: usize = 25; + +/// Opens the mask fill's source picker from its Grayscale slot and clicks the tile labelled `tile`, scrolled into view first fn pick(harness: &mut Harness<'_, TextureCraftApp>, tile: &str) { harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); harness.run_steps(3); - harness.get_by_label(tile).click(); + harness.get_by_role_and_label(Role::ListBoxOption, tile).scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + harness.get_by_role_and_label(Role::ListBoxOption, tile).click(); harness.run_steps(3); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 01b2e2e2..3789cf98 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -23,8 +23,20 @@ fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { harness.run_steps(3); } +/// The lowest list showing `label`: Properties' (the Layers panel above it has a channel list showing "Base color" too) +fn lowest_list<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_all_by_role_and_label(egui::Role::ComboBox, label).max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() +} + fn save(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { harness.run_steps(6); + // Material orbs render off the UI thread: wait for their full pictures + let start = std::time::Instant::now(); + while !texturecraft_ui_egui::orb_previews::OrbPreviews::settled(&harness.ctx) && start.elapsed() < std::time::Duration::from_secs(20) { + std::thread::sleep(std::time::Duration::from_millis(10)); + harness.run_steps(1); + } + harness.run_steps(2); let img = harness.render().unwrap_or_else(|e| panic!("{name}: {e}")); let path = dir.join(format!("{name}.png")); img.save(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); @@ -786,53 +798,6 @@ fn i18n_snapshots() { texturecraft_ui_egui::i18n::set_language("en"); } -/// The merged effect panel selects an image and exposes its projection controls -#[test] -#[ignore] -fn mask_fill_image_snapshot() { - use serde_json::json; - use texturecraft_engine::{ - core::{EffectKind, LayerId, Source}, - execute, - }; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut png_bytes = Vec::new(); - image::RgbaImage::from_fn(16, 16, |x, y| { - let value = if (x / 4 + y / 4) % 2 == 0 { 255 } else { 32 }; - image::Rgba([value, value, value, 255]) - }) - .write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png) - .unwrap(); - let name = session.import_resource_bytes("Mask checker.png", png_bytes).unwrap(); - let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap()["layer"].as_u64().unwrap(); - execute(&mut session, "mask.add.black", &json!({})).unwrap(); - let effect = execute(&mut session, "effect.add.fill", &json!({"target": "mask", "value": 1.0})).unwrap()["effect"].as_u64().unwrap(); - execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(6); - - // The Grayscale slot opens the source picker; its search finds the image - harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); - harness.run_steps(3); - harness.event(egui::Event::Text("checker".into())); - harness.run_steps(3); - save(&mut harness, &output_dir, "mask-fill-image-menu"); - - harness.get_by_role_and_label(egui::Role::ListBoxOption, &name).click(); - harness.run_steps(4); - - let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; - assert_eq!(*source, Source::image(name)); - assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); - - save(&mut harness, &output_dir, "mask-fill-image-selected"); -} - /// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered #[test] #[ignore] @@ -862,35 +827,6 @@ fn panel_header_snapshots() { save(&mut harness, &output_dir, "panel-header-close-hovered"); } -#[test] -#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn tile_generator_gradient_map_snapshot() { - use serde_json::json; - use texturecraft_engine::execute; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - execute( - &mut session, - "layer.fill.set", - &json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}), - ) - .unwrap(); - - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.dock.focus(Panel::Properties); - harness.run_steps(6); - harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me(); - harness.run_steps(30); - - assert!(harness.query_by_label_contains("Add color").is_some()); - save(&mut harness, &output_dir, "tile-generator-gradient-map"); -} - /// Edit > Settings: the three pages and a compact window at 150% scale #[test] #[ignore] @@ -1196,6 +1132,428 @@ fn fill_symmetry_snapshots() { save(&mut harness, &output_dir, "symmetry-uv"); } +/// A material link as MaterialCraft leaves it on a fill: three float inputs, a preset and five outputs (the maps stay the fill's own sources) +fn steel_painted_worn() -> texturecraft_engine::core::MaterialLink { + use serde_json::json; + use texturecraft_engine::core::{LinkParam, LinkPreset, MaterialLink}; + let float = |id: &str, label: &str, value: f32| LinkParam { + id: id.into(), + label: label.into(), + group: String::new(), + value: json!({"t": "float", "v": value}), + default: json!({"t": "float", "v": 0.5}), + min: 0.0, + max: 1.0, + options: Vec::new(), + }; + MaterialLink { + name: "Steel Painted Worn".into(), + package: String::new(), + graph: "main".into(), + params: vec![float("wear", "Wear", 0.55), float("hue", "Paint hue", 0.3), float("dirt", "Dirt", 0.2)], + presets: vec![LinkPreset { name: "Fresh paint".into(), values: Default::default() }], + inputs: Vec::new(), + size: 1024, + resolution: None, + mapping: Default::default(), + outputs: ["baseColor", "metallic", "roughness", "normal", "height"].map(|output| (output.to_owned(), format!("steel_{output}.png"))).into(), + } +} + +/// Screen 04: the colour picker window open on a uniform base colour with five swatches, its close, a slider, a swatch and + hovered, a swatch's menu, with its lists open (a hovered option previews nothing), in RGB and resized from its top left corner; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn fill_color_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let orange = [0xE5, 0x8A, 0x4E].map(|c| texturecraft_engine::texel::srgb_to_linear(f32::from(c as u8) / 255.0)); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": orange})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": layer, "channel": "height", "enabled": true})).unwrap(); + for swatch in ["#E58A4E", "#BEBEBE", "#3C4046", "#7A7AF5", "#B0623A"] { + execute(&mut session, "swatch.add", &json!({"color": swatch})).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + + // The tab scrolls the panel to its section (the scroll animates for about twenty frames) + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "picker-open"); + let title = harness.get_by_role_and_label(egui::Role::TitleBar, "Base color").rect(); + harness.hover_at(egui::pos2(title.right() + 6.0, title.center().y)); + save(&mut harness, &output_dir, "picker-close-hover"); + harness.get_by_role_and_label(egui::Role::Slider, "S").hover(); + save(&mut harness, &output_dir, "picker-hover"); + harness.get_by_role_and_label(egui::Role::Button, "#7A7AF5").hover(); + save(&mut harness, &output_dir, "picker-swatch-hover"); + harness.get_by_role_and_label(egui::Role::Button, "Add swatch").hover(); + harness.run_steps(30); + save(&mut harness, &output_dir, "picker-add-hover"); + let chip = harness.get_by_role_and_label(egui::Role::Button, "#7A7AF5").rect().center(); + harness.hover_at(chip); + harness.run_steps(1); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: chip, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Button, "Remove swatch").hover(); + save(&mut harness, &output_dir, "picker-swatch-menu"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ComboBox, "sRGB").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Linear").hover(); + save(&mut harness, &output_dir, "picker-space-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ComboBox, "HSV").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "RGB").hover(); + save(&mut harness, &output_dir, "picker-model-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "RGB").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "picker-rgb"); + + // The window stands at the screen's bottom here, so it grows from its top left corner + let corner = harness.get_by_role_and_label(egui::Role::TitleBar, "Base color").rect().left_top() + egui::vec2(2.0, 2.0); + let by = egui::vec2(-120.0, -90.0); + harness.hover_at(corner); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=4 { + harness.hover_at(corner + by * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: corner + by, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + save(&mut harness, &output_dir, "picker-resized"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("picker-resized-{name}")); + } + } +} + +/// Screen 04: a fill's Material section in Channels (a procedural base colour with its Attributes open, a uniform metallic, a normal image, a signed height), its source list open with a hover, the picker on the base colour, the Material side of a plain fill (no material, its material list open with a hover, Copper picked; Copper also in the dark and light themes) and of a linked material; the linked one also in the dark and light themes +#[test] +#[ignore] +fn fill_material_snapshots() { + use serde_json::json; + use texturecraft_engine::core::{LayerId, LayerKind}; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + image::RgbaImage::from_fn(16, 16, |x, y| image::Rgba([110 + (x * 8) as u8, 110 + (y * 8) as u8, 250, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let normal = session.import_resource_bytes("bricks_normal.png", png).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.55, 0.2, 0.08]})).unwrap()["layer"].as_u64().unwrap(); + for settings in [ + json!({"channel": "basecolor", "procedural": "Clouds", "low": [0.3, 0.08, 0.02], "high": [0.7, 0.3, 0.12]}), + json!({"channel": "normal", "enabled": true}), + json!({"channel": "normal", "image": normal}), + json!({"channel": "height", "enabled": true}), + ] { + let mut settings = settings; + settings["layer"] = json!(layer); + execute(&mut session, "layer.fill.set", &settings).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + save(&mut harness, &output_dir, "material-channels"); + + // The orb follows the Layers panel's channel list: its list open, then one channel alone each + harness.get_all_by_role_and_label(egui::Role::ComboBox, "Material").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-ball-list"); + harness.key_press(egui::Key::Escape); + for channel in [texturecraft_engine::core::Channel::BaseColor, texturecraft_engine::core::Channel::Normal, texturecraft_engine::core::Channel::Height] { + harness.state_mut().ui.layer_material_view = false; + harness.state_mut().ui.layer_channel = channel; + save(&mut harness, &output_dir, &format!("material-ball-{}", channel.id())); + } + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("material-ball-height-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::default(); + } + harness.state_mut().ui.layer_material_view = true; + + // The Base color slot (the lowest "Base color" list: the Layers panel has one too) with its list open + lowest_list(&harness, "Base color").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Perlin noise").hover(); + save(&mut harness, &output_dir, "material-source-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_all_by_role_and_label(egui::Role::Button, "Attributes").next().unwrap().click(); + save(&mut harness, &output_dir, "material-attributes"); + harness.get_all_by_role_and_label(egui::Role::Button, "Attributes").next().unwrap().click(); + harness.run_steps(2); + harness.get_all_by_role_and_label(egui::Role::Button, "Invert").next().unwrap().hover(); + save(&mut harness, &output_dir, "material-invert-hover"); + + // The procedural slot's Resolution: one row in its card, its one list holding the Relative factors and the Fixed sizes + let texture_set = harness.state().session.doc.project.texture_sets[0].resolution; + let resolution = format!("Texture set · {texture_set}"); + harness.get_by_role_and_label(egui::Role::ComboBox, &resolution).click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "1024 × 1024").hover(); + save(&mut harness, &output_dir, "material-procedural-resolution-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + + // The same plain fill on the Material side: one whole material, picked from the card's list + harness.get_by_role_and_label(egui::Role::RadioButton, "Material").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-whole-none"); + harness.get_by_role_and_label(egui::Role::ComboBox, "None").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Copper").hover(); + save(&mut harness, &output_dir, "material-whole-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Copper").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::RadioButton, "Channels").hover(); + save(&mut harness, &output_dir, "material-whole-copper"); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("material-whole-copper-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.get_by_role_and_label(egui::Role::RadioButton, "Channels").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-whole-copper-channels"); + harness.get_by_role_and_label(egui::Role::RadioButton, "Material").click(); + harness.run_steps(2); + + // Back to the fill the linked shots below expect (the pick was one undo step) + execute(&mut harness.state_mut().session, "edit.undo", &json!({})).unwrap(); + + let session = &mut harness.state_mut().session; + if let Some(LayerKind::Fill(fill)) = session.doc.project.layers.get_mut(&LayerId(layer)).map(|layer| &mut layer.kind) { + fill.link = Some(Box::new(steel_painted_worn())); + } + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + save(&mut harness, &output_dir, "material-linked"); + + // The bands sit below the panel's fold: scroll each control into view (the scroll animates for about twenty frames) + let reach = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(25); + }; + + // The band is folded by the time it is reached in this run: unfold it first + if harness.query_by_role_and_label(egui::Role::ComboBox, "normal").is_none() { + reach(&mut harness, egui::Role::Button, "Channels mapping"); + harness.get_by_role_and_label(egui::Role::Button, "Channels mapping").click(); + harness.run_steps(2); + } + reach(&mut harness, egui::Role::ComboBox, "normal"); + harness.get_by_role_and_label(egui::Role::ComboBox, "roughness").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "normal").hover(); + save(&mut harness, &output_dir, "material-mapping-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + reach(&mut harness, egui::Role::Button, "Resolution"); + save(&mut harness, &output_dir, "material-resolution-folded"); + harness.get_by_role_and_label(egui::Role::Button, "Resolution").click(); + harness.run_steps(2); + reach(&mut harness, egui::Role::ComboBox, "Texture set · 256"); + save(&mut harness, &output_dir, "material-resolution"); + harness.get_by_role_and_label(egui::Role::ComboBox, "Texture set · 256").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "×2 · 512").hover(); + save(&mut harness, &output_dir, "material-resolution-relative-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::RadioButton, "Fixed").click(); + harness.run_steps(2); + + // This link has no package, so the re-cook fails with a toast over the panel + harness.state_mut().toasts.clear(); + harness.get_by_role_and_label(egui::Role::ComboBox, "256 × 256").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "1024 × 1024").hover(); + save(&mut harness, &output_dir, "material-resolution-fixed-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Button, "Resolution").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-resolution-fixed-folded"); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("material-linked-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.get_by_role_and_label(egui::Role::RadioButton, "Channels").click(); + save(&mut harness, &output_dir, "material-linked-channels"); +} + +/// The armed eyedropper is the pointer over the panels too, its tip on the hovered pixel +#[test] +#[ignore] +fn eyedropper_pointer_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + + // A light and a dark model: the disc's white outline and faint dark ring must read on both + for (name, color) in [("light", [0.92, 0.92, 0.9]), ("dark", [0.01, 0.01, 0.012])] { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": color})).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.prefs.language = "en".into(); + + // Only the app's own pointer shows, not the test's stand-in arrow + harness.set_render_cursor(false); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(3); + harness.get_all_by_role_and_label(egui::Role::Button, "Pick color").next().unwrap().click(); + harness.run_steps(3); + harness.hover_at(egui::pos2(520.0, 430.0)); + harness.run_steps(2); + save(&mut harness, &output_dir, &format!("eyedropper-over-{name}-model")); + if name == "light" { + let over_panel = harness.get_by_role_and_label(egui::Role::Tab, "Material").rect().center(); + harness.hover_at(over_panel); + harness.run_steps(2); + save(&mut harness, &output_dir, "eyedropper-over-properties"); + harness.hover_at(egui::pos2(1590.0, 300.0)); + harness.run_steps(2); + save(&mut harness, &output_dir, "eyedropper-at-right-edge"); + harness.hover_at(egui::pos2(12.0, 950.0)); + harness.run_steps(2); + save(&mut harness, &output_dir, "eyedropper-at-bottom-left-corner"); + } + } +} + +/// Gives the shelf thumbnails rendered off the UI thread time to arrive +fn settle_thumbnails(h: &mut Harness<'_, TextureCraftApp>) { + for _ in 0..100 { + std::thread::sleep(std::time::Duration::from_millis(20)); + h.run_steps(1); + } +} + +/// The channel source picker opened from each kind of source, searching, on Anchor points, and the filter picker in the same style +#[test] +#[ignore] +fn source_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + let rust = image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba([150 + ((x * 7 + y * 3) % 60) as u8, 70 + ((x * y) % 40) as u8, 30, 255])); + rust.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let rust = session.import_resource_bytes("rust_albedo.png", png).unwrap(); + let below = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "effect.add.anchor", &json!({"layer": below, "name": "Edge wear"})).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.45, 0.13, 0.05]})).unwrap()["layer"].clone(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(3); + + let shot = |harness: &mut Harness<'_, TextureCraftApp>, mut source: serde_json::Value, hover: Option<&str>, search: Option<&str>, name: &str| { + source["layer"] = layer.clone(); + source["channel"] = json!("baseColor"); + execute(&mut harness.state_mut().session, "layer.fill.set", &source).unwrap(); + harness.run_steps(3); + lowest_list(harness, "Base color").click(); + harness.run_steps(30); + if let Some(text) = search { + harness.event(egui::Event::Text(text.into())); + harness.run_steps(3); + } + settle_thumbnails(harness); + if let Some(label) = hover { + let at = harness.get_by_role_and_label(egui::Role::ListBoxOption, label).rect().center(); + harness.hover_at(at); + } + save(harness, &output_dir, name); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + }; + shot(&mut harness, json!({"color": [0.45, 0.13, 0.05]}), Some("Grunge"), None, "source-picker-top"); + shot(&mut harness, json!({"image": rust}), Some("Import..."), None, "source-picker-textures"); + shot(&mut harness, json!({"alpha": "scratches"}), Some("Cracks"), None, "source-picker-alphas"); + shot(&mut harness, json!({"alpha": "letter_y"}), None, None, "source-picker-end"); + shot(&mut harness, json!({"color": [0.45, 0.13, 0.05]}), None, Some("scr"), "source-picker-search"); + + // Anchor points on the Roughness slot, scrolled into view first + harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness").scroll_to_me(); + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Tab, "Anchor points").click(); + harness.run_steps(3); + let anchor = harness.get_all_by_role(egui::Role::ListBoxOption).next().unwrap().rect().center(); + harness.hover_at(anchor); + save(&mut harness, &output_dir, "source-picker-anchors"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The picked procedural's card, then the three themes with the picker open from Uniform + execute(&mut harness.state_mut().session, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "procedural": "Clouds", "scale": 4.0})) + .unwrap(); + save(&mut harness, &output_dir, "source-picker-picked"); + execute(&mut harness.state_mut().session, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "color": [0.45, 0.13, 0.05]})).unwrap(); + harness.run_steps(3); + lowest_list(&harness, "Base color").click(); + settle_thumbnails(&mut harness); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("source-picker-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The filter picker in the same style + let filter = execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let filter = texturecraft_engine::core::LayerId(filter["effect"].as_u64().unwrap()); + harness.state_mut().session.target = texturecraft_engine::StackTarget::Effect(filter); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::ComboBox, "Invert").click(); + settle_thumbnails(&mut harness); + let blur = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Blur").rect().center(); + harness.hover_at(blur); + save(&mut harness, &output_dir, "filter-picker-v4"); +} + /// The culling rows' i on a planar fill: each one hovered with its tooltip, in the medium theme, then the Depth culling one in the dark and light themes #[test] #[ignore] @@ -1299,6 +1657,48 @@ fn popup_tabs_snapshots() { } } +#[test] +#[ignore = "writes the material picker (Material mode) to TC_UI_SNAPSHOTS; run with --ignored"] +/// A whole-material fill's card opens the material picker: grouped under its categories, Copper chosen and Brass hovered, then a search +fn material_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.material", &json!({"layer": layer, "material": "copper"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Content; + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(4); + if harness.query_by_role_and_label(egui::Role::ComboBox, "Copper").is_none() { + harness.get_by_role_and_label(egui::Role::RadioButton, "Material").click(); + harness.run_steps(4); + } + harness.get_by_role_and_label(egui::Role::ComboBox, "Copper").click(); + harness.run_steps(30); + let brass = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Brass").rect().center(); + harness.hover_at(brass); + harness.run_steps(4); + save(&mut harness, &output_dir, "material-picker-open"); + harness.event(egui::Event::Text("steel".into())); + harness.run_steps(6); + save(&mut harness, &output_dir, "material-picker-search"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(4); + save(&mut harness, &output_dir, &format!("material-picker-search-{name}")); + } + } +} + /// The Properties panel at its minimum width (the right column dragged as narrow as it goes), on the Fill tab's widest row (3D projection settings) and on a filter #[test] #[ignore] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bd11cb2d..bc2cc695 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -560,6 +560,50 @@ and Height are shaded on a lit neutral material in the 3D view. `viewport.nextCh the shading uses (mesh normal, Height channel slope and Normal channel), unlit; the 2D view shows its tangent-space form. +## Colour swatches + +The project's swatches (`Project.swatches`, linear RGB, stored in the `.tcraft` file; projects without any +save none) are the Swatches row under the colour picker. `swatch.list` lists them, `swatch.add {color}` +(`[r, g, b]` linear or `"#rrggbb"`, clamped to 0..1, at most 64) adds one at the end and +`swatch.remove {index}` removes one; `project.inspect` shows them as `swatches`. Applying a swatch is an +ordinary colour edit (`layer.fill.set {color}`). + +## A fill's whole material + +A fill layer or content fill effect can hold one built-in plain material whole (the Material side of +its Material section). `layer.fill.material {layer? | effect?, material}` sets every channel the +material writes from it, turns those channels on and the others off, and keeps the fill's projection; +`material: null` returns the channels to their defaults (a content fill effect keeps the channels it +changes, at their defaults); setting what the fill already holds adds no undo step. Smart materials (folders of layers) are added +with `material.apply` instead. The fill remembers the material (`Fill.material`, saved only when set; +`project.inspect` shows it as `material`) until a channel's source is set on its own with +`layer.fill.set`. A plain material added from the shelf names its fill the same way. + +## Folders, effect blending and masks + +- `folder.contents.set {layer?, scale?, rotation?}` lays a Scale (multiplying every fill's tiling inside) + and a Rotation (degrees added to every fill's angle) on a folder's contents, never written into the fills; + `folder.contents.reset {layer?}` drops them and puts back the seeds `folder.randomizeSeeds {layer?}` changed. + `folder.randomizeSeeds` gives every pattern, generator and noise filter inside a new seed (seeds that were + equal stay equal) and returns `{seeds}`, how many changed. +- `effect.blending.modeToEveryChannel`, `opacityToEveryChannel` and `bothToEveryChannel {effect?, channel?}` + give every channel of a content effect one channel's blend mode, opacity or both; `effect.blending.copy` + and `effect.blending.paste {effect?}` carry every channel's blending between effects (a mask effect takes + the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending and + `effect.set {effect, channels: {roughness: false}}` switches a content effect's channels on or off. +- `mask.add.bitmap {layer?, image | alpha, projection?}` adds a mask fill reading an image's gray; + `effect.set {effect, idMap: image resource | null}` gives a colour selection its own ID map in place of + the baked one; `tool.material {maskImage: image resource | null}` paints an image's gray into masks. +- `effect.add.colorSelection {layer?, color?, tolerance?}` and `mask.add.heightCombination {layer?}` add a + colour selection or a compare mask (this layer's height against the layers below) to a layer's mask, + making the mask first when it has none; both return `{effect}`. +- `effect.filter.restoreDefaults {effect?}` puts a filter's parameters back to its defaults (name, + channels and blending stay) and returns `{changed}`. +- `layer.fill.resetProjection {layer? | effect?}` puts the Fill section back to a new fill's (same + projection kind; a placed frame, the symmetry and the sources stay); `layer.fill.resetFrame` puts a + warp's frame back around the mesh with its corners unpulled. Each is one undo step, or none when + nothing changes. + ## MaterialCraft materials A v3 `.mcmat` holds a published SBS graph and its source assets. TextureCraft uses the shared `craft-mcmat` reader and cooks the archive through `materialcraft-cli`. The resulting fill stores its channel textures and the original archive in the project. Linked cooks use the Settings percentage of available RAM. A cook that exceeds the estimated budget reports the required and configured byte counts without replacing the current fill. Its exposed values, presets and mesh-map inputs appear in `project.inspect`. Republish older MCMAT files from their original authoring project. Procedural imports and re-cooks require the desktop CLI. Saved projects retain their baked maps for use in the browser. @@ -573,7 +617,9 @@ operation returns a busy error and can be retried. | `material.load` | `{path, above?, inside?, index?}`: `.tcmat`, `.mcmat` or `.mcraft` (cooked first) | | `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` | | `material.link.preset` | `{layer?, name, cook?: true}` | -| `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) | +| `material.link.map` | `{layer?, channel, output}`: the channel reads another output of the material | +| `material.link.resolution` | `{layer?, relative: -3..3 \| fixed: 128..8192, cook?: true}`: the size the material cooks at | +| `material.link.cook` | `{layer?}`: re-cook at its picked resolution (default: the texture set's) with its baked mesh maps (after a bake or a resize) | | `material.link.saveSource` | `{layer?, path}`: the original linked source with its `.mcmat`, `.mcraft` or `.sbs` extension | For a 1024-pixel texture set, TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size 1024x1024` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The desktop worker decodes the returned maps before installing the fill at its original drop target. The executable is resolved from From ef3ab0324348a805d756cdf649dad45cc439ce38 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:47 +0000 Subject: [PATCH 026/153] Masks: Mask Fill with a fill layer's Properties and the Grayscale paint tab --- crates/engine/src/mask_cmds.rs | 302 +++++++++++++++------ crates/engine/tests/it/mask_fill_source.rs | 164 +++++++++++ crates/ui-egui/src/mask_fill_panel.rs | 28 ++ crates/ui-egui/src/mask_paint_panel.rs | 86 ++++++ crates/ui-egui/src/mask_source_choice.rs | 9 + crates/ui-egui/tests/it/mask_fill_rows.rs | 175 ++++++++++++ 6 files changed, 683 insertions(+), 81 deletions(-) create mode 100644 crates/engine/tests/it/mask_fill_source.rs create mode 100644 crates/ui-egui/src/mask_fill_panel.rs create mode 100644 crates/ui-egui/src/mask_paint_panel.rs create mode 100644 crates/ui-egui/src/mask_source_choice.rs create mode 100644 crates/ui-egui/tests/it/mask_fill_rows.rs diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 98c8f906..44a81ea7 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,12 +2,14 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, + BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, + GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::layer_cmds::{projection_from, projection_from_fields}; +use crate::mask_owner::MaskOwner; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; @@ -20,7 +22,7 @@ pub fn specs() -> Vec { "Add mask with color selection", ["Layers", "Mask"], None, - "{layer?, color?: ID color as [r,g,b] linear or \"#rrggbb\" sRGB, tolerance?}", + "{layer?, color?: a first ID color as [r,g,b] linear or \"#rrggbb\" sRGB (default: none, pick them with effect.colorSelection.pick), tolerance?} → {effect} (in the layer's mask, a new black one if it has none; selected)", has_layer, add_color_mask ), @@ -58,7 +60,7 @@ pub fn specs() -> Vec { "Add levels", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, inLow?, inHigh?, gamma?, outLow?, outHigh?}", + "{layer?, target?: mask|content, name?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?: the one content channel it remaps (default baseColor; not normal maps, not on a mask), clamp?: values past the input handles stop at the output ends (default false)}", has_layer, add_levels ), @@ -76,7 +78,7 @@ pub fn specs() -> Vec { "Add compare mask", ["Layers", "Effects"], None, - "{layer?, name?, op?: lesser|within|greater, value?, tolerance?}", + "{layer?, name?, left?: layersBelow|thisLayer|thisMask|constant (default thisLayer), op?: lesser|within|greater (default greater), right? (default layersBelow), compareChannel? (default height), value?: the constant, tolerance?, hardness? (default 0.9)}", has_layer, add_compare ), @@ -85,7 +87,7 @@ pub fn specs() -> Vec { "Add anchor point", ["Layers", "Effects"], None, - "{layer?, target?: content|mask (content), name?} (on the content it records the stack up to this layer, in a mask the mask value at that point; fills, masks and generators above read it: effect.add.fill {anchor}, effect.add.generator {microAnchor})", + "{layer?, target?: content|mask (default content), name? (default the layer's name, \" mask\" in a mask)} (on the content it records the stack up to this layer, in a mask the mask value at that point: every channel reads that gray; fills, masks and generators above read it: effect.add.fill {anchor}, effect.add.generator {microAnchor})", has_layer, add_anchor ), @@ -114,7 +116,7 @@ pub fn specs() -> Vec { "Effect input histogram", [], None, - "{effect, channel?: for content effects (default: the layer's first channel), bins?: 2..256 (64)} → {target: mask|content, channel?, bins: [count per bucket over 0..1]}", + "{effect, channel?: for content effects (default: the channel a levels effect remaps, else the layer's first channel), bins?: 2..256 (64)} → {target: mask|content, channel?, bins: [count per bucket over 0..1], luminance?, components?: [red, green, blue] (a color channel), compare?: {left, right} (a compare mask: what each side reads)}", always, histogram ), @@ -141,16 +143,21 @@ fn add_mask(s: &mut Session, p: &Value, bg: MaskBackground) -> Result { } fn add_color_mask(s: &mut Session, p: &Value) -> Result { - let color = color_param("mask.add.colorSelection", p, "color")?.unwrap_or([1.0, 0.0, 0.0]); + push_own_mask_effect(s, p, color_selection("mask.add.colorSelection", p)?, "Add mask with color selection", |_| Ok(())) +} + +/// A colour selection with the `color` and `tolerance` params of command `cmd` +pub(crate) fn color_selection(cmd: &str, p: &Value) -> Result { + let colors: Vec<[f32; 3]> = color_param(cmd, p, "color")?.into_iter().collect(); let tolerance = f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0); - with_mask(s, p, "mask.add.colorSelection", "Add mask with color selection", |s, id| { - let eid = s.doc.project.alloc_id(); - let l = s.doc.project.layer_mut(s.doc.project.mask_owner(id))?; - let m = l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)); - m.effects.push(Effect::new(eid, EffectKind::ColorSelection { colors: vec![color], tolerance })); - Ok(()) - })?; - Ok(Value::Null) + Ok(EffectKind::ColorSelection(ColorSelection::new(colors, tolerance))) +} + +/// `p` aimed at the layer's mask, whatever `target` it names +pub(crate) fn mask_target(p: &Value) -> Value { + let mut params = p.as_object().cloned().unwrap_or_default(); + params.insert("target".into(), json!("mask")); + Value::Object(params) } /// The mask layer `id` draws with (an instance's source's unless it has its own). @@ -232,38 +239,72 @@ fn name_param(p: &Value) -> Option<&str> { strp(p, "name").filter(|n| !n.trim().is_empty() && n.chars().count() <= 256) } -/// Add an effect to the selected layer's mask (creating a mask if there is none) or, with -/// `target: "content"` or a content-only effect, to its content stack. +/// Add an effect to the selected layer's mask (creating a mask if there is none) or, with `target: "content"` or a content-only effect, to its content stack fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) -> Result { + let label = format!("Add {}", kind.name().to_ascii_lowercase()); + push_effect_as(s, p, kind, blend, &label) +} + +/// [`push_effect`] as the undo step `label` +pub(crate) fn push_effect_as(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode, label: &str) -> Result { + push_effect_in(s, p, kind, blend, label, |_| Ok(()), MaskOwner::Shared) +} + +/// An Add mask item's effect, `first` made in the same undo step: it goes in the layer's own mask, so an instance without one gets its own instead of changing its source's +pub(crate) fn push_own_mask_effect(s: &mut Session, p: &Value, kind: EffectKind, label: &str, first: impl FnOnce(&mut Session) -> Result<()>) -> Result { + push_effect_in(s, &mask_target(p), kind, BlendMode::Normal, label, first, MaskOwner::Own) +} + +/// [`push_effect_as`] into `owner`'s mask, making the change `first` in the same undo step before adding the effect +fn push_effect_in( + s: &mut Session, + p: &Value, + mut kind: EffectKind, + blend: BlendMode, + label: &str, + first: impl FnOnce(&mut Session) -> Result<()>, + owner: MaskOwner, +) -> Result { let content = kind.content_only() == Some(true) || content_target(p, "effect.add")?; - if kind.content_only().is_some_and(|c| c != content) { + if kind.content_only().is_some_and(|content_only| content_only != content) { return Err(bad("effect.add", format!("{} effects go on masks, not on layer content", kind.name()))); } - let label = format!("Add {}", kind.name().to_ascii_lowercase()); - let eid = with_mask(s, p, "effect.add", &label, |s, id| { - let eid = s.doc.project.alloc_id(); + if let EffectKind::Levels(levels) = &mut kind { + levels_target(levels, content)?; + } + let new_effect = with_mask(s, p, "effect.add", label, |s, id| { + first(s)?; + let new_effect = s.doc.project.alloc_id(); - // An instance's content and inherited mask belong to its source - let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) }; - let l = s.doc.project.layer_mut(id)?; - let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; - let mut e = Effect::new(eid, kind); - e.blend = blend; - if let Some(n) = name_param(p) { - e.name = n.to_string(); + // An instance's content and (unless it has its own) mask belong to its source + let id = match (content, owner) { + (true, _) => s.doc.project.content_layer(id).map_or(id, |source| source.id), + (false, MaskOwner::Own) => id, + (false, MaskOwner::Shared) => s.doc.project.mask_owner(id), + }; + let layer = s.doc.project.layer_mut(id)?; + let background = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. } | EffectKind::ColorSelection(_)) { + MaskBackground::Black + } else { + MaskBackground::White + }; + let mut effect = Effect::new(new_effect, kind); + effect.blend = blend; + if let Some(name) = name_param(p) { + effect.name = name.to_string(); } if !content { - l.mask.get_or_insert_with(|| Mask::new(bg)).effects.push(e); - } else if l.is_group() { - return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", l.name))); + layer.mask.get_or_insert_with(|| Mask::new(background)).effects.push(effect); + } else if layer.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", layer.name))); } else { - l.content_effects.push(e); + layer.content_effects.push(effect); } - s.target = StackTarget::Effect(eid); - Ok(eid) + s.target = StackTarget::Effect(new_effect); + Ok(new_effect) })?; - Ok(json!({ "effect": eid.0 })) + Ok(json!({ "effect": new_effect.0 })) } /// A source reading anchor point `anchor` for layer `reader`: the anchor must sit on a layer @@ -409,12 +450,18 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S Ok(weights) } -/// An anchor point on the layer content by default, preserving previous placement, or in its mask with `target: "mask"`. +/// An anchor point on the layer content by default, preserving previous placement, or in its mask with `target: "mask"`; named after the layer (" mask" in a mask) unless given a name fn add_anchor(session: &mut Session, params: &Value) -> Result { // Params may be null or an object without a target: both default to the content - let mut params = params.as_object().cloned().unwrap_or_default(); - params.entry("target").or_insert_with(|| json!("content")); - push_effect(session, &Value::Object(params), EffectKind::Anchor, BlendMode::Normal) + let content = strp(params, "target").is_none() || content_target(params, "effect.add.anchor")?; + let mut fields = params.as_object().cloned().unwrap_or_default(); + fields.insert("target".into(), json!(if content { "content" } else { "mask" })); + if name_param(params).is_none() { + let layer = session.doc.project.layer(layer_param(session, "effect.add.anchor", params)?)?; + let name = if content { layer.name.clone() } else { format!("{} mask", layer.name) }; + fields.insert("name".into(), json!(name)); + } + push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal) } /// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer @@ -493,24 +540,55 @@ fn add_generator(session: &mut Session, params: &Value) -> Result { push_effect(session, params, EffectKind::Generator(generator), blend) } -pub(crate) fn levels_from(p: &Value, l: &mut Levels) { - for (k, slot) in [("inLow", &mut l.in_low), ("inHigh", &mut l.in_high), ("gamma", &mut l.gamma), ("outLow", &mut l.out_low), ("outHigh", &mut l.out_high)] { - if let Some(v) = f32p(p, k) { - *slot = if k == "gamma" { v.clamp(0.01, 10.0) } else { v.clamp(0.0, 1.0) }; +pub(crate) fn levels_from(cmd: &str, p: &Value, levels: &mut Levels) -> Result<()> { + let slots = [ + ("inLow", &mut levels.in_low), + ("inHigh", &mut levels.in_high), + ("gamma", &mut levels.gamma), + ("outLow", &mut levels.out_low), + ("outHigh", &mut levels.out_high), + ]; + for (key, slot) in slots { + if let Some(value) = f32p(p, key) { + let range = if key == "gamma" { Levels::GAMMA_RANGE } else { 0.0..=1.0 }; + *slot = value.clamp(*range.start(), *range.end()); } } + if let Some(clamp) = boolp(p, "clamp") { + levels.clamp = clamp; + } + match channel_param(cmd, p, "affects")? { + // Levels pass normal maps through unchanged (`per_unit`) + Some(channel) if channel.kind() == ChannelKind::NormalMap => Err(bad(cmd, format!("levels cannot remap `{}`, a normal map", channel.id()))), + Some(channel) => { + levels.affects = Some(channel); + Ok(()) + } + None => Ok(()), + } +} + +/// A levels effect added to a mask remaps its one value; on the content it remaps Base color unless told otherwise +fn levels_target(levels: &mut Levels, content: bool) -> Result<()> { + if content { + levels.affects.get_or_insert(Channel::BaseColor); + } else if levels.affects.is_some() { + return Err(bad("effect.add", "a mask's levels remap its one value: leave out `affects`")); + } + Ok(()) } fn add_levels(s: &mut Session, p: &Value) -> Result { - let mut l = Levels::default(); - levels_from(p, &mut l); - push_effect(s, p, EffectKind::Levels(l), BlendMode::Normal) + let mut levels = Levels::default(); + levels_from("effect.add.levels", p, &mut levels)?; + push_effect(s, p, EffectKind::Levels(levels), BlendMode::Normal) } fn add_filter(s: &mut Session, p: &Value) -> Result { let id = strp(p, "filter").unwrap_or("invert"); let kind = crate::filter_lib::build(id, p)?; - // Library filters are named after their shelf entry (material finishes are fill effects). + + // Library filters are named after their shelf entry (material finishes are fill effects) let mut p = p.clone(); if name_param(&p).is_none() && let (Some(d), Some(o)) = (crate::filter_lib::find(id), p.as_object_mut()) @@ -521,18 +599,56 @@ fn add_filter(s: &mut Session, p: &Value) -> Result { } fn add_compare(s: &mut Session, p: &Value) -> Result { - let op = match strp(p, "op").unwrap_or("greater") { - "lesser" | "less" => CompareOp::LesserThan, - "within" => CompareOp::WithinTolerance, - "greater" => CompareOp::GreaterThan, - other => return Err(bad("effect.add.compare", format!("unknown op `{other}`"))), - }; - let kind = - EffectKind::Compare { op, value: f32p(p, "value").unwrap_or(0.5).clamp(0.0, 1.0), tolerance: f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0) }; + let mut kind = new_compare(); + compare_from("effect.add.compare", p, &mut kind)?; push_effect(s, p, kind, BlendMode::Normal) } -/// The `effect` param, or the selected effect. +/// A new compare mask: this layer's height over the layers below it, hardness 0.9 +pub(crate) fn new_compare() -> EffectKind { + EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.5, + tolerance: 0.1, + left: CompareSource::ThisLayer, + right: CompareSource::LayersBelow, + channel: Channel::Height, + hardness: 0.9, + } +} + +/// Apply the compare parameters of `p` to `kind` (a compare effect) +fn compare_from(cmd: &str, p: &Value, kind: &mut EffectKind) -> Result<()> { + let EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } = kind else { return Ok(()) }; + let named_source = |key: &str| -> Result> { + match strp(p, key) { + None => Ok(None), + Some(id) => CompareSource::from_id(id) + .map(Some) + .ok_or_else(|| bad(cmd, format!("unknown {key} source `{id}` (layersBelow, thisLayer, thisMask, constant)"))), + } + }; + if let Some(id) = strp(p, "op") { + *op = CompareOp::from_id(id).ok_or_else(|| bad(cmd, format!("unknown op `{id}`")))?; + } + if let Some(source) = named_source("left")? { + *left = source; + } + if let Some(source) = named_source("right")? { + *right = source; + } + if let Some(compared) = channel_param(cmd, p, "compareChannel")? { + *channel = compared; + } + for (key, slot) in [("value", value), ("tolerance", tolerance), ("hardness", hardness)] { + if let Some(number) = f32p(p, key) { + *slot = number.clamp(0.0, 1.0); + } + } + Ok(()) +} + +/// The `effect` param, or the selected effect pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result { match (u64p(p, "effect"), s.target) { (Some(e), _) => Ok(LayerId(e)), @@ -541,20 +657,43 @@ pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result { } } -/// The distribution of the values entering an effect (what a levels effect remaps). +/// Histogram bins when the call names none +const DEFAULT_HISTOGRAM_BINS: u64 = 64; + +/// The fewest and most histogram bins a call takes +const HISTOGRAM_BINS_RANGE: (u64, u64) = (2, 256); + +/// The distribution of the values entering an effect (what a levels effect remaps) fn histogram(s: &mut Session, p: &Value) -> Result { const CMD: &str = "effect.histogram"; - let eid = effect_id(s, p, CMD)?; - let (owner, _) = s.doc.project.effect(eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; - let l = s.doc.project.layer(owner)?; - let content = l.content_effects.iter().any(|e| e.id == eid); - let channel = match channel_param(CMD, p, "channel")? { - Some(c) => c, - None => l.channels.keys().next().copied().unwrap_or(Channel::BaseColor), + let effect = effect_id(s, p, CMD)?; + let (owner, found) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + let remapped = match &found.kind { + EffectKind::Levels(levels) => levels.affects, + _ => None, }; - let bins = u64p(p, "bins").unwrap_or(64).clamp(2, 256) as usize; - let counts = s.effect_histogram(eid, channel, bins).ok_or_else(|| bad(CMD, "the texture set is not ready"))?; - Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) + let layer = s.doc.project.layer(owner)?; + let content = layer.content_effects.iter().any(|candidate| candidate.id == effect); + let channel = match channel_param(CMD, p, "channel")? { + Some(channel) => channel, + None => remapped.or_else(|| layer.channels.keys().next().copied()).unwrap_or(Channel::BaseColor), + }; + let (fewest_bins, most_bins) = HISTOGRAM_BINS_RANGE; + let bins = u64p(p, "bins").unwrap_or(DEFAULT_HISTOGRAM_BINS).clamp(fewest_bins, most_bins) as usize; + let counts = s.effect_histogram(effect, channel, bins).ok_or_else(|| bad(CMD, "the texture set is not ready"))?; + if !content { + let mut out = json!({"target": "mask", "bins": counts.all}); + if let Some([left, right]) = s.compare_histograms(effect, bins) { + out["compare"] = json!({"left": left, "right": right}); + } + return Ok(out); + } + + let mut out = json!({"target": "content", "channel": channel.id(), "bins": counts.all, "luminance": counts.luminance}); + if !counts.components.is_empty() { + out["components"] = json!(counts.components); + } + Ok(out) } /// Edit visibility, blending, name, effect parameters, or a filter's type @@ -569,6 +708,15 @@ fn set(session: &mut Session, params: &Value) -> Result { GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`"))) }) .transpose()?; + let channel = channel_param(CMD, params, "channel")?; + let on_mask = crate::effect_blending_cmds::on_mask(&session.doc.project, effect); + if channel.is_some() && on_mask { + return Err(bad(CMD, "a mask effect blends one channel: leave out `channel`")); + } + + if on_mask && params.get("affects").is_some() { + return Err(bad(CMD, "a mask's levels remap its one value: leave out `affects`")); + } // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one let anchor = match session.doc.project.effect(effect) { @@ -614,6 +762,7 @@ fn set(session: &mut Session, params: &Value) -> Result { None => None, }; let swaps_filter = swapped.is_some(); + let id_map = crate::color_selection_cmds::id_map_param(session, params)?; let mesh = session.mesh.clone(); session.edit("Edit effect", |session| { @@ -630,12 +779,7 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(visible) = boolp(params, "visible") { edited.visible = visible; } - if let Some(blend) = blend { - edited.blend = blend; - } - if let Some(opacity) = f32p(params, "opacity") { - edited.opacity = opacity.clamp(0.0, 1.0); - } + crate::effect_blending_cmds::set_blending(edited, channel, blend, f32p(params, "opacity")); if let Some(name) = name_param(params) { edited.name = name.to_string(); } @@ -665,7 +809,7 @@ fn set(session: &mut Session, params: &Value) -> Result { } } _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), - EffectKind::Levels(levels) => levels_from(params, levels), + EffectKind::Levels(levels) => levels_from(CMD, params, levels)?, // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} @@ -698,12 +842,8 @@ fn set(session: &mut Session, params: &Value) -> Result { // Preserve projection fields that the edit does not supply *projection = projection_from(&placement, CMD, Some(&*projection), || crate::warp_cmds::fitted_frame(&mesh))?; } - EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, - EffectKind::Compare { tolerance, .. } => { - if let Some(value) = f32p(params, "tolerance") { - *tolerance = value.clamp(0.0, 1.0); - } - } + EffectKind::ColorSelection(selection) => crate::color_selection_cmds::apply_params(params, selection, id_map)?, + kind @ EffectKind::Compare { .. } => compare_from(CMD, params, kind)?, _ => {} } diff --git a/crates/engine/tests/it/mask_fill_source.rs b/crates/engine/tests/it/mask_fill_source.rs new file mode 100644 index 00000000..71ad1384 --- /dev/null +++ b/crates/engine/tests/it/mask_fill_source.rs @@ -0,0 +1,164 @@ +//! A mask fill effect edited through the `layer.fill.*` commands like any fill: its one grayscale source, its projection and its symmetry + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, LayerId, OutputResolution, Procedural, ProceduralKind, Projection, Source}; +use texturecraft_engine::fill_alpha::resource_name; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::paint::alphas; +use texturecraft_engine::{Session, execute}; + +/// A paint layer whose mask holds one fill effect, and that effect +fn mask_fill() -> (Session, LayerId, LayerId) { + mask_fill_on(128) +} + +/// [`mask_fill`] on a texture set `size` texels across +fn mask_fill_on(size: u32) -> (Session, LayerId, LayerId) { + let mut s = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, size).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + let effect = LayerId(execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap()); + (s, layer, effect) +} + +fn source(s: &Session, effect: LayerId) -> Source { + match &s.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Fill { source, .. } => source.clone(), + other => panic!("not a mask fill: {other:?}"), + } +} + +fn projection(s: &Session, effect: LayerId) -> Projection { + match &s.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Fill { projection, .. } => projection.clone(), + other => panic!("not a mask fill: {other:?}"), + } +} + +/// Mask values along the texture's diagonal +fn mask_line(s: &Session, layer: LayerId) -> Vec { + let texels: Vec<(u32, u32)> = (0..16).map(|i| (i * 8 + 3, i * 8 + 5)).collect(); + s.mask_at(layer, &texels).unwrap() +} + +#[test] +fn a_mask_fill_takes_a_procedural_an_image_an_alpha_or_a_value_as_its_one_grayscale_source() { + let (mut s, layer, effect) = mask_fill(); + let kind = ProceduralKind::ALL[0]; + + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": kind.label(), "scale": 4.0})).unwrap(); + let Source::Procedural { pattern, low, high, .. } = source(&s, effect) else { panic!("not a procedural: {:?}", source(&s, effect)) }; + assert_eq!((pattern.kind, pattern.scale, low, high), (kind, 4.0, [0.0; 3], [1.0; 3])); + let line = mask_line(&s, layer); + assert!(line.iter().any(|value| (value - line[0]).abs() > 1e-3), "the mask follows the pattern: {line:?}"); + + // A parameter alone keeps the rest of the pattern + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": kind.label(), "contrast": 1.5})).unwrap(); + let Source::Procedural { pattern, .. } = source(&s, effect) else { panic!("not a procedural") }; + assert_eq!((pattern.scale, pattern.contrast), (4.0, 1.5)); + + let scratches = alphas::find("scratches").unwrap(); + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "alpha": "scratches"})).unwrap(); + assert_eq!(source(&s, effect), Source::image(resource_name(scratches))); + assert!(s.doc.resources.contains_key(&resource_name(scratches))); + + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 0.25})).unwrap(); + assert_eq!(source(&s, effect), Source::Uniform([0.25; 3])); + assert!(mask_line(&s, layer).iter().all(|value| (value - 0.25).abs() < 1e-3)); + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 7.0})).unwrap(); + assert_eq!(source(&s, effect), Source::Uniform([1.0; 3]), "a mask value stays in 0..1"); + + let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("projectionSettings"), "inspect shows the mask fill's projection"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(source(&s, effect), Source::image(resource_name(scratches)), "each pick is one undo step"); +} + +#[test] +fn a_mask_fill_has_no_channels_or_material() { + let (mut s, _, effect) = mask_fill(); + let before = source(&s, effect); + for refused in [ + json!({"effect": effect.0, "channel": "height", "value": 0.5}), + json!({"effect": effect.0, "enabled": false}), + json!({"effect": effect.0}), + json!({"effect": effect.0, "procedural": "no such pattern"}), + ] { + assert!(execute(&mut s, "layer.fill.set", &refused).is_err(), "{refused}"); + } + assert!(execute(&mut s, "layer.fill.material", &json!({"effect": effect.0, "material": null})).is_err()); + assert_eq!(source(&s, effect), before); +} + +#[test] +fn a_mask_fill_is_projected_and_reset_like_any_fill() { + let (mut s, _, effect) = mask_fill(); + execute(&mut s, "layer.fill.projection", &json!({"effect": effect.0, "projection": "planar", "scale": 2.0, "symmetry": true})).unwrap(); + assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 2.0)); + let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("projectionSettings"), "inspect shows the mask fill's projection"); + + execute(&mut s, "layer.fill.resetProjection", &json!({"effect": effect.0})).unwrap(); + assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 1.0), "the reset keeps the projection, at its defaults"); + match &s.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Fill { sampling, .. } => assert!(sampling.symmetry.on, "the reset keeps the Symmetry section"), + other => panic!("not a mask fill: {other:?}"), + } + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 2.0), "the reset is one undo step"); +} + +fn resolution(s: &Session, effect: LayerId) -> OutputResolution { + match source(s, effect) { + Source::Procedural { pattern, .. } => pattern.resolution, + other => panic!("not a procedural: {other:?}"), + } +} + +#[test] +fn a_procedural_source_is_made_at_its_resolution() { + let (mut s, layer, effect) = mask_fill_on(512); + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "scale": 8.0})).unwrap(); + let every_texel = mask_line(&s, layer); + assert!(resolution(&s, effect).is_default()); + + // A quarter of the texture set's size: the pattern is made at 128 × 128 and smoothed back up + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolutionFactor": -2})).unwrap(); + assert_eq!(resolution(&s, effect).factor, -2); + let coarse = mask_line(&s, layer); + assert!(coarse.iter().zip(&every_texel).any(|(sampled, exact)| (sampled - exact).abs() > 1e-3), "{coarse:?} vs {every_texel:?}"); + assert!(execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string().contains("\"resolution\""), "inspect shows it"); + + // Another parameter keeps it; a bad size is refused and changes nothing + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "contrast": 1.0})).unwrap(); + assert_eq!(resolution(&s, effect).factor, -2); + assert!(execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolution": "big"})).is_err()); + assert_eq!(resolution(&s, effect).factor, -2); + + // The default size again: every texel, as before + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolution": "auto", "resolutionFactor": 0})).unwrap(); + assert!(resolution(&s, effect).is_default()); + assert_eq!(mask_line(&s, layer), every_texel); +} + +#[test] +fn a_pattern_saved_before_resolutions_existed_reads_and_saves_unchanged() { + let old = r#"{"kind":"Clouds","scale":4.0,"seed":1,"contrast":1.0,"balance":0.0,"invert":false}"#; + let pattern: Procedural = serde_json::from_str(old).unwrap(); + assert_eq!(pattern, Procedural::new(ProceduralKind::Clouds)); + assert_eq!(serde_json::to_string(&pattern).unwrap(), old, "no resolution, no new field in the file"); +} + +#[test] +fn setting_the_source_a_mask_fill_already_reads_adds_no_undo_step() { + let (mut s, _, effect) = mask_fill(); + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 0.25})).unwrap(); + let steps = s.history_labels().len(); + + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 0.25})).unwrap(); + + assert_eq!(s.history_labels().len(), steps); + assert_eq!(source(&s, effect), Source::Uniform([0.25; 3])); +} diff --git a/crates/ui-egui/src/mask_fill_panel.rs b/crates/ui-egui/src/mask_fill_panel.rs new file mode 100644 index 00000000..c08d8175 --- /dev/null +++ b/crates/ui-egui/src/mask_fill_panel.rs @@ -0,0 +1,28 @@ +//! A mask fill effect's Properties: the Fill and Symmetry sections a fill layer has, then its Grayscale section with its one source slot + +use serde_json::json; +use texturecraft_engine::core::{Fill, LayerId, Projection, Sampling, Source}; + +use crate::TextureCraftApp; +use crate::fill_material_panel::source_card; +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::source_slot::SourceSlot; + +/// Every section of mask fill effect `effect` in layer `reader`'s mask +pub(crate) fn mask_fill_sheet( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + effect: LayerId, + source: Source, + projection: Projection, + sampling: Sampling, + reader: LayerId, +) { + let base = json!({"effect": effect.0}); + let placement = Fill { projection, sampling, ..Fill::default() }; + crate::fill_panel::placement_sections(app, sheet, &placement, &base, reader); + + sheet.section(tr("Grayscale"), false); + source_card(app, sheet, source, &base, SourceSlot::Grayscale, reader, false); +} diff --git a/crates/ui-egui/src/mask_paint_panel.rs b/crates/ui-egui/src/mask_paint_panel.rs new file mode 100644 index 00000000..d2ab456f --- /dev/null +++ b/crates/ui-egui/src/mask_paint_panel.rs @@ -0,0 +1,86 @@ +//! The paint tools' Grayscale tab while a mask is painted: the GRAYSCALE section with the slot of the gray a stroke lays down + +use egui::Ui; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::compose::ImageStore; +use texturecraft_engine::core::{NormalFormat, Source}; + +use crate::TextureCraftApp; +use crate::fill_material_panel::{shown_color, source_line}; +use crate::i18n::{n_, tr}; +use crate::mask_source_choice::MaskSourceChoice; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::PropertySheet; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::slot_thumbnail::{paint_thumbnail, thumbnail}; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; +use crate::tile_picture::TilePicture; + +/// The GRAYSCALE section: a slot card for one gray (with its ramp and invert) or an image whose gray is painted +pub(crate) fn grayscale_sheet(app: &mut TextureCraftApp, ui: &mut Ui) { + PropertySheet::show(ui, "mask_paint_sheet", |sheet| { + sheet.section(tr("Grayscale"), false); + let gray = app.session.tool.mask_value; + let source = match &app.session.tool.mask_image { + Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() }, + None => Source::Uniform([gray; 3]), + }; + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); + let line = source_line(app, &source); + let image = app.session.tool.mask_image.is_some(); + let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false); + + let popup = sheet.ui.make_persistent_id("mask_paint_source"); + if slot.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = match &app.session.tool.mask_image { + Some(name) => MaskSourceChoice::Image(name.clone()), + None => MaskSourceChoice::Uniform, + }; + let ctx = sheet.ui.ctx().clone(); + let tabs = |_: &mut Thumbs| source_tabs(&app.session.images, shown_color([gray; 3])); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) { + Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => { + app.run("tool.material", json!({"maskImage": name})); + } + Some(MaskSourceChoice::Uniform) if image => { + app.run("tool.material", json!({"maskImage": null})); + } + _ => {} + } + if slot.clear { + app.run("tool.material", json!({"maskImage": null})); + } + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("tool.material", json!({"maskImage": name})); + } + + if !image { + let mut value = gray; + let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0); + if edit.invert { + app.run("tool.material", json!({"maskValue": 1.0 - gray})); + } else if edit.changed.is_some() { + app.run("tool.material", json!({"maskValue": value})); + } + } + sheet.close_card(); + }); +} + +/// The picker's one Resources tab: Textures (Import... first, then the project's images) and Uniform +fn source_tabs(images: &ImageStore, uniform: egui::Color32) -> Vec> { + let textures = ResourcePickerItem::textures(images, MaskSourceChoice::Import, |name| MaskSourceChoice::Image(name.to_owned())); + let uniform = + vec![ResourcePickerItem { id: MaskSourceChoice::Uniform, label: tr("Uniform value").to_owned(), caption: None, picture: TilePicture::Swatch(uniform) }]; + let groups = + [(n_("Textures"), textures), (n_("Uniform"), uniform)].into_iter().map(|(header, items)| PickerGroup { header: Some(tr(header)), items }).collect(); + vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }] +} diff --git a/crates/ui-egui/src/mask_source_choice.rs b/crates/ui-egui/src/mask_source_choice.rs new file mode 100644 index 00000000..9cc38201 --- /dev/null +++ b/crates/ui-egui/src/mask_source_choice.rs @@ -0,0 +1,9 @@ +//! What the mask paint Grayscale slot's picker offers + +/// One tile of the Grayscale slot's picker: one gray, an image resource, or importing one +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum MaskSourceChoice { + Uniform, + Image(String), + Import, +} diff --git a/crates/ui-egui/tests/it/mask_fill_rows.rs b/crates/ui-egui/tests/it/mask_fill_rows.rs new file mode 100644 index 00000000..041a2bb9 --- /dev/null +++ b/crates/ui-egui/tests/it/mask_fill_rows.rs @@ -0,0 +1,175 @@ +//! A mask fill effect's Properties: Fill | Symmetry | Grayscale tabs, the fill's projection rows, and one Grayscale slot whose picker sets its source + +use egui::{Event, Modifiers, PointerButton, Pos2, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, ProceduralKind, Projection, ResolutionMode, Source}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::move_on_model::MoveOnModel; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Tall enough that Properties shows every section of a mask fill without scrolling +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1600.0); + +/// Moves of a mouse drag, one per frame +const DRAG_MOVES: usize = 40; + +/// How far left a drag moves the projection on the model +const MOVE_DRAG: egui::Vec2 = egui::vec2(-60.0, 0.0); + +/// The app with a paint layer whose mask holds one fill effect, that effect selected; the layer's and the effect's ids +fn app_with_mask_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, LayerId, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let layer = LayerId(texturecraft_engine::execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap()); + let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": projection})).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); + texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + 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(STARTUP_FRAMES); + (harness, layer, effect) +} + +fn mask_fill(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> (Source, Projection) { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Fill { source, projection, .. } => (source.clone(), projection.clone()), + other => panic!("not a mask fill: {other:?}"), + } +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(SETTLE_FRAMES); +} + +/// Scrolls the `role` named `label` into view first, then clicks it +fn click_below(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + click(harness, role, label); +} + +#[test] +fn a_mask_fill_has_fill_symmetry_and_grayscale_tabs_and_its_slot_picks_the_source() { + let (mut harness, _, effect) = app_with_mask_fill("uv"); + for tab in ["Fill", "Symmetry", "Grayscale"] { + assert!(harness.query_by_role_and_label(Role::Tab, tab).is_some(), "the {tab} tab"); + } + assert!(harness.query_by_role_and_label(Role::Tab, "Material").is_none(), "a mask fill has no material"); + assert!(harness.query_by_label("Move on model").is_some(), "the Fill section's projection rows"); + + click(&mut harness, Role::ComboBox, "Grayscale"); + assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "the slot opens the source picker"); + click(&mut harness, Role::ListBoxOption, "Clouds"); + let (Source::Procedural { pattern, low, high, .. }, _) = mask_fill(&harness, effect) else { panic!("a procedural") }; + assert_eq!((pattern.kind, low, high), (ProceduralKind::Clouds, [0.0; 3], [1.0; 3]), "a gray pattern spans black to white"); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); + assert!(harness.query_by_label("Scale").is_some(), "the pattern's own rows follow the slot"); + for shown in ["Contrast", "Balance", "Random"] { + assert!(harness.query_by_label(shown).is_some(), "a grayscale's {shown} (Seed's dice) shows with Scale, Attributes folded"); + } + + // Resolution: the pattern is made at the texture set's size until another is picked + let resolution = |harness: &Harness<'_, TextureCraftApp>| match mask_fill(harness, effect).0 { + Source::Procedural { pattern, .. } => (pattern.resolution.mode, pattern.resolution.custom, pattern.resolution.factor), + other => panic!("a procedural: {other:?}"), + }; + click_below(&mut harness, Role::ComboBox, "Texture set · 256"); + for caption in ["Relative", "Fixed"] { + assert!(harness.query_by_role_and_label(Role::Label, caption).is_some(), "one list holds the {caption} sizes under their caption"); + } + click(&mut harness, Role::ListBoxOption, "1024 × 1024"); + assert_eq!(resolution(&harness), (ResolutionMode::Custom, 1024, 0)); + click_below(&mut harness, Role::ComboBox, "1024 × 1024"); + click(&mut harness, Role::ListBoxOption, "×4 · 1024"); + assert_eq!(resolution(&harness), (ResolutionMode::Auto, 1024, 2), "1024 is the texture set's ×4"); + + // The slot's × puts the mask fill back to white + click(&mut harness, Role::Button, "Clear"); + assert_eq!(mask_fill(&harness, effect).0, Source::Uniform([1.0; 3])); +} + +/// A drag as a mouse sends it: press, hold still a frame, then small moves one per frame until released; `watch` looks at the app after each move +fn mouse_drag_watching(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, mut watch: impl FnMut(&Harness<'_, TextureCraftApp>)) { + let button = |pos: Pos2, pressed: bool| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + harness.event(Event::PointerMoved(from)); + harness.run_steps(1); + harness.event(button(from, true)); + harness.run_steps(DRAG_STEP_FRAMES); + for step in 1..=DRAG_MOVES { + harness.event(Event::PointerMoved(from.lerp(to, step as f32 / DRAG_MOVES as f32))); + harness.run_steps(1); + watch(harness); + } + harness.event(button(to, false)); + harness.run_steps(DRAG_STEP_FRAMES); +} + +#[test] +fn a_mask_fills_projection_moves_on_the_model_and_resets_with_its_section() { + let (mut harness, layer, effect) = app_with_mask_fill("uv"); + + // A real drag that starts on the held button slides the mask fill's image + let button = harness.get_by_role_and_label(Role::Button, "Move on model").rect().center(); + let mut held = None; + mouse_drag_watching(&mut harness, button, button + MOVE_DRAG, |harness| held = held.or(harness.state().moving_on_model)); + assert_eq!(held, Some(MoveOnModel { layer, effect: Some(effect) })); + assert_eq!(harness.state().moving_on_model, None, "letting go ends it"); + let Projection::Uv { offset, .. } = mask_fill(&harness, effect).1 else { panic!("still UV") }; + assert!(offset[0] != 0.0 && offset[1] == 0.0, "a drag across slides the image across: {offset:?}"); + + click(&mut harness, Role::Button, "Fill: Reset to defaults"); + assert_eq!(mask_fill(&harness, effect).1, Projection::default(), "the Fill section's reset reaches the mask fill"); +} + +/// A mask fill reading a content anchor point picks the channel it reads in its Grayscale card +#[test] +fn a_mask_fill_reading_a_content_anchor_picks_its_channel() { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let low = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"roughness": 0.2})).unwrap()["layer"].clone(); + let anchor = texturecraft_engine::execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "content"})).unwrap()["effect"].clone(); + let top = texturecraft_engine::execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].clone(); + let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": top, "target": "mask", "anchor": anchor})).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); + texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": top, "target": effect.0})).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + let Source::Anchor { channel, .. } = mask_fill(&harness, effect).0 else { panic!("an anchor source") }; + assert_eq!(channel, Channel::Height, "a new anchor source reads height"); + + click_below(&mut harness, Role::ComboBox, "Height"); + click(&mut harness, Role::ListBoxOption, "Roughness"); + + let Source::Anchor { channel, .. } = mask_fill(&harness, effect).0 else { panic!("still an anchor source") }; + assert_eq!(channel, Channel::Roughness, "the pick reads the anchor's roughness"); +} + +/// An instance showing its source's mask fill lists only the anchor points below both: one between the source and the instance is refused by the source's mask +#[test] +fn an_inherited_mask_fill_lists_only_anchors_below_its_owner() { + const BETWEEN: &str = "Edge wear between"; + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let source = texturecraft_engine::execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].clone(); + let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": source, "target": "mask"})).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); + let between = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let anchor = texturecraft_engine::execute(&mut session, "effect.add.anchor", &json!({"layer": between, "target": "content"})).unwrap()["effect"].clone(); + texturecraft_engine::execute(&mut session, "effect.set", &json!({"effect": anchor, "name": BETWEEN})).unwrap(); + let instance = texturecraft_engine::execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); + texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": instance})).unwrap(); + session.target = texturecraft_engine::StackTarget::Effect(effect); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + let shown = harness.query_all_by_label(BETWEEN).count(); + + click(&mut harness, Role::ComboBox, "Grayscale"); + click(&mut harness, Role::Tab, "Anchor points"); + + assert_eq!(harness.query_all_by_label(BETWEEN).count(), shown, "the anchor above the source is not offered"); +} From 82b981e6419014dd6e1a378184bafa32243a1fd4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:12 +0000 Subject: [PATCH 027/153] Temporary: the fill's Material section keeps main's channel rows and filter effects main's filter panel --- crates/compose/src/eval.rs | 25 +++++++++--------- crates/compose/src/lib.rs | 1 + crates/core/src/layer.rs | 2 +- crates/core/src/lib.rs | 2 ++ crates/engine/src/fill_reset_cmds.rs | 1 + crates/engine/src/layer_cmds.rs | 9 ++++--- crates/engine/src/mask_cmds.rs | 2 +- crates/engine/src/materials.rs | 1 + crates/engine/src/warp_cmds.rs | 1 + crates/engine/tests/it/fill_projections.rs | 1 + crates/ui-egui/src/dock.rs | 26 ++++++++++++------- crates/ui-egui/src/fill_panel.rs | 4 +++ crates/ui-egui/src/fill_source_slot.rs | 6 ++--- crates/ui-egui/src/projection_preview.rs | 2 ++ crates/ui-egui/src/property_sheet/group.rs | 1 + crates/ui-egui/src/property_sheet/mod.rs | 2 +- crates/ui-egui/src/property_sheet/row_lead.rs | 1 + .../src/property_sheet/section_tabs.rs | 2 -- crates/ui-egui/src/property_sheet/slider.rs | 2 ++ crates/ui-egui/src/property_sheet/slot.rs | 2 ++ .../src/property_sheet/switch_control.rs | 1 + .../src/property_sheet/tests/gallery.rs | 2 ++ crates/ui-egui/src/round_gizmo.rs | 1 + crates/ui-egui/src/viewport.rs | 1 + crates/ui-egui/tests/it/properties_popup.rs | 4 +++ 25 files changed, 68 insertions(+), 34 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index adbf91ae..6413c421 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -10,9 +10,9 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, - blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Filtering, Generator, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, ShapeCrop, Source, + TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -1097,7 +1097,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], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -1155,7 +1155,7 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann img.resampled_tile(w, h, tx, ty, &empty).map(Cow::Owned) } -fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { +fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { if !mask.enabled { return None; } @@ -1179,8 +1179,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } -/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are -/// planned when `kids`. +/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( inp: &Inputs<'a>, @@ -1221,6 +1220,7 @@ fn plan_node<'a>( LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => { let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); + Content::Fill { fill: Box::new(Cow::Borrowed(f)), depth, covers_all } } LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), @@ -1373,7 +1373,7 @@ impl<'t> Tape<'t> { impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), tape: Tape::Off } + Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), tape: Tape::Off, copy: None } } /// Run `f` with `tape` as this texel's tape. @@ -2221,12 +2221,13 @@ impl<'a, 'b> Texel<'a, 'b> { } None => (value, coverage), }, + EffectKind::Levels(levels) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), // Baked lighting reads the texel's normal and occlusion, and lights the base color only EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let nrm = self.coords().nrm.to_array(); - let k = f.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); - (mix3(v, v.map(|x| (x * k).clamp(0.0, 1.0)), o), cov) + let factor = filter.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); + (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) } _ => (value, coverage), }, @@ -2905,7 +2906,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u 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 // is the whole set: with a neighbourhood filter below, each tile gets its own. - let probe = neighbourhood_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); + let probe = evaluation_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); let shared = probe.is_empty().then_some(probe); let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); let hist = tiles @@ -2915,7 +2916,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let fields = match &shared { Some(f) => f, None => { - own = neighbourhood_fields(&cut_inp, &channels, &[(tx, ty)]); + own = evaluation_fields(&cut_inp, &channels, &[(tx, ty)]); &own } }; diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 25548ab5..206f1437 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -41,6 +41,7 @@ pub mod warp; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use eval::{ + BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; pub use pattern_context::PatternContext; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index b9677515..267f05c2 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; +use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, DepthCulling, Projector, ShapeCrop, lum}; mod curvature_detail; mod curvature_mode; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 3797e2a5..be8338bc 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -42,6 +42,8 @@ pub use fill_symmetry::FillSymmetry; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator, + TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index d5d1afa6..f1c5317b 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -13,6 +13,7 @@ pub fn specs() -> Vec { "Reset fill settings", [], None, + "{layer? | effect?: content fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", has_layer, reset_projection )] diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 4c8b209f..d5936ece 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -3,8 +3,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, ChannelBlend, ChannelKind, EffectKind, Fill, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, - Source, + Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, + Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; use crate::commands::{ @@ -113,7 +113,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Set fill projection", [], None, - "{layer? | effect?: content fill effect id, projection?: uv|triplanar|planar|spherical|cylindrical (default: the current one), scale?: number | [u, v] (uv), rotation?: degrees (uv), offset?: [u, v] (uv) | [x, y, z] (triplanar, planar), sharpness?: 1..64 (triplanar), axis?: 0|1|2 (planar, cylindrical)} — what is not given keeps its value", + "{layer? | effect?: content fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", has_layer, fill_projection ), @@ -518,6 +518,7 @@ pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result Result<&mut Fill> { match target { FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index ac1db3f5..98c8f906 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, - MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Source, + MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 62c36dd2..5b8c1c7d 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -786,6 +786,7 @@ pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f3 Layer::new( id, "Brush material", + LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None }), &channels, ) } diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 71d0f051..6a3e18b0 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -17,6 +17,7 @@ pub fn specs() -> Vec { "Reset frame", [], None, + "{layer? | effect?: content fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", has_layer, reset_frame )] diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 7d0ebc93..5d9d18de 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -466,6 +466,7 @@ fn an_axis_planar_reading_a_pattern_is_not_placed() { let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); let effect = added["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 70c4f246..27d8e91c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,8 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, DecalFlip, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, - MaterialLink, Projection, Source, + BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Projection, + Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; @@ -1885,7 +1885,6 @@ fn effect_type_label(kind: &EffectKind) -> &'static str { pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); - egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); let scope = SectionScope::Docked; if let Some(tabs) = properties_fill_tabs(app) { crate::property_sheet::section_tabs(ui, scope, 0, &tabs); @@ -1920,6 +1919,8 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: }); } +/// The tabs over the panel when it shows a fill layer's sections, which they jump between +pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 2]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } @@ -1928,6 +1929,7 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: match app.session.target { StackTarget::Content => { let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; + matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(crate::fill_panel::fill_tabs) } _ => None, } @@ -1956,8 +1958,6 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { match (&selected, app.session.target) { // Polygon fill shows its own settings and says what it fills into, wherever it can fill _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), - (Some(layer), StackTarget::Effect(effect)) => legacy_body(ui, |ui| effect_properties(app, ui, layer, effect)), - (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => legacy_body(ui, |ui| fill_properties(app, ui, layer)), (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() => legacy_body(ui, |ui| { @@ -2066,6 +2066,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); 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(PREVIEW_STROKE_MIN_ALPHA))))); let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); ui.add_space(BRUSH_PREVIEW_GAP); @@ -2721,6 +2722,7 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let LayerKind::Fill(fill) = &layer.kind else { return }; let on: Vec = layer.channels.keys().copied().collect(); PropertySheet::show(ui, ("fill_sheet", layer.id.0), |sheet| { + crate::fill_panel::placement_sections(app, sheet, fill, &json!({"layer": layer.id.0}), layer.id); }); legacy_body(ui, |ui| { if let Some(link) = &fill.link { @@ -2945,7 +2947,7 @@ 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 enabled channels; `reader` owns it +/// Sources of a fill layer or fill effect (`base`) for its enabled channels; `reader` owns it fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, enabled_channels: &[Channel], reader: LayerId) { let salt = base.to_string(); ui.add_space(FILL_MATERIAL_GAP); @@ -3305,6 +3307,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe // Property sheets keep the panel's own edges; only the rows not yet laid out by one get the legacy margin match &effect.kind { EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), + EffectKind::Levels(levels) => legacy_body(ui, |ui| crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels)), EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); @@ -3353,9 +3356,11 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Material(fill) => { let enabled: Vec = fill.sources.keys().copied().collect(); PropertySheet::show(ui, ("fill_effect_sheet", id), |sheet| { + crate::fill_panel::placement_sections(app, sheet, fill, &json!({"effect": id}), layer.id); }); + legacy_body(ui, |ui| fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id)); } - EffectKind::Anchor => { + EffectKind::Anchor => legacy_body(ui, |ui| { ui.label(caption(tr("Anchor point"))); let text = if anchor_in_mask(app, effect_id) { tr("Records the mask value at this point. Fill effects and generators in masks above can read it.") @@ -3400,10 +3405,11 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe tool_properties(app, ui); } }), + EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), + EffectKind::ColorSelection { colors, tolerance } => { + legacy_body(ui, |ui| crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance)) } - EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), - EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), - other => { + other => legacy_body(ui, |ui| { ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); }), } diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs index b58dcde4..746c63e4 100644 --- a/crates/ui-egui/src/fill_panel.rs +++ b/crates/ui-egui/src/fill_panel.rs @@ -7,6 +7,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::frame_placement; use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length}; +use texturecraft_engine::core::{Backface, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE}; use texturecraft_engine::paint::FULL_TURN_DEGREES; @@ -74,6 +75,9 @@ const ROTATION_FIELD_SPEED: f32 = 0.5; /// Change per pixel dragged on a 3D scale field const SCALE_FIELD_SPEED: f32 = 0.01; +/// The tabs over a fill's Properties, each jumping to its section +pub(crate) fn fill_tabs() -> [(&'static str, &'static str); 2] { + [(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry"))] } /// Which fill a `base` addresses, (layer, effect), as the salt of its rows' widget state diff --git a/crates/ui-egui/src/fill_source_slot.rs b/crates/ui-egui/src/fill_source_slot.rs index 2b8dfeda..cecfd509 100644 --- a/crates/ui-egui/src/fill_source_slot.rs +++ b/crates/ui-egui/src/fill_source_slot.rs @@ -28,7 +28,7 @@ const UNIFORM_TILE_GRAY: f32 = 0.8; const UNIFORM_SWATCH_NAME: &str = "swatch:uniform"; /// One swatch for every frame, so its preview stays cached static UNIFORM_SWATCH: LazyLock> = - LazyLock::new(|| Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], srgb: false })); + LazyLock::new(|| Arc::new(ImageRes::new(1, 1, vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], false))); /// The slot of `fill`, which reads `source`; `anchors` are the anchor points below its layer and `caption` names what it fills pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, fill: &FillSourceTarget, source: &Source, (anchors, caption): (&[(LayerId, String)], &str)) { @@ -283,7 +283,7 @@ mod tests { for index in 0..IMAGE_COUNT { let name = format!("picker-image-{index:03}.png"); session.doc.resources.insert(name.clone(), Arc::new(vec![0])); - session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false })); + session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false))); } let mut harness = picker_harness(session, Vec::new()); @@ -320,7 +320,7 @@ mod tests { let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); for index in 0..128 { let name = format!("picker-{index:03}.png"); - session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false })); + session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false))); } let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); let mut app = TextureCraftApp::new(&creation_context, session); diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs index fefc92d8..903a01a9 100644 --- a/crates/ui-egui/src/projection_preview.rs +++ b/crates/ui-egui/src/projection_preview.rs @@ -29,6 +29,8 @@ use rendered_preview::RenderedPreview; use screen::Screen; use view::View; +/// The whole of a texture, as the part of it a picture shows +const FULL_UV: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); /// Largest preview side in pixels; the square is never drawn bigger than this const MAX_SIDE_PX: usize = 256; diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index d115e162..09ff1a4c 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -2,6 +2,7 @@ use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2} use egui_phosphor::regular as ic; use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; +use super::{BandResponse, GROUP_GAP, PropertySheet, TEXT_SIZE}; use crate::theme::semibold; /// Draws a band's picture in its rect diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index cbd25d6a..1da4e0eb 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -26,7 +26,6 @@ mod tooltip; mod track; mod value_text; -pub(crate) use section_tabs::{full_height_tab_rect, shown_tab_box}; #[cfg(test)] mod tests; @@ -36,6 +35,7 @@ pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; pub(crate) use preview_size::PreviewSize; pub(crate) use row_lead::RowLead; +pub(crate) use section_tabs::{SectionScope, forget_sections, full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box}; pub(crate) use stack_slider::StackSlider; use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs index 5d3b981c..36d82d8a 100644 --- a/crates/ui-egui/src/property_sheet/row_lead.rs +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -25,6 +25,7 @@ impl<'a> RowLead<'a> { /// The row's name, as assistive tech reads it pub(crate) fn text(self) -> &'a str { match self { + RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) => text, } } } diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 99edf990..8daf36e5 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -1,7 +1,5 @@ -use egui::{CornerRadius, Painter, Rect, pos2}; use egui::{Align2, Color32, CornerRadius, FontId, Id, Painter, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; -use crate::theme::Tokens; use super::row::SECTION_RULE_TO_CAPTION; use super::{PAD, SMALL_TEXT_SIZE}; use crate::theme::{Tokens, semibold}; diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index cfd35af1..a377cfdd 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -1,9 +1,11 @@ use std::ops::RangeInclusive; +use egui::{Align2, Id, Rect, Sense, Stroke, WidgetInfo, pos2}; use super::number_field::shown_number; use super::track::Track; use super::value_text::ValueText; +use super::{PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, TEXT_SIZE}; use crate::theme::semibold; /// Radius of a slider's knob diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 96e72f7e..fe2cef24 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,4 +1,6 @@ +use egui::{CornerRadius, FontId, Sense, Stroke, StrokeKind, pos2}; +use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; /// Air between a full-width button's icon and its words const BUTTON_ICON_GAP: f32 = 8.0; diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index e0107857..54b099f8 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,5 +1,6 @@ use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; /// Draws a picture row's picture into its square diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs index 3a9e730a..b1774512 100644 --- a/crates/ui-egui/src/property_sheet/tests/gallery.rs +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -2,6 +2,7 @@ use super::Filtering; +/// The gallery's controls, with the values they last set pub(super) struct Gallery { pub(super) filtering: Filtering, pub(super) position: [f32; 3], @@ -11,5 +12,6 @@ pub(super) struct Gallery { impl Default for Gallery { fn default() -> Self { + Gallery { filtering: Filtering::BilinearHq, position: [0.0, 1.25, -0.5], position_merges: Vec::new(), linked: true } } } diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index 146cd50f..0e531677 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -429,6 +429,7 @@ pub(crate) mod tests { use texturecraft_engine::core::{Fill, LayerId, LayerKind, Projection, Projector}; use super::*; + use crate::frame_gizmo::tests::{drag, drag_frames, fill_app, fill_app_with, panel_xyz, press_and_move, projection}; fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> RoundGizmo { RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 159fdecc..4a8015ec 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -877,6 +877,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let popup = app.properties_popup.is_some() || rail_popup; // A pending ID color pick takes the next click instead of the brush + let picking = app.picking_id_color.is_some(); if picking { crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); if !alt diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index fcc33f66..f3b7823b 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -208,9 +208,13 @@ fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_pane assert!(tab_lit(&harness, popup, "Fill"), "it opens on Fill"); assert!(in_popup(&harness, "UV projection")); + let symmetry = harness.get_all_by_role_and_label(Role::Tab, "Symmetry").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); + click(&mut harness, PointerButton::Primary, symmetry); harness.run_steps(JUMP_FRAMES); assert!(is_open(&harness), "a tab click keeps it open"); + assert!(!in_popup(&harness, "UV projection"), "the list jumped down to SYMMETRY"); + assert!(tab_lit(&harness, popup, "Symmetry"), "the section in view is lit"); assert!(!tab_lit(&harness, popup, "Fill")); assert!(tab_lit(&harness, docked, "Fill"), "the docked panel keeps its own place"); } From 5be1193f7b2223073d030ad1d1ce0ba8cb6ad73c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:30 +0000 Subject: [PATCH 028/153] Temporary: the mask fill's source slot and the filter slot use the new picker; main's filter panel stays until part 5 --- crates/compose/src/eval.rs | 2 - crates/compose/tests/cache_and_instances.rs | 1 + crates/engine/src/fill_material_cmds.rs | 2 + crates/engine/src/layer_cmds.rs | 5 +- crates/engine/src/layer_cmds/fill_target.rs | 3 +- crates/engine/src/materials.rs | 2 +- crates/engine/tests/it/filter_support.rs | 2 + crates/engine/tests/session.rs | 1 + crates/ui-egui/src/dock.rs | 72 +++++++++---------- crates/ui-egui/src/fill_material_panel.rs | 9 +++ crates/ui-egui/src/fill_panel.rs | 4 -- crates/ui-egui/src/filter_slot.rs | 10 ++- crates/ui-egui/src/material_orb.rs | 3 + crates/ui-egui/src/orb_environment.rs | 2 + crates/ui-egui/src/projection_preview.rs | 3 - crates/ui-egui/src/property_sheet/group.rs | 1 - crates/ui-egui/src/property_sheet/mod.rs | 1 - crates/ui-egui/src/property_sheet/slot.rs | 9 ++- crates/ui-egui/src/property_sheet/tests.rs | 1 + .../src/property_sheet/tests/gallery.rs | 2 - crates/ui-egui/src/slot_thumbnail.rs | 1 + crates/ui-egui/src/source_slot.rs | 5 ++ crates/ui-egui/src/viewport.rs | 1 - crates/ui-egui/tests/it/fill_channel_image.rs | 10 +-- crates/ui-egui/tests/it/properties_popup.rs | 4 -- .../ui-egui/tests/it/tile_generator_panel.rs | 2 +- 26 files changed, 90 insertions(+), 68 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 1b90a147..eaf04ca2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1194,7 +1194,6 @@ fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } -/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids` /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are /// planned when `kids`. #[allow(clippy::too_many_arguments)] @@ -2247,7 +2246,6 @@ impl<'a, 'b> Texel<'a, 'b> { // Baked lighting reads the texel's normal and occlusion, and lights the base color only EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { - let factor = filter.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index e8c4270c..3b6faa0a 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -668,6 +668,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { // Changing the hot mask must invalidate the retained fields let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap(); + blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); diff --git a/crates/engine/src/fill_material_cmds.rs b/crates/engine/src/fill_material_cmds.rs index 2248e9b3..c2c5449f 100644 --- a/crates/engine/src/fill_material_cmds.rs +++ b/crates/engine/src/fill_material_cmds.rs @@ -45,6 +45,7 @@ fn set_material(s: &mut Session, p: &Value) -> Result { match target { // A fill effect changes a channel while it has a source: its channels stay on, at their defaults FillTarget::Effect(_) => edited.sources.iter_mut().for_each(|(channel, source)| *source = Source::uniform_of(*channel)), + FillTarget::Layer(_) => edited.sources.clear(), } Ok(()) })?; @@ -116,6 +117,7 @@ fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMat fn target_set(s: &Session, target: FillTarget) -> Result { let owner = match target { FillTarget::Layer(id) => id, + FillTarget::Effect(id) => s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?, }; s.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0))) } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index a490b39a..bac08e2e 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -6,6 +6,7 @@ use texturecraft_core::{ Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; +use texturecraft_paint::alphas; use crate::commands::{ CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, normal_format_param, strp, u64p, @@ -117,7 +118,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -524,12 +525,12 @@ pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result match s.doc.project.effect(effect).map(|(_, found)| &found.kind) { Some(EffectKind::Material(_)) => Ok(FillTarget::Effect(effect)), + _ => Err(bad(cmd, format!("{} is not a content fill effect", effect.0))), }, None => Ok(FillTarget::Layer(content_param(s, cmd, p)?)), } } -/// The material of the fill at `target` pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { match target { FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind { diff --git a/crates/engine/src/layer_cmds/fill_target.rs b/crates/engine/src/layer_cmds/fill_target.rs index 62cfaa7c..a92e52ec 100644 --- a/crates/engine/src/layer_cmds/fill_target.rs +++ b/crates/engine/src/layer_cmds/fill_target.rs @@ -1,6 +1,7 @@ use texturecraft_core::LayerId; -/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's (`effect`) +/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's +/// (`effect`). #[derive(Clone, Copy)] pub(crate) enum FillTarget { Layer(LayerId), diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 287c7cc8..6640df26 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -786,7 +786,6 @@ pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f3 Layer::new( id, "Brush material", - LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None }), LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None, material: None }), &channels, ) @@ -842,6 +841,7 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { crate::layer_cmds::insert_selected(s, layer)? } else { let folder_id = s.doc.project.alloc_id(); + let mut folder = Layer::new(folder_id, material.label, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); for blend in folder.channels.values_mut() { *blend = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; } diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index eb585ba3..8109c419 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -1,5 +1,7 @@ //! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite +use texturecraft_engine::Session; +use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 36b45d1f..0cf88cf2 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -273,6 +273,7 @@ fn gray_png() -> Vec { out } +/// Frame edits and frame and Fill section resets on the fills they act on (a planar, a warp and a decal mask) meet hostile values without panicking; a refused edit changes nothing and adds no undo step #[test] fn panic_hunt_frames_and_transforms() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index fe8fd68d..b564144f 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Projection, - Source, + BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; @@ -20,6 +19,7 @@ use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_s use crate::past_end::PastEnd; use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; +use crate::source_choice::SourceChoice; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; @@ -1921,7 +1921,6 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: } /// The tabs over the panel when it shows a fill layer's sections, which they jump between -pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 2]> { pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 3]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; @@ -1931,7 +1930,6 @@ pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static s match app.session.target { StackTarget::Content => { let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; - matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(crate::fill_panel::fill_tabs) matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false)) } _ => None, @@ -2730,7 +2728,6 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let LayerKind::Fill(fill) = &layer.kind else { return }; let on: Vec = layer.channels.keys().copied().collect(); PropertySheet::show(ui, ("fill_sheet", layer.id.0), |sheet| { - crate::fill_panel::placement_sections(app, sheet, fill, &json!({"layer": layer.id.0}), layer.id); crate::fill_panel::fill_sheet(app, sheet, fill, &json!({"layer": layer.id.0}), &on, layer.id); }); } @@ -2886,37 +2883,6 @@ pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Chan if mask_anchor_enabled(app, anchor) == Some(false) { format!("{label} ({})", tr("Off")) } else { label } } -/// 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; - -/// Sources of a fill layer or fill effect (`base`) for its enabled channels; `reader` owns it -fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, enabled_channels: &[Channel], reader: LayerId) { - let salt = base.to_string(); - 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| { - for channel in &channels { - let enabled = enabled_channels.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(FILL_CHANNELS_GAP); - let anchors = anchors_below(app, reader); - for channel in channels { - if enabled_channels.contains(&channel) { - fill_channel(app, ui, fill, base, channel, &anchors, &salt); - } - } -} - /// Slider range of a fill's scale or tiling const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; @@ -3141,18 +3107,50 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); + let name = match source { + Source::Anchor { anchor, channel, .. } => { let project = &app.session.doc.project; + let owner = project.effect(*anchor).and_then(|(owner, _)| project.layers.get(&owner)); + let read = if anchor_in_mask(app, *anchor) { "Mask" } else { channel.label() }; + format!("{} · {}", owner.map_or_else(|| tr("missing").to_string(), |layer| layer.name.clone()), tr(read)) } Source::Uniform(_) => tr("Uniform value").to_string(), Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), + Source::Image { name, .. } => name.clone(), }; + // Main's Grayscale slot on the new picker: patterns, images and a uniform value, or the anchor points below + let (rect, source_response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::filter_slot::SLOT_HEIGHT), Sense::click()); + source_response.widget_info(|| egui::WidgetInfo { + current_text_value: Some(name.clone()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, tr("Grayscale")) }); + let (ctx, popup) = (ui.ctx().clone(), ui.make_persistent_id(("fill_source_picker", id))); + if source_response.clicked() { + crate::resource_picker::toggle(&ctx, popup); } + let highlighted = source_response.hovered() || egui::Popup::is_id_open(&ctx, popup); + crate::filter_slot::paint(ui, rect, (highlighted, source_response.has_focus()), None, (tr("Grayscale"), &name)); + let current = crate::fill_material_panel::source_choice(source); + let images = app.session.images.clone(); + let picked = crate::resource_picker::show(&source_response, popup, &mut app.thumbs, Some(¤t), current != SourceChoice::Uniform, |thumbs| { + let mut tabs = crate::fill_material_panel::source_tabs(thumbs, &ctx, &images, &anchors, Color32::from_gray(204)); + tabs.iter_mut().for_each(|tab| tab.groups.retain(|group| group.header != Some(tr("Alphas")))); + tabs }); + let anchor_channel = if let Source::Anchor { channel, .. } = source { *channel } else { Channel::Height }; + let params = match picked.filter(|choice| *choice != current) { + Some(SourceChoice::Procedural(kind)) => Some(json!({"effect": id, "procedural": kind.label()})), + Some(SourceChoice::Image(image)) => Some(json!({"effect": id, "image": image})), + Some(SourceChoice::Uniform) => Some(json!({"effect": id, "uniform": 1.0})), + Some(SourceChoice::Anchor(anchor)) => Some(json!({"effect": id, "anchor": anchor.0, "anchorChannel": anchor_channel.id()})), + Some(SourceChoice::Import) => { crate::menus::invoke(app, &ctx, "resource.import"); + None } + Some(SourceChoice::Alpha(_)) | None => None, }; + if let Some(params) = params { app.run("effect.set", params); } @@ -3198,10 +3196,8 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Material(fill) => { let enabled: Vec = fill.sources.keys().copied().collect(); PropertySheet::show(ui, ("fill_effect_sheet", id), |sheet| { - crate::fill_panel::placement_sections(app, sheet, fill, &json!({"effect": id}), layer.id); crate::fill_panel::fill_sheet(app, sheet, fill, &json!({"effect": id}), &enabled, layer.id); }); - legacy_body(ui, |ui| fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id)); } EffectKind::Anchor => legacy_body(ui, |ui| { ui.label(caption(tr("Anchor point"))); diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 23776d76..3332d551 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -178,6 +178,7 @@ pub(crate) fn source_line(app: &TextureCraftApp, source: &Source) -> String { } } +/// One source's card (a channel's): its slot (the row opens the source picker), then the source's own settings; `in_card`: only its slot row, inside the card open now pub(crate) fn source_card( app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, @@ -287,6 +288,7 @@ fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSl } /// The picker's choice `source` is: a library alpha's image is its alpha +pub(crate) fn source_choice(source: &Source) -> SourceChoice { match source { Source::Uniform(_) => SourceChoice::Uniform, Source::Procedural { pattern, .. } => SourceChoice::Procedural(pattern.kind), @@ -296,6 +298,13 @@ fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSl } /// The source picker's tabs: Resources (Procedurals, Textures with Import... first, Alphas in their shelf groups, Uniform) and the stack's Anchor points +pub(crate) fn source_tabs( + thumbs: &mut Thumbs, + ctx: &egui::Context, + images: &ImageStore, + anchors: &[(LayerId, String)], + uniform: Color32, +) -> Vec> { let procedurals = ProceduralKind::ALL.into_iter().map(|kind| tile(SourceChoice::Procedural(kind), tr(kind.label()), None, TilePicture::Procedural(kind))).collect(); let textures = ResourcePickerItem::textures(images, SourceChoice::Import, |name| SourceChoice::Image(name.to_owned())); diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs index 7f740796..65f2c632 100644 --- a/crates/ui-egui/src/fill_panel.rs +++ b/crates/ui-egui/src/fill_panel.rs @@ -7,7 +7,6 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::frame_placement; use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length}; -use texturecraft_engine::core::{Backface, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; use texturecraft_engine::core::{Backface, Channel, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE}; use texturecraft_engine::paint::FULL_TURN_DEGREES; @@ -76,9 +75,6 @@ const ROTATION_FIELD_SPEED: f32 = 0.5; /// Change per pixel dragged on a 3D scale field const SCALE_FIELD_SPEED: f32 = 0.01; -/// The tabs over a fill's Properties, each jumping to its section -pub(crate) fn fill_tabs() -> [(&'static str, &'static str); 2] { - [(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry"))] /// The tabs over a fill's Properties, each jumping to its section: a mask fill's last section is its Grayscale, a fill layer's its Material pub(crate) fn fill_tabs(grayscale: bool) -> [(&'static str, &'static str); 3] { let last = if grayscale { (ic::SQUARE_HALF, tr("Grayscale")) } else { (ic::CIRCLE_HALF, tr("Material")) }; diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 8f2bbb03..c41b7021 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -53,10 +53,18 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: paint(ui, rect, (highlighted, response.has_focus()), thumbnail.as_ref().map(egui::TextureHandle::id), (tr("Filter"), name)); let tabs = |thumbs: &mut Thumbs| { + let mut groups: Vec> = Vec::new(); + for def in filter_effects().iter().filter(|def| def.mask || !on_mask) { + let item = + ResourcePickerItem { id: def.id, label: tr(def.label).to_owned(), caption: None, picture: TilePicture::Texture(thumbs.filter(&ctx, def.id)) }; + match groups.last_mut() { + Some(group) if group.header == Some(tr(def.group)) => group.items.push(item), + _ => groups.push(PickerGroup { header: Some(tr(def.group)), items: vec![item] }), } } + vec![PickerTab { icon: ic::FUNNEL, name: tr("Filter"), groups }] }; - let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter); + let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); if let Some(id) = picked.filter(|id| Some(*id) != current) { app.run("effect.set", json!({"effect": effect, "filter": id})); } diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs index 704959cc..aa3d6388 100644 --- a/crates/ui-egui/src/material_orb.rs +++ b/crates/ui-egui/src/material_orb.rs @@ -4,6 +4,7 @@ use egui::{Color32, ColorImage, Painter, Rect, pos2}; use rayon::prelude::*; +use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::texel::linear_to_srgb; @@ -13,6 +14,8 @@ use crate::orb_previews::{OrbJob, OrbPreviews}; use crate::preview_image::aces; use crate::theme::Tokens; +/// The reflectance of non-metals at normal incidence +const DIELECTRIC_REFLECTANCE: f32 = 0.04; /// Largest orb rendered, in physical pixels const MAX_SIDE_PX: usize = 512; diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index c7d50c8e..286249a1 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -36,6 +36,8 @@ impl OrbEnvironment { let rgb = decoded.into_rgb32f(); let (pixels, _) = rgb.as_raw().as_chunks::<3>(); + let rgba: Vec<[f32; 4]> = pixels.iter().map(|&[red, green, blue]| [red, green, blue, 1.0]).collect(); + let env = EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false)?; drop(rgb); Some(OrbEnvironment::of(&env)) diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs index 18a8bc60..cc1ae480 100644 --- a/crates/ui-egui/src/projection_preview.rs +++ b/crates/ui-egui/src/projection_preview.rs @@ -30,9 +30,6 @@ use rendered_preview::RenderedPreview; use screen::Screen; use view::View; -/// The whole of a texture, as the part of it a picture shows -const FULL_UV: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - /// Largest preview side in pixels; the square is never drawn bigger than this const MAX_SIDE_PX: usize = 256; diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index 2e93f4af..b4eb8182 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -2,7 +2,6 @@ use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2} use egui_phosphor::regular as ic; use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; -use super::{BandResponse, GROUP_GAP, PropertySheet, TEXT_SIZE}; use super::{BandResponse, GROUP_GAP, OpenCard, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; use crate::theme::semibold; diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index c3786b5c..65806206 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -41,7 +41,6 @@ pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; pub(crate) use preview_size::PreviewSize; pub(crate) use row_lead::RowLead; -pub(crate) use section_tabs::{SectionScope, forget_sections, full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box}; pub(crate) use section_tabs::{ SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box, diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 5bdfb324..1095571b 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,8 +1,6 @@ -use egui::{CornerRadius, FontId, Sense, Stroke, StrokeKind, pos2}; use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use egui_phosphor::regular as ic; -use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; use super::switch_control::PILL_SIZE; use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, SlotResponse, TEXT_SIZE}; use crate::theme::semibold; @@ -278,10 +276,17 @@ impl PropertySheet<'_> { dice_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::i18n::tr("Random"))); if dice_response.clicked() { + *seed = next_seed(*seed); changed = true; } changed } } +/// A new seed that looks random but follows from the old one (SplitMix32's mixing step), so tests and replays get the same sequence +pub(crate) fn next_seed(seed: u32) -> u32 { + let mut z = seed.wrapping_add(0x9e37_79b9); + z = (z ^ (z >> 16)).wrapping_mul(0x85eb_ca6b); + z = (z ^ (z >> 13)).wrapping_mul(0xc2b2_ae35); + z ^ (z >> 16) } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 2cc6c702..312dcef5 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -4,6 +4,7 @@ use egui_kittest::kittest::Queryable as _; use egui_phosphor::regular as ic; use super::number_field::shown_number; +use super::slot::next_seed; use super::{NumberField, PropertySheet}; use crate::theme::{Accent, Brightness, Tokens}; diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs index 2332a36b..4f81abb1 100644 --- a/crates/ui-egui/src/property_sheet/tests/gallery.rs +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -2,7 +2,6 @@ use super::Filtering; -/// The gallery's controls, with the values they last set /// Every control of the shared set once, with the values the gallery last set pub(super) struct Gallery { pub(super) scale: usize, @@ -28,7 +27,6 @@ pub(super) struct Gallery { impl Default for Gallery { fn default() -> Self { - Gallery { filtering: Filtering::BilinearHq, position: [0.0, 1.25, -0.5], position_merges: Vec::new(), linked: true } Gallery { scale: 0, filtering: Filtering::BilinearHq, diff --git a/crates/ui-egui/src/slot_thumbnail.rs b/crates/ui-egui/src/slot_thumbnail.rs index 68f972d0..d739e42a 100644 --- a/crates/ui-egui/src/slot_thumbnail.rs +++ b/crates/ui-egui/src/slot_thumbnail.rs @@ -1,5 +1,6 @@ //! The picture a slot card shows of a fill channel's source +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, TextureHandle, TextureId, pos2}; use egui_phosphor::regular as ic; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::Source; diff --git a/crates/ui-egui/src/source_slot.rs b/crates/ui-egui/src/source_slot.rs index 3de5e7b2..b52bf7a3 100644 --- a/crates/ui-egui/src/source_slot.rs +++ b/crates/ui-egui/src/source_slot.rs @@ -1,5 +1,7 @@ +//! What a source slot card edits: one channel of a fill's material use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, ChannelKind}; use crate::i18n::tr; @@ -24,6 +26,7 @@ impl SourceSlot { } } + /// The value Uniform and the slot's × give it pub(crate) fn default_value(self) -> [f32; 3] { match self { SourceSlot::Channel(channel) => channel.default_value(), @@ -35,6 +38,7 @@ impl SourceSlot { if self.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 } } + /// A procedural's two ends when it is picked: a softer part of the channel's range pub(crate) fn procedural_ends(self) -> ([f32; 3], [f32; 3]) { /// Base color stays off pure black and white, which read as unlit or blown out const BASE_COLOR_ENDS: ([f32; 3], [f32; 3]) = ([0.15; 3], [0.85; 3]); @@ -52,6 +56,7 @@ impl SourceSlot { } } + /// The fill command's fields naming the slot pub(crate) fn fields(self) -> Value { match self { SourceSlot::Channel(channel) => json!({"channel": channel.id()}), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index c2e92805..0ac74f2e 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -878,7 +878,6 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let picker = crate::color_picker::blocks_view_press(ui.ctx()); let popup = app.properties_popup.is_some() || rail_popup || picker; - let picking = app.picking_id_color.is_some(); // A pending ID color pick or eyedropper takes the next click instead of the brush let picking = app.picking_id_color.is_some() || app.picking_color.is_some(); if picking { diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index c39610c9..5dc4b43d 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -6,10 +6,7 @@ use serde_json::json; use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; use texturecraft_ui_egui::TextureCraftApp; -/// The Roughness channel's source slot in Properties -fn roughness<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness") -} +use crate::fill_support::click_node; /// Opens the Roughness slot's source picker on the Material tab and types `search` into its search field, which has the focus fn open_roughness_source_menu(harness: &mut Harness<'_, TextureCraftApp>, search: &str) { @@ -133,8 +130,10 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.run_steps(30); harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); harness.run_steps(3); + // The search field has the focus: it brings the tile into the grid's view harness.event(egui::Event::Text("mask".into())); harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, &image_name).click(); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; @@ -151,7 +150,10 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { assert_eq!(harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").value().as_deref(), Some(image_name.as_str()), "the slot names the image"); harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); harness.run_steps(3); + // The search field has the focus: it brings the tile into the grid's view + harness.event(egui::Event::Text("uniform".into())); harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Uniform value").click(); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index d6db3fb2..930e3365 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -218,14 +218,10 @@ fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_pane assert!(tab_lit(&harness, popup, "Fill"), "it opens on Fill"); assert!(in_popup(&harness, "UV projection")); - let symmetry = harness.get_all_by_role_and_label(Role::Tab, "Symmetry").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); - click(&mut harness, PointerButton::Primary, symmetry); let material = harness.get_all_by_role_and_label(Role::Tab, "Material").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); click(&mut harness, PointerButton::Primary, material); harness.run_steps(JUMP_FRAMES); assert!(is_open(&harness), "a tab click keeps it open"); - assert!(!in_popup(&harness, "UV projection"), "the list jumped down to SYMMETRY"); - assert!(tab_lit(&harness, popup, "Symmetry"), "the section in view is lit"); assert!(!in_popup(&harness, "UV projection"), "the list jumped down to MATERIAL"); assert!(tab_lit(&harness, popup, "Material"), "the section in view is lit"); assert!(!tab_lit(&harness, popup, "Fill")); diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 5613ca7d..7e8dabd5 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -117,7 +117,7 @@ fn the_anchor_points_tab_picks_an_anchor() { let project = &harness.state().session.doc.project; let owner = project.layers.values().find(|layer| layer.content_effects.iter().any(|effect| effect.name == "Height")).unwrap(); let label = format!("{} / Height", owner.name); - harness.get_by_role_and_label(Role::Button, &label).click(); + harness.get_by_role_and_label(Role::ListBoxOption, &label).click(); harness.run_steps(3); assert!(source(&harness, effect).anchor().is_some()); } From b746a68bf3dc68e17b6838a1ad0af3974b3fbaa6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:47 +0000 Subject: [PATCH 029/153] Effects: Levels and Compare mask panels --- crates/ui-egui/src/compare_properties.rs | 167 ++++++++++++++++++ crates/ui-egui/src/compare_settings.rs | 15 ++ crates/ui-egui/src/histogram_cache.rs | 28 +++ crates/ui-egui/src/levels_display.rs | 74 ++++++++ crates/ui-egui/src/levels_editor.rs | 159 ++++++++++------- crates/ui-egui/src/levels_handle.rs | 5 +- crates/ui-egui/src/levels_properties.rs | 144 ++++++++------- .../ui-egui/src/property_sheet/compare_row.rs | 50 ++++++ .../property_sheet/compare_row_response.rs | 9 + 9 files changed, 510 insertions(+), 141 deletions(-) create mode 100644 crates/ui-egui/src/compare_properties.rs create mode 100644 crates/ui-egui/src/compare_settings.rs create mode 100644 crates/ui-egui/src/histogram_cache.rs create mode 100644 crates/ui-egui/src/levels_display.rs create mode 100644 crates/ui-egui/src/property_sheet/compare_row.rs create mode 100644 crates/ui-egui/src/property_sheet/compare_row_response.rs diff --git a/crates/ui-egui/src/compare_properties.rs b/crates/ui-egui/src/compare_properties.rs new file mode 100644 index 00000000..74e7029c --- /dev/null +++ b/crates/ui-egui/src/compare_properties.rs @@ -0,0 +1,167 @@ +//! Properties of a compare mask: its channel, both sources and their operator, constant, tolerance, hardness and histograms + +use std::sync::Arc; + +use egui::{Align2, Color32, FontId, Mesh, Rect, Sense, Shape, Stroke, Ui, pos2, vec2}; +use serde_json::json; +use texturecraft_engine::core::{CompareOp, CompareSource, Layer, LayerId}; + +use crate::TextureCraftApp; +use crate::compare_settings::CompareSettings; +use crate::histogram_cache::{HISTOGRAM_BUCKETS, cached_histogram}; +use crate::i18n::{n_, tr}; +use crate::levels_editor::{GRID_FRACTIONS, HISTOGRAM_HEIGHT}; +use crate::property_sheet::PropertySheet; +use crate::theme::{AXIS_COLORS, Tokens}; + +/// Air the tallest bucket keeps under the well's top +const HISTOGRAM_HEADROOM: f32 = 4.0; + +/// From the well's bottom to its value labels' centres +const AXIS_LABEL_OFFSET: f32 = 10.0; + +/// The room the value labels take under the well +const AXIS_LABEL_ROOM: f32 = 22.0; + +/// Size of the value labels under the well +const AXIS_LABEL_SIZE: f32 = 10.0; + +/// How much of a source's colour shows over the well; half, so where both sources overlap the one under shows through (levels' single histogram mixes more of its colour) +const HISTOGRAM_TINT: f32 = 0.5; + +/// The value labels under the well, at its edges and quarter lines +const AXIS_LABELS: [&str; 5] = ["0", "0.25", "0.5", "0.75", "1"]; + +/// Width of the constant's line in the well +const CONSTANT_LINE_WIDTH: f32 = 2.0; + +/// Gap between the well's top and the top of the constant's line +const CONSTANT_LINE_INSET: f32 = 2.0; + +/// The colours that tag the left and the right source +const SOURCE_TAGS: [Color32; 2] = [AXIS_COLORS[1], AXIS_COLORS[2]]; + +/// The operator switch's words, in [`CompareOp::ALL`] order +const OPERATOR_WORDS: [&str; 3] = ["<", "≈", ">"]; + +/// The properties of compare mask `effect_id` on `layer`; every edit goes through `effect.set` +pub(crate) fn compare_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId, settings: CompareSettings) { + let project = &app.session.doc.project; + let channels = project.locate(layer.id).and_then(|(set, _, _)| project.texture_set(set).ok()).map(|set| set.channel_list()).unwrap_or_default(); + let id = effect_id.0; + let CompareSettings { op, mut constant, mut tolerance, left, right, channel, mut hardness } = settings; + + PropertySheet::show(ui, ("compare_sheet", id), |sheet| { + sheet.section(tr("Compare mask"), false); + if let (Some(picked), _) = sheet.dropdown(tr("Channel"), channel, &channels, |option| tr(option.label()).to_string(), None) { + app.run("effect.set", json!({"effect": id, "compareChannel": picked.id()})); + } + + let operator = CompareOp::ALL.iter().position(|candidate| *candidate == op).unwrap_or_default(); + let picked = sheet.compare_rows((left, right), &CompareSource::ALL, source_name, SOURCE_TAGS, (&OPERATOR_WORDS, operator)); + if let Some(source) = picked.left { + app.run("effect.set", json!({"effect": id, "left": source.id()})); + } + if let Some(source) = picked.right { + app.run("effect.set", json!({"effect": id, "right": source.id()})); + } + if let Some(chosen) = picked.operator.and_then(|index| CompareOp::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "op": chosen.id()})); + } + + if (left == CompareSource::Constant || right == CompareSource::Constant) + && let Some(merge) = sheet.slider(tr("Constant"), &mut constant, 0.0..=1.0, 2) + { + app.run("effect.set", json!({"effect": id, "value": constant, "merge": merge})); + } + if op == CompareOp::WithinTolerance + && let Some(merge) = sheet.slider(tr("Tolerance"), &mut tolerance, 0.0..=1.0, 2) + { + app.run("effect.set", json!({"effect": id, "tolerance": tolerance, "merge": merge})); + } + if let Some(merge) = sheet.slider(tr("Hardness"), &mut hardness, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "hardness": hardness, "merge": merge})); + } + + if sheet.band(tr("Source histograms"), true, None, None).open { + let histograms = histogram_counts(app, sheet.ui, effect_id); + + // A constant has no spread: it shows as a line at its value in its side's colour + let constants = [left, right].map(|side| (side == CompareSource::Constant).then_some(constant)); + sheet.embed(|ui| source_histograms(ui, histograms.as_deref(), constants)); + } + }); +} + +/// A source's name in its list +fn source_name(source: CompareSource) -> String { + tr(match source { + CompareSource::LayersBelow => n_("Layers below"), + CompareSource::ThisLayer => n_("This layer"), + CompareSource::ThisMask => n_("This mask"), + CompareSource::Constant => n_("Constant"), + }) + .to_string() +} + +/// The well with the two sources' histograms (`counts`, left then right; a side reading a constant has `constants` set instead), quarter lines and value labels +fn source_histograms(ui: &mut Ui, counts: Option<&[Vec; 2]>, constants: [Option; 2]) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), HISTOGRAM_HEIGHT + AXIS_LABEL_ROOM), Sense::hover()); + let well = Rect::from_min_size(rect.min, vec2(rect.width(), HISTOGRAM_HEIGHT)); + let painter = ui.painter_at(rect.expand2(vec2(AXIS_LABEL_SIZE, 0.0))); + painter.rect_filled(well, 0.0, tokens.field); + let at = |share: f32| well.left() + well.width() * share; + for quarter in GRID_FRACTIONS { + painter.line_segment([pos2(at(quarter), well.top()), pos2(at(quarter), well.bottom())], Stroke::new(1.0, tokens.separator)); + } + + // The right source first, the left over it; a constant side draws no spread + let shown = |side: usize| counts.and_then(|both| both.get(side)).filter(|bins| !bins.is_empty() && constants.get(side).copied().flatten().is_none()); + let tallest = [0, 1].into_iter().filter_map(shown).flatten().copied().max().unwrap_or(0).max(1) as f32; + for side in [1, 0] { + if let (Some(tag), Some(bins)) = (SOURCE_TAGS.get(side), shown(side)) { + painter.add(Shape::mesh(spread_mesh(well, bins, tallest, tag.gamma_multiply(HISTOGRAM_TINT)))); + } + } + for (side, constant) in constants.iter().enumerate() { + if let (Some(value), Some(tag)) = (constant, SOURCE_TAGS.get(side)) { + let x = at(value.clamp(0.0, 1.0)); + painter.line_segment([pos2(x, well.top() + CONSTANT_LINE_INSET), pos2(x, well.bottom())], Stroke::new(CONSTANT_LINE_WIDTH, *tag)); + } + } + + for (index, label) in AXIS_LABELS.iter().enumerate() { + let x = at(index as f32 / (AXIS_LABELS.len() - 1) as f32); + painter.text(pos2(x, well.bottom() + AXIS_LABEL_OFFSET), Align2::CENTER_CENTER, *label, FontId::proportional(AXIS_LABEL_SIZE), tokens.text_dim); + } +} + +/// One source's spread in `well`: a single `tint` mesh from bucket centre to bucket centre (separate strips would leave seams between them), `tallest` reaching the well's top less its headroom +fn spread_mesh(well: Rect, bins: &[u32], tallest: f32, tint: Color32) -> Mesh { + let step = well.width() / bins.len() as f32; + let tops = bins + .iter() + .enumerate() + .map(|(index, count)| (well.left() + (index as f32 + 0.5) * step, well.bottom() - (*count as f32 / tallest) * (HISTOGRAM_HEIGHT - HISTOGRAM_HEADROOM))); + let outline = std::iter::once((well.left(), well.bottom())).chain(tops).chain(std::iter::once((well.right(), well.bottom()))); + + let mut mesh = Mesh::default(); + for (index, (x, top)) in outline.enumerate() { + mesh.colored_vertex(pos2(x, top), tint); + mesh.colored_vertex(pos2(x, well.bottom()), tint); + if let Ok(next) = u32::try_from(index * 2) + && index > 0 + { + mesh.add_triangle(next - 2, next - 1, next); + mesh.add_triangle(next - 1, next + 1, next); + } + } + mesh +} + +/// What the two sides of compare mask `effect_id` read +fn histogram_counts(app: &TextureCraftApp, ui: &Ui, effect_id: LayerId) -> Option; 2]>> { + let key = egui::Id::unique(("compare_histograms", effect_id.0)); + cached_histogram(ui, "compare_histograms_owner", key, app.session.revision, || app.session.compare_histograms(effect_id, HISTOGRAM_BUCKETS)) +} diff --git a/crates/ui-egui/src/compare_settings.rs b/crates/ui-egui/src/compare_settings.rs new file mode 100644 index 00000000..167de5e2 --- /dev/null +++ b/crates/ui-egui/src/compare_settings.rs @@ -0,0 +1,15 @@ +//! What a compare mask holds, as its properties show it + +use texturecraft_engine::core::{Channel, CompareOp, CompareSource}; + +/// What a compare mask holds: its operator, constant, tolerance, sources, channel and hardness +#[derive(Clone, Copy)] +pub(crate) struct CompareSettings { + pub(crate) op: CompareOp, + pub(crate) constant: f32, + pub(crate) tolerance: f32, + pub(crate) left: CompareSource, + pub(crate) right: CompareSource, + pub(crate) channel: Channel, + pub(crate) hardness: f32, +} diff --git a/crates/ui-egui/src/histogram_cache.rs b/crates/ui-egui/src/histogram_cache.rs new file mode 100644 index 00000000..febeea2c --- /dev/null +++ b/crates/ui-egui/src/histogram_cache.rs @@ -0,0 +1,28 @@ +//! The histograms the levels and compare mask screens show, cached by document revision + +use std::sync::Arc; + +use egui::{Id, Ui}; + +/// Buckets of a properties screen's histogram, over 0..1 +pub(crate) const HISTOGRAM_BUCKETS: usize = 64; + +/// The histogram cached under `key` for `revision`, recomputed by `count` once no button is held; one entry per `owner`, so a hidden effect's is dropped +pub(crate) fn cached_histogram(ui: &Ui, owner: &str, key: Id, revision: u64, count: impl FnOnce() -> Option) -> Option> { + let owner = ui.make_persistent_id(owner); + ui.data_mut(|data| { + let previous = std::mem::replace(data.get_temp_mut_or(owner, key), key); + if previous != key { + data.remove::<(u64, Arc)>(previous); + } + }); + + match ui.data(|data| data.get_temp::<(u64, Arc)>(key)) { + Some((cached, histogram)) if cached == revision || ui.input(|input| input.pointer.any_down()) => Some(histogram), + _ => count().map(|histogram| { + let histogram = Arc::new(histogram); + ui.data_mut(|data| data.insert_temp(key, (revision, histogram.clone()))); + histogram + }), + } +} diff --git a/crates/ui-egui/src/levels_display.rs b/crates/ui-egui/src/levels_display.rs new file mode 100644 index 00000000..07c19bf4 --- /dev/null +++ b/crates/ui-egui/src/levels_display.rs @@ -0,0 +1,74 @@ +//! Which histogram the levels editor draws for a colour channel + +use egui::Color32; +use texturecraft_engine::compose::EffectHistogram; + +use crate::i18n::n_; +use crate::theme::{AXIS_COLORS, Tokens}; + +/// A levels histogram's view: the three colours, all pooled, one colour, or luminance +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum LevelsDisplay { + #[default] + Colors, + Rgb, + Red, + Green, + Blue, + Luminance, +} + +impl LevelsDisplay { + pub(crate) const ALL: [LevelsDisplay; 6] = + [LevelsDisplay::Colors, LevelsDisplay::Rgb, LevelsDisplay::Red, LevelsDisplay::Green, LevelsDisplay::Blue, LevelsDisplay::Luminance]; + + /// Its word on the display switch, untranslated (short words of the reference's switch) + pub(crate) fn word(self) -> &'static str { + match self { + LevelsDisplay::Colors => n_("Colors"), + LevelsDisplay::Rgb => "RGB", + LevelsDisplay::Red => "R", + LevelsDisplay::Green => "G", + LevelsDisplay::Blue => "B", + LevelsDisplay::Luminance => n_("Lum"), + } + } + + /// The colours its word takes when chosen: red, green and blue split "Colors" + pub(crate) fn tints(self) -> &'static [Color32] { + let [red, green, blue] = &AXIS_COLORS; + match self { + LevelsDisplay::Colors => &AXIS_COLORS, + LevelsDisplay::Red => std::slice::from_ref(red), + LevelsDisplay::Green => std::slice::from_ref(green), + LevelsDisplay::Blue => std::slice::from_ref(blue), + LevelsDisplay::Rgb | LevelsDisplay::Luminance => &[], + } + } + + /// The histograms it draws, each with its colour, in drawing order + pub(crate) fn series<'h>(self, histogram: &'h EffectHistogram, tokens: &Tokens) -> Vec<(&'h [u32], Color32)> { + let component = + |index: usize| histogram.components.get(index).map(|counts| (counts.as_slice(), AXIS_COLORS.get(index).copied().unwrap_or(tokens.text))); + match self { + LevelsDisplay::Colors => (0..AXIS_COLORS.len()).filter_map(component).collect(), + LevelsDisplay::Red => component(0).into_iter().collect(), + LevelsDisplay::Green => component(1).into_iter().collect(), + LevelsDisplay::Blue => component(2).into_iter().collect(), + LevelsDisplay::Rgb => vec![(histogram.all.as_slice(), tokens.text)], + LevelsDisplay::Luminance => vec![(histogram.luminance.as_slice(), tokens.text)], + } + } + + /// The counts Auto fits the input range to: what the view shows, the three colours pooled + pub(crate) fn auto_counts(self, histogram: &EffectHistogram) -> &[u32] { + let component = |index: usize| histogram.components.get(index).map_or(histogram.all.as_slice(), Vec::as_slice); + match self { + LevelsDisplay::Colors | LevelsDisplay::Rgb => &histogram.all, + LevelsDisplay::Red => component(0), + LevelsDisplay::Green => component(1), + LevelsDisplay::Blue => component(2), + LevelsDisplay::Luminance => &histogram.luminance, + } + } +} diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index bff5d745..14586dd8 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -1,13 +1,16 @@ -//! Levels handles over a histogram and output gradient, with labelled fields for exact values +//! Levels handles over a histogram; a handle opens labelled fields for exact values -use egui::{Color32, CornerRadius, CursorIcon, Id, Pos2, Rect, Response, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui::{Color32, CursorIcon, Id, Pos2, Rect, Response, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; use texturecraft_engine::core::Levels; +use crate::exact_entry_open::ExactEntryOpen; use crate::i18n::tr; use crate::levels_handle::LevelsHandle; -use crate::theme::Tokens; +use crate::theme::{Tokens, lerp_color}; + +/// Height of a histogram well; the compare mask's well matches it +pub(crate) const HISTOGRAM_HEIGHT: f32 = 70.0; -const HISTOGRAM_HEIGHT: f32 = 56.0; const HANDLE_HEIGHT: f32 = 11.0; const HANDLE_HALF_WIDTH: f32 = 5.0; @@ -20,19 +23,23 @@ const HANDLE_TARGET_SIZE: f32 = 24.0; /// Fraction of the track moved by one arrow key press const KEYBOARD_STEP: f32 = 0.01; -const GRADIENT_HEIGHT: f32 = 8.0; -const GAP_BELOW_HISTOGRAM: f32 = 3.0; const VALUE_ROW_HEIGHT: f32 = 16.0; -const VALUE_FONT_SIZE: f32 = 11.5; +const VALUE_FONT_SIZE: f32 = 10.0; -/// Padding of the histogram well around its bars -const WELL_PADDING: f32 = 3.0; +/// Size of the exact-entry fields' labels +const FIELD_LABEL_SIZE: f32 = 11.5; + +/// How much of a histogram's colour shows over the well (the rest is the well) +const HISTOGRAM_TINT: f32 = 0.55; + +/// Room the well's painter keeps round the well, so the edge lines on its sides are not clipped +const WELL_CLIP_MARGIN: f32 = 1.0; /// Gray of the gamma handle, between the black input-low and white input-high handles const GAMMA_HANDLE_GRAY: u8 = 128; /// Grid lines across the histogram, at these fractions of its width -const GRID_FRACTIONS: [f32; 3] = [0.25, 0.5, 0.75]; +pub(crate) const GRID_FRACTIONS: [f32; 3] = [0.25, 0.5, 0.75]; /// Decimals printed beside a handle; exact entry keeps the stored precision const VALUE_DECIMALS: usize = 3; @@ -40,18 +47,11 @@ const VALUE_DECIMALS: usize = 3; /// Space kept around a printed value; a value closer to one already printed is left out const VALUE_SPACING: f32 = 2.0; -/// Opacity of the shade over the histogram outside the input range -const OUTSIDE_RANGE_SHADE: f32 = 0.7; - -/// Opacity of the line at gamma, fainter than the input range's accent lines -const GAMMA_LINE_OPACITY: f32 = 0.6; - -/// Edits `levels` over histogram `counts`; `Some(merge)` per change, `merge` true for a drag's later frames -pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, counts: Option<&[u32]>, levels: &mut Levels) -> Option { - let height = VALUE_ROW_HEIGHT * 2.0 + HANDLE_HEIGHT * 2.0 + HISTOGRAM_HEIGHT + GAP_BELOW_HISTOGRAM + GRADIENT_HEIGHT; +/// Edits `levels` over the histograms in `series` (counts and colour, drawn in order); `Some(merge)` per change, `merge` true for a drag's later frames +pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, series: &[(&[u32], Color32)], levels: &mut Levels) -> Option { + let height = VALUE_ROW_HEIGHT * 2.0 + HANDLE_HEIGHT * 2.0 + HISTOGRAM_HEIGHT; let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); let histogram_top = rect.top() + VALUE_ROW_HEIGHT + HANDLE_HEIGHT; - let gradient_top = output_handles_top(rect) - GRADIENT_HEIGHT; let track = track(rect); let id = ui.make_persistent_id(("levels_editor", id_salt)); @@ -109,12 +109,17 @@ pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debu responses.push((handle, response)); } - let well = Rect::from_x_y_ranges(rect.x_range().shrink(HANDLE_HALF_WIDTH), histogram_top..=histogram_top + HISTOGRAM_HEIGHT); - paint_histogram(ui, well, counts.unwrap_or_default(), levels); - paint_output_gradient(ui, Rect::from_x_y_ranges(track, gradient_top..=gradient_top + GRADIENT_HEIGHT)); + let well = Rect::from_x_y_ranges(track, histogram_top..=histogram_top + HISTOGRAM_HEIGHT); + paint_histogram(ui, well, series); paint_handles_and_values(ui, rect, &responses, levels); let cancel_typing = responses.iter().any(|(_, response)| response.is_pointer_button_down_on()); + let open_id = id.with("exact_entry"); + let open = focus_value.is_some() || ui.data(|data| data.get_temp::(open_id)).is_some(); + if !open { + return edit; + } + let fields = [LevelsHandle::InputLow, LevelsHandle::Gamma, LevelsHandle::InputHigh, LevelsHandle::OutputLow, LevelsHandle::OutputHigh]; let mut labels = Vec::with_capacity(fields.len()); @@ -122,7 +127,7 @@ pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debu ui.columns(fields.len(), |columns| { for (ui, handle) in columns.iter_mut().zip(fields) { let label = - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| ui.label(egui::RichText::new(handle.label()).size(VALUE_FONT_SIZE))).inner; + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| ui.label(egui::RichText::new(handle.label()).size(FIELD_LABEL_SIZE))).inner; labels.push(label.id); } }); @@ -139,6 +144,17 @@ pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debu ui.colored_label(Tokens::get(ui.ctx()).warning, tr("Enter a finite number")); } + // The row closes once no field is being typed in; a field just asked for focus holds it from the next frame + let typing = fields.iter().any(|handle| ui.memory(|memory| memory.has_focus(id.with((handle, "value"))))); + let keep_open = focus_value.is_some() || typing || invalid; + ui.data_mut(|data| { + if keep_open { + data.insert_temp(open_id, ExactEntryOpen); + } else { + data.remove::(open_id); + } + }); + edit } @@ -158,6 +174,7 @@ fn forget_previous_editor(ui: &Ui, id: Id, handles: &[LevelsHandle]) { data.remove::<(String, bool)>(field); data.remove::(previous.with(handle)); } + data.remove::(previous.with("exact_entry")); } data.insert_temp(owner, id); }); @@ -171,9 +188,9 @@ fn output_handles_top(rect: Rect) -> f32 { rect.bottom() - VALUE_ROW_HEIGHT - HANDLE_HEIGHT } -/// The x range the handles move along in the editor's `rect`, lined up with the histogram bars +/// The x range the handles move along in the editor's `rect`: the histogram's width, the end handles reaching the rect's edges fn track(rect: Rect) -> egui::Rangef { - rect.x_range().shrink(HANDLE_HALF_WIDTH + WELL_PADDING) + rect.x_range().shrink(HANDLE_HALF_WIDTH) } fn track_x(track: &egui::Rangef, position: f32) -> f32 { @@ -208,50 +225,49 @@ fn value_rect(rect: Rect, handle: LevelsHandle, levels: &Levels, size: egui::Vec placed.translate(vec2(shift, 0.0)) } -/// The histogram in its well: quarter lines, the outside of the input range dimmed, lines at the handles -fn paint_histogram(ui: &Ui, well: Rect, counts: &[u32], levels: &Levels) { +/// The histograms in their well over quarter lines, each a column per bucket in its colour, the tallest bucket of all filling the well +fn paint_histogram(ui: &Ui, well: Rect, series: &[(&[u32], Color32)]) { let tokens = Tokens::get(ui.ctx()); - let painter = ui.painter_at(well); - painter.rect(well, CornerRadius::same(tokens.radius), tokens.field, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); - - let inner = well.shrink(WELL_PADDING); - let vertical_line = |x: f32, color: Color32| painter.line_segment([pos2(x, inner.top()), pos2(x, inner.bottom())], Stroke::new(1.0, color)); + let painter = ui.painter_at(well.expand(WELL_CLIP_MARGIN)); + painter.rect_filled(well, 0.0, tokens.field); + let vertical_line = |x: f32, color: Color32| painter.line_segment([pos2(x, well.top()), pos2(x, well.bottom())], Stroke::new(1.0, color)); for fraction in GRID_FRACTIONS { - vertical_line(track_x(&inner.x_range(), fraction), tokens.field_border); + vertical_line(track_x(&well.x_range(), fraction), tokens.separator); } - let fullest = counts.iter().copied().max().unwrap_or(0).max(1) as f32; - let bar_width = inner.width() / counts.len().max(1) as f32; - for (index, count) in counts.iter().enumerate() { - let bar_height = inner.height() * *count as f32 / fullest; - let x = inner.left() + index as f32 * bar_width; - painter.rect_filled(Rect::from_min_max(pos2(x, inner.bottom() - bar_height), pos2(x + bar_width, inner.bottom())), 0.0, tokens.text_dim); + let fullest = series.iter().flat_map(|(counts, _)| counts.iter().copied()).max().unwrap_or(0).max(1) as f32; + let buckets = series.iter().map(|(counts, _)| counts.len()).max().unwrap_or(0); + let bar_width = well.width() / buckets.max(1) as f32; + for index in 0..buckets { + let bars: Vec<(u32, Color32)> = series.iter().map(|(counts, color)| (counts.get(index).copied().unwrap_or(0), *color)).collect(); + let x = well.left() + index as f32 * bar_width; + for (low, high, color) in bucket_segments(&bars) { + let [bottom, top] = [low, high].map(|count| well.bottom() - well.height() * count as f32 / fullest); + painter.rect_filled(Rect::from_min_max(pos2(x, top), pos2(x + bar_width, bottom)), 0.0, lerp_color(tokens.field, color, HISTOGRAM_TINT)); + } } - let x_at = |handle: LevelsHandle| track_x(&inner.x_range(), handle.position(levels)); - let (low, high) = (x_at(LevelsHandle::InputLow), x_at(LevelsHandle::InputHigh)); - let shade = tokens.field.gamma_multiply(OUTSIDE_RANGE_SHADE); - painter.rect_filled(Rect::from_x_y_ranges(inner.left()..=low, inner.y_range()), 0.0, shade); - painter.rect_filled(Rect::from_x_y_ranges(high..=inner.right(), inner.y_range()), 0.0, shade); - vertical_line(low, tokens.accent); - vertical_line(high, tokens.accent); - vertical_line(x_at(LevelsHandle::Gamma), tokens.text_dim.gamma_multiply(GAMMA_LINE_OPACITY)); + vertical_line(well.left(), tokens.text_dim); + vertical_line(well.right(), tokens.text_dim); } -/// A black-to-white strip: the output values the output handles pick from -fn paint_output_gradient(ui: &Ui, strip: Rect) { - let mut mesh = egui::Mesh::default(); - for (corner, color) in - [(strip.left_top(), Color32::BLACK), (strip.right_top(), Color32::WHITE), (strip.right_bottom(), Color32::WHITE), (strip.left_bottom(), Color32::BLACK)] - { - mesh.colored_vertex(corner, color); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); +/// One bucket's bars (count, colour) as stacked segments (from count, to count, colour): each segment in the sum of the colours of every bar reaching it, so bars of equal height show as their mix instead of the last one drawn hiding the others +fn bucket_segments(bars: &[(u32, Color32)]) -> Vec<(u32, u32, Color32)> { + let mut heights: Vec = bars.iter().map(|(count, _)| *count).filter(|count| *count > 0).collect(); + heights.sort_unstable(); + heights.dedup(); - let painter = ui.painter(); - painter.add(mesh); - painter.rect_stroke(strip, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), egui::StrokeKind::Outside); + let mut low = 0; + let mut segments = Vec::with_capacity(heights.len()); + for high in heights { + let reaching = bars.iter().filter(|(count, _)| *count >= high).map(|(_, color)| *color); + let mix = reaching.fold(Color32::BLACK, |sum, color| { + Color32::from_rgb(sum.r().saturating_add(color.r()), sum.g().saturating_add(color.g()), sum.b().saturating_add(color.b())) + }); + segments.push((low, high, mix)); + low = high; + } + segments } /// Each handle filled with its gray, the active one on top, and its value beside it, overlapping values left out @@ -277,7 +293,7 @@ fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Res } else if response.hovered() { tokens.text_strong } else { - tokens.text + tokens.text_dim }; let points_down = LevelsHandle::INPUT.contains(&handle); painter.add(egui::Shape::convex_polygon(handle_outline(x, handle_top(rect, handle), points_down), fill, Stroke::new(1.5, outline))); @@ -289,7 +305,7 @@ fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Res let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); by_priority.sort_by_key(|(_, response)| std::cmp::Reverse(priority(response))); for &(handle, ref response) in by_priority { - let color = if response.hovered() || response.has_focus() || response.dragged() { tokens.text_strong } else { tokens.text }; + let color = if response.hovered() || response.has_focus() || response.dragged() { tokens.text } else { tokens.text_dim }; let galley = painter.layout_no_wrap(shown_value(handle.value(levels)), font.clone(), color); let text_rect = value_rect(rect, handle, levels, galley.size()); if printed.iter().any(|other| other.expand(VALUE_SPACING).intersects(text_rect)) { @@ -404,6 +420,19 @@ fn number_field(ui: &mut Ui, id: Id, label: Id, handle: LevelsHandle, levels: &m mod tests { use super::*; + #[test] + fn equal_component_bars_show_their_mix_and_a_lone_bar_its_own_colour() { + let [red, green, blue] = [Color32::from_rgb(200, 0, 0), Color32::from_rgb(0, 200, 0), Color32::from_rgb(0, 0, 200)]; + + let equal = bucket_segments(&[(5, red), (5, green), (5, blue)]); + let stepped = bucket_segments(&[(2, red), (5, green), (0, blue)]); + let lone = bucket_segments(&[(4, blue)]); + + assert_eq!(equal, [(0, 5, Color32::from_rgb(200, 200, 200))], "equal counts read as one neutral bar, not blue over the others"); + assert_eq!(stepped, [(0, 2, Color32::from_rgb(200, 200, 0)), (2, 5, green)], "where red ends green shows alone"); + assert_eq!(lone, [(0, 4, blue)], "a single series keeps its colour"); + } + #[test] fn switching_effects_releases_old_field_and_drag_state() { let context = egui::Context::default(); @@ -411,8 +440,9 @@ mod tests { for effect in 0..100 { context .run_ui(egui::RawInput::default(), |ui| { - levels_editor(ui, effect, None, &mut levels); let id = ui.make_persistent_id(("levels_editor", effect)); + ui.data_mut(|data| data.insert_temp(id.with("exact_entry"), ExactEntryOpen)); + levels_editor(ui, effect, &[], &mut levels); ui.data_mut(|data| { data.insert_temp(id.with((LevelsHandle::Gamma, "value")), ("invalid draft".to_string(), true)); data.insert_temp(id.with(LevelsHandle::Gamma), true); @@ -425,6 +455,7 @@ mod tests { assert_eq!(data.count::(), 5, "only the current effect's fields remain"); assert_eq!(data.count::<(String, bool)>(), 1, "only the current draft remains"); assert_eq!(data.count::(), 1, "only the current drag state remains"); + assert_eq!(data.count::(), 0, "the open row closes once nothing is typed in it"); }); } } diff --git a/crates/ui-egui/src/levels_handle.rs b/crates/ui-egui/src/levels_handle.rs index 8be37584..98a3b605 100644 --- a/crates/ui-egui/src/levels_handle.rs +++ b/crates/ui-egui/src/levels_handle.rs @@ -7,9 +7,6 @@ use crate::i18n::tr; /// Narrowest gap the handles and typed values leave between the low and high handle of a pair const MIN_HANDLE_GAP: f32 = 0.01; -/// Gamma range of the handle and typed values: the engine's own, so the handle nearly reaches either input handle -const GAMMA_RANGE: std::ops::RangeInclusive = 0.01..=10.0; - /// One draggable value of a levels effect #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum LevelsHandle { @@ -75,7 +72,7 @@ impl LevelsHandle { LevelsHandle::InputHigh => (levels.in_low, false), LevelsHandle::OutputLow => (levels.out_high, levels.out_low <= levels.out_high), LevelsHandle::OutputHigh => (levels.out_low, levels.out_high < levels.out_low), - LevelsHandle::Gamma => return GAMMA_RANGE, + LevelsHandle::Gamma => return Levels::GAMMA_RANGE, }; // Invalid project values must not become NaN clamp bounds diff --git a/crates/ui-egui/src/levels_properties.rs b/crates/ui-egui/src/levels_properties.rs index d3673538..254775d6 100644 --- a/crates/ui-egui/src/levels_properties.rs +++ b/crates/ui-egui/src/levels_properties.rs @@ -1,83 +1,85 @@ -//! Properties of a levels effect: the levels editor, then the channel picker (content), Reset, Auto and Invert +//! Properties of a levels effect: its caption, the channel it remaps (content), the levels editor over the histogram, the histogram's view (colour channels), then Reset, Auto, Invert and Clamp use std::sync::Arc; use egui::Ui; use serde_json::json; +use texturecraft_engine::compose::EffectHistogram; use texturecraft_engine::core::{Channel, ChannelKind, Layer, LayerId, Levels}; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::histogram_cache::{HISTOGRAM_BUCKETS, cached_histogram}; +use crate::i18n::{tr, trf}; +use crate::levels_display::LevelsDisplay; use crate::levels_editor::levels_editor; -use crate::theme::caption; - -/// Buckets of the histogram, over 0..1 -const HISTOGRAM_BUCKETS: usize = 64; +use crate::property_sheet::PropertySheet; +use crate::theme::Tokens; /// Share of the counted texels a bucket needs to hold for Auto to keep it in the input range const AUTO_MIN_SHARE: f64 = 0.001; +/// The action row's buttons, by their place in it +const RESET_ACTION: usize = 0; +const AUTO_ACTION: usize = 1; +const INVERT_ACTION: usize = 2; + /// The properties of levels effect `effect_id` of `layer`; every edit goes through `effect.set` pub(crate) fn levels_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId, levels: &Levels) { - ui.label(caption(tr("Levels"))); - let is_content = layer.content_effects.iter().any(|effect| effect.id == effect_id); - let channels: Vec = - if is_content { layer.channels.keys().copied().filter(|channel| channel.kind() != ChannelKind::NormalMap).collect() } else { Vec::new() }; - let picked = egui::Id::unique(("levels_channel", effect_id.0)); - let channel = ui - .data(|data| data.get_temp(picked)) - .filter(|channel| channels.contains(channel)) - .or(channels.first().copied()) - .or(layer.channels.keys().next().copied()) - .unwrap_or(Channel::BaseColor); - let counts = histogram_counts(app, ui, effect_id, channel); + let choices = if is_content { affects_choices(app, layer, levels) } else { Vec::new() }; + let channel = levels.affects.or(choices.iter().copied().flatten().next()).unwrap_or(Channel::BaseColor); + let histogram = histogram_counts(app, ui, effect_id, channel); + let shows_colors = is_content && channel.kind() == ChannelKind::Color; + let display_id = egui::Id::unique(("levels_display", effect_id.0)); + let display = if shows_colors { ui.data(|data| data.get_temp(display_id)).unwrap_or_default() } else { LevelsDisplay::Luminance }; + let tokens = Tokens::get(ui.ctx()); let mut edited = *levels; - let mut edit = levels_editor(ui, effect_id, counts.as_ref().map(|counts| counts.as_slice()), &mut edited); - ui.horizontal(|ui| { - if !channels.is_empty() { - egui::ComboBox::from_id_salt(picked) - .selected_text(tr(channel.label())) - .show_ui(ui, |ui| { - for option in channels { - if ui.selectable_label(option == channel, tr(option.label())).clicked() { - ui.data_mut(|data| data.insert_temp(picked, option)); - } - } - }) - .response - .on_hover_text(tr("Channel")); + let mut edit = None; + PropertySheet::show(ui, ("levels_sheet", effect_id.0), |sheet| { + let target = if is_content { affects_name(levels.affects) } else { tr("Mask").to_string() }; + sheet.section(&trf("Levels - {target}", &[("target", &target)]), false); + if is_content && let (Some(Some(picked)), _) = sheet.dropdown(tr("Affects"), levels.affects, &choices, affects_name, None) { + app.run("effect.set", json!({"effect": effect_id.0, "affects": picked.id()})); } - // Right to left: the last button comes first - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Invert")).clicked() { - std::mem::swap(&mut edited.out_low, &mut edited.out_high); - edit = Some(false); + let series = histogram.as_ref().map(|histogram| display.series(histogram, &tokens)).unwrap_or_default(); + edit = sheet.embed(|ui| levels_editor(ui, effect_id, &series, &mut edited)); + if shows_colors { + let words = LevelsDisplay::ALL.map(|view| tr(view.word())); + let tints = LevelsDisplay::ALL.map(LevelsDisplay::tints); + let chosen = LevelsDisplay::ALL.iter().position(|view| *view == display).unwrap_or_default(); + if let Some(view) = sheet.wide_switch(&words, chosen, &tints).and_then(|index| LevelsDisplay::ALL.get(index).copied()) { + sheet.ui.data_mut(|data| data.insert_temp(display_id, view)); } + } - let auto_range = counts.as_ref().and_then(|counts| auto_input_range(counts)); - let auto = ui.add_enabled(auto_range.is_some(), egui::Button::new(tr("Auto"))).on_hover_text(tr("Fit the input range to the histogram")); - if auto.clicked() - && let Some((low, high)) = auto_range - { - (edited.in_low, edited.in_high) = (low, high); - edit = Some(false); - } + let auto_range = histogram.as_ref().and_then(|histogram| auto_input_range(display.auto_counts(histogram))); + let mut clamp = levels.clamp; + let (reset, auto, invert) = (tr("Reset"), tr("Auto"), tr("Invert")); - if ui.add_enabled(edited != Levels::default(), egui::Button::new(tr("Reset"))).clicked() { - edited = Levels::default(); - edit = Some(false); - } - }); + // In RESET_ACTION, AUTO_ACTION, INVERT_ACTION order + let buttons = [(reset, edited != edited.reset()), (auto, auto_range.is_some()), (invert, true)]; + let actions = sheet.action_row(&buttons, tr("Clamp"), &mut clamp); + match (actions.clicked, auto_range) { + (Some(RESET_ACTION), _) => edited = edited.reset(), + (Some(AUTO_ACTION), Some((low, high))) => (edited.in_low, edited.in_high) = (low, high), + (Some(INVERT_ACTION), _) => std::mem::swap(&mut edited.out_low, &mut edited.out_high), + _ => {} + } + if actions.clicked.is_some() { + edit = Some(false); + } + if actions.toggled { + app.run("effect.set", json!({"effect": effect_id.0, "clamp": clamp})); + } }); // Auto or Invert with nothing to change would add an empty undo step if let Some(merge) = edit && edited != *levels { - let Levels { in_low, in_high, gamma, out_low, out_high } = edited; + let Levels { in_low, in_high, gamma, out_low, out_high, .. } = edited; app.run( "effect.set", json!({"effect": effect_id.0, "inLow": in_low, "inHigh": in_high, "gamma": gamma, "outLow": out_low, "outHigh": out_high, "merge": merge}), @@ -85,28 +87,23 @@ pub(crate) fn levels_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: & } } -/// The histogram levels effect `effect_id` remaps, recomputed after a change once no pointer button is held -fn histogram_counts(app: &TextureCraftApp, ui: &Ui, effect_id: LayerId, channel: Channel) -> Option>> { +/// What a content levels can remap: its texture set's channels but normal maps (levels pass them through); levels from before the choice first, remapping all of them +fn affects_choices(app: &TextureCraftApp, layer: &Layer, levels: &Levels) -> Vec> { + let project = &app.session.doc.project; + let channels = project.locate(layer.id).and_then(|(set, _, _)| project.texture_set(set).ok()).map(|set| set.channel_list()).unwrap_or_default(); + let remappable = channels.into_iter().filter(|channel| channel.kind() != ChannelKind::NormalMap).map(Some); + levels.affects.is_none().then_some(None).into_iter().chain(remappable).collect() +} + +/// The name of what a levels remaps +fn affects_name(affects: Option) -> String { + affects.map_or_else(|| tr("All channels").to_string(), |channel| tr(channel.label()).to_string()) +} + +/// The histograms levels effect `effect_id` remaps for `channel` +fn histogram_counts(app: &TextureCraftApp, ui: &Ui, effect_id: LayerId, channel: Channel) -> Option> { let key = egui::Id::unique(("levels_histogram", effect_id.0, channel)); - let owner = ui.make_persistent_id("levels_histogram_owner"); - - // Selection changes the revision, so old effects' histograms cannot be reused - ui.data_mut(|data| { - let previous = std::mem::replace(data.get_temp_mut_or(owner, key), key); - if previous != key { - data.remove::<(u64, Arc>)>(previous); - } - }); - - let revision = app.session.revision; - match ui.data(|data| data.get_temp::<(u64, Arc>)>(key)) { - Some((cached, counts)) if cached == revision || ui.input(|input| input.pointer.any_down()) => Some(counts), - _ => app.session.effect_histogram(effect_id, channel, HISTOGRAM_BUCKETS).map(|counts| { - let counts = Arc::new(counts); - ui.data_mut(|data| data.insert_temp(key, (revision, counts.clone()))); - counts - }), - } + cached_histogram(ui, "levels_histogram_owner", key, app.session.revision, || app.session.effect_histogram(effect_id, channel, HISTOGRAM_BUCKETS)) } /// The input range Auto picks: the first to the last bucket holding more than [`AUTO_MIN_SHARE`] of the texels @@ -121,7 +118,8 @@ fn auto_input_range(counts: &[u32]) -> Option<(f32, f32)> { #[cfg(test)] mod tests { - use super::{HISTOGRAM_BUCKETS, auto_input_range}; + use super::auto_input_range; + use crate::histogram_cache::HISTOGRAM_BUCKETS; #[test] fn auto_skips_buckets_under_the_share() { diff --git a/crates/ui-egui/src/property_sheet/compare_row.rs b/crates/ui-egui/src/property_sheet/compare_row.rs new file mode 100644 index 00000000..8da1b36a --- /dev/null +++ b/crates/ui-egui/src/property_sheet/compare_row.rs @@ -0,0 +1,50 @@ +//! A comparison across two rows: two colour-tagged source dropdowns and the operator switch + +use egui::{Color32, CornerRadius, Rect}; + +use super::choice::VALUE_INSET; +use super::{CompareRowResponse, PropertySheet}; + +/// Width of the operator switch at the right end of the first row +const OPERATOR_SWITCH_WIDTH: f32 = 66.0; + +/// Air between the left source and the operator switch +const OPERATOR_AIR: f32 = 6.0; + +/// Width of a source's colour tag +const TAG_WIDTH: f32 = 3.0; + +/// Corner radius of a source's colour tag: softens its ends without rounding a 3 px bar into a pill +const TAG_RADIUS: u8 = 1; + +impl PropertySheet<'_> { + /// The two sources of a comparison, `left` tagged `tags[0]` with `operators` beside it, `right` tagged `tags[1]` under it; every list hangs from its own button + pub(crate) fn compare_rows( + &mut self, + (left, right): (T, T), + options: &[T], + name: impl Fn(T) -> String, + tags: [Color32; 2], + (operators, operator): (&[&str], usize), + ) -> CompareRowResponse { + let first = self.wide_row(); + let switch = Rect::from_x_y_ranges((self.right - OPERATOR_SWITCH_WIDTH)..=self.right, first.y_range()); + let left_button = Rect::from_x_y_ranges(self.left..=(switch.left() - OPERATOR_AIR), first.y_range()); + let left_response = self.tagged_button(left_button, &name(left), tags[0]); + let left_pick = self.hanging_list(&left_response, left, options, &name, None).0; + let operator_pick = self.segments(switch, operators, operator, super::switch_control::untinted, None); + + let second = self.wide_row(); + let right_response = self.tagged_button(second, &name(right), tags[1]); + let right_pick = self.hanging_list(&right_response, right, options, &name, None).0; + CompareRowResponse { left: left_pick, right: right_pick, operator: operator_pick } + } + + /// A dropdown button in `rect` tagged by `tag` along its left edge + fn tagged_button(&mut self, rect: Rect, value: &str, tag: Color32) -> egui::Response { + self.dropdown_button_led(rect, value, |painter| { + painter.rect_filled(Rect::from_x_y_ranges(rect.left()..=(rect.left() + TAG_WIDTH), rect.y_range()), CornerRadius::same(TAG_RADIUS), tag); + rect.left() + VALUE_INSET + }) + } +} diff --git a/crates/ui-egui/src/property_sheet/compare_row_response.rs b/crates/ui-egui/src/property_sheet/compare_row_response.rs new file mode 100644 index 00000000..da656199 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/compare_row_response.rs @@ -0,0 +1,9 @@ +//! What a comparison's rows picked + +/// What a comparison's rows picked: a source per side (left, right) and the operator +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CompareRowResponse { + pub(crate) left: Option, + pub(crate) right: Option, + pub(crate) operator: Option, +} From a7d165e0295b60a5d6136bddefc8d4854786299e Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:29:12 +0000 Subject: [PATCH 030/153] Fills: review repairs from #698 Chasse's repairs to this part's code, carried over from the #698 head (5644b7d3). --- apps/texturecraft/src/main.rs | 3 +- crates/automation/src/render.rs | 3 + crates/compose/src/axis_frame.rs | 1 + crates/compose/src/eval.rs | 205 +++++++++++++++--- crates/compose/src/eval/evaluation_inputs.rs | 23 ++ crates/compose/src/eval/thumbnail.rs | 9 +- crates/compose/src/fill_copies.rs | 5 + crates/compose/src/frame_placement.rs | 9 + crates/compose/src/lib.rs | 5 +- crates/compose/src/pattern.rs | 23 ++ crates/compose/src/projector_cover.rs | 13 +- crates/compose/src/projector_depth.rs | 103 +++------ crates/compose/src/projector_depth_cache.rs | 97 +++++++++ crates/compose/src/solo.rs | 9 + crates/compose/src/store.rs | 1 + crates/compose/src/tile_length.rs | 9 +- crates/compose/src/tile_length/mesh_size.rs | 6 + crates/compose/tests/cache_and_instances.rs | 22 ++ crates/core/src/layer.rs | 34 ++- crates/core/src/layer/filtering.rs | 30 +++ crates/core/src/layer/sampling.rs | 33 +++ crates/core/src/layer/scale_mode.rs | 25 +++ crates/core/src/layer/uv_transform.rs | 22 ++ crates/core/src/layer/uv_wrap.rs | 40 ++++ crates/core/src/project.rs | 1 + crates/engine/src/decal_cmds.rs | 2 +- crates/engine/src/fill_reset_cmds.rs | 5 + crates/engine/src/layer_cmds.rs | 4 + crates/engine/src/layer_cmds/fill_target.rs | 8 + crates/engine/src/resource_cmds.rs | 1 + crates/engine/src/session.rs | 53 +++-- crates/engine/src/thumbs.rs | 7 + crates/engine/src/view_cmds.rs | 14 ++ crates/engine/tests/it/fill_patterns.rs | 2 + crates/engine/tests/it/fill_projections.rs | 69 ++++++ crates/engine/tests/it/fill_sampling.rs | 13 ++ crates/engine/tests/it/painter_gaps.rs | 64 +++++- crates/engine/tests/it/user_smart_mask.rs | 1 + crates/geom/src/mesh.rs | 2 + crates/paint/src/brush.rs | 1 + crates/render/tests/headless.rs | 4 +- crates/ui-egui/src/dock.rs | 12 +- crates/ui-egui/src/fill_panel.rs | 4 +- crates/ui-egui/src/fill_pictures.rs | 1 + crates/ui-egui/src/fill_symmetry_panel.rs | 6 + crates/ui-egui/src/frame_gizmo.rs | 35 ++- crates/ui-egui/src/gray_slider.rs | 3 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/move_on_model.rs | 25 +++ crates/ui-egui/src/pointer_lock/tests.rs | 10 + crates/ui-egui/src/preview_dots.rs | 2 + crates/ui-egui/src/projection_gizmo.rs | 6 +- .../src/projection_gizmo/gizmo_drag.rs | 7 +- crates/ui-egui/src/projection_preview.rs | 39 +++- crates/ui-egui/src/properties_popup.rs | 3 + .../ui-egui/src/property_sheet/axis_rows.rs | 1 + .../ui-egui/src/property_sheet/info_icon.rs | 2 + crates/ui-egui/src/property_sheet/mod.rs | 9 +- .../src/property_sheet/number_field.rs | 17 +- crates/ui-egui/src/property_sheet/slider.rs | 18 +- .../src/property_sheet/switch_control.rs | 24 +- crates/ui-egui/src/property_sheet/tests.rs | 2 + .../ui-egui/src/property_sheet/value_text.rs | 67 ++++-- .../src/property_sheet/value_text_draft.rs | 9 + crates/ui-egui/src/render_mode/tests.rs | 2 + crates/ui-egui/src/round_gizmo.rs | 33 ++- crates/ui-egui/src/symmetry/view_overlay.rs | 8 +- crates/ui-egui/src/theme.rs | 18 +- crates/ui-egui/src/viewport.rs | 33 ++- crates/ui-egui/src/viewport_mesh_bounds.rs | 23 ++ crates/ui-egui/src/widgets.rs | 13 +- crates/ui-egui/tests/brush_cursor_2d.rs | 4 + .../ui-egui/tests/it/fill_projection_rows.rs | 9 + crates/ui-egui/tests/it/fill_symmetry_rows.rs | 12 + crates/ui-egui/tests/it/polygon_fill.rs | 7 + crates/ui-egui/tests/it/project_config.rs | 3 + crates/ui-egui/tests/it/properties_popup.rs | 5 + crates/ui-egui/tests/it/shelf_drop.rs | 2 + crates/ui-egui/tests/ui_snapshots.rs | 1 + 79 files changed, 1198 insertions(+), 261 deletions(-) create mode 100644 crates/compose/src/eval/evaluation_inputs.rs create mode 100644 crates/compose/src/projector_depth_cache.rs create mode 100644 crates/compose/src/tile_length/mesh_size.rs create mode 100644 crates/core/src/layer/filtering.rs create mode 100644 crates/core/src/layer/sampling.rs create mode 100644 crates/core/src/layer/scale_mode.rs create mode 100644 crates/core/src/layer/uv_transform.rs create mode 100644 crates/core/src/layer/uv_wrap.rs create mode 100644 crates/engine/src/layer_cmds/fill_target.rs create mode 100644 crates/ui-egui/src/property_sheet/value_text_draft.rs create mode 100644 crates/ui-egui/src/viewport_mesh_bounds.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 3a768c2b..4af56d84 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -165,8 +165,7 @@ impl eframe::App for Shell { } fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - // winit gives the window its caption back when it changes the window's flags (maximize, - // restore, …): take it off again before the frame is laid out. + // Restore the frameless style after winit changes the window flags if let Some(guard) = self.window_frame.as_mut() { guard(); } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 588f1752..d626849e 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -284,7 +284,9 @@ mod tests { let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1); mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1)); let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap(); + assert_eq!(session.caches.len(), 2); + session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true))); execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap(); let camera = session.camera; @@ -302,6 +304,7 @@ mod tests { assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap(); + assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); assert_eq!(gpu.h.renderer.aux_size(1), Some(128)); } diff --git a/crates/compose/src/axis_frame.rs b/crates/compose/src/axis_frame.rs index a4daa864..b63be023 100644 --- a/crates/compose/src/axis_frame.rs +++ b/crates/compose/src/axis_frame.rs @@ -151,6 +151,7 @@ mod tests { fn only_axis_planars_are_placed() { let bounds = (Vec3::NEG_ONE, Vec3::ONE); assert!(placed_from_axis(&Projection::default(), bounds).is_none()); + let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame"); assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none()); assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none()); diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6413c421..5dedc593 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,6 +2,7 @@ //! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport //! and for export. +mod evaluation_inputs; pub(crate) mod thumbnail; use std::borrow::Cow; @@ -18,6 +19,7 @@ use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::fill_copies::FillCopies; @@ -29,6 +31,7 @@ use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; use crate::projector_depth::ProjectorDepth; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use evaluation_inputs::EvaluationInputs; const NCH: usize = Channel::ALL.len(); @@ -71,6 +74,7 @@ impl Stencil { if c.w <= 1e-6 { return None; } + let (dx, dy) = (c.x / c.w - self.center[0], c.y / c.w - self.center[1]); let (sn, cs) = (-self.rotation).sin_cos(); let lx = (dx * cs - dy * sn) / self.half[0].max(1e-6); @@ -78,6 +82,7 @@ impl Stencil { if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) { return None; } + let s = self.image.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); let rgb = if self.image.srgb { [s[0], s[1], s[2]].map(texturecraft_texel::srgb_to_linear) } else { [s[0], s[1], s[2]] }; Some((rgb, s[3].clamp(0.0, 1.0))) @@ -279,6 +284,7 @@ impl Field { if x < self.x0 || y < self.y0 || x >= self.x0 + self.w || y >= self.y0 + self.h { return None; } + let i = ((y - self.y0) * self.w + (x - self.x0)) as usize * self.comps; self.data.get(i..i + self.comps) } @@ -600,7 +606,7 @@ fn stroke_at(preview: Option<&[u16]>, o: usize) -> f32 { /// The full stack of tile (tx, ty) when `layer` reads anchor points (empty otherwise): evaluated /// up to the layer, it records the anchors below it. -fn anchor_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { +fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { match inp.project.texture_set(inp.ts) { Ok(set) if reads_anchor(inp.project, id) => plan(inp, &set.stack, channels, tx, ty, 0, fields), _ => Vec::new(), @@ -639,7 +645,7 @@ enum Job<'a> { } /// 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 { +fn field(inp: &EvaluationInputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { let effects = match job { Job::Mask(mask) => &mask.effects, Job::Content(_) => &inp.project.content_layer(id)?.content_effects, @@ -709,7 +715,7 @@ fn is_box_blur(op: Op) -> bool { /// 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( - inputs: &Inputs, + inputs: &EvaluationInputs, channels: &[Channel], below: &Fields, id: LayerId, @@ -1021,13 +1027,19 @@ fn unpremultiply(data: &mut [f32], comps: usize) { /// Precompute the neighbourhood-filtered masks and content channels of every layer that needs /// one, over `tiles` plus the filter's reach. Walks bottom → top so each field sees the fields /// (and anchors) below it. Cheap when no layer has a blur or sharpen. -pub fn neighbourhood_fields(inp: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { +pub fn neighbourhood_fields(inputs: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(inputs, &projectors); + evaluation_fields(&inputs, channels, tiles) +} + +fn evaluation_fields(inp: &EvaluationInputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { let stack = inp.project.texture_set(inp.ts).map(|s| s.stack.as_slice()).unwrap_or_default(); fields_of(inp, channels, stack, tiles) } /// [`neighbourhood_fields`] of the layers drawn by `list` only. -fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields { +fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields { let mut out = Fields::new(); if tiles.is_empty() || inp.gbuf.width == 0 { return out; @@ -1147,7 +1159,8 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann if (img.width(), img.height()) == (w, h) { return img.tile(tx, ty).map(Cow::Borrowed); } - // Empty texels of signed channels hold a signed zero. + + // Empty texels of signed channels hold a signed zero let empty: Vec = match channel { Some(c) if c.kind() == ChannelKind::Signed => [vec![to_u16_signed(0.0); c.components()], vec![0]].concat(), _ => Vec::new(), @@ -1171,7 +1184,7 @@ fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u3 Some(MaskPlan { background, effects, start }) } -fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { +fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } @@ -1182,7 +1195,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( - inp: &Inputs<'a>, + inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, @@ -1271,7 +1284,7 @@ struct LevelPlan<'a> { /// Plan the path to the hot layer for tile (tx, ty); the layers before the path are left out /// on tiles the cache holds (`warm`). -fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec> { +fn plan_levels<'a>(inp: &EvaluationInputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec> { let last = levels.len().saturating_sub(1); levels .iter() @@ -1294,6 +1307,7 @@ fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f3 if a <= 0.0 { return (v, cov); } + let b = if cov > 0.0 { blend_chan(c, mode, v, p) } else { p }; let nc = a + cov * (1.0 - a); (mix3(v, b, a / nc.max(1e-5)), nc) @@ -1312,8 +1326,8 @@ fn covers_every_texel(proj: &Projection, sampling: Sampling, depth: Option<&Proj } /// A fill's projector depth (None: not culled by depth) and whether it covers every texel -fn fill_coverage(inp: &Inputs, projection: &Projection, sampling: Sampling) -> (Option>, bool) { - let depth = ProjectorDepth::of(inp.mesh, inp.bounds, projection); +fn fill_coverage(inp: &EvaluationInputs, projection: &Projection, sampling: Sampling) -> (Option>, bool) { + let depth = inp.projectors.get(inp.mesh, inp.bounds, projection); let covers_all = covers_every_texel(projection, sampling, depth.as_deref()); (depth, covers_all) } @@ -1523,7 +1537,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// A fill's value and coverage through `proj`, from `one` (which samples it once): with `sampling`'s symmetry on, every copy of the projection is sampled and the copies are laid over each other, the texel's own copy on top fn symmetric(&mut self, proj: &Projection, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) { - // Most fills have no symmetry: they are sampled directly and never pay for the surface lookup + // Skip the world-space lookup when no symmetry copies are needed if !takes_symmetry(proj, sampling) { return one(self); } @@ -1589,7 +1603,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// `place`'s fill at this texel in channel `ch`, every symmetric copy laid over each other when its symmetry is on #[inline(always)] fn fill_place_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { - // Without symmetry the fill is sampled directly: through `symmetric`'s closure a plain fill composites about 8% slower + // Sample directly without symmetry to keep the common path free of the copy search if takes_symmetry(&place.fill.projection, place.fill.sampling) { self.symmetric(&place.fill.projection, place.fill.sampling, |texel| texel.fill_texel(place, source, ch)) } else { @@ -1646,7 +1660,7 @@ impl<'a, 'b> Texel<'a, 'b> { let samples = self.image_uvs(proj, &c); let [(uv, _), ..] = samples; - // The shape is read over the footprint the image's colour is, so a shrunk image's coverage matches its averaged colour + // Use the image's sampling footprint so minified color and coverage agree let alpha = image.map_or(1.0, |img| { let [footprint, ..] = match sampling.filtering { Filtering::BilinearHq => self.footprints(proj, &samples, img), @@ -1818,7 +1832,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { match generator.inputs.get(&map) { - // Generator inputs have no sampling setting: they read as projects saved before sampling choices did + // Keep legacy sampling for generator inputs without a sampling setting Some(source) => Some(self.source(source, &Projection::default(), Sampling::SAVED_BEFORE, ChannelKind::Scalar)[0]), None => self.baked(map), } @@ -2026,8 +2040,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// is identical. fn eval_split(&mut self, mut acc: Acc, levels: &[LevelPlan], accs: &mut [Acc], masks: &mut [f32], warm: bool, tape: &mut Tape<'b>) -> Acc { let last = levels.len().saturating_sub(1); - // Down the path: the deepest level the stack reaches (a folder masked out or not drawn - // here stops it). + + // A hidden or masked folder limits how far the evaluator descends let mut reach = last; for (d, lv) in levels.iter().enumerate() { if !warm { @@ -2039,6 +2053,7 @@ impl<'a, 'b> Texel<'a, 'b> { if d == last { break; } + let m = match &lv.at { Some(g) => self.taped(tape, |t| t.tape_mask(g)), None => 0.0, @@ -2049,6 +2064,7 @@ impl<'a, 'b> Texel<'a, 'b> { if m > 0.0 { continue; } + reach = d; break; } @@ -2058,7 +2074,7 @@ impl<'a, 'b> Texel<'a, 'b> { { self.eval(std::slice::from_ref(hot), &mut acc); } - // Back up: the layers after the path, then each folder's mix over the stack outside it. + // Back up: the layers after the path, then each folder's mix over the stack outside it for d in (0..=reach).rev() { if let Some(lv) = levels.get(d) { self.taped(tape, |t| t.eval(&lv.above, &mut acc)); @@ -2100,10 +2116,11 @@ impl<'a, 'b> Texel<'a, 'b> { if tri == NO_TRI { return true; } + let first = tri.saturating_mul(3); let subs = &self.inp.mesh.submeshes; let holds = |k: usize| subs.get(k).is_some_and(|s| s.start <= first && first < s.start.saturating_add(s.count)); - // Submeshes are in index order; anything else is searched. + // Submeshes are in index order; anything else is searched let k = subs.partition_point(|s| s.start <= first).checked_sub(1).filter(|k| holds(*k)).or_else(|| (0..subs.len()).find(|k| holds(*k))); k.and_then(|k| allowed.get(k).copied()).unwrap_or(true) } @@ -2154,7 +2171,7 @@ impl<'a, 'b> Texel<'a, 'b> { fn painted(&mut self, data: Option<&[u16]>, c: &ChanPlan, preview: bool) -> ([f32; 3], f32) { let pv = if preview { self.inp.preview } else { None }; let mut sa = pv.map(|p| (self.stroke * p.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); - // Projection: the stencil's alpha shapes the stroke and its color is the base color. + // Projection: the stencil's alpha shapes the stroke and its color is the base color let stencil = match pv.and_then(|p| p.stencil.as_ref()) { Some(st) if sa > 0.0 => { let s = self.world().and_then(|w| st.sample_world(w)); @@ -2200,6 +2217,7 @@ impl<'a, 'b> Texel<'a, 'b> { if cov <= 0.0 { return ([0.0; 3], 0.0); } + let inv = 1.0 / cov.max(1e-5); let v = if c.comps == 3 { val.map(|x| x * inv) } else { [val[0] * inv; 3] }; (v, cov.min(1.0)) @@ -2272,7 +2290,37 @@ pub const BLOCK: u32 = 16; /// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and /// filling it). Results are identical to [`composite_tiles`]. -pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { +pub fn composite_tiles_cached(inputs: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) { + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(inputs, &projectors); + composite_evaluation_tiles(&inputs, out, tiles, below); +} + +/// Composite tile batches with a reusable cache for the mesh owned by the caller. +pub fn composite_tiles_with_projectors( + inputs: &Inputs, + mesh: &Arc, + projectors: &mut ProjectorDepthCache, + out: &mut Composite, + tiles: &[(u32, u32)], + mut below: Option<&mut BelowCache>, +) { + if !std::ptr::eq(inputs.mesh, mesh.as_ref()) { + composite_tiles_cached(inputs, out, tiles, None); + return; + } + + if projectors.bind(mesh) + && let Some(cache) = below.as_deref_mut() + { + cache.clear(); + } + + let inputs = EvaluationInputs::new(inputs, projectors); + composite_evaluation_tiles(&inputs, out, tiles, below); +} + +fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) { let Ok(set) = inp.project.texture_set(inp.ts) else { return }; if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { return; @@ -2378,7 +2426,7 @@ fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { /// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`), /// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`. -fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { +fn block_fields(inp: &EvaluationInputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { match hot { Some(hot) if fresh.len() < tiles.len() => { let mut fields = fields_of(inp, channels, stack, fresh); @@ -2402,7 +2450,7 @@ type Joined = (Vec>>>, bool); /// Composite one block of tiles, split along the path to the hot layer when `below` holds it; /// returns what to cache (for at most `quota` tiles). fn composite_block( - inp: &Inputs, + inp: &EvaluationInputs, stack: &[LayerId], out: &mut Composite, tiles: &[(u32, u32)], @@ -2421,7 +2469,7 @@ fn composite_block( let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); - // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy. + // Tiles split into bands of rows, so a handful of tiles still keeps every thread busy let bands = TILE / BAND; let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect(); let mut results: Vec = tasks @@ -2459,11 +2507,13 @@ fn composite_block( if y >= h { break; } + for lx in 0..TILE { let x = tx * TILE + lx; if x >= w { break; } + let gbuffer_index = (y * w + x) as usize; let tile_offset = (ly * TILE + lx) as usize; let band_offset = ((ly - band * BAND) * TILE + lx) as usize; @@ -2473,11 +2523,11 @@ fn composite_block( any = true; let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset)); - // Reuse one anchor buffer per band. + // Reuse one anchor buffer per band texel.anchors = std::mem::take(&mut anchors); match &levels { Some(levels) => { - // The texel's stream starts with the stack at each level. + // The texel's stream starts with the stack at each level let start = match &mut tape { Tape::Record(t) => { t.resize(t.len() + slots, 0.0); @@ -2518,7 +2568,7 @@ fn composite_block( }) .collect(); - // Join the bands of each tile (in parallel; uncovered tiles are freed). + // Join the bands of each tile (in parallel; uncovered tiles are freed) let joined: Vec = results .par_chunks(bands as usize) .map(|parts| { @@ -2545,7 +2595,7 @@ fn composite_block( } } - // Tiles without covered texels cost nothing to composite: not worth caching. + // Tiles without covered texels cost nothing to composite: not worth caching if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::>>() { records.push(((tx, ty), bands)); } @@ -2676,6 +2726,8 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) /// orientation of the exported maps), `gbuf.width × gbuf.height` of them; black outside the mesh /// Returns None without an enabled mask pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); 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); @@ -2684,7 +2736,7 @@ pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { // 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 fields = evaluation_fields(inputs, &channels, &coordinates); let width_usize = width as usize; let tile_side = TILE as usize; let mut output = vec![0.0f32; width_usize * height as usize]; @@ -2709,6 +2761,8 @@ pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { /// Keep preview tiles at 8 bits instead of retaining the export's full float atlas /// Returns None without an enabled mask pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); 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); @@ -2717,7 +2771,12 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { // 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 fields = evaluation_fields(inputs, &channels, &coordinates); + let size = size.max(1); + if size <= width.min(height) && (width != size || height != size) { + return Some(downsample_mask(inputs, id, mask, &channels, &fields, size)); + } + let width_usize = width as usize; let tile_side = TILE as usize; let mut atlas = vec![0u8; width_usize * height as usize]; @@ -2736,7 +2795,6 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { } }); - let size = size.max(1); if width == size && height == size { return Some(atlas); } @@ -2756,6 +2814,49 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { Some(output) } +/// Sample a smaller mask image directly into disjoint output row groups +fn downsample_mask(inputs: &EvaluationInputs, id: LayerId, mask: &Mask, channels: &[Channel], fields: &Fields, size: u32) -> Vec { + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let source_at = |pixel, span| ((u64::from(pixel) * u64::from(span)) / u64::from(size)) as u32; + let first_output = |source, span| (u64::from(source) * u64::from(size)).div_ceil(u64::from(span)).min(u64::from(size)) as u32; + let mut output = vec![0; size as usize * size as usize]; + let mut destination = output.as_mut_slice(); + let mut bands = Vec::with_capacity(height.div_ceil(TILE) as usize); + + // Partition rows by the tile that contains each row's source texels + for tile_y in 0..height.div_ceil(TILE) { + let first_row = first_output(tile_y * TILE, height); + let past_row = first_output((tile_y + 1) * TILE, height); + if past_row > first_row { + let (rows, rest) = destination.split_at_mut((past_row - first_row) as usize * size as usize); + bands.push((tile_y, first_row, past_row, rows)); + destination = rest; + } + } + + bands.into_par_iter().for_each(|(tile_y, first_row, past_row, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let first_column = first_output(tile_x * TILE, width); + let past_column = first_output((tile_x + 1) * TILE, width); + if first_column == past_column { + continue; + } + + let offsets = (first_row..past_row).flat_map(|row| { + let y = source_at(row, height) % TILE; + (first_column..past_column).map(move |column| (y * TILE + source_at(column, width) % TILE) as usize) + }); + let texels = mask_tile(inputs, id, mask, channels, fields, (tile_x, tile_y), offsets); + let pixels = rows.chunks_exact_mut(size as usize).flat_map(|row| &mut row[first_column as usize..past_column as usize]); + for (pixel, (_, value)) in pixels.zip(texels) { + *pixel = (value * 255.0 + 0.5) as u8; + } + } + }); + + output +} + /// The layer mask as one-component values at the texture set's full resolution over `tiles` /// (uncovered texels read zero). Clone and smudge read it. Unlike [`mask_image`] it also reads a /// disabled mask; None when the layer has no mask. @@ -2767,11 +2868,13 @@ pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option /// Evaluate requested tiles directly into the stroke's mask image. pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> { + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id)?; let channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); - let fields = neighbourhood_fields(inputs, &channels, tiles); + let fields = evaluation_fields(inputs, &channels, tiles); let computed: Vec<((u32, u32), Vec)> = tiles .par_iter() .map(|&tile| { @@ -2794,6 +2897,8 @@ pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], imag /// 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 projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; let mut output = vec![0.0; texels.len()]; @@ -2818,7 +2923,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option = requested .par_iter_mut() .flat_map_iter(|(&tile, requests)| { @@ -2841,7 +2946,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option( - inputs: &'a Inputs<'a>, + inputs: &'a EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, channels: &[Channel], @@ -2902,6 +3007,8 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u } }; let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; + let projectors = ProjectorDepthCache::default(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); 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 @@ -2981,7 +3088,9 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti l.visible = true; } let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; - let fields = neighbourhood_fields(&visible_inputs, &channels, tiles); + let projectors = ProjectorDepthCache::default(); + let visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + let fields = evaluation_fields(&visible_inputs, &channels, tiles); let out: Vec> = tiles .par_iter() @@ -3155,6 +3264,7 @@ mod tests { // Not repeating, it crops to its tile, so it has to know where each texel lands let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(coords_lookups(&f) > 0); } @@ -3173,6 +3283,7 @@ mod tests { // Not repeating, it crops to its tile, so each texel works its coverage out let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") }; fill.sampling.wrap = texturecraft_core::UvWrap::None; + assert!(cover_calls(&f) > 0); } @@ -3229,17 +3340,20 @@ mod tests { cache.ahead.clear(); composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache)); + assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers"); cache.ahead = all_tiles(resolution, resolution).into_iter().skip(1).collect(); composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields); cache.clear(); + assert!(weak_fields.upgrade().is_none(), "invalidating the cache releases intermediate anchor stages too"); composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache)); let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields); drop(cache); + assert!(weak_fields.upgrade().is_none(), "dropping the cache releases a cancelled run's fields"); } } @@ -3334,6 +3448,7 @@ mod tests { f.project.layer_mut(id).unwrap().mask = Some(mask); let out = run(&f, None); let vals: Vec = (0..64).map(|x| out.value(Channel::BaseColor, x, 20)[0]).collect(); + assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } @@ -3390,13 +3505,17 @@ mod tests { // 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()); } @@ -3440,6 +3559,7 @@ mod tests { assert_eq!(atlas.len(), 128 * 64); assert!(preview.contains(&0)); assert!(preview.contains(&255)); + for ((&preview_value, &sparse_value), &(x, y)) in preview.iter().zip(&sparse).zip(&sampled_texels) { assert!((f32::from(preview_value) / 255.0 - sparse_value).abs() <= 0.5 / 255.0 + 1e-6); assert!((atlas[(y * 128 + x) as usize] - sparse_value).abs() <= 1e-6); @@ -3497,6 +3617,7 @@ mod tests { 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"); } } @@ -3650,6 +3771,7 @@ mod tests { assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}"); assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}"); assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}"); + for texel in far { assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}"); } @@ -3852,10 +3974,12 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [0.0, 1.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 5, 5)); assert!(close(out.value(Channel::Roughness, 5, 5), [0.2; 3]), "a hue shift leaves scalars alone"); + content_fx(&mut f, id, EffectKind::Filter(Filter::Invert)); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [1.0, 0.0, 1.0])); assert!(close(out.value(Channel::Roughness, 5, 5), [0.8; 3])); + // Hidden effects are skipped and opacity fades an effect let fx = &mut f.project.layer_mut(id).unwrap().content_effects; fx[0].visible = false; @@ -3907,8 +4031,10 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 30, 30), [0.5; 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); assert!(close(out.value(Channel::Roughness, 30, 30), [0.5; 3])); + f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != hp); content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 64.0 })); + assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.0; 3])); // A checker's borders light up while cell interiors stay black @@ -3945,7 +4071,9 @@ soft {soft:?}" let rc = Filter::ReplaceColor { from: [0.8, 0.1, 0.1], to: [0.1, 0.1, 0.8], tolerance: 0.1, softness: 0.1 }; assert!(close(rc.point(ChannelKind::Color, [0.85, 0.1, 0.1]).unwrap(), [0.15, 0.1, 0.8])); assert!(close(rc.point(ChannelKind::Color, [0.1, 0.8, 0.1]).unwrap(), [0.1, 0.8, 0.1])); + let half = rc.point(ChannelKind::Color, [0.8, 0.1 + 0.15 * 3f32.sqrt(), 0.1]).unwrap(); + assert!((half[2] - 0.45).abs() < 0.02, "halfway through the softness: {half:?}"); assert_eq!(rc.point(ChannelKind::Scalar, [0.8; 3]), Some([0.8; 3])); } @@ -3990,6 +4118,7 @@ soft {soft:?}" let mut f = fixture(); let id = fill_layer(&mut f.project, [0.1; 3], 0.2); content_fx(&mut f, id, EffectKind::Filter(Filter::Glow { radius: 32.0, amount: 1.0 })); + assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.4; 3])); } @@ -4063,7 +4192,9 @@ soft {soft:?}" let images = ImageStore::default(); let inp = inputs(&f, &images, None); let flat = flatten_layer(&inp, id, &all_tiles(64, 64)).unwrap(); + assert!(flat.iter().all(|(c, _, _)| *c == Channel::Roughness)); + let (_, _, data) = flat.iter().find(|(_, t, _)| *t == (0, 0)).unwrap(); let o = 3 * TILE as usize + 3; assert!((from_u16(data[o * 2]) - 0.55).abs() < 1e-3 && (from_u16(data[o * 2 + 1]) - 1.0).abs() < 1e-3); @@ -4508,6 +4639,7 @@ soft {soft:?}" composite_tiles(&inp, &mut out, &all_tiles(64, 64)); out.value(Channel::BaseColor, 32, 32) }; + assert!(close(texel(&f, [false, false]), [1.0, 0.0, 0.0]), "the left half shows red"); assert!(close(texel(&f, [true, false]), [0.0, 0.0, 1.0]), "Flip U shows the right half there"); assert!(close(texel(&f, [false, true]), [1.0, 0.0, 0.0]), "Flip V leaves the left half"); @@ -4533,12 +4665,13 @@ soft {soft:?}" fn a_shrunk_cropped_frames_coverage_averages_its_image_alpha_as_its_colour_does() { let f = decal_fixture(|fill| fill.sampling.filtering = Filtering::BilinearHq); - // Red columns a texel wide, opaque and see-through in turn, far finer than the frame's texels; not a power of two, so a full-size read lands anywhere between two columns + // Odd-width alternating alpha stripes exercise minification between source texels const SIZE: u32 = 1000; let stripes = (0..SIZE * SIZE).map(|i| [1.0, 0.0, 0.0, if i % 2 == 0 { 1.0 } else { 0.0 }]).collect(); let shown = decal_texels(&composite_with_decal(&f, crate::store::ImageRes::new(SIZE, SIZE, stripes, false))); assert!(!shown.is_empty(), "the frame shows"); + let half = [0.75, 0.25, 0.25]; assert!( shown.iter().all(|v| v.iter().zip(half).all(|(got, want)| (got - want).abs() < 0.05)), diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs new file mode 100644 index 00000000..6f50f143 --- /dev/null +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -0,0 +1,23 @@ +use std::ops::Deref; + +use super::Inputs; +use crate::ProjectorDepthCache; + +pub(super) struct EvaluationInputs<'a> { + inputs: &'a Inputs<'a>, + pub(super) projectors: &'a ProjectorDepthCache, +} + +impl<'a> EvaluationInputs<'a> { + pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self { + Self { inputs, projectors } + } +} + +impl<'a> Deref for EvaluationInputs<'a> { + type Target = Inputs<'a>; + + fn deref(&self) -> &Self::Target { + self.inputs + } +} diff --git a/crates/compose/src/eval/thumbnail.rs b/crates/compose/src/eval/thumbnail.rs index 92290afe..e7bf4f7e 100644 --- a/crates/compose/src/eval/thumbnail.rs +++ b/crates/compose/src/eval/thumbnail.rs @@ -1,6 +1,9 @@ //! Isolated folder evaluation with the original stack available for anchor inputs. -use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed}; +use super::{ + Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Texel, all_tiles, evaluation_fields, plan, tile_texels, to_u16, + to_u16_signed, +}; /// Composite one layer over channel defaults, keeping anchors from the stack below it. pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option { @@ -8,7 +11,9 @@ pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) let channels = set.channel_list(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let tiles = all_tiles(width, height); - let fields = neighbourhood_fields(inputs, &channels, &tiles); + let projectors = ProjectorDepthCache::default(); + let inputs = &EvaluationInputs::new(inputs, &projectors); + let fields = evaluation_fields(inputs, &channels, &tiles); let mut composite = Composite::with_size(&[channel], width, height); let output = composite.channels.get_mut(&channel)?; diff --git a/crates/compose/src/fill_copies.rs b/crates/compose/src/fill_copies.rs index cd4fc02a..b14464c4 100644 --- a/crates/compose/src/fill_copies.rs +++ b/crates/compose/src/fill_copies.rs @@ -104,13 +104,16 @@ mod tests { let mut mirror = symmetry(SymmetryKind::Mirror, 0); mirror.position = [0.5, 0.0, 0.0]; let left: Vec = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert_eq!(left.len(), 2); // The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5)); assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5)); assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5)); + let right: Vec = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect(); + assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5)); } @@ -120,6 +123,7 @@ mod tests { radial.count = 4; radial.flip = [true, false]; let copies: Vec = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect(); + assert_eq!(copies.len(), 4); assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5)); assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5)); @@ -129,6 +133,7 @@ mod tests { // A texel on +Y lies in copy 1's wedge, so copy 1 comes first there let on_y: Vec = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect(); + assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5)); } diff --git a/crates/compose/src/frame_placement.rs b/crates/compose/src/frame_placement.rs index 0adac17b..91574127 100644 --- a/crates/compose/src/frame_placement.rs +++ b/crates/compose/src/frame_placement.rs @@ -240,6 +240,7 @@ mod tests { let flat = folded(&proj).unwrap(); let Projector { rotation, scale, crop, .. } = projector_of(&flat); assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed"); + close(&samples(&proj), &samples(&flat)); } let unturned = planar(Projector::default()); @@ -263,6 +264,7 @@ mod tests { match folded(&proj) { Some(flat) => { assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed"); + close(&samples(&proj), &samples(&flat)); } None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"), @@ -286,11 +288,15 @@ mod tests { let width = folded(&proj).unwrap().frame().unwrap().size[0]; let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap(); + assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width"); + let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap(); + assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre"); } let place = placement(&planar(Projector::default()), BOUNDS).unwrap(); + assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size"); assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None); assert_eq!(placement(&Projection::default(), BOUNDS), None); @@ -300,8 +306,11 @@ mod tests { fn a_frames_upright_turn_is_its_turn_round_its_normal() { let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() }; assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3); + flat.rotation = -100.0; + assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3); + let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() }; assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up"); } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 206f1437..ccf2d252 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -28,6 +28,7 @@ pub mod pattern; mod pattern_context; pub mod projector_cover; pub mod projector_depth; +mod projector_depth_cache; pub mod projector_view; pub mod solo; pub mod store; @@ -42,9 +43,11 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, - covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, + composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, + stack_reads_neighbours, }; pub use pattern_context::PatternContext; +pub use projector_depth_cache::ProjectorDepthCache; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index f94b1d8b..bf2b319e 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -678,6 +678,25 @@ pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option< local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos; } + frame_position(frame, local) +} + +/// Read the position and facing of one sample when a placed frame culls by angle +pub(crate) fn frame_sample(frame: &Decal, projector: &Projector, position: Vec3, surface_normal: Vec3) -> Option<(Vec3, f32)> { + let (origin, right, up, normal) = decal_axes(frame)?; + let from_origin = position - origin; + let local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal)); + + if !projector.turns() { + return Some((frame_position(frame, local)?, surface_normal.dot(normal))); + } + + let normal = Vec3::new(surface_normal.dot(right), surface_normal.dot(up), surface_normal.dot(normal)); + let sample = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: normal }); + Some((frame_position(frame, sample.pos)?, sample.nrm.z)) +} + +fn frame_position(frame: &Decal, local: Vec3) -> Option { let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z); local.is_finite().then_some(local) } @@ -750,6 +769,7 @@ mod tests { // Coarse reads are exact at cell centers and blend between them assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5); + let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5; assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse)); assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); @@ -823,6 +843,7 @@ mod tests { } let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO); assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}"); + let placed = Projection::Planar { scale: 1.0, axis: 2, @@ -832,6 +853,7 @@ mod tests { placed: Some(frame), }; assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way"); + for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] { let before = uv * Vec2::from(tiling) + Vec2::from(offset); assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before"); @@ -909,6 +931,7 @@ mod tests { } assert!(largest_difference < 1.0 / 65535.0, "worst difference {largest_difference}"); + let near_axis = triplanar_weights(Vec3::new(0.2, 1.0, 0.1).normalize(), 8.0, 1.0); assert_eq!((near_axis.x, near_axis.z), (0.0, 0.0), "{near_axis}"); diff --git a/crates/compose/src/projector_cover.rs b/crates/compose/src/projector_cover.rs index e19a6c73..7c5bf358 100644 --- a/crates/compose/src/projector_cover.rs +++ b/crates/compose/src/projector_cover.rs @@ -5,7 +5,7 @@ use texturecraft_geom::glam::{Vec2, Vec3}; use crate::frame_placement::warp_reach; use crate::organic::smoothstep; -use crate::pattern::{Coords, depth_fade, frame_crop, frame_facing, frame_local, placed_uv, projector_local}; +use crate::pattern::{Coords, depth_fade, frame_crop, frame_local, frame_sample, placed_uv, projector_local}; use crate::warp::warp_uv; /// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out @@ -94,8 +94,13 @@ pub fn backface_cover(backface: &Backface, facing: f32) -> f32 { /// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate) pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { - let local = frame_local(frame, projector, p)?; - let mut cover = if projector.backface.on { backface_cover(&projector.backface, frame_facing(frame, projector, nrm)) } else { 1.0 }; + let (local, mut cover) = if projector.backface.on { + let (local, facing) = frame_sample(frame, projector, p, nrm)?; + (local, backface_cover(&projector.backface, facing)) + } else { + (frame_local(frame, projector, p)?, 1.0) + }; + if projector.crop == ShapeCrop::Cropped { cover *= frame_crop(frame, local); } @@ -273,8 +278,10 @@ mod tests { let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0); let before = symmetric_before(&frame, p, nrm, center); mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none()); + assert_eq!(before, now, "{p} {nrm}"); } + assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not"); } } diff --git a/crates/compose/src/projector_depth.rs b/crates/compose/src/projector_depth.rs index bf0aafcd..5b87c7a8 100644 --- a/crates/compose/src/projector_depth.rs +++ b/crates/compose/src/projector_depth.rs @@ -1,7 +1,6 @@ //! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use texturecraft_core::Projection; use texturecraft_geom::Mesh; @@ -21,63 +20,41 @@ pub struct ProjectorDepth { front: Vec<[f32; 3]>, } -/// Built maps by their view and the mesh they come from -type CacheEntry = (ProjectorView, u64, Arc); - /// The smallest grid cell across and up, so a flat view still divides const MIN_CELL_SIZE: f32 = 1e-6; /// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps const EDGE_TOLERANCE: f32 = 1e-6; -static CACHE: Mutex> = Mutex::new(Vec::new()); - impl ProjectorDepth { - /// The depth map of `proj` over `mesh` within `bounds`, built once per view and mesh; None unless `proj` culls by depth - pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), proj: &Projection) -> Option> { - let view = ProjectorView::of(proj, bounds)?; - let mesh_key = fingerprint(mesh); - - // Built with the cache locked: the build runs no parallel work, and tiles asking for the same map wait for it instead of building it again - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(at) = cache.iter().position(|(cached_view, cached_mesh, _)| *cached_view == view && *cached_mesh == mesh_key) { - let (cached_view, cached_mesh, depth) = cache.remove(at); - cache.insert(0, (cached_view, cached_mesh, depth.clone())); - return Some(depth); - } - - let depth = Arc::new(ProjectorDepth::build(view, mesh)?); - cache.insert(0, (view, mesh_key, depth.clone())); - cache.truncate(CACHE_MAPS); - Some(depth) - } - - /// Drop every built map: a mesh replacing another (a reimport, another project) can share the old one's fingerprint - pub fn forget_all() { - CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); + /// Build the depth map of a borrowed mesh, if the projection uses depth culling. + pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option> { + let view = ProjectorView::of(projection, bounds)?; + Self::build(view, mesh).map(Arc::new) } /// Rasterize every triangle of `mesh` in `view`, keeping the nearest per cell (None when no vertex lands in the view) pub fn build(view: ProjectorView, mesh: &Mesh) -> Option { - let local: Vec> = mesh.positions.iter().map(|position| view.local(*position)).collect(); - let (lo, hi) = local + let projected: Vec> = mesh.positions.iter().map(|position| view.local(*position)).collect(); + let (min, max) = projected .iter() .flatten() .fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate()))); - if lo.x > hi.x || lo.y > hi.y { + if min.x > max.x || min.y > max.y { return None; } - let cell = ((hi - lo) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE)); - let mut depth = ProjectorDepth { view, origin: lo, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] }; + let cell = ((max - min) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE)); + let mut depth = ProjectorDepth { view, origin: min, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] }; let mut budget = CELL_BUDGET; - for tri in mesh.indices.as_chunks::<3>().0 { - let corner = |i: u32| local.get(i as usize).copied().flatten(); - let (Some(a), Some(b), Some(c)) = (corner(tri[0]), corner(tri[1]), corner(tri[2])) else { continue }; + for &[first, second, third] in mesh.indices.as_chunks::<3>().0 { + let corner = |i: u32| projected.get(i as usize).copied().flatten(); + let (Some(a), Some(b), Some(c)) = (corner(first), corner(second), corner(third)) else { continue }; if !depth.raster([a, b, c], &mut budget) { break; } } + Some(depth) } @@ -85,15 +62,16 @@ impl ProjectorDepth { fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool { let [a, b, c] = triangle; let (d1, d2) = (b - a, c - a); - let det = d1.x * d2.y - d1.y * d2.x; - if !det.is_finite() || det.abs() < MIN_SCREEN_AREA { - // Seen edge on, it covers nothing + let determinant = d1.x * d2.y - d1.y * d2.x; + if !determinant.is_finite() || determinant.abs() < MIN_SCREEN_AREA { + // An edge-on triangle covers no cells return true; } - let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / det, (d1.x * d2.z - d2.x * d1.z) / det).clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE)); + let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / determinant, (d1.x * d2.z - d2.x * d1.z) / determinant) + .clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE)); - // Corners in cells: cell (i, j) has its centre at (i + 0.5, j + 0.5) + // Evaluate coverage at cell centres let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell); let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc)); let first = |v: f32| (v - 0.5).ceil().clamp(0.0, SIZE as f32) as usize; @@ -122,17 +100,18 @@ impl ProjectorDepth { } } } + true } /// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front - pub fn cover(&self, p: Vec3, hardness: f32) -> f32 { - // A hand-edited NaN hardness keeps the layer visible rather than making its texels NaN + pub fn cover(&self, position: Vec3, hardness: f32) -> f32 { + // Keep the layer visible when a hand-edited hardness is invalid if !hardness.is_finite() { return 1.0; } - let Some(view_point) = self.view.local(p) else { return 1.0 }; + let Some(view_point) = self.view.local(position) else { return 1.0 }; let at = (view_point.truncate() - self.origin) / self.cell; if !(at.x >= 0.0 && at.y >= 0.0 && at.x < SIZE as f32 && at.y < SIZE as f32) { return 1.0; @@ -141,13 +120,13 @@ impl ProjectorDepth { let (x, y) = (at.x as usize, at.y as usize); let Some(&[near, across, up]) = self.front.get(y * SIZE + x).filter(|cell| cell[0].is_finite()) else { return 1.0 }; - // The nearest surface's plane carried from the cell centre to the point, so a surface is never behind itself + // Extend the cell's plane to avoid culling a surface against itself let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell; let slope = Vec2::new(across, up); let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z; let unit = self.view.unit(); - // Neighbouring triangles of a curved surface part from the carried plane by about one cell of its slope + // Add slope bias for curvature across adjacent triangles let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit); let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit; if width <= f32::EPSILON { @@ -163,19 +142,6 @@ fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 { (b - a).perp_dot(q - a) } -/// Which mesh a map was built for: its sizes and a spread of its vertices and indices -fn fingerprint(mesh: &Mesh) -> u64 { - let mut hasher = DefaultHasher::new(); - (mesh.positions.len(), mesh.indices.len()).hash(&mut hasher); - for position in mesh.positions.iter().step_by((mesh.positions.len() / FINGERPRINT_SAMPLES).max(1)) { - position.to_array().map(f32::to_bits).hash(&mut hasher); - } - for index in mesh.indices.iter().step_by((mesh.indices.len() / FINGERPRINT_SAMPLES).max(1)) { - index.hash(&mut hasher); - } - hasher.finish() -} - /// Cells across and up the grid const SIZE: usize = 512; @@ -197,12 +163,6 @@ const MAX_SLOPE_BIAS: f32 = 0.05; /// How far behind the nearest surface culling fades out at hardness 0, in mesh radii const FADE: f32 = 0.1; -/// Maps kept built (each is about 3 MB) -const CACHE_MAPS: usize = 8; - -/// Vertices and indices the mesh fingerprint reads -const FINGERPRINT_SAMPLES: usize = 64; - #[cfg(test)] mod tests { use super::*; @@ -254,22 +214,21 @@ mod tests { } #[test] - fn a_mesh_edited_where_its_fingerprint_does_not_look_is_rebuilt_once_forgotten() { - // Unused vertices spread the fingerprint's samples so the front square's right edge is not among them + fn interleaved_meshes_keep_their_own_projector_depth() { let mut mesh = two_squares(0.5, -0.5); - mesh.positions.extend((0..FINGERPRINT_SAMPLES * 3).map(|_| Vec3::ZERO)); + // Add enough unused vertices for the old sample to skip the changed edge + mesh.positions.resize(200, Vec3::ZERO); let mut edited = mesh.clone(); for right in [1, 2] { edited.positions[right].x = 0.5; } - assert_eq!(fingerprint(&mesh), fingerprint(&edited), "the edit is unseen by the fingerprint"); + assert_eq!(mesh.bounds(), edited.bounds()); + let proj = planar_z(true, 1.0); let behind_the_cut = Vec3::new(0.75, 0.3, -0.5); let bounds = mesh.bounds(); assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0); - ProjectorDepth::forget_all(); - let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap(); assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more"); } diff --git a/crates/compose/src/projector_depth_cache.rs b/crates/compose/src/projector_depth_cache.rs new file mode 100644 index 00000000..658e480d --- /dev/null +++ b/crates/compose/src/projector_depth_cache.rs @@ -0,0 +1,97 @@ +use std::sync::{Arc, Mutex, Weak}; + +use texturecraft_core::Projection; +use texturecraft_geom::{Mesh, glam::Vec3}; + +use crate::{projector_depth::ProjectorDepth, projector_view::ProjectorView}; + +type ViewDepth = (ProjectorView, Option>); + +// Each map holds about 3 MiB +const MAX_CACHED_VIEWS: usize = 8; + +/// Reuse projector depth maps for one mesh across tile batches. +#[derive(Default)] +pub struct ProjectorDepthCache { + mesh: Weak, + maps: Mutex>, +} + +impl ProjectorDepthCache { + pub(crate) fn bind(&mut self, mesh: &Arc) -> bool { + if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) { + self.maps.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); + self.mesh = Arc::downgrade(mesh); + return true; + } + + false + } + + pub(crate) fn get(&self, mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option> { + let view = ProjectorView::of(projection, bounds)?; + + // Rasterization is serial so tile workers can wait for a single build + let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(index) = maps.iter().position(|(cached_view, _)| *cached_view == view) { + let entry = maps.remove(index); + let depth = entry.1.clone(); + maps.insert(0, entry); + return depth; + } + + let depth = ProjectorDepth::build(view, mesh).map(Arc::new); + maps.insert(0, (view, depth.clone())); + maps.truncate(MAX_CACHED_VIEWS); + + depth + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::{Projector, UvTransform}; + use texturecraft_geom::primitives; + + #[test] + fn eviction_and_mesh_replacement_release_maps_after_the_last_reader() { + let mut cache = ProjectorDepthCache::default(); + let mut mesh = Arc::new(primitives::plane(2.0, 2)); + let mesh_reference = Arc::downgrade(&mesh); + let bounds = mesh.bounds(); + let mut maps = Vec::new(); + let mut first_reader = None; + + cache.bind(&mesh); + for angle_degrees in 0..MAX_CACHED_VIEWS + 4 { + let mut projector = Projector::depth_culled(); + projector.rotation[2] = angle_degrees as f32; + let projection = Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }; + let map = cache.get(&mesh, bounds, &projection).unwrap(); + let reused = cache.get(&mesh, bounds, &projection).unwrap(); + assert!(Arc::ptr_eq(&map, &reused)); + maps.push(Arc::downgrade(&map)); + if angle_degrees == 0 { + first_reader = Some(map); + } + } + + assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS + 1); + drop(first_reader); + assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS); + + // Mutating a uniquely held Arc disassociates its weak references + Arc::make_mut(&mut mesh).positions[0].y += 1.0; + assert!(mesh_reference.upgrade().is_none()); + cache.bind(&mesh); + assert!(maps.iter().all(|map| map.upgrade().is_none())); + + let projection = + Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None }; + let last_map = Arc::downgrade(&cache.get(&mesh, mesh.bounds(), &projection).unwrap()); + + drop(cache); + assert!(last_map.upgrade().is_none()); + } +} diff --git a/crates/compose/src/solo.rs b/crates/compose/src/solo.rs index 3703ba57..c9d17f5a 100644 --- a/crates/compose/src/solo.rs +++ b/crates/compose/src/solo.rs @@ -103,6 +103,7 @@ mod tests { p.layer_mut(rust).unwrap().visible = false; let before = p.clone(); let view = solo_project(&p, rust, false).unwrap(); + assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off"); assert!(!view.layers[&below].visible, "the others are hidden"); assert!(view.layers[&other_set].visible, "another texture set keeps its layers"); @@ -117,9 +118,12 @@ mod tests { let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false); let view = solo_project(&p, inner, false).unwrap(); + assert!(view.layers[&folder].visible && view.layers[&inner].visible); assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible); + let whole = solo_project(&p, folder, false).unwrap(); + assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents"); assert!(!whole.layers[&outside].visible); } @@ -134,8 +138,11 @@ mod tests { masked(&mut p, id); } let kept = solo_project(&p, inner, false).unwrap(); + assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays"); + let view = solo_project(&p, inner, true).unwrap(); + assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled); assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched"); assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask"); @@ -148,6 +155,7 @@ mod tests { masked(&mut p, source); let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false); let view = solo_project(&p, instance, true).unwrap(); + assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled); assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask"); } @@ -159,6 +167,7 @@ mod tests { let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false); let view = solo_project(&p, instance, false).unwrap(); + assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible); } diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 43d9b19a..e7b78d3b 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -124,6 +124,7 @@ impl ImageRes { if !u.is_finite() || !v.is_finite() { return [0.0; 4]; } + bilinear(&self.rgba, self.width, self.height, u, v, (true, true)) } diff --git a/crates/compose/src/tile_length.rs b/crates/compose/src/tile_length.rs index c08e668f..21a2872b 100644 --- a/crates/compose/src/tile_length.rs +++ b/crates/compose/src/tile_length.rs @@ -6,12 +6,9 @@ use texturecraft_core::{FULL_TURN_DEGREES, Projection}; use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch}; -/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV) -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct MeshSize { - pub radius: f32, - pub uv_density: f32, -} +mod mesh_size; + +pub use mesh_size::MeshSize; /// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round) fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { diff --git a/crates/compose/src/tile_length/mesh_size.rs b/crates/compose/src/tile_length/mesh_size.rs new file mode 100644 index 00000000..9d433361 --- /dev/null +++ b/crates/compose/src/tile_length/mesh_size.rs @@ -0,0 +1,6 @@ +/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshSize { + pub radius: f32, + pub uv_density: f32, +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 406d8480..4ec0863e 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -214,12 +214,14 @@ fn mask_with_height_follows_the_layer_height() { let row = TILE * 2; let (left, right) = (16, RES - 16); let v = |c: &Composite, x| c.value(Channel::BaseColor, x, row)[0]; + assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray"); assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left)); assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right)); // Without a mask there is nothing to combine f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false; + assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3); } @@ -544,11 +546,13 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() { f.project.layer_mut(low).unwrap().content_effects.insert(0, blur); let blurred = reference(&f, 0); assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat"); + let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES); let (images, baked) = (Default::default(), Default::default()); for t in all_tiles(RES, RES) { composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]); } + assert!(one_by_one == blurred); } @@ -584,7 +588,9 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { for t in all_tiles(RES, RES) { composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]); } + assert!(one_by_one == want, "per-tile composites differ from one pass"); + for hot in [top, streaks] { assert!(!check_cached(&f, 0, hot).is_empty()); } @@ -665,6 +671,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); + assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it"); assert!(!cache.holds_fields()); @@ -677,6 +684,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { let mut inp = inputs(&fixture, 0, &images, &baked); inp.preview = Some(&preview); composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache)); + assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs"); } @@ -719,7 +727,9 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { cache.set_hot(Some(hot)); let mut out = Composite::new(&channels, SIZE); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache)); + assert_eq!(cache.len(), bottom.len()); + cache.budget = cache.bytes(); // Cache eviction during the run must rebuild missing lower-layer fields @@ -731,6 +741,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { assert!(cache.holds_fields()); } } + assert!(above.len() > bottom.len()); assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path"); } @@ -790,13 +801,17 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() { fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); let input = inputs(&fixture, 0, &images, &baked); composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image"); let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); } } @@ -832,11 +847,14 @@ fn cached_stack_tracks_referenced_images_only() { let replacement = image_with_value(0.4); let replacement_weak = Arc::downgrade(&replacement); images.insert("used".into(), replacement); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels"); + previous_image = Some(replacement_weak); } "remove" => { images.remove("used"); + assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels"); } "cold" => {} @@ -848,13 +866,17 @@ fn cached_stack_tracks_referenced_images_only() { fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); let input = inputs(&fixture, 0, &images, &baked); composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}"); let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); } } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 267f05c2..34664b03 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -10,31 +10,41 @@ mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; +mod filtering; mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; +mod sampling; +mod scale_mode; mod tile_blending; mod tile_generator; mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_transform; +mod uv_wrap; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; +pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; +pub use sampling::Sampling; +pub use scale_mode::ScaleMode; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_transform::UvTransform; +pub use uv_wrap::UvWrap; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -103,6 +113,7 @@ impl HeightMask { if !self.enabled || !h.is_finite() { return m; } + (m + self.contrast * 4.0 * m * (1.0 - m) * (h + self.offset)).clamp(0.0, 1.0) } } @@ -244,27 +255,6 @@ pub enum Projection { }, } -/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct UvTransform { - pub tiling: [f32; 2], - pub rotation: f32, - pub offset: [f32; 2], -} - -impl Default for UvTransform { - fn default() -> Self { - UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } - } -} - -impl UvTransform { - /// Whether it changes nothing, as projections saved before it existed did (not saved then) - pub fn is_default(&self) -> bool { - *self == UvTransform::default() - } -} - /// The frame a planar projection placed on the surface (a decal) projects from, in world space #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Decal { @@ -1789,6 +1779,7 @@ mod tests { ]; for saved in fills { let loaded: Fill = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); } @@ -1798,6 +1789,7 @@ mod tests { ]; for saved in effects { let loaded: EffectKind = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); } } diff --git a/crates/core/src/layer/filtering.rs b/crates/core/src/layer/filtering.rs new file mode 100644 index 00000000..2f5667bb --- /dev/null +++ b/crates/core/src/layer/filtering.rs @@ -0,0 +1,30 @@ +use serde::{Deserialize, Serialize}; + +/// How a fill reads its image sources between texels +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Filtering { + /// Bilinear on the image level that matches the texel's footprint: smooth when the image is shrunk + #[default] + BilinearHq, + /// Bilinear on the full image: sharp, but may shimmer where the image is shrunk + BilinearSharp, + /// The nearest image texel + Nearest, +} + +impl Filtering { + pub const ALL: [Filtering; 3] = [Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + Filtering::BilinearHq => "bilinearHq", + Filtering::BilinearSharp => "bilinearSharp", + Filtering::Nearest => "nearest", + } + } + + pub fn from_id(id: &str) -> Option { + Filtering::ALL.into_iter().find(|f| f.id() == id) + } +} diff --git a/crates/core/src/layer/sampling.rs b/crates/core/src/layer/sampling.rs new file mode 100644 index 00000000..9fa568fb --- /dev/null +++ b/crates/core/src/layer/sampling.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +use super::{Filtering, ScaleMode, UvWrap}; +use crate::FillSymmetry; + +/// How a fill samples its images and what its size is set in; older fills read with [`Sampling::SAVED_BEFORE`] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)] +pub struct Sampling { + #[serde(default)] + pub filtering: Filtering, + #[serde(default)] + pub wrap: UvWrap, + #[serde(default)] + pub scale: ScaleMode, + #[serde(default, skip_serializing_if = "FillSymmetry::is_default")] + pub symmetry: FillSymmetry, +} + +impl Sampling { + /// What fills saved before the sampling choices existed did: plain bilinear + pub const SAVED_BEFORE: Sampling = + Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF }; + + /// Serde default for fills saved before the field existed + pub fn saved_before() -> Sampling { + Sampling::SAVED_BEFORE + } + + /// Whether it samples as fills saved before the field existed did (not saved then, so they save as they were) + pub fn is_saved_before(&self) -> bool { + *self == Sampling::SAVED_BEFORE + } +} diff --git a/crates/core/src/layer/scale_mode.rs b/crates/core/src/layer/scale_mode.rs new file mode 100644 index 00000000..b9659eb6 --- /dev/null +++ b/crates/core/src/layer/scale_mode.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// What a fill's size is set in: repeats of its tile, or the tile's length on the mesh (stored as tiling either way) +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum ScaleMode { + #[default] + Tiling, + PhysicalSize, +} + +impl ScaleMode { + pub const ALL: [ScaleMode; 2] = [ScaleMode::Tiling, ScaleMode::PhysicalSize]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + ScaleMode::Tiling => "tiling", + ScaleMode::PhysicalSize => "physicalSize", + } + } + + pub fn from_id(id: &str) -> Option { + ScaleMode::ALL.into_iter().find(|mode| mode.id() == id) + } +} diff --git a/crates/core/src/layer/uv_transform.rs b/crates/core/src/layer/uv_transform.rs new file mode 100644 index 00000000..e341ea19 --- /dev/null +++ b/crates/core/src/layer/uv_transform.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct UvTransform { + pub tiling: [f32; 2], + pub rotation: f32, + pub offset: [f32; 2], +} + +impl Default for UvTransform { + fn default() -> Self { + UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } + } +} + +impl UvTransform { + /// Whether it changes nothing, as projections saved before it existed did (not saved then) + pub fn is_default(&self) -> bool { + *self == UvTransform::default() + } +} diff --git a/crates/core/src/layer/uv_wrap.rs b/crates/core/src/layer/uv_wrap.rs new file mode 100644 index 00000000..4ff480ff --- /dev/null +++ b/crates/core/src/layer/uv_wrap.rs @@ -0,0 +1,40 @@ +use serde::{Deserialize, Serialize}; + +/// Whether a UV-placed fill repeats past its 0..1 tile, across, down, both or neither +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum UvWrap { + #[default] + Repeat, + RepeatHorizontally, + RepeatVertically, + /// One tile only: outside it the fill does not cover + None, +} + +impl UvWrap { + pub const ALL: [UvWrap; 4] = [UvWrap::None, UvWrap::RepeatHorizontally, UvWrap::RepeatVertically, UvWrap::Repeat]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + UvWrap::Repeat => "repeat", + UvWrap::RepeatHorizontally => "repeatHorizontally", + UvWrap::RepeatVertically => "repeatVertically", + UvWrap::None => "none", + } + } + + pub fn from_id(id: &str) -> Option { + UvWrap::ALL.into_iter().find(|w| w.id() == id) + } + + /// Whether the fill repeats across (u) and down (v) + pub fn repeats(self) -> (bool, bool) { + match self { + UvWrap::Repeat => (true, true), + UvWrap::RepeatHorizontally => (true, false), + UvWrap::RepeatVertically => (false, true), + UvWrap::None => (false, false), + } + } +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 7bbb1aa5..7b6c92c2 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -841,6 +841,7 @@ mod tests { l.as_object_mut().unwrap().remove("content_effects"); } let old: Project = serde_json::from_value(v).unwrap(); + assert!(old.layers.values().all(|l| l.content_effects.is_empty())); } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index d49e7afe..255ff27c 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -238,7 +238,7 @@ fn framed(session: &Session, command: &str, id: LayerId, effect: Option return Err(bad(command, "an axis planar reading a procedural pattern keeps its axis: placing its frame would move the pattern")); } - // A frame faces one way: culling read through an uneven or mirrored scale would hide other faces once the scale is in the frame (a placed frame keeps its edits that move no frame) + // Keep the active projection while folding scaling would change which faces cull if matches!(projection, Projection::Planar { placed: None, .. }) && !culling_keeps_facing(projection) { return Err(bad(command, UNFOLDABLE_CULLING)); } diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index f1c5317b..6d50a4c4 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -51,6 +51,7 @@ pub fn at_defaults(projection: &Projection, sampling: Sampling) -> bool { fn reset_projection(s: &mut Session, p: &Value) -> Result { let target = fill_target(s, p, "layer.fill.resetProjection")?; let (projection, sampling) = placement_mut(s, target)?; + if at_defaults(projection, *sampling) { return Ok(Value::Null); } @@ -61,6 +62,7 @@ fn reset_projection(s: &mut Session, p: &Value) -> Result { *sampling = reset_sampling(*sampling); Ok(()) })?; + Ok(Value::Null) } @@ -84,6 +86,7 @@ mod tests { flip: [false; 2], }; let mut kinds: Vec = UNFRAMED_PROJECTION_IDS.iter().filter_map(|id| new_unframed_projection(id)).collect(); + assert_eq!(kinds.len(), UNFRAMED_PROJECTION_IDS.len(), "every listed id makes a projection"); kinds.extend([Projection::warp(frame), Projection::decal(frame)]); @@ -94,7 +97,9 @@ mod tests { } other => other, }; + let reset = reset_projection_of(&turned); + assert_eq!(std::mem::discriminant(&reset), std::mem::discriminant(&kind), "{kind:?}"); assert_eq!(reset.frame(), kind.frame(), "the frame stays where it is placed"); } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index d5936ece..86fd4a55 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -13,6 +13,10 @@ use crate::commands::{ use crate::layer_selection::{batch_param, ids_json}; use crate::{EngineError, Result, Session, cmd, session::StackTarget}; +mod fill_target; + +pub(crate) use fill_target::FillTarget; + /// One full turn, in degrees (the brush's, so every angle wraps on the same turn) pub(crate) use texturecraft_paint::FULL_TURN_DEGREES; diff --git a/crates/engine/src/layer_cmds/fill_target.rs b/crates/engine/src/layer_cmds/fill_target.rs new file mode 100644 index 00000000..62cfaa7c --- /dev/null +++ b/crates/engine/src/layer_cmds/fill_target.rs @@ -0,0 +1,8 @@ +use texturecraft_core::LayerId; + +/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's (`effect`) +#[derive(Clone, Copy)] +pub(crate) enum FillTarget { + Layer(LayerId), + Effect(LayerId), +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index d20a81e5..e1f352c7 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -247,6 +247,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { if !s.doc.resources.contains_key(&name) { return Err(bad("resource.remove", format!("no resource `{name}`"))); } + s.edit("Remove resource", |s| { s.doc.resources.remove(&name); Ok(()) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 8a036f72..83a8461d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -1,6 +1,6 @@ //! The editing session: document, mesh, per-texture-set caches, history, tool state. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; use std::sync::Arc; use serde::{Deserialize, Serialize}; @@ -60,7 +60,7 @@ impl SetCache { pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache { let (w, h) = ts.size(); let gbuf = UvGBuffer::new(mesh, ts.material, w, h); - // Padding stays inside each UV tile. + // Padding stays inside each UV tile let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution()); let covered = covered_tiles(&gbuf); let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect(); @@ -476,6 +476,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, + /// Projection fill depth maps shared by this session's tile batches. + projector_depth_cache: texturecraft_compose::ProjectorDepthCache, /// The polygon fill box being dragged pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). @@ -497,9 +499,6 @@ impl Session { let source = Arc::new(mesh); let mesh = tiled_mesh(&source, &doc.project); - // Depth maps built for the mesh this one replaces must not be taken for its own - texturecraft_compose::projector_depth::ProjectorDepth::forget_all(); - let bvh = Bvh::new(&mesh); let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (bounds_min, bounds_max) = mesh.bounds(); @@ -547,6 +546,7 @@ impl Session { log: crate::log::SessionLog::new(), log_id: next_mesh_id(), depth_cache: None, + projector_depth_cache: Default::default(), polygon_fill_drag: None, export_presets: Default::default(), brush_presets: Default::default(), @@ -827,9 +827,11 @@ impl Session { if changed.is_empty() && before.texture_sets.len() == self.doc.project.texture_sets.len() { return; } + self.mesh = tiled_mesh(&self.source, &self.doc.project); self.mesh_id = next_mesh_id(); self.depth_cache = None; + self.projector_depth_cache = Default::default(); for ts in changed { if let (Some(c), Some(set)) = (self.caches.get_mut(ts), self.doc.project.texture_sets.get(ts)) { *c = SetCache::new(&self.mesh, set); @@ -1021,6 +1023,7 @@ impl Session { let solo_view = if self.pending_tiles() > 0 { self.solo_view() } else { None }; let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); + let mut mesh_bounds = None; let mut changed = false; for ts in order { let Some(cache) = self.caches.get_mut(ts) else { continue }; @@ -1058,12 +1061,19 @@ impl Session { block_scales: cache.composite.block_scales.clone(), preview, images: &self.images, - bounds: self.mesh.bounds(), + bounds: *mesh_bounds.get_or_insert_with(|| self.mesh.bounds()), }; // Look ahead so sliced updates filter a run of tiles once cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() }; - texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); + texturecraft_compose::composite_tiles_with_projectors( + &inputs, + &self.mesh, + &mut self.projector_depth_cache, + &mut cache.composite, + &tiles, + Some(&mut cache.below), + ); // The composited tiles and the neighbours their padding reached change let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); @@ -1247,7 +1257,7 @@ const CHUNK: usize = 256; /// The most a budgeted update spends on settling tiles (what they show is already right). pub const SETTLE_BUDGET_MS: f64 = 6.0; -/// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters +/// Take up to `max_tiles` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters /// evaluate compact regions. fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> { // A zero-sized request cannot select a pivot @@ -1259,17 +1269,26 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u return std::mem::take(dirty).into_iter().collect(); } - let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect(); - - // Partition by block order so only the requested chunk needs sorting - tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); - tiles.truncate(max_tiles); - tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x)); - for tile in &tiles { - dirty.remove(tile); + // Keep only the earliest block-ordered tiles in this chunk + let block_order = |(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x); + let mut keys = dirty.iter().copied().map(block_order); + let mut selected: BinaryHeap<_> = keys.by_ref().take(max_tiles).collect(); + for key in keys { + if let Some(mut latest) = selected.peek_mut() + && key < *latest + { + *latest = key; + } } - tiles + selected + .into_sorted_vec() + .into_iter() + .map(|(_, _, y, x)| { + dirty.remove(&(x, y)); + (x, y) + }) + .collect() } /// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited. diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index bd6bdd13..0fd6c6e4 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -513,17 +513,23 @@ mod tests { let (mut service, jobs, results) = held_worker(); service.begin_frame(&session, 0.0); service.get(&session, target); + assert!(service.poll(&session)); + let job = jobs.try_recv().unwrap(); results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap(); service.begin_frame(&session, 0.1); + assert!(service.get(&session, target).image.is_none()); + let repaint = service.poll(&session); assert!(service.is_fresh(target)); assert!(repaint, "the frame drew before collecting the final thumbnail"); + service.begin_frame(&session, 0.2); + assert!(service.get(&session, target).image.is_some()); assert!(!service.poll(&session), "an idle cache must stop repainting"); } @@ -539,6 +545,7 @@ mod tests { service.begin_frame(&session, 0.1); service.poll(&session); + assert_eq!(jobs.try_recv().map(|job| job.target).ok(), Some(target), "the late request is dispatched, not dropped"); } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index fc85fd59..6d77ebf5 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -499,10 +499,14 @@ mod tests { #[test] fn hdr_resources_become_the_environment() { let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected"); + let e = execute(&mut s, "display.set", &json!({"environment": "nonexistent"})).unwrap_err().to_string(); + assert!(e.contains("Studio Soft"), "unknown environments are rejected with the valid names: {e}"); assert_eq!(s.doc.project.display.environment, "Studio Soft"); + execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap(); let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3])); let mut hdr = Vec::new(); @@ -510,6 +514,7 @@ mod tests { let name = s.import_resource_bytes("sky.hdr", hdr).unwrap(); let res = &s.images[&name]; assert!(!res.srgb && res.rgba[0][0] > 30.0, "HDR keeps values above 1"); + let env = format!("resource:{name}"); let r = execute( &mut s, @@ -517,12 +522,16 @@ mod tests { &json!({"environment": env, "specGloss": true, "parallax": true, "displacement": true, "taa": false, "scatterColor": [2.0, 0.5, 0.25], "scatterRadius": 0.3}), ) .unwrap(); + assert_eq!(r["environment"], json!(env)); + let d = &s.doc.project.display; assert!(d.spec_gloss && d.parallax && d.displacement && !d.taa); assert_eq!((d.scatter_color, d.scatter_radius), ([1.0, 0.5, 0.25], 0.3), "scatter settings (clamped)"); assert_eq!(d.environment_resource(), Some(name.as_str())); + execute(&mut s, "file.removeUnused", &Value::Null).unwrap(); + assert!(s.doc.resources.contains_key(&name), "the environment's image counts as used"); } @@ -530,16 +539,21 @@ mod tests { fn the_projection_gizmos_hide_per_project_and_old_projects_show_them() { let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); let shown = serde_json::to_value(&s.doc.project.display).unwrap(); + assert!(s.doc.project.display.projection_gizmos && shown.get("projection_gizmos").is_none(), "shown by default and saved as before: {shown}"); let hidden = execute(&mut s, "display.set", &json!({"projectionGizmos": false})).unwrap(); + assert!(!s.doc.project.display.projection_gizmos); assert_eq!(hidden["projection_gizmos"], json!(false), "hidden is saved with the project"); assert!(s.history_labels().is_empty(), "a view flag is no undo step"); let reopened: texturecraft_core::project::DisplaySettings = serde_json::from_value(hidden).unwrap(); + assert!(!reopened.projection_gizmos, "a saved project opens with its gizmos hidden"); + let old: texturecraft_core::project::DisplaySettings = serde_json::from_value(shown).unwrap(); + assert!(old.projection_gizmos, "a project saved before the flag shows them"); } } diff --git a/crates/engine/tests/it/fill_patterns.rs b/crates/engine/tests/it/fill_patterns.rs index c5d854ba..18ba302c 100644 --- a/crates/engine/tests/it/fill_patterns.rs +++ b/crates/engine/tests/it/fill_patterns.rs @@ -57,6 +57,7 @@ fn a_pattern_parameter_given_alone_keeps_every_other_one() { } let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"balance\":-0.5") && inspected.contains("\"invert\":false"), "inspect shows the balance and invert"); } @@ -65,5 +66,6 @@ fn a_pattern_parameter_given_alone_keeps_every_other_one() { fn another_pattern_kind_starts_from_its_defaults() { let (mut session, layer) = clouds_fill(); execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "procedural": "Cells"})).unwrap(); + assert_eq!(roughness(&session, layer), (Procedural::new(ProceduralKind::Cells), [0.0; 3], [1.0; 3])); } diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 5d9d18de..23711592 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -50,12 +50,19 @@ fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() { let plain = snapshot(&mut s); set(&mut s, layer, json!({"projectorRotation": [30, 45, 60]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: rotation turns the pattern"); + set(&mut s, layer, json!({"projectorRotation": [0, 0, 0], "projectorScale": [2, 0.5, 1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: per-axis scale stretches the pattern"); + set(&mut s, layer, json!({"projectorScale": 1, "offset": [0.3, 0.2, 0.1]})); + assert_ne!(snapshot(&mut s), plain, "{kind}: offset moves the pattern"); + set(&mut s, layer, json!({"offset": 0})); + assert_eq!(snapshot(&mut s), plain, "{kind}: the defaults change nothing"); set(&mut s, layer, json!({"projectorRotation": [10, 20, 30], "projectorScale": [1, 2, 3]})); @@ -71,6 +78,7 @@ fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() { other => panic!("{kind}: loaded as {other:?}"), }; assert_eq!(settings, Projector::default(), "{kind}: an older save has no turn or stretch"); + set(&mut s, layer, json!({"projectorRotation": 0, "projectorScale": 1})); } @@ -118,9 +126,12 @@ fn match_per_uv_tile_repeats_the_source_once_per_tile() { assert_ne!(left, right, "a UV projection runs on into the next tile"); set(&mut s, layer, json!({"projection": "uvTile"})); + assert_eq!(projection(&s, layer), Projection::UvTile); + let (left, right) = tiles(&mut s); let worst = left.iter().zip(&right).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 1e-4, "every tile shows the same pattern (worst difference {worst})"); } @@ -132,13 +143,17 @@ fn cylindrical_angle_is_the_arc_one_repeat_spans() { set(&mut s, layer, json!({"projection": "cylindrical"})); let plain = snapshot(&mut s); set(&mut s, layer, json!({"angle": 120})); + assert!(matches!(projection(&s, layer), Projection::Cylindrical { angle: 120.0, .. })); assert_ne!(snapshot(&mut s), plain, "a third of the way round repeats three times"); + set(&mut s, layer, json!({"angle": 360})); + assert_eq!(snapshot(&mut s), plain, "360 degrees is the whole way round"); let mut saved = serde_json::to_value(projection(&s, layer)).unwrap(); saved["Cylindrical"].as_object_mut().unwrap().remove("angle"); + assert!(matches!(serde_json::from_value(saved).unwrap(), Projection::Cylindrical { angle: 360.0, .. })); } @@ -160,6 +175,7 @@ fn shape_crop_stops_a_projection_at_its_shape() { set(&mut s, layer, json!({"projection": "triplanar"})); let plain = snapshot(&mut s); set(&mut s, layer, json!({"shapeCrop": "cropped"})); + assert_eq!(snapshot(&mut s), plain, "the default box holds the whole mesh"); set(&mut s, layer, json!({"projectorScale": 0.5})); @@ -186,6 +202,7 @@ fn backface_culling_keeps_a_planar_projection_off_faces_turned_away() { let (far, near) = (facing_z(&s, -1.1, -0.05), facing_z(&s, 0.05, 1.1)); assert!(!far.is_empty() && !near.is_empty()); assert!(far.iter().any(|&i| plain[i] != empty[i]), "without culling the projection reaches the far side"); + set(&mut s, layer, json!({"backfaceCulling": true, "backfaceAngle": 90, "backfaceHardness": 1})); let culled = snapshot(&mut s); assert!(far.iter().all(|&i| culled[i] == empty[i]), "faces turned away get none of the projection"); @@ -241,6 +258,7 @@ fn placed_planars_with_a_decals_look_save_as_decals() { let fill = Fill { projection: Projection::decal(frame), ..Fill::default() }; let saved = serde_json::to_value(&fill).unwrap(); + assert_eq!(saved["projection"], json!({ "Decal": frame })); assert_eq!(serde_json::from_value::(saved).unwrap(), fill, "and reads back the same"); @@ -248,6 +266,7 @@ fn placed_planars_with_a_decals_look_save_as_decals() { let Projection::Planar { uv, .. } = &mut turned.projection else { panic!("{:?}", turned.projection) }; uv.rotation = 30.0; let saved = serde_json::to_value(&turned).unwrap(); + assert_eq!(saved["projection"]["Planar"]["placed"], json!(frame)); assert_eq!(serde_json::from_value::(saved).unwrap(), turned); } @@ -265,6 +284,7 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() assert_eq!((corners, depth), (Projection::FRAME_CORNERS, Projection::WARP_DEPTH)); assert_eq!((frame.normal, frame.up), ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), "seen from the front"); assert!(frame.size.iter().all(|side| (side - 2.0).abs() < 1e-3) && frame.center.iter().all(|c| c.abs() < 1e-3), "around the unit sphere: {frame:?}"); + let unpulled = snapshot(&mut s); assert_ne!(unpulled, empty); @@ -272,7 +292,9 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() set(&mut s, layer, json!({"warpCorners": pulled})); let bent = snapshot(&mut s); assert_ne!(bent, unpulled, "a pulled corner bends the image"); + set(&mut s, layer, json!({"projection": "warp", "rotation": 0})); + assert_eq!(snapshot(&mut s), bent, "picking warp again keeps the corners"); set(&mut s, layer, json!({"shapeCrop": "cropped", "warpCorners": Projection::FRAME_CORNERS})); @@ -283,6 +305,7 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() assert!(!beyond.is_empty() && !within.is_empty()); assert!(beyond.iter().all(|&i| cropped[i] == empty[i]), "past its Projection Depth the warp does not reach"); assert!(within.iter().all(|&i| cropped[i] == unpulled[i]), "within it the warp covers as before"); + set(&mut s, layer, json!({"projectionDepth": 1})); let deep = snapshot(&mut s); assert!(beyond.iter().all(|&i| deep[i] == unpulled[i]), "a deeper warp reaches the whole sphere"); @@ -291,15 +314,20 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); let Projection::Warp { frame: reset, corners, depth, .. } = projection(&s, layer) else { panic!("still a warp") }; assert_eq!((reset, corners, depth), (frame, Projection::FRAME_CORNERS, 1.0), "the frame and corners go back; the depth stays"); + let steps = s.history_labels().len(); execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a frame already reset adds no undo step"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projection"], "Warp projection"); assert_eq!(row["fill"]["projectionSettings"]["Warp"]["corners"], json!(Projection::FRAME_CORNERS)); + set(&mut s, layer, json!({"projection": "planar"})); + assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset"); } @@ -314,6 +342,7 @@ fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { set(&mut s, layer, json!({"projection": "planar", "axis": 2})); let Projection::Planar { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; assert_eq!(projector.depth, DepthCulling::NEW, "a new planar projection culls by depth"); + let culled = snapshot(&mut s); set(&mut s, layer, json!({"depthCulling": false})); let plain = snapshot(&mut s); @@ -326,18 +355,23 @@ fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() { assert!(near.iter().all(|&i| culled[i] == plain[i]), "the near side keeps all of it"); set(&mut s, layer, json!({"depthCulling": true, "depthCullingHardness": 0})); + assert_ne!(snapshot(&mut s), culled, "a softer cull fades further behind the near side"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["projectionSettings"]["Planar"]["projector"]["depth"], json!({"on": true, "hardness": 0.0})); set(&mut s, layer, json!({"projection": "warp"})); let Projection::Warp { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) }; assert_eq!(projector.depth, DepthCulling::NEW, "a new warp culls by depth"); + let warped = snapshot(&mut s); assert!(far.iter().all(|&i| warped[i] == empty[i]), "a warp from the front leaves the far side bare"); let saved: Projector = serde_json::from_value(json!({"rotation": [0, 0, 0], "scale": [1, 1, 1]})).unwrap(); + assert_eq!(saved.depth, DepthCulling { on: false, hardness: 0.75 }, "an older save has no depth culling"); } @@ -357,13 +391,17 @@ fn fill_symmetry_axis_reads_an_index_or_a_letter() { }; set(&mut s, layer, json!({"symmetryAxis": "Y"})); + assert_eq!(axis(&s), 1); + set(&mut s, layer, json!({"symmetryAxis": 2})); + assert_eq!(axis(&s), 2); for refused in [json!("w"), json!(true), json!(-1), json!(3)] { assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": refused})).is_err(), "{refused}"); } + assert_eq!(axis(&s), 2, "a refused axis changes nothing"); } @@ -392,7 +430,9 @@ fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() { assert!(filled(&far, &turned, &empty) > far.len() / 2, "the copy turned half round reaches the far side"); assert!(near.iter().all(|&i| turned[i] == plain[i]), "the original keeps its own wedge"); assert_ne!(turned, mirrored, "a turned copy is not a mirrored one"); + set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), plain, "switched off, the copies go"); // A left to right ramp shows a copy's image turned over @@ -408,11 +448,14 @@ fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() { set(&mut s, layer, json!({"projection": "uv"})); let uv = snapshot(&mut s); set(&mut s, layer, json!({"symmetry": false})); + assert_eq!(snapshot(&mut s), uv, "a UV projection has no copies"); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryType": "spiral"})).is_err()); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": 3})).is_err()); + let saved: Sampling = serde_json::from_value(json!({"filtering": "BilinearHq", "wrap": "Repeat", "scale": "Tiling"})).unwrap(); + assert_eq!(saved.symmetry, FillSymmetry::OFF, "an older save has no symmetry"); } @@ -431,23 +474,28 @@ fn moving_an_axis_planar_places_it_as_its_frame_first() { let placed = projection(&s, layer); let Projection::Planar { placed: Some(frame), projector, .. } = &placed else { panic!("placed: {placed:?}") }; assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "the turn is in the frame now"); + let after = snapshot(&mut s); let moved = before.iter().zip(&after).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); assert!(moved * 200 < before.len(), "the image stays where it was: {moved} of {} texels changed", before.len()); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.4, 0.0], "merge": true})).unwrap(); + assert_ne!(snapshot(&mut s), after, "then the frame moves the image"); let Projection::Planar { placed: Some(slid), .. } = projection(&s, layer) else { panic!("still placed") }; assert_eq!((slid.offset, slid.size), ([0.4, 0.0], frame.size)); s.undo().unwrap(); + assert_eq!(projection(&s, layer), axis, "placing and moving is one step"); set(&mut s, layer, json!({"projection": "warp", "warpCorners": [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]})); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap(); let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("still a warp") }; assert_eq!((frame.rotation, corners[1]), (30.0, [0.9, 0.9]), "a warp's frame turns and keeps its corners"); + set(&mut s, layer, json!({"projection": "spherical"})); + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).is_err(), "a spherical projection has no frame"); } @@ -486,6 +534,7 @@ fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing( if placed { set(&mut s, layer, json!({"projectorScale": 1})); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap(); + assert!(projection(&s, layer).placed().is_some(), "an even scale places the frame"); } @@ -502,6 +551,7 @@ fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing( // A placed frame's edit that moves no frame still lands execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "flipU": true})).unwrap(); + assert!(projection(&s, layer).frame().is_some_and(|frame| frame.flip[0]), "the flip lands on the placed frame"); } @@ -524,10 +574,14 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first( execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameOffset": [0.0, 0.0, 0.0]})).unwrap(); let Projection::Planar { placed: Some(frame), projector, .. } = projection(&s, layer) else { panic!("still placed") }; assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "folded into the frame"); + let (lo, hi) = s.mesh.bounds(); assert!((Vec3::from(frame.center) - (lo + hi) * 0.5).length() < 1e-4, "offset 0 = the mesh's centre: {frame:?}"); + let shown = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((shown.rotation[2] - 30.0).abs() < 1e-3 && shown.rotation[0].abs() < 1e-3, "the projector's turn shows as the frame's: {shown:?}"); + let folded = snapshot(&mut s); let changed = turned.iter().zip(&folded).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count(); assert!(changed * 200 < turned.len(), "the frame was already at the centre: the image stays, {changed} of {} texels changed", turned.len()); @@ -536,16 +590,21 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first( .unwrap(); let Projection::Planar { placed: Some(narrow), .. } = projection(&s, layer) else { panic!("still placed") }; assert!((narrow.size[0] - frame.size[0] * 0.5).abs() < 1e-4 && (narrow.size[1] - frame.size[1]).abs() < 1e-4, "Scale X halves the width"); + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameRotation": [0, 0, 90], "merge": true})).unwrap(); let again = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap(); + assert!((again.rotation[2] - 90.0).abs() < 1e-3 && (again.scale[0] - shown.scale[0] * 0.5).abs() < 1e-4, "{again:?}"); assert_eq!(s.history_labels().len(), steps + 1, "a drag is one undo step"); + s.undo().unwrap(); + assert_eq!(snapshot(&mut s), turned, "undo puts the turned projector back"); for bad in [json!({"frameScale": [1, 2]}), json!({"frameOffset": "x"}), json!({"frameScale": [0, -1, "deep"]})] { let mut params = bad.clone(); params["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.decal.set", ¶ms).is_err(), "{bad}"); } @@ -583,10 +642,12 @@ fn a_decal_edit_that_changes_nothing_adds_no_undo_step() { json!({"effect": mask_effect, "image": ramp}), ] { execute(&mut s, "layer.decal.set", &unchanged).unwrap(); + assert_eq!(s.history_labels().len(), steps, "{unchanged} changes nothing"); } execute(&mut s, "layer.decal.set", &json!({"layer": layer, "rotation": 45})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1, "a turn is an edit"); } @@ -625,6 +686,7 @@ fn inspect_shows_a_mask_decals_frame_as_a_layer_decals() { ] { assert!(on_request(frame), "the {name} shows its frame on the requested placement: {frame}"); } + assert_eq!(layer_frame, layer_decal["decal"], "a layer decal's frame"); assert_eq!(mask_effect["decal"], mask_decal["decal"], "a mask decal's frame"); } @@ -652,6 +714,7 @@ fn a_warps_current_reach_as_depth_adds_no_undo_step() { let reach = depth * frame.size[0].max(frame.size[1]); execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": reach})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "reach {reach} is the one it has"); } @@ -705,17 +768,21 @@ fn reset_fill_settings_keeps_the_projection_and_restores_its_defaults_in_one_und assert_eq!(reset.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the sampling is a new fill's; the symmetry stays"); assert_eq!(reset.sources, changed.sources, "the material stays"); assert!(texturecraft_engine::fill_reset_cmds::at_defaults(&reset.projection, reset.sampling)); + let steps = s.history_labels().len(); execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "resetting a Fill section at its defaults adds no undo step"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill(&s), changed, "one undo brings every setting back"); assert!(execute(&mut s, "layer.fill.resetProjection", &json!({"layer": 9999})).is_err(), "no such layer"); // A UV fill comes back to a UV projection at tiling 1 and renders like a new fill set(&mut s, layer, json!({"projection": "uv", "tiling": [3, 2], "rotation": 30})); execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(fill(&s).projection, Projection::default()); assert_eq!(snapshot(&mut s), fresh, "it renders like the new fill"); } @@ -737,6 +804,7 @@ fn reset_fill_settings_keeps_a_warp_frame_and_restores_its_settings() { assert_ne!(moved, fitted, "the frame was moved"); execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap(); + assert_eq!(projection(&s, layer), Projection::warp(moved), "still a warp: its frame stays, every setting is a new warp's"); } @@ -760,6 +828,7 @@ fn malformed_warp_corners_copy_flips_and_a_warps_own_placement_are_rejected_and_ ] { let mut p = bad.clone(); p["layer"] = json!(layer.0); + assert!(execute(&mut s, "layer.fill.projection", &p).is_err(), "{bad}"); } diff --git a/crates/engine/tests/it/fill_sampling.rs b/crates/engine/tests/it/fill_sampling.rs index fd17f481..cfb64e15 100644 --- a/crates/engine/tests/it/fill_sampling.rs +++ b/crates/engine/tests/it/fill_sampling.rs @@ -71,10 +71,12 @@ fn filtering_decides_how_a_shrunk_image_reads() { let red = cache.composite.value(Channel::BaseColor, x, y)[0]; !(0.01..=0.99).contains(&red) }); + assert!(pure, "Nearest reads one image texel: black or white only"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["filtering"], json!("nearest")); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": "trilinear"})).is_err()); } @@ -90,6 +92,7 @@ fn fills_saved_before_filtering_keep_their_look() { let mut saved = serde_json::to_value(fill).unwrap(); saved.as_object_mut().unwrap().remove("sampling"); let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling, Sampling::SAVED_BEFORE); assert_eq!(loaded.sampling.filtering, Filtering::BilinearSharp); } @@ -126,18 +129,22 @@ fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() { let near = |got: f32, want: f32| (got - want).abs() < 0.05; let repeat = shown(&mut s); assert!(near(repeat, 1.0), "Repeat covers the band: {repeat}"); + set(&mut s, json!({"wrap": "none"})).unwrap(); let none = shown(&mut s); assert!(near(none, 0.125), "None: a quarter across, half down: {none}"); + set(&mut s, json!({"wrap": "repeatHorizontally"})).unwrap(); let across = shown(&mut s); assert!(near(across, 0.5), "repeating across: the whole width, half down: {across}"); + set(&mut s, json!({"wrap": "repeatVertically"})).unwrap(); let down = shown(&mut s); assert!(near(down, 0.25), "repeating down: a quarter across, the whole height: {down}"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["wrap"], json!("repeatVertically")); assert!(set(&mut s, json!({"wrap": "mirror"})).is_err()); @@ -187,12 +194,16 @@ fn three_d_projections_take_uv_transformations() { let mut saved = serde_json::to_value(projection(&s)).unwrap(); saved["Triplanar"].as_object_mut().unwrap().remove("uv"); let loaded: Projection = serde_json::from_value(saved).unwrap(); + assert!(matches!(loaded, Projection::Triplanar { uv, .. } if uv == UvTransform::default())); + set(&mut s, json!({"tiling": 1, "rotation": 0, "uvOffset": [0, 0]})).unwrap(); + assert_eq!(snapshot(&mut s), plain, "the identity transform changes nothing"); // On a UV projection, tiling is its scale set(&mut s, json!({"projection": "uv", "tiling": [2, 4]})).unwrap(); + assert!(matches!(projection(&s), Projection::Uv { scale, .. } if scale == [2.0, 4.0])); } @@ -208,11 +219,13 @@ fn scale_mode_is_stored_without_changing_the_tiling() { let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["scaleMode"], json!("physicalSize")); assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "inches"})).is_err()); let mut saved = serde_json::to_value(&fill).unwrap(); saved["sampling"].as_object_mut().unwrap().remove("scale"); let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling.scale, ScaleMode::Tiling); } diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 4ad6c736..26fcb753 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -133,6 +133,7 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); execute(&mut s, "effect.add.filter", &p).unwrap(); } + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite())); } @@ -187,10 +188,13 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { let name = s .import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] })) .unwrap(); + assert!(execute(&mut s, "layer.add.decal", &json!({"image": "missing.png"})).is_err()); assert!(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 2, "y": 2})).is_err(), "off the mesh"); + let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(); let layer = id(r.clone(), "layer"); + assert!((r["decal"]["size"][1].as_f64().unwrap() - 0.5).abs() < 1e-6); let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; assert!(matches!(f.projection, Projection::Planar { placed: Some(_), .. })); @@ -202,19 +206,30 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { // Bigger, then moved along its plane, then re-placed with a click execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0))); + execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap(); + assert!(!red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "moved away"); + let r = execute(&mut s, "layer.decal.set", &json!({"x": 170, "y": 180})).unwrap(); + assert_eq!(r["decal"]["offset"], json!([0.0, 0.0]), "re-placing resets the offset"); assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("Planar projection") && inspect.contains("\"decal\"") && inspect.contains("\"rotation\":45"), "inspect shows the decal"); + // Not a decal; one undo step per edit let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err()); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); } @@ -239,9 +254,13 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // Only the effect id, with no layer selected s.selected.clear(); + assert!(s.selected_layer().is_none()); + let r = execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "size": [0.3, 0.2], "offset": [0.1, -0.05], "rotation": 30, "depth": 0.2})).unwrap(); + assert_eq!(r["layer"], json!(layer.0), "the owning layer is reported"); + let after = effect_decal(&s, effect); assert_eq!((after.size, after.offset, after.rotation), ([0.3, 0.2], [0.1, -0.05], 30.0)); assert_eq!(after.center, before.center, "the other fields stay"); @@ -249,10 +268,12 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // Re-placing with a click execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer.0, "x": 170, "y": 180})).unwrap(); + assert_eq!(effect_decal(&s, effect).offset, [0.0, 0.0]); execute(&mut s, "edit.undo", &Value::Null).unwrap(); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect_decal(&s, effect), before, "undo restores the effect's decal"); // The layer decal is untouched by all of it @@ -261,8 +282,10 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // Errors: unknown effect, an effect that is not a decal, an effect of another layer assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err()); + execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap(); let levels = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": "levels"})).unwrap(), "effect"); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": levels.0, "size": 1})).is_err()); assert!(execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer_decal.0, "size": 1})).is_err()); assert_eq!(effect_decal(&s, effect), before); @@ -270,6 +293,7 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { // A new image replaces the effect's source, not a layer channel let other = s.import_resource_bytes("other.png", png(4, 4, |_, _| [0, 0, 0, 255])).unwrap(); execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "image": other})).unwrap(); + assert!(matches!(&s.doc.project.effect(effect).unwrap().1.kind, EffectKind::Fill { source: Source::Image { name, .. }, .. } if *name == other)); } @@ -281,8 +305,10 @@ fn decals_keep_the_image_aspect_and_flip_their_image() { let name = s.import_resource_bytes("wide.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap(); let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(); let layer = id(r.clone(), "layer"); + assert_eq!(r["decal"]["size"], json!([1.0, 0.5]), "a new decal follows its image"); assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra"); + let size = |s: &mut Session| { let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; let Projection::Planar { placed: Some(d), .. } = &f.projection else { panic!("a decal") }; @@ -291,33 +317,52 @@ fn decals_keep_the_image_aspect_and_flip_their_image() { // A pair of sides is taken as given, unless the proportions are kept: then the width wins execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.6]); + execute(&mut s, "layer.decal.set", &json!({"size": [0.8, 0.8], "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.8, 0.4], "the width sets the height by the image's aspect"); + execute(&mut s, "layer.decal.set", &json!({"size": 0.2, "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.4, 0.2], "a height sets the width"); + execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap(); execute(&mut s, "layer.decal.set", &json!({"keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.3], "turning the lock on fits the height to the width"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.6], "one undo step"); // Flip U and V each on their own, kept by later edits, undone one step at a time execute(&mut s, "layer.decal.set", &json!({"size": [1.0, 0.5]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && !red(at(&mut s, Channel::BaseColor, 210.0, 200.0))); + let r = execute(&mut s, "layer.decal.set", &json!({"flipU": true})).unwrap(); + assert_eq!(r["decal"]["flip"], json!([true, false])); assert!(!red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && red(at(&mut s, Channel::BaseColor, 210.0, 200.0)), "Flip U mirrors the image in its frame"); + execute(&mut s, "layer.decal.set", &json!({"flipV": true, "rotation": 10})).unwrap(); + assert_eq!(size(&mut s).1, [true, true]); + execute(&mut s, "layer.decal.set", &json!({"flipU": false})).unwrap(); + assert_eq!(size(&mut s).1, [false, true], "the other flip stays"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&mut s).1, [true, true]); // A new image in the same call sets the aspect: a tall one (1:2) let tall = s.import_resource_bytes("tall.png", png(4, 8, |_, _| [255, 0, 0, 255])).unwrap(); execute(&mut s, "layer.decal.set", &json!({"image": tall, "size": 0.4, "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.2, 0.4]); } @@ -505,28 +550,36 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() { let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5}); let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer"); + assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal"); assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel"); + let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap(); + assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks"); let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); let masked = id(added.clone(), "layer"); let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); + assert!( matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Planar { placed: Some(_), .. }, .. })) ); assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); + execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere"); let effect = &added["maskEffect"]; execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer"); let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4}); assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused"); @@ -686,24 +739,32 @@ fn fill_projection_edits_keep_what_they_do_not_change() { }; set(&mut s, json!({"rotation": 390, "offset": [0.25, 0.5]})).unwrap(); set(&mut s, json!({"scale": 2})).unwrap(); + assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 2.0], rotation: 30.0, offset: [0.25, 0.5] }, "a scale keeps the rotation and offset"); + set(&mut s, json!({"projection": "uv", "scale": [2, 3], "offset": "far"})).unwrap(); + assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 3.0], rotation: 30.0, offset: [0.25, 0.5] }, "the same kind keeps its fields; a bad offset is ignored"); + set(&mut s, json!({"projection": "triplanar", "offset": [1, 2, 3]})).unwrap(); set(&mut s, json!({"sharpness": 100})).unwrap(); + assert_eq!( proj(&s), Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0], uv: Default::default(), projector: Default::default() }, "a new kind starts from its defaults" ); + set(&mut s, json!({"projection": "planar", "axis": 7, "offset": [1e9, 0, 0]})).unwrap(); + assert_eq!( proj(&s), Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0], uv: Default::default(), projector: Projector::depth_culled(), placed: None }, "hostile values are clamped" ); assert!(set(&mut s, json!({"projection": "hexagonal"})).is_err()); - // The offset moves the pattern: a UV offset changes what the composite shows. + + // The offset moves the pattern: a UV offset changes what the composite shows set(&mut s, json!({"projection": "uv", "scale": 1})).unwrap(); execute( &mut s, @@ -934,6 +995,7 @@ fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited let bytes = session.to_project_bytes().unwrap(); let mut loaded = Session::from_project_bytes(&bytes).unwrap(); + assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2); execute(&mut loaded, "layer.decal.set", &json!({"layer": layer.0, "rotation": 12})).unwrap(); diff --git a/crates/engine/tests/it/user_smart_mask.rs b/crates/engine/tests/it/user_smart_mask.rs index 72916dcb..b51d7dd1 100644 --- a/crates/engine/tests/it/user_smart_mask.rs +++ b/crates/engine/tests/it/user_smart_mask.rs @@ -202,6 +202,7 @@ fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() { } assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask")); + let bytes = texturecraft_engine::formats::save_project_bytes(&file).unwrap(); let before = s.doc.project.clone(); let history = s.history_labels(); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index bf68e50b..cdb17b2e 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -610,7 +610,9 @@ mod tests { #[test] fn uv_density_is_mesh_units_per_uv_unit() { assert_eq!(quad().uv_density(0), Some(1.0)); + let plane = crate::primitives::plane(3.0, 4).uv_density(0).unwrap(); + assert!((plane - 3.0).abs() < 1e-4, "{plane}"); assert_eq!(quad().uv_density(1), None, "no triangles of that material"); } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 2cb62488..c7039666 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -496,6 +496,7 @@ mod tests { (None, Some(lib)) => lib.sample(shape.level, x, y), (None, None) => shape.alpha.sample(x, y, 0.4, 7), }; + assert_eq!(shape.sample(x, y, 0.4, 7).to_bits(), before.to_bits(), "{:?} at ({x}, {y})", shape.alpha); } } diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 39ab2e2b..43843f69 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -762,7 +762,7 @@ fn warmth(img: &Img) -> f32 { fn imported_hdr_environment_lights_the_ball() { let Some((mut h, frame)) = setup() else { return }; let base = render(&mut h, &frame, "env_default"); - // A procedural HDR: a hot orange sky over a dim blue ground (values far above 1). + // A procedural HDR: a hot orange sky over a dim blue ground (values far above 1) let (w, hh) = (256u32, 128u32); let rgba = (0..w * hh).map(|i| if i / w < hh / 2 { [12.0, 4.0, 1.0, 1.0] } else { [0.02, 0.05, 0.2, 1.0] }).collect(); let sky = ImageRes::new(w, hh, rgba, false); @@ -771,7 +771,9 @@ fn imported_hdr_environment_lights_the_ball() { assert_ne!(lit.px, base.px, "the imported environment changes the lighting"); assert!(warmth(&lit) > warmth(&base) + 10.0, "the orange sky tints the ball"); assert!(lit.mean(200, 100, 280, 180) > 20.0, "lit, finite shading (NaNs would render black)"); + h.renderer.set_environment(&h.device, &h.queue, "Studio Soft", None); + assert_eq!(render(&mut h, &frame, "env_default_again").px, base.px, "built-ins come back"); } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 27d8e91c..dd2a06d3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -519,7 +519,7 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, effect_group(app, ui, &layer, depth, true, false); } - // A line under the layer and its effects separates it from the next layer. + // A line under the layer and its effects separates it from the next layer let tokens = Tokens::get(ui.ctx()); let available = ui.available_rect_before_wrap(); ui.painter().hline(available.x_range(), available.top() - 0.5, Stroke::new(1.0, tokens.separator)); @@ -567,7 +567,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize // One of several selected layers (Shift/Ctrl+click) is highlighted like the active one let highlighted = selected || app.session.is_layer_selected(layer.id); - let several = selection_with(app, layer.id); let content_target = selected && targets_content(app); let preferred_size = layer_preview_size(app); let row_height = layer_row_height(preferred_size); @@ -849,8 +848,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); // Several selected layers move together, so none of them is a place to drop them - let in_drag = |dragged: u64| dragged == layer.id.0 || several.as_ref().is_some_and(|layers| layers.contains(&dragged)); - let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(*dragged)); + let in_drag = |app: &TextureCraftApp, dragged: u64| { + dragged == layer.id.0 || (app.session.is_layer_selected(layer.id) && app.session.is_layer_selected(LayerId(dragged))) + }; + let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(app, *dragged)); let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); if moving || shelf_material { @@ -867,7 +868,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } if let Some(dragged) = dnd_release::(&row) - && !in_drag(*dragged) + && !in_drag(app, *dragged) { match selection_with(app, LayerId(*dragged)) { Some(layers) => app.run("layer.move", json!({"layers": layers, "above": layer.id.0, "inside": inside})), @@ -1812,6 +1813,7 @@ mod image_menu_tests { harness.run_steps(30); assert!(preview_stats(&harness.ctx).0 > initial_previews, "scrolling creates newly visible previews"); + harness.get_by_label(&last_name).click(); harness.run_steps(2); diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs index 746c63e4..88aef1be 100644 --- a/crates/ui-egui/src/fill_panel.rs +++ b/crates/ui-egui/src/fill_panel.rs @@ -355,7 +355,7 @@ fn placement_rows( None => PreviewLower::Offset { values: &mut lower_offset, range: OFFSET_TRACK, typed: OFFSET_TYPED }, }; let placement = Placement { tiling, rotation, offset }; - let bounds = app.session.mesh.bounds(); + let bounds = app.viewport_mesh_bounds.get(&app.session.mesh); // A warp shows its frame's size and turn as its gizmo leaves them let warp = match &fill.projection { @@ -423,7 +423,7 @@ fn world_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &F let edited = |fields: &[NumberField]| -> Vec { fields.iter().map(|field| field.value).collect() }; // A placed planar or a warp: the frame, its projector folded in - if let Some(shown) = frame_placement::placement(&fill.projection, app.session.mesh.bounds()) { + if let Some(shown) = frame_placement::placement(&fill.projection, app.viewport_mesh_bounds.get(&app.session.mesh)) { let run = |app: &mut TextureCraftApp, key: &str, values: Vec, merge: bool| { app.run("layer.decal.set", with(base, json!({key: values, "merge": merge}))); }; diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 25c48d60..5a9fa0d7 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -386,6 +386,7 @@ mod tests { let placement = |offset: [f32; 2]| Placement { tiling: [2.0, 2.0], rotation: 30.0, offset }; let (still, rest) = slid_window(placement([0.0, 0.0])); assert_eq!(rest, [0.5, 0.5], "at Offset 0 the dot sits in the ring"); + let slid = placement([-0.25, 0.0]); let (columns, dot) = slid_window(slid); assert_eq!(columns, still, "the view never zooms or turns for the Offset"); diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs index 0a95f428..20e18818 100644 --- a/crates/ui-egui/src/fill_symmetry_panel.rs +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -30,11 +30,13 @@ const SPAN_SLIDER: usize = 1; pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, projection: &Projection, sampling: Sampling, base: &Value) { let symmetry = sampling.symmetry; let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields); + if !projection.takes_symmetry() { let reason = match projection { Projection::UvTile => tr("Not available with Fill (Match per UV Tile)"), _ => tr("Not available with UV projection"), }; + sheet.section_unavailable(tr("Symmetry"), reason); return; } @@ -51,10 +53,12 @@ pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySh if let Some(kind) = picked { run(app, json!({"symmetryType": kind.id()})); } + let axis = symmetry.axis_index(); if let Some(picked) = sheet.switch_tinted(tr("Axis"), &AXIS_NAMES, axis, &AXIS_COLORS) { run(app, json!({"symmetryAxis": picked})); } + if symmetry.kind == SymmetryKind::Radial { radial_rows(app, sheet, &symmetry, base); } @@ -86,10 +90,12 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr let picture = |painter: &Painter, rect: Rect| ring_picture(painter, rect, symmetry, axis_color, &tokens); let count = symmetry.copies(); let (mut count_value, mut span_value) = (count as f32, symmetry.span); + let mut sliders = [ StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" }, StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" }, ]; + let edited = sheet.picture_sliders(&picture, &mut sliders); if let Some((SPAN_SLIDER, merge)) = edited { run_projection(app, base, json!({"angleSpan": span_value, "merge": merge})); diff --git a/crates/ui-egui/src/frame_gizmo.rs b/crates/ui-egui/src/frame_gizmo.rs index 6b27767b..2671f4b2 100644 --- a/crates/ui-egui/src/frame_gizmo.rs +++ b/crates/ui-egui/src/frame_gizmo.rs @@ -101,7 +101,8 @@ impl FrameGizmo { if unplaced && placing_moves_pattern(sources.into_iter()) { return None; } - let placed = placed_from_axis(projection, app.session.mesh.bounds()); + + let placed = placed_from_axis(projection, app.viewport_mesh_bounds.get(&app.session.mesh)); // Where the projection lands: a projector's own turn and scale moved into the frame, as the panel's 3D projection settings show it let landed = folded(placed.as_ref().unwrap_or(projection))?; @@ -290,7 +291,7 @@ impl Gizmo for FrameGizmo { json!({"size": size}) } FrameGrab::Turn => { - // The sweep round the centre on the frame's own plane (across turning towards up is a positive turn), so a tilted or off-centre frame follows the pointer too + // Measure the turn in the frame's own plane so a tilted frame follows the pointer let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees()); let swept = angle(to)? - angle(from)?; let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN; @@ -537,6 +538,7 @@ pub(crate) mod tests { assert!(slid.offset[0] > 0.0 && slid.offset[1].abs() < slid.offset[0] * 0.2, "the centre square slides it right: {slid:?}"); assert_eq!(slid.size, axis.decal.size, "sliding keeps its size"); assert_eq!(harness.state().session.history_labels().last().map(String::as_str), Some("Edit decal")); + let steps = harness.state().session.history_labels().len(); let placed = gizmo(&harness); @@ -557,6 +559,7 @@ pub(crate) mod tests { let (mut harness, layer) = fill_app("warp"); let warp = gizmo(&harness); assert_eq!(warp.warp, Some(Projection::FRAME_CORNERS)); + let to = warp.corners[1] + vec2(-40.0, 30.0); drag(&mut harness, warp.corners[1], to, Modifiers::NONE); let Projection::Warp { corners, frame, .. } = projection(&harness, layer) else { panic!("still a warp") }; @@ -646,6 +649,7 @@ pub(crate) mod tests { let (mut harness, layer) = fill_app("warp"); let warp = gizmo(&harness); assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1))); + drag(&mut harness, warp.sides[1], warp.center + (warp.sides[1] - warp.center) * 0.5, Modifiers::NONE); let Projection::Warp { frame, corners, .. } = projection(&harness, layer) else { panic!("still a warp") }; assert!(frame.size[0] < warp.decal.size[0] * 0.75 && (frame.size[1] - warp.decal.size[1]).abs() < 1e-4, "the right edge dot narrows it: {frame:?}"); @@ -661,6 +665,7 @@ pub(crate) mod tests { let center = gizmo(&harness).center; let to = center + vec2(40.0, 0.0); press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(frame_dragging(&harness), "the centre square is held"); harness.event(egui::Event::WindowFocused(false)); @@ -673,9 +678,12 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), left, "moves after it leave the frame where it was"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "and add no step"); } @@ -693,6 +701,7 @@ pub(crate) mod tests { harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); assert!(!frame_dragging(&harness), "and ends the frame drag"); @@ -700,9 +709,12 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the frame stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); } @@ -722,7 +734,7 @@ pub(crate) mod tests { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let (mut harness, layer) = fill_app("warp"); - // The frame waits at its left limit, a mesh diagonal off the ball's centre, clear of the panels on the right; the camera backs off so it shows with its arrows + // Offset the frame from the panels and back the camera up to expose its arrows harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "offset": [-100.0, 0.0]})).unwrap(); harness.state_mut().session.camera.distance *= 3.0; harness.run_steps(2); @@ -735,12 +747,14 @@ pub(crate) mod tests { press_and_move(&mut harness, tip, tip - inward * 25.0, Modifiers::NONE); assert_eq!(projection(&harness, layer), at_limit, "past the limit the frame stays where it is"); + move_and_let_go(&mut harness, tip - inward * 25.0, tip + inward * 25.0); assert_ne!(projection(&harness, layer), at_limit, "back inside the frame moves"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag made its own undo step"); harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), at_limit, "undo takes back the drag only"); } @@ -752,6 +766,7 @@ pub(crate) mod tests { harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "roughness", "procedural": "Checker"})).unwrap(); harness.run_steps(2); + assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "placing would move the pattern"); } @@ -769,11 +784,15 @@ pub(crate) mod tests { press_and_move(&mut harness, center, center + vec2(0.0, 30.0), Modifiers::NONE); harness.key_press_modifiers(Modifiers::COMMAND, egui::Key::Z); harness.run_steps(1); + assert_eq!(projection(&harness, layer), first, "Ctrl+Z undid the drag so far"); + move_and_let_go(&mut harness, center + vec2(0.0, 30.0), center + vec2(0.0, 40.0)); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag's later edits made a step of their own"); harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), first, "undo goes back to where the first drag left the frame"); } @@ -797,21 +816,28 @@ pub(crate) mod tests { assert!(eye.left() > projection_row.right() && (eye.center().y - projection_row.center().y).abs() < 0.5, "the eye ends the Projection row"); click(&mut harness, eye.center()); + assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos"); assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab"); + let before = projection(&harness, layer); drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), before, "a drag where the centre square was moves nothing"); let eye = harness.get_by_label("Show projection gizmos").rect(); click(&mut harness, eye.center()); + assert!(harness.state().session.doc.project.display.projection_gizmos, "the eye shows them again"); + drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "shown, the centre square slides it again"); // A UV projection has no gizmo: its row keeps the whole width for the dropdown harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "uv"})).unwrap(); harness.run_steps(2); + assert!(harness.query_by_label("Hide projection gizmos").is_none(), "no eye without a gizmo"); } @@ -957,6 +983,7 @@ pub(crate) mod tests { let side = gizmo(&harness); drag_frames(&mut harness, layer, side.sides[0], side.center + (side.sides[0] - side.center) * 0.5, Modifiers::NONE, true, check(layer)); let narrowed = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(narrowed.scale[1] < slid.scale[1] * 0.75 && (narrowed.scale[0] - slid.scale[0]).abs() < 1e-4, "{slid:?} -> {narrowed:?}"); // The view steps back so a corner shows beside the panels @@ -967,6 +994,7 @@ pub(crate) mod tests { let inside = *corner.corners.iter().find(|at| view.contains(**at)).expect("a corner in the view"); drag_frames(&mut harness, layer, inside, corner.center + (inside - corner.center) * 0.6, Modifiers::NONE, true, check(layer)); let scaled = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!(scaled.scale[1] < narrowed.scale[1] * 0.8 && scaled.scale[0] < narrowed.scale[0] * 0.8, "a corner scales it: {scaled:?}"); // Move on model held with Shift turns the frame round its normal @@ -974,6 +1002,7 @@ pub(crate) mod tests { let button = harness.get_by_label("Move on model").rect().center(); drag_frames(&mut harness, layer, button, button + vec2(-60.0, 0.0), Modifiers::SHIFT, true, check(layer)); let turned = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap(); + assert!((turned.rotation[2] - before.rotation[2]).abs() > 10.0, "turned: {before:?} -> {turned:?}"); assert_eq!(harness.state().session.history_labels().len(), steps + 4, "one undo step per drag"); diff --git a/crates/ui-egui/src/gray_slider.rs b/crates/ui-egui/src/gray_slider.rs index eac04af1..1dd5ae91 100644 --- a/crates/ui-egui/src/gray_slider.rs +++ b/crates/ui-egui/src/gray_slider.rs @@ -19,6 +19,7 @@ const MIN_BAR_WIDTH: f32 = KNOB_RADIUS * 4.0; pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option { let tokens = Tokens::get(ui.ctx()); let (field, typed) = value_header(ui, label, value, 0.0..=1.0, 2); + ui.horizontal(|ui| { let mut edit = typed; @@ -28,6 +29,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option(field)); @@ -54,6 +56,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option, /// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`). @@ -337,6 +339,7 @@ impl TextureCraftApp { uv_rotation_snap: None, uv_view_reset: false, session, + viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(), ui, ui_store, gpu, diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs index 0871d95e..37a15b5c 100644 --- a/crates/ui-egui/src/move_on_model.rs +++ b/crates/ui-egui/src/move_on_model.rs @@ -323,17 +323,21 @@ mod tests { let mut pointer = press_the_button(&mut harness); let from = pointer.at; assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press starts the hold"); + let moved = vec2(-300.0, -20.0); pointer.drags(&mut harness, moved, 30, Modifiers::NONE); let after = RoundGizmo::of(harness.state(), rect).unwrap(); + assert!((after.center - (before.center + moved)).length() < 2.0, "the projector follows the mouse: {:?} -> {:?}", before.center, after.center); assert!(pointer.hidden, "the pointer hides while held"); assert!(pointer.at.distance(from) < 1.0, "and stays on the pad, so no screen edge stops the drag: {:?}", pointer.at); + let slid = projection(&harness, layer); assert_ne!(projector_offset(&slid), [0.0; 3], "the projector itself moved: {slid:?}"); assert_eq!(uv_of(&slid), UvTransform::default(), "not only the image inside it"); let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().moving_on_model, None, "letting go ends it"); assert!(!pointer.hidden && pointer.at == from, "the pointer shows again where the press began: {:?}", pointer.at); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per hold"); @@ -342,6 +346,7 @@ mod tests { // The 3D view has its drags back: a drag on the model off the projector's handles moves nothing let off = on_the_model_off_the_handles(&harness); drag(&mut harness, off, off + vec2(60.0, 0.0), Modifiers::NONE); + assert_eq!(projection(&harness, layer), slid, "no mode is left on"); } @@ -353,6 +358,7 @@ mod tests { let steps = harness.state().session.history_labels().len(); let mut pointer = press_the_button(&mut harness); pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "the hold is under way"); harness.input_mut().events.push(egui::Event::WindowFocused(false)); @@ -363,6 +369,7 @@ mod tests { assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step, as letting go makes"); pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, None, "the button still down in egui starts no new hold"); assert_eq!(projection(&harness, layer), left, "moves after it leave the projection alone"); } @@ -377,10 +384,12 @@ mod tests { harness.run_steps(2); let mut pointer = press_the_button(&mut harness); pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "{layout:?}: the hold is under way"); harness.state_mut().run("layer.remove", json!({"layer": layer.0})).unwrap(); pointer.frame(&mut harness); + assert_eq!(harness.state().moving_on_model, None, "{layout:?}: the hold ended with its fill"); assert!(!pointer.hidden, "{layout:?}: the pointer shows again"); } @@ -393,13 +402,19 @@ mod tests { let (mut harness, layer) = fill_app("triplanar"); let pad = harness.get_by_label("Move on model").rect(); assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}"); + let before = projection(&harness, layer); let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0)); pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold"); + pointer.drags(&mut harness, vec2(40.0, 0.0), 10, Modifiers::NONE); + assert!(pointer.hidden, "the pointer is held"); + let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), before, "the drag moved the projection"); assert_eq!(harness.state().moving_on_model, None); } @@ -428,6 +443,7 @@ mod tests { let turned = projection(&harness, layer); assert!(uv_of(&turned).rotation < shifted.rotation, "the right button turns it: {shifted:?} -> {turned:?}"); assert_eq!(projector_offset(&turned), projector_offset(&slid), "without sliding"); + pointer.button(&mut harness, PointerButton::Secondary, false, Modifiers::NONE); wheel(&mut harness, &mut pointer); @@ -437,10 +453,13 @@ mod tests { assert!(harness.state().properties_popup.is_none(), "the right click opened no Properties popup"); let_go(&mut harness, &mut pointer); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the whole hold is one undo step"); + let back = pointer.at; pointer.moves(&mut harness, over_view - back, Modifiers::NONE); wheel(&mut harness, &mut pointer); + assert_ne!(harness.state().session.camera, camera, "let go, the wheel zooms the camera"); assert_eq!(uv_of(&projection(&harness, layer)), scaled, "and leaves the projection alone"); } @@ -457,13 +476,17 @@ mod tests { let mut pointer = press_the_button(&mut harness); pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::SHIFT); + assert_eq!(projection(&harness, layer), turned, "an up and down turn changes nothing"); + pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::NONE); let_go(&mut harness, &mut pointer); + assert_ne!(projection(&harness, layer), turned, "the slide moved the frame"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the hold made its own undo step"); harness.state_mut().session.undo().unwrap(); + assert_eq!(projection(&harness, layer), turned, "undo takes back the hold only"); } @@ -476,9 +499,11 @@ mod tests { let mut pointer = press_the_button(&mut harness); let from = pointer.at; wheel(&mut harness, &mut pointer); + assert_eq!(harness.get_by_label("Move on model").rect().center(), from, "a wheel step over the panel while held scales, it does not scroll the panel"); let Projection::Uv { scale, .. } = projection(&harness, layer) else { panic!("still UV") }; assert!(scale[0] < 1.0, "the wheel up makes the image bigger: {scale:?}"); + let far = vec2(-3.0 * from.x, 0.0); pointer.drags(&mut harness, far, 60, Modifiers::NONE); let_go(&mut harness, &mut pointer); diff --git a/crates/ui-egui/src/pointer_lock/tests.rs b/crates/ui-egui/src/pointer_lock/tests.rs index bbce1297..7b85654e 100644 --- a/crates/ui-egui/src/pointer_lock/tests.rs +++ b/crates/ui-egui/src/pointer_lock/tests.rs @@ -44,11 +44,14 @@ fn a_put_back_pointer_never_reaches_the_edge_and_comes_back_where_the_press_bega pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.hidden, "let go, the pointer shows again"); assert_eq!(pointer.at, PRESS, "where the press began"); assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it there too"); + let moved = *harness.state(); pointer.moves(&mut harness, vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(pointer.at, PRESS + vec2(30.0, 0.0), "a free pointer moves again"); assert_eq!(*harness.state(), moved, "and drags nothing"); } @@ -61,11 +64,13 @@ fn a_folded_put_back_counts_every_move_from_the_press() { pointer.folds = true; pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); pointer.drags(&mut harness, vec2(1500.0, -40.0), 30, Modifiers::NONE); + assert!(pointer.hidden && pointer.put_backs >= 30, "hidden, and put back after every move: {pointer:?}"); assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts: {:?}", harness.state()); pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == PRESS, "let go, it shows again where the press began: {pointer:?}"); } @@ -78,6 +83,7 @@ fn a_locked_pointer_reads_raw_motion_and_is_let_go_where_the_press_began() { pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.locked && !pointer.hidden, "let go, the pointer is free and shows"); assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it where the press began"); } @@ -88,6 +94,7 @@ fn a_browser_pointer_is_not_held() { let mut pointer = SystemPointer::at(&mut harness, PRESS); pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); pointer.drags(&mut harness, vec2(100.0, 0.0), 10, Modifiers::NONE); + assert!(!pointer.hidden && pointer.put_backs == 0, "the pointer moves and shows"); assert_eq!(*harness.state(), vec2(100.0, 0.0), "the drag reads it as it moves"); } @@ -103,9 +110,12 @@ fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() { pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE); let window = harness.ctx.content_rect().width(); pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE); + assert!(pointer.hidden && pointer.at.distance(press) < 1.0, "the pointer is hidden and kept on the field: {pointer:?}"); + pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE); pointer.frame(&mut harness); + assert!(!pointer.hidden && pointer.at == press, "let go, it shows again on the field: {pointer:?}"); let texturecraft_engine::core::Projection::Triplanar { offset, .. } = crate::frame_gizmo::tests::projection(&harness, layer) else { diff --git a/crates/ui-egui/src/preview_dots.rs b/crates/ui-egui/src/preview_dots.rs index 09af91a8..d4220c73 100644 --- a/crates/ui-egui/src/preview_dots.rs +++ b/crates/ui-egui/src/preview_dots.rs @@ -37,6 +37,7 @@ pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, toke let length = span.length(); let start = DOT_RADIUS + LINE_SPACING; let end = length - RING_RADIUS - LINE_SPACING / 2.0; + if length.is_finite() && end > start { let toward = span / length; let count = (((end - start) / LINE_SPACING).floor() as usize).min(MAX_LINE_DOTS); @@ -46,6 +47,7 @@ pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, toke painter.circle_filled(at, LINE_DOT, tokens.text); } } + painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_UNDER, tokens.field)); painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_LINE, tokens.text)); painter.circle_filled(position, DOT_RADIUS + DOT_RIM, tokens.field); diff --git a/crates/ui-egui/src/projection_gizmo.rs b/crates/ui-egui/src/projection_gizmo.rs index 06b1c199..edc56a76 100644 --- a/crates/ui-egui/src/projection_gizmo.rs +++ b/crates/ui-egui/src/projection_gizmo.rs @@ -4,6 +4,8 @@ mod gizmo; mod gizmo_drag; mod shown_gizmo; +use std::sync::Arc; + use egui::{PointerButton, Rect}; use serde_json::{Value, json}; use texturecraft_engine::Session; @@ -32,10 +34,10 @@ pub(crate) fn input(app: &mut TextureCraftApp, ctx: &egui::Context, re && let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin())) && let Some(grab) = gizmo.grab(from) { - drag = Some(GizmoDrag { grab, from, start: gizmo.clone(), edited_revision: None }); + drag = Some(GizmoDrag { grab, from, start: Arc::new(gizmo.clone()), edited_revision: None }); } - // A window that lost the focus gets no release: the drag ends there. A release still applies a move that came in the same frame + // Apply a final move on release and let focus loss end a drag without one let released = response.drag_stopped_by(PointerButton::Primary); let pressed = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary) || released; let Some(mut drag) = drag.filter(|_| pressed && !focus_lost(ctx)) else { diff --git a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs index bf8221b5..184009c1 100644 --- a/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs +++ b/crates/ui-egui/src/projection_gizmo/gizmo_drag.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use egui::Pos2; use super::Gizmo; @@ -6,9 +8,10 @@ use super::Gizmo; #[derive(Clone, Debug)] pub(crate) struct GizmoDrag { pub(crate) grab: G::Grab, - /// Where the drag started and the gizmo then + /// Where the drag started pub(crate) from: Pos2, - pub(crate) start: G, + /// The starting gizmo shared by the pointer, edit and overlay paths + pub(crate) start: Arc, /// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there pub(crate) edited_revision: Option, } diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs index 903a01a9..37992c63 100644 --- a/crates/ui-egui/src/projection_preview.rs +++ b/crates/ui-egui/src/projection_preview.rs @@ -12,7 +12,7 @@ use texturecraft_engine::compose::frame_placement::{folded, upright_turn}; use texturecraft_engine::compose::pattern::{Coords, decal_axes, image_samples}; use texturecraft_engine::compose::projector_cover::projector_cover; use texturecraft_engine::core::{Projection, Projector, ShapeCrop}; -use texturecraft_engine::geom::glam::{Vec2, Vec3}; +use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; use rayon::prelude::*; @@ -134,6 +134,9 @@ const UNCOVERED: f32 = 0.45; /// How much of the projection reaches a ray past which it counts as covered, for the edge of its reach const HALF_COVERED: f32 = 0.5; +/// A missed ray has no coverage value in the 0..1 range +const MISSED_RAY_COVERAGE: f32 = -1.0; + /// How far a ray on the edge of the projection's reach is drawn from the accent towards the shape's colour const EDGE_BLEND: f32 = 0.5; @@ -378,18 +381,18 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t let supersample = supersample.max(1); let rays = side * supersample; - // Per ray: the lit colour and how much of the projection lands there (None = the background) - let samples: Vec> = (0..rays * rays) + // Pack lit RGB and coverage into one vector per ray + let samples: Vec = (0..rays * rays) .into_par_iter() .map(|ray| { let (x, y) = (ray % rays, ray / rays); let across = ((x as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; let down = ((y as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half; let origin = right * across - up * down + eye * CAMERA_DISTANCE; - let hit = intersect(shape, origin, forward)?; + let Some(hit) = intersect(shape, origin, forward) else { return Vec4::new(0.0, 0.0, 0.0, MISSED_RAY_COVERAGE) }; let shade = AMBIENT + (1.0 - AMBIENT) * hit.nrm.dot(light).max(0.0); let (color, cover) = surface(projection, &hit, shades); - Some((color * shade, cover)) + (color * shade).extend(cover) }) .collect(); @@ -400,10 +403,13 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t let mut sum = Vec3::ZERO; for sub in 0..supersample * supersample { let (rx, ry) = (x * supersample + sub % supersample, y * supersample + sub / supersample); - let color = match samples.get(ry * rays + rx).copied().flatten() { - Some((color, cover)) if on_edge(&samples, rays, rx, ry, cover) => edge.lerp(color, EDGE_BLEND), - Some((color, _)) => color, - None => background, + let sample = samples[ry * rays + rx]; + let color = if sample.w == MISSED_RAY_COVERAGE { + background + } else if on_edge(&samples, rays, rx, ry, sample.w) { + edge.lerp(sample.truncate(), EDGE_BLEND) + } else { + sample.truncate() }; sum += color; } @@ -413,7 +419,7 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t } /// Where the projection's reach ends on the shape: covered here, not on a neighbouring ray of the shape -fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cover: f32) -> bool { +fn on_edge(samples: &[Vec4], rays: usize, x: usize, y: usize, cover: f32) -> bool { if cover <= HALF_COVERED { return false; } @@ -421,7 +427,7 @@ fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cov let neighbours = [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)]; neighbours .into_iter() - .any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).copied().flatten().is_some_and(|(_, cover)| cover <= HALF_COVERED)) + .any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).is_some_and(|sample| sample.w != MISSED_RAY_COVERAGE && sample.w <= HALF_COVERED)) } /// The unlit colour at a hit and how much of the projection reaches it, from the dark and light checker and the uncovered shape `shades` in linear light @@ -651,6 +657,7 @@ mod tests { #[test] fn the_view_fits_the_projector_down_to_half_the_shape() { assert_eq!(fitted_half(&sized(0.4)), VIEW_HALF, "a small projector keeps the plain framing"); + let default = fitted_half(&sized(1.0)); assert!(default > VIEW_HALF && default < MAX_VIEW_HALF, "{default}"); assert_eq!(fitted_half(&sized(3.0)), MAX_VIEW_HALF, "x3 stops at half the shape's size"); @@ -662,6 +669,7 @@ mod tests { let screen = Screen { view: View::new(), rect, half: fitted_half(&shown) }; passed_sides(outline.points().map(|point| screen.at(point)), rect) }; + assert_eq!(sides(1.0), [false; 4], "a fitted projector stays inside the square"); assert_eq!(sides(3.0), [true; 4], "an x3 sphere runs past every side"); @@ -683,10 +691,12 @@ mod tests { for offset in [[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [1.5, 0.8, 0.0]] { let slid = Projection::Spherical { scale, uv, offset, projector }; assert_eq!(fitted_half(&slid), fitted_half(&sized(1.0)), "Offset {offset:?} keeps the view"); + let (resting, half) = resting_fit(&slid, PreviewShape::Sphere); let screen = Screen { view: View::new(), rect, half }; let ring = screen.at(resting.unwrap().center); let dot = screen.at(ProjectorOutline::of(&slid, PreviewShape::Sphere.half_size()).unwrap().center); + assert!(ring.distance(rect.center()) < 1e-3, "the ring marks the middle: {ring:?}"); assert_eq!(dot.distance(ring) > 1.0, offset != [0.0; 3], "the filled dot leaves the ring only when slid: {dot:?}"); } @@ -709,6 +719,7 @@ mod tests { let outline = ProjectorOutline::of(&sized(1.0), PreviewShape::Sphere.half_size()).unwrap(); let hidden = |line: &Vec| line.iter().filter(|point| screen.hidden(PreviewShape::Sphere, **point)).count(); assert_eq!(hidden(&outline.lines[0]), 0, "the rim is all seen"); + let equator = hidden(&outline.lines[1]); assert!(equator > 0 && equator < outline.lines[1].len(), "the equator is half hidden: {equator}"); } @@ -788,15 +799,21 @@ mod tests { let at = pos2(10.0, 10.0); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; preview_frame(&ctx, &spherical(1.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "at rest: in full"); preview_frame(&ctx, &spherical(1.0), vec![egui::Event::PointerMoved(at), button(true)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "a press alone keeps the full picture: nothing changed"); + preview_frame(&ctx, &spherical(2.0), Vec::new()); + assert_eq!(shown_supersample(&ctx), Some(DRAG_SUPERSAMPLE), "a change while held renders lighter"); + let dragged = shown_key(&ctx); preview_frame(&ctx, &spherical(2.0), vec![button(false)]); + assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "let go: the same picture in full"); assert_eq!(shown_key(&ctx), dragged); } diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 341fda86..4e4d2f34 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -39,6 +39,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: && !gesture_key_held && !crate::viewport::focus_picking(ui.ctx()) && ui.input(|input| input.modifiers.is_none()); + if !free || !response.clicked_by(PointerButton::Secondary) { return; } @@ -71,8 +72,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { 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).inner_margin(egui::Margin::ZERO).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(); diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index 13d65ee9..5eb2724c 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -46,6 +46,7 @@ impl PropertySheet<'_> { let response = self.ui.interact(Rect::from_center_size(center, CAPTION_SWITCH_HIT), id, Sense::click()); response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, title)); self.pill(center, on, true); + self.paint_control_focus(&response); response } diff --git a/crates/ui-egui/src/property_sheet/info_icon.rs b/crates/ui-egui/src/property_sheet/info_icon.rs index b18c0513..a8cbee52 100644 --- a/crates/ui-egui/src/property_sheet/info_icon.rs +++ b/crates/ui-egui/src/property_sheet/info_icon.rs @@ -50,6 +50,7 @@ impl<'u> PropertySheet<'u> { /// Paints the pending i at `glyph_x` in its slot from `slot_left` fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) { let Some(tip) = self.info.take() else { return }; + let row_top = center_y - ROW_HEIGHT / 2.0; let slot = Rect::from_min_size(pos2(slot_left, row_top), vec2(INFO_SLOT, ROW_HEIGHT)); let id = self.next_id(); @@ -69,6 +70,7 @@ impl<'u> PropertySheet<'u> { .inner_margin(TIP_MARGIN) .shadow(TIP_SHADOW); let text_width = anchor.width() - TIP_MARGIN.sum().x; + let mut tooltip = egui::Tooltip::for_enabled(&response); tooltip.popup = tooltip .popup diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 1da4e0eb..e5c97ea2 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -25,6 +25,7 @@ mod switch_control; mod tooltip; mod track; mod value_text; +mod value_text_draft; #[cfg(test)] mod tests; @@ -44,6 +45,8 @@ use crate::theme::{Tokens, semibold}; use open_card::OpenCard; use sheet_measure::SheetMeasure; +type SheetMeasures = egui::cache::FramePublisher; + /// Side padding: every row starts and ends this far inside the panel pub(crate) const PAD: f32 = 12.0; @@ -124,7 +127,7 @@ impl<'u> PropertySheet<'u> { /// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { let id = ui.make_persistent_id(id_salt); - let used = ui.data(|data| data.get_temp::(id)).unwrap_or_default(); + let used = ui.memory_mut(|memory| memory.caches.cache::().get(&id).copied()).unwrap_or_default(); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let rect = ui.available_rect_before_wrap(); let mut sheet = PropertySheet { @@ -153,11 +156,13 @@ impl<'u> PropertySheet<'u> { section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top }); } + // Refresh visible sheets so measurements of closed sheets expire let seen = sheet.seen; + sheet.ui.memory_mut(|memory| memory.caches.cache::().set(id, seen)); if seen != used { - sheet.ui.data_mut(|data| data.insert_temp(id, seen)); sheet.ui.ctx().request_discard("Properties columns changed"); } + result } diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 22337ebb..f3f76bcc 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -92,7 +92,7 @@ impl PropertySheet<'_> { /// One field: its tag on the left, the value on the right; drag or click to type. Named "`label` `tag`" ("Scale X") fn number_field(&mut self, rect: Rect, label: &str, field: &mut NumberField) -> Option { let id = self.next_id(); - let typing_id = id.with("typed"); + let typing_id = id.with((self.id, "typed")); let tokens = self.tokens; let painter = self.ui.painter().clone(); painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); @@ -112,26 +112,27 @@ impl PropertySheet<'_> { } let decimals = field.decimals; - if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { - let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); - let response = self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, edit); + if let Some(mut draft) = self.typing_draft(typing_id) { + let response = + self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, typing_id, &mut draft); painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); if !response.lost_focus() { - self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + self.keep_typing(typing_id, draft); return None; } - let untouched = self.end_typing(typing_id, &text); + let untouched = self.end_typing(typing_id, &draft); + let text = draft.text.trim(); if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { return None; } // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile - if untouched || text.trim() == shown_number(field.value, decimals) { + if untouched || text == shown_number(field.value, decimals) { return None; } - let typed: f32 = text.trim().trim_end_matches(field.suffix).trim().parse().ok()?; + let typed: f32 = text.trim_end_matches(field.suffix).trim().parse().ok()?; if !typed.is_finite() || typed == field.value { return None; } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index a377cfdd..9ce3760a 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -188,12 +188,12 @@ impl PropertySheet<'_> { pub(super) fn value_text_field(&mut self, id: Id, value_text: ValueText<'_>, value: f32, range: &RangeInclusive, decimals: usize) -> Option { let ValueText { label, right, width, center_y, shown, suffix } = value_text; let rect = Rect::from_min_max(pos2(right - width, center_y - ROW_HIT_HALF_HEIGHT), pos2(right, center_y + ROW_HIT_HALF_HEIGHT)); - let field_id = id.with("typed"); - let editing = self.ui.data(|data| data.get_temp::(field_id)); + let field_id = id.with((self.id, "typed")); + let editing = self.typing_draft(field_id); let seeded = || shown_number(value, decimals); let tokens = self.tokens; - let Some(mut typed_text) = editing else { + let Some(mut draft) = editing else { self.skip_typing_edit(); let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); @@ -209,25 +209,25 @@ impl PropertySheet<'_> { }; // Typing happens on the value's own line: no box, the line under it goes accent - let edit = egui::TextEdit::singleline(&mut typed_text).id(field_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); - let response = self.typing_edit(rect.left(), right, center_y, edit); + let response = self.typing_edit(rect.left(), right, center_y, field_id, &mut draft); self.value_line(rect.left(), right, center_y, tokens.accent); if !response.lost_focus() { - self.ui.data_mut(|data| data.insert_temp(field_id, typed_text)); + self.keep_typing(field_id, draft); return None; } - let untouched = self.end_typing(field_id, &typed_text); + let untouched = self.end_typing(field_id, &draft); + let typed_text = draft.text.trim(); if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { return None; } // Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile - if untouched || typed_text.trim() == seeded() { + if untouched || typed_text == seeded() { return None; } - let typed: f32 = typed_text.trim().trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?; + let typed: f32 = typed_text.trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?; // A typed value that lands on the current one (a clamp, "0.750" for 0.75) is no edit either typed.is_finite().then(|| kept_in(typed, range)).filter(|kept| *kept != value) diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 54b099f8..03677ab4 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,4 +1,4 @@ -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; @@ -36,7 +36,21 @@ const TOGGLE_KNOB_TRAVEL: f32 = 4.5; const PAIR_PITCH: f32 = 76.0; const PAIR_NAME_TO_PILL: f32 = 32.0; +/// Width of a focused control's outline in points +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; + impl PropertySheet<'_> { + pub(super) fn paint_control_focus(&self, response: &Response) { + if response.has_focus() { + self.ui.painter().rect_stroke( + response.rect, + CornerRadius::same(CONTROL_RADIUS), + Stroke::new(FOCUS_OUTLINE_WIDTH, self.tokens.text_strong), + StrokeKind::Inside, + ); + } + } + /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { self.switch_tinted(label, options, selected, &[]) @@ -96,6 +110,8 @@ impl PropertySheet<'_> { } else if response.hovered() { painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.row_hover); } + + self.paint_control_focus(&response); let runs = tints(index); let tint = runs.first().copied().unwrap_or(tokens.text); let (font, color) = if on { (semibold(SMALL_TEXT_SIZE), tint) } else { (FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) }; @@ -150,7 +166,9 @@ impl PropertySheet<'_> { if response.clicked() { *on = !*on; } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, label)); + self.paint_control_focus(&response); response.clicked() } @@ -165,14 +183,16 @@ impl PropertySheet<'_> { let hit = Rect::from_min_max(pos2(x, control.top()), pos2(pill.x + PILL_SIZE.x / 2.0, control.bottom())); let id = self.next_id(); let response = self.ui.interact(hit, id, Sense::click()); - response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}"))); if response.clicked() { *state = !*state; clicked = Some(index); } + + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}"))); let tokens = self.tokens; self.ui.painter().text(pos2(x, center_y), Align2::LEFT_CENTER, name, font.clone(), if *state { tokens.text } else { tokens.text_dim }); self.pill(pill, *state, true); + self.paint_control_focus(&response); } clicked } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 546bddf2..11b20f48 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -177,6 +177,7 @@ fn dropdown_list_hangs_from_its_button_at_its_width_and_picks() { let at = harness.get_by_label("Nearest").rect().center(); click_at(&mut harness, at); harness.run_steps(2); + assert_eq!(harness.state().filtering, Filtering::Nearest); } @@ -206,6 +207,7 @@ fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { harness.hover_at(reason.center()); harness.run_steps(TOOLTIP_WAIT_FRAMES); + assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole"); } diff --git a/crates/ui-egui/src/property_sheet/value_text.rs b/crates/ui-egui/src/property_sheet/value_text.rs index b40ca7a4..a569f284 100644 --- a/crates/ui-egui/src/property_sheet/value_text.rs +++ b/crates/ui-egui/src/property_sheet/value_text.rs @@ -1,5 +1,13 @@ //! Where a slider's value sits and how it reads +use egui::Id; +use egui::text_edit::TextEditState; + +use super::value_text_draft::ValueTextDraft; +use crate::theme::semibold; + +type ValueTextDrafts = egui::cache::FramePublisher>; + /// A value drawn right-aligned at `right` in a `width` wide box centred on `center_y`, reading `shown`; typing may end in `suffix`; it answers as `label`'s value pub(super) struct ValueText<'a> { pub(super) label: &'a dyn std::fmt::Display, @@ -13,41 +21,52 @@ pub(super) struct ValueText<'a> { /// How far below a value's centre its typing line runs const LINE_DROP: f32 = 9.0; -/// Where the field `field_id` keeps the text its typing opened with -fn opened_id(field_id: egui::Id) -> egui::Id { - field_id.with("opened") -} - impl super::PropertySheet<'_> { /// Starts typing `text` into the field `field_id`, all of it selected so the first key replaces it - pub(super) fn start_typing(&mut self, field_id: egui::Id, text: String) { - let mut state = egui::text_edit::TextEditState::load(self.ui.ctx(), field_id).unwrap_or_default(); - state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); - state.store(self.ui.ctx(), field_id); - self.ui.data_mut(|data| { - data.insert_temp(opened_id(field_id), text.clone()); - data.insert_temp(field_id, text); - }); + pub(super) fn start_typing(&mut self, field_id: Id, text: String) { + let mut editor = TextEditState::default(); + editor.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + self.keep_typing(field_id, ValueTextDraft { original: text.clone(), text, editor }); self.ui.memory_mut(|memory| memory.request_focus(field_id)); } - /// Ends typing into the field `field_id`; whether `typed` is still the text it opened with (left so, it changes nothing, even after the value changed meanwhile) - pub(super) fn end_typing(&mut self, field_id: egui::Id, typed: &str) -> bool { - let opened = self.ui.data_mut(|data| { - data.remove::(field_id); - data.remove_temp::(opened_id(field_id)) - }); - opened.is_some_and(|opened| opened.trim() == typed.trim()) + pub(super) fn typing_draft(&self, field_id: Id) -> Option { + self.ui.memory_mut(|memory| memory.caches.cache::().get(&field_id).cloned().flatten()) } - /// Shows `edit` from `left` to `right` centred on `center_y` (an edit is never shorter than the theme's interact height), so its value sits where the shown value sat; leaves the sheet's rows where they are - pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, edit: egui::TextEdit<'_>) -> egui::Response { - let line = self.ui.painter().layout_no_wrap("0".to_owned(), crate::theme::semibold(super::TEXT_SIZE), self.tokens.text).size().y; + /// Keep the draft only while its field is drawn + pub(super) fn keep_typing(&self, field_id: Id, draft: ValueTextDraft) { + self.ui.memory_mut(|memory| memory.caches.cache::().set(field_id, Some(draft))); + } + + /// Ends typing and reports whether the text still matches what the field opened with + pub(super) fn end_typing(&self, field_id: Id, draft: &ValueTextDraft) -> bool { + self.ui.memory_mut(|memory| memory.caches.cache::().set(field_id, None)); + draft.original.trim() == draft.text.trim() + } + + /// Shows an edit in place of the displayed value, without shifting the sheet's rows + pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, field_id: Id, draft: &mut ValueTextDraft) -> egui::Response { + let font = semibold(super::TEXT_SIZE); + let line = self.ui.painter().layout_no_wrap("0".to_owned(), font.clone(), self.tokens.text).size().y; let height = line.max(self.ui.spacing().interact_size.y); let rect = egui::Rect::from_min_max(egui::pos2(left, center_y - height / 2.0), egui::pos2(right, center_y + height / 2.0)); let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); let mut child = self.ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(layout)); - child.add(edit.frame(egui::Frame::NONE).margin(egui::vec2(0.0, 0.0))) + + draft.editor.clone().store(child.ctx(), field_id); + let output = egui::TextEdit::singleline(&mut draft.text) + .id(field_id) + .font(font) + .align(egui::Align2::RIGHT_CENTER) + .frame(egui::Frame::NONE) + .margin(egui::Margin::ZERO) + .show(&mut child); + + // Keep selection and undo history with the draft instead of egui's persistent widget data + child.data_mut(|data| data.remove::(field_id)); + draft.editor = output.state; + output.response.response } /// Takes the one auto id [`Self::typing_edit`]'s child takes, for a value shown instead of typed: the controls after it keep their ids when typing starts or ends, so a click from one field to the next types into the one clicked diff --git a/crates/ui-egui/src/property_sheet/value_text_draft.rs b/crates/ui-egui/src/property_sheet/value_text_draft.rs new file mode 100644 index 00000000..a124fd47 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/value_text_draft.rs @@ -0,0 +1,9 @@ +use egui::text_edit::TextEditState; + +/// The input, original value, and editor state of a visible Properties field +#[derive(Clone)] +pub(super) struct ValueTextDraft { + pub(super) text: String, + pub(super) original: String, + pub(super) editor: TextEditState, +} diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index d8f7ada3..d480483b 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -53,6 +53,7 @@ fn environment_cache_retains_source_identity_until_replaced() { assert!(original_source.upgrade().is_none(), "replacing the resource releases its decoded pixels immediately"); assert_ne!(first_key, gpu_scene_key(&app.session), "a new source restarts tracing under the same environment name"); + let second = super::trace_scene(&app).env; assert!(!Arc::ptr_eq(&first, &second)); assert_ne!(first.data, second.data, "replacing the image changes the lighting"); @@ -60,6 +61,7 @@ fn environment_cache_retains_source_identity_until_replaced() { app.session.images.insert("renamed".into(), replacement); app.session.doc.project.display.environment = "resource:renamed".into(); + assert!(!Arc::ptr_eq(&second, &super::trace_scene(&app).env), "the environment name is also part of the key"); } diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index 0e531677..f017b9ba 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -89,7 +89,7 @@ impl RoundGizmo { _ => return None, }; - let (lower, upper) = app.session.mesh.bounds(); + let (lower, upper) = app.viewport_mesh_bounds.get(&app.session.mesh); let (mesh_center, radius) = mesh_frame((lower, upper)); let [x, y, z] = projector.rotation.map(f32::to_radians); let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); @@ -214,7 +214,7 @@ impl RoundGizmo { let right_of_rim = top.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x)); self.outline.extend([top, cap(-half_height)]); - // The two side lines, where the round side turns away from the camera; seen end on there are none, and the dot sits on the rim's right + // End-on views show a rim handle because the two side lines coincide let side = along.cross(facing - along * facing.dot(along)).try_normalize(); let mut sides = Vec::new(); for edge in side.into_iter().flat_map(|side| [side, -side]) { @@ -273,7 +273,7 @@ impl RoundGizmo { (turn, self.stretch, origin) } RoundGrab::Size(axes) => { - // How far the pointer went along the line from the centre through where the handle was grabbed (past the centre, none: a drag never flips it); the command keeps each axis's size in its limits on its own side, so does the offset worked out here + // Clamp the drag to the command's size limits so the offset keeps the same center let reach = from - self.center; let factor = ((to - self.center).dot(reach) / reach.length().max(MIN_HANDLE_REACH).powi(2)).max(0.0); let stretch = Vec3::from(axes.map(|on| if on { factor } else { 1.0 })) * self.stretch; @@ -476,6 +476,7 @@ pub(crate) mod tests { let stored = &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind; let LayerKind::Fill(Fill { projection: Projection::Cylindrical { axis, .. }, .. }) = stored else { panic!("a cylindrical fill") }; *axis = 3; + assert_eq!(gizmo(&harness).outline, round_y); } @@ -491,13 +492,16 @@ pub(crate) mod tests { let (projector, offset) = projector_and_offset(&projection(&harness, layer)); assert!(offset[0] < -0.05 && offset[1].abs() < 1e-3 && offset[2].abs() < 1e-3, "the X arrow moves the centre along X: {offset:?}"); assert_eq!(projector.rotation, [0.0; 3]); + let moved = gizmo(&harness); assert!(moved.center.x > start.center.x + 20.0, "the centre follows: {moved:?}"); // The Z ring (seen face on) turns it round Z; the centre stays where it is let clear = |p: &&Pos2| moved.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min); let on_ring = *moved.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap(); + assert_eq!(moved.grab(on_ring), Some(RoundGrab::Ring(2))); + drag(&mut harness, on_ring, moved.center + (on_ring - moved.center).rot90(), Modifiers::NONE); let (turned, _) = projector_and_offset(&projection(&harness, layer)); assert!(turned.rotation[2].abs() > 30.0 && turned.rotation[0].abs() < 1e-2, "{:?}", turned.rotation); @@ -507,6 +511,7 @@ pub(crate) mod tests { let dot = scaling.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at; let center = scaling.center; assert_eq!(gizmo(&harness).grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, center + (dot - center) * 1.5, Modifiers::NONE); let (scaled, _) = projector_and_offset(&projection(&harness, layer)); assert!(scaled.scale.iter().all(|scale| (scale - 1.5).abs() < 0.05), "the side dot scales it evenly: {:?}", scaled.scale); @@ -522,9 +527,11 @@ pub(crate) mod tests { let height = cylinder.sizes.iter().find(|size| size.axes == [false, true, false]).expect("the height handle"); let SizeHandle { at: top, axes, along } = *height; assert_eq!(axes, [false, true, false], "the top handle works along the axis"); + let along = along.expect("the height handle is a double arrow"); assert!(along.y.abs() > 0.99, "drawn upright, along the upright axis: {along:?}"); assert_eq!(cylinder.cursor(RoundGrab::Size(axes), false), egui::CursorIcon::ResizeVertical); + drag(&mut harness, top, cylinder.center + (top - cylinder.center) * 0.5, Modifiers::NONE); let (projector, _) = projector_and_offset(&projection(&harness, layer)); assert!(projector.scale[1] < 0.7 && projector.scale[0] == 1.0 && projector.scale[2] == 1.0, "{:?}", projector.scale); @@ -593,6 +600,7 @@ pub(crate) mod tests { let center = gizmo(&harness).center; let to = center + vec2(40.0, 0.0); press_and_move(&mut harness, center, to, Modifiers::NONE); + assert!(round_dragging(&harness), "the centre square is held"); harness.event(egui::Event::WindowFocused(false)); @@ -605,6 +613,7 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), left, "moves after it leave the projector where it was"); } @@ -622,6 +631,7 @@ pub(crate) mod tests { harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT); harness.run_steps(1); + assert_ne!(harness.state().session.camera, camera, "Alt turns the camera"); assert!(!round_dragging(&harness), "and ends the projector drag"); @@ -629,9 +639,12 @@ pub(crate) mod tests { harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32)); harness.run_steps(1); } + assert_eq!(projection(&harness, layer), slid, "Alt let go, the projector stays where the drag left it"); + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); } @@ -646,11 +659,13 @@ pub(crate) mod tests { let front = gizmo(&harness); assert!(front.rings[0].is_empty(), "the X ring seen edge on is left out: {:?}", front.rings[0]); assert!(front.rings[1..].iter().all(|ring| !ring.is_empty()), "the Y and Z rings show"); + let on_the_line = front.center + vec2(0.0, 40.0); assert_ne!(front.grab(on_the_line), Some(RoundGrab::Ring(0)), "a press where its line would be does not grab it"); harness.state_mut().session.camera.yaw = 0.5; harness.run_steps(2); + assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows"); } @@ -678,8 +693,10 @@ pub(crate) mod tests { let (mut harness, layer) = fill_app("spherical"); let start = gizmo(&harness); assert_eq!(start.sizes.len(), 1, "one dot: {:?}", start.sizes); + let dot = start.sizes[0].at; assert_eq!(start.grab(dot), Some(RoundGrab::Size([true; 3]))); + drag(&mut harness, dot, start.center + (dot - start.center) * 1.4, Modifiers::NONE); let (scaled, _) = projector_and_offset(&projection(&harness, layer)); assert!(scaled.scale.iter().all(|scale| (scale - 1.4).abs() < 0.08), "it scales evenly: {:?}", scaled.scale); @@ -700,6 +717,7 @@ pub(crate) mod tests { Some(RoundGrab::Size([true, false, false])), "grabbed from its tip" ); + drag(&mut harness, across.at, box_gizmo.center + (across.at - box_gizmo.center) * 0.5, Modifiers::NONE); let (stretched, _) = projector_and_offset(&projection(&harness, layer)); assert!((stretched.scale[0] - scaled.scale[0] * 0.5).abs() < 0.05, "the X face halves it across: {:?}", stretched.scale); @@ -727,6 +745,7 @@ pub(crate) mod tests { let start = gizmo(&harness); assert_eq!(start.stretch, Vec3::from(mirrored), "the gizmo reads the mirror as the projection does"); + drag(&mut harness, start.center, start.center + vec2(30.0, -20.0), Modifiers::NONE); let (slid, offset) = projector_and_offset(&projection(&harness, layer)); assert_eq!(slid.scale, mirrored, "a slide keeps the mirror"); @@ -735,6 +754,7 @@ pub(crate) mod tests { let tip = gizmo(&harness).arrows[1].unwrap(); let center = gizmo(&harness).center; drag(&mut harness, tip, tip + (tip - center).normalized() * 20.0, Modifiers::NONE); + assert_eq!(projector_and_offset(&projection(&harness, layer)).0.scale, mirrored, "so does a move along an arrow"); let before_turn = projector_and_offset(&projection(&harness, layer)).0; @@ -782,12 +802,15 @@ pub(crate) mod tests { let center = gizmo(&harness).center; harness.hover_at(center); harness.run_steps(2); + assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "the centre square shows it slides"); harness.event(egui::Event::ModifiersChanged(Modifiers::ALT)); harness.event(egui::Event::PointerMoved(center + vec2(1.0, 0.0))); harness.run_steps(2); + assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "with Alt held it does not"); + harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); harness.run_steps(2); } @@ -816,6 +839,7 @@ pub(crate) mod tests { drag(&mut harness, center, center + vec2(-40.0, 0.0), Modifiers::COMMAND); harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); harness.run_steps(2); + assert_ne!(harness.state().session.tool.brush.flow, flow, "the drag changes the brush"); assert_eq!(projection(&harness, layer), before, "and leaves the projection"); } @@ -859,10 +883,12 @@ pub(crate) mod tests { let painted = harness.state().session.quick_mask.revision; click(&mut harness, edge, off); + assert_eq!(harness.state().session.quick_mask.revision, painted, "a press that began on the handle paints no dab"); // The same click a little past the handle paints click(&mut harness, off, off + (off - edge)); + assert_ne!(harness.state().session.quick_mask.revision, painted, "a press off the handle paints"); } @@ -879,6 +905,7 @@ pub(crate) mod tests { let across = [true, true, false]; let dot = end_on.sizes.iter().find(|size| size.axes == across).unwrap_or_else(|| panic!("the across dot: {:?}", end_on.sizes)).at; assert_eq!(end_on.grab(dot), Some(RoundGrab::Size(across))); + drag(&mut harness, dot, end_on.center + (dot - end_on.center) * 1.5, Modifiers::NONE); let (projector, _) = projector_and_offset(&projection(&harness, layer)); assert!(projector.scale[0] > 1.2 && projector.scale[1] > 1.2 && projector.scale[2] == 1.0, "it scales across only: {:?}", projector.scale); diff --git a/crates/ui-egui/src/symmetry/view_overlay.rs b/crates/ui-egui/src/symmetry/view_overlay.rs index 4f805951..eff8362e 100644 --- a/crates/ui-egui/src/symmetry/view_overlay.rs +++ b/crates/ui-egui/src/symmetry/view_overlay.rs @@ -67,7 +67,7 @@ pub(crate) fn scene_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> Vec= 2.5, "{b:?} {a:?}: accent on panel"); assert!(contrast(Color32::WHITE, t.accent_strong) >= 2.5, "{b:?} {a:?}: white on accent button"); assert!(contrast(t.viewport_text, t.viewport) >= 3.0, "{b:?}: lettering on the views"); - // Slider rails show on the card. + // Slider rails show on the card assert!(contrast(t.button_border, t.panel) >= 1.6, "{b:?}: rail on panel"); } } - // The views keep their studio slate. + + // The views keep their studio slate assert_eq!(Tokens::for_brightness(Brightness::Light).viewport, Tokens::for_brightness(Brightness::Dark).viewport); } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4a8015ec..a58be4de 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -895,7 +895,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let gizmo = ShownGizmo::of(app, rect); let frame_drag = gizmo_free && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref()); - // Alt (or another mode) taking the pointer mid-drag ends the drag: let go of Alt, it must not resume from where it began before the camera moved + // End the gizmo drag when navigation takes over because the camera may have moved if !gizmo_free { ShownGizmo::let_go(ui.ctx()); } @@ -1031,7 +1031,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); - let (bounds_min, bounds_max) = app.session.mesh.bounds(); + let (bounds_min, bounds_max) = app.viewport_mesh_bounds.get(&app.session.mesh); let radius = app.session.tool.brush.size * (bounds_max - bounds_min).length(); brush_cursor(app, ui, rect, hit.pos, hit.nrm, radius); symmetry_cursor = Some((hit.pos, hit.nrm)); @@ -2542,7 +2542,7 @@ mod tests { #[test] fn unavailable_tools_finish_strokes_and_box_fills() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives}; @@ -2580,17 +2580,22 @@ mod tests { let app = harness.state_mut(); app.ui.mode = crate::state::Mode::Painting; app.session.view = ViewMode::Mask(LayerId(7)); + assert_eq!(mask_view_layer(app), Some(LayerId(7))); + app.session.quick_mask.editing = true; + assert!(quick_mask_shown(app)); assert_eq!(mask_view_layer(app), None, "the quick mask is on screen, not the layer mask"); + app.session.quick_mask.editing = false; + assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view"); } #[test] fn stored_surfaces_release_after_a_frame_without_paths() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{core::EffectKind, execute, geom::primitives}; @@ -2678,7 +2683,7 @@ mod tests { #[test] fn decal_frame_rejects_a_stale_effect_after_failed_layer_selection() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{StackTarget, execute}; @@ -2703,6 +2708,7 @@ mod tests { drag_decal_handle(&mut harness, original.center, original.center + vec2(40.0, 0.0)); let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind; + assert!( matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Planar { placed: Some(decal), .. }, .. } if *decal == original.decal) ); @@ -2711,7 +2717,7 @@ mod tests { #[test] fn decal_frame_keeps_an_instances_inherited_mask_effect_editable() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; @@ -2726,18 +2732,21 @@ mod tests { assert_eq!(session.ts(), 1); assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); + let inherited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal)); drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5); let edited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source"); } #[test] fn decal_frame_rejects_a_source_mask_overridden_by_the_selected_instance() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; @@ -2757,7 +2766,7 @@ mod tests { #[test] #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] fn decal_frame_selection_snapshots() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; @@ -2769,25 +2778,31 @@ mod tests { let effect = original.effect.unwrap(); let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + harness.run_steps(6); assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some()); + harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap(); let session = &mut harness.state_mut().session; let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err()); + harness.run_steps(6); assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none()); + harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap(); } #[test] fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() { - // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + // Hold the language lock while drawing the harness let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); diff --git a/crates/ui-egui/src/viewport_mesh_bounds.rs b/crates/ui-egui/src/viewport_mesh_bounds.rs new file mode 100644 index 00000000..32542076 --- /dev/null +++ b/crates/ui-egui/src/viewport_mesh_bounds.rs @@ -0,0 +1,23 @@ +use std::cell::RefCell; +use std::sync::{Arc, Weak}; + +use texturecraft_engine::geom::{Mesh, glam::Vec3}; + +/// Axis-aligned bounds shared by projection controls for the current mesh +#[derive(Default)] +pub(crate) struct ViewportMeshBounds { + mesh: RefCell>, + bounds: std::cell::Cell<(Vec3, Vec3)>, +} + +impl ViewportMeshBounds { + pub(crate) fn get(&self, mesh: &Arc) -> (Vec3, Vec3) { + let mut previous = self.mesh.borrow_mut(); + if previous.as_ptr() != Arc::as_ptr(mesh) { + self.bounds.set(mesh.bounds()); + *previous = Arc::downgrade(mesh); + } + + self.bounds.get() + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 9891dcc8..93bb6b5a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -449,7 +449,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool let tk = Tokens::get(ui.ctx()); let mut srgb = [c.r(), c.g(), c.b()]; let hsv_of = |srgb: [u8; 3]| hsv_from_rgb(srgb.map(|v| v as f32 / 255.0)); - // Remembered with the color it was for, so hue and saturation survive black, white and grays. + // Remembered with the color it was for, so hue and saturation survive black, white and grays let (mut h, mut s, mut v) = ui.data(|d| d.get_temp::<(Color32, (f32, f32, f32))>(id)).filter(|(k, _)| k == c).map_or_else(|| hsv_of(srgb), |(_, hsv)| hsv); let mut typed = false; let mut dragged = false; @@ -465,7 +465,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool (h, s, v) = hsv_of(srgb); } let border = Stroke::new(1.0, tk.field_border); - // Saturation across, value up. + // Saturation across, value up let (rect, resp) = ui.allocate_exact_size(vec2(width, width), Sense::click_and_drag()); if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) { (s, v) = (((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0), 1.0 - ((p.y - rect.top()) / rect.height()).clamp(0.0, 1.0)); @@ -500,7 +500,12 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> /// Cells across and down: fine enough that a hue strip's six ramps read smooth const GRID_CELLS: u32 = 24; - let mut mesh = egui::Mesh::default(); + let side_vertices = GRID_CELLS as usize + 1; + let cell_count = (GRID_CELLS * GRID_CELLS) as usize; + // Each grid cell contributes two triangles + let mut mesh = + egui::Mesh { vertices: Vec::with_capacity(side_vertices * side_vertices), indices: Vec::with_capacity(cell_count * 6), ..Default::default() }; + for j in 0..=GRID_CELLS { for i in 0..=GRID_CELLS { let (x, y) = (i as f32 / GRID_CELLS as f32, j as f32 / GRID_CELLS as f32); @@ -508,6 +513,7 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b)); } } + for j in 0..GRID_CELLS { for i in 0..GRID_CELLS { let top_left = j * (GRID_CELLS + 1) + i; @@ -516,6 +522,7 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> mesh.add_triangle(top_left + 1, bottom_left + 1, bottom_left); } } + painter.add(mesh); } diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 6c54d052..d56067e4 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -145,13 +145,17 @@ fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { // The outline stays anchored while the pointer is hidden inside the view harness.hover_at(center + egui::vec2(10.0, 0.0)); harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "anchored outline while the pointer is in the view"); assert_eq!(cursor(&harness), CursorIcon::None); + // Outside the view, the outline stays anchored and the system pointer returns harness.hover_at(egui::pos2(2.0, 2.0)); harness.run_steps(3); + assert_eq!(rings_at(&harness, center).len(), 1, "the outline stays at the press origin outside the view"); assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible"); + harness.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl }); harness.event(Event::ModifiersChanged(egui::Modifiers::NONE)); harness.run_steps(2); diff --git a/crates/ui-egui/tests/it/fill_projection_rows.rs b/crates/ui-egui/tests/it/fill_projection_rows.rs index 8d0fbe71..a84a7743 100644 --- a/crates/ui-egui/tests/it/fill_projection_rows.rs +++ b/crates/ui-egui/tests/it/fill_projection_rows.rs @@ -34,6 +34,7 @@ fn each_projection_shows_its_own_rows() { for label in ["Depth culling", "Backface culling", "Angle", "Extends Outside Shape", "Offset X", "Rotation Y", "Scale Z"] { assert!(shows(&harness, label), "planar: {label}"); } + assert!(!shows(&harness, "Reset frame"), "planar has no frame to reset"); let (harness, _) = app_with_fill("warp"); @@ -42,12 +43,14 @@ fn each_projection_shows_its_own_rows() { for label in ["Depth", "Reset frame", "Depth culling", "Offset X", "Rotation X", "Scale X"] { assert!(shows(&harness, label), "warp: {label}"); } + assert!(!shows(&harness, "Backface culling"), "a warp has no backface culling"); let (harness, _) = app_with_fill("cylindrical"); for label in ["Angle", "Backface culling", "Extends Outside Shape", "Offset X"] { assert!(shows(&harness, label), "cylindrical: {label}"); } + assert!(!shows(&harness, "Depth culling")); let (harness, _) = app_with_fill("triplanar"); @@ -111,6 +114,7 @@ fn the_culling_rows_i_explains_the_row_on_hover_without_covering_its_values() { let before = projection(&harness, layer); let info = harness.get_by_label(DEPTH_CULLING_TIP).rect().center(); click_at(&mut harness, info); + assert_eq!(projection(&harness, layer), before); } @@ -173,7 +177,9 @@ fn reset_frame_puts_a_warps_corners_back() { fn the_3d_projection_settings_fold_away() { let (mut harness, _) = app_with_fill("spherical"); assert!(harness.query_by_label("Scale X").is_some(), "the band starts open"); + click_label(&mut harness, "3D projection settings"); + assert!(harness.query_by_label("Scale X").is_none()); assert!(harness.query_by_label("Spherical projection").is_some(), "the rows above it stay"); } @@ -205,10 +211,13 @@ fn the_fill_caption_resets_the_whole_fill_section_to_its_projections_defaults_in ); assert_eq!(after.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the symmetry stays"); assert!(harness.get_by_label("Fill: Reset to defaults").accesskit_node().is_disabled(), "at the defaults it is faint and inert"); + click_at(&mut harness, reset); + assert_eq!(fill(&harness, layer), after, "a click at the defaults changes nothing"); harness.state_mut().run("edit.undo", json!({})); + assert_eq!(fill(&harness, layer), after_band, "one undo step brings the whole section back"); } diff --git a/crates/ui-egui/tests/it/fill_symmetry_rows.rs b/crates/ui-egui/tests/it/fill_symmetry_rows.rs index 466f07f5..240be1a9 100644 --- a/crates/ui-egui/tests/it/fill_symmetry_rows.rs +++ b/crates/ui-egui/tests/it/fill_symmetry_rows.rs @@ -48,24 +48,32 @@ fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() { assert!(harness.query_by_label("Mirror symmetry").is_none(), "off, the section is the caption alone"); click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(symmetry(&harness, layer).on); assert!(harness.query_by_label("Axis position X").is_some(), "a mirror across X moves along X"); assert!(harness.query_by_label("Count").is_none(), "a mirror has no radial rows"); click_node(&mut harness, Role::RadioButton, "Y"); + assert_eq!(symmetry(&harness, layer).axis, 1); + click_node(&mut harness, Role::CheckBox, "Flip copy U"); + assert_eq!(symmetry(&harness, layer).flip, [true, false]); click_node(&mut harness, Role::ComboBox, "Mirror symmetry"); click_node(&mut harness, Role::ListBoxOption, "Radial symmetry"); + assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial); + for label in ["Count", "Angle span", "Axis position X", "Axis position Z"] { assert!(harness.query_by_label(label).is_some(), "radial round Y: {label}"); } + assert!(harness.query_by_label("Axis position Y").is_none(), "the turning axis does not move along itself"); click_node(&mut harness, Role::CheckBox, "Symmetry"); + assert!(!symmetry(&harness, layer).on); assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial, "switched off, the settings stay"); } @@ -74,7 +82,9 @@ fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() { fn a_uv_fill_says_why_in_place_of_the_symmetry_switch() { let (mut harness, layer) = app_with_fill("uv"); assert!(harness.query_by_role_and_label(Role::CheckBox, "Symmetry").is_none(), "no switch to click"); + click_label(&mut harness, "Not available with UV projection"); + assert!(!symmetry(&harness, layer).on, "a UV projection has no symmetry to switch on"); assert!(harness.query_by_label("Type").is_none(), "its settings stay hidden, not greyed"); } @@ -87,11 +97,13 @@ fn a_count_click_that_keeps_the_count_adds_no_undo_step_and_a_drag_to_the_next_a let inside = count_at(&harness, 6.2); click_at(&mut harness, inside); + assert_eq!(symmetry(&harness, layer).count, 6); assert_eq!(undo_depth(&harness), steps, "a count that stays six is no edit"); let (from, to) = (count_at(&harness, 6.0), count_at(&harness, 7.3)); drag(&mut harness, from, to); + assert_eq!(symmetry(&harness, layer).count, 7); assert_eq!(undo_depth(&harness), steps + 1, "the drag's frames merge into one step"); } diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index 5a923224..ac418f44 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -59,10 +59,12 @@ fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() { 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!( @@ -81,6 +83,7 @@ fn a_box_drag_in_the_2d_view_is_one_fill() { 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")); } @@ -100,10 +103,12 @@ fn a_new_press_after_release_does_not_resume_the_previous_box() { .events .extend([Event::PointerMoved(point), Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); harness.run_steps(1); + assert_eq!(painted_tiles(&harness), tiles_after_drag, "a press alone must not refill the old rectangle"); harness.event(Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(1); + assert_eq!(history(&harness).len(), history_after_drag.len() + 1, "only the new click records a step"); } @@ -115,11 +120,13 @@ fn the_symmetry_toggle_is_offered_for_polygon_fill_and_a_symmetric_click_is_one_ harness.get_by_label("Symmetry settings"); harness.get_by_label("Symmetry").click(); harness.run_steps(2); + assert!(harness.state().session.tool.brush.symmetry.any(), "the toggle turns mirroring on for the fill"); let center = harness.state().viewport_rect.center(); let before = history(&harness).len(); click(&mut harness, center); + assert_eq!(history(&harness).len(), before + 1, "the fill and its mirror copies are one undo step"); assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); } diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index a2cd6187..50b4f220 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -188,7 +188,9 @@ fn the_window_follows_the_reference_layout() { for labels in order.windows(2) { assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]); } + assert!(h.query_by_label("Custom unit scale").is_none(), "Physical size starts collapsed"); + let disabled = |role: Role, label: &str| h.get_by_role_and_label(role, label).accesskit_node().is_disabled(); for (role, label) in [ (Role::CheckBox, "Compute tangent space per fragment"), @@ -205,6 +207,7 @@ fn the_window_follows_the_reference_layout() { let center = h.get_by_role_and_label(Role::CheckBox, "Compute tangent space per fragment").rect().center(); h.hover_at(center); h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "the hint of a setting TextureCraft does not have yet"); } diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index f3b7823b..3ff215b7 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -171,9 +171,13 @@ 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:?}"); + let projected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": fill, "projection": "uv"})); + assert!(projected.is_ok(), "{projected:?}"); + harness.run_steps(3); let center = view_center(&harness); @@ -227,6 +231,7 @@ fn bake_and_render_modes_never_open_it() { harness.state_mut().ui.mode = mode; harness.run_steps(3); click(&mut harness, PointerButton::Secondary, center); + assert_eq!(harness.state().properties_popup, None, "{mode:?}"); } } diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 848064c3..d1c732fd 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -258,7 +258,9 @@ fn the_click_that_closes_the_drop_menu_paints_nothing_and_adds_no_undo_step() { let image = import_white_image(&mut harness); drop_asset(&mut harness, Asset::Texture(image), position); harness.run_steps(2); + assert!(menu_open(&harness, position)); + let history = harness.state().session.history_labels().len(); // A point on the same set, away from the menu diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 804cf5fc..01b2e2e2 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -829,6 +829,7 @@ fn mask_fill_image_snapshot() { let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; assert_eq!(*source, Source::image(name)); assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); + save(&mut harness, &output_dir, "mask-fill-image-selected"); } From 0abf2805a8370dc987abce550543da9886494b3f Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:29:30 +0000 Subject: [PATCH 031/153] Material and colour: review repairs from #698 Chasse's repairs to this part's code, carried over from the #698 head (5644b7d3). --- ATTRIBUTION.md | 13 ++- NOTICE | 12 +++ crates/core/src/layer.rs | 7 +- crates/engine/src/fill_alpha.rs | 3 + crates/engine/src/fill_material_cmds.rs | 20 +++-- crates/engine/src/layer_cmds.rs | 8 -- crates/engine/src/link_cmds.rs | 50 +++++++---- crates/engine/src/preview.rs | 27 +++--- crates/engine/src/session.rs | 21 +++-- crates/engine/tests/it/fill_alpha_source.rs | 3 + crates/engine/tests/it/fill_whole_material.rs | 11 +++ crates/engine/tests/it/filter_support.rs | 1 + crates/engine/tests/it/materialcraft_link.rs | 39 ++++++++ crates/engine/tests/session.rs | 69 +++++++++++--- .../ui-egui/src/color_picker/picker_state.rs | 7 ++ crates/ui-egui/src/drawn_icon/distance.rs | 33 ++++--- crates/ui-egui/src/drawn_icon/mod.rs | 6 ++ crates/ui-egui/src/fill_material_panel.rs | 3 + crates/ui-egui/src/material_orb.rs | 38 +++++--- crates/ui-egui/src/orb_environment.rs | 6 +- crates/ui-egui/src/orb_previews.rs | 8 ++ crates/ui-egui/src/orb_previews/worker.rs | 1 + crates/ui-egui/src/properties_popup.rs | 1 + .../ui-egui/src/property_sheet/color_bar.rs | 45 +++++++--- .../src/property_sheet/color_picker_rows.rs | 69 ++++++-------- crates/ui-egui/src/property_sheet/slot.rs | 13 ++- .../src/property_sheet/switch_control.rs | 15 ++++ crates/ui-egui/src/property_sheet/tests.rs | 14 +++ crates/ui-egui/src/rail_popup.rs | 2 +- crates/ui-egui/src/resource_picker.rs | 52 ++++++----- crates/ui-egui/src/round_gizmo.rs | 4 + .../ui-egui/src/screen_pick/cursor_image.rs | 4 + crates/ui-egui/src/screen_pick/live_swatch.rs | 1 + crates/ui-egui/src/screen_pick/pick_shared.rs | 27 ++++++ crates/ui-egui/src/screen_pick/portal.rs | 90 +++++++++++++++---- crates/ui-egui/src/thumbs.rs | 7 ++ crates/ui-egui/src/viewport.rs | 2 + crates/ui-egui/tests/brush_cursor_2d.rs | 2 + crates/ui-egui/tests/it/fill_channel_image.rs | 1 + crates/ui-egui/tests/it/fill_material_rows.rs | 68 ++++++++++++++ crates/ui-egui/tests/it/layers_panel.rs | 1 + crates/ui-egui/tests/it/properties_popup.rs | 8 ++ crates/ui-egui/tests/it/properties_scroll.rs | 3 + crates/ui-egui/tests/it/source_picker.rs | 15 ++++ 44 files changed, 634 insertions(+), 196 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index bdd983f6..985861ac 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -23,7 +23,7 @@ licensed and keep their license file next to them. | `docs/images/texturecraft-light.png` | README screenshot: the light brightness level with the blue accent | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-lantern.png` | README render: a storm lantern (original procedural mesh of lathes and swept wires, eight texture sets) in chipped red enamel, rust, soot, tarnished brass and glass with an emissive flame (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-camera.png` | README render: a rangefinder camera (original procedural mesh) in black enamel worn to brass, leatherette, chrome and coated glass; the lens distance scale is an original image drawn in code (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | -| `assets/environments/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | https://polyhaven.com/a/studio_small_09 (1K .hdr) | CC0-1.0 | +| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | https://polyhaven.com/a/studio_small_09 (1K .hdr) | CC0-1.0 | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | @@ -41,6 +41,17 @@ These come from Rust crate dependencies (not files in this repository) and keep Without craft-fonts, Chinese, Japanese, Korean and Arabic UI text uses the operating system's fonts at run time (nothing is bundled); see [docs/localization-parity.md](docs/localization-parity.md). +## Native eyedropper dependencies + +| Crate | Use | Upstream | License | +|---|---|---|---| +| `raw-window-handle` | Identify native application windows | https://github.com/rust-windowing/raw-window-handle | MIT OR Apache-2.0 OR Zlib | +| `winsafe` | Windows pointer and event handling | https://github.com/rodrigocfd/winsafe | MIT | +| `xcap` | Windows screen pixel capture | https://github.com/nashaofu/xcap | Apache-2.0 | +| `widestring` | Windows string handling through `xcap` | https://github.com/VoidStarKat/widestring-rs | MIT OR Apache-2.0 | +| `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 | +| `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT | + ## Procedural content (no asset files) Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedurals diff --git a/NOTICE b/NOTICE index a6c9da4b..25d962ff 100644 --- a/NOTICE +++ b/NOTICE @@ -12,6 +12,18 @@ Third-party material This product bundles third-party material under its own licenses, listed below. The per-file list (author, source, license) is in ATTRIBUTION.md. +Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr), +by Sergej Majboroda (Poly Haven) — CC0-1.0. +Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256). + +Native eyedropper components: +- raw-window-handle — MIT OR Apache-2.0 OR Zlib. Copyright (c) 2019, 2020 Osspial. +- winsafe — MIT. Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias. +- xcap — Apache-2.0. +- widestring (through xcap on Windows) — MIT OR Apache-2.0. +- x11rb — MIT OR Apache-2.0. Copyright 2019 x11rb contributors. +- zbus — MIT. Copyright (c) 2024 Zeeshan Ali Khan and zbus contributors. + Phosphor Icons (compiled in through the egui-phosphor crate) — MIT. egui default fonts (compiled in through the epaint_default_fonts crate): Ubuntu-Light — Ubuntu Font Licence 1.0; Hack — MIT and Bitstream Vera License; Noto Emoji — SIL Open Font License 1.1; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1f8f731d..7d380e4c 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1652,9 +1652,11 @@ mod tests { assert!((l.apply(0.4) - 0.5).abs() < 1e-6); assert_eq!(l.apply(0.0), 0.0); assert_eq!(l.apply(1.0), 1.0); + let g = Levels { gamma: 2.0, ..Levels::default() }; assert!((g.apply(0.25) - 0.5).abs() < 1e-6); - // Degenerate ranges never divide by zero. + + // Degenerate ranges never divide by zero let d = Levels { in_low: 0.5, in_high: 0.5, ..Levels::default() }; assert!(d.apply(0.7).is_finite()); } @@ -1693,9 +1695,10 @@ mod tests { assert!(close(hsl_adjust(c, 0.0, 0.0, 0.0), c), "identity"); assert!(close(hsl_adjust([1.0, 0.0, 0.0], 1.0 / 3.0, 0.0, 0.0), [0.0, 1.0, 0.0]), "red → green"); assert!(close(hsl_adjust([1.0, 0.0, 0.0], -1.0 / 3.0, 0.0, 0.0), [0.0, 0.0, 1.0]), "red → blue"); + let gray = hsl_adjust(c, 0.0, -1.0, 0.0); assert!((gray[0] - gray[1]).abs() < 1e-6 && (gray[1] - gray[2]).abs() < 1e-6); - // Grays only change lightness, whatever the hue and saturation. + // Grays only change lightness, whatever the hue and saturation assert!(close(hsl_adjust([0.4; 3], 0.3, 1.0, 0.5), [0.7; 3])); assert!(close(hsl_adjust([0.4; 3], 0.0, 0.0, -0.5), [0.2; 3])); assert!(hsl_adjust([f32::NAN, 2.0, -1.0], f32::NAN, 5.0, -5.0).iter().all(|v| v.is_finite())); diff --git a/crates/engine/src/fill_alpha.rs b/crates/engine/src/fill_alpha.rs index 3ce4f6af..7f31ad2f 100644 --- a/crates/engine/src/fill_alpha.rs +++ b/crates/engine/src/fill_alpha.rs @@ -35,8 +35,10 @@ impl Session { let bytes = png(alpha)?; let image = texturecraft_formats::decode_image(&bytes).map_err(|error| EngineError::Other(format!("{name}: {error}")))?; + self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); + Ok(name) } } @@ -60,6 +62,7 @@ mod tests { assert_eq!(name, format!("{PREFIX}{}{EXTENSION}", alpha.id), "the id is a safe resource name as it is"); assert_eq!(library_alpha_of(&name).map(|found| &found.id), Some(&alpha.id)); } + assert!(library_alpha_of("alpha_.png").is_none()); } } diff --git a/crates/engine/src/fill_material_cmds.rs b/crates/engine/src/fill_material_cmds.rs index c2c5449f..77d538b1 100644 --- a/crates/engine/src/fill_material_cmds.rs +++ b/crates/engine/src/fill_material_cmds.rs @@ -53,10 +53,12 @@ fn set_material(s: &mut Session, p: &Value) -> Result { }; s.edit(&format!("Set fill material {}", found.label), |s| { - let sources = material_sources(&mut s.doc.project, set, found)?; + let channels = s.doc.project.texture_set(set)?.channel_list(); + let sources = material_sources(&mut s.doc.project, &channels, found)?; let edited = fill_mut(s, target)?; edited.sources = sources; edited.material = Some(found.id.to_string()); + let written: Vec = edited.sources.keys().copied().collect(); if let FillTarget::Layer(id) = target { let layer = s.doc.project.layer_mut(id)?; @@ -104,10 +106,15 @@ fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMat return Ok(false); } - // A channel set on its own clears the material; one turned off or back on keeps it, so an effect (whose sources are its channels) compares them whole + // Turning a channel off keeps the material name, so compare every source on content effects Ok(match (material, layer_channels) { (Some(_), Some(channels)) => channels.len() == fill.sources.len() && fill.sources.keys().all(|channel| channels.contains_key(channel)), - (Some(found), None) => fill.sources == material_sources(&mut s.doc.project.clone(), set, found)?, + (Some(found), None) => { + let channels = s.doc.project.texture_set(set)?.channel_list(); + // The recipe allocates a layer ID, but comparing its sources must leave the project alone + let mut scratch = Project::new("", ""); + fill.sources == material_sources(&mut scratch, &channels, found)? + } (None, Some(_)) => fill.sources.is_empty(), (None, None) => fill.sources.iter().all(|(channel, source)| *source == Source::uniform_of(*channel)), }) @@ -122,10 +129,9 @@ fn target_set(s: &Session, target: FillTarget) -> Result { s.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0))) } -/// The sources `material` writes in texture set `set`: its fill's channels the set has (the built fill's ids are taken from `project`) -fn material_sources(project: &mut Project, set: usize, material: &SmartMaterial) -> Result> { - let channels = project.texture_set(set)?.channel_list(); - let fill = whole_fill(project, material, &channels)?; +/// The material's sources for the enabled channels. The recipe allocates layer IDs in `project`. +fn material_sources(project: &mut Project, channels: &[Channel], material: &SmartMaterial) -> Result> { + let fill = whole_fill(project, material, channels)?; Ok(fill.sources.into_iter().filter(|(channel, _)| channels.contains(channel)).collect()) } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index bac08e2e..b8b2ae93 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -513,14 +513,6 @@ fn blending_set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Which fill `layer.fill.*` edits: a fill layer's (`layer`), a content fill effect's (`effect`) or a mask fill effect's (`effect`: one grayscale source, no channels or material) -#[derive(Clone, Copy)] -pub(crate) enum FillTarget { - Layer(LayerId), - Effect(LayerId), - Mask(LayerId), -} - pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { match u64p(p, "effect").map(LayerId) { Some(effect) => match s.doc.project.effect(effect).map(|(_, found)| &found.kind) { diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index bf4df701..f34e3c26 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -100,9 +100,9 @@ pub fn specs() -> Vec { } /// The link of fill layer `id`. -fn link_of(session: &Session, cmd: &str, id: LayerId) -> Result { +fn link_of<'a>(session: &'a Session, cmd: &str, id: LayerId) -> Result<&'a MaterialLink> { match &session.doc.project.layer(id)?.kind { - LayerKind::Fill(Fill { link: Some(link), .. }) => Ok(link.as_ref().clone()), + LayerKind::Fill(Fill { link: Some(link), .. }) => Ok(link.as_ref()), _ => Err(bad(cmd, format!("layer {} is not a MaterialCraft material", id.0))), } } @@ -183,17 +183,18 @@ fn preset(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, CMD, p)?; let name = strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?; let link = link_of(s, CMD, id)?; - let values = link.presets.iter().find(|pr| pr.name == name).ok_or_else(|| bad(CMD, format!("`{}` has no preset `{name}`", link.name)))?.values.clone(); + let preset = link.presets.iter().find(|preset| preset.name == name).ok_or_else(|| bad(CMD, format!("`{}` has no preset `{name}`", link.name)))?; // Leave values the painter cannot set unchanged - let values = values.into_iter().filter(|(k, _)| link.params.iter().any(|p| p.id == *k)); + let values = + preset.values.iter().filter(|(key, _)| link.params.iter().any(|param| ¶m.id == *key)).map(|(key, value)| (key.clone(), value.clone())).collect(); update(s, CMD, id, values, boolp(p, "cook").unwrap_or(true)) } /// Set parameter values of linked layer `id`; with `cook`, re-cook now (one undo step). -fn update(s: &mut Session, cmd: &str, id: LayerId, overrides: impl IntoIterator, cook_now: bool) -> Result { +fn update(s: &mut Session, cmd: &str, id: LayerId, overrides: Map, cook_now: bool) -> Result { let link = link_of(s, cmd, id)?; - let values = checked(cmd, &link, &overrides.into_iter().collect::>())?; + let values = checked(cmd, link, &overrides)?; if cook_now { return cook(s, id, values); } @@ -243,13 +244,15 @@ fn map(s: &mut Session, p: &Value) -> Result { /// The `relative` or `fixed` param of `material.link.resolution`; `Some(None)` is the texture set's own size pub(crate) fn picked_resolution(p: &Value) -> Option> { - let integer = |key: &str| p.get(key).and_then(Value::as_i64); - match (integer("relative"), integer("fixed")) { + match (p.get("relative"), p.get("fixed")) { (Some(factor), None) => { - let factor = i8::try_from(factor).ok().filter(|factor| CookResolution::FACTORS.contains(factor))?; + let factor = i8::try_from(factor.as_i64()?).ok().filter(|factor| CookResolution::FACTORS.contains(factor))?; Some((factor != 0).then_some(CookResolution::Relative(factor))) } - (None, Some(size)) => u32::try_from(size).ok().filter(|size| CookResolution::cookable(*size)).map(|size| Some(CookResolution::Fixed(size))), + (None, Some(size)) => { + let size = u32::try_from(size.as_i64()?).ok().filter(|size| CookResolution::cookable(*size))?; + Some(Some(CookResolution::Fixed(size))) + } _ => None, } } @@ -276,13 +279,12 @@ fn resolution(s: &mut Session, p: &Value) -> Result { return Ok(json!({"layer": id.0, "cooked": false})); } - // Cook first so a failed cook changes nothing, then store and swap the maps as one step + // Install the resolution and maps in one edit so a failed install also leaves the old resolution let mut job = s.link_job(id, &Map::new())?; let (texture_set, _, _) = s.doc.project.locate(id).ok_or_else(|| bad(CMD, format!("layer {} is not in a stack", id.0)))?; job.size = size.unwrap_or(CookResolution::TEXTURE_SET).size(s.doc.project.texture_set(texture_set)?.resolution); let material = job.run()?; - store(s)?; - s.apply_link_cook(id, &material, true)?; + s.install_link_cook(id, &material, s.merge_edits, Some(size))?; Ok(json!({"layer": id.0, "cooked": true, "size": job.size})) } @@ -519,7 +521,7 @@ impl Session { let mut images = std::collections::HashSet::new(); for image in self.images.values().filter(|image| images.insert(Arc::as_ptr(image))) { - retained_bytes = retained_bytes.saturating_add(image.rgba.capacity() as u64 * std::mem::size_of::<[f32; 4]>() as u64); + retained_bytes = retained_bytes.saturating_add(image_texel_bytes(image)); } budget.set_retained(retained_bytes); @@ -551,7 +553,7 @@ impl Session { graph: Some(link.graph.clone()), size: self.link_size(id)?, values, - input_identifiers: link.inputs, + input_identifiers: link.inputs.clone(), baked: self.doc.baked.get(&texture_set).cloned(), budget: self.link_memory_budget(), canceled: Arc::default(), @@ -570,6 +572,10 @@ impl Session { /// With `merge`, this folds into the previous undo step when that was an edit of the same kind /// (a parameter set while the cook ran). pub fn apply_link_cook(&mut self, id: LayerId, material: &CookedMaterial, merge: bool) -> Result<()> { + self.install_link_cook(id, material, merge, None) + } + + fn install_link_cook(&mut self, id: LayerId, material: &CookedMaterial, merge: bool, resolution_change: Option>) -> Result<()> { self.link_memory_budget().check(material_bytes(material))?; let names = self.edit_merging(EDIT, merge, |session| { let LayerKind::Fill(mut fill) = session.doc.project.layer(id)?.kind.clone() else { @@ -577,6 +583,10 @@ impl Session { }; let link = fill.link.as_mut().ok_or_else(|| EngineError::Other(format!("layer {} is not a MaterialCraft material", id.0)))?; + if let Some(resolution) = resolution_change { + link.resolution = resolution; + } + for parameter in &mut link.params { if let Some(cooked) = material.interface.parameters.iter().find(|candidate| candidate.id == parameter.id) { parameter.value = cooked.value.clone(); @@ -621,9 +631,13 @@ impl Session { } fn material_bytes(material: &CookedMaterial) -> u64 { - material.maps.iter().fold(0u64, |total, map| { - total.saturating_add(map.bytes.capacity() as u64).saturating_add(map.image.rgba.capacity() as u64 * std::mem::size_of::<[f32; 4]>() as u64) - }) + material.maps.iter().fold(0u64, |total, map| total.saturating_add(map.bytes.capacity() as u64).saturating_add(image_texel_bytes(&map.image))) +} + +fn image_texel_bytes(image: &texturecraft_compose::ImageRes) -> u64 { + let texel_bytes = |capacity: usize| (capacity as u64).saturating_mul(std::mem::size_of::<[f32; 4]>() as u64); + let full_image = texel_bytes(image.rgba.capacity()); + image.mips.get().into_iter().flatten().fold(full_image, |bytes, mip| bytes.saturating_add(texel_bytes(mip.rgba.capacity()))) } /// A resource name that preserves its suffix through a project round trip. diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 55e4bde0..15d8c072 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -19,13 +19,18 @@ pub struct Sample { /// The view-space normal (= position on the unit sphere) of each pixel of a `size²` image, /// row-major, None outside the sphere. pub fn sphere_normals(size: usize) -> impl Iterator> { - let r = (size as f32 * 0.5 - 1.0).max(0.5); - (0..size * size).map(move |i| { - let (x, y) = ((i % size) as f32 + 0.5 - size as f32 * 0.5, size as f32 * 0.5 - (i / size) as f32 - 0.5); - let (dx, dy) = (x / r, y / r); - let d2 = dx * dx + dy * dy; - (d2 <= 1.0).then(|| Vec3::new(dx, dy, (1.0 - d2).max(0.0).sqrt())) - }) + (0..size * size).map(sphere_normal_at(size)) +} + +fn sphere_normal_at(size: usize) -> impl Fn(usize) -> Option { + let center_px = size as f32 * 0.5; + let radius_px = (center_px - 1.0).max(0.5); + move |pixel_index| { + let (x, y) = ((pixel_index % size) as f32 + 0.5 - center_px, center_px - (pixel_index / size) as f32 - 0.5); + let (dx, dy) = (x / radius_px, y / radius_px); + let length_squared = dx * dx + dy * dy; + (length_squared <= 1.0).then(|| Vec3::new(dx, dy, (1.0 - length_squared).max(0.0).sqrt())) + } } fn coords(n: Vec3) -> Coords { @@ -53,11 +58,11 @@ pub fn material(id: &str, size: usize) -> Option>> { 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(); - let samples = normals + let normal_at = sphere_normal_at(size); + let samples = (0..size * size) .into_par_iter() - .map(|normal| { - let at = coords(normal?); + .map(|pixel_index| { + let at = coords(normal_at(pixel_index)?); let mut values = CHANNELS.map(Channel::default_value); for layer in layers.iter().filter(|layer| layer.visible) { // Plain materials are unmasked fills diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 83a8461d..2668cb1f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -746,6 +746,14 @@ impl Session { // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); + if removed_or_replaced_resource { + for cache in &mut self.caches { + cache.invalidate_all(); + } + + return; + } + let added_resource_names: BTreeSet<_> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).collect(); let uses_added_resource = |texture_set_index: usize| { use texturecraft_core::{EffectKind, Fill, Source}; @@ -779,19 +787,14 @@ impl Session { stack, ) }; - for texture_set_index in 0..self.caches.len() { - let before = stack_key(previous_document, texture_set_index); - let after = stack_key(&self.doc, texture_set_index); - let resource_changed = removed_or_replaced_resource || uses_added_resource(texture_set_index); - let Some(cache) = self.caches.get_mut(texture_set_index) else { - continue; - }; - - if resource_changed { + for (texture_set_index, cache) in self.caches.iter_mut().enumerate() { + if uses_added_resource(texture_set_index) { cache.invalidate_all(); continue; } + let before = stack_key(previous_document, texture_set_index); + let after = stack_key(&self.doc, texture_set_index); if before == after { continue; } diff --git a/crates/engine/tests/it/fill_alpha_source.rs b/crates/engine/tests/it/fill_alpha_source.rs index 6c3e7dd3..ae64f128 100644 --- a/crates/engine/tests/it/fill_alpha_source.rs +++ b/crates/engine/tests/it/fill_alpha_source.rs @@ -32,6 +32,7 @@ fn an_alpha_becomes_the_channels_image_once_and_its_set_is_one_undo_step() { assert_eq!(source(&session, layer, Channel::Roughness), Source::image(name.clone())); assert!(session.doc.resources.contains_key(&name), "the alpha's picture is a project resource, so the project saves it"); + let image = session.images.get(&name).expect("the channel's image is decoded"); assert_eq!((image.width, image.height), (alphas::BASE as u32, alphas::BASE as u32)); assert_eq!(library_alpha_of(&name).map(|alpha| alpha.id.as_str()), Some("scratches"), "the slot can name the alpha it came from"); @@ -39,6 +40,7 @@ fn an_alpha_becomes_the_channels_image_once_and_its_set_is_one_undo_step() { // One undo takes the source and the resource back together execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(source(&session, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness)); assert!(!session.doc.resources.contains_key(&name), "undo takes the resource back with the source"); @@ -62,5 +64,6 @@ fn an_unknown_alpha_changes_nothing() { // No undo step either: the next undo takes back the added layer execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(session.doc.project.layer(layer).is_err(), "the refused set added no undo step"); } diff --git a/crates/engine/tests/it/fill_whole_material.rs b/crates/engine/tests/it/fill_whole_material.rs index b444a3fb..3083c969 100644 --- a/crates/engine/tests/it/fill_whole_material.rs +++ b/crates/engine/tests/it/fill_whole_material.rs @@ -30,6 +30,7 @@ fn a_fill_takes_one_whole_material_names_it_and_forgets_it_once_a_channel_is_set execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "opacity", "value": 0.5})).unwrap(); let projection = fill(&s, id).projection; let saved: Value = serde_json::to_value(fill(&s, id)).unwrap(); + assert!(saved.get("material").is_none(), "a fill without a whole material saves as before"); execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "copper_hammered"})).unwrap(); @@ -42,16 +43,22 @@ fn a_fill_takes_one_whole_material_names_it_and_forgets_it_once_a_channel_is_set assert_eq!(execute(&mut s, "project.inspect", &json!({})).unwrap().to_string().matches("\"material\":\"copper_hammered\"").count(), 1); let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(fill(&reopened, id).material.as_deref(), Some("copper_hammered"), "saved with the project"); execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(fill(&s, id).material, None, "one undo step"); assert_eq!(fill(&s, id).source(Channel::BaseColor), Source::Uniform([1.0, 0.0, 0.0])); + execute(&mut s, "edit.redo", &json!({})).unwrap(); execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "metallic", "enabled": false})).unwrap(); + assert!(fill(&s, id).material.is_some(), "turning a channel off keeps the material"); + execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "roughness", "value": 0.3})).unwrap(); + assert_eq!(fill(&s, id).material, None, "a channel set on its own is no longer the whole material"); execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "Steel"})).unwrap(); @@ -63,10 +70,12 @@ fn a_fill_takes_one_whole_material_names_it_and_forgets_it_once_a_channel_is_set let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); execute(&mut s, "layer.fill.material", &json!({"effect": effect, "material": "gold_polished"})).unwrap(); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("\"material\":\"gold_polished\"")); // The shelf names a plain material's fill; a smart one is no whole material let shelf = layer(execute(&mut s, "material.apply", &json!({"material": "brass"})).unwrap()); + assert_eq!(fill(&s, shelf).material.as_deref(), Some("brass")); assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "steel_painted_worn"})).is_err(), "smart"); assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "nope"})).is_err()); @@ -110,6 +119,7 @@ fn clearing_a_content_fill_effects_material_lays_its_channels_defaults() { assert_eq!(cleared.material, None); assert_eq!(cleared.sources.keys().copied().collect::>(), material_channels, "the material's channels stay on"); assert!(cleared.sources.iter().all(|(channel, source)| *source == Source::uniform_of(*channel)), "at their defaults"); + let roughness = crate::filter_support::center(&mut s, Channel::Roughness)[0]; assert!((roughness - Channel::Roughness.default_value()[0]).abs() < 0.01, "the effect still lays the default roughness: {roughness}"); } @@ -146,6 +156,7 @@ fn setting_the_material_again_brings_back_a_content_fill_effects_channel_turned_ for enabled in off_and_on { execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "roughness", "enabled": enabled})).unwrap(); } + assert_ne!(effect_fill(&s, effect).sources, whole, "roughness is off or back at its default"); execute(&mut s, "layer.fill.material", &gold).unwrap(); diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index 8109c419..020b202f 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -29,6 +29,7 @@ pub(crate) fn facing_session() -> Session { s.viewport = Vec2::splat(VIEWPORT_SIDE); s.camera.yaw = 0.0; s.camera.pitch = 0.0; + s.update(); s } diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index d9052f04..3ab6a7c7 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -156,9 +156,13 @@ fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { assert!(set(&mut session, json!({"id": "nope", "value": 1, "cook": false})).is_err()); assert!(set(&mut session, json!({"id": "wear", "value": "soft", "cook": false})).is_err()); assert!(set(&mut session, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err()); + set(&mut session, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]})); + set(&mut session, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.9})); // Cooks follow the texture set resolution @@ -175,15 +179,19 @@ fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { assert!(!session.doc.resources.contains_key(&old), "old maps are dropped"); execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!((roughness(&mut session) - 0.25).abs() < 2e-3, "undo restores the earlier maps"); assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.5})); execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert!((roughness(&mut session) - 0.75).abs() < 2e-3); // Presets skip unsupported inputs and reject unknown names assert!(execute(&mut session, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err()); + execute(&mut session, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap(); + assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 1.0})); } @@ -193,21 +201,31 @@ fn channels_read_the_output_they_are_mapped_to() { let mut s = session(); let id = install(&mut s); let map = |s: &mut Session, output: &str| execute(s, "material.link.map", &json!({"layer": id.0, "channel": "roughness", "output": output})); + assert!(map(&mut s, "curvature").is_err(), "outputs the material lacks are errors"); assert!(execute(&mut s, "material.link.map", &json!({"layer": id.0, "output": "roughness"})).is_err()); // Roughness reads the ambient occlusion output (all white) map(&mut s, "ambientOcclusion").unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3); assert_eq!(link(&s, id).output_of(Channel::Roughness), "ambientOcclusion"); + let saved = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(link(&saved, id), link(&s, id)); + s.apply_link_cook(id, &cooked(0.75, 0.5), false).unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3, "a re-cook keeps the mapping"); + map(&mut s, "roughness").unwrap(); + assert!((roughness(&mut s) - 0.75).abs() < 2e-3); assert!(link(&s, id).mapping.is_empty(), "a channel's own output is no mapping"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3); // A link saved before mappings (no outputs list) maps from its channels' maps @@ -217,13 +235,17 @@ fn channels_read_the_output_they_are_mapped_to() { let link = fill.link.as_mut().unwrap(); link.outputs.clear(); let saved = serde_json::to_value(&**link).unwrap(); + assert!(saved.get("outputs").is_none() && saved.get("mapping").is_none() && saved.get("resolution").is_none(), "{saved}"); } execute(&mut old, "material.link.map", &json!({"layer": id.0, "channel": "roughness", "output": "ambientOcclusion"})).unwrap(); + assert!((roughness(&mut old) - 1.0).abs() < 2e-3); assert!(link(&old, id).outputs.contains_key("roughness"), "the unmapped output stays listed"); + let kept = old.doc.resources.len(); execute(&mut old, "file.removeUnused", &Value::Null).unwrap(); + assert_eq!(old.doc.resources.len(), kept, "outputs no channel reads are kept"); } @@ -238,14 +260,22 @@ fn materials_cook_at_their_picked_resolution() { size["cook"] = json!(false); execute(s, "material.link.resolution", &size) }; + assert_eq!(size(&s), 128); + pick(&mut s, json!({"fixed": 1024})).unwrap(); + assert_eq!((link(&s, id).resolution, size(&s)), (Some(CookResolution::Fixed(1024)), 1024)); + pick(&mut s, json!({"relative": 2})).unwrap(); + assert_eq!(size(&s), 512); + let steps = s.history_labels().len(); pick(&mut s, json!({"relative": 2})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "the size it already has adds no step"); + for bad in [ json!({"fixed": 300}), json!({"fixed": 64}), @@ -254,12 +284,21 @@ fn materials_cook_at_their_picked_resolution() { json!({"relative": "x"}), json!({}), json!({"relative": 1, "fixed": 256}), + json!({"relative": "x", "fixed": 256}), + json!({"relative": 1, "fixed": null}), ] { assert!(pick(&mut s, bad.clone()).is_err(), "{bad}"); } + + assert_eq!(size(&s), 512, "rejected options keep the current resolution"); + assert_eq!(s.history_labels().len(), steps, "rejected options add no undo step"); + pick(&mut s, json!({"relative": 0})).unwrap(); + assert_eq!((link(&s, id).resolution, size(&s)), (None, 128)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&s), 512); // A hostile project's size falls back to the texture set's diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 0cf88cf2..be7a504a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -181,6 +181,7 @@ fn polygon_fill_and_color_picker() { execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).unwrap(); execute(&mut s, "tool.colorPicker", &Value::Null).unwrap(); let r = execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).unwrap(); + assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}"); } @@ -197,8 +198,11 @@ fn color_at_reads_the_surface_without_changing_the_brush() { let read = s.color_at(Vec2::new(200.0, 200.0), viewport).unwrap(); let surface = read.get(&Channel::Roughness).unwrap(); + assert!((surface[0] - 0.9).abs() < 0.01, "{surface:?}"); + let brush = s.tool.values.get(&Channel::Roughness).unwrap(); + assert!((brush[0] - 0.2).abs() < 0.01, "the brush keeps its own value: {brush:?}"); } @@ -921,14 +925,19 @@ fn blending_set_gives_each_channel_its_own_mode_and_opacity_in_one_undo_step() { assert_eq!((after[&Channel::BaseColor].mode, after[&Channel::BaseColor].opacity), (texturecraft_engine::core::BlendMode::Multiply, 0.25)); assert_eq!((after[&Channel::Roughness].mode, after[&Channel::Roughness].opacity), (before[&Channel::Roughness].mode, 0.5)); assert_eq!(after[&Channel::Metallic], before[&Channel::Metallic], "channels not listed stay as they were"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(read(&s), before, "one undo step restores every listed channel"); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); // A channel the layer has disabled stays disabled execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "metallic", "enabled": false})).unwrap(); execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"metallic": {"opacity": 0.1}}})).unwrap(); + assert!(!read(&s).contains_key(&Channel::Metallic)); + let stable = read(&s); for bad in [ json!({"layer": layer}), @@ -940,21 +949,61 @@ fn blending_set_gives_each_channel_its_own_mode_and_opacity_in_one_undo_step() { assert_eq!(read(&s), stable, "an error changes nothing"); } execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"baseColor": {"opacity": 2.0}, "roughness": {"opacity": -1.0}}})).unwrap(); + assert_eq!((read(&s)[&Channel::BaseColor].opacity, read(&s)[&Channel::Roughness].opacity), (1.0, 0.0), "opacity is clamped"); } #[test] -fn a_new_session_forgets_the_projector_depth_maps_built_before_it() { - use texturecraft_engine::compose::projector_depth::ProjectorDepth; - use texturecraft_engine::core::{Projection, Projector, UvTransform}; +fn interleaved_sessions_render_depth_from_their_own_mesh() { + use texturecraft_engine::geom::{Mesh, glam::Vec3}; - let mesh = primitives::sphere(1.0, 16, 8); - let projection = - Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None }; - let built = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); + let make_mesh = |front_edge| { + let mut positions = vec![ + Vec3::new(0.0, -1.0, 0.5), + Vec3::new(front_edge, -1.0, 0.5), + Vec3::new(front_edge, 1.0, 0.5), + Vec3::new(0.0, 1.0, 0.5), + Vec3::new(-1.0, -1.0, -0.5), + Vec3::new(1.0, -1.0, -0.5), + Vec3::new(1.0, 1.0, -0.5), + Vec3::new(-1.0, 1.0, -0.5), + ]; + // Padding makes the old sampled key miss the front edge + positions.resize(200, Vec3::ZERO); + let mut uvs = vec![ + Vec2::new(0.5, 0.0), + Vec2::new(1.0, 0.0), + Vec2::new(1.0, 1.0), + Vec2::new(0.5, 1.0), + Vec2::new(0.0, 0.0), + Vec2::new(0.5, 0.0), + Vec2::new(0.5, 1.0), + Vec2::new(0.0, 1.0), + ]; + uvs.resize(positions.len(), Vec2::ZERO); + let normals = vec![Vec3::Z; positions.len()]; + Mesh::from_parts(positions, Some(normals), uvs, vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7], "Two squares").unwrap() + }; - Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let mut covered = Session::new_project("Covered", make_mesh(1.0), "squares", None, 128).unwrap(); + let mut exposed = Session::new_project("Exposed", make_mesh(0.5), "squares", None, 128).unwrap(); + let sample_rear_surface = |session: &Session| session.caches[0].composite.value(Channel::BaseColor, 56, 32); - let after = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); - assert!(!std::sync::Arc::ptr_eq(&built, &after), "a mesh sharing the old one's fingerprint must not take its map"); + for session in [&mut covered, &mut exposed] { + execute(session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute( + session, + "layer.fill.projection", + &json!({ + "projection": "planar", "axis": 2, "depthCulling": true, "depthCullingHardness": 1.0, + }), + ) + .unwrap(); + session.update(); + } + + let hidden = sample_rear_surface(&covered); + let visible = sample_rear_surface(&exposed); + assert!((hidden[0] - hidden[1]).abs() < 0.05, "the rear surface is occluded: {hidden:?}"); + assert!(visible[0] > visible[1] + 0.5, "the rear surface is exposed: {visible:?}"); } diff --git a/crates/ui-egui/src/color_picker/picker_state.rs b/crates/ui-egui/src/color_picker/picker_state.rs index d6b90abf..a94b8d6e 100644 --- a/crates/ui-egui/src/color_picker/picker_state.rs +++ b/crates/ui-egui/src/color_picker/picker_state.rs @@ -14,6 +14,8 @@ pub(crate) struct PickerState { pub(crate) hsv: [f32; 3], pub(crate) space: ColorSpace, pub(crate) model: ColorModel, + /// Height measured while the picker is visible, in points + pub(crate) height: Option, /// Where its title bar's drag left the window's top left corner; None while it stands beside the panel pub(crate) moved_to: Option, } @@ -79,7 +81,9 @@ mod tests { let blue = 2.0 / 3.0; state.set_hsv([blue, 1.0, 0.0]); state.set_space(ColorSpace::Linear); + assert_eq!(state.hsv, [blue, 1.0, 0.0], "black keeps the field's hue and saturation"); + state.set_hsv([state.hsv[0], state.hsv[1], 1.0]); let [red, green, blue_part] = state.linear; assert!(blue_part > 0.9 && red < 0.01 && green < 0.01, "raising Value brings blue back: {:?}", state.linear); @@ -87,9 +91,12 @@ mod tests { // A gray keeps its hue but takes its own saturation; a colour is read again state.set_hsv([0.25, 0.0, 0.5]); state.set_space(ColorSpace::Srgb); + assert_eq!((state.hsv[0], state.hsv[1]), (0.25, 0.0)); + state.set_hsv([0.0, 1.0, 1.0]); state.set_space(ColorSpace::Linear); + assert!(state.hsv[0].abs() < 1e-4 && (state.hsv[1] - 1.0).abs() < 1e-4, "red reads as red: {:?}", state.hsv); } } diff --git a/crates/ui-egui/src/drawn_icon/distance.rs b/crates/ui-egui/src/drawn_icon/distance.rs index 7b85c112..6ef855d1 100644 --- a/crates/ui-egui/src/drawn_icon/distance.rs +++ b/crates/ui-egui/src/drawn_icon/distance.rs @@ -11,26 +11,23 @@ pub(crate) fn convex_polygon(point: Point, corners: &[Point]) -> f32 { let centre = corners.iter().fold([0.0, 0.0], |sum, corner| [sum[0] + corner[0] / count, sum[1] + corner[1] / count]); let next = corners.iter().skip(1).chain(std::iter::once(&first)); - // A repeated corner (a list that closes on its first corner) has no edge, and its zero normal would read as on the outline - let edges: Vec<(Point, Point, f32)> = corners - .iter() - .zip(next) - .map(|(from, to)| (*from, [to[0] - from[0], to[1] - from[1]])) - .map(|(from, edge)| (from, edge, edge[0].hypot(edge[1]))) - .filter(|(_, _, length)| *length > f32::EPSILON) - .collect(); - if edges.len() < POLYGON_MIN_EDGES { - return f32::INFINITY; + let mut edge_count = 0; + let mut greatest_distance = f32::NEG_INFINITY; + for (from, to) in corners.iter().zip(next) { + let edge = sub(*to, *from); + let length = edge[0].hypot(edge[1]); + + // Repeated corners contribute no edge + if length > f32::EPSILON { + let normal = [edge[1] / length, -edge[0] / length]; + let side = dot(sub(point, *from), normal); + let signed = if dot(sub(centre, *from), normal) > 0.0 { -side } else { side }; + greatest_distance = greatest_distance.max(signed); + edge_count += 1; + } } - edges - .into_iter() - .map(|(from, edge, length)| { - let normal = [edge[1] / length, -edge[0] / length]; - let side = dot(sub(point, from), normal); - if dot(sub(centre, from), normal) > 0.0 { -side } else { side } - }) - .fold(f32::NEG_INFINITY, f32::max) + if edge_count < POLYGON_MIN_EDGES { f32::INFINITY } else { greatest_distance } } /// Fewer edges than a triangle's enclose nothing diff --git a/crates/ui-egui/src/drawn_icon/mod.rs b/crates/ui-egui/src/drawn_icon/mod.rs index f42e29f9..96b661c5 100644 --- a/crates/ui-egui/src/drawn_icon/mod.rs +++ b/crates/ui-egui/src/drawn_icon/mod.rs @@ -45,6 +45,7 @@ impl DrawnIcon { let pixels = side as f32; let min = ((center.to_vec2() * pixels_per_point) - egui::Vec2::splat(pixels / 2.0)).round() / pixels_per_point; let rect = egui::Rect::from_min_size(min.to_pos2(), egui::Vec2::splat(pixels / pixels_per_point)); + let whole = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)); painter.image(self.texture(painter.ctx(), side).id(), rect, whole, color); } @@ -52,6 +53,7 @@ impl DrawnIcon { /// The icon `side` pixels square as a white texture with its coverage as alpha, rendered once per size fn texture(self, ctx: &egui::Context, side: u32) -> egui::TextureHandle { let id = egui::Id::unique(("drawn_icon", self, side)); + if let Some(texture) = ctx.data(|data| data.get_temp::(id)) { return texture; } @@ -71,18 +73,22 @@ mod tests { #[test] fn an_icon_is_painted_as_one_tinted_texture_on_whole_pixels() { let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| { let painter = ui.painter(); DrawnIcon::Invert.paint(painter, egui::pos2(10.3, 20.6), 14.0, egui::Color32::RED); DrawnIcon::Invert.paint(painter, egui::pos2(40.0, 20.0), 14.0, egui::Color32::GREEN); }); + let shapes: Vec = output.shapes.iter().map(|clipped| clipped.shape.clone()).collect(); output.drop_without_applying_deltas(); let meshes: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Mesh(mesh) = shape { Some(mesh.clone()) } else { None }).collect(); assert_eq!(meshes.len(), 2, "one textured quad per icon: {shapes:?}"); + let [first, second] = [&meshes[0], &meshes[1]]; assert_eq!(first.texture_id, second.texture_id, "the texture is rendered once per size"); + let bounds = first.calc_bounds(); assert_eq!((bounds.min, bounds.size()), (egui::pos2(3.0, 14.0), egui::vec2(14.0, 14.0)), "snapped to whole pixels"); assert!(first.vertices.iter().all(|vertex| vertex.color == egui::Color32::RED), "tinted"); diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 3332d551..c58c9807 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -247,6 +247,7 @@ pub(crate) fn source_card( } return; } + match source { Source::Uniform(value) => uniform_rows(app, sheet, slot_of, value, &set), Source::Procedural { pattern, low, high, .. } => procedural_rows(app, sheet, slot_of, &pattern, [low, high], slot.reset, &set), @@ -342,6 +343,7 @@ fn uniform_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, slot_o } return; } + let mut gray = value[0]; let edit = sheet.ramp(label, &mut gray, slot_of.range()); if edit.invert { @@ -450,6 +452,7 @@ fn procedural_rows( app.run("layer.fill.set", set(with(&json!({"procedural": kind}), size))); return; } + if let Some((key, value, merge)) = edit { let mut settings = json!({"procedural": kind, "merge": merge}); settings[key] = value; diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs index aa3d6388..b41cbabf 100644 --- a/crates/ui-egui/src/material_orb.rs +++ b/crates/ui-egui/src/material_orb.rs @@ -49,12 +49,27 @@ pub(crate) fn material_orb(painter: &Painter, rect: Rect, material: &OrbMaterial /// The orb `side` pixels square, on `backdrop` pub(crate) fn render(material: &OrbMaterial, side: usize, backdrop: Color32) -> ColorImage { let side = side.clamp(1, MAX_SIDE_PX); - let env = OrbEnvironment::get(); - let back = [backdrop.r(), backdrop.g(), backdrop.b()].map(|component| f32::from(component) / 255.0); - // One pixel in orb radii: the step for the height slope and the reach of the anti-aliased outline let pixel = 2.0 / (side as f32 * SPHERE_RADIUS); - let uniform = (!material.varies()).then(|| material.sample(&orb_coords(Vec3::Y), 1.0)); + + match material.alone() { + Some(channel) => { + let footprint = pixel * std::f32::consts::FRAC_1_PI; + render_pixels(side, backdrop, pixel, |normal, coverage| (channel_view(channel, material.value(channel, &orb_coords(normal), footprint)), coverage)) + } + None => { + let studio = OrbEnvironment::get(); + let uniform = (!material.varies()).then(|| material.sample(&orb_coords(Vec3::Y), 1.0)); + render_pixels(side, backdrop, pixel, |normal, coverage| { + let (linear, opacity) = shade(material, studio, normal, pixel, uniform); + (linear.map(|component| linear_to_srgb(aces(component * EXPOSURE))), coverage * opacity) + }) + } + } +} + +fn render_pixels(side: usize, backdrop: Color32, pixel: f32, shade_pixel: impl Fn(Vec3, f32) -> ([f32; 3], f32) + Sync) -> ColorImage { + let back = [backdrop.r(), backdrop.g(), backdrop.b()].map(|component| f32::from(component) / 255.0); let mut pixels = vec![Color32::TRANSPARENT; side * side]; pixels.par_chunks_mut(side).enumerate().for_each(|(y, row)| { for (x, out) in row.iter_mut().enumerate() { @@ -70,16 +85,7 @@ pub(crate) fn render(material: &OrbMaterial, side: usize, backdrop: Color32) -> // Pixels on the outline shade the sphere's rim let (u, v) = if distance > 1.0 { (u / distance, v / distance) } else { (u, v) }; let normal = Vec3::new(u, v, (1.0 - u * u - v * v).max(0.0).sqrt()); - let (shown, alpha) = match material.alone() { - Some(channel) => { - let footprint = pixel * std::f32::consts::FRAC_1_PI; - (channel_view(channel, material.value(channel, &orb_coords(normal), footprint)), coverage) - } - None => { - let (linear, opacity) = shade(material, env, normal, pixel, uniform); - (linear.map(|component| linear_to_srgb(aces(component * EXPOSURE))), coverage * opacity) - } - }; + let (shown, alpha) = shade_pixel(normal, coverage); let [r, g, b] = [0, 1, 2].map(|channel| ((back[channel] + (shown[channel] - back[channel]) * alpha) * 255.0).round().clamp(0.0, 255.0) as u8); *out = Color32::from_rgb(r, g, b); } @@ -173,6 +179,7 @@ mod tests { fn the_orb_sits_on_its_backdrop_and_shows_its_colour() { let image = render(&copper(), 64, BACKDROP); assert_eq!(image.pixels[0], BACKDROP, "the corner is off the sphere"); + let middle = at(&image, 32, 32); assert!(middle.r() > middle.b(), "copper is warm: {middle:?}"); } @@ -228,6 +235,7 @@ mod tests { let shown = render(&OrbMaterial::of_fill(&fill, &on, &Default::default()), 64, BACKDROP); let changed = shown.pixels.iter().zip(&flat.pixels).filter(|(a, b)| a != b).count(); assert!(changed > 64 * 64 / 4, "{channel:?} changes the orb: {changed} pixels"); + let off = render(&OrbMaterial::of_fill(&fill, &[], &Default::default()), 64, BACKDROP); let flat_off = render(&OrbMaterial::of_fill(&Fill::default(), &[], &Default::default()), 64, BACKDROP); assert_eq!(off.pixels, flat_off.pixels, "{channel:?} switched off shows its default"); @@ -247,6 +255,7 @@ mod tests { let lightness: Vec = image.pixels.iter().filter(|pixel| **pixel != BACKDROP).map(|pixel| pixel.g()).collect(); let (darkest, brightest) = (lightness.iter().min().copied().unwrap_or(0), lightness.iter().max().copied().unwrap_or(0)); assert!(brightest - darkest > 100, "the black and white halves both show: {darkest}..{brightest}"); + let missing = render(&OrbMaterial::of_fill(&fill, &[Channel::BaseColor], &Default::default()), 64, BACKDROP); assert_ne!(missing.pixels, image.pixels, "a missing image reads the default"); } @@ -283,6 +292,7 @@ mod tests { output.textures_delta.clear(); std::thread::sleep(Duration::from_millis(5)); } + assert_eq!(OrbPreviews::shown_size(&ctx, "hidpi"), Some([expected, expected]), "at {scale}x"); } } diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index 286249a1..e0bd4da4 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -7,7 +7,7 @@ use texturecraft_engine::geom::glam::Vec3; use texturecraft_render::ibl::{self, EnvImage}; /// The bundled environment: a small photo studio with soft boxes, 512 x 256 equirect Radiance HDR -const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/environments/studio_small_09_512.hdr"); +const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/hdr/studio_small_09_512.hdr"); /// Prefiltered levels from mirror (0) to fully rough (last) const LEVELS: u32 = 6; @@ -57,8 +57,10 @@ impl OrbEnvironment { let turned = turn(direction); let level = roughness.clamp(0.0, 1.0) * (self.levels.len().saturating_sub(1)) as f32; let below = level.floor() as usize; + let sample = |index: usize| self.levels.get(index).or(self.levels.last()).map_or(Vec3::ZERO, |env| env.sample(turned)); let fraction = level - level.floor(); + if fraction <= 0.0 { sample(below) } else { sample(below).lerp(sample(below + 1), fraction) } } @@ -66,9 +68,11 @@ impl OrbEnvironment { pub(crate) fn diffuse(&self, normal: Vec3) -> Vec3 { let basis = ibl::sh_basis(turn(normal)); let mut light = Vec3::ZERO; + for (coefficient, weight) in self.irradiance.iter().zip(basis) { light += Vec3::from(*coefficient) * weight; } + light.max(Vec3::ZERO) } } diff --git a/crates/ui-egui/src/orb_previews.rs b/crates/ui-egui/src/orb_previews.rs index ffc478d4..65487764 100644 --- a/crates/ui-egui/src/orb_previews.rs +++ b/crates/ui-egui/src/orb_previews.rs @@ -227,6 +227,7 @@ mod tests { } break; } + std::thread::sleep(Duration::from_millis(5)); } sizes @@ -239,7 +240,9 @@ mod tests { let job = OrbJob::new(copper(0.3), 200, Color32::BLACK); let mut first = None; run(&ctx, |ctx| first = OrbPreviews::texture(ctx, place, job.key, || job.clone())); + assert!(first.is_none(), "the first pass does not wait for the render"); + let sizes = draw_until_settled(&ctx, place, &job); // A fast render can bring both pictures between two frames, so only the full one is sure to show; the quick one never comes after it @@ -250,6 +253,7 @@ mod tests { // The same look again: drawn at once from the cache, nothing new to render let mut again = None; run(&ctx, |ctx| again = OrbPreviews::texture(ctx, place, job.key, || job.clone())); + assert_eq!(again.map(|texture| texture.size()), Some([200, 200])); assert!(OrbPreviews::settled(&ctx), "a cached look renders nothing"); @@ -257,9 +261,12 @@ mod tests { let rougher = OrbJob::new(copper(0.8), 200, Color32::BLACK); let mut meanwhile = None; run(&ctx, |ctx| meanwhile = OrbPreviews::texture(ctx, place, rougher.key, || rougher.clone())); + assert!(meanwhile.is_some(), "the last picture stays while the new one renders"); assert!(!OrbPreviews::settled(&ctx), "the new look is rendering"); + draw_until_settled(&ctx, place, &rougher); + assert!(OrbPreviews::settled(&ctx)); } @@ -337,6 +344,7 @@ mod tests { // The cached picture holds the image weakly, so its address stays taken however the allocator reuses blocks assert!(Arc::weak_count(&image) >= 1, "the cached picture keeps the image's address"); + drop(image); // Same name and size: the freed image's address must not come back to the cached picture's key diff --git a/crates/ui-egui/src/orb_previews/worker.rs b/crates/ui-egui/src/orb_previews/worker.rs index ad7d8260..01f50dcb 100644 --- a/crates/ui-egui/src/orb_previews/worker.rs +++ b/crates/ui-egui/src/orb_previews/worker.rs @@ -24,6 +24,7 @@ impl Worker { // Idle, the thread holds no context: the context owns the job sender, so a held one would keep both alive drop(repaint.take()); let Ok((job, ctx)) = job_rx.recv() else { break }; + waiting.push(job); repaint = Some(ctx); } diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 4f70d16a..e72f193d 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -52,6 +52,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: /// Draws the open popup and closes it on a press outside it (but not an eyedropper pick's) 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, diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs index 82fe8887..b9239dc0 100644 --- a/crates/ui-egui/src/property_sheet/color_bar.rs +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -67,16 +67,21 @@ const PICKER_MIN_WIDTH: f32 = 240.0; const RESIZE_GRIP: f32 = 5.0; const RESIZE_CORNER: f32 = 8.0; +type VisiblePickers = egui::cache::FramePublisher; + /// The picker state stored at `state_id`, else a closed picker fn picker_state(ctx: &egui::Context, state_id: Id) -> PickerState { - ctx.data(|data| data.get_temp::(state_id)).unwrap_or_default() + ctx.memory_mut(|memory| memory.caches.cache::().get(&state_id).copied()).unwrap_or_default() } /// Opens `state` on `linear` in the colour space and model the user last picked in any picker -fn open_picker(ctx: &egui::Context, state: &mut PickerState, linear: [f32; 3]) { - let (space, model) = ctx.data(|data| data.get_temp::<(ColorSpace, ColorModel)>(Id::unique(PREFERENCES_KEY))).unwrap_or_default(); +fn open_picker(ctx: &egui::Context, state_id: Id, state: &mut PickerState, linear: [f32; 3]) { + let (preferences, moved_to) = + ctx.data(|data| (data.get_temp::<(ColorSpace, ColorModel)>(Id::unique(PREFERENCES_KEY)).unwrap_or_default(), data.get_temp::(state_id))); + let (space, model) = preferences; state.space = space; state.model = model; + state.moved_to = moved_to; state.open_on(linear); } @@ -127,27 +132,44 @@ impl PropertySheet<'_> { let ctx = self.ui.ctx().clone(); let state_id = id.with("picker"); let mut state = picker_state(&ctx, state_id); - state.follow(linear); if let Some(picked) = ColorPick::delivered(&ctx, id) { - state.set_linear(picked); pick.picked = Some(picked); } - if response.clicked() { + let clicked = response.clicked(); + let was_open = state.open; + if clicked { if state.open { state.open = false; } else { - open_picker(&ctx, &mut state, linear); + open_picker(&ctx, state_id, &mut state, linear); } } if state.open { + state.follow(linear); + if let Some(picked) = pick.picked { + state.set_linear(picked); + } + + let previous_position = state.moved_to; let inside = self.picker_popup(&response, glyph, label, &mut state, waiting, swatches); pick.picked = pick.picked.or(inside.picked); pick.merge = inside.merge; pick.eyedropper |= inside.eyedropper; pick.swatch = inside.swatch; + + // Reopening remembers an explicit move without saving an inactive editor + if state.moved_to != previous_position + && let Some(moved_to) = state.moved_to + { + ctx.data_mut(|data| data.insert_temp(state_id, moved_to)); + } } - ctx.data_mut(|data| data.insert_temp(state_id, state)); + + if was_open || state.open { + ctx.memory_mut(|memory| memory.caches.cache::().set(state_id, state)); + } + pick } @@ -163,8 +185,7 @@ impl PropertySheet<'_> { // A kept size may come from a bigger screen or a damaged settings file (max/min also turn NaN into a bound) let width = width.max(PICKER_MIN_WIDTH).min(screen.width().max(PICKER_MIN_WIDTH)); let field_height = field_height.max(FIELD_MIN_HEIGHT).min(screen.height().max(FIELD_MIN_HEIGHT)); - let height_id = id.with("picker_height"); - let height = ctx.data(|data| data.get_temp::(height_id)).unwrap_or(PICKER_HEIGHT_GUESS + field_height - FIELD_HEIGHT); + let height = state.height.unwrap_or(PICKER_HEIGHT_GUESS + field_height - FIELD_HEIGHT); let panel = Rect::from_x_y_ranges(self.ui.clip_rect().left().min(self.left - PAD)..=self.right + PAD, screen.y_range()); let corner = state.moved_to.unwrap_or_else(|| beside(panel, bar.rect.top(), vec2(width, height), screen)); @@ -229,7 +250,7 @@ impl PropertySheet<'_> { (pick, face, drag.dragged().then(|| drag.drag_delta()), closed.clicked(), resize) }); let (pick, face, dragged, closed, resize) = shown.inner; - ctx.data_mut(|data| data.insert_temp(height_id, face.height())); + state.height = Some(face.height()); if (state.space, state.model) != shown_in { ctx.data_mut(|data| data.insert_temp(Id::unique(PREFERENCES_KEY), (state.space, state.model))); } @@ -254,7 +275,7 @@ impl PropertySheet<'_> { && input.pointer.interact_pos().is_some_and(|at| !face.contains(at) && !bar.rect.contains(at) && !eyedropper.contains(at)) }); - // The app leaves Escape to an open picker (menus.rs); Escape in the hex field ends the typing first (egui drops the field's focus before it hears the key) + // Escape ends hex editing first even when egui has already dropped the field's focus let escape = ctx.input(|input| input.key_pressed(egui::Key::Escape)) && ctx.memory(|memory| memory.focused().is_none_or(|focused| focused == bar.id)) && !hex_took_escape(&ctx); diff --git a/crates/ui-egui/src/property_sheet/color_picker_rows.rs b/crates/ui-egui/src/property_sheet/color_picker_rows.rs index 386037d1..8ad5a498 100644 --- a/crates/ui-egui/src/property_sheet/color_picker_rows.rs +++ b/crates/ui-egui/src/property_sheet/color_picker_rows.rs @@ -1,12 +1,16 @@ //! The colour picker's rows: its colour space, the saturation/value field beside the hue strip, before | after with the hex code and eyedropper, the model's three sliders, the working-space values and the project's swatches use egui::ecolor::{hsv_from_rgb, rgb_from_hsv}; -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::text_edit::TextEditState; +use egui::{ + Align2, Color32, CornerRadius, Direction, FontId, Layout, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, UiBuilder, WidgetInfo, pos2, vec2, +}; use egui_phosphor::regular as ic; use texturecraft_engine::core::MAX_SWATCHES; use super::slider::KNOB_RADIUS; +use super::value_text_draft::ValueTextDraft; use super::{CONTROL_HEIGHT, CONTROL_RADIUS, GLYPH_SIZE, GLYPH_TARGET, PAD, PropertySheet, ROW_HEIGHT, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::color_picker::{ColorModel, ColorPick, ColorSpace, PickerState, SwatchEdit, eight_bit, hex, parse_hex}; use crate::drawn_icon::DrawnIcon; @@ -51,9 +55,6 @@ const HEX_RIGHT_INSET: f32 = HUE_STRIP_WIDTH + FIELD_TO_STRIP; const HASH_INSET: f32 = 8.0; const DIGITS_INSET: f32 = 20.0; -/// Passes after the hex field last had focus that a typed code still applies (egui reports a lost focus up to two passes late) -const FOCUS_LOOKBACK_PASSES: u64 = 2; - /// Where the hex field notes the pass in which Escape ended its typing (that Escape does not close the picker) const HEX_ESCAPE_KEY: &str = "color_picker_hex_escape"; @@ -259,56 +260,40 @@ impl PropertySheet<'_> { painter.rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); painter.text(pos2(field.left() + HASH_INSET, field.center().y), Align2::LEFT_CENTER, "#", FontId::proportional(TEXT_SIZE), tokens.text_dim); let digits = Rect::from_min_max(pos2(field.left() + DIGITS_INSET, field.top()), field.right_bottom()); - let text_id = id.with("typed"); - let opened_id = text_id.with("opened"); - let editing = self.ui.data(|data| data.get_temp::(text_id)); - - // Text left by a picker that closed mid-edit (its field no longer drawn, so never told it lost focus) is not shown again - let focused_pass_id = text_id.with("focused pass"); - let pass = self.ui.ctx().cumulative_pass_nr(); - if self.ui.memory(|memory| memory.has_focus(text_id)) { - self.ui.data_mut(|data| data.insert_temp(focused_pass_id, pass)); - } - let focused_pass = self.ui.data(|data| data.get_temp::(focused_pass_id)); - let focused = focused_pass.is_some_and(|focused_pass| pass.saturating_sub(focused_pass) <= FOCUS_LOOKBACK_PASSES); - if editing.is_some() && !focused { - self.ui.data_mut(|data| { - data.remove::(text_id); - data.remove::(opened_id); - }); - } - let editing = editing.filter(|_| focused); - - let Some(mut text) = editing else { + let text_id = id.with((self.id, "hex_typed")); + let Some(mut draft) = self.typing_draft(text_id) else { + self.skip_typing_edit(); let response = self.ui.interact(digits, id, Sense::click()).on_hover_cursor(egui::CursorIcon::Text); response.widget_info(|| WidgetInfo::labeled(Role::TextInput, true, tr("Hex color"))); - self.ui.painter().text(pos2(digits.left(), digits.center().y), Align2::LEFT_CENTER, hex(shown), semibold(TEXT_SIZE), tokens.text); + let text = hex(shown); + self.ui.painter().text(pos2(digits.left(), digits.center().y), Align2::LEFT_CENTER, text.as_str(), semibold(TEXT_SIZE), tokens.text); if response.clicked() { - self.ui.data_mut(|data| { - data.insert_temp(opened_id, hex(shown)); - data.insert_temp(text_id, hex(shown)); - }); + self.keep_typing(text_id, ValueTextDraft { original: text.clone(), text, editor: TextEditState::default() }); self.ui.memory_mut(|memory| memory.request_focus(text_id)); } + return None; }; - let edit = egui::TextEdit::singleline(&mut text) + draft.editor.store(self.ui.ctx(), text_id); + let edit = egui::TextEdit::singleline(&mut draft.text) .id(text_id) .font(semibold(TEXT_SIZE)) .frame(egui::Frame::NONE) .align(Align2::LEFT_CENTER) - .margin(vec2(0.0, 0.0)); - let response = self.ui.put(digits, edit); - if !response.lost_focus() { - self.ui.data_mut(|data| data.insert_temp(text_id, text)); + .margin(egui::Margin::ZERO); + let layout = Layout::centered_and_justified(Direction::TopDown); + let output = self.ui.scope_builder(UiBuilder::new().max_rect(digits).layout(layout), |ui| edit.show(ui)).inner; + + // Keep undo and selection history with the draft + self.ui.data_mut(|data| data.remove::(text_id)); + draft.editor = output.state; + if !output.response.lost_focus() { + self.keep_typing(text_id, draft); return None; } - let opened = self.ui.data_mut(|data| { - data.remove::(text_id); - data.remove_temp::(opened_id) - }); + self.end_typing(text_id, &draft); if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { // Escape ends the typing only: the picker stays open let pass = self.ui.ctx().cumulative_pass_nr(); @@ -316,10 +301,10 @@ impl PropertySheet<'_> { return None; } - // Left as it opened, the code is no edit: reading it back would round the colour to what the code shows, or write it over a colour changed meanwhile - let typed = parse_hex(&text)?; + // An unchanged code must preserve newer or higher precision colour values + let typed = parse_hex(&draft.text)?; let code = hex(typed); - (Some(&code) != opened.as_ref() && code != hex(shown)).then_some(typed) + (code != draft.original && code != hex(shown)).then_some(typed) } /// The model dropdown, sized to its value, and the ⋯ menu at the right edge; a click in its list picks, a hover changes nothing diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 1095571b..6717eb3c 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -223,21 +223,20 @@ impl PropertySheet<'_> { let dice = Rect::from_min_max(pos2(self.right - DICE_WIDTH, control.top()), control.max); let id = self.next_id(); - let typing_id = id.with("typed"); + let typing_id = id.with((self.id, "typed")); let tokens = self.tokens; let painter = self.ui.painter().clone(); painter.rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); // The value sits right like every number; the box lights on hover and goes accent while typing let mut changed = false; - if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { - let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); - let response = self.typing_edit(field.left() + SEED_VALUE_INSET, field.right() - SEED_VALUE_INSET, center_y, edit); + if let Some(mut draft) = self.typing_draft(typing_id) { + let response = self.typing_edit(field.left() + SEED_VALUE_INSET, field.right() - SEED_VALUE_INSET, center_y, typing_id, &mut draft); painter.rect_stroke(field, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); if response.lost_focus() { - let untouched = self.end_typing(typing_id, &text); - if let Ok(typed) = text.trim().parse::() + let untouched = self.end_typing(typing_id, &draft); + if let Ok(typed) = draft.text.trim().parse::() && !untouched && typed != *seed && !self.ui.input(|input| input.key_pressed(egui::Key::Escape)) @@ -246,7 +245,7 @@ impl PropertySheet<'_> { changed = true; } } else { - self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + self.keep_typing(typing_id, draft); } } else { self.skip_typing_edit(); diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index c8210d11..1792d9e5 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -55,12 +55,26 @@ const CHANNEL_STRIP_AIR: f32 = 6.0; /// The least air around a channel pill's name before the names shrink a point const PILL_TEXT_AIR: f32 = 10.0; +/// Width of a focused control's outline in points +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; + /// No tint for any segment: the chosen word keeps the text colour pub(super) fn untinted(_index: usize) -> &'static [Color32] { &[] } impl PropertySheet<'_> { + pub(super) fn paint_control_focus(&self, response: &Response) { + if response.has_focus() { + self.ui.painter().rect_stroke( + response.rect, + CornerRadius::same(CONTROL_RADIUS), + Stroke::new(FOCUS_OUTLINE_WIDTH, self.tokens.text_strong), + StrokeKind::Inside, + ); + } + } + /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { self.switch_tinted(label, options, selected, &[]) @@ -292,6 +306,7 @@ impl PropertySheet<'_> { StrokeKind::Inside, ); painter.text(pill.center(), Align2::CENTER_CENTER, *name, font, color); + self.paint_control_focus(&response); } self.drawn(rect.bottom()); self.space(CHANNEL_STRIP_AIR); diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 312dcef5..d47ab16a 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -218,6 +218,7 @@ fn a_culling_row_reads_name_then_picture_and_switch_with_its_i_at_the_end() { let at = harness.get_by_label("Depth Culling").rect().center(); click_at(&mut harness, at); harness.run_steps(2); + assert_ne!(harness.state().depth_culling, was, "a click on the row flips it"); } @@ -340,10 +341,12 @@ fn a_click_on_a_value_or_the_seed_selects_it_so_typing_replaces_it() { let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); let value = harness.get_by_label("Hardness value").rect(); type_at(&mut harness, value.center(), "0.4"); + assert_eq!(harness.state().hardness, 0.4, "the slider's value is replaced, not appended to"); let seed = harness.get_by_label("Seed value").rect(); type_at(&mut harness, seed.center(), "77"); + assert_eq!(harness.state().seed, 77, "the seed is replaced, not appended to"); } @@ -385,6 +388,7 @@ fn a_value_left_untyped_keeps_a_change_made_while_it_was_open() { harness.drag_at(at); harness.drop_at(at); harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_some(), "{label}: the click opens the value to type"); // Changed elsewhere while the field is open, then Enter without typing @@ -394,11 +398,13 @@ fn a_value_left_untyped_keeps_a_change_made_while_it_was_open() { harness.run_steps(1); harness.key_press(egui::Key::Enter); harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_none(), "{label}: Enter closes the value"); assert_eq!(harness.state().hardness, 0.9, "{label}: the slider keeps the newer value"); assert_eq!(harness.state().position[0], 0.5, "{label}: the number field keeps the newer value"); assert_eq!(harness.state().seed, newer_seed, "{label}: the seed keeps the newer value"); } + assert!(harness.state().hardness_merges.is_empty(), "the slider reports no edit: {:?}", harness.state().hardness_merges); assert!(harness.state().position_merges.is_empty(), "the number field reports no edit: {:?}", harness.state().position_merges); } @@ -430,12 +436,14 @@ fn a_typed_value_equal_to_the_current_one_changes_nothing() { let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 1.0, ..Gallery::default() }); let hardness = harness.get_by_label("Hardness value").rect(); type_at(&mut harness, hardness.center(), "5"); + assert_eq!(harness.state().hardness, 1.0, "a value past the end is kept at the end"); assert!(harness.state().hardness_merges.is_empty(), "kept at the value it had, it reports no edit: {:?}", harness.state().hardness_merges); harness.state_mut().hardness = 0.75; harness.run_steps(1); type_at(&mut harness, hardness.center(), ".750"); + assert_eq!(harness.state().hardness, 0.75); assert!(harness.state().hardness_merges.is_empty(), "the same number written another way reports no edit: {:?}", harness.state().hardness_merges); } @@ -449,6 +457,7 @@ fn a_value_just_under_zero_opens_without_a_minus_sign() { harness.drag_at(hardness.center()); harness.drop_at(hardness.center()); harness.run_steps(2); + assert_eq!(harness.get_by_role(egui::Role::TextInput).value().as_deref(), Some("0.00")); } @@ -475,6 +484,7 @@ fn a_drag_merges_after_its_first_step_and_a_click_does_not() { assert!(drag_merges.len() >= 2, "the drag changes the value more than once: {drag_merges:?}"); assert_eq!(drag_merges.first(), Some(&false), "the drag's first change starts an undo step: {drag_merges:?}"); assert!(drag_merges.iter().skip(1).all(|merge| *merge), "later changes continue it: {drag_merges:?}"); + let merges = &harness.state().hardness_merges; assert_eq!(merges.len(), drag_merges.len() + 1, "the click changes the value once: {merges:?}"); assert_eq!(merges.last(), Some(&false), "the click starts its own undo step: {merges:?}"); @@ -635,6 +645,7 @@ fn a_fold_keeps_its_state_when_rows_above_it_come_and_go() { let at = harness.get_by_label("Edges").rect().center(); click_at(&mut harness, at); harness.run_steps(2); + assert!(harness.query_by_label("Edge rows").is_none()); *harness.state_mut() = false; @@ -667,6 +678,7 @@ fn the_next_picker_opens_in_the_colour_space_last_picked() { let at = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Linear").rect().center(); click_at(&mut harness, at); harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::ComboBox, "Linear").is_some(), "Bar B's picker shows Linear"); let at = harness.get_by_role_and_label(egui::Role::Button, "Close").rect().center(); @@ -697,6 +709,7 @@ fn a_color_bars_picker_stays_open_when_a_row_above_it_goes_away() { let at = harness.get_by_role_and_label(egui::Role::Button, "Tint").rect().center(); click_at(&mut harness, at); harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::TitleBar, "Tint").is_some(), "the picker opened"); *harness.state_mut() = false; @@ -726,6 +739,7 @@ fn a_fold_before_a_sections_first_band_keeps_its_state_when_the_band_above_goes_ let at = harness.get_by_label("Edges").rect().center(); click_at(&mut harness, at); harness.run_steps(2); + assert!(harness.query_by_label("Edge rows").is_none()); *harness.state_mut() = false; diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index a590761a..615ff4cc 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -218,7 +218,7 @@ fn placement(ctx: &egui::Context, strip: Rect, icon: Rect) -> (Pos2, f32) { fn closed_by_input(ctx: &egui::Context, shown: Option, strip: Rect) -> bool { let pressed_at = ctx.input(|input| input.pointer.press_origin().filter(|_| input.pointer.any_pressed())); - // A press on the rail is left to its icons, which switch or close the popup themselves; one in the popup's colour picker window stays in the popup + // The rail icons and colour picker handle their own presses let in_picker = |at: Pos2| crate::color_picker::open_window(ctx).is_some_and(|picker| picker.contains(at)); let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at)) && !in_picker(at)); outside && !egui::Popup::is_any_open(ctx) diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index d418eade..92a3b3fc 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -1,5 +1,6 @@ //! A popup hanging under a slot that picks a resource (a filter, a channel's source) from tiles under bright group headers, behind edge tabs and a search field +use egui::text_edit::TextEditState; use egui::{Align, Align2, Color32, CornerRadius, FontId, Frame, Id, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2}; use egui_phosphor::regular as ic; @@ -11,6 +12,8 @@ use crate::theme::{HARD_SHADOW, Tokens, semibold}; use crate::thumbs::Thumbs; use crate::tile_picture::TilePicture; +type PickerSearches = egui::cache::FramePublisher; + /// Columns of tiles in the grid const COLUMNS: usize = 4; /// One row of tiles: the picture, two lines of name and air @@ -84,10 +87,8 @@ pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { } egui::Popup::open_id(ctx, popup_id); - ctx.data_mut(|data| { - data.insert_temp(search_id(popup_id), String::new()); - data.insert_temp(opened_id(popup_id), true); - }); + ctx.memory_mut(|memory| memory.caches.cache::().set(popup_id, (String::new(), TextEditState::default()))); + ctx.data_mut(|data| data.insert_temp(opened_id(popup_id), true)); } /// Draws picker `popup_id` under `slot` (above it where the window ends first) at its width while open, on the tab holding `current` (scrolled to it when `reveal_current`, else at the top); returns the id clicked, and runs `tabs` only while open @@ -130,20 +131,22 @@ pub(crate) fn show( .show(|ui| { ui.set_width(width); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let just_opened = !ui.is_sizing_pass() && ui.data_mut(|data| data.remove_temp::(opened_id(popup_id))).unwrap_or(false); let current_tab = || current.and_then(|current| tabs.iter().position(|tab| tab.items().any(|item| &item.id == current))); let stored_tab = ui.data(|data| data.get_temp::(tab_id(popup_id))); let mut open_tab = if just_opened { current_tab().or(stored_tab) } else { stored_tab.or_else(current_tab) }.unwrap_or(0).min(tabs.len().saturating_sub(1)); - let query = search_query(&ui.data(|data| data.get_temp::(search_id(popup_id))).unwrap_or_default()); + let (search, editor) = ui.memory_mut(|memory| memory.caches.cache::().get(&popup_id).cloned()).unwrap_or_default(); if tabs.len() > 1 - && let Some(clicked) = tab_strip(ui, &tabs, open_tab, &query) + && let Some(clicked) = tab_strip(ui, &tabs, open_tab, &search_query(&search)) { open_tab = clicked; } + ui.data_mut(|data| data.insert_temp(tab_id(popup_id), open_tab)); - let query = search_field(ui, popup_id, just_opened); + let query = search_field(ui, popup_id, just_opened, search, editor); if let Some(tab) = tabs.get(open_tab) { let reveal = just_opened && reveal_current; @@ -153,6 +156,7 @@ pub(crate) fn show( if just_opened && !reveal { scroll = scroll.vertical_scroll_offset(0.0); } + scroll.show(ui, |ui| { // A search that leaves few tiles must not shrink the popup, or egui moves it ui.set_min_height(grid_height); @@ -165,6 +169,7 @@ pub(crate) fn show( if picked.is_some() { egui::Popup::close_id(&ctx, popup_id); } + picked } @@ -219,9 +224,8 @@ fn tab_strip(ui: &mut Ui, tabs: &[PickerTab], open: usize, query: &str) -> } /// The neutral search field (no accent outline, focused or not), focused the frame the picker opens, × clearing it; returns the lowercase query -fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { +fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool, mut search: String, editor: TextEditState) -> String { let tokens = Tokens::get(ui.ctx()); - let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), SEARCH_ROW), Sense::hover()); let field = Rect::from_center_size(row.center(), vec2(row.width() - 2.0 * SIDE, FIELD_HEIGHT)); let painter = ui.painter(); @@ -236,7 +240,11 @@ fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { let text_rect = Rect::from_min_max(pos2(field.left() + SEARCH_TEXT_X, field.top()), pos2(field.right() - 2.0 * CLEAR_X, field.bottom())); let hint = egui::RichText::new(tr("Search")).color(tokens.text_dim).size(SEARCH_TEXT_SIZE); + let field_id = popup_id.with("search_field"); + editor.store(ui.ctx(), field_id); + let edit = egui::TextEdit::singleline(&mut search) + .id(field_id) .frame(Frame::NONE) .hint_text(hint) .font(semibold(SEARCH_TEXT_SIZE)) @@ -261,7 +269,12 @@ fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { } let query = search_query(&search); - ui.data_mut(|data| data.insert_temp(search_id(popup_id), search)); + let state = TextEditState::load(ui.ctx(), field_id).unwrap_or_default(); + + // Keep the text and undo history only while the picker is drawn + ui.data_mut(|data| data.remove::(field_id)); + ui.memory_mut(|memory| memory.caches.cache::().set(popup_id, (search, state))); + query } @@ -272,9 +285,11 @@ fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tab: &PickerTab< let cell = (ui.available_width() - SIDE - SCROLL_ROOM) / COLUMNS as f32; let mut picked = None; let mut place = 0; + let mut row = Vec::new(); + for group in &tab.groups { - let shown: Vec<&ResourcePickerItem> = group.items.iter().filter(|item| item.matches(query)).collect(); - if shown.is_empty() { + let mut matching_items = group.items.iter().filter(|item| item.matches(query)).peekable(); + if matching_items.peek().is_none() { continue; } @@ -282,10 +297,10 @@ fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tab: &PickerTab< if let Some(header) = group.header { caption_row(ui, left, HEADER_HEIGHT, header, semibold(HEADER_SIZE), tokens.text); } + let mut caption_top = group_top; - let mut row: Vec<(usize, &ResourcePickerItem)> = Vec::new(); let mut last_caption = None; - for (index, item) in shown.iter().enumerate() { + for item in matching_items { if item.caption != last_caption { flush_row(ui, thumbs, &mut row, left, cell, current, &mut picked); if let Some(caption) = item.caption { @@ -294,6 +309,7 @@ fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tab: &PickerTab< } last_caption = item.caption; } + row.push((place, item)); place += 1; if let Some(grid_height) = reveal_in @@ -305,10 +321,11 @@ fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tab: &PickerTab< let from = if row_top + ROW_HEIGHT - label_top <= grid_height { label_top } else { row_top }; ui.scroll_to_rect(Rect::from_min_max(pos2(left, from), pos2(left + cell, row_top + ROW_HEIGHT)), Some(Align::TOP)); } - if row.len() == COLUMNS || index + 1 == shown.len() { + if row.len() == COLUMNS { flush_row(ui, thumbs, &mut row, left, cell, current, &mut picked); } } + flush_row(ui, thumbs, &mut row, left, cell, current, &mut picked); } picked @@ -439,11 +456,6 @@ fn name_lines(ui: &Ui, rect: Rect, label: &str, bright: bool, bold: bool) { } } -/// 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 opened_id(popup_id: Id) -> Id { popup_id.with("opened") diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index 94a73684..d0497fdf 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -827,15 +827,19 @@ pub(crate) mod tests { harness.run_steps(25); harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); harness.run_steps(2); + assert!(crate::color_picker::open_window(&harness.ctx).is_some(), "the picker is open"); + let steps = harness.state().session.history_labels().len(); drag(&mut harness, from, from + vec2(40.0, 0.0), Modifiers::NONE); + assert!(crate::color_picker::open_window(&harness.ctx).is_none(), "the press closed the picker"); assert_eq!(projection(&harness, layer), before, "and slid nothing"); assert_eq!(harness.state().session.history_labels().len(), steps, "nor made an undo step"); drag(&mut harness, from, from + vec2(40.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "the next press slides again"); } diff --git a/crates/ui-egui/src/screen_pick/cursor_image.rs b/crates/ui-egui/src/screen_pick/cursor_image.rs index 06eed9a8..d1d33782 100644 --- a/crates/ui-egui/src/screen_pick/cursor_image.rs +++ b/crates/ui-egui/src/screen_pick/cursor_image.rs @@ -186,6 +186,7 @@ mod tests { assert!(image.alpha(hx, hy).is_some_and(|alpha| alpha >= INK_ALPHA), "{size}: the hotspot pixel is ink"); assert!(hx < size / 4 && hy >= size * 3 / 4, "{size}: the tip is at the bottom left: {:?}", image.hotspot); + for y in 0..size { for x in 0..size { let ink = image.alpha(x, y).is_some_and(|alpha| alpha >= INK_ALPHA); @@ -204,6 +205,7 @@ mod tests { let [bulb_x, bulb_y] = pipette::square(0.85, 0.0).map(|edge| (edge * 20.0) as u32); assert_eq!(pixel(bulb_x, bulb_y + 12), Some(vec![255, 255, 255, 255]), "the bulb is white"); assert_eq!(pixel(31, 31).and_then(|pixel| pixel.get(3).copied()), Some(0), "the bottom-right corner is clear"); + let [hx, hy] = image.hotspot; assert!(pixel(hx, hy).and_then(|pixel| pixel.first().copied()).is_some_and(|grey| grey < 128), "the tip's edge is the dark outline"); assert_eq!(CursorImage::eyedropper(0).size, 8, "a degenerate size is clamped"); @@ -244,6 +246,7 @@ mod tests { assert!(grey(tube).is_some_and(|grey| grey < 64), "the tube's inside is dark, as the glyph leaves it clear"); assert!(image.alpha(at(tube).1, at(tube).0).is_some_and(|alpha| alpha == u8::MAX), "and still opaque, so the pointer reads"); assert_eq!(grey(pipette::square(0.85, 0.0)), Some(u8::MAX), "the bulb is white"); + for (index, coverage) in glyph.iter().enumerate() { let (row, column) = (index as u32 / glyph_px + top, index as u32 % glyph_px); let alpha = image.alpha(column, row).unwrap_or(0); @@ -260,6 +263,7 @@ mod tests { assert_eq!([word(2), word(4)], [Some(CUR_TYPE), Some(1)], "one cursor picture"); assert_eq!([word(10), word(12)], [Some(image.hotspot[0] as u16), Some(image.hotspot[1] as u16)], "the hotspot is the tip"); assert_eq!(file.len(), (CUR_HEADER_BYTES + BITMAP_HEADER_BYTES) as usize + 32 * 32 * 4 + 4 * 32, "header, bitmap header, colour rows and mask rows"); + let [hx, hy] = image.hotspot; let bottom_up_row = (31 - hy) as usize; let alpha = file.get((CUR_HEADER_BYTES + BITMAP_HEADER_BYTES) as usize + (bottom_up_row * 32 + hx as usize) * 4 + 3).copied(); diff --git a/crates/ui-egui/src/screen_pick/live_swatch.rs b/crates/ui-egui/src/screen_pick/live_swatch.rs index 8d03b410..08bfda57 100644 --- a/crates/ui-egui/src/screen_pick/live_swatch.rs +++ b/crates/ui-egui/src/screen_pick/live_swatch.rs @@ -38,6 +38,7 @@ impl LiveSwatch { /// Shows the colour under the tip in the pointer's disc, while the pointer is off the app (the app draws its own there) fn refresh(&mut self, shared: &PickShared) { let Ok(point) = winsafe::GetCursorPos() else { return }; + if over_own_window(point) || over_windows(&shared.windows(), point.x, point.y) { return; } diff --git a/crates/ui-egui/src/screen_pick/pick_shared.rs b/crates/ui-egui/src/screen_pick/pick_shared.rs index 9fa7a692..3359577f 100644 --- a/crates/ui-egui/src/screen_pick/pick_shared.rs +++ b/crates/ui-egui/src/screen_pick/pick_shared.rs @@ -1,5 +1,7 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(all(unix, not(target_os = "macos")))] +use std::task::Waker; /// What the frame loop tells the thread that waits for a click outside the app #[derive(Default)] @@ -11,11 +13,17 @@ pub(crate) struct PickShared { /// The pointer is over none of the app's windows #[cfg(all(unix, not(target_os = "macos")))] pointer_outside: AtomicBool, + #[cfg(all(unix, not(target_os = "macos")))] + portal_waker: Mutex>, } impl PickShared { pub(crate) fn stop(&self) { self.stop.store(true, Ordering::Relaxed); + #[cfg(all(unix, not(target_os = "macos")))] + if let Some(waker) = self.take_portal_waker() { + waker.wake(); + } } #[cfg(any(windows, all(unix, not(target_os = "macos"))))] @@ -44,6 +52,25 @@ impl PickShared { pub(crate) fn pointer_outside(&self) -> bool { self.pointer_outside.load(Ordering::Relaxed) } + + #[cfg(all(unix, not(target_os = "macos")))] + pub(super) fn watch_portal_stop(&self, waker: &Waker) -> bool { + let mut waiting = self.portal_waker.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if self.stopped() { + return true; + } + + if waiting.as_ref().is_none_or(|registered| !registered.will_wake(waker)) { + *waiting = Some(waker.clone()); + } + + false + } + + #[cfg(all(unix, not(target_os = "macos")))] + pub(super) fn take_portal_waker(&self) -> Option { + self.portal_waker.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take() + } } /// Whether the screen pixel `(x, y)` lies on one of `windows` diff --git a/crates/ui-egui/src/screen_pick/portal.rs b/crates/ui-egui/src/screen_pick/portal.rs index adecf393..104c983b 100644 --- a/crates/ui-egui/src/screen_pick/portal.rs +++ b/crates/ui-egui/src/screen_pick/portal.rs @@ -2,19 +2,27 @@ //! desktop's own colour picker (the xdg-desktop-portal Screenshot.PickColor call) takes the click and reports the colour use std::collections::HashMap; -use std::sync::Arc; +use std::future::{Future, poll_fn}; +use std::pin::{Pin, pin}; use std::sync::mpsc::Sender; +use std::task::Poll; use std::time::Duration; -use zbus::blocking::{Connection, Proxy}; +use zbus::AsyncDrop; +use zbus::blocking::{Proxy, connection::Builder}; +use zbus::export::futures_core::Stream; use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; use super::{PickOutcome, PickShared}; /// How often the thread checks whether the pointer has left the app -const POLL: Duration = Duration::from_millis(30); +const POINTER_POLL_INTERVAL: Duration = Duration::from_millis(30); +/// Bound portal method replies without timing out the user's interaction +const METHOD_REPLY_TIMEOUT: Duration = Duration::from_secs(5); + const PORTAL: &str = "org.freedesktop.portal.Desktop"; const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; +const REQUEST_INTERFACE: &str = "org.freedesktop.portal.Request"; /// The token that names this app's request, so its answer can be awaited before the call is made const TOKEN: &str = "texturecraft_eyedropper"; /// The portal's answer code for a pick the user made @@ -23,37 +31,60 @@ const RESPONSE_SUCCESS: u32 = 0; const RESPONSE_CANCELLED: u32 = 1; /// Waits for the pointer to leave the app's windows, then lets the desktop's picker take one click -pub(super) fn run(shared: &Arc, outcomes: &Sender, ctx: &egui::Context) { +pub(super) fn run(shared: &PickShared, outcomes: &Sender, ctx: &egui::Context) { while !shared.pointer_outside() { if shared.stopped() { return; } - std::thread::sleep(POLL); + std::thread::sleep(POINTER_POLL_INTERVAL); } - // The pick may have ended in the same poll the pointer left: no desktop picker for it + // The pick can end in the poll that sees the pointer leave + if shared.stopped() { + return; + } + + let outcome = pick_color(shared).unwrap_or(PickOutcome::Unavailable); if shared.stopped() { return; } - let outcome = pick_color().unwrap_or(PickOutcome::Unavailable); let _ = outcomes.send(outcome); ctx.request_repaint(); } -fn pick_color() -> Option { - let connection = Connection::session().ok()?; +fn pick_color(shared: &PickShared) -> Option { + let connection = Builder::session().ok()?.method_timeout(METHOD_REPLY_TIMEOUT).build().ok()?; let sender = connection.unique_name()?.trim_start_matches(':').replace('.', "_"); let request_path = format!("{PORTAL_PATH}/request/{sender}/{TOKEN}"); - let request = Proxy::new(&connection, PORTAL, request_path, "org.freedesktop.portal.Request").ok()?; - let mut responses = request.receive_signal("Response").ok()?; - + let request = Proxy::new(&connection, PORTAL, request_path, REQUEST_INTERFACE).ok()?; let screenshot = Proxy::new(&connection, PORTAL, PORTAL_PATH, "org.freedesktop.portal.Screenshot").ok()?; - let options = HashMap::from([("handle_token", Value::from(TOKEN))]); - let _handle: OwnedObjectPath = screenshot.call("PickColor", &("", options)).ok()?; + let mut responses = zbus::block_on(request.inner().receive_signal("Response")).ok()?; - let answer = responses.next()?; + let Some(handle) = request_handle(&screenshot, &request, shared) else { + zbus::block_on(responses.async_drop()); + return None; + }; + + let answer = zbus::block_on(poll_fn(|context| { + if shared.watch_portal_stop(context.waker()) { + return Poll::Ready(None); + } + + Pin::new(&mut responses).poll_next(context) + })); + drop(shared.take_portal_waker()); + + // A closed request does not send a response of its own + if shared.stopped() + && let Ok(active_request) = Proxy::new(&connection, PORTAL, handle.as_str(), REQUEST_INTERFACE) + { + let _ = active_request.call_noreply("Close", &()); + } + + zbus::block_on(responses.async_drop()); + let answer = answer?; let (code, results): (u32, HashMap) = answer.body().deserialize().ok()?; if let Some(ended) = ended_without_colour(code) { return Some(ended); @@ -63,6 +94,35 @@ fn pick_color() -> Option { Some(PickOutcome::Picked([red, green, blue].map(to_byte))) } +/// Start the pick, closing the predicted request if the UI cancels before the method replies +fn request_handle(screenshot: &Proxy<'_>, request: &Proxy<'_>, shared: &PickShared) -> Option { + let arguments = ("", HashMap::from([("handle_token", Value::from(TOKEN))])); + let mut pending = pin!(screenshot.inner().call("PickColor", &arguments)); + let mut polled = false; + let reply = zbus::block_on(poll_fn(|context| { + if shared.watch_portal_stop(context.waker()) { + return Poll::Ready(None); + } + + polled = true; + pending.as_mut().poll(context).map(Some) + })); + drop(shared.take_portal_waker()); + + match reply { + Some(result) => result.ok(), + None if !polled => None, + None => { + if request.call::<_, _, ()>("Close", &()).is_ok() { + return None; + } + + // Some portals export the request late, so use the returned handle if early Close fails + zbus::block_on(pending).ok() + } + } +} + /// How a portal answer of `code` ends the pick when it brings no colour: a cancel ends it, a failure leaves the pick on the model fn ended_without_colour(code: u32) -> Option { match code { diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index ecfa8b14..9014c9a3 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -183,6 +183,7 @@ impl Thumbs { if self.received_in_pass == pass { return; } + self.received_in_pass = pass; for (key, image) in self.worker.poll() { @@ -440,6 +441,7 @@ mod tests { let old_preview = thumbs.saved_brush_preview(&path, &images); assert!(thumbs.big(&ctx, old_preview, 8).is_none()); + images.insert("alpha.png".into(), image(0.8)); let current_preview = thumbs.saved_brush_preview(&path, &images); assert!(thumbs.big(&ctx, current_preview.clone(), 8).is_none()); @@ -451,6 +453,7 @@ mod tests { let mut output = ctx.run_pass(Default::default(), |_| {}); output.textures_delta.clear(); + assert!(thumbs.rendered_big(&ctx, ¤t_preview, 8).is_some(), "the current completion must survive an old failure"); } @@ -537,6 +540,7 @@ mod tests { drop(thumbs.saved_brush_preview(&second_path, &images)); drop(old_image); drop(other_image); + assert!(old_weak.upgrade().is_none(), "cached settings do not retain a replaced image"); assert!(other_weak.upgrade().is_some(), "the project still owns its current image"); eprintln!( @@ -547,10 +551,12 @@ mod tests { let replacement = Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[0.0; 4]; IMAGE_TEXELS], false)); images.insert("alpha.png".into(), replacement); drop(thumbs.saved_brush_preview(&first_path, &images)); + assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image"); eprintln!("saved brush cache after second replacement: 0 of {IMAGE_BYTES} previous image bytes retained"); thumbs.forget_saved_files(); + assert!(thumbs.saved_brush_previews.is_empty(), "refresh releases parsed brush settings"); } @@ -598,6 +604,7 @@ mod tests { images.insert("image-3".into(), Arc::new(ImageRes::new(2, 2, vec![[0.7; 4]; 4], false))); drop(thumbs.image(&context, "image-3", &images["image-3"])); thumbs.sync_images(&images, 2); + assert_eq!(thumbs.images.len(), 2); images.clear(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 0ac74f2e..13bf3900 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2640,11 +2640,13 @@ mod tests { harness.state_mut().picking_color = Some(bar); click(&mut harness, on_the_uvs); + assert_eq!(harness.state().session.history_labels().len(), steps, "the click painted nothing"); assert_eq!(harness.state().picking_color, Some(bar), "the eyedropper still waits"); harness.state_mut().picking_color = None; click(&mut harness, on_the_uvs); + assert_eq!(harness.state().session.undo_label(), Some("Polygon fill"), "without a pick the same click paints"); } diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 7185890e..21a5f5a7 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -168,9 +168,11 @@ fn a_waiting_eyedropper_hides_the_2d_brush_outline() { let pointer = egui::pos2(800.0, 480.0); harness.hover_at(pointer); harness.run_steps(3); + assert!(rings_at(&harness, pointer).is_empty(), "no brush outline under the eyedropper (its own pointer is drawn instead)"); harness.state_mut().picking_color = None; harness.run_steps(3); + assert_eq!(rings_at(&harness, pointer).len(), 1, "without a pick the outline is back"); } diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index 5dc4b43d..bd7222b8 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -89,6 +89,7 @@ fn switching_projects_releases_image_previews_with_equal_revisions() { // Freshly loaded projects can have equal revisions despite different resources assert_eq!(loaded.revision, 1); + session.switch_to(loaded); thumbnails.sync_images(&session.images, session.revision); let image = &session.images[&name]; diff --git a/crates/ui-egui/tests/it/fill_material_rows.rs b/crates/ui-egui/tests/it/fill_material_rows.rs index 0e20a2df..98333f42 100644 --- a/crates/ui-egui/tests/it/fill_material_rows.rs +++ b/crates/ui-egui/tests/it/fill_material_rows.rs @@ -81,10 +81,12 @@ fn the_channel_strip_turns_a_channel_and_its_card_off_and_on() { click(&mut harness, Role::CheckBox, "Metal"); let channels = &harness.state().session.doc.project.layer(layer).unwrap().channels; + assert!(!channels.contains_key(&Channel::Metallic), "off in the strip, the fill stops writing Metallic"); assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "a channel that is off has no card"); click(&mut harness, Role::CheckBox, "Metal"); + assert!(harness.state().session.doc.project.layer(layer).unwrap().channels.contains_key(&Channel::Metallic)); assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some()); } @@ -110,6 +112,7 @@ fn a_slot_lists_its_sources_restores_a_procedural_and_clears_back_to_uniform() { assert_eq!(pattern, Procedural::new(ProceduralKind::Clouds), "⟲ keeps the pattern and restores its settings"); click_in_slot(&mut harness, "Metallic", Role::Button, "Clear"); + assert_eq!(source(&harness, layer, Channel::Metallic), Source::uniform_of(Channel::Metallic), "× goes back to a uniform value"); } @@ -167,12 +170,15 @@ fn source_picker_images_render_on_scroll_and_release_on_removal() { harness.run_steps(THUMBNAIL_FRAMES); let scrolled = image_thumbnails(&harness); assert!(scrolled > opened, "a scroll makes the thumbnails of the tiles it brings into view: {opened} -> {scrolled}"); + click(&mut harness, Role::ListBoxOption, &last); + assert_eq!(source(&harness, layer, Channel::Metallic), Source::image(last)); let app = harness.state_mut(); app.session.images.clear(); app.thumbs.sync_images(&app.session.images, app.session.revision + 1); + assert_eq!(image_thumbnails(&harness), 0, "removed images release their picker thumbnails"); } @@ -220,11 +226,13 @@ fn a_linked_material_shows_its_inputs_and_the_switch_shows_its_channels() { let wear = float_param("wear", "Wear", 0.5); link_fill(&mut harness, layer, vec![wear], &[]); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Painted steel").is_some(), "the Material side shows the whole material"); assert!(harness.query_by_role_and_label(Role::Slider, "Wear").is_some(), "with its inputs"); assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "and no channel cards"); click(&mut harness, Role::RadioButton, "Channels"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "the Channels side shows a card per channel"); assert!(harness.query_by_role_and_label(Role::Slider, "Wear").is_none()); } @@ -259,11 +267,13 @@ fn a_linked_whole_number_input_changes_only_on_a_new_whole_number() { // A link without a package fails to re-cook with a toast: no toast, no cook click_at(&mut harness, along(track, 0.32)); harness.run_steps(SETTLE_FRAMES); + assert_eq!(undo_depth(&harness), steps, "3.2 rounds to the 3 the input holds: no undo step"); assert!(harness.state().toasts.is_empty(), "and no re-cook"); drag(&mut harness, along(track, 0.3), along(track, 0.53)); harness.run_steps(SETTLE_FRAMES); + assert_eq!(fill_of(&harness, layer).link.unwrap().params[0].value, json!({"t": "int", "v": 5}), "the drag ends on 5"); assert_eq!(undo_depth(&harness), steps + 1, "the drag's whole numbers merge into one step"); } @@ -313,18 +323,25 @@ fn a_linked_material_maps_its_channels_and_picks_its_resolution() { // Channels mapping: the Roughness row lists the outputs; picking one makes Roughness read it click_below(&mut harness, Role::ComboBox, "roughness"); click(&mut harness, Role::ListBoxOption, "baseColor"); + assert_eq!(link(&harness).output_of(Channel::Roughness), "baseColor"); assert!(matches!(source(&harness, layer, Channel::Roughness), Source::Image { name, .. } if name == "steel_base.png")); // Resolution: folded until clicked; Fixed keeps the size, the list picks another, Relative goes back to a factor assert!(harness.query_by_role_and_label(Role::RadioButton, "Fixed").is_none(), "Resolution starts folded"); + click_below(&mut harness, Role::Button, "Resolution"); click_below(&mut harness, Role::RadioButton, "Fixed"); + assert_eq!(link(&harness).resolution, Some(CookResolution::Fixed(TEXTURE_RESOLUTION))); + click_below(&mut harness, Role::ComboBox, "256 × 256"); click(&mut harness, Role::ListBoxOption, "1024 × 1024"); + assert_eq!(link(&harness).resolution, Some(CookResolution::Fixed(1024))); + click_below(&mut harness, Role::RadioButton, "Relative"); + assert_eq!(link(&harness).resolution, Some(CookResolution::Relative(2)), "1024 is the texture set's ×4"); } @@ -374,6 +391,7 @@ fn the_colour_bar_opens_the_picker_which_types_restores_and_waits_for_an_eyedrop let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); let before = base_color(&harness, layer); click(&mut harness, Role::Button, "Base color"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "the picker shows its colour space"); type_hex(&mut harness, "FF8000"); @@ -383,6 +401,7 @@ fn the_colour_bar_opens_the_picker_which_types_restores_and_waits_for_an_eyedrop click(&mut harness, Role::ComboBox, "HSV"); click(&mut harness, Role::ListBoxOption, "RGB"); + assert!(harness.query_by_role_and_label(Role::Slider, "R").is_some(), "the sliders edit R, G and B"); assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "picking from its own list keeps the picker open"); @@ -392,6 +411,7 @@ fn the_colour_bar_opens_the_picker_which_types_restores_and_waits_for_an_eyedrop click_picker_eyedropper(&mut harness); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model"); } @@ -427,13 +447,16 @@ fn the_picker_is_a_window_beside_the_panel_that_its_title_drags_and_its_close_or .unwrap() .rect(); click_at(&mut harness, close.center()); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "× closes it"); click(&mut harness, Role::Button, "Base color"); let reopened = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); assert!((reopened.min - moved.min).length() < 1.0, "it opens again where it was dragged: {reopened:?}"); + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "Escape closes it"); } @@ -443,10 +466,12 @@ fn escape_ends_an_eyedropper_pick_before_the_picker_and_an_alt_orbit_keeps_the_p click(&mut harness, Role::Button, "Base color"); click_bar_eyedropper(&mut harness); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model"); harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_none(), "Escape ends the pick"); assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the same Escape leaves the picker open"); @@ -461,10 +486,12 @@ fn escape_ends_an_eyedropper_pick_before_the_picker_and_an_alt_orbit_keeps_the_p harness.event(egui::Event::PointerButton { pos: view + egui::vec2(40.0, 10.0), button: egui::PointerButton::Primary, pressed: false, modifiers: alt }); harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "an Alt+drag on the model orbits and keeps the picker open"); harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the next Escape closes the picker"); } @@ -491,26 +518,35 @@ fn the_swatches_row_keeps_the_picker_colour_in_the_project_applies_it_on_a_click let add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect(); let space = harness.get_by_role_and_label(Role::ComboBox, "sRGB").rect(); assert!(add.top() > space.bottom() && (add.left() - space.left()).abs() < 1.0, "the row is under the picker, at its left edge: {add:?}"); + click_at(&mut harness, add.center()); + assert_eq!(harness.state().session.doc.project.swatches, vec![orange], "+ keeps the picker's colour in the project"); assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "the picker stays open"); + let depth = undo_depth(&harness); let kept = harness.get_by_role_and_label(Role::Button, "#FF8000").rect(); click_at(&mut harness, kept.center()); + assert_eq!(undo_depth(&harness), depth, "a swatch the picker already shows changes nothing"); click(&mut harness, Role::Button, "Previous color"); + assert_eq!(base_color(&harness, layer), before); + let chip = harness.get_by_role_and_label(Role::Button, "#FF8000").rect(); let moved_add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect(); assert!((chip.left() - add.left()).abs() < 1.0 && moved_add.left() > chip.right(), "the swatch takes the + chip's place, + moves right"); + click_at(&mut harness, chip.center()); + assert_eq!(base_color(&harness, layer), orange, "a click on a swatch applies it"); assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "applying keeps the picker open"); right_click(&mut harness, chip.center()); let remove = harness.get_by_role_and_label(Role::Button, "Remove swatch").rect(); click_at(&mut harness, remove.center()); + assert!(harness.state().session.doc.project.swatches.is_empty(), "its right-click menu removes it"); assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a pick in the menu keeps the picker open"); } @@ -523,6 +559,7 @@ fn a_hex_code_left_as_it_opened_is_no_edit() { click(&mut harness, Role::TextInput, "Hex color"); harness.key_press(egui::Key::Enter); harness.run_steps(SETTLE_FRAMES); + assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "the colour is not rounded to the code it shows"); assert_eq!(undo_depth(&harness), depth, "no undo step"); } @@ -555,6 +592,7 @@ fn a_hex_code_half_typed_when_a_press_closes_the_picker_is_gone_when_it_opens_ag harness.run_steps(1); let view = harness.state().viewport_rect.center(); click_at(&mut harness, view); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the press closes the picker"); assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "closing applies nothing"); @@ -563,6 +601,7 @@ fn a_hex_code_half_typed_when_a_press_closes_the_picker_is_gone_when_it_opens_ag click(&mut harness, Role::TextInput, "Hex color"); harness.key_press(egui::Key::Enter); harness.run_steps(SETTLE_FRAMES); + assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "the field shows the colour's own code, not the text typed before"); assert_eq!(undo_depth(&harness), depth, "no undo step"); } @@ -587,6 +626,7 @@ const FIELD_MIN_HEIGHT: f32 = 100.0; fn the_picker_is_titled_by_its_channel_resizes_from_its_edges_keeps_its_size_and_previews_nothing_on_hover() { let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); click(&mut harness, Role::Button, "Base color"); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the title is the channel's name alone"); let face = picker_face(&harness); @@ -596,10 +636,13 @@ fn the_picker_is_titled_by_its_channel_resizes_from_its_edges_keeps_its_size_and let by = egui::vec2(80.0, 60.0); let corner = face.right_bottom() - egui::vec2(2.0, 2.0); drag(&mut harness, corner, corner + by); + assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a resize keeps the picker open"); + let grown = picker_face(&harness); assert!((grown.min - face.min).length() < 1.0, "the bottom right corner leaves the top left where it was: {grown:?} {face:?}"); assert!((grown.size() - (face.size() + by)).length() < 1.0, "the corner drags the size: {grown:?} from {face:?}"); + let grown_field = harness.get_by_role_and_label(Role::Slider, "Saturation and value").rect(); let grown_hue = harness.get_by_role_and_label(Role::Slider, "Hue").rect(); let grown_track = harness.get_by_role_and_label(Role::Slider, "S").rect(); @@ -630,17 +673,23 @@ fn the_picker_is_titled_by_its_channel_resizes_from_its_edges_keeps_its_size_and let value = |harness: &Harness<'_, TextureCraftApp>| harness.get_by_role_and_label(Role::Slider, "V").accesskit_node().numeric_value(); let shown = value(&harness); assert!(shown.is_some(), "the V slider says its value"); + click(&mut harness, Role::ComboBox, "sRGB"); harness.get_by_role_and_label(Role::ListBoxOption, "Linear").hover(); harness.run_steps(SETTLE_FRAMES); + assert_eq!(value(&harness), shown, "a hovered colour space changes nothing"); + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); click(&mut harness, Role::ComboBox, "HSV"); harness.get_by_role_and_label(Role::ListBoxOption, "RGB").hover(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::Slider, "R").is_none(), "a hovered model changes nothing"); + click(&mut harness, Role::ListBoxOption, "RGB"); + assert!(harness.query_by_role_and_label(Role::Slider, "R").is_some(), "a click picks it"); } @@ -655,7 +704,9 @@ fn a_plain_fill_switches_to_one_whole_material_picks_it_from_its_card_and_clears assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "a plain fill opens on Channels: a card per channel"); click_node(&mut harness, Role::RadioButton, "Material"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "the Material side has no channel cards"); + click_node(&mut harness, Role::ComboBox, "None"); // The card opens the material picker, not a list: unfiltered it offers the plain materials but no smart ones @@ -665,18 +716,23 @@ fn a_plain_fill_switches_to_one_whole_material_picks_it_from_its_card_and_clears // Its search keeps only the materials it names harness.event(egui::Event::Text("hammered".into())); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Steel").is_none(), "searching hides what it doesn't name"); + click_node(&mut harness, Role::ListBoxOption, "Copper Hammered"); + assert_eq!(whole_material(&harness, layer).as_deref(), Some("copper_hammered"), "the picker sets the whole material"); assert!(harness.query_by_role_and_label(Role::ComboBox, "Copper Hammered").is_some(), "the card names it"); assert!(harness.query_by_role(Role::ListBoxOption).is_none(), "the picker closed on the pick"); click_node(&mut harness, Role::RadioButton, "Channels"); + assert!(matches!(source(&harness, layer, Channel::BaseColor), Source::Procedural { .. }), "the material set every channel"); assert!(harness.query_by_role_and_label(Role::ComboBox, "Height").is_some(), "its channels show as cards"); click_node(&mut harness, Role::RadioButton, "Material"); click_in_slot(&mut harness, "Copper Hammered", Role::Button, "Clear"); + assert_eq!(whole_material(&harness, layer), None, "× drops the material"); assert_eq!(source(&harness, layer, Channel::BaseColor), Source::uniform_of(Channel::BaseColor), "and returns the channels to their defaults"); } @@ -694,17 +750,22 @@ fn pick_outside(harness: &mut Harness<'_, TextureCraftApp>, outcome: PickOutcome fn a_click_outside_the_app_hands_its_screen_colour_to_the_bar_and_a_cancelled_or_impossible_one_changes_nothing() { let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]})); assert!(!harness.state().screen_picking, "tests have no real window: no system hook or grab"); + let before = base_color(&harness, layer); click(&mut harness, Role::Button, "Base color"); pick_outside(&mut harness, PickOutcome::Unavailable); + assert!(harness.state().picking_color.is_some(), "where the system cannot read the screen the pick stays on the model"); assert_eq!(base_color(&harness, layer), before, "nothing changes until a click"); + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "Escape ends the pick and its wait"); pick_outside(&mut harness, PickOutcome::Cancelled); + assert!(harness.state().picking_color.is_none(), "dismissing the desktop's picker ends the pick"); assert_eq!(base_color(&harness, layer), before, "a cancelled pick changes nothing"); @@ -733,9 +794,12 @@ fn an_armed_eyedropper_is_the_pointer_over_the_whole_window_and_the_app_losing_t harness.state_mut().screen_pick = Some(ScreenPick::waiting(bar)); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_some(), "a focused app keeps waiting"); + harness.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().focused = Some(false); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "another app came forward: the pick ends"); assert_eq!(base_color(&harness, layer), before, "nothing changes"); assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::None, "the pointer is the user's again"); @@ -752,11 +816,13 @@ fn escape_in_the_hex_field_ends_the_typing_and_a_second_escape_closes_the_picker harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the first Escape only ends the typing"); assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "and applies nothing"); harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the next Escape closes the picker"); } @@ -772,6 +838,7 @@ fn a_hex_code_left_as_it_opened_keeps_a_colour_set_meanwhile() { let depth = undo_depth(&harness); harness.key_press(egui::Key::Enter); harness.run_steps(SETTLE_FRAMES); + assert_eq!(base_color(&harness, layer), [0.0, 0.0, 1.0], "the untouched code is not written back"); assert_eq!(undo_depth(&harness), depth, "no undo step"); } @@ -786,6 +853,7 @@ fn a_swatch_menu_left_open_while_the_list_changes_never_removes_another_swatch() click(&mut harness, Role::Button, "Base color"); let green_chip = harness.get_by_role_and_label(Role::Button, "#00FF00").rect(); right_click(&mut harness, green_chip.center()); + assert!(harness.query_by_role_and_label(Role::Button, "Remove swatch").is_some(), "the green swatch's menu is open"); // An agent removes the first swatch: green moves to its place, blue to green's diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 90f4c1d8..02416390 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -413,6 +413,7 @@ fn alt_click_on_the_content_thumbnail_leaves_the_view_alone() { let (mut h, _) = harness(); let at = thumb(&h, "Masked fill", false); alt_click(&mut h, at); + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material); } diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 930e3365..1ebbd850 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -221,6 +221,7 @@ fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_pane let material = harness.get_all_by_role_and_label(Role::Tab, "Material").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); click(&mut harness, PointerButton::Primary, material); harness.run_steps(JUMP_FRAMES); + assert!(is_open(&harness), "a tab click keeps it open"); assert!(!in_popup(&harness, "UV projection"), "the list jumped down to MATERIAL"); assert!(tab_lit(&harness, popup, "Material"), "the section in view is lit"); @@ -248,6 +249,7 @@ fn the_colour_picker_opened_in_the_popup_takes_its_presses_and_the_first_escape( harness.run_steps(SETTLE_FRAMES); let center = view_center(&harness); click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); @@ -260,15 +262,19 @@ fn the_colour_picker_opened_in_the_popup_takes_its_presses_and_the_first_escape( let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); click(&mut harness, PointerButton::Primary, title.center()); + assert!(is_open(&harness), "a press in the picker window stays in the popup"); assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "and keeps the picker open"); harness.key_press(Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the first Escape closes the picker"); assert!(is_open(&harness), "and leaves the popup open"); + harness.key_press(Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(!is_open(&harness), "the next Escape closes the popup"); } @@ -286,11 +292,13 @@ fn an_eyedropper_pick_from_the_popup_keeps_the_popup_open_for_its_colour() { harness.run_steps(SCROLL_FRAMES); let button = harness.get_all_by_role_and_label(Role::Button, "Pick color").find(|node| in_popup(node.rect())).unwrap().rect(); click(&mut harness, PointerButton::Primary, button.center()); + assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model"); // The model's middle, left of the popup let model = egui::pos2(popup.left() - MODEL_LEFT_OF_POPUP, center.y); click(&mut harness, PointerButton::Primary, model); + assert!(harness.state().picking_color.is_none(), "the click on the model picks"); assert!(is_open(&harness), "and leaves the popup open for the picked colour"); } diff --git a/crates/ui-egui/tests/it/properties_scroll.rs b/crates/ui-egui/tests/it/properties_scroll.rs index e3c45785..e4c15155 100644 --- a/crates/ui-egui/tests/it/properties_scroll.rs +++ b/crates/ui-egui/tests/it/properties_scroll.rs @@ -139,12 +139,14 @@ fn a_list_whose_sections_all_fit_still_scrolls_its_last_section_to_the_top() { assert!(last_row_bottom(&harness) < TALL_WINDOW.y, "every section fits in the list"); wheel_to_end(&mut harness); + assert!(tab_lit(&harness, "Material"), "the wheel brought MATERIAL to the top"); assert!(!tab_lit(&harness, "Fill")); assert!(combo_top(&harness, "UV projection") < list_top, "FILL scrolled out above the list"); select_row(&mut harness, "Folder"); select_row(&mut harness, "Fill A"); + assert!(tab_lit(&harness, "Material"), "coming back keeps the place past the rows' end"); } @@ -155,6 +157,7 @@ fn a_last_section_taller_than_the_list_scrolls_to_its_real_end() { let strip = harness.get_by_role_and_label(Role::Tab, "Fill").rect(); let bar = harness.get_all_by_role(Role::ScrollBar).map(|bar| bar.rect()).find(|bar| bar.top() >= strip.top() && bar.left() > strip.left()); let list_bottom = bar.unwrap().bottom(); + assert!(last_row_bottom(&harness) > SHORT_WINDOW.y, "the list's rows run below the window"); wheel_to_end(&mut harness); diff --git a/crates/ui-egui/tests/it/source_picker.rs b/crates/ui-egui/tests/it/source_picker.rs index 23214a4b..af9cdb4b 100644 --- a/crates/ui-egui/tests/it/source_picker.rs +++ b/crates/ui-egui/tests/it/source_picker.rs @@ -67,6 +67,7 @@ fn type_search(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { fn a_procedural_tile_sets_the_channel_and_closes_the_picker() { let (mut harness, layer) = app_with_fill(|_, _| {}); click_slot(&mut harness, "Roughness"); + assert!(harness.query_by_role_and_label(Role::Tab, "Resources").is_some(), "the picker has its Resources tab"); assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "and its Anchor points tab"); @@ -79,6 +80,7 @@ fn a_procedural_tile_sets_the_channel_and_closes_the_picker() { click_slot(&mut harness, "Roughness"); type_search(&mut harness, "uniform"); click_tile(&mut harness, "Uniform value"); + assert_eq!(source(&harness, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness)); } @@ -89,9 +91,13 @@ fn an_alpha_from_the_search_becomes_the_channels_source() { // The search field has the focus as the picker opens and searches every Resources group type_search(&mut harness, "crack"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Clouds").is_none(), "the search hides what doesn't match"); + click_widget(&mut harness, Role::Button, "Clear search"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Clouds").is_some(), "× clears the search"); + type_search(&mut harness, "crack"); click_tile(&mut harness, "Cracks"); @@ -105,13 +111,16 @@ fn the_picker_opens_on_the_current_sources_tab_scrolled_to_it() { let stencil = json!({"layer": layer.0, "channel": "roughness", "alpha": "letter_z"}); texturecraft_engine::execute(session, "layer.fill.set", &stencil).unwrap(); }); + assert!(matches!(source(&harness, layer, Channel::Roughness), Source::Image { .. })); + click_slot(&mut harness, "Roughness"); harness.run_steps(SCROLL_FRAMES); // The last alpha sits far below the picker's first rows; it shows, outlined as the current let tile = harness.get_by_role_and_label(Role::ListBoxOption, "Stencil Z"); assert_eq!(tile.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the current tile is outlined"); + let picker = picker_rect(&harness, "Stencil Z"); assert!(picker.contains_rect(tile.rect()), "the current tile is scrolled into view: {:?} in {picker:?}", tile.rect()); } @@ -126,10 +135,12 @@ fn the_anchor_points_tab_lists_the_stacks_anchors() { let reader = harness.state().session.selected_layer().unwrap(); click_slot(&mut harness, "Roughness"); click_widget(&mut harness, Role::Tab, "Anchor points"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Clouds").is_none(), "the tab shows anchors only"); let anchor = harness.get_all_by_role(Role::ListBoxOption).find_map(|node| node.accesskit_node().label().filter(|label| label.contains("Edge wear"))); click_tile(&mut harness, &anchor.expect("the anchor below is offered")); + assert!(matches!(source(&harness, reader, Channel::Roughness), Source::Anchor { .. })); } @@ -157,9 +168,12 @@ fn escape_or_a_click_outside_closes_it_and_the_wheel_still_zooms_the_view() { modifiers: egui::Modifiers::NONE, }); harness.run_steps(SCROLL_FRAMES); + assert!(clouds(&harness).top() < first_tile.top(), "the wheel over the picker scrolls its grid"); + click_slot(&mut harness, "Roughness"); click_slot(&mut harness, "Roughness"); + assert_eq!(clouds(&harness), first_tile, "the first tile shows again"); assert_eq!(source(&harness, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness), "nothing changed"); } @@ -179,6 +193,7 @@ fn near_the_windows_bottom_the_picker_opens_above_its_slot_at_full_size() { let shown = picker_rect(&harness, FIRST_TILE); assert!(shown.bottom() <= slot.top(), "with no room under the slot it opens above it, never over it: {shown:?} {slot:?}"); assert!(harness.ctx.content_rect().contains_rect(shown), "inside the window: {shown:?}"); + click_slot(&mut harness, SLOT_LOW_IN_THE_CARD); harness.set_size(TALL_WINDOW_SIZE); From 876e8fd64f8cca8463664af6deea5b4654e7fb02 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:48 +0000 Subject: [PATCH 032/153] Masks: Colour selection panel --- crates/ui-egui/src/color_selection_editor.rs | 211 +++++++++----- .../src/property_sheet/id_color_row.rs | 99 +++++++ .../property_sheet/id_color_row_response.rs | 8 + .../tests/it/color_selection_editor.rs | 265 ++++++++++++++---- 4 files changed, 465 insertions(+), 118 deletions(-) create mode 100644 crates/ui-egui/src/property_sheet/id_color_row.rs create mode 100644 crates/ui-egui/src/property_sheet/id_color_row_response.rs diff --git a/crates/ui-egui/src/color_selection_editor.rs b/crates/ui-egui/src/color_selection_editor.rs index 6bb0e6e6..c27eca39 100644 --- a/crates/ui-egui/src/color_selection_editor.rs +++ b/crates/ui-egui/src/color_selection_editor.rs @@ -1,83 +1,143 @@ -//! Properties of a color selection effect: tolerance and the ID colors it selects +//! Properties of a color selection effect: its ID Mask slot with the output value, hardness, tolerance, background, and the ID colors it selects -use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; +use egui::{Color32, CornerRadius, Painter, Rect, Stroke, StrokeKind, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::compose::ImageStore; +use texturecraft_engine::core::{ColorSelection, LayerId, SelectionBackground}; use crate::TextureCraftApp; +use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; use crate::id_color_pick::IdColorPick; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::PropertySheet; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::slot_thumbnail::{SlotThumbnail, paint_empty_slot, paint_thumbnail}; use crate::theme::Tokens; -use crate::widgets::{icon_button, slider_edit}; +use crate::thumbs::Thumbs; -/// Width of one R, G or B readout, so the columns line up from row to row (fits "G: 255") -const READOUT_WIDTH: f32 = 50.0; +/// Squares on each side of the transparent background's checker +const CHECKER_SQUARES: usize = 4; -/// Height of a color row's swatch and readouts, as tall as the app's other swatches -const ROW_HEIGHT: f32 = 18.0; - -const SWATCH_WIDTH: f32 = 36.0; - -const ROW_BUTTON_SIZE: f32 = 20.0; - -/// Tolerance, a Colors list with a pick mode, and one row per ID color (swatch, re-pick, R/G/B, remove) -pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, colors: &[[f32; 3]], tolerance: f32) { - let tokens = Tokens::get(ui.ctx()); - let mut edited_tolerance = tolerance; - if let Some(merge) = slider_edit(ui, tr("Tolerance"), &mut edited_tolerance, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": effect.0, "tolerance": edited_tolerance, "merge": merge})); - } - - let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index); - let has_id_map = app.session.baked(set_index).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Id)); - if !has_id_map { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (Ctrl+Shift+B) to pick colors from the mesh."))).color(tokens.warning)); - } +/// The checker's two grays +const CHECKER_GRAYS: [u8; 2] = [150, 90]; +/// The ID Mask slot, the output value, hardness, tolerance and background, then the Colors band: Pick color and one row per ID color. Every edit goes through `effect.set` or `effect.colorSelection.pick` +pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, selection: &ColorSelection) { + let id = effect.0; let picking = app.picking_id_color.filter(|pick| pick.effect == effect); - ui.group(|ui| { - ui.horizontal(|ui| { - ui.label(tr("Colors")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let adding = picking.is_some_and(|pick| pick.index.is_none()); - let button = egui::Button::new(format!("{} {}", ic::EYEDROPPER, tr("Pick color"))).selected(adding); - if ui.add_enabled(has_id_map, button).clicked() { - toggle_pick(app, effect, None, adding); - } - }); - }); + let tokens = Tokens::get(ui.ctx()); + let (mut output, mut hardness, mut tolerance, background) = (selection.output, selection.hardness, selection.tolerance, selection.background); - for (index, color) in colors.iter().enumerate() { - ui.horizontal(|ui| { - id_swatch(ui, *color); - let repicking = picking.is_some_and(|pick| pick.index == Some(index)); - let repick = ui.add_enabled_ui(has_id_map, |ui| icon_button(ui, ic::EYEDROPPER, tr("Pick color"), repicking, ROW_BUTTON_SIZE)).inner; - if repick.clicked() { - toggle_pick(app, effect, Some(index), repicking); - } + PropertySheet::show(ui, ("color_selection_sheet", id), |sheet| { + sheet.section(tr("Color selection"), false); + let has_id_map = id_mask_slot(app, sheet, effect, selection, &tokens); - for (channel, value) in ["R", "G", "B"].iter().zip(display_bytes(*color)) { - ui.allocate_ui_with_layout(vec2(READOUT_WIDTH, ROW_HEIGHT), egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.set_min_width(READOUT_WIDTH); - ui.label(format!("{channel}: {value}")); - }); - } + // A pick waiting on a map that is gone (its image cleared, no baked ID map) ends, as its disabled Pick color shows + if !has_id_map && picking.is_some() { + IdColorPick::end(app); + } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let remove = ui.add_enabled_ui(colors.len() > 1, |ui| icon_button(ui, ic::MINUS, tr("Remove"), false, ROW_BUTTON_SIZE)).inner; - if remove.clicked() { - // Removing a row changes the indices of pending replacements - IdColorPick::end(app); - let remaining: Vec<[f32; 3]> = colors.iter().enumerate().filter(|(kept, _)| *kept != index).map(|(_, kept)| *kept).collect(); - app.run("effect.set", json!({"effect": effect.0, "colors": remaining})); - } - }); - }); + sheet.caption(tr("Output value")); + let ramp = sheet.ramp(tr("Output value"), &mut output, 0.0..=1.0); + if ramp.invert { + app.run("effect.set", json!({"effect": id, "output": 1.0 - output})); + } else if let Some(merge) = ramp.changed { + app.run("effect.set", json!({"effect": id, "output": output, "merge": merge})); + } + sheet.close_card(); + + if let Some(merge) = sheet.slider(tr("Hardness"), &mut hardness, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "hardness": hardness, "merge": merge})); + } + if let Some(merge) = sheet.slider(tr("Tolerance"), &mut tolerance, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "tolerance": tolerance, "merge": merge})); + } + let swatch = |painter: &Painter, rect: Rect, background: SelectionBackground| background_swatch(painter, rect, background, &tokens); + let name = |background: SelectionBackground| tr(background.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Background Color"), background, &SelectionBackground::ALL, name, Some(&swatch)) { + app.run("effect.set", json!({"effect": id, "background": picked.id()})); + } + + let count = selection.colors.len().to_string(); + if !sheet.band(tr("Colors"), true, None, Some(&count)).open { + return; + } + + let adding = picking.is_some_and(|pick| pick.index.is_none()); + if sheet.button_enabled(DrawnIcon::Pipette, tr("Pick color"), adding, has_id_map).clicked() { + toggle_pick(app, effect, None, adding); + } + for (index, color) in selection.colors.iter().enumerate() { + let repicking = picking.is_some_and(|pick| pick.index == Some(index)); + let row = sheet.id_color_row(display_bytes(*color), repicking, has_id_map); + if row.repick { + toggle_pick(app, effect, Some(index), repicking); + } + if row.remove { + // Removing a row changes the indices of pending replacements + IdColorPick::end(app); + let remaining: Vec<[f32; 3]> = selection.colors.iter().enumerate().filter(|(kept, _)| *kept != index).map(|(_, kept)| *kept).collect(); + app.run("effect.set", json!({"effect": id, "colors": remaining})); + } } }); } +/// The ID Mask slot: its thumbnail and line, the texture picker it opens, its clear and an image dropped on it; whether an ID map is there to pick colors from +fn id_mask_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect: LayerId, selection: &ColorSelection, tokens: &Tokens) -> bool { + let id = effect.0; + let ctx = sheet.ui.ctx().clone(); + let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index); + let (picture, line) = match &selection.id_map { + Some(name) => { + let picture = app + .session + .images + .get(name) + .cloned() + .map_or(SlotThumbnail::Glyph(ic::IMAGE), |image| SlotThumbnail::Texture(app.thumbs.image(&ctx, name, &image))); + (Some(picture), format!("{name} · {}", tr("texture"))) + } + None => match app.session.baked(set_index).and_then(|baked| app.thumbs.id_mesh_map(&ctx, set_index, baked)) { + Some(texture) => (Some(SlotThumbnail::Texture(texture)), format!("{} · {}", tr("ID"), tr("mesh map"))), + None => (None, tr("None").to_owned()), + }, + }; + let has_id_map = picture.is_some() && selection.id_map.as_ref().is_none_or(|name| app.session.images.contains_key(name)); + + let thumbnail = |painter: &Painter, rect: Rect| match &picture { + Some(picture) => paint_thumbnail(painter, rect, picture, tokens), + None => paint_empty_slot(painter, rect, tokens), + }; + let slot = sheet.slot(&thumbnail, tr("ID Mask"), &line, None, selection.id_map.is_some(), false); + let popup = sheet.ui.make_persistent_id(("id_map_picker", id)); + if slot.pick.clicked() { + resource_picker::toggle(&ctx, popup); + } + + // The picker's ids are `Some(name)` for an image and `None` for Import..., so no image chosen is no current tile + let current = selection.id_map.clone().map(Some); + let tabs = |_: &mut Thumbs| texture_tabs(&app.session.images); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs) { + Some(None) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(Some(name)) if selection.id_map.as_ref() != Some(&name) => { + app.run("effect.set", json!({"effect": id, "idMap": name})); + } + Some(Some(_)) | None => {} + } + if slot.clear { + app.run("effect.set", json!({"effect": id, "idMap": null})); + } + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("effect.set", json!({"effect": id, "idMap": name})); + } + has_id_map +} + /// The layer whose mask holds `effect` fn effect_owner(app: &TextureCraftApp, effect: LayerId) -> LayerId { app.session.doc.project.effect(effect).map_or(effect, |(owner, _)| owner) @@ -96,9 +156,28 @@ fn display_bytes(color: [f32; 3]) -> [u8; 3] { color.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8) } -fn id_swatch(ui: &mut Ui, color: [f32; 3]) { - let tokens = Tokens::get(ui.ctx()); - let [red, green, blue] = display_bytes(color); - let (rect, _) = ui.allocate_exact_size(vec2(SWATCH_WIDTH, ROW_HEIGHT), Sense::hover()); - ui.painter().rect(rect, f32::from(tokens.radius), Color32::from_rgb(red, green, blue), Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); +/// The ID Mask picker: the project's textures, Import... first; the id is the texture's name, none for Import... +fn texture_tabs(images: &ImageStore) -> Vec>> { + let textures = ResourcePickerItem::textures(images, None, |name| Some(name.to_owned())); + vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups: vec![PickerGroup { header: Some(tr("Textures")), items: textures }] }] +} + +/// The swatch of a background choice: its gray, or a checker for transparent +fn background_swatch(painter: &Painter, rect: Rect, background: SelectionBackground, tokens: &Tokens) { + match background.value() { + Some(gray) => { + painter.rect_filled(rect, CornerRadius::ZERO, Color32::from_gray((gray * 255.0).round() as u8)); + } + None => { + let square = rect.size() / CHECKER_SQUARES as f32; + for row in 0..CHECKER_SQUARES { + for column in 0..CHECKER_SQUARES { + let min = rect.min + vec2(column as f32 * square.x, row as f32 * square.y); + let gray = CHECKER_GRAYS[(row + column) % 2]; + painter.rect_filled(Rect::from_min_size(min, square), CornerRadius::ZERO, Color32::from_gray(gray)); + } + } + } + } + painter.rect_stroke(rect, CornerRadius::ZERO, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); } diff --git a/crates/ui-egui/src/property_sheet/id_color_row.rs b/crates/ui-egui/src/property_sheet/id_color_row.rs new file mode 100644 index 00000000..17095786 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/id_color_row.rs @@ -0,0 +1,99 @@ +//! One ID color of a color selection: its swatch (the eyedropper that picks it again), its R G B, and a × while hovered + +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::{GLYPH_SIZE, GLYPH_TARGET, IdColorRowResponse, PropertySheet, ROW_HEIGHT, ROW_RADIUS, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::drawn_icon::DrawnIcon; + +/// Height of the swatch +const SWATCH_HEIGHT: f32 = 18.0; + +/// Air between the swatch and the controls column, where the readouts start +const SWATCH_TO_COLUMN: f32 = 12.0; + +/// Room the × keeps at the row's end +const REMOVE_ROOM: f32 = 24.0; + +/// From the right edge to the ×'s centre +const REMOVE_INSET: f32 = 6.0; + +/// Size of the pipette on a hovered swatch +const PIPETTE_SIZE: f32 = 14.0; + +/// From a component's letter to its value +const LETTER_TO_VALUE: f32 = 12.0; + +/// Corner radius of the swatch +const SWATCH_RADIUS: u8 = 3; + +/// Above this luminance the swatch's eyedropper is drawn dark +const LIGHT_SWATCH: f32 = 0.5; + +/// The eyedropper's colour on a light swatch and on a dark one: near black and near white, so it reads on any ID colour +const PIPETTE_ON_LIGHT: Color32 = Color32::from_gray(20); +const PIPETTE_ON_DARK: Color32 = Color32::from_gray(235); + +/// Size of the ×: a point smaller than a row's glyphs, so it stays quiet beside the readouts +const REMOVE_GLYPH_SIZE: f32 = GLYPH_SIZE - 1.0; + +impl PropertySheet<'_> { + /// The row of ID color `rgb`; `repicking` outlines it while its pick runs, `enabled` is false without an ID map to pick from + pub(crate) fn id_color_row(&mut self, rgb: [u8; 3], repicking: bool, enabled: bool) -> IdColorRowResponse { + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + let face = self.bled_row(rect); + let hovered = self.ui.rect_contains_pointer(face); + let swatch = + Rect::from_min_max(pos2(self.left, center_y - SWATCH_HEIGHT / 2.0), pos2(self.column() - SWATCH_TO_COLUMN, center_y + SWATCH_HEIGHT / 2.0)); + let [red, green, blue] = rgb; + let readout = || format!("R {red} G {green} B {blue}"); + + let tokens = self.tokens; + if hovered || repicking { + let outline = if repicking { Stroke::new(1.0, tokens.accent) } else { Stroke::NONE }; + self.ui.painter().rect(face, CornerRadius::same(ROW_RADIUS), tokens.row, outline, StrokeKind::Inside); + } + + let swatch_id = self.next_id(); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let pick_tip = crate::i18n::tr("Pick color"); + let swatch_response = self.tip(self.ui.interact(swatch, swatch_id, sense), pick_tip); + swatch_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, format!("{pick_tip} {}", readout()))); + let color = Color32::from_rgb(red, green, blue); + let painter = self.ui.painter().clone(); + painter.rect_filled(swatch, CornerRadius::same(SWATCH_RADIUS), color); + if enabled && (hovered || repicking) { + // Rec. 709 luminance + let luminance = (0.2126 * f32::from(red) + 0.7152 * f32::from(green) + 0.0722 * f32::from(blue)) / 255.0; + let glyph = if luminance > LIGHT_SWATCH { PIPETTE_ON_LIGHT } else { PIPETTE_ON_DARK }; + DrawnIcon::Pipette.paint(&painter, swatch.center(), PIPETTE_SIZE, glyph); + } + + let step = (self.right - REMOVE_ROOM - self.column()) / rgb.len() as f32; + for (index, (letter, value)) in ["R", "G", "B"].into_iter().zip(rgb).enumerate() { + let x = self.column() + step * index as f32; + painter.text(pos2(x, center_y), Align2::LEFT_CENTER, letter, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); + painter.text(pos2(x + LETTER_TO_VALUE, center_y), Align2::LEFT_CENTER, value.to_string(), FontId::proportional(TEXT_SIZE), tokens.text); + } + + // The × answers only while the row is hovered, so it never takes a click meant for the row under a moving pointer + let remove = Rect::from_center_size(pos2(self.right - REMOVE_INSET, center_y), vec2(GLYPH_TARGET, GLYPH_TARGET)); + let remove_id = self.next_id(); + let remove_tip = crate::i18n::tr("Remove"); + let remove_response = self.ui.interact(remove, remove_id, if hovered { Sense::click() } else { Sense::hover() }); + remove_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, hovered, format!("{remove_tip} {}", readout()))); + let remove_response = self.tip(remove_response, remove_tip); + if hovered { + painter.text( + remove.center(), + Align2::CENTER_CENTER, + ic::X, + FontId::proportional(REMOVE_GLYPH_SIZE), + if remove_response.hovered() { tokens.text } else { tokens.text_dim }, + ); + } + self.drawn(swatch.bottom()); + IdColorRowResponse { repick: swatch_response.clicked(), remove: hovered && remove_response.clicked() } + } +} diff --git a/crates/ui-egui/src/property_sheet/id_color_row_response.rs b/crates/ui-egui/src/property_sheet/id_color_row_response.rs new file mode 100644 index 00000000..8d39054d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/id_color_row_response.rs @@ -0,0 +1,8 @@ +/// What one ID color's row did this frame +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct IdColorRowResponse { + /// The swatch was clicked: pick this color again + pub(crate) repick: bool, + /// The × was clicked + pub(crate) remove: bool, +} diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 97ce9790..8a946e94 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -1,18 +1,30 @@ -//! The color selection editor in Properties: one row per ID color, remove, and the pick mode +//! The color selection in Properties: the ID Mask slot, output value, background, one row per ID color, remove, and the pick mode +use egui::accesskit::Role; use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; -use texturecraft_engine::core::{BakedMap, EffectKind, LayerId}; +use texturecraft_engine::core::{BakedMap, EffectKind, LayerId, SelectionBackground}; use texturecraft_engine::{StackTarget, ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; +use crate::{BAKE_RESOLUTION, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + const FIRST: [f32; 3] = [200.0 / 255.0, 0.0, 0.0]; const SECOND: [f32; 3] = [10.0 / 255.0, 1.0, 0.0]; const THIRD: [f32; 3] = [30.0 / 255.0, 0.0, 1.0]; const ID_PART: [u8; 3] = [90, 160, 220]; +/// Most air between a control and the text of its tooltip above it: the tooltip's gap plus its frame's margin +const TIP_GAP: f32 = 16.0; + +/// Frames past the tooltip delay +const TOOLTIP_WAIT_FRAMES: usize = 60; + +/// The Colors band's button that starts a pick +const PICK_COLOR: &str = "Pick color"; + /// An ID map of one color, as a PNG fn id_map_png() -> Vec { let [red, green, blue] = ID_PART; @@ -24,7 +36,7 @@ fn id_map_png() -> Vec { /// A selected color selection of three colors on a fill layer's mask fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); if with_id_map { let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); @@ -43,14 +55,14 @@ fn color_selection_session(with_id_map: bool) -> (texturecraft_engine::Session, fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let (session, effect) = color_selection_session(with_id_map); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - harness.run_steps(4); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); (harness, effect) } fn colors(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Vec<[f32; 3]> { match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { - EffectKind::ColorSelection { colors, .. } => colors.clone(), + EffectKind::ColorSelection(selection) => selection.colors.clone(), other => panic!("not a color selection: {other:?}"), } } @@ -61,7 +73,7 @@ fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); harness.run_steps(1); harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); } /// Whether the pointer at `pointer` is the drawn eyedropper: the system pointer hidden and a picture painted under it @@ -74,24 +86,20 @@ fn eyedropper_at(harness: &Harness<'_, TextureCraftApp>, pointer: Pos2) -> bool }) } -fn pick_color_label() -> String { - format!("{} Pick color", egui_phosphor::regular::EYEDROPPER) +/// The accessible name of `color`'s row button `action` ("Pick color" on the swatch, "Remove" on the ×) +fn row_label(action: &str, color: [f32; 3]) -> String { + let [red, green, blue] = color.map(|value| (value * 255.0).round() as u8); + format!("{action} R {red} G {green} B {blue}") } #[test] fn each_color_gets_a_row_and_remove_sends_the_list_without_it() { let (mut harness, effect) = app_with_color_selection(false); - for readout in ["R: 200", "R: 10", "R: 30"] { - assert!(harness.query_by_label(readout).is_some(), "{readout} row"); + for color in [FIRST, SECOND, THIRD] { + assert!(harness.query_by_label(&row_label("Pick color", color)).is_some(), "{color:?} row"); } - let second_row = harness.get_by_label("R: 10").rect().center().y; - let remove = harness - .query_all_by_label("Remove") - .find(|button| (button.rect().center().y - second_row).abs() < 8.0) - .expect("the second row's remove button") - .rect() - .center(); + let remove = row_button(&harness, SECOND, "Remove"); click_at(&mut harness, remove); assert_eq!(colors(&harness, effect), vec![FIRST, THIRD]); @@ -100,8 +108,8 @@ fn each_color_gets_a_row_and_remove_sends_the_list_without_it() { #[test] fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { let (mut harness, effect) = app_with_color_selection(true); - harness.get_by_label(&pick_color_label()).click(); - harness.run_steps(3); + harness.get_by_label(PICK_COLOR).click(); + harness.run_steps(SETTLE_FRAMES); assert!(harness.state().picking_id_color.is_some_and(|pick| pick.effect == effect && pick.index.is_none())); assert_eq!(harness.state().session.view, ViewMode::MeshMap(BakedMap::Id)); @@ -120,29 +128,29 @@ fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { } #[test] -fn without_an_id_map_picking_is_off_and_a_warning_says_why() { - let (mut harness, _) = app_with_color_selection(false); - let warning = format!("{} Bake an ID map (Ctrl+Shift+B) to pick colors from the mesh.", egui_phosphor::regular::WARNING); - assert!(harness.query_by_label(&warning).is_some()); - - harness.get_by_label(&pick_color_label()).click(); - harness.run_steps(3); +fn without_an_id_map_picking_is_off() { + let (mut harness, effect) = app_with_color_selection(false); + harness.get_by_label(PICK_COLOR).click(); + harness.run_steps(SETTLE_FRAMES); + let repick = row_button(&harness, FIRST, "Pick color"); + click_at(&mut harness, repick); assert!(harness.state().picking_id_color.is_none()); + assert_eq!(colors(&harness, effect).len(), 3); } -fn row_button(harness: &Harness<'_, TextureCraftApp>, readout: &str, label: &str) -> Pos2 { - let row_y = harness.get_by_label(readout).rect().center().y; - harness.query_all_by_label(label).find(|button| (button.rect().center().y - row_y).abs() < 8.0).unwrap().rect().center() +/// The centre of `color`'s row button `action` +fn row_button(harness: &Harness<'_, TextureCraftApp>, color: [f32; 3], action: &str) -> Pos2 { + harness.get_by_label(&row_label(action, color)).rect().center() } #[test] fn removing_a_row_cancels_a_pending_replacement() { let (mut harness, effect) = app_with_color_selection(true); - let repick = row_button(&harness, "R: 10", "Pick color"); + let repick = row_button(&harness, SECOND, "Pick color"); click_at(&mut harness, repick); assert_eq!(harness.state().picking_id_color.unwrap().index, Some(1)); - let remove = row_button(&harness, "R: 200", "Remove"); + let remove = row_button(&harness, FIRST, "Remove"); click_at(&mut harness, remove); assert_eq!(colors(&harness, effect), vec![SECOND, THIRD]); @@ -153,12 +161,12 @@ fn removing_a_row_cancels_a_pending_replacement() { #[test] fn escape_cancels_the_pick_without_editing_colors() { let (mut harness, effect) = app_with_color_selection(true); - harness.get_by_label(&pick_color_label()).click(); - harness.run_steps(3); + harness.get_by_label(PICK_COLOR).click(); + harness.run_steps(SETTLE_FRAMES); let history = harness.state().session.history_labels(); harness.key_press(egui::Key::Escape); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.state().picking_id_color.is_none()); assert_eq!(harness.state().session.view, ViewMode::Material); @@ -169,21 +177,21 @@ fn escape_cancels_the_pick_without_editing_colors() { #[test] fn escape_cancels_id_picking_with_a_hidden_rail_popup() { let (mut harness, effect) = app_with_color_selection(true); - harness.get_by_label(&pick_color_label()).click(); - harness.run_steps(3); + harness.get_by_label(PICK_COLOR).click(); + harness.run_steps(SETTLE_FRAMES); let context = harness.ctx.clone(); texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.log"); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); harness.get_by_role_and_label(egui::Role::Button, "Close"); harness.key_press(egui::Key::Tab); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.state().ui.hide_ui); assert!(harness.query_by_role_and_label(egui::Role::Button, "Close").is_none()); assert!(harness.state().picking_id_color.is_some()); let history = harness.state().session.history_labels(); harness.key_press(egui::Key::Escape); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.state().picking_id_color.is_none(), "one Escape cancels ID picking despite the hidden popup"); assert_eq!(harness.state().session.view, ViewMode::Material); @@ -198,9 +206,9 @@ fn picking_from_the_popup_closes_it_before_the_viewport_click() { let (mut harness, effect) = app_with_color_selection(true); let bounds = harness.state().viewport_rect; harness.state_mut().properties_popup = Some(PropertiesPopup::Open { at: bounds.center() - egui::vec2(100.0, 100.0), bounds }); - harness.run_steps(4); + harness.run_steps(REDRAW_FRAMES); let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); - let pick = harness.query_all_by_label(&pick_color_label()).find(|button| popup.contains_rect(button.rect())).unwrap().rect().center(); + let pick = harness.query_all_by_label(PICK_COLOR).find(|button| popup.contains_rect(button.rect())).unwrap().rect().center(); click_at(&mut harness, pick); assert!(harness.state().picking_id_color.is_some()); @@ -217,11 +225,11 @@ fn a_2d_pick_replaces_the_chosen_row_and_undo_restores_it() { let (mut harness, effect) = app_with_color_selection(true); harness.state_mut().ui.layout = ViewLayout::Only3D; - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); let center = harness.state().viewport_rect.center(); harness.state_mut().ui.layout = ViewLayout::Only2D; - harness.run_steps(3); - let repick = row_button(&harness, "R: 10", "Pick color"); + harness.run_steps(SETTLE_FRAMES); + let repick = row_button(&harness, SECOND, "Pick color"); click_at(&mut harness, repick); click_at(&mut harness, center); @@ -235,11 +243,11 @@ fn a_2d_pick_replaces_the_chosen_row_and_undo_restores_it() { #[test] fn deselection_cancels_picking_and_preserves_a_view_chosen_meanwhile() { let (mut harness, effect) = app_with_color_selection(true); - harness.get_by_label(&pick_color_label()).click(); - harness.run_steps(3); + harness.get_by_label(PICK_COLOR).click(); + harness.run_steps(SETTLE_FRAMES); execute(&mut harness.state_mut().session, "viewport.view", &json!({"mode": "uvChecker"})).unwrap(); harness.state_mut().session.target = StackTarget::Content; - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.state().picking_id_color.is_none()); assert_eq!(harness.state().session.view, ViewMode::UvChecker); @@ -254,7 +262,7 @@ fn removing_an_image_during_id_picking_falls_back_to_material() { let session = &mut harness.state_mut().session; let name = session.import_resource_bytes("preview.png", png.into_inner()).unwrap(); execute(session, "viewport.view", &json!({"mode": "image", "image": name})).unwrap(); - harness.get_by_label(&pick_color_label()).click(); + harness.get_by_label(PICK_COLOR).click(); harness.run_steps(3); assert_eq!(harness.state().session.view, ViewMode::MeshMap(BakedMap::Id)); assert!(harness.state().picking_id_color.is_some()); @@ -291,7 +299,7 @@ fn color_selection_snapshots_and_quick_mask_pick() { }; save(&mut harness, "color-selection-editor"); - harness.get_by_label(&pick_color_label()).click(); + harness.get_by_label(PICK_COLOR).click(); let center = harness.state().viewport_rect.center(); harness.hover_at(center + egui::vec2(80.0, 0.0)); let expected = save(&mut harness, "color-selection-picking"); @@ -313,7 +321,7 @@ fn color_selection_snapshots_and_quick_mask_pick() { execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; - harness.get_by_label(&pick_color_label()).click(); + harness.get_by_label(PICK_COLOR).click(); save(&mut harness, "color-selection-picking-2d"); click_at(&mut harness, center); @@ -322,3 +330,156 @@ fn color_selection_snapshots_and_quick_mask_pick() { execute(&mut harness.state_mut().session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); save(&mut harness, "color-selection-no-id-map"); } + +fn selection(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> texturecraft_engine::core::ColorSelection { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::ColorSelection(selection) => selection.clone(), + other => panic!("not a color selection: {other:?}"), + } +} + +#[test] +fn the_background_list_and_the_output_invert_edit_one_undo_step_each() { + let (mut harness, effect) = app_with_color_selection(true); + for slider in ["Output value", "Hardness", "Tolerance"] { + assert!(harness.query_by_role_and_label(Role::Slider, slider).is_some(), "{slider} row"); + } + let steps = harness.state().session.history_labels().len(); + + harness.get_by_role_and_label(Role::ComboBox, "Black").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_role_and_label(Role::ListBoxOption, "White").click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(selection(&harness, effect).background, SelectionBackground::White); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); + + let invert = harness.get_by_role_and_label(Role::Button, "Invert").rect().center(); + click_at(&mut harness, invert); + assert_eq!(selection(&harness, effect).output, 0.0); + assert_eq!(harness.state().session.history_labels().len(), steps + 2); +} + +#[test] +fn the_background_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click_outside() { + let (mut harness, effect) = app_with_color_selection(true); + crate::assert_list_leaves_the_wheel_and_closes(&mut harness, |harness| { + harness.get_by_role_and_label(Role::ComboBox, "Black").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_role_and_label(Role::ComboBox, "Black").rect() + }); + assert_eq!(selection(&harness, effect).background, SelectionBackground::Black, "nothing changed"); +} + +#[test] +fn the_id_mask_slot_picks_a_texture_and_its_x_goes_back_to_the_mesh_map() { + let (mut session, effect) = color_selection_session(true); + let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); + + harness.get_by_role_and_label(Role::ComboBox, "ID Mask").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_role_and_label(Role::ListBoxOption, &texture).click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(selection(&harness, effect).id_map.as_deref(), Some(texture.as_str())); + + let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect().center(); + click_at(&mut harness, clear); + assert_eq!(selection(&harness, effect).id_map, None); + assert!(harness.query_by_role_and_label(Role::Button, "Clear").is_none(), "the mesh map has no ×"); +} + +/// Whether the ID Mask picker's tile `label` shows as the current one (egui reports a selected tile as toggled) +fn tile_is_current(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.get_by_role_and_label(Role::ListBoxOption, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn reading_the_mesh_map_shows_no_tile_as_the_current_id_mask() { + let (mut session, effect) = color_selection_session(true); + let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); + assert_eq!(selection(&harness, effect).id_map, None, "the selection reads the ID mesh map"); + + harness.get_by_role_and_label(Role::ComboBox, "ID Mask").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(!tile_is_current(&harness, "Import..."), "Import... is an action, not the map read"); + assert!(!tile_is_current(&harness, &texture)); + + harness.get_by_role_and_label(Role::ListBoxOption, &texture).click(); + harness.run_steps(REDRAW_FRAMES); + harness.get_by_role_and_label(Role::ComboBox, "ID Mask").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(tile_is_current(&harness, &texture), "a chosen texture is the current tile"); + assert!(!tile_is_current(&harness, "Import...")); +} + +#[test] +fn the_invert_tooltip_shows_right_above_its_button() { + let (mut harness, _) = app_with_color_selection(true); + let invert = harness.get_by_role_and_label(Role::Button, "Invert").rect(); + harness.hover_at(invert.center()); + + harness.run_steps(TOOLTIP_WAIT_FRAMES); + let tip = + harness.get_all_by_label("Invert").find(|node| node.accesskit_node().role() == Role::Label).map(|node| node.rect()).expect("the button's tooltip"); + assert!(tip.bottom() <= invert.top() && invert.top() - tip.bottom() <= TIP_GAP, "the tooltip sits right above the button: {tip:?} {invert:?}"); + assert!(tip.right() >= invert.left() && tip.left() <= invert.right(), "the tooltip overlaps the button's columns, not off to its side: {tip:?} {invert:?}"); +} + +#[test] +#[ignore = "requires a GPU adapter; set TC_UI_SNAPSHOTS to save the rendered view"] +fn invert_tooltip_snapshot() { + let (session, _) = color_selection_session(true); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); + let invert = harness.get_by_role_and_label(Role::Button, "Invert").rect(); + harness.hover_at(invert.center()); + harness.run_steps(TOOLTIP_WAIT_FRAMES); + let image = harness.render().unwrap(); + if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { + image.save(std::path::Path::new(&directory).join("invert-tooltip.png")).unwrap(); + } +} + +#[test] +fn a_hand_picked_id_mask_picks_without_a_bake() { + let (mut session, effect) = color_selection_session(false); + session.doc.baked.clear(); + let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": texture})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); + + harness.get_by_label(PICK_COLOR).click(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_id_color.is_some_and(|pick| pick.effect == effect), "Pick color starts picking with no bake"); + + let center = harness.state().viewport_rect.center(); + click_at(&mut harness, center); + + let picked = colors(&harness, effect); + assert_eq!(picked.len(), 4, "the click adds a row"); + assert_eq!(picked[3], ID_PART.map(|channel| channel as f32 / 255.0), "read from the chosen image"); +} + +#[test] +fn clearing_the_only_id_mask_ends_a_waiting_pick() { + let (mut session, effect) = color_selection_session(false); + session.doc.baked.clear(); + let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": texture})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); + harness.get_by_label(PICK_COLOR).click(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_id_color.is_some(), "the pick waits"); + + let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect().center(); + click_at(&mut harness, clear); + assert_eq!(selection(&harness, effect).id_map, None); + assert!(harness.state().picking_id_color.is_none(), "with no ID map left the pick ends"); + assert_eq!(harness.state().session.view, ViewMode::Material, "and the earlier view comes back"); +} From 0bea86f27d8ba2937ad13ca094b00c55572fc478 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:48 +0000 Subject: [PATCH 033/153] Effects: Anchor point panel and its references --- crates/ui-egui/src/anchor_properties.rs | 74 +++++++++++++++++++ .../src/property_sheet/reference_row.rs | 53 +++++++++++++ crates/ui-egui/src/reference.rs | 12 +++ crates/ui-egui/tests/it/rename_anchor.rs | 26 ++++--- 4 files changed, 154 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/anchor_properties.rs create mode 100644 crates/ui-egui/src/property_sheet/reference_row.rs create mode 100644 crates/ui-egui/src/reference.rs diff --git a/crates/ui-egui/src/anchor_properties.rs b/crates/ui-egui/src/anchor_properties.rs new file mode 100644 index 00000000..98ecd292 --- /dev/null +++ b/crates/ui-egui/src/anchor_properties.rs @@ -0,0 +1,74 @@ +//! Properties of an anchor point: its name, typed in place, and the References band with what reads it (a click selects that) + +use egui::Ui; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{EffectKind, LayerId, LayerKind, Project}; + +use crate::TextureCraftApp; +use crate::i18n::{n_, tr}; +use crate::property_sheet::PropertySheet; +use crate::reference::Reference; + +/// The properties of anchor point `anchor` named `name`; renaming goes through `effect.set`, a reference's click through `layer.select` +pub(crate) fn anchor_properties(app: &mut TextureCraftApp, ui: &mut Ui, anchor: LayerId, name: &str) { + let references = references(&app.session.doc.project, anchor); + PropertySheet::show(ui, ("anchor_sheet", anchor.0), |sheet| { + sheet.section(tr("Anchor point"), false); + if let Some(renamed) = sheet.name_field(tr("Anchor point name"), name) { + app.run("effect.set", json!({"effect": anchor.0, "name": renamed})); + } + + // The count says when nothing reads it + let count = references.len().to_string(); + if !sheet.band(tr("References"), true, None, Some(&count)).open { + return; + } + + for reference in &references { + if sheet.reference_row(reference.glyph, &reference.name, tr(reference.kind)) { + let target = reference.effect.map_or_else(|| json!("content"), |effect| json!(effect.0)); + app.run("layer.select", json!({"layer": reference.layer.0, "target": target})); + } + } + }); +} + +/// What reads `anchor`, bottom to top +fn references(project: &Project, anchor: LayerId) -> Vec { + project + .anchor_readers(anchor) + .into_iter() + .filter_map(|(layer_id, effect)| { + let layer = project.layers.get(&layer_id)?; + let (kind, glyph) = match effect { + None if matches!(layer.kind, LayerKind::Fill(_)) => (n_("Fill"), ic::PAINT_BUCKET), + None => return None, + Some(effect) => { + let in_content = layer.content_effects.iter().any(|content_effect| content_effect.id == effect); + match project.effect(effect).map(|(_, found)| &found.kind) { + Some(EffectKind::Fill { .. } | EffectKind::Material(_)) if in_content => (n_("Fill"), ic::PAINT_BUCKET), + Some(EffectKind::Fill { .. }) => (n_("Mask fill"), ic::PAINT_BUCKET), + Some(other) => (other.name(), reader_glyph(other)), + None => return None, + } + } + }; + Some(Reference { layer: layer_id, name: layer.name.clone(), kind, glyph, effect }) + }) + .collect() +} + +/// The icon of an effect that reads an anchor point, the one its Add effect item shows +fn reader_glyph(kind: &EffectKind) -> &'static str { + match kind { + EffectKind::Compare { .. } => ic::SCALES, + EffectKind::Levels(_) => ic::CHART_BAR, + EffectKind::Filter(_) => ic::FUNNEL, + EffectKind::ColorSelection(_) => ic::SELECTION, + EffectKind::Generator(_) => ic::SPARKLE, + EffectKind::Paint | EffectKind::Path(_) => ic::PAINT_BRUSH, + EffectKind::Anchor => ic::ANCHOR, + EffectKind::Fill { .. } | EffectKind::Material(_) => ic::PAINT_BUCKET, + } +} diff --git a/crates/ui-egui/src/property_sheet/reference_row.rs b/crates/ui-egui/src/property_sheet/reference_row.rs new file mode 100644 index 00000000..8c016d72 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/reference_row.rs @@ -0,0 +1,53 @@ +//! One row of a list of things to go to: a glyph, a name and its kind (dim); hovered, a face and an arrow show the click selects it + +use egui::{Align2, CornerRadius, FontId, Sense, pos2}; +use egui_phosphor::regular as ic; + +use super::{GLYPH_SIZE, PropertySheet, ROW_HEIGHT, ROW_RADIUS, TEXT_SIZE}; + +/// From the left edge to the glyph's centre, and from there to the name +const GLYPH_CENTER: f32 = 6.0; +const GLYPH_TO_NAME: f32 = 14.0; + +/// Size of the arrow +const ARROW_SIZE: f32 = 12.0; + +/// Air between the name and its kind +const NAME_TO_KIND: f32 = 6.0; + +/// From the right edge to the arrow's centre +const ARROW_INSET: f32 = 6.0; + +impl PropertySheet<'_> { + /// The row of `name` (a `kind`, drawn with `glyph`); returns true when it was clicked + pub(crate) fn reference_row(&mut self, glyph: &str, name: &str, kind: &str) -> bool { + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + let face = self.bled_row(rect); + let id = self.next_id(); + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + + // The kind and the arrow keep their room; a name too long for the rest is cut short and shows in full on hover + let kind_galley = painter.layout_no_wrap(kind.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text_dim); + let name_left = self.left + GLYPH_CENTER + GLYPH_TO_NAME; + let name_room = self.right - ARROW_INSET - ARROW_SIZE * 0.5 - kind_galley.size().x - NAME_TO_KIND - name_left; + let name_galley = crate::widgets::elided(&painter, name, TEXT_SIZE, tokens.text, name_room); + let cut_short = name_galley.elided; + + let response = self.ui.interact(face, id, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); + let response = if cut_short { response.on_hover_text(name) } else { response }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{name} {kind}"))); + + if response.hovered() { + painter.rect_filled(face, CornerRadius::same(ROW_RADIUS), tokens.button); + painter.text(pos2(self.right - ARROW_INSET, center_y), Align2::CENTER_CENTER, ic::CARET_RIGHT, FontId::proportional(ARROW_SIZE), tokens.text); + } + painter.text(pos2(self.left + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), tokens.text_dim); + let name_right = name_left + name_galley.size().x; + painter.galley(pos2(name_left, center_y - name_galley.size().y * 0.5), name_galley, tokens.text); + painter.galley(pos2(name_right + NAME_TO_KIND, center_y - kind_galley.size().y * 0.5), kind_galley, tokens.text_dim); + self.drawn(rect.bottom()); + response.clicked() + } +} diff --git a/crates/ui-egui/src/reference.rs b/crates/ui-egui/src/reference.rs new file mode 100644 index 00000000..636a630d --- /dev/null +++ b/crates/ui-egui/src/reference.rs @@ -0,0 +1,12 @@ +//! One reader of an anchor point, as the anchor's References band lists it + +use texturecraft_engine::core::LayerId; + +/// One reader of an anchor point: the layer, its name, what reads (kind name and its icon) and the effect (None: the fill layer itself) +pub(crate) struct Reference { + pub(crate) layer: LayerId, + pub(crate) name: String, + pub(crate) kind: &'static str, + pub(crate) glyph: &'static str, + pub(crate) effect: Option, +} diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index 244c7f7b..e98d2e6c 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -162,6 +162,16 @@ fn sphere_session() -> Session { Session::new_project("anchors", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap() } +/// Opens the Layers toolbar's Add effect menu and clicks its item `item` (the one nearest the menu's button) +fn add_effect(h: &mut Harness<'_, TextureCraftApp>, item: &str) { + let menu = h.get_by_role_and_label(Role::Button, "Add effect").rect(); + h.get_by_role_and_label(Role::Button, "Add effect").click(); + h.run_steps(3); + let distance = |rect: egui::Rect| rect.center().distance(menu.center()); + let row = h.get_all_by_role_and_label(Role::Button, item).map(|node| node.rect()).min_by(|a, b| distance(*a).total_cmp(&distance(*b))).unwrap(); + crate::filter_support::click_at(h, row.center()); +} + fn mask_anchor_of(h: &Harness<'_, TextureCraftApp>, layer: u64) -> Option { let layer = h.state().session.doc.project.layer(LayerId(layer)).unwrap(); layer.mask.iter().flat_map(|m| m.effects.iter()).find(|e| matches!(e.kind, EffectKind::Anchor)).map(|e| e.id.0) @@ -180,23 +190,16 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { let low = low_layer(&mut session); let mut h = harness_for(session); - // The wand adds to the mask, since the mask's fill is the selected target of the Low layer + // Add effect adds to the mask, since the mask's fill is the selected target of the Low layer assert!(matches!(h.state().session.target, StackTarget::Effect(_))); - h.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); - h.run_steps(3); - assert!(h.query_by_label("Add to the mask").is_some(), "the menu offers the mask"); - h.get_by_label("Add anchor point").click(); - h.run_steps(3); + add_effect(&mut h, "Anchor point"); let anchor = mask_anchor_of(&h, low).expect("the anchor point is in the mask of Low"); assert!(h.state().session.doc.project.layer(LayerId(low)).unwrap().content_effects.is_empty(), "the anchor point is not on the layer content"); // A higher layer with a mask fill, added through the same menu let high = high_layer(&mut h.state_mut().session); h.run_steps(3); - h.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); - h.run_steps(3); - h.get_by_label("Add fill").click(); - h.run_steps(3); + add_effect(&mut h, "Fill"); assert!(matches!(reader_source(&h, high), Source::Uniform(_)), "a new fill starts as a uniform value"); // The Anchor points tab lists the mask anchor of the layer below @@ -207,7 +210,8 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { h.get_by_role_and_label(Role::Tab, "Anchor points").click(); h.run_steps(3); - let label = format!("Low / mask / {}", effect_name(&h, anchor)); + // The only anchor below is listed by its name alone + let label = effect_name(&h, anchor); h.get_by_role_and_label(Role::ListBoxOption, &label).click(); h.run_steps(3); From 9ed26168d0108ee82974cd6336d24a2ce83fac37 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:48 +0000 Subject: [PATCH 034/153] Layers: the layer toolbar (channel list, Add effect, Add mask) --- crates/ui-egui/src/layer_toolbar.rs | 462 ++++++++++++++++++ crates/ui-egui/src/layer_toolbar/add_item.rs | 14 + .../src/layer_toolbar/bitmap_choice.rs | 7 + crates/ui-egui/src/layer_toolbar/item_icon.rs | 7 + crates/ui-egui/src/layer_toolbar/menu_icon.rs | 7 + crates/ui-egui/src/layer_toolbar/pick.rs | 7 + crates/ui-egui/tests/it/layer_toolbar.rs | 198 ++++++++ 7 files changed, 702 insertions(+) create mode 100644 crates/ui-egui/src/layer_toolbar.rs create mode 100644 crates/ui-egui/src/layer_toolbar/add_item.rs create mode 100644 crates/ui-egui/src/layer_toolbar/bitmap_choice.rs create mode 100644 crates/ui-egui/src/layer_toolbar/item_icon.rs create mode 100644 crates/ui-egui/src/layer_toolbar/menu_icon.rs create mode 100644 crates/ui-egui/src/layer_toolbar/pick.rs create mode 100644 crates/ui-egui/tests/it/layer_toolbar.rs diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs new file mode 100644 index 00000000..05ad4070 --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -0,0 +1,462 @@ +//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons and remove + +use egui::{Align2, Color32, CornerRadius, FontId, Frame, Id, Painter, Pos2, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::compose::ImageStore; +use texturecraft_engine::core::{Layer, LayerId}; +use texturecraft_engine::paint::alphas; + +use crate::TextureCraftApp; +use crate::i18n::{n_, tr}; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::theme::{HARD_SHADOW, Tokens}; +use crate::thumbs::Thumbs; +use crate::tile_picture::TilePicture; + +mod add_item; +mod bitmap_choice; +mod item_icon; +mod menu_icon; +mod pick; + +use add_item::AddItem; +use bitmap_choice::BitmapChoice; +use item_icon::ItemIcon; +use menu_icon::MenuIcon; +use pick::Pick; + +/// The row's height and its controls' height +const BAR_HEIGHT: f32 = 40.0; +const CONTROL_HEIGHT: f32 = 26.0; +const CONTROL_ROUNDING: u8 = 5; + +/// Room between the row's ends and its first and last controls +const SIDE_PADDING: f32 = 8.0; + +const CHANNEL_WIDTH: f32 = 88.0; +/// A menu button: its icon, then its caret +const MENU_BUTTON_WIDTH: f32 = 32.0; +const MENU_ICON_X: f32 = 11.0; +const MENU_CARET_INSET: f32 = 8.0; +const MENU_ICON_SIZE: f32 = 14.0; +const MASK_ICON_SIZE: f32 = 12.0; +const CARET_SIZE: f32 = 11.0; +const BUTTON_WIDTH: f32 = 24.0; +const ICON_SIZE: f32 = 14.0; +/// Air after the channel list, between the two menu buttons, before the add-layer buttons and between them +const CHANNEL_GAP: f32 = 6.0; +const MENU_GAP: f32 = 3.0; +const GROUP_GAP: f32 = 8.0; +const BUTTON_GAP: f32 = 2.0; +const CHANNEL_TEXT_X: f32 = 8.0; +const CHANNEL_CARET_INSET: f32 = 10.0; +const CHANNEL_CARET_SIZE: f32 = 12.0; +const TEXT_SIZE: f32 = 12.0; + +/// The row's width besides the channel list's: its padding, the two menu buttons and their gaps +const MENUS_ROW_WIDTH: f32 = 2.0 * SIDE_PADDING + CHANNEL_GAP + 2.0 * MENU_BUTTON_WIDTH + MENU_GAP; +/// The three add-layer buttons and Remove +const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP; +/// The width every control takes in one row +const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH; + +/// A hanging menu: its caption, rows, icon and text columns and its smallest width +const MENU_PADDING: f32 = 4.0; +const MENU_CAPTION_HEIGHT: f32 = 22.0; +const MENU_CAPTION_X: f32 = 12.0; +const MENU_CAPTION_SIZE: f32 = 10.0; +const MENU_ROW: f32 = 24.0; +const MENU_ROW_INSET: f32 = 4.0; +const MENU_ROW_ROUNDING: u8 = 4; +const MENU_ITEM_ICON_X: f32 = 18.0; +const MENU_ITEM_ICON_SIZE: f32 = 13.0; +const MENU_ITEM_SWATCH: f32 = 12.0; +const MENU_ITEM_SWATCH_ROUNDING: u8 = 2; +const MENU_TEXT_X: f32 = 34.0; +const MENU_RIGHT: f32 = 22.0; +const MENU_MIN_WIDTH: f32 = 120.0; +const MENU_ROUNDING: u8 = 6; + +/// The menu rises over its button's bottom edge by this much (a negative gap), so the two read as one tab with no seam +const MENU_TAB_OVERLAP: f32 = -1.0; + +const SHADOW_OFFSET: [i8; 2] = [3, 4]; +/// The two swatches of Add mask's White and Black +const WHITE_SWATCH: u8 = 235; +const BLACK_SWATCH: u8 = 10; + + +/// The Layers panel's top row and what its menus open +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + + // A panel narrower than one row puts the add-layer buttons and Remove on a second row, where they stay inside it + let width = ui.available_width(); + let two_rows = width < ONE_ROW_WIDTH; + let (area, _) = ui.allocate_exact_size(vec2(width, if two_rows { 2.0 * BAR_HEIGHT } else { BAR_HEIGHT }), Sense::hover()); + let anchor = ui.interact(area, ui.scope_id().with("layer_toolbar"), Sense::hover()); + let bar = Rect::from_min_size(area.min, vec2(width, BAR_HEIGHT)); + let top = bar.center().y - CONTROL_HEIGHT * 0.5; + let mut x = bar.left() + SIDE_PADDING; + let control = |x: f32, top: f32, width: f32| Rect::from_min_size(pos2(x, top), vec2(width, CONTROL_HEIGHT)); + + // Narrower still, the channel list gives up width before a menu button leaves the panel + let channel_width = CHANNEL_WIDTH.min(width - MENUS_ROW_WIDTH).max(0.0); + channel_list(app, ui, control(x, top, channel_width), &tokens); + x += channel_width + CHANNEL_GAP; + + let selected = app.session.selected_layer().filter(|id| app.session.doc.project.layers.contains_key(id)); + let effects = || effect_items(app, layer_of(app, selected)); + let mut pick = menu_button(ui, control(x, top, MENU_BUTTON_WIDTH), tr("Add effect"), MenuIcon::Glyph(ic::MAGIC_WAND), tr("Add effect"), effects, &tokens); + x += MENU_BUTTON_WIDTH + MENU_GAP; + let masks = || mask_items(layer_of(app, selected)); + pick = pick.or(menu_button(ui, control(x, top, MENU_BUTTON_WIDTH), tr("Add mask"), MenuIcon::Mask, tr("Add mask"), masks, &tokens)); + x += MENU_BUTTON_WIDTH + GROUP_GAP; + + let (top, mut x) = if two_rows { (top + BAR_HEIGHT, bar.left() + SIDE_PADDING) } else { (top, x) }; + for (glyph, label, command) in [ + (ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), + (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill"), + (ic::FOLDER_SIMPLE, tr("Add folder"), "layer.add.group"), + ] { + if plain_button(ui, control(x, top, BUTTON_WIDTH), glyph, label, &tokens).clicked() { + app.run(command, Value::Null); + } + x += BUTTON_WIDTH + BUTTON_GAP; + } + let remove = control((bar.right() - SIDE_PADDING - BUTTON_WIDTH).max(x), top, BUTTON_WIDTH); + if plain_button(ui, remove, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), &tokens).clicked() { + app.run("layer.remove", Value::Null); + } + + // Keyed by the layer that opened it: a picker no longer shown when the selection moves closes, so its pick never lands on another layer + let popup = |layer: LayerId| ui.scope_id().with(("bitmap_mask_picker", layer.0)); + match (pick, selected) { + (Some(Pick::Run { command, params }), Some(layer)) => run_on(app, ui, layer, command, params), + (Some(Pick::Bitmap), Some(layer)) => resource_picker::toggle(ui.ctx(), popup(layer)), + _ => {} + } + if let Some(layer) = selected { + bitmap_picker(app, &anchor, popup(layer), layer); + } +} + +/// Layer `id` of the project, when there is one +fn layer_of(app: &TextureCraftApp, id: Option) -> Option<&Layer> { + id.and_then(|id| app.session.doc.project.layers.get(&id)) +} + +/// How far a hovered dropdown lightens towards the text colour +const HOVER_TINT: f32 = 0.06; + +/// Air between the channel's name and its caret, and between the button and its list +const CHANNEL_TEXT_AIR: f32 = 2.0; +const CHANNEL_LIST_GAP: f32 = 1.0; + +/// The displayed channel, or Material for the whole material: a list hanging from its button +fn channel_list(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, tokens: &Tokens) { + let response = ui.interact(rect, ui.scope_id().with("layer_channel"), Sense::click()); + let current = if app.ui.layer_material_view { tr("Material") } else { tr(app.ui.layer_channel.label()) }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, current)); + let painter = ui.painter(); + let fill = if response.hovered() { tokens.button.lerp_to_gamma(tokens.text, HOVER_TINT) } else { tokens.button }; + painter.rect(rect, CornerRadius::same(CONTROL_ROUNDING), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + let caret_x = rect.right() - CHANNEL_CARET_INSET; + let text = crate::widgets::elided( + painter, + current.to_owned(), + TEXT_SIZE, + tokens.text, + caret_x - CHANNEL_CARET_SIZE * 0.5 - rect.left() - CHANNEL_TEXT_X - CHANNEL_TEXT_AIR, + ); + painter.galley(pos2(rect.left() + CHANNEL_TEXT_X, rect.center().y - text.size().y * 0.5), text, tokens.text); + painter.text(pos2(caret_x, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CHANNEL_CARET_SIZE), tokens.text); + + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); + egui::Popup::menu(&response).id(ui.scope_id().with("layer_channel_list")).width(rect.width()).gap(CHANNEL_LIST_GAP).show(|ui| { + ui.set_min_width(rect.width()); + if ui.selectable_label(app.ui.layer_material_view, tr("Material")).clicked() { + app.ui.layer_material_view = true; + } + for channel in channels { + let picked = !app.ui.layer_material_view && app.ui.layer_channel == channel; + if ui.selectable_label(picked, tr(channel.label())).clicked() { + app.ui.layer_channel = channel; + app.ui.layer_material_view = false; + } + } + }); +} + +/// How far the open dropdown's tab reaches into its list, and how much of the seam under it the tab covers +const TAB_OVERLAP: f32 = 1.5; +const TAB_SEAM_COVER: f32 = 2.5; + +/// The tab's border width: the seam cover stays inside it and its left line runs on down over the seam +const TAB_BORDER_WIDTH: f32 = 1.0; + +/// A button with its icon and a caret whose menu hangs from it (caption, then the `items` built while it is open); the item picked +fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &str, items: impl FnOnce() -> Vec, tokens: &Tokens) -> Option { + let response = tip_above(ui.interact(rect, ui.scope_id().with(("layer_toolbar_menu", label)), Sense::click()), label); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let popup = ui.scope_id().with(("layer_toolbar_menu_popup", label)); + let open = egui::Popup::is_id_open(ui.ctx(), popup); + let painter = ui.painter(); + if response.hovered() && !open { + painter.rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button); + } + button_face(painter, rect, icon, tokens); + + // A click opens the menu this frame + let items = if open || response.clicked() { items() } else { Vec::new() }; + let width = menu_width(ui, &items); + let frame = Frame::NONE + .fill(tokens.chrome) + .stroke(Stroke::new(1.0, tokens.field_border)) + .corner_radius(CornerRadius { nw: 0, ..CornerRadius::same(MENU_ROUNDING) }) + .shadow(Shadow { offset: SHADOW_OFFSET, blur: 0, spread: 0, color: HARD_SHADOW }); + let mut picked = None; + let shown = egui::Popup::menu(&response).id(popup).align(egui::RectAlign::BOTTOM_START).gap(MENU_TAB_OVERLAP).frame(frame).width(width).show(|ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + ui.add_space(MENU_PADDING); + let (head, _) = ui.allocate_exact_size(vec2(width, MENU_CAPTION_HEIGHT - MENU_PADDING), Sense::hover()); + let caption = egui::RichText::new(caption.to_uppercase()).size(MENU_CAPTION_SIZE).strong().color(tokens.text_dim); + let galley = egui::WidgetText::from(caption).into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body); + ui.painter().galley(pos2(head.left() + MENU_CAPTION_X, head.center().y - galley.size().y * 0.5), galley, tokens.text_dim); + for item in &items { + if menu_row(ui, width, item, tokens).clicked() { + picked = Some(if item.command == BITMAP { Pick::Bitmap } else { Pick::Run { command: item.command, params: item.params.clone() } }); + ui.close(); + } + } + ui.add_space(MENU_PADDING); + }); + + // The open button becomes the menu's tab: same fill and border, no line between them + if let Some(shown) = shown { + let painter = ui.ctx().layer_painter(shown.response.layer_id); + let tab = Rect::from_min_max(rect.min, pos2(rect.right(), shown.response.rect.top() + TAB_OVERLAP)); + let top = CornerRadius { nw: CONTROL_ROUNDING, ne: CONTROL_ROUNDING, sw: 0, se: 0 }; + painter.rect(tab, top, tokens.chrome, Stroke::new(TAB_BORDER_WIDTH, tokens.field_border), StrokeKind::Inside); + painter.rect_filled( + Rect::from_min_max(pos2(tab.left() + TAB_BORDER_WIDTH, tab.bottom() - TAB_SEAM_COVER), pos2(tab.right() - TAB_BORDER_WIDTH, tab.bottom())), + CornerRadius::ZERO, + tokens.chrome, + ); + let border_x = tab.left() + TAB_BORDER_WIDTH * 0.5; + painter.vline(border_x, tab.bottom() - TAB_SEAM_COVER..=tab.bottom(), Stroke::new(TAB_BORDER_WIDTH, tokens.field_border)); + button_face(&painter, rect, icon, tokens); + } + picked +} + +/// A menu button's icon and caret +fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) { + let icon_at = pos2(rect.left() + MENU_ICON_X, rect.center().y); + match icon { + MenuIcon::Glyph(glyph) => { + painter.text(icon_at, Align2::CENTER_CENTER, glyph, FontId::proportional(MENU_ICON_SIZE), tokens.text); + } + MenuIcon::Mask => mask_icon(painter, icon_at, MASK_ICON_SIZE, tokens.text), + } + painter.text(pos2(rect.right() - MENU_CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_SIZE), tokens.text); +} + +/// The menu's width: its longest item, with room for the icons and the right edge +fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 { + let widest = items + .iter() + .map(|item| ui.fonts_mut(|fonts| fonts.layout_no_wrap(tr(item.short).to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x)) + .fold(0.0, f32::max); + (widest + MENU_TEXT_X + MENU_RIGHT).max(MENU_MIN_WIDTH) +} + +/// One menu row: hover face, icon, name; dim and unclickable when it can't go where the selection is +fn menu_row(ui: &mut Ui, width: f32, item: &AddItem, tokens: &Tokens) -> Response { + let sense = if item.enabled { Sense::click() } else { Sense::hover() }; + let (rect, response) = ui.allocate_exact_size(vec2(width, MENU_ROW), sense); + let label = tr(item.short); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, item.enabled, label)); + let painter = ui.painter(); + if item.enabled && response.hovered() { + painter.rect_filled(rect.shrink2(vec2(MENU_ROW_INSET, 0.0)), CornerRadius::same(MENU_ROW_ROUNDING), tokens.button); + } + let color = if item.enabled { tokens.text } else { tokens.text_dim }; + let icon_at = pos2(rect.left() + MENU_ITEM_ICON_X, rect.center().y); + match item.icon { + ItemIcon::Glyph(glyph) => { + painter.text(icon_at, Align2::CENTER_CENTER, glyph, FontId::proportional(MENU_ITEM_ICON_SIZE), color); + } + ItemIcon::Swatch(gray) => { + let swatch = Rect::from_center_size(icon_at, vec2(MENU_ITEM_SWATCH, MENU_ITEM_SWATCH)); + painter.rect( + swatch, + CornerRadius::same(MENU_ITEM_SWATCH_ROUNDING), + Color32::from_gray(gray), + Stroke::new(1.0, tokens.field_border), + StrokeKind::Inside, + ); + } + } + painter.text(pos2(rect.left() + MENU_TEXT_X, rect.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color); + response +} + +/// The tooltip of toolbar button `response`, above it so it covers none of the layer rows under the toolbar +fn tip_above(response: Response, text: &str) -> Response { + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(response.rect).align(egui::RectAlign::TOP).align_alternatives(&[egui::RectAlign::LEFT, egui::RectAlign::RIGHT]); + tooltip.show(|ui| ui.label(text)); + response +} + +/// A plain icon button of the row: a button face while hovered +fn plain_button(ui: &mut Ui, rect: Rect, glyph: &str, label: &str, tokens: &Tokens) -> Response { + let response = tip_above(ui.interact(rect, ui.scope_id().with(("layer_toolbar_button", glyph)), Sense::click()), label); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + if response.hovered() { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button); + } + ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), tokens.text); + response +} + +/// The outline width and corner rounding of a drawn toolbar icon +const ICON_LINE_WIDTH: f32 = 1.5; +const ICON_ROUNDING: u8 = 2; + +/// Add mask's icon: a square, half of it filled corner to corner +pub(crate) fn mask_icon(painter: &Painter, center: Pos2, size: f32, color: Color32) { + let half = size * 0.5; + let filled = vec![pos2(center.x + half, center.y - half), pos2(center.x + half, center.y + half), pos2(center.x - half, center.y + half)]; + painter.add(egui::Shape::convex_polygon(filled, color, Stroke::NONE)); + painter.rect_stroke( + Rect::from_center_size(center, vec2(size, size)), + CornerRadius::same(ICON_ROUNDING), + Stroke::new(ICON_LINE_WIDTH, color), + StrokeKind::Inside, + ); +} + +/// Selects `layer` when it isn't, runs `command` on it, and shows a filter Add filter added in Properties with its picker open +fn run_on(app: &mut TextureCraftApp, ui: &Ui, layer: LayerId, command: &str, params: Value) { + if app.session.selected_layer() != Some(layer) { + app.run("layer.select", json!({"layer": layer.0})); + } + let mut params = params; + if let Some(object) = params.as_object_mut() { + object.insert("layer".into(), json!(layer.0)); + } + let added = app.run(command, params); + if command == "effect.add.filter" + && let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64()) + { + app.ui.dock.focus(crate::docking::Panel::Properties); + crate::filter_slot::open_picker_when_shown(ui.ctx(), effect); + } +} + +/// The Add effect items for `layer`: on its content when the content is the selected target, else in its mask; an item that can't go there is greyed, not sent elsewhere (all of them without a layer) +fn effect_items(app: &TextureCraftApp, layer: Option<&Layer>) -> Vec { + let content = layer.is_some_and(|layer| !layer.is_group() && app.session.selected_layer() == Some(layer.id) && crate::dock::targets_content(app)); + let target = if content { "content" } else { "mask" }; + + // Generators, compare masks and colour selections go in masks only + let anywhere = layer.is_some(); + let mask_only = anywhere && !content; + let item = |icon, short, long, command, params: Value, enabled| AddItem { icon: ItemIcon::Glyph(icon), short, long, command, params, enabled }; + vec![ + item(ic::SPARKLE, n_("Generator"), n_("Add generator"), "effect.add.generator", json!({}), mask_only), + item(ic::PAINT_BRUSH, n_("Paint"), n_("Add paint"), "effect.add.paint", json!({"target": target}), anywhere), + item(ic::PAINT_BUCKET, n_("Fill"), n_("Add fill"), "effect.add.fill", json!({"target": target}), anywhere), + item(ic::CHART_BAR, n_("Levels"), n_("Add levels"), "effect.add.levels", json!({"target": target}), anywhere), + item(ic::SCALES, n_("Compare mask"), n_("Add compare mask"), "effect.add.compare", json!({}), mask_only), + item(ic::FUNNEL, n_("Filter"), n_("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER}), anywhere), + item(ic::SELECTION, n_("Color selection"), n_("Add color selection"), "effect.add.colorSelection", json!({}), mask_only), + item(ic::ANCHOR, n_("Anchor point"), n_("Add anchor point"), "effect.add.anchor", json!({"target": target}), anywhere), + ] +} + +/// The command of Add mask's Bitmap: the texture picker opens first and adds the mask with the picked texture +const BITMAP: &str = "mask.add.bitmap"; + +/// The Add mask items: a layer that has a mask of its own adds to it through Add effect instead +fn mask_items(layer: Option<&Layer>) -> Vec { + let enabled = layer.is_some_and(|layer| layer.mask.is_none()); + let item = |icon, short, long, command| AddItem { icon, short, long, command, params: json!({}), enabled }; + vec![ + item(ItemIcon::Swatch(WHITE_SWATCH), n_("White"), n_("Add white mask"), "mask.add.white"), + item(ItemIcon::Swatch(BLACK_SWATCH), n_("Black"), n_("Add black mask"), "mask.add.black"), + item(ItemIcon::Glyph(ic::IMAGE), n_("Bitmap"), n_("Add bitmap mask"), BITMAP), + item(ItemIcon::Glyph(ic::SELECTION), n_("Color selection"), n_("Add mask with color selection"), "mask.add.colorSelection"), + item(ItemIcon::Glyph(ic::SCALES), n_("Height combination"), n_("Add mask with height combination"), "mask.add.heightCombination"), + ] +} + +/// The layer context menu's Add effect items (its own buttons, the long names) +pub(crate) fn effect_menu_items(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { + for item in effect_items(app, Some(layer)) { + let text = format!("{} {}", icon_of(item.icon), tr(item.long)); + if ui.add_enabled(item.enabled, egui::Button::new(text)).clicked() { + run_on(app, ui, layer.id, item.command, item.params); + ui.close(); + } + } +} + +/// The Add mask items of a layer row's empty mask slot (the long names); Bitmap opens the picker under the layer row +pub(crate) fn mask_slot_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, picker: Id) { + for item in mask_items(Some(layer)) { + if ui.add_enabled(item.enabled, egui::Button::new(tr(item.long))).clicked() { + if item.command == BITMAP { + resource_picker::toggle(ui.ctx(), picker); + } else { + run_on(app, ui, layer.id, item.command, item.params); + } + ui.close(); + } + } +} + +fn icon_of(icon: ItemIcon) -> &'static str { + match icon { + ItemIcon::Glyph(glyph) => glyph, + ItemIcon::Swatch(_) => ic::SQUARE, + } +} + +/// The texture picker of Add bitmap mask, hanging under `anchor` at its width while open: a pick adds the mask to `layer`, Escape or a click elsewhere adds nothing +pub(crate) fn bitmap_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id, layer: LayerId) { + let ctx = anchor.ctx.clone(); + let images = &app.session.images; + let tabs = |thumbs: &mut Thumbs| bitmap_tabs(thumbs, &ctx, images); + match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) { + Some(BitmapChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(BitmapChoice::Image(name)) => { + app.run("layer.select", json!({"layer": layer.0})); + app.run(BITMAP, json!({"layer": layer.0, "image": name})); + } + Some(BitmapChoice::Alpha(alpha)) => { + app.run("layer.select", json!({"layer": layer.0})); + app.run(BITMAP, json!({"layer": layer.0, "alpha": alpha})); + } + None => {} + } +} + +/// The bitmap picker's one tab: Textures (Import... first) and the Alphas in their shelf groups +fn bitmap_tabs(thumbs: &mut Thumbs, ctx: &egui::Context, images: &ImageStore) -> Vec> { + let tile = |id, label: &str, caption, picture| ResourcePickerItem { id, label: label.to_owned(), caption, picture }; + let textures = ResourcePickerItem::textures(images, BitmapChoice::Import, |name| BitmapChoice::Image(name.to_owned())); + let alphas = alphas::library() + .iter() + .map(|alpha| tile(BitmapChoice::Alpha(alpha.id.as_str()), tr(&alpha.label), Some(tr(alpha.category)), TilePicture::Texture(thumbs.alpha(ctx, alpha)))) + .collect(); + let groups = vec![PickerGroup { header: Some(tr("Textures")), items: textures }, PickerGroup { header: Some(tr("Alphas")), items: alphas }]; + vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }] +} diff --git a/crates/ui-egui/src/layer_toolbar/add_item.rs b/crates/ui-egui/src/layer_toolbar/add_item.rs new file mode 100644 index 00000000..8e44a94c --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/add_item.rs @@ -0,0 +1,14 @@ +use serde_json::Value; + +use super::ItemIcon; + +/// One item of the Add effect or Add mask menu +pub(super) struct AddItem { + pub(super) icon: ItemIcon, + /// The toolbar menu's name (the button says "Add effect" / "Add mask") and the layer context menu's + pub(super) short: &'static str, + pub(super) long: &'static str, + pub(super) command: &'static str, + pub(super) params: Value, + pub(super) enabled: bool, +} diff --git a/crates/ui-egui/src/layer_toolbar/bitmap_choice.rs b/crates/ui-egui/src/layer_toolbar/bitmap_choice.rs new file mode 100644 index 00000000..3a0d637e --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/bitmap_choice.rs @@ -0,0 +1,7 @@ +/// What the bitmap picker offers: Import..., an image resource, a library alpha +#[derive(Clone, PartialEq)] +pub(super) enum BitmapChoice { + Import, + Image(String), + Alpha(&'static str), +} diff --git a/crates/ui-egui/src/layer_toolbar/item_icon.rs b/crates/ui-egui/src/layer_toolbar/item_icon.rs new file mode 100644 index 00000000..b5875428 --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/item_icon.rs @@ -0,0 +1,7 @@ +/// What an Add menu item shows at its left +#[derive(Clone, Copy)] +pub(super) enum ItemIcon { + Glyph(&'static str), + /// A gray swatch (Add mask's White and Black) + Swatch(u8), +} diff --git a/crates/ui-egui/src/layer_toolbar/menu_icon.rs b/crates/ui-egui/src/layer_toolbar/menu_icon.rs new file mode 100644 index 00000000..adfcff01 --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/menu_icon.rs @@ -0,0 +1,7 @@ +/// The icon of a menu button +#[derive(Clone, Copy)] +pub(super) enum MenuIcon { + Glyph(&'static str), + /// Add mask's square, half of it filled corner to corner + Mask, +} diff --git a/crates/ui-egui/src/layer_toolbar/pick.rs b/crates/ui-egui/src/layer_toolbar/pick.rs new file mode 100644 index 00000000..743293e0 --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/pick.rs @@ -0,0 +1,7 @@ +use serde_json::Value; + +/// What a click in one of the row's menus asks for, done once the menu has closed +pub(super) enum Pick { + Run { command: &'static str, params: Value }, + Bitmap, +} diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs new file mode 100644 index 00000000..004be414 --- /dev/null +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -0,0 +1,198 @@ +//! The Layers panel's top row: Add effect greys what can't go where the selection is, Add mask adds a mask with its effect, and +//! Bitmap adds nothing until a texture is picked + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source}; +use texturecraft_engine::paint::alphas; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, click_widget}; + +/// Tall enough for the toolbar, the layer rows and their menus at once +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1200.0); + +/// Frames past the tooltip delay at the harness's step +const TOOLTIP_DELAY_FRAMES: usize = 60; + +/// Slack, in points, for a list row that starts on the list's own bottom edge +const EDGE_TOLERANCE: f32 = 1.0; + +/// The app with a selected fill layer, its content the target +fn app() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, layer) +} + +/// Opens the row's menu `menu` and clicks its item `item` +fn pick(harness: &mut Harness<'_, TextureCraftApp>, menu: &str, item: &str) { + click_widget(harness, Role::Button, menu); + click_widget(harness, Role::Button, item); +} + +fn mask_kinds(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Vec { + let project = &harness.state().session.doc.project; + project.layer(layer).unwrap().mask.as_ref().map(|mask| mask.effects.iter().map(|effect| effect.kind.clone()).collect()).unwrap_or_default() +} + +#[test] +fn add_effect_greys_mask_only_effects_on_the_content_and_adds_them_in_the_mask() { + let (mut harness, layer) = app(); + let steps = harness.state().session.history_labels().len(); + for item in ["Compare mask", "Color selection", "Generator"] { + pick(&mut harness, "Add effect", item); + assert_eq!(harness.state().session.history_labels().len(), steps, "{item} is greyed on the layer content, not sent to the mask"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + } + assert!(harness.state().session.doc.project.layer(layer).unwrap().mask.is_none()); + + harness.state_mut().run("mask.add.white", json!({"layer": layer.0})); + harness.run_steps(SETTLE_FRAMES); + pick(&mut harness, "Add effect", "Color selection"); + let kinds = mask_kinds(&harness, layer); + assert!(matches!(kinds.as_slice(), [EffectKind::ColorSelection(_)]), "{kinds:?}"); + let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap(); + let added = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::ColorSelection(_))).unwrap().id; + assert_eq!(harness.state().session.target, StackTarget::Effect(added), "the new colour selection is selected"); +} + +#[test] +fn add_mask_adds_a_height_combination_and_greys_once_the_layer_has_a_mask() { + let (mut harness, layer) = app(); + pick(&mut harness, "Add mask", "Height combination"); + let kinds = mask_kinds(&harness, layer); + assert!(matches!(kinds.as_slice(), [EffectKind::Compare { .. }]), "{kinds:?}"); + + let steps = harness.state().session.history_labels().len(); + pick(&mut harness, "Add mask", "White"); + assert_eq!(harness.state().session.history_labels().len(), steps, "a layer with a mask adds to it through Add effect"); +} + +#[test] +fn bitmap_opens_the_texture_picker_and_adds_the_mask_only_once_one_is_picked() { + let (mut harness, layer) = app(); + pick(&mut harness, "Add mask", "Bitmap"); + assert!(egui::Popup::is_any_open(&harness.ctx), "Bitmap opens the texture picker"); + assert!(harness.state().session.doc.project.layer(layer).unwrap().mask.is_none(), "no mask until a texture is picked"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(harness.state().session.doc.project.layer(layer).unwrap().mask.is_none(), "Escape adds nothing"); + + let alpha = alphas::find("round_soft").unwrap(); + pick(&mut harness, "Add mask", "Bitmap"); + let tile = harness.get_by_label(&alpha.label).rect(); + click_at(&mut harness, tile.center()); + let kinds = mask_kinds(&harness, layer); + let name = texturecraft_engine::fill_alpha::resource_name(alpha); + assert!(matches!(kinds.as_slice(), [EffectKind::Fill { source: Source::Image { name: read, .. }, .. }] if *read == name), "{kinds:?}"); +} + +/// The Bitmap picker belongs to the layer that opened it: when an agent selects another layer it closes, and a click where its tile was masks neither +#[test] +fn the_bitmap_picker_closes_when_the_selection_moves_and_masks_no_other_layer() { + let (mut harness, opener) = app(); + let other = LayerId(harness.state_mut().run("layer.add.fill", Value::Null).unwrap()["layer"].as_u64().unwrap()); + harness.state_mut().run("layer.select", json!({"layer": opener.0})); + harness.run_steps(SETTLE_FRAMES); + pick(&mut harness, "Add mask", "Bitmap"); + let alpha = alphas::find("round_soft").unwrap(); + let tile = harness.get_by_label(&alpha.label).rect(); + + harness.state_mut().run("layer.select", json!({"layer": other.0})); + harness.run_steps(SETTLE_FRAMES); + let still_open = egui::Popup::is_any_open(&harness.ctx); + click_at(&mut harness, tile.center()); + + assert!(!still_open, "the picker closes with its layer's selection"); + assert!(mask_kinds(&harness, other).is_empty(), "the pick never masks the newly selected layer"); + assert!(mask_kinds(&harness, opener).is_empty(), "nor the layer that opened it"); +} + +/// A floating Layers panel this narrow cannot hold the toolbar on one row +const NARROW_LAYERS: [f32; 4] = [600.0, 200.0, 200.0, 400.0]; + +/// In a narrow floating Layers panel the add-layer buttons and Remove wrap inside it, where a click still reaches them +#[test] +fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() { + use craft_ui::docking::Action; + use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; + + let (mut harness, _) = app(); + let mut workspace = harness.state().ui.dock.workspace().clone(); + workspace.apply_all([Action::Float { panel: Panel::Layers, rect: NARROW_LAYERS }], permissions).unwrap(); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); + harness.run_steps(SETTLE_FRAMES); + let [left, _, width, _] = NARROW_LAYERS; + + for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add folder", "Remove layer"] { + let button = harness.query_all_by_label_contains(label).find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect(); + assert!(button.left() >= left && button.right() <= left + width, "{label} at {button:?} stays inside the panel"); + } + + let layers = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers.len(); + let before = layers(&harness); + let folder = harness.get_by_role_and_label(Role::Button, "Add folder").rect(); + click_at(&mut harness, folder.center()); + assert_eq!(layers(&harness), before + 1, "Add folder answers a click"); + let remove = harness.query_all_by_label_contains("Remove layer").find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect(); + click_at(&mut harness, remove.center()); + assert_eq!(layers(&harness), before, "and Remove does"); +} + +#[test] +fn a_toolbar_tooltip_shows_above_its_button_off_the_layer_rows() { + let (mut harness, _) = app(); + let button = harness.get_by_role_and_label(Role::Button, "Add effect").rect(); + harness.hover_at(button.center()); + + // Past the tooltip delay + harness.run_steps(TOOLTIP_DELAY_FRAMES); + let tip = + harness.get_all_by_label("Add effect").find(|node| node.accesskit_node().role() == Role::Label).map(|node| node.rect()).expect("the button's tooltip"); + assert!(tip.bottom() <= button.top(), "the tooltip sits above the toolbar: {tip:?} {button:?}"); +} + +/// Where the Layers panel's channel list shows `current`, if it does (the topmost list showing it: Properties sits below) +fn channel_list(harness: &Harness<'_, TextureCraftApp>, current: &str) -> Option { + harness.query_all_by_role_and_label(Role::ComboBox, current).map(|node| node.rect()).min_by(|a, b| a.top().total_cmp(&b.top())) +} + +/// Opens the Layers panel's channel list showing `current` and picks `item` in it (the nearest `item` under the list) +fn pick_channel(harness: &mut Harness<'_, TextureCraftApp>, current: &str, item: &str) { + let list = channel_list(harness, current).unwrap(); + click_at(harness, list.center()); + + let below = |rect: egui::Rect| rect.top() >= list.bottom() - EDGE_TOLERANCE && rect.left() < list.right() && rect.right() > list.left(); + let row = harness.query_all_by_label(item).map(|node| node.rect()).filter(|rect| below(*rect)).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap(); + + // A real press and release on the row, as a mouse would + click_at(harness, row.center()); +} + +#[test] +fn the_channel_list_starts_on_material_and_picks_a_channel_or_material_again() { + let (mut harness, _) = app(); + let start = channel_list(&harness, "Material"); + assert!(start.is_some(), "the list starts on the whole material"); + + pick_channel(&mut harness, "Material", "Roughness"); + + assert_eq!(channel_list(&harness, "Roughness"), start, "the list shows the channel picked"); + assert!(!harness.state().ui.layer_material_view); + assert_eq!(harness.state().ui.layer_channel, Channel::Roughness); + + pick_channel(&mut harness, "Roughness", "Material"); + + assert!(harness.state().ui.layer_material_view, "Material shows the whole material again"); + assert_eq!(harness.state().ui.layer_channel, Channel::Roughness, "the rows keep the last channel's blending"); +} From 2eeadf2d71fe7c1110f1263762a08897c761d038 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:59 +0000 Subject: [PATCH 035/153] Filters: the filter library and its maths (blur, bevel, glow, drop shadow, baked lighting, gradients, shape filters) --- crates/compose/src/distance_envelope.rs | 64 + crates/compose/src/environment_sh.rs | 194 +++ crates/compose/src/environment_sky.rs | 164 +++ crates/compose/src/soft_box.rs | 30 + crates/compose/src/warp_source_sample.rs | 59 + crates/compose/src/warp_texel.rs | 76 ++ crates/core/src/color_match.rs | 116 ++ crates/core/src/ramp_curve.rs | 38 + crates/core/src/source_warp.rs | 135 ++ crates/core/src/stylized_shading.rs | 193 +++ crates/core/src/unit_value.rs | 33 + crates/core/src/warp_source.rs | 64 + crates/engine/src/filter_lib.rs | 1131 ++++++++++++++--- crates/engine/src/stylized_lighting_params.rs | 99 ++ crates/engine/tests/it/filter_stylize.rs | 242 ++++ crates/engine/tests/it/filter_support.rs | 47 + 16 files changed, 2529 insertions(+), 156 deletions(-) create mode 100644 crates/compose/src/distance_envelope.rs create mode 100644 crates/compose/src/environment_sh.rs create mode 100644 crates/compose/src/environment_sky.rs create mode 100644 crates/compose/src/soft_box.rs create mode 100644 crates/compose/src/warp_source_sample.rs create mode 100644 crates/compose/src/warp_texel.rs create mode 100644 crates/core/src/color_match.rs create mode 100644 crates/core/src/ramp_curve.rs create mode 100644 crates/core/src/source_warp.rs create mode 100644 crates/core/src/stylized_shading.rs create mode 100644 crates/core/src/unit_value.rs create mode 100644 crates/core/src/warp_source.rs create mode 100644 crates/engine/src/stylized_lighting_params.rs create mode 100644 crates/engine/tests/it/filter_stylize.rs diff --git a/crates/compose/src/distance_envelope.rs b/crates/compose/src/distance_envelope.rs new file mode 100644 index 00000000..d78ea341 --- /dev/null +++ b/crates/compose/src/distance_envelope.rs @@ -0,0 +1,64 @@ +//! The lower envelope of parabolas that turns a line of squared distances into each place's squared distance to the nearest feature + +/// The lower envelope of the parabolas over a line of squared distances, which gives each place's squared distance to the nearest feature along it and the line before +#[derive(Default)] +pub(crate) struct DistanceEnvelope { + /// The parabolas still lowest somewhere: their vertex and where their stretch begins + parabolas: Vec<(usize, f64)>, + /// The line as it was + heights: Vec, +} + +impl DistanceEnvelope { + /// Replace `line` with each place's squared distance to the nearest feature + pub(crate) fn lower(&mut self, line: &mut [f32]) { + self.heights.clear(); + self.heights.extend_from_slice(line); + self.parabolas.clear(); + let heights = &self.heights; + + // In f64, where squared places and their sums stay exact past 4096 texels and a wide line cannot overflow a 32-bit usize + let lifted = |at: usize| f64::from(heights.get(at).copied().unwrap_or(f32::MAX)) + at as f64 * at as f64; + for at in 0..heights.len() { + let mut start = f64::NEG_INFINITY; + while let Some(&(vertex, from)) = self.parabolas.last() { + let crossing = (lifted(at) - lifted(vertex)) / (2.0 * (at - vertex) as f64); + if crossing <= from { + self.parabolas.pop(); + } else { + start = crossing; + break; + } + } + self.parabolas.push((at, start)); + } + + let mut current = 0; + for (at, out) in line.iter_mut().enumerate() { + while self.parabolas.get(current + 1).is_some_and(|(_, from)| *from < at as f64) { + current += 1; + } + if let Some(&(vertex, _)) = self.parabolas.get(current) { + *out = (at as f32 - vertex as f32).powi(2) + heights.get(vertex).copied().unwrap_or(f32::MAX); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Past 4096 texels a squared place is no longer exact in f32: two close features at the end of a wide line still each read 0 + #[test] + fn close_features_far_along_a_wide_line_stay_exact() { + const FAR: f32 = 4.0e8; + let mut line = vec![FAR; 10_000]; + line[9_950] = 1.0; + line[9_951] = 0.0; + + DistanceEnvelope::default().lower(&mut line); + + assert_eq!(line[9_949..9_954], [2.0, 1.0, 0.0, 1.0, 4.0]); + } +} diff --git a/crates/compose/src/environment_sh.rs b/crates/compose/src/environment_sh.rs new file mode 100644 index 00000000..30a2d847 --- /dev/null +++ b/crates/compose/src/environment_sh.rs @@ -0,0 +1,194 @@ +//! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it + +use std::sync::{Arc, Mutex}; + +use texturecraft_core::project::DisplaySettings; +use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3}; +use texturecraft_geom::glam::Vec3; + +use crate::environment_sky::{VIEWPORT_WIDTH, dir_of, environment_linear, radiance, sh_basis, sh9_averaged}; +use crate::store::{ImageRes, ImageStore}; + +/// The diffuse light of the viewport environment and the turn the viewport gives it +pub struct EnvironmentSh { + coefficients: [[f32; 3]; 9], + /// The viewport's environment rotation (radians) + rotation: f32, +} + +/// The environment the last coefficients were worked out for: a built-in by name, or an imported image (held, so it is not a different image at the same address) +type CacheEntry = (String, Option>, Arc<[[f32; 3]; 9]>); + +static CACHE: Mutex> = Mutex::new(None); + +impl EnvironmentSh { + /// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment + pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh { + let image = display.environment_resource().and_then(|name| images.get(name)).cloned(); + let same = |entry: &CacheEntry| match (&entry.1, &image) { + (Some(held), Some(image)) => Arc::ptr_eq(held, image), + (None, None) => entry.0 == display.environment, + _ => false, + }; + let rotation = display.env_rotation.to_radians(); + + let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2.clone()); + if let Some(coefficients) = cached { + return EnvironmentSh { coefficients: *coefficients, rotation }; + } + + // Worked out with the cache unlocked: the averaging runs on the thread pool, where a worker holding the lock could take another tile's task that waits for it + let coefficients = match &image { + Some(image) => image_sh(image), + None => built_in_sh(&display.environment), + }; + *CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image, Arc::new(coefficients))); + EnvironmentSh { coefficients, rotation } + } + + /// The diffuse light reaching a surface facing world direction `normal` with the environment turned `horizontal` and tilted `vertical` (radians) past the viewport's turn + pub fn irradiance(&self, normal: Vec3, horizontal: f32, vertical: f32) -> Vec3 { + let (sin_tilt, cos_tilt) = vertical.sin_cos(); + let tilted = Vec3::new(normal.x, cos_tilt * normal.y - sin_tilt * normal.z, sin_tilt * normal.y + cos_tilt * normal.z); + + // Turned as the viewport turns its environment + let (sin_turn, cos_turn) = (self.rotation + horizontal).sin_cos(); + let direction = Vec3::new(cos_turn * tilted.x - sin_turn * tilted.z, tilted.y, sin_turn * tilted.x + cos_turn * tilted.z); + let light = sh_basis(direction).iter().zip(&self.coefficients).fold(Vec3::ZERO, |sum, (basis, coefficient)| sum + Vec3::from(*coefficient) * *basis); + light.max(Vec3::ZERO) + } + + /// Baked Lighting Environment's lit base color: linear `albedo`, its metal read from `channels` (straight values by [`Channel::index`]), in `light` (the environment's diffuse light at the surface, exposure applied), darkened by ambient occlusion `ao` by `[diffuse, specular]` occlusion. The viewer looks straight at the surface, so what it reflects is the light around the normal + pub fn shade(albedo: [f32; 3], light: Vec3, ao: f32, [diffuse_occlusion, specular_occlusion]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] { + let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 }; + let metal = finite_unit(channels.get(Channel::Metallic.index()).map_or(0.0, |m| m[0])); + let f0 = mix3([DIELECTRIC_REFLECTANCE; 3], albedo, metal); + let diffuse = 1.0 + (ao - 1.0) * finite_unit(diffuse_occlusion); + let specular = 1.0 + (ao - 1.0) * finite_unit(specular_occlusion); + let incoming = light.to_array(); + std::array::from_fn(|k| finite_unit(albedo[k] * (1.0 - metal) * incoming[k] * diffuse + f0[k] * incoming[k] * specular)) + } +} + +/// The coefficients of built-in environment `name` as the viewport works them out: drawn at its width, then averaged +fn built_in_sh(name: &str) -> [[f32; 3]; 9] { + let (width, height) = (VIEWPORT_WIDTH, VIEWPORT_WIDTH / 2); + sh9_averaged(width, height, |x, y| radiance(name, dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32))) +} + +/// The coefficients of an imported equirect image, every texel averaged in as the viewport does +fn image_sh(image: &ImageRes) -> [[f32; 3]; 9] { + let linear = |v: f32| environment_linear(v, image.srgb); + sh9_averaged(image.width, image.height, |x, y| { + let texel = image.rgba.get((y as usize) * image.width as usize + x as usize).copied().unwrap_or([0.0; 4]); + Vec3::new(linear(texel[0]), linear(texel[1]), linear(texel[2])) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A uniform environment lights every direction alike, whatever the turn; brighter skies light more + #[test] + fn a_uniform_image_lights_every_way_alike() { + let image = |v: f32| ImageRes { width: 32, height: 16, rgba: vec![[v, v, v, 1.0]; 32 * 16], srgb: false, mips: Default::default() }; + let sh = EnvironmentSh { coefficients: image_sh(&image(0.5)), rotation: 1.0 }; + for normal in [Vec3::Y, Vec3::X, Vec3::NEG_Y, Vec3::new(0.6, 0.0, 0.8)] { + let light = sh.irradiance(normal, 0.3, 0.7); + assert!((light - Vec3::splat(0.5)).abs().max_element() < 0.02, "{normal}: {light}"); + } + } + + /// The studio's key light is up and to one side: a surface facing up gets more light than one facing down, and turning the environment moves the light around + #[test] + fn a_built_in_lights_by_where_the_surface_faces_and_turns() { + let display = DisplaySettings { environment: "Studio Soft".into(), ..DisplaySettings::default() }; + let sh = EnvironmentSh::of(&display, &ImageStore::default()); + assert!(sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum() > 2.0 * sh.irradiance(Vec3::NEG_Y, 0.0, 0.0).element_sum()); + let side = Vec3::new(0.7, 0.0, 0.7).normalize(); + let (here, turned) = (sh.irradiance(side, 0.0, 0.0), sh.irradiance(side, std::f32::consts::PI, 0.0)); + assert!((here - turned).abs().max_element() > 0.05, "{here} vs {turned}"); + let night = EnvironmentSh::of(&DisplaySettings { environment: "Night".into(), ..DisplaySettings::default() }, &ImageStore::default()); + assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment"); + } + + /// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock + #[test] + fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() { + use rayon::prelude::*; + + const WORKERS: usize = 8; + const TILES: usize = 1024; + // One tile in so many asks for the light; the rest finish at once, so their workers are free to steal the averaging's work + const LIT_EVERY: usize = 128; + const ROUNDS: usize = 20; + const PATIENCE: std::time::Duration = std::time::Duration::from_secs(60); + + let (done, finished) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let Ok(pool) = rayon::ThreadPoolBuilder::new().num_threads(WORKERS).build() else { return }; + pool.install(|| { + for round in 0..ROUNDS { + // Each round shows another environment, so its first tile misses the cache + let environment = if round % 2 == 0 { "Sunset" } else { "Night" }; + let display = DisplaySettings { environment: environment.into(), ..DisplaySettings::default() }; + (0..TILES).into_par_iter().filter(|tile| tile % LIT_EVERY == 0).for_each(|_| { + EnvironmentSh::of(&display, &ImageStore::default()); + }); + } + }); + let _ = done.send(()); + }); + assert!(finished.recv_timeout(PATIENCE).is_ok(), "the tiles deadlocked on the cache"); + } + + /// Diffuse occlusion darkens non-metals by the ambient occlusion; metals take their light from the reflections, which only specular occlusion darkens + #[test] + fn occlusion_darkens_the_diffuse_and_the_reflections_apart() { + let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect(); + let light = Vec3::splat(1.0); + let dielectric = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0]; + assert!(dielectric([1.0, 0.0]) < dielectric([0.0, 0.0]) * 0.5); + channels[Channel::Metallic.index()] = [1.0; 3]; + let metal = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0]; + assert_eq!(metal([1.0, 0.0]), metal([0.0, 0.0])); + assert!(metal([0.0, 1.0]) < metal([0.0, 0.0]) * 0.5); + } + + /// The coefficients of `radiance` read at every place of a fine grid, the integral the averaged ones must match + fn fine_sh(width: u32, radiance: impl Fn(Vec3) -> Vec3) -> [[f32; 3]; 9] { + let height = width / 2; + crate::environment_sky::sh9(width, height, |x, y| radiance(dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32))) + } + + /// Sunset's sun is smaller than a texel of a coarse grid: averaging the viewport's drawing keeps its light, as the viewport does + #[test] + fn a_small_sun_lights_as_the_viewport_shows_it() { + let display = DisplaySettings { environment: "Sunset".into(), ..DisplaySettings::default() }; + + let baked = EnvironmentSh::of(&display, &ImageStore::default()).coefficients; + let fine = fine_sh(1024, |direction| radiance("Sunset", direction)); + + for (baked, fine) in baked.iter().zip(&fine) { + for (baked, fine) in baked.iter().zip(fine) { + assert!((baked - fine).abs() < 0.02, "{baked} vs {fine}"); + } + } + } + + /// An imported image's small bright patch counts though it falls between the texels a coarse read would take + #[test] + fn a_small_bright_patch_of_an_image_counts() { + const BRIGHT: f32 = 500.0; + let (width, height) = (1024u32, 512u32); + let patch = |x: u32, y: u32| (97..101).contains(&x) && (193..197).contains(&y); + let rgba = (0..width * height).map(|i| if patch(i % width, i / width) { [BRIGHT, BRIGHT, BRIGHT, 1.0] } else { [0.0, 0.0, 0.0, 1.0] }).collect(); + let image = ImageRes { width, height, rgba, srgb: false, mips: Default::default() }; + + let averaged = image_sh(&image)[0][0]; + let exact = crate::environment_sky::sh9(width, height, |x, y| if patch(x, y) { Vec3::splat(BRIGHT) } else { Vec3::ZERO })[0][0]; + + assert!(exact > 0.01 && (averaged - exact).abs() < exact * 0.05, "{averaged} vs {exact}"); + } +} diff --git a/crates/compose/src/environment_sky.rs b/crates/compose/src/environment_sky.rs new file mode 100644 index 00000000..0c37ccd2 --- /dev/null +++ b/crates/compose/src/environment_sky.rs @@ -0,0 +1,164 @@ +//! The built-in environments (drawn in code, no image assets) and their diffuse light as spherical harmonics, for the viewport and Baked Lighting Environment + +use std::f32::consts::{PI, TAU}; + +use rayon::prelude::*; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::soft_box::SoftBox; + +/// The width the viewport draws a built-in environment at (half as tall) +pub const VIEWPORT_WIDTH: u32 = 512; + +/// The width an environment is box-averaged down to before its diffuse light is worked out: averaging keeps a sun smaller than a texel +const SH_WIDTH: u32 = 128; + +/// The brightest radiance the viewport keeps of an imported environment (it stores half floats) +const HALF_FLOAT_MAX: f32 = 65_000.0; + +/// The irradiance convolution factor of each SH band (the cosine lobe's π, 2π/3 and π/4), one per coefficient +const COSINE_LOBE_BANDS: [f32; 9] = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0]; + +/// The linear radiance of a component `v` of an imported environment's texel (sRGB-encoded when `srgb`): not a number is 0, capped at the half-float range, sRGB at 1 +pub fn environment_linear(v: f32, srgb: bool) -> f32 { + let v = if v.is_finite() { v.clamp(0.0, HALF_FLOAT_MAX) } else { 0.0 }; + if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v } +} + +/// The direction at equirect place `u = φ / 2π`, `v = θ / π`: `(sin θ cos φ, cos θ, sin θ sin φ)`, row 0 straight up +pub fn dir_of(u: f32, v: f32) -> Vec3 { + let (theta, phi) = (v * PI, u * TAU); + Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin()) +} + +/// The equirect place of direction `d` +pub fn uv_of(d: Vec3) -> Vec2 { + let phi = d.z.atan2(d.x); + Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI) +} + +/// Smoothstep of `t` over 0..1 +pub(crate) fn smooth(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// How fast a sky turns from its horizon to its zenith and to its ground (powers of the height; under 1 turns early) +const ZENITH_FALLOFF: f32 = 0.6; +const GROUND_FALLOFF: f32 = 0.25; + +/// A sky blending `horizon` up to `zenith` and down to `ground` +fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 { + if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(ZENITH_FALLOFF)) } else { horizon.lerp(ground, (-d.y).powf(GROUND_FALLOFF)) } +} + +/// The Sunset sun's disc: the cosine of its edge from the centre, the width of its soft rim, and its brightness +const SUN_EDGE_COS: f32 = 0.9985; +const SUN_EDGE_WIDTH: f32 = 0.0012; +const SUN_RADIANCE: f32 = 120.0; + +/// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio) +pub fn radiance(name: &str, d: Vec3) -> Vec3 { + match name { + "Studio Contrast" => { + let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01)); + base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d) + + SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d) + } + "Overcast" => { + let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15)); + base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(d) + } + "Sunset" => { + let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); + let sun_dir = dir_of(0.12, 0.47); + let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE; + base + Vec3::new(1.0, 0.6, 0.3) * sun + } + "Warehouse" => { + let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06)); + for k in 0..6 { + c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d); + } + c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d) + } + "Night" => { + let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005)); + base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d) + + SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d) + } + + // "Studio Soft" (default) + _ => { + let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07)); + base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d) + + SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d) + + SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d) + } + } +} + +/// The 9 real spherical-harmonics basis functions at unit direction `d` (the standard band 0..2 constants) +pub fn sh_basis(d: Vec3) -> [f32; 9] { + let (x, y, z) = (d.x, d.y, d.z); + [ + 0.282_095, + 0.488_603 * y, + 0.488_603 * z, + 0.488_603 * x, + 1.092_548 * x * y, + 1.092_548 * y * z, + 0.315_392 * (3.0 * z * z - 1.0), + 1.092_548 * x * z, + 0.546_274 * (x * x - y * y), + ] +} + +/// Diffuse irradiance as 9 SH coefficients of the equirect image `width` x `height` whose texels `radiance` gives (already convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance) +pub fn sh9(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3) -> [[f32; 3]; 9] { + let (w, h) = (width.max(1), height.max(1)); + let mut sums = [Vec3::ZERO; 9]; + for y in 0..h { + let theta = PI * (y as f32 + 0.5) / h as f32; + let solid_angle = (TAU / w as f32) * (PI / h as f32) * theta.sin(); + for x in 0..w { + let direction = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); + + // No firefly clamp: the projection integrates, so a bright sun lights diffuse fully + let weighted = radiance(x, y) * solid_angle; + for (sum, basis) in sums.iter_mut().zip(sh_basis(direction)) { + *sum += weighted * basis; + } + } + } + std::array::from_fn(|k| (sums[k] * COSINE_LOBE_BANDS[k] / PI).to_array()) +} + +/// [`sh9`] of the equirect image `width` x `height` whose texels `radiance` gives, box-halved while wider than [`SH_WIDTH`] (an odd last row or column is dropped, as the viewport drops it) +pub fn sh9_averaged(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3 + Sync) -> [[f32; 3]; 9] { + if width <= SH_WIDTH { + return sh9(width, height, radiance); + } + + let mut image = half(width, height, radiance); + while image.0 > SH_WIDTH { + let (w, h, data) = ℑ + image = half(*w, *h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO)); + } + let (w, h, data) = image; + sh9(w, h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO)) +} + +/// The equirect image `width` x `height` whose texels `texel` gives, box-downsampled by 2 (wrapping around, clamped at the poles): its width, height and texels +pub fn half(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> (u32, u32, Vec) { + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + let get = |x: u32, y: u32| texel(x % width.max(1), y.min(height.saturating_sub(1))); + let mut data = vec![Vec3::ZERO; (w * h) as usize]; + data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| { + for (x, texel) in row.iter_mut().enumerate() { + let (sx, sy) = (x as u32 * 2, y as u32 * 2); + *texel = (get(sx, sy) + get(sx + 1, sy) + get(sx, sy + 1) + get(sx + 1, sy + 1)) * 0.25; + } + }); + (w, h, data) +} diff --git a/crates/compose/src/soft_box.rs b/crates/compose/src/soft_box.rs new file mode 100644 index 00000000..b1fba4f7 --- /dev/null +++ b/crates/compose/src/soft_box.rs @@ -0,0 +1,30 @@ +//! A soft rectangular light of the built-in environments + +use texturecraft_geom::glam::Vec3; + +/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees) +pub(crate) struct SoftBox { + pub azimuth: f32, + pub elevation: f32, + pub half_width: f32, + pub half_height: f32, + pub color: Vec3, +} + +/// Where the light starts to fade, as a share of its half size, and over how much of it +const EDGE_FADE_START: f32 = 0.8; +const EDGE_FADE_WIDTH: f32 = 0.4; + +impl SoftBox { + /// The light the box sends along direction `d` + pub fn eval(&self, d: Vec3) -> Vec3 { + let elevation = d.y.clamp(-1.0, 1.0).asin().to_degrees(); + let azimuth = d.z.atan2(d.x).to_degrees(); + + // The azimuth difference wrapped to -180..180 degrees + let azimuth_step = ((azimuth - self.azimuth + 540.0).rem_euclid(360.0)) - 180.0; + let (x, y) = (azimuth_step.abs() / self.half_width, (elevation - self.elevation).abs() / self.half_height); + let edge = |t: f32| 1.0 - crate::environment_sky::smooth((t - EDGE_FADE_START) / EDGE_FADE_WIDTH); + self.color * edge(x) * edge(y) + } +} diff --git a/crates/compose/src/warp_source_sample.rs b/crates/compose/src/warp_source_sample.rs new file mode 100644 index 00000000..9ab36aad --- /dev/null +++ b/crates/compose/src/warp_source_sample.rs @@ -0,0 +1,59 @@ +//! A warp's or slope blur's source as read around one texel + +use texturecraft_core::{WarpSource, WarpSourceMode, lum}; + +use crate::eval::{MIN_ALPHA, texel_noise}; +use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample}; + +/// A warp's or slope blur's source at one texel's neighbourhood +pub(crate) struct WarpSourceSample<'a> { + source: &'a WarpSource, + /// The default noise's seed + seed: u32, + res: u32, + comps: usize, + sample: Sample<'a>, + input: Input<'a>, + /// Half the texels the source is blurred across, worked out once per texel + half_blur: f32, +} + +impl<'a> WarpSourceSample<'a> { + /// `source` (default noise seeded `seed`) at `res` texels across a UV tile, reading `comps` values a texel through `sample`, or Custom Input through `input` + pub(crate) fn new(source: &'a WarpSource, seed: u32, (res, comps): (u32, usize), (sample, input): (Sample<'a>, Input<'a>)) -> Self { + WarpSourceSample { source, seed, res, comps, sample, input, half_blur: source.blur_texels(res) / 2.0 } + } + + /// The source at texel position `(x, y)` after its blur, Balance and Contrast + pub(crate) fn at(&self, x: f32, y: f32) -> f32 { + let half = self.half_blur; + let value = if half > 0.0 { + let corners = [(-half, -half), (half, -half), (-half, half), (half, half)]; + let (sum, count) = corners.iter().filter_map(|(dx, dy)| self.raw(x + dx, y + dy)).fold((0.0f32, 0u8), |(sum, count), read| (sum + read, count + 1)); + if count == 0 { WarpSource::MID_GRAY } else { sum / f32::from(count) } + } else { + self.raw(x, y).unwrap_or(WarpSource::MID_GRAY) + }; + self.source.shape(value) + } + + /// The source at texel position `(x, y)` before it is shaped; None where the values it filters cover nothing + fn raw(&self, x: f32, y: f32) -> Option { + match self.source.mode { + WarpSourceMode::DefaultNoise => Some(WarpSource::stretch_noise(texel_noise(x, y, [0.0; 2], self.res, self.source.noise_scale(), self.seed))), + WarpSourceMode::PreviousInput => { + let mut read = [0.0f32; 5]; + (self.sample)(x, y, &mut read); + match (self.comps, read) { + // Content stays premultiplied by its own coverage + (4, [r, g, b, alpha, _]) if alpha > MIN_ALPHA => Some(lum([r / alpha, g / alpha, b / alpha])), + (1, [value, .., weight]) if weight > MIN_READ_WEIGHT => Some(value / weight), + _ => None, + } + } + + // Mid gray (its default) moves nothing + WarpSourceMode::CustomNoise => (self.input)(x, y), + } + } +} diff --git a/crates/compose/src/warp_texel.rs b/crates/compose/src/warp_texel.rs new file mode 100644 index 00000000..0866e9ed --- /dev/null +++ b/crates/compose/src/warp_texel.rs @@ -0,0 +1,76 @@ +//! What a Warp filter reads for one texel: its source, then the moves its mode makes + +use texturecraft_core::{SourceWarp, WarpBlending, WarpMode}; + +use crate::eval::direction; +use crate::warp_source_sample::WarpSourceSample; + +/// Bilinear sample at an absolute texel position into an accumulator (components, then weight), as [`crate::eval`]'s gather reads +pub(crate) type Sample<'a> = &'a dyn Fn(f32, f32, &mut [f32; 5]); + +/// The filter's Custom Noise image input at an absolute texel position; None where the values it filters cover nothing +pub(crate) type Input<'a> = &'a dyn Fn(f32, f32) -> Option; + +/// A read weighing less than this covers nothing +pub(crate) const MIN_READ_WEIGHT: f32 = 1e-6; + +/// Warp `warp` at texel `(x, y)` (`res` texels across a UV tile, `comps` values a texel) into `acc`: where its source sends it, or those reads blended +pub(crate) fn warp_texel(warp: &SourceWarp, (x, y): (f32, f32), (res, comps): (u32, usize), acc: &mut [f32; 5], (sample, input): (Sample<'_>, Input<'_>)) { + let source = WarpSourceSample::new(&warp.source, warp.seed, (res, comps), (sample, input)); + let reach = warp.move_texels(res); + if warp.mode == WarpMode::Warp { + let probe = SourceWarp::probe_texels(res); + let rise = [source.at(x + probe, y) - source.at(x - probe, y), source.at(x, y + probe) - source.at(x, y - probe)]; + let [dx, dy] = warp.slope_move(rise, res); + sample(x + dx, y + dy, acc); + return; + } + + let directions = warp.angles().map(direction); + let moved = |(at_x, at_y): (f32, f32), [dx, dy]: [f32; 2]| { + let along = SourceWarp::amount(source.at(at_x, at_y)) * reach; + (at_x + dx * along, at_y + dy * along) + }; + match (warp.mode, warp.blending) { + (WarpMode::MultiDirectional, WarpBlending::Chain) => { + let (end_x, end_y) = directions.fold((x, y), moved); + sample(end_x, end_y, acc); + } + (WarpMode::MultiDirectional, WarpBlending::Max | WarpBlending::Min) => { + let reads = directions.map(|direction| moved((x, y), direction)); + keep_extreme_read(reads, warp.blending == WarpBlending::Max, comps, acc, sample); + } + + // One direction, or the average of several: the reads add up in `acc` + _ => { + for direction in directions { + let (at_x, at_y) = moved((x, y), direction); + sample(at_x, at_y, acc); + } + } + } +} + +/// Keeps in `acc` the largest (or smallest) of the reads at `positions`, component by component; reads that cover nothing are skipped +pub(crate) fn keep_extreme_read(positions: impl Iterator, larger: bool, comps: usize, acc: &mut [f32; 5], sample: Sample<'_>) { + let mut picked: Option<[f32; 5]> = None; + for (at_x, at_y) in positions { + let mut read = [0.0f32; 5]; + sample(at_x, at_y, &mut read); + if read[4] <= MIN_READ_WEIGHT { + continue; + } + + let read = read.map(|component| component / read[4]); + picked = Some(match picked { + Some(so_far) => std::array::from_fn(|k| if larger { so_far[k].max(read[k]) } else { so_far[k].min(read[k]) }), + None => read, + }); + } + + if let Some(picked) = picked { + let kept = comps.min(4); + acc[..kept].copy_from_slice(&picked[..kept]); + acc[4] = 1.0; + } +} diff --git a/crates/core/src/color_match.rs b/crates/core/src/color_match.rs new file mode 100644 index 00000000..c945bf72 --- /dev/null +++ b/crates/core/src/color_match.rs @@ -0,0 +1,116 @@ +//! Color Match's settings: the colors moved so a source color lands on a target color + +use serde::{Deserialize, Serialize}; + +use crate::{SourceColorMode, TargetColorMode, oklab}; + +/// A Color Match filter: every color moved, in OKLab, by the step from its source color to its target color +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ColorMatch { + /// Source Color Mode: the color moved from + pub source_mode: SourceColorMode, + /// Source Color (linear), read in Source Color Mode Parameter + pub source_color: [f32; 3], + /// Target Color Mode: the color moved to + pub target_mode: TargetColorMode, + /// Target Color (linear), read in Target Color Mode Parameter + pub target_color: [f32; 3], + /// Custom Color Variation: the colors keep at most Hue, Chroma and Luma of their difference from the source + pub custom_variation: bool, + /// Hue (degrees): how far a hue may stay from the target's + pub hue: f32, + /// Chroma: how far a chroma may stay from the target's + pub chroma: f32, + /// Luma: how far a lightness may stay from the target's + pub luma: f32, +} + +impl ColorMatch { + /// Mid gray (128 sRGB) in linear + const GRAY: [f32; 3] = [0.215_860_5; 3]; + + /// The most Hue keeps (degrees): two hues are at most half a turn apart + pub const MAX_HUE_DEGREES: f32 = 180.0; + /// The most Chroma keeps (OKLab chroma) + pub const MAX_CHROMA: f32 = 1.0; + /// The most Luma keeps (OKLab lightness, 0..1) + pub const MAX_LUMA: f32 = 1.0; + + /// A new Color Match: the texture's mean moves to the target and every texel keeps all of its difference from the mean (Color Variation at its widest), so the layer keeps its pattern until a variation is lowered + pub const LIBRARY: ColorMatch = ColorMatch { + source_mode: SourceColorMode::Average, + source_color: Self::GRAY, + target_mode: TargetColorMode::Parameter, + target_color: Self::GRAY, + custom_variation: true, + hue: Self::MAX_HUE_DEGREES, + chroma: Self::MAX_CHROMA, + luma: Self::MAX_LUMA, + }; + + /// Linear `color` moved by the step from `source` to `target`; without Custom Color Variation it keeps all of its difference from the source, with it at most Hue, Chroma and Luma of it (all 0: the target color itself). Hostile values give the color back + pub fn apply(&self, color: [f32; 3], source: [f32; 3], target: [f32; 3]) -> [f32; 3] { + let [lightness, a, b] = oklab::from_linear(color.map(|v| v.max(0.0))); + let [source_lightness, source_a, source_b] = oklab::from_linear(source.map(|v| v.max(0.0))); + let [target_lightness, target_a, target_b] = oklab::from_linear(target.map(|v| v.max(0.0))); + + let moved = if self.custom_variation { + let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; + let keep = |difference: f32, max: f32| difference.clamp(-max, max); + let (chroma, hue) = (a.hypot(b), b.atan2(a)); + let (source_chroma, source_hue) = (source_a.hypot(source_b), source_b.atan2(source_a)); + let (target_chroma, target_hue) = (target_a.hypot(target_b), target_b.atan2(target_a)); + let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; + let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA)); + let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0); + let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians()); + [out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()] + } else { + [target_lightness + lightness - source_lightness, target_a + a - source_a, target_b + b - source_b] + }; + + let out = oklab::to_linear(moved); + if out.iter().all(|v| v.is_finite()) { out.map(|v| v.clamp(0.0, 1.0)) } else { color } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn near(a: [f32; 3], b: [f32; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3) + } + + #[test] + fn the_source_color_lands_on_the_target_and_variation_is_kept_as_asked() { + let red = [0.6, 0.1, 0.05]; + let blue = [0.05, 0.1, 0.6]; + let lighter_red = [0.8, 0.2, 0.1]; + let lightness = |color: [f32; 3]| oklab::from_linear(color)[0]; + + // Without Custom Color Variation every difference from the source is kept + let keep_all = ColorMatch { custom_variation: false, ..ColorMatch::LIBRARY }; + let moved = keep_all.apply(lighter_red, red, blue); + assert!(near(keep_all.apply(red, red, blue), blue), "the source itself becomes the target"); + assert!(lightness(moved) > lightness(blue) + 0.05, "a lighter texel stays lighter than the target"); + assert!(moved[2] > moved[0], "and turns blue"); + + // Custom Color Variation at 0: every color is the target + let flat = ColorMatch { luma: 0.0, chroma: 0.0, hue: 0.0, ..ColorMatch::LIBRARY }; + assert!(near(flat.apply(lighter_red, red, blue), blue)); + + // A new Color Match's widest limits keep the lightness difference again + let library = ColorMatch::LIBRARY; + assert!(lightness(library.apply(lighter_red, red, blue)) > lightness(blue) + 0.05, "a new Color Match keeps the variation"); + + // Luma alone: the lightness difference kept up to it + let luma_only = ColorMatch { luma: 0.02, ..flat }; + let limited = lightness(luma_only.apply(lighter_red, red, blue)) - lightness(blue); + assert!((limited - 0.02).abs() < 1e-3, "lightness kept up to Luma: {limited}"); + + let hostile = ColorMatch { hue: f32::NAN, chroma: f32::INFINITY, luma: -1.0, ..flat }; + assert!(hostile.apply([f32::NAN, 0.5, 0.5], red, blue).iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); + } +} diff --git a/crates/core/src/ramp_curve.rs b/crates/core/src/ramp_curve.rs new file mode 100644 index 00000000..101a90ed --- /dev/null +++ b/crates/core/src/ramp_curve.rs @@ -0,0 +1,38 @@ +//! The bend Bevel Smooth's ramp and Mask Outline's fade take, sanitised once per filter + +/// A Curve Shape of 1 raises a ramp to the power ¼ and −1 to the power 4, 0 leaves it straight +const CURVE_SHAPE_BASE: f32 = 4.0; + +/// A 0..1 ramp moved by an offset, then raised to a power: below 0 the shape rises later, above 0 sooner +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RampCurve { + offset: f32, + exponent: f32, +} + +impl RampCurve { + /// The curve moving a ramp by `offset` and bending it by `shape` (each −1..1, 0 when not finite) + pub fn new(offset: f32, shape: f32) -> RampCurve { + let bounded = |x: f32| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 }; + RampCurve { offset: bounded(offset), exponent: CURVE_SHAPE_BASE.powf(-bounded(shape)) } + } + + /// Ramp value `along` (0..1) moved and bent + pub fn apply(self, along: f32) -> f32 { + (along + self.offset).clamp(0.0, 1.0).powf(self.exponent) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_shape_bends_and_the_offset_moves() { + assert_eq!(RampCurve::new(0.0, 0.0).apply(0.3), 0.3, "straight"); + assert_eq!(RampCurve::new(0.0, 1.0).apply(0.0625), 0.5, "the power ¼ rises sooner"); + assert_eq!(RampCurve::new(0.0, -1.0).apply(0.5), 0.0625, "the power 4 rises later"); + assert_eq!(RampCurve::new(0.25, 0.0).apply(0.5), 0.75); + assert_eq!(RampCurve::new(f32::NAN, f32::INFINITY), RampCurve::new(0.0, 0.0), "hostile settings leave it straight"); + } +} diff --git a/crates/core/src/source_warp.rs b/crates/core/src/source_warp.rs new file mode 100644 index 00000000..4891f752 --- /dev/null +++ b/crates/core/src/source_warp.rs @@ -0,0 +1,135 @@ +//! The Warp filter's settings and the moves it makes + +use serde::{Deserialize, Serialize}; + +use crate::{WarpBlending, WarpMode, WarpSource, WarpSourceMode, finite_unit}; + +/// Texels read from where a source sends them: along its slope, along one direction, or along several blended +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceWarp { + /// The default noise's seed + pub seed: u32, + pub mode: WarpMode, + /// How far a texel moves at most, a share of the UV tile before the divider (0..1) + pub intensity: f32, + /// Divides `intensity` (1, 10, 100 or 1000) for fine moves + pub divider: u16, + /// The direction (degrees) of the directional modes, the first of several in Multi Directional Warp + pub angle: f32, + /// How many directions a Multi Directional Warp spreads evenly around the circle (1, 2 or 4) + pub directions: u8, + pub blending: WarpBlending, + pub source: WarpSource, +} + +impl SourceWarp { + /// The Warp filter as the library adds it + pub const LIBRARY: SourceWarp = SourceWarp { + seed: 0, + mode: WarpMode::Warp, + intensity: 0.1, + divider: 10, + angle: 0.0, + directions: 4, + blending: WarpBlending::Average, + source: WarpSource::LIBRARY, + }; + + /// The direction counts a Multi Directional Warp takes + pub const DIRECTIONS: [u8; 3] = [1, 2, 4]; + + /// The share of the UV tile the source's slope is measured across, on each side of a texel + pub const PROBE_SHARE: f32 = 1.0 / 256.0; + + /// The source's slope (rise per UV tile) that moves a texel the whole way in Warp mode + pub const FULL_SLOPE: f32 = 4.0; + + /// How many texels a texel moves at most at `res` texels across a UV tile + pub fn move_texels(&self, res: u32) -> f32 { + move_texels(self.intensity, self.divider, res) + } + + /// How many texels each side of a texel Warp mode measures the source's slope across + pub fn probe_texels(res: u32) -> f32 { + (res as f32 * Self::PROBE_SHARE).max(1.0) + } + + /// The directions (degrees) texels move along: none in Warp mode (the slope decides), the Angle, or Directions spread from it + pub fn angles(&self) -> impl Iterator + Clone + use<> { + let angle = if self.angle.is_finite() { self.angle } else { 0.0 }; + let count = match self.mode { + WarpMode::Warp => 0, + WarpMode::Directional => 1, + WarpMode::MultiDirectional if Self::DIRECTIONS.contains(&self.directions) => self.directions, + WarpMode::MultiDirectional => 1, + }; + (0..count).map(move |index| angle + 360.0 * f32::from(index) / f32::from(count)) + } + + /// How many texels around a texel the warp reads at `res` texels across a UV tile: its moves (chained ones add up) and where it reads its source + pub fn reach(&self, res: u32) -> f32 { + let chained = self.mode == WarpMode::MultiDirectional && self.blending == WarpBlending::Chain; + let moves = self.move_texels(res) * if chained { self.angles().count().max(1) as f32 } else { 1.0 }; + if self.source.mode != WarpSourceMode::PreviousInput { + return moves; + } + + let probe = if self.mode == WarpMode::Warp { Self::probe_texels(res) } else { 0.0 }; + moves + probe + self.source.blur_texels(res) * std::f32::consts::FRAC_1_SQRT_2 + } + + /// How far (−1..1 of the move) a source value moves a texel along a direction: backwards below mid gray, forwards above + pub fn amount(value: f32) -> f32 { + if value.is_finite() { (2.0 * value - 1.0).clamp(-1.0, 1.0) } else { 0.0 } + } + + /// Warp mode's move (texels) from how much the source rises across [`SourceWarp::probe_texels`] each side of a texel along x and y + pub fn slope_move(&self, rise: [f32; 2], res: u32) -> [f32; 2] { + let across = 2.0 * Self::probe_texels(res) / res.max(1) as f32; + let [x, y] = rise.map(|rise| if rise.is_finite() { rise / across / Self::FULL_SLOPE } else { 0.0 }); + let length = x.hypot(y); + let fit = if length > 1.0 { 1.0 / length } else { 1.0 }; + let reach = self.move_texels(res); + [x * fit * reach, y * fit * reach] + } +} + +/// How many texels Intensity over Divider moves at `res` texels across a UV tile (Warp's and Blur Slope's) +pub(crate) fn move_texels(intensity: f32, divider: u16, res: u32) -> f32 { + finite_unit(intensity) / f32::from(divider.max(1)) * res as f32 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn moves_follow_intensity_mode_and_directions() { + let warp = SourceWarp::LIBRARY; + assert!((warp.move_texels(2048) - 20.48).abs() < 1e-3, "0.1 ÷ 10 of the tile"); + assert_eq!(warp.angles().count(), 0); + let directional = SourceWarp { mode: WarpMode::Directional, angle: 30.0, ..warp }; + assert_eq!(directional.angles().collect::>(), vec![30.0]); + let multi = SourceWarp { mode: WarpMode::MultiDirectional, angle: 10.0, ..warp }; + assert_eq!(multi.angles().collect::>(), vec![10.0, 100.0, 190.0, 280.0]); + let chained = SourceWarp { blending: WarpBlending::Chain, ..multi }; + assert!((chained.reach(2048) - 4.0 * 20.48).abs() < 1e-3, "four moves one after the other"); + let input = SourceWarp { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..warp }; + assert!((input.reach(2048) - (20.48 + 8.0)).abs() < 1e-3, "plus where it measures the slope"); + assert_eq!((SourceWarp::amount(0.0), SourceWarp::amount(0.5), SourceWarp::amount(1.0)), (-1.0, 0.0, 1.0)); + } + + #[test] + fn slope_moves_saturate_and_hostile_settings_stay_in_range() { + let warp = SourceWarp::LIBRARY; + let gentle = warp.slope_move([0.01, 0.0], 2048); + assert!(gentle[0] > 0.0 && gentle[0] < warp.move_texels(2048), "{gentle:?}"); + let steep = warp.slope_move([1.0, 1.0], 2048); + assert!((steep[0].hypot(steep[1]) - warp.move_texels(2048)).abs() < 1e-3, "a cliff moves the whole way, no further: {steep:?}"); + let hostile = SourceWarp { intensity: f32::NAN, angle: f32::INFINITY, directions: 9, divider: 0, mode: WarpMode::MultiDirectional, ..warp }; + assert_eq!((hostile.move_texels(2048), hostile.angles().collect::>()), (0.0, vec![0.0])); + assert_eq!(hostile.slope_move([f32::NAN, 1.0], 2048)[0], 0.0); + assert_eq!(SourceWarp { intensity: 9.0, divider: 1, ..warp }.move_texels(1024), 1024.0); + } +} diff --git a/crates/core/src/stylized_shading.rs b/crates/core/src/stylized_shading.rs new file mode 100644 index 00000000..57d4d5ca --- /dev/null +++ b/crates/core/src/stylized_shading.rs @@ -0,0 +1,193 @@ +//! Baked Lighting Stylized's settings worked out once per filter, and the shading of each texel with them + +use std::f32::consts::PI; + +use crate::lighting_output::LightingOutput; +use crate::stylized_lighting::StylizedLighting; +use crate::sun_and_sky::SunAndSky; +use crate::{Channel, finite_unit, mix3}; + +/// The curvature map's value on a flat surface (below it concave, above convex) +pub const FLAT_CURVATURE: f32 = 0.5; + +/// The scale that takes either side of [`FLAT_CURVATURE`] to 0..1 +const CURVATURE_SIDE_SCALE: f32 = 2.0; + +/// The Cook-Torrance denominator 4·(n·l)·(n·v) with the viewer straight on (n·v = 1), n·l cancelled by the light's own facing +const COOK_TORRANCE_DENOMINATOR: f32 = 4.0; + +/// The roughness highlights never go below (a mirror would be a single texel of infinite light) +const MIN_ROUGHNESS: f32 = 0.08; + +/// The smoothness below which cavity and edges switch on as a step +const MIN_SMOOTHNESS: f32 = 1e-3; + +/// A [`StylizedLighting`] under its [`SunAndSky`], with every value that depends only on the settings worked out once +#[derive(Clone, Debug, PartialEq)] +pub struct StylizedShading { + /// The sun, Light 1 and Light 2: the unit direction toward each, its intensity and its color + lights: [([f32; 3], f32, [f32; 3]); 3], + sky_intensity: f32, + sky_color: [f32; 3], + horizon_color: [f32; 3], + ground_color: [f32; 3], + /// Diffuse AO, Specular AO, Diffuse Cavity, Specular Cavity and Edges Intensity, each 0..1 + diffuse_ao: f32, + specular_ao: f32, + diffuse_cavity: f32, + specular_cavity: f32, + edges_intensity: f32, + cavity_smoothness: f32, + edges_smoothness: f32, + specular_glossiness: bool, + output: LightingOutput, + /// The reflectance of non-metals at normal incidence, 0..1 + dielectric_reflectance: f32, + /// The relief the baked height gives the lit normals; None lights the mesh's own normals + relief: Option, +} + +impl StylizedShading { + /// `settings` lit by `light` + pub fn new(settings: &StylizedLighting, light: SunAndSky) -> StylizedShading { + let sun = (light.sun.direction(), light.sun.intensity, settings.sun_color); + let [first, second] = settings.lights.map(|extra| (extra.direction(), extra.intensity, extra.color)); + StylizedShading { + lights: [sun, first, second], + sky_intensity: light.sky_intensity, + sky_color: settings.sky_color, + horizon_color: settings.horizon_color, + ground_color: settings.ground_color, + diffuse_ao: finite_unit(light.diffuse_ao), + specular_ao: finite_unit(settings.specular_ao), + diffuse_cavity: finite_unit(settings.diffuse_cavity), + specular_cavity: finite_unit(settings.specular_cavity), + edges_intensity: finite_unit(settings.edges_intensity), + cavity_smoothness: settings.cavity_smoothness, + edges_smoothness: settings.edges_smoothness, + specular_glossiness: settings.specular_glossiness, + output: settings.output, + dielectric_reflectance: finite_unit(settings.dielectric_reflectance), + relief: (!settings.mesh_only).then_some(settings.height_to_normal), + } + } + + /// The relief the baked height gives the normals it lights (Height to Normal Intensity); None lights the mesh's own normals + pub fn relief(&self) -> Option { + self.relief + } + + /// The ambient light reaching a surface facing `normal` from the sky, horizon and ground + fn ambient(&self, normal: [f32; 3]) -> [f32; 3] { + let up = normal[1].clamp(-1.0, 1.0); + if up >= 0.0 { mix3(self.horizon_color, self.sky_color, up) } else { mix3(self.horizon_color, self.ground_color, -up) } + } + + /// The lit base color of linear `albedo` facing `normal` (world space, unit) with baked ambient occlusion `ao` and curvature `curvature` ([`FLAT_CURVATURE`] flat), its material read from `channels` (straight values by [`Channel::index`]); the viewer looks straight at the surface + pub fn shade(&self, albedo: [f32; 3], normal: [f32; 3], [ao, curvature]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] { + let channel = |channel: Channel| channels.get(channel.index()).copied().unwrap_or_else(|| channel.default_value()); + let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 }; + let curvature = if curvature.is_finite() { curvature } else { FLAT_CURVATURE }; + let cavity = fade_in((FLAT_CURVATURE - curvature) * CURVATURE_SIDE_SCALE, self.cavity_smoothness); + let edge = fade_in((curvature - FLAT_CURVATURE) * CURVATURE_SIDE_SCALE, self.edges_smoothness); + + let (roughness, f0, diffuse_albedo) = if self.specular_glossiness { + (1.0 - finite_unit(channel(Channel::Glossiness)[0]), channel(Channel::Specular).map(finite_unit), albedo) + } else { + let metal = finite_unit(channel(Channel::Metallic)[0]); + let f0 = mix3([self.dielectric_reflectance; 3], albedo, metal); + + // Without highlights the whole base color is lit, as Baked Lighting did + let kept = if self.output.specular() { 1.0 - metal } else { 1.0 }; + (finite_unit(channel(Channel::Roughness)[0]), f0, albedo.map(|x| x * kept)) + }; + let roughness = roughness.max(MIN_ROUGHNESS); + let sky = self.ambient(normal); + + let diffuse_ao = 1.0 + (ao - 1.0) * self.diffuse_ao; + let specular_ao = 1.0 + (ao - 1.0) * self.specular_ao; + let diffuse_cavity = 1.0 - cavity * self.diffuse_cavity; + let specular_cavity = 1.0 - cavity * self.specular_cavity; + + let mut diffuse = sky.map(|sky_light| sky_light * self.sky_intensity * diffuse_ao * diffuse_cavity); + let mut specular = [0.0f32; 3]; + for &(direction, intensity, color) in &self.lights { + let facing = dot(normal, direction); + if facing <= 0.0 || intensity <= 0.0 { + continue; + } + + let half = normalize([normal[0] + direction[0], normal[1] + direction[1], normal[2] + direction[2]]); + let normal_dot_half = dot(normal, half).max(0.0); + let highlight = ggx(normal_dot_half, roughness) / COOK_TORRANCE_DENOMINATOR * facing * specular_cavity; + for (((diffuse, specular), color), f0) in diffuse.iter_mut().zip(&mut specular).zip(color).zip(f0) { + *diffuse += color * intensity * facing * diffuse_cavity; + *specular += color * intensity * highlight * schlick(f0, normal_dot_half); + } + } + for ((specular, f0), sky_light) in specular.iter_mut().zip(f0).zip(sky) { + *specular += f0 * sky_light * self.sky_intensity * specular_ao * specular_cavity; + } + + std::array::from_fn(|k| { + let lit = if self.output.diffuse() { diffuse_albedo[k] * diffuse[k] } else { 0.0 }; + let shine = if self.output.specular() { specular[k] } else { 0.0 }; + let shaded = finite_unit(lit + shine); + finite_unit(shaded + (1.0 - shaded) * edge * self.edges_intensity) + }) + } +} + +/// `amount` (clamped 0..1) reaching full over `smoothness`: a step when it is about 0 or not a number +fn fade_in(amount: f32, smoothness: f32) -> f32 { + let amount = amount.clamp(0.0, 1.0); + if smoothness.is_nan() || smoothness <= MIN_SMOOTHNESS { + return if amount > 0.0 { 1.0 } else { 0.0 }; + } + + (amount / smoothness).min(1.0) +} + +/// The GGX distribution of microfacets facing `normal_dot_half` (the cosine between the normal and the half vector) at `roughness` +fn ggx(normal_dot_half: f32, roughness: f32) -> f32 { + let alpha_squared = (roughness * roughness).powi(2); + let denominator = normal_dot_half * normal_dot_half * (alpha_squared - 1.0) + 1.0; + alpha_squared / (PI * denominator * denominator) +} + +/// Schlick's Fresnel of reflectance `f0` at cosine `cos` +fn schlick(f0: f32, cos: f32) -> f32 { + f0 + (1.0 - f0) * (1.0 - cos.clamp(0.0, 1.0)).powi(5) +} + +fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// `v` at unit length; a vector too short to have a direction points up +fn normalize(v: [f32; 3]) -> [f32; 3] { + const MIN_LENGTH: f32 = 1e-6; + + let length = dot(v, v).sqrt(); + if length > MIN_LENGTH { v.map(|x| x / length) } else { [0.0, 1.0, 0.0] } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A smoothness that is not a number switches cavity and edges on as a step: a flat surface stays untouched + #[test] + fn a_nan_smoothness_fades_in_as_a_step() { + assert_eq!((fade_in(0.0, f32::NAN), fade_in(0.3, f32::NAN)), (0.0, 1.0)); + } + + /// The relief is the Height to Normal Intensity, unless the filter lights the mesh's own normals + #[test] + fn the_relief_follows_mesh_only() { + let light = SunAndSky { sun: StylizedLighting::PLAIN.lights[0], sky_intensity: 1.0, diffuse_ao: 0.0 }; + assert_eq!(StylizedShading::new(&StylizedLighting::PLAIN, light).relief(), None); + let detailed = StylizedLighting { mesh_only: false, height_to_normal: 0.7, ..StylizedLighting::PLAIN }; + assert_eq!(StylizedShading::new(&detailed, light).relief(), Some(0.7)); + } +} diff --git a/crates/core/src/unit_value.rs b/crates/core/src/unit_value.rs new file mode 100644 index 00000000..aed6e18e --- /dev/null +++ b/crates/core/src/unit_value.rs @@ -0,0 +1,33 @@ +//! Settings and values sanitised to the 0..1 range filters read them in + +/// A value at its threshold still counts when float rounding left it a step below (a white read back as 0.99999994) +const THRESHOLD_TOLERANCE: f32 = f32::EPSILON; + +/// `x` clamped to 0..1, 0 when not finite +pub fn finite_unit(x: f32) -> f32 { + if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 } +} + +/// Whether `value` reaches `threshold` (clamped to 0..1, `fallback` when not finite) +pub fn at_or_above_threshold(value: f32, threshold: f32, fallback: f32) -> bool { + let threshold = if threshold.is_finite() { threshold.clamp(0.0, 1.0) } else { fallback }; + value >= threshold - THRESHOLD_TOLERANCE +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_land_in_the_unit_range() { + assert_eq!([finite_unit(-2.0), finite_unit(0.25), finite_unit(7.0), finite_unit(f32::NAN), finite_unit(f32::INFINITY)], [0.0, 0.25, 1.0, 0.0, 0.0]); + } + + #[test] + fn a_threshold_counts_a_value_rounded_just_below_it() { + assert!(at_or_above_threshold(1.0 - f32::EPSILON / 2.0, 1.0, 0.5)); + assert!(!at_or_above_threshold(0.49, 0.5, 0.5)); + assert!(at_or_above_threshold(0.5, f32::NAN, 0.5), "a hostile threshold falls back"); + assert!(at_or_above_threshold(1.0, 9.0, 0.5), "a threshold past 1 is 1"); + } +} diff --git a/crates/core/src/warp_source.rs b/crates/core/src/warp_source.rs new file mode 100644 index 00000000..80ff4914 --- /dev/null +++ b/crates/core/src/warp_source.rs @@ -0,0 +1,64 @@ +//! The values a Warp's moves follow and how they are shaped first + +use serde::{Deserialize, Serialize}; + +use crate::WarpSourceMode; +use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray}; + +/// A Warp's source: noise, the values it filters or an image, blurred, balanced and contrasted +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WarpSource { + pub mode: WarpSourceMode, + /// How widely the source is averaged first (0..1, up to [`WarpSource::BLUR_SHARE`] of the UV tile) + pub blur: f32, + /// Added to the source around 0.5 (0..1) + pub balance: f32, + /// Steepens the source around mid gray (0..1) + pub contrast: f32, + /// How many times the default noise repeats across a UV tile (0.01..16) + pub tiling: f32, +} + +impl WarpSource { + /// The source as the library's Warp starts with it + pub const LIBRARY: WarpSource = WarpSource { mode: WarpSourceMode::DefaultNoise, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, tiling: 1.0 }; + + /// Noise features across a UV tile at Source Tiling 1 + pub const NOISE_FEATURES: f32 = 4.0; + + /// The share of the UV tile a Source Blur of 1 averages over + pub const BLUR_SHARE: f32 = 1.0 / 16.0; + + /// Mid gray: the source value that moves nothing, and the noise's middle + pub const MID_GRAY: f32 = 0.5; + + /// How far noise is stretched from mid gray so it spans black to white + pub const NOISE_STRETCH: f32 = 1.5; + + /// The Tiling range + pub const TILING_MIN: f32 = 0.01; + pub const TILING_MAX: f32 = 16.0; + + /// Noise features per UV tile + pub fn noise_scale(&self) -> f32 { + let tiling = if self.tiling.is_finite() { self.tiling.clamp(Self::TILING_MIN, Self::TILING_MAX) } else { 1.0 }; + Self::NOISE_FEATURES * tiling + } + + /// How many texels across the source is averaged over at `res` texels across a UV tile + pub fn blur_texels(&self, res: u32) -> f32 { + let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 }; + blur * Self::BLUR_SHARE * res as f32 + } + + /// Fractal noise `noise` (around mid gray) stretched to span 0..1 + pub fn stretch_noise(noise: f32) -> f32 { + if noise.is_finite() { (Self::MID_GRAY + (noise - Self::MID_GRAY) * Self::NOISE_STRETCH).clamp(0.0, 1.0) } else { Self::MID_GRAY } + } + + /// Source value `value` after Balance and Contrast + pub fn shape(&self, value: f32) -> f32 { + shape_gray(value, self.balance, self.contrast, false) + } +} diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index c424f839..b4a72c26 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -3,10 +3,18 @@ //! by id; `filter.list` lists them with their default parameters. use serde_json::{Value, json}; -use texturecraft_core::{Channel, EffectKind, Fill, Filter, Levels, Procedural, ProceduralKind, Projection, Source}; +use texturecraft_core::{ + AnisotropicKuwahara, Bevel, BevelBlur, BevelCorner, BevelDirection, BevelSmooth, Channel, ColorMatch, ConversionMode, CurvePreset, DirectionalDistance, + Effect, EffectKind, Fill, Filter, GradientInput, GrayscaleConversion, GrayscaleMode, HeightToNormal, HighpassSpace, LayerId, Levels, MaskOutline, Mirror, + MirrorCorner, MirrorMode, OutlinePosition, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PbrValidate, Procedural, ProceduralKind, Projection, SlopeBlending, + Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedLighting, TargetColorMode, ThresholdMode, TileTransform, ValidationMode, WarpBlending, + WarpMode, WarpSource, WarpSourceMode, +}; -use crate::commands::{CommandSpec, always, bad, color_of, color_param, f32p, u64p}; -use crate::{Result, cmd}; +use crate::commands::{CommandSpec, always, bad, boolp, color_of, color_param, f32p, has_layer, strp, u64p}; +use crate::filter_about::FilterAbout; +use crate::layer_cmds::FULL_TURN_DEGREES; +use crate::{Result, Session, cmd}; /// A filter of the library. #[derive(Clone, Copy, Debug)] @@ -20,6 +28,11 @@ pub struct FilterDef { } impl FilterDef { + /// What it does and the words it is found by (its Attributes) + pub fn about(&self) -> Option { + crate::filter_about::of(self.id) + } + /// 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(_))) @@ -40,31 +53,47 @@ const fn def(id: &'static str, label: &'static str, group: &'static str, mask: b pub const FILTERS: &[FilterDef] = &[ def("hsl", "HSL Perceptive", "Adjustments", true), def("levels", "Levels", "Adjustments", true), - def("contrastLuminosity", "Contrast/Luminosity", "Adjustments", true), + def("contrastLuminosity", "Contrast Luminosity", "Adjustments", true), def("colorBalance", "Color Balance", "Adjustments", true), - def("gradientMap", "Gradient Map", "Adjustments", true), + def("colorCorrect", "Color Correct", "Adjustments", true), + def("gradientMap", "Gradient", "Adjustments", true), + def("gradientCurve", "Gradient Curve", "Adjustments", true), + def("gradientDynamic", "Gradient Dynamic", "Adjustments", true), def("posterize", "Posterize", "Adjustments", true), def("clamp", "Clamp", "Adjustments", true), + def("smoothstep", "Smoothstep", "Adjustments", true), + def("heightAdjust", "Height Adjust", "Adjustments", true), def("histogramScan", "Histogram Scan", "Adjustments", true), def("histogramRange", "Histogram Range", "Adjustments", true), def("histogramShift", "Histogram Shift", "Adjustments", true), def("invert", "Invert", "Adjustments", true), def("threshold", "Threshold", "Adjustments", true), - def("grayscale", "Grayscale", "Adjustments", false), + def("grayscale", "Grayscale Conversion", "Adjustments", true), def("edgeDetect", "Edge Detect", "Adjustments", true), def("normalInvert", "Normal Invert", "Adjustments", false), - def("bakedLighting", "Baked Lighting", "Adjustments", false), + def("bakedLighting", "Baked Lighting Stylized", "Adjustments", false), + def("bakedLightingEnvironment", "Baked Lighting Environment", "Adjustments", false), def("replaceColor", "Replace Color", "Adjustments", false), + def("pbrValidate", "PBR Validate (Metallic Roughness)", "Adjustments", false), + def("heightToNormal", "Height To Normal", "Adjustments", false), + def("colorMatch", "Color Match", "Adjustments", false), def("blur", "Blur", "Blur and sharpen", true), def("blurDirectional", "Blur Directional", "Blur and sharpen", true), - def("slopeBlur", "Slope Blur", "Blur and sharpen", true), + def("slopeBlur", "Blur Slope", "Blur and sharpen", true), def("sharpen", "Sharpen", "Blur and sharpen", true), - def("highPass", "High Pass", "Blur and sharpen", true), + def("highPass", "Highpass", "Blur and sharpen", true), + def("fxaa", "FXAA (Anti-aliasing)", "Blur and sharpen", true), + def("anisotropicKuwahara", "Anisotropic Kuwahara", "Blur and sharpen", true), def("bevel", "Bevel", "Blur and sharpen", true), + def("bevelSmooth", "Bevel Smooth", "Blur and sharpen", true), + def("directionalDistance", "Directional Distance", "Blur and sharpen", true), def("glow", "Glow", "Blur and sharpen", true), + def("dropShadow", "Drop Shadow", "Blur and sharpen", true), + def("maskOutline", "Mask Outline", "Blur and sharpen", true), def("warp", "Warp", "Distort", true), - def("warpDirectional", "Warp Directional", "Distort", true), - def("mosaic", "Mosaic", "Distort", true), + def("mosaic", "Pixelate", "Distort", true), + def("mirror", "Mirror", "Distort", true), + def("transform", "Transform", "Distort", true), def("matFinishGrind", "MatFinish Grind", "Material finish", false), def("matFinishRaw", "MatFinish Raw", "Material finish", false), def("matFinishSanded", "MatFinish Sanded", "Material finish", false), @@ -75,69 +104,264 @@ fn norm(s: &str) -> String { s.to_ascii_lowercase().replace([' ', '_', '-', '/'], "") } -/// The library filter `id` (case and separators ignored; labels work too). +/// The library filter `id` (case and separators ignored; labels work too). Directional Warp's former id and labels find Warp, whose mode it is now pub fn find(id: &str) -> Option<&'static FilterDef> { - let n = norm(id); - FILTERS.iter().find(|f| norm(f.id) == n || norm(f.label) == n) + let wanted = if is_directional_warp(id) { norm("warp") } else { norm(id) }; + FILTERS.iter().find(|def| norm(def.id) == wanted || norm(def.label) == wanted) +} + +/// Whether `id` names Directional Warp, a filter of its own before the warp modes (`warpDirectional`, "Warp Directional", "Directional Warp") +fn is_directional_warp(id: &str) -> bool { + matches!(norm(id).as_str(), "warpdirectional" | "directionalwarp") } pub fn specs() -> Vec { - vec![cmd!( - "filter.list", - "List filters", - [], - None, - "{} — the filter library: id, label, group, whether masks take it, default parameters", - always, - |_, _| Ok(Value::Array( - FILTERS - .iter() - .map(|f| json!({"id": f.id, "label": f.label, "group": f.group, "mask": f.mask, "defaults": build(f.id, &Value::Null).ok()})) - .collect() - )) - )] + vec![ + cmd!( + "effect.filter.restoreDefaults", + "Restore defaults", + [], + None, + "{effect?: filter effect id, default the selected effect} — its filter's parameters back to their defaults (name, channels and blending stay; a filter saved before its library replacement becomes that replacement, as the library adds it) in one undo step; no step when they are already; returns {changed}", + has_layer, + restore_defaults + ), + cmd!( + "filter.list", + "List filters", + [], + None, + "{} — the filter library: id, label, group, whether masks take it, default parameters, what it does (description) and its tags", + always, + |_, _| Ok(Value::Array(FILTERS.iter().map(listed).collect())) + ), + ] } -/// The effect for library filter `id` with its defaults, then the parameters in `p`. +/// `filter.list`'s entry for `def` +fn listed(def: &FilterDef) -> Value { + let about = def.about(); + json!({ + "id": def.id, + "label": def.label, + "group": def.group, + "mask": def.mask, + "defaults": build(def.id, &Value::Null).ok(), + "description": about.map(|about| about.description), + "tags": about.map(|about| about.tags), + }) +} + +/// The filter `effect.filter.restoreDefaults` works on: its id and the library defaults of the filter it is (None: an empty filter) +fn filter_defaults(s: &Session, p: &Value) -> Result<(LayerId, Option)> { + const CMD: &str = "effect.filter.restoreDefaults"; + let effect = crate::mask_cmds::effect_id(s, p, CMD)?; + let filter = match s.doc.project.effect(effect) { + Some((_, Effect { kind: EffectKind::Filter(filter), .. })) => filter, + Some(_) => return Err(bad(CMD, format!("effect {} is not a filter", effect.0))), + None => return Err(bad(CMD, format!("no effect {}", effect.0))), + }; + let defaults = match build(filter.label(), &Value::Null) { + Ok(EffectKind::Filter(defaults)) => Some(defaults), + _ => None, + }; + Ok((effect, defaults)) +} + +/// Puts a filter effect's parameters back to their library defaults in one undo step +fn restore_defaults(s: &mut Session, p: &Value) -> Result { + let (effect, defaults) = filter_defaults(s, p)?; + let current = s.doc.project.effect(effect).map(|(_, found)| &found.kind); + let Some(defaults) = defaults.filter(|defaults| !matches!(current, Some(EffectKind::Filter(filter)) if filter == defaults)) else { + return Ok(json!({"changed": false})); + }; + + s.edit("Restore defaults", |s| { + if let Some(edited) = s.doc.project.effect_mut(effect) { + edited.kind = EffectKind::Filter(defaults); + } + Ok(()) + })?; + Ok(json!({"changed": true})) +} + +/// A Color Correct tone that changes nothing: no contrast, no luminosity, saturation as it is +const NEUTRAL_TONE: [f32; 3] = [0.0, 0.0, 0.5]; + +/// Mid gray as a color picker shows it (sRGB 0.5), in linear RGB +pub const MID_GRAY: f32 = 0.214; + +/// The two Channel Input and Extract Direction choices: the channel the filter sits on, or its image input +const CURRENT_CHANNEL: &str = "currentChannel"; +const CUSTOM_INPUT: &str = "customInput"; + +/// A new glow's warm light, in linear RGB +const GLOW_COLOR: [f32; 3] = [0.871, 0.578, 0.188]; + +/// The Glow filter as the library adds it: a soft warm halo outside the shapes +pub const LIBRARY_GLOW: Filter = Filter::HaloGlow { on_mask: false, precise: false, width: 0.15, spread: 0.0, opacity: 1.0, color: GLOW_COLOR }; + +/// The Drop Shadow filter as the library adds it: a half-opaque black shadow cast downward +pub const LIBRARY_DROP_SHADOW: Filter = Filter::DropShadow { angle: 90.0, distance: 0.1, size: 0.2, spread: 0.0, opacity: 0.5, color: [0.0; 3] }; + +/// The Gradient Curve filter as the library adds it +pub const LIBRARY_GRADIENT_CURVE: Filter = Filter::GradientCurve { preset: CurvePreset::Round, invert: false, balance: 0.5, contrast: 0.0 }; + +/// The Gradient Dynamic filter as the library adds it: a horizontal ramp from a light gray +pub const LIBRARY_GRADIENT_DYNAMIC: Filter = Filter::GradientDynamic { vertical: false, position: 0.0, color: [0.6; 3] }; + +/// The Baked Lighting Environment filter as the library adds it: the environment as it stands, full ambient occlusion +pub const LIBRARY_ENVIRONMENT_LIGHTING: Filter = + Filter::EnvironmentLighting { horizontal: 0.0, vertical: 0.0, exposure: 0.0, height_intensity: 4.0, ambient_occlusion: 1.0, specular_occlusion: 0.0 }; + +pub use crate::stylized_lighting_params::{MAX_CAVITY_SMOOTHNESS, MAX_DIELECTRIC_REFLECTANCE, MAX_HEIGHT_TO_NORMAL, MAX_LIGHT_INTENSITY}; + +/// A Seed slider's end; any seed can be typed +const SEED_SLIDER_MAX: f32 = 999.0; + +/// The Tiling range of a warp's or slope blur's source +pub const SOURCE_TILING_MIN: f32 = WarpSource::TILING_MIN; +pub const SOURCE_TILING_MAX: f32 = WarpSource::TILING_MAX; + +/// The Source Tiling slider range of a noise-driven warp or blur +const NOISE_TILING_MIN: f32 = 0.5; +const NOISE_TILING_MAX: f32 = 64.0; + +/// A blur Intensity slider's end, in the reference workflow's unit (see [`Filter::BLUR_INTENSITY`]) +pub const BLUR_INTENSITY_SLIDER_MAX: f32 = 16.0; + +/// The widest radius or width a filter takes, in texels at 2K; its slider ends at [`TEXELS_SLIDER_MAX`] +const TEXELS_MAX: f32 = 256.0; +const TEXELS_SLIDER_MAX: f32 = 128.0; + +/// Slider ends where a larger value can still be typed +const SHARPEN_SLIDER_MAX: f32 = 4.0; +const GLOW_AMOUNT_SLIDER_MAX: f32 = 5.0; +pub const SKY_INTENSITY_SLIDER_MAX: f32 = 2.0; +const EDGE_WIDTH_SLIDER_MAX: f32 = 64.0; +const MOSAIC_PIXELS_SLIDER_MAX: f32 = 128.0; + +/// The largest values that can be typed past those slider ends +const SHARPEN_AMOUNT_MAX: f32 = 10.0; +const GLOW_AMOUNT_MAX: f32 = 10.0; +const SKY_INTENSITY_MAX: f32 = 10.0; + +/// The largest mosaic cell, in pixels +const MOSAIC_SIZE_MAX: f32 = 2048.0; + +/// Height Adjust's largest Multiply +const HEIGHT_MULTIPLY_MAX: f32 = 10.0; + +/// Height Adjust's Offset reaches this far either way, as the reference's does +const HEIGHT_OFFSET_MAX: f32 = 10.0; + +/// Distance Bevel's largest Smoothing +pub const DISTANCE_BEVEL_SMOOTHING_MAX: f32 = Bevel::SMOOTHING_MAX; + +/// Bevel Smooth's and Directional Distance's largest Distance, as a share of the texture +pub const SMOOTH_DISTANCE_MAX: f32 = 0.3; + +/// Bevel Smooth's largest Smoothing +pub const BEVEL_SMOOTHING_MAX: f32 = BevelSmooth::SMOOTHING_MAX; + +/// The most colors `colors` takes at once +const GRADIENT_COLORS_GIVEN_MAX: usize = 16; + +/// The fewest colors a gradient's Color Quantity uses +pub const GRADIENT_QUANTITY_MIN: u8 = 2; + +/// Stylized lighting's Sun Intensity end +pub const SUN_INTENSITY_MAX: f32 = 10.0; +/// Environment lighting's Height Intensity end +const HEIGHT_INTENSITY_MAX: f32 = 8.0; + +/// The Gradient filter as the library adds it: black, mid gray and white at 0, 0.5 and 1 (the other seven colors wait white at 1) +fn library_gradient() -> Filter { + let quantity = 3; + let mut colors = vec![[0.0; 3], [MID_GRAY; 3]]; + colors.resize(usize::from(Filter::MAX_GRADIENT_COLORS), [1.0; 3]); + let mut positions = vec![0.0, 0.5]; + positions.resize(colors.len(), 1.0); + Filter::GradientMap { colors, positions, quantity: Some(quantity), input: GradientInput::LIBRARY, linear: true, debug: false } +} + +/// The Baked Lighting Stylized filter as the library adds it: a sun 45° up in front, full sky light, no diffuse AO +pub fn library_baked_lighting() -> Filter { + Filter::BakedLighting { azimuth: 0.0, elevation: 45.0, light: 1.0, ambient: 1.0, occlusion: 0.0, stylized: Some(Box::new(StylizedLighting::library())) } +} + +/// The effect for library filter `id` with its defaults, then the parameters in `p` pub fn build(id: &str, p: &Value) -> Result { - let cmd = "effect.add.filter"; - let d = find(id).ok_or_else(|| bad(cmd, format!("unknown filter `{id}` (see filter.list)")))?; - let mut f = match d.id { + build_for("effect.add.filter", id, p) +} + +/// The effect for library filter `id` with its defaults, then the parameters in `p`; errors name `cmd` (`effect.set` swaps a filter with it) +pub(crate) fn build_for(cmd: &str, id: &str, p: &Value) -> Result { + let def = find(id).ok_or_else(|| bad(cmd, format!("unknown filter `{id}` (see filter.list)")))?; + let mut filter = match def.id { "invert" => Filter::Invert, - "threshold" => Filter::Threshold { level: 0.5 }, - "blur" => Filter::Blur { radius: 2.0 }, + "threshold" => Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }, + "blur" => Filter::Blur { radius: 0.3 * Filter::BLUR_INTENSITY, wrap: false }, "sharpen" => Filter::Sharpen { amount: 1.0 }, - "hsl" => Filter::Hsl { hue: 0.0, saturation: 0.0, lightness: 0.0 }, - "contrastLuminosity" => Filter::ContrastLuminosity { contrast: 0.3, luminosity: 0.0 }, + "hsl" => Filter::Hsl { hue: 0.0, saturation: 0.0, lightness: 0.0, perceptive: true }, + "contrastLuminosity" => Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.0 }, + "colorCorrect" => Filter::ColorCorrect { shadows: NEUTRAL_TONE, midtones: NEUTRAL_TONE, highlights: NEUTRAL_TONE }, "colorBalance" => Filter::ColorBalance { shadows: [0.0; 3], midtones: [0.0; 3], highlights: [0.0; 3] }, - "gradientMap" => Filter::GradientMap { colors: vec![[0.02, 0.02, 0.04], [0.45, 0.16, 0.05], [1.0, 0.85, 0.55]] }, - "posterize" => Filter::Posterize { levels: 4.0 }, - "clamp" => Filter::Clamp { min: 0.2, max: 0.8 }, - "histogramScan" => Filter::HistogramScan { position: 0.5, contrast: 0.5 }, + "gradientMap" => library_gradient(), + "gradientCurve" => LIBRARY_GRADIENT_CURVE, + "gradientDynamic" => LIBRARY_GRADIENT_DYNAMIC, + "posterize" => Filter::Posterize { levels: 8.0, alpha: false }, + "clamp" => Filter::Clamp { min: 0.0, max: 1.0 }, + "smoothstep" => Filter::Smoothstep { min: 0.0, max: 1.0 }, + "heightAdjust" => Filter::HeightAdjust { invert: false, offset: 0.0, multiply: 1.0 }, + "histogramScan" => Filter::HistogramScan { position: 0.5, contrast: 0.0, invert_position: false }, "histogramRange" => Filter::HistogramRange { range: 0.5, position: 0.5 }, - "histogramShift" => Filter::HistogramShift { offset: 0.25 }, - "warp" => Filter::Warp { intensity: 16.0, scale: 4.0, seed: 1 }, + "histogramShift" => Filter::HistogramShift { offset: 0.0 }, + "warp" => Filter::SourceWarp(SourceWarp::LIBRARY), "blurDirectional" => Filter::DirectionalBlur { radius: 16.0, angle: 0.0 }, - "slopeBlur" => Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1 }, - "highPass" => Filter::HighPass { radius: 8.0 }, + "slopeBlur" => Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY), + "highPass" => Filter::HighPass { radius: 3.0 * Filter::BLUR_INTENSITY, space: HighpassSpace::Working, alpha: false }, "edgeDetect" => Filter::EdgeDetect { width: 2.0 }, - "warpDirectional" => Filter::DirectionalWarp { intensity: 16.0, angle: 0.0, scale: 4.0, seed: 1 }, - "grayscale" => Filter::Grayscale, + "grayscale" => Filter::GrayscaleConversion(GrayscaleConversion::LIBRARY), "normalInvert" => Filter::NormalInvert, - "bevel" => Filter::Bevel { width: 16.0 }, - "mosaic" => Filter::Mosaic { size: 32.0 }, - "glow" => Filter::Glow { radius: 16.0, amount: 1.0 }, + "bevel" => Filter::DistanceBevel(Bevel::LIBRARY), + "bevelSmooth" => Filter::BevelSmooth(BevelSmooth::LIBRARY), + "directionalDistance" => Filter::DirectionalDistance(DirectionalDistance::LIBRARY), + "mosaic" => Filter::Mosaic { size: Filter::pixel_size(32.0), alpha: true }, + "fxaa" => Filter::Fxaa { alpha: false }, + "anisotropicKuwahara" => Filter::AnisotropicKuwahara(AnisotropicKuwahara::LIBRARY), + "pbrValidate" => Filter::PbrValidate(PbrValidate::LIBRARY), + "heightToNormal" => Filter::HeightToNormal(HeightToNormal::LIBRARY), + "colorMatch" => Filter::ColorMatch(ColorMatch::LIBRARY), + "mirror" => Filter::Mirror(Mirror::LIBRARY), + "transform" => Filter::Transform(TileTransform::LIBRARY), + "maskOutline" => Filter::MaskOutline(MaskOutline::LIBRARY), + "glow" => LIBRARY_GLOW, + "dropShadow" => LIBRARY_DROP_SHADOW, "replaceColor" => Filter::ReplaceColor { from: [0.5, 0.05, 0.05], to: [0.05, 0.15, 0.5], tolerance: 0.2, softness: 0.15 }, - "bakedLighting" => Filter::BakedLighting { azimuth: 45.0, elevation: 45.0, light: 0.8, ambient: 0.4, occlusion: 1.0 }, + "bakedLighting" => library_baked_lighting(), + "bakedLightingEnvironment" => LIBRARY_ENVIRONMENT_LIGHTING, "levels" => { - let mut l = Levels::default(); crate::mask_cmds::levels_from(cmd, p, &mut l)?; - return Ok(EffectKind::Levels(l)); + let mut levels = Levels::default(); + crate::mask_cmds::levels_from(cmd, p, &mut levels)?; + return Ok(EffectKind::Levels(levels)); } finish => return mat_finish(finish).map(EffectKind::Material).ok_or_else(|| bad(cmd, format!("unknown filter `{id}`"))), }; - apply(p, &mut f, cmd)?; - Ok(EffectKind::Filter(f)) + + // A new gradient given its colors ramps through all of them, or the `quantity` given, evenly unless places are given too + if let Filter::GradientMap { positions, quantity, .. } = &mut filter + && p.get("colors").is_some() + { + *quantity = None; + if p.get("positions").is_none() { + positions.clear(); + } + } + + apply_named(Some(id), p, &mut filter, cmd)?; + Ok(EffectKind::Filter(filter)) } /// A material finish: procedural roughness and height (tri-planar, so it is seamless). @@ -157,93 +381,508 @@ fn mat_finish(id: &str) -> Option { Some(fill) } -/// Scalar parameters of a filter for editors: (param key, label, value, min, max). Colors -/// (color balance, gradient map) and the HSL hue have their own editors. -pub fn scalar_params(f: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f32)> { - match f { - Filter::Blur { radius } => vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0)], - Filter::Sharpen { amount } => vec![("amount", "Amount", *amount, 0.0, 5.0)], - Filter::Threshold { level } => vec![("level", "Level", *level, 0.0, 1.0)], +/// Scalar parameters of a filter for editors: (param key, label, value, min, max); colors (color balance, gradient map) and the HSL hue have their own editors +pub fn scalar_params(filter: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f32)> { + match filter { + Filter::Blur { radius, .. } => vec![("intensity", "Blur Intensity", *radius / Filter::BLUR_INTENSITY, 0.0, BLUR_INTENSITY_SLIDER_MAX)], + Filter::Sharpen { amount } => vec![("amount", "Sharpen Intensity", *amount, 0.0, SHARPEN_SLIDER_MAX)], + Filter::Threshold { level, .. } => vec![("level", "Threshold", *level, 0.0, 1.0)], Filter::Hsl { saturation, lightness, .. } => { vec![("saturation", "Saturation", *saturation, -1.0, 1.0), ("lightness", "Lightness", *lightness, -1.0, 1.0)] } Filter::ContrastLuminosity { contrast, luminosity } => { vec![("contrast", "Contrast", *contrast, -1.0, 1.0), ("luminosity", "Luminosity", *luminosity, -1.0, 1.0)] } - Filter::Posterize { levels } => vec![("levels", "Steps", *levels, 2.0, 64.0)], - Filter::Clamp { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)], - Filter::HistogramScan { position, contrast } => vec![("position", "Position", *position, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], + Filter::Posterize { levels, .. } => vec![("levels", "Colors Amount", *levels, POSTERIZE_LEVELS_MIN, POSTERIZE_LEVELS_MAX)], + Filter::Clamp { min, max } => vec![("min", "Min", *min, 0.0, 1.0), ("max", "Max", *max, 0.0, 1.0)], + Filter::Smoothstep { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)], + Filter::HeightAdjust { offset, multiply, .. } => { + vec![("offset", "Offset", *offset, -HEIGHT_OFFSET_MAX, HEIGHT_OFFSET_MAX), ("multiply", "Multiply", *multiply, 0.0, HEIGHT_MULTIPLY_MAX)] + } + Filter::HistogramScan { position, contrast, .. } => vec![("position", "Position", *position, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], Filter::HistogramRange { range, position } => vec![("range", "Range", *range, 0.0, 1.0), ("position", "Position", *position, 0.0, 1.0)], - Filter::HistogramShift { offset } => vec![("offset", "Offset", *offset, -1.0, 1.0)], - Filter::Warp { intensity, scale, seed } => { + Filter::HistogramShift { offset } => vec![("position", "Position", Filter::shift_position(*offset), 0.0, 1.0)], + Filter::Warp { intensity, scale, seed, .. } => { vec![ - ("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0), - ("scale", "Noise scale", *scale, 0.5, 64.0), - ("seed", "Seed", *seed as f32, 0.0, 999.0), + ("intensity", "Intensity", *intensity, 0.0, TEXELS_SLIDER_MAX), + ("scale", "Source Tiling", *scale, NOISE_TILING_MIN, NOISE_TILING_MAX), + ("seed", "Seed", *seed as f32, 0.0, SEED_SLIDER_MAX), ] } Filter::DirectionalBlur { radius, angle } => { - vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0), ("angle", "Angle (degrees)", *angle, 0.0, 360.0)] - } - Filter::SlopeBlur { radius, scale, seed } => { vec![ - ("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0), - ("scale", "Slope scale", *scale, 0.5, 64.0), - ("seed", "Seed", *seed as f32, 0.0, 999.0), + ("intensity", "Intensity", *radius / Filter::BLUR_INTENSITY, 0.0, BLUR_INTENSITY_SLIDER_MAX), + ("angle", "Angle", *angle, 0.0, FULL_TURN_DEGREES), ] } - Filter::HighPass { radius } => vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0)], - Filter::EdgeDetect { width } => vec![("width", "Width (texels at 2K)", *width, 0.0, 64.0)], - Filter::DirectionalWarp { intensity, angle, scale, seed } => { + Filter::SlopeBlur { radius, scale, seed, .. } => { vec![ - ("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0), - ("angle", "Angle (degrees)", *angle, 0.0, 360.0), - ("scale", "Noise scale", *scale, 0.5, 64.0), - ("seed", "Seed", *seed as f32, 0.0, 999.0), + ("radius", "Intensity", *radius, 0.0, TEXELS_SLIDER_MAX), + ("scale", "Source Tiling", *scale, NOISE_TILING_MIN, NOISE_TILING_MAX), + ("seed", "Seed", *seed as f32, 0.0, SEED_SLIDER_MAX), ] } - Filter::Bevel { width } => vec![("width", "Width (texels at 2K)", *width, 0.0, 128.0)], - Filter::Mosaic { size } => vec![("size", "Cell size (texels at 2K)", *size, 1.0, 256.0)], + Filter::HighPass { radius, .. } => vec![("intensity", "Radius", *radius / Filter::BLUR_INTENSITY, 0.0, BLUR_INTENSITY_SLIDER_MAX)], + Filter::GrayscaleConversion(conversion) => conversion_params(conversion), + Filter::AnisotropicKuwahara(kuwahara) => vec![ + ("radius", "Radius", kuwahara.radius, 0.0, AnisotropicKuwahara::MAX_RADIUS), + ("smoothness", "Smoothness", kuwahara.smoothness, 0.0, 1.0), + ("sharpness", "Sharpness", kuwahara.sharpness, AnisotropicKuwahara::MIN_SHARPNESS, 1.0), + ("tensorSmoothness", "Tensor Smoothness", kuwahara.tensor_smoothness, 0.0, 1.0), + ("anisotropy", "Anisotropy", kuwahara.anisotropy, 0.0, 1.0), + ("angle", "Anisotropy Angle", kuwahara.angle, 0.0, FULL_TURN_DEGREES), + ], + Filter::Grayscale => conversion_params(&GrayscaleConversion::of_luminance()), + Filter::HeightToNormal(converter) if converter.world_units => vec![ + ("surfaceSize", "Surface Size (cm)", converter.surface_size, HeightToNormal::MIN_SURFACE_SIZE, HeightToNormal::MAX_SURFACE_SIZE), + ("heightDepth", "Height Depth (cm)", converter.height_depth, 0.0, HeightToNormal::MAX_HEIGHT_DEPTH), + ], + Filter::HeightToNormal(converter) => vec![("normalIntensity", "Normal Intensity", converter.intensity, 0.0, HeightToNormal::MAX_INTENSITY)], + Filter::ColorMatch(matcher) => { + vec![ + ("hue", "Hue", matcher.hue, 0.0, FULL_TURN_DEGREES), + ("chroma", "Chroma", matcher.chroma, 0.0, ColorMatch::MAX_CHROMA), + ("luma", "Luma", matcher.luma, 0.0, ColorMatch::MAX_LUMA), + ] + } + Filter::EdgeDetect { width } => vec![("width", "Width", *width, 0.0, EDGE_WIDTH_SLIDER_MAX)], + Filter::DirectionalWarp { intensity, angle, scale, seed, .. } => { + vec![ + ("intensity", "Intensity", *intensity, 0.0, TEXELS_SLIDER_MAX), + ("angle", "Angle", *angle, 0.0, FULL_TURN_DEGREES), + ("scale", "Source Tiling", *scale, NOISE_TILING_MIN, NOISE_TILING_MAX), + ("seed", "Seed", *seed as f32, 0.0, SEED_SLIDER_MAX), + ] + } + Filter::Bevel { width, .. } => vec![("width", "Distance", *width, 0.0, TEXELS_SLIDER_MAX)], + Filter::Mosaic { size, .. } => vec![("pixelsAmount", "Pixels Amount", Filter::pixels_amount(*size), 1.0, MOSAIC_PIXELS_SLIDER_MAX)], + Filter::DistanceBevel(bevel) => { + vec![("distance", "Distance", bevel.distance, -1.0, 1.0), ("smoothing", "Smoothing", bevel.smoothing, 0.0, DISTANCE_BEVEL_SMOOTHING_MAX)] + } + Filter::SourceWarp(warp) => { + let mut params = vec![("seed", "Seed", warp.seed as f32, 0.0, SEED_SLIDER_MAX), ("intensity", "Intensity", warp.intensity, 0.0, 1.0)]; + if warp.mode != WarpMode::Warp { + params.push(("angle", "Angle", warp.angle, 0.0, FULL_TURN_DEGREES)); + } + params.extend([ + ("sourceBlur", "Source Blur", warp.source.blur, 0.0, 1.0), + ("sourceBalance", "Source Balance", warp.source.balance, 0.0, 1.0), + ("sourceContrast", "Source Contrast", warp.source.contrast, 0.0, 1.0), + ("sourceTiling", "Source Tiling", warp.source.tiling, SOURCE_TILING_MIN, SOURCE_TILING_MAX), + ]); + params + } + Filter::SourceSlopeBlur(slope) => vec![ + ("seed", "Seed", slope.seed as f32, 0.0, SEED_SLIDER_MAX), + ("intensity", "Intensity", slope.intensity, 0.0, 1.0), + ("quality", "Quality", slope.quality, 0.0, 1.0), + ("sourceBlur", "Blur", slope.source.blur, 0.0, 1.0), + ("sourceBalance", "Position", slope.source.balance, 0.0, 1.0), + ("sourceContrast", "Contrast", slope.source.contrast, 0.0, 1.0), + ("sourceTiling", "Source Tiling", slope.source.tiling, SOURCE_TILING_MIN, SOURCE_TILING_MAX), + ], + Filter::BevelSmooth(smooth) => vec![ + ("distance", "Distance", smooth.distance, 0.0, SMOOTH_DISTANCE_MAX), + ("smoothing", "Smoothing", smooth.smoothing, 0.0, BEVEL_SMOOTHING_MAX), + ("curveOffset", "Curve Offset", smooth.curve_offset, -1.0, 1.0), + ("curveShape", "Curve Shape", smooth.curve_shape, -1.0, 1.0), + ("maskThreshold", "Mask Threshold", smooth.threshold, 0.0, 1.0), + ("distanceMapMultiplier", "Distance Map Multiplier", smooth.multiplier, 0.0, 1.0), + ], + Filter::DirectionalDistance(trail) => vec![ + ("distance", "Distance", trail.distance, 0.0, SMOOTH_DISTANCE_MAX), + ("angle", "Angle", trail.angle, 0.0, FULL_TURN_DEGREES), + ("contrast", "Contrast", trail.contrast, 0.0, 1.0), + ("distanceMapMultiplier", "Distance Map Multiplier", trail.multiplier, 0.0, 1.0), + ], + // Only the offset of the axis the mode mirrors across shows + Filter::Mirror(mirror) => match mirror.mode { + MirrorMode::AxisX => vec![("axisXOffset", "Axis X Offset", mirror.offset[0], 0.0, 1.0)], + MirrorMode::AxisY => vec![("axisYOffset", "Axis Y Offset", mirror.offset[1], 0.0, 1.0)], + MirrorMode::Corner => Vec::new(), + }, + Filter::MaskOutline(outline) => vec![ + ("threshold", "Threshold", outline.threshold, 0.0, 1.0), + ("width", "Width", outline.width, 0.0, 1.0), + ("blur", "Blur", outline.blur, 0.0, 1.0), + ("curveShape", "Curve Shape", outline.curve, -1.0, 1.0), + ], Filter::Glow { radius, amount } => { - vec![("radius", "Radius (texels at 2K)", *radius, 0.0, 128.0), ("amount", "Amount", *amount, 0.0, 5.0)] + vec![("radius", "Width", *radius, 0.0, TEXELS_SLIDER_MAX), ("amount", "Amount", *amount, 0.0, GLOW_AMOUNT_SLIDER_MAX)] } - Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } => vec![ - ("azimuth", "Light azimuth (degrees)", *azimuth, 0.0, 360.0), - ("elevation", "Light elevation (degrees)", *elevation, -90.0, 90.0), - ("light", "Light intensity", *light, 0.0, 4.0), - ("ambient", "Ambient", *ambient, 0.0, 2.0), - ("occlusion", "Ambient occlusion", *occlusion, 0.0, 1.0), + Filter::HaloGlow { width, spread, opacity, .. } => { + vec![("width", "Width", *width, -1.0, 1.0), ("spread", "Spread", *spread, 0.0, 1.0), ("opacity", "Opacity", *opacity, 0.0, 1.0)] + } + Filter::DropShadow { angle, distance, size, spread, opacity, .. } => vec![ + ("angle", "Angle", *angle, 0.0, FULL_TURN_DEGREES), + ("distance", "Distance", *distance, -Filter::SHADOW_DISTANCE_MAX, Filter::SHADOW_DISTANCE_MAX), + ("size", "Size", *size, 0.0, 1.0), + ("spread", "Spread", *spread, 0.0, 1.0), + ("opacity", "Opacity", *opacity, 0.0, 1.0), + ], + Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, .. } => vec![ + ("light", "Sun Intensity", *light, 0.0, SUN_INTENSITY_MAX), + ("azimuth", "Horizontal Angle", *azimuth, 0.0, FULL_TURN_DEGREES), + ("elevation", "Vertical Angle", *elevation, 0.0, FULL_TURN_DEGREES), + ("ambient", "Sky Intensity", *ambient, 0.0, SKY_INTENSITY_SLIDER_MAX), + ("occlusion", "Diffuse AO", *occlusion, 0.0, 1.0), + ], + Filter::EnvironmentLighting { horizontal, vertical, exposure, height_intensity, ambient_occlusion, specular_occlusion } => vec![ + ("horizontalRotation", "Horizontal Rotation", *horizontal, 0.0, FULL_TURN_DEGREES), + ("verticalRotation", "Vertical Rotation", *vertical, 0.0, FULL_TURN_DEGREES), + ("exposure", "Exposure", *exposure, -Filter::ENVIRONMENT_EXPOSURE_STOPS, Filter::ENVIRONMENT_EXPOSURE_STOPS), + ("heightIntensity", "Height Intensity", *height_intensity, 0.0, HEIGHT_INTENSITY_MAX), + ("ambientOcclusion", "Ambient Occlusion Intensity", *ambient_occlusion, 0.0, 1.0), + ("specularOcclusion", "Specular Occlusion Intensity", *specular_occlusion, 0.0, 1.0), ], Filter::ReplaceColor { tolerance, softness, .. } => { vec![("tolerance", "Tolerance", *tolerance, 0.0, 1.0), ("softness", "Softness", *softness, 0.0, 1.0)] } - Filter::Invert | Filter::ColorBalance { .. } | Filter::GradientMap { .. } | Filter::Grayscale | Filter::NormalInvert => Vec::new(), + Filter::GradientMap { input, .. } => vec![ + ("blur", "Blur Intensity", input.blur, 0.0, BLUR_INTENSITY_SLIDER_MAX), + ("balance", "Balance", input.balance, 0.0, 1.0), + ("contrast", "Contrast", input.contrast, 0.0, 1.0), + ], + Filter::GradientCurve { balance, contrast, .. } => vec![("balance", "Balance", *balance, 0.0, 1.0), ("contrast", "Contrast", *contrast, 0.0, 1.0)], + Filter::GradientDynamic { position, .. } => vec![("position", "Gradient Input Position", *position, 0.0, 1.0)], + Filter::Invert + | Filter::InvertOff + | Filter::ColorBalance { .. } + | Filter::ColorCorrect { .. } + | Filter::NormalInvert + | Filter::Fxaa { .. } + | Filter::PbrValidate(_) + | Filter::Transform(_) + | Filter::Empty => Vec::new(), } } -/// Set the parameters of `f` given in `p` (clamped to their ranges); `effect.set` uses it too. -pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { - let set = |slot: &mut f32, key: &str, lo: f32, hi: f32| { - if let Some(v) = f32p(p, key) { - *slot = v.clamp(lo, hi); +/// Grayscale Conversion's sliders: Balance and Contrast, then the Channels Weights' Red, Green, Blue and Alpha in that mode +fn conversion_params(conversion: &GrayscaleConversion) -> Vec<(&'static str, &'static str, f32, f32, f32)> { + let mut params = vec![("balance", "Balance", conversion.balance, 0.0, 1.0), ("contrast", "Contrast", conversion.contrast, 0.0, 1.0)]; + if conversion.mode == ConversionMode::ChannelsWeights { + let [red, green, blue, alpha] = conversion.weights; + params.extend([ + ("red", "Red", red, 0.0, 1.0), + ("green", "Green", green, 0.0, 1.0), + ("blue", "Blue", blue, 0.0, 1.0), + ("alpha", "Alpha", alpha, 0.0, 1.0), + ]); + } + params +} + +/// The keys `effect.set` takes for Grayscale Conversion +const CONVERSION_KEYS: [&str; 9] = ["channelInput", "invert", "balance", "contrast", "mode", "red", "green", "blue", "alpha"]; + +/// Set the Grayscale Conversion settings given in `p`: channelInput (currentChannel or customInput), invert, balance, contrast, mode and the red, green, blue and alpha weights +fn apply_conversion(p: &Value, conversion: &mut GrayscaleConversion, cmd: &str) -> Result<()> { + conversion.custom_input = two_way(p, "channelInput", CURRENT_CHANNEL, CUSTOM_INPUT, cmd)?.unwrap_or(conversion.custom_input); + set_bool(p, "invert", &mut conversion.invert, cmd)?; + conversion.mode = choice(p, "mode", &ConversionMode::ALL, ConversionMode::id, cmd)?.unwrap_or(conversion.mode); + + let [red, green, blue, alpha] = &mut conversion.weights; + for (key, slot) in + [("balance", &mut conversion.balance), ("contrast", &mut conversion.contrast), ("red", red), ("green", green), ("blue", blue), ("alpha", alpha)] + { + if let Some(value) = f32p(p, key) { + *slot = value.clamp(0.0, 1.0); + } + } + Ok(()) +} + +/// Make a gradient use its first `wanted` colors: an evenly spaced ramp keeps its places from now on, and each added color starts at 1 as the ramp's color there +fn set_quantity(colors: &mut Vec<[f32; 3]>, positions: &mut Vec, quantity: &mut Option, wanted: u8) { + let used = quantity.map_or(colors.len(), usize::from).min(colors.len()); + + // The used colors without a place keep the even place the ramp gave them + let last = used.saturating_sub(1).max(1) as f32; + for index in positions.len()..used { + positions.push(index as f32 / last); + } + + let wanted_len = usize::from(wanted); + + // At 1 the blend space does not matter: only the rightmost stop counts, which need not be the last in the list + let used_colors = colors.get(..used).unwrap_or_default(); + let fill = texturecraft_core::gradient_input::ramp(used_colors, positions, true, 1.0).unwrap_or([1.0; 3]); + if colors.len() < wanted_len { + colors.resize(wanted_len, fill); + } + if positions.len() < wanted_len { + positions.resize(wanted_len, 1.0); + } + *quantity = Some(wanted); +} + +/// Set the Mirror settings given in `p`: displayDebug, mode, axisXOffset, axisYOffset, invertAxisX, invertAxisY and cornerType +fn apply_mirror(p: &Value, mirror: &mut Mirror, cmd: &str) -> Result<()> { + mirror.mode = choice(p, "mode", &MirrorMode::ALL, MirrorMode::id, cmd)?.unwrap_or(mirror.mode); + mirror.corner = choice(p, "cornerType", &MirrorCorner::ALL, MirrorCorner::id, cmd)?.unwrap_or(mirror.corner); + + let [offset_x, offset_y] = &mut mirror.offset; + for (key, slot) in [("axisXOffset", offset_x), ("axisYOffset", offset_y)] { + if let Some(offset) = f32p(p, key) { + *slot = offset.clamp(0.0, 1.0); + } + } + + let [invert_x, invert_y] = &mut mirror.invert; + for (key, slot) in [("displayDebug", &mut mirror.debug), ("invertAxisX", invert_x), ("invertAxisY", invert_y)] { + set_bool(p, key, slot, cmd)?; + } + Ok(()) +} + +/// The choice among `all` whose id (`id`) `p` gives under `key`, if it gives one; an unknown id is refused +pub(crate) fn choice(p: &Value, key: &str, all: &[T], id: fn(T) -> &'static str, cmd: &str) -> Result> { + if p.get(key).is_none() { + return Ok(None); + } + + let given = strp(p, key).unwrap_or_default(); + let found = all.iter().copied().find(|choice| id(*choice) == given); + found.map(Some).ok_or_else(|| { + let ids: Vec<&str> = all.iter().map(|choice| id(*choice)).collect(); + bad(cmd, format!("`{key}` must be {}", one_of(&ids))) + }) +} + +/// Which of two ids `p` gives under `key` (true: `on_id`), if it gives one; any other value is refused +pub(crate) fn two_way(p: &Value, key: &str, off_id: &str, on_id: &str, cmd: &str) -> Result> { + if p.get(key).is_none() { + return Ok(None); + } + + match strp(p, key) { + Some(id) if id == off_id => Ok(Some(false)), + Some(id) if id == on_id => Ok(Some(true)), + _ => Err(bad(cmd, format!("`{key}` must be {off_id} or {on_id}"))), + } +} + +/// Set `slot` to the true or false `p` gives under `key`, if it gives one; any other value is refused +pub(crate) fn set_bool(p: &Value, key: &str, slot: &mut bool, cmd: &str) -> Result<()> { + if p.get(key).is_some() { + *slot = boolp(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be true or false")))?; + } + Ok(()) +} + +/// Set `slot` to the color `p` gives under `key` (clamped to 0..1), if it gives one; any other value, null too, is refused +pub(crate) fn set_color(p: &Value, key: &str, slot: &mut [f32; 3], cmd: &str) -> Result<()> { + if p.get(key).is_some() { + let rgb = color_param(cmd, p, key)?.ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")")))?; + *slot = rgb.map(|x| x.clamp(0.0, 1.0)); + } + Ok(()) +} + +/// An array of exactly three finite numbers +fn three_numbers(given: &Value) -> Option<[f32; 3]> { + let [first, second, third] = given.as_array()?.as_slice() else { return None }; + let number = |value: &Value| value.as_f64().map(|x| x as f32).filter(|x| x.is_finite()); + Some([number(first)?, number(second)?, number(third)?]) +} + +/// The allowed values of a setting as its error message lists them: "a, b or c" +fn one_of(allowed: &[T]) -> String { + let words: Vec = allowed.iter().map(ToString::to_string).collect(); + match words.split_last() { + Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")), + _ => words.concat(), + } +} + +/// Whether `p` asks `filter`, a warp saved before the warp modes, for a mode it can't hold: Directional Warp's former id on a Warp, or a `warpMode` it is not +pub(crate) fn changes_saved_warp_mode(named: &str, p: &Value, filter: &Filter) -> bool { + let saved_mode = match filter { + Filter::Warp { .. } => WarpMode::Warp, + Filter::DirectionalWarp { .. } => WarpMode::Directional, + _ => return false, + }; + match p.get("warpMode") { + Some(mode) => mode.as_str() != Some(saved_mode.id()), + None => is_directional_warp(named) && saved_mode != WarpMode::Directional, + } +} + +/// [`apply`] for the filter id `named`, if one is given: Directional Warp's former id turns a Warp to Directional mode unless `warpMode` is given +pub(crate) fn apply_named(named: Option<&str>, p: &Value, filter: &mut Filter, cmd: &str) -> Result<()> { + apply(p, filter, cmd)?; + + if let Filter::SourceWarp(warp) = filter + && named.is_some_and(is_directional_warp) + && p.get("warpMode").is_none() + { + warp.mode = WarpMode::Directional; + } + Ok(()) +} + +/// Set the parameters of `filter` given in `p` (clamped to their ranges); `effect.set` uses it too +pub(crate) fn apply(p: &Value, filter: &mut Filter, cmd: &str) -> Result<()> { + let set = |slot: &mut f32, key: &str, low: f32, high: f32| { + if let Some(value) = f32p(p, key) { + *slot = value.clamp(low, high); } }; let seed = |slot: &mut u32| { - if let Some(v) = u64p(p, "seed") { - *slot = u32::try_from(v).unwrap_or(u32::MAX); + if let Some(value) = u64p(p, "seed") { + *slot = u32::try_from(value).unwrap_or(u32::MAX); } }; + let divider = |slot: &mut u16| -> Result<()> { + if p.get("divider").is_some() { + let value = u64p(p, "divider").and_then(|value| u16::try_from(value).ok()).filter(|value| Filter::DIVIDERS.contains(value)); + *slot = value.ok_or_else(|| bad(cmd, format!("`divider` must be {}", one_of(&Filter::DIVIDERS))))?; + } + Ok(()) + }; + + // A blur's Intensity in the reference workflow's unit (radius in texels at 2K ÷ Filter::BLUR_INTENSITY) + let blur_intensity = |radius: &mut f32| { + if let Some(intensity) = f32p(p, "intensity") { + *radius = (intensity * Filter::BLUR_INTENSITY).clamp(0.0, TEXELS_MAX); + } + }; + let switch = |slot: &mut bool, key: &str| set_bool(p, key, slot, cmd); + let shade = |slot: &mut [f32; 3]| set_color(p, "color", slot, cmd); let angle = |slot: &mut f32| { - if let Some(v) = f32p(p, "angle") { - *slot = v.rem_euclid(360.0); + if let Some(degrees) = f32p(p, "angle") { + *slot = degrees.rem_euclid(FULL_TURN_DEGREES); } }; - match f { - Filter::Invert | Filter::Grayscale | Filter::NormalInvert => {} - Filter::Threshold { level } => set(level, "level", 0.0, 1.0), - Filter::Blur { radius } => set(radius, "radius", 0.0, 256.0), - Filter::Sharpen { amount } => set(amount, "amount", 0.0, 10.0), - Filter::Hsl { hue, saturation, lightness } => { + + match filter { + Filter::Invert | Filter::InvertOff => { + let mut on = matches!(filter, Filter::Invert); + switch(&mut on, "invert")?; + *filter = if on { Filter::Invert } else { Filter::InvertOff }; + } + Filter::NormalInvert | Filter::Empty => {} + // A Grayscale saved before the settings takes its luminance weights on its first edit, so it looks the same + Filter::Grayscale => { + if CONVERSION_KEYS.iter().any(|key| p.get(key).is_some()) { + let mut conversion = GrayscaleConversion::of_luminance(); + apply_conversion(p, &mut conversion, cmd)?; + *filter = Filter::GrayscaleConversion(conversion); + } + } + Filter::GrayscaleConversion(conversion) => apply_conversion(p, conversion, cmd)?, + Filter::AnisotropicKuwahara(kuwahara) => { + kuwahara.custom_input = two_way(p, "extractDirection", CURRENT_CHANNEL, CUSTOM_INPUT, cmd)?.unwrap_or(kuwahara.custom_input); + set(&mut kuwahara.radius, "radius", 0.0, AnisotropicKuwahara::MAX_RADIUS); + set(&mut kuwahara.smoothness, "smoothness", 0.0, 1.0); + set(&mut kuwahara.sharpness, "sharpness", AnisotropicKuwahara::MIN_SHARPNESS, 1.0); + set(&mut kuwahara.tensor_smoothness, "tensorSmoothness", 0.0, 1.0); + set(&mut kuwahara.anisotropy, "anisotropy", 0.0, 1.0); + angle(&mut kuwahara.angle); + } + Filter::PbrValidate(validate) => { + validate.mode = choice(p, "validationMode", &ValidationMode::ALL, ValidationMode::id, cmd)?.unwrap_or(validate.mode); + for (key, slot, allowed) in [ + ("albedoDarkRangeThreshold", &mut validate.albedo_dark, PbrValidate::ALBEDO_DARK), + ("metalReflectanceRange", &mut validate.metal_low, PbrValidate::METAL_LOW), + ] { + if p.get(key).is_some() { + let value = u64p(p, key).and_then(|value| u8::try_from(value).ok()).filter(|value| allowed.contains(value)); + *slot = value.ok_or_else(|| bad(cmd, format!("`{key}` must be {}", one_of(&allowed))))?; + } + } + } + Filter::HeightToNormal(converter) => { + switch(&mut converter.overwrite, "overwriteExistingNormal")?; + switch(&mut converter.world_units, "useWorldUnits")?; + set(&mut converter.surface_size, "surfaceSize", HeightToNormal::MIN_SURFACE_SIZE, HeightToNormal::MAX_SURFACE_SIZE); + set(&mut converter.height_depth, "heightDepth", 0.0, HeightToNormal::MAX_HEIGHT_DEPTH); + set(&mut converter.intensity, "normalIntensity", 0.0, HeightToNormal::MAX_INTENSITY); + } + Filter::ColorMatch(matcher) => { + matcher.source_mode = choice(p, "sourceColorMode", &SourceColorMode::ALL, SourceColorMode::id, cmd)?.unwrap_or(matcher.source_mode); + matcher.target_mode = choice(p, "targetColorMode", &TargetColorMode::ALL, TargetColorMode::id, cmd)?.unwrap_or(matcher.target_mode); + set_color(p, "sourceColor", &mut matcher.source_color, cmd)?; + set_color(p, "targetColor", &mut matcher.target_color, cmd)?; + switch(&mut matcher.custom_variation, "customColorVariation")?; + set(&mut matcher.hue, "hue", 0.0, FULL_TURN_DEGREES); + set(&mut matcher.chroma, "chroma", 0.0, ColorMatch::MAX_CHROMA); + set(&mut matcher.luma, "luma", 0.0, ColorMatch::MAX_LUMA); + } + Filter::Threshold { level, mode } => { + set(level, "level", 0.0, 1.0); + *mode = choice(p, "mode", &ThresholdMode::ALL, ThresholdMode::id, cmd)?.unwrap_or(*mode); + } + Filter::Mirror(mirror) => apply_mirror(p, mirror, cmd)?, + Filter::Transform(transform) => crate::tile_transform_params::apply(p, transform, cmd)?, + Filter::SourceWarp(warp) => { + seed(&mut warp.seed); + warp.mode = choice(p, "warpMode", &WarpMode::ALL, WarpMode::id, cmd)?.unwrap_or(warp.mode); + set(&mut warp.intensity, "intensity", 0.0, 1.0); + divider(&mut warp.divider)?; + angle(&mut warp.angle); + if p.get("directions").is_some() { + let count = u64p(p, "directions").and_then(|count| u8::try_from(count).ok()).filter(|count| SourceWarp::DIRECTIONS.contains(count)); + warp.directions = count.ok_or_else(|| bad(cmd, format!("`directions` must be {}", one_of(&SourceWarp::DIRECTIONS))))?; + } + warp.blending = choice(p, "blendingMode", &WarpBlending::ALL, WarpBlending::id, cmd)?.unwrap_or(warp.blending); + warp.source.mode = choice(p, "sourceMode", &WarpSourceMode::ALL, WarpSourceMode::id, cmd)?.unwrap_or(warp.source.mode); + set(&mut warp.source.blur, "sourceBlur", 0.0, 1.0); + set(&mut warp.source.balance, "sourceBalance", 0.0, 1.0); + set(&mut warp.source.contrast, "sourceContrast", 0.0, 1.0); + set(&mut warp.source.tiling, "sourceTiling", SOURCE_TILING_MIN, SOURCE_TILING_MAX); + } + Filter::SourceSlopeBlur(slope) => { + seed(&mut slope.seed); + set(&mut slope.intensity, "intensity", 0.0, 1.0); + divider(&mut slope.divider)?; + slope.blending = choice(p, "blendingMode", &SlopeBlending::ALL, SlopeBlending::id, cmd)?.unwrap_or(slope.blending); + set(&mut slope.quality, "quality", 0.0, 1.0); + slope.source.mode = choice(p, "sourceMode", &WarpSourceMode::ALL, WarpSourceMode::id, cmd)?.unwrap_or(slope.source.mode); + set(&mut slope.source.blur, "sourceBlur", 0.0, 1.0); + set(&mut slope.source.balance, "sourceBalance", 0.0, 1.0); + set(&mut slope.source.contrast, "sourceContrast", 0.0, 1.0); + set(&mut slope.source.tiling, "sourceTiling", SOURCE_TILING_MIN, SOURCE_TILING_MAX); + } + Filter::DistanceBevel(bevel) => { + set(&mut bevel.distance, "distance", -1.0, 1.0); + set(&mut bevel.smoothing, "smoothing", 0.0, DISTANCE_BEVEL_SMOOTHING_MAX); + bevel.corner = choice(p, "cornerType", &BevelCorner::ALL, BevelCorner::id, cmd)?.unwrap_or(bevel.corner); + bevel.blur = choice(p, "blurMode", &BevelBlur::ALL, BevelBlur::id, cmd)?.unwrap_or(bevel.blur); + switch(&mut bevel.wrap, "wrap")?; + } + Filter::BevelSmooth(smooth) => { + smooth.direction = choice(p, "direction", &BevelDirection::ALL, BevelDirection::id, cmd)?.unwrap_or(smooth.direction); + set(&mut smooth.distance, "distance", 0.0, SMOOTH_DISTANCE_MAX); + set(&mut smooth.smoothing, "smoothing", 0.0, BEVEL_SMOOTHING_MAX); + set(&mut smooth.curve_offset, "curveOffset", -1.0, 1.0); + set(&mut smooth.curve_shape, "curveShape", -1.0, 1.0); + set(&mut smooth.threshold, "maskThreshold", 0.0, 1.0); + set(&mut smooth.multiplier, "distanceMapMultiplier", 0.0, 1.0); + switch(&mut smooth.wrap, "wrap")?; + } + Filter::DirectionalDistance(trail) => { + set(&mut trail.distance, "distance", 0.0, SMOOTH_DISTANCE_MAX); + angle(&mut trail.angle); + set(&mut trail.contrast, "contrast", 0.0, 1.0); + set(&mut trail.multiplier, "distanceMapMultiplier", 0.0, 1.0); + } + Filter::MaskOutline(outline) => { + outline.position = choice(p, "maskPosition", &OutlinePosition::ALL, OutlinePosition::id, cmd)?.unwrap_or(outline.position); + switch(&mut outline.from_black, "startFromBlack")?; + set(&mut outline.threshold, "threshold", 0.0, 1.0); + set(&mut outline.width, "width", 0.0, 1.0); + set(&mut outline.blur, "blur", 0.0, 1.0); + set(&mut outline.curve, "curveShape", -1.0, 1.0); + } + Filter::Blur { radius, wrap: wraps } => { + set(radius, "radius", 0.0, TEXELS_MAX); + blur_intensity(radius); + switch(wraps, "wrap")?; + } + Filter::Sharpen { amount } => set(amount, "amount", 0.0, SHARPEN_AMOUNT_MAX), + Filter::Hsl { hue, saturation, lightness, perceptive } => { + *perceptive = two_way(p, "mode", "regular", "perceptive", cmd)?.unwrap_or(*perceptive); set(hue, "hue", -1.0, 1.0); set(saturation, "saturation", -1.0, 1.0); set(lightness, "lightness", -1.0, 1.0); @@ -252,81 +891,195 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { set(contrast, "contrast", -1.0, 1.0); set(luminosity, "luminosity", -1.0, 1.0); } + Filter::ColorCorrect { shadows, midtones, highlights } => { + for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] { + if let Some(given) = p.get(key) { + let [contrast, luminosity, saturation] = + three_numbers(given).ok_or_else(|| bad(cmd, format!("`{key}` must be [contrast, luminosity, saturation]")))?; + *slot = [contrast.clamp(-1.0, 1.0), luminosity.clamp(-1.0, 1.0), saturation.clamp(0.0, 1.0)]; + } + } + } Filter::ColorBalance { shadows, midtones, highlights } => { for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] { - if let Some(val) = p.get(key).filter(|v| !v.is_null()) { - let v = color_of(val).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; - *slot = v.map(|x| x.clamp(-1.0, 1.0)); + if let Some(given) = p.get(key).filter(|given| !given.is_null()) { + let offsets = color_of(given).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?; + *slot = offsets.map(|x| x.clamp(-1.0, 1.0)); } } } - Filter::GradientMap { colors } => { + Filter::GradientMap { colors, positions, quantity, input, linear, debug } => { if let Some(list) = p.get("colors") { - let parsed: Option> = list.as_array().and_then(|a| a.iter().map(|c| color_of(c).map(|v| v.map(|x| x.clamp(0.0, 1.0)))).collect()); + let parsed: Option> = + list.as_array().and_then(|given| given.iter().map(|color| color_of(color).map(|rgb| rgb.map(|x| x.clamp(0.0, 1.0)))).collect()); match parsed { - Some(c) if (1..=16).contains(&c.len()) => *colors = c, - _ => return Err(bad(cmd, "`colors` must be 1 to 16 colors ([r, g, b] linear or \"#rrggbb\" sRGB)")), + Some(parsed) if (1..=GRADIENT_COLORS_GIVEN_MAX).contains(&parsed.len()) => *colors = parsed, + _ => return Err(bad(cmd, format!("`colors` must be 1 to {GRADIENT_COLORS_GIVEN_MAX} colors ([r, g, b] linear or \"#rrggbb\" sRGB)"))), } } + if let Some(list) = p.get("positions") { + let parsed: Option> = + list.as_array().and_then(|given| given.iter().map(|place| place.as_f64().map(|place| (place as f32).clamp(0.0, 1.0))).collect()); + match parsed { + Some(parsed) if parsed.len() <= colors.len() => *positions = parsed, + _ => return Err(bad(cmd, "`positions` must be numbers in 0..1, at most one per color")), + } + } + if p.get("quantity").is_some() { + let wanted = u64p(p, "quantity") + .and_then(|count| u8::try_from(count).ok()) + .filter(|count| (GRADIENT_QUANTITY_MIN..=Filter::MAX_GRADIENT_COLORS).contains(count)); + let wanted = wanted + .ok_or_else(|| bad(cmd, format!("`quantity` must be a whole number from {GRADIENT_QUANTITY_MIN} to {}", Filter::MAX_GRADIENT_COLORS)))?; + set_quantity(colors, positions, quantity, wanted); + } + input.mode = choice(p, "grayscaleMode", &GrayscaleMode::ALL, GrayscaleMode::id, cmd)?.unwrap_or(input.mode); + set(&mut input.blur, "blur", 0.0, BLUR_INTENSITY_SLIDER_MAX); + set(&mut input.balance, "balance", 0.0, 1.0); + set(&mut input.contrast, "contrast", 0.0, 1.0); + for (key, slot) in [("invert", &mut input.invert), ("linear", linear), ("debug", debug)] { + switch(slot, key)?; + } } - Filter::Posterize { levels } => set(levels, "levels", 2.0, 64.0), - Filter::Clamp { min, max } => { + Filter::GradientCurve { preset, invert, balance, contrast } => { + *preset = choice(p, "preset", &CurvePreset::ALL, CurvePreset::id, cmd)?.unwrap_or(*preset); + switch(invert, "invert")?; + set(balance, "balance", 0.0, 1.0); + set(contrast, "contrast", 0.0, 1.0); + } + Filter::GradientDynamic { vertical, position, color } => { + *vertical = two_way(p, "orientation", "horizontal", "vertical", cmd)?.unwrap_or(*vertical); + set(position, "position", 0.0, 1.0); + shade(color)?; + } + Filter::Posterize { levels, alpha } => { + set(levels, "levels", POSTERIZE_LEVELS_MIN, POSTERIZE_LEVELS_MAX); + switch(alpha, "applyToAlpha")?; + } + Filter::Clamp { min, max } | Filter::Smoothstep { min, max } => { set(min, "min", 0.0, 1.0); set(max, "max", 0.0, 1.0); } - Filter::HistogramScan { position, contrast } => { + Filter::HeightAdjust { invert, offset, multiply } => { + switch(invert, "invert")?; + set(offset, "offset", -HEIGHT_OFFSET_MAX, HEIGHT_OFFSET_MAX); + set(multiply, "multiply", 0.0, HEIGHT_MULTIPLY_MAX); + } + Filter::HistogramScan { position, contrast, invert_position } => { set(position, "position", 0.0, 1.0); set(contrast, "contrast", 0.0, 1.0); + switch(invert_position, "invertPosition")?; } Filter::HistogramRange { range, position } => { set(range, "range", 0.0, 1.0); set(position, "position", 0.0, 1.0); } - Filter::HistogramShift { offset } => set(offset, "offset", -1.0, 1.0), - Filter::Warp { intensity, scale, seed: s } => { - set(intensity, "intensity", 0.0, 256.0); - set(scale, "scale", 0.01, 1000.0); - seed(s); + Filter::HistogramShift { offset } => { + set(offset, "offset", -1.0, 1.0); + if let Some(position) = f32p(p, "position") { + *offset = Filter::shift_offset(position); + } } - Filter::DirectionalBlur { radius, angle: a } => { - set(radius, "radius", 0.0, 256.0); - angle(a); + Filter::Warp { intensity, scale, seed: noise_seed, divider: intensity_divider } => { + set(intensity, "intensity", 0.0, TEXELS_MAX); + set(scale, "scale", Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX); + seed(noise_seed); + divider(intensity_divider)?; } - Filter::SlopeBlur { radius, scale, seed: s } => { - set(radius, "radius", 0.0, 256.0); - set(scale, "scale", 0.01, 1000.0); - seed(s); + Filter::DirectionalBlur { radius, angle: direction } => { + set(radius, "radius", 0.0, TEXELS_MAX); + blur_intensity(radius); + angle(direction); } - Filter::HighPass { radius } => set(radius, "radius", 0.0, 256.0), - Filter::EdgeDetect { width } | Filter::Bevel { width } => set(width, "width", 0.0, 256.0), - Filter::Mosaic { size } => set(size, "size", 1.0, 512.0), + Filter::SlopeBlur { radius, scale, seed: noise_seed, divider: intensity_divider } => { + set(radius, "radius", 0.0, TEXELS_MAX); + set(scale, "scale", Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX); + seed(noise_seed); + divider(intensity_divider)?; + } + Filter::HighPass { radius, space, alpha } => { + set(radius, "radius", 0.0, TEXELS_MAX); + blur_intensity(radius); + *space = choice(p, "colorSpace", &HighpassSpace::ALL, HighpassSpace::id, cmd)?.unwrap_or(*space); + switch(alpha, "applyToAlpha")?; + } + Filter::EdgeDetect { width } => set(width, "width", 0.0, TEXELS_MAX), + Filter::Bevel { width, wrap: wraps } => { + set(width, "width", 0.0, TEXELS_MAX); + switch(wraps, "wrap")?; + } + Filter::Mosaic { size, alpha } => { + set(size, "size", 1.0, MOSAIC_SIZE_MAX); + if let Some(amount) = f32p(p, "pixelsAmount") { + *size = Filter::pixel_size(amount.round()); + } + switch(alpha, "applyToAlpha")?; + } + Filter::Fxaa { alpha } => switch(alpha, "affectAlphaChannel")?, Filter::Glow { radius, amount } => { - set(radius, "radius", 0.0, 256.0); - set(amount, "amount", 0.0, 10.0); + set(radius, "radius", 0.0, TEXELS_MAX); + set(amount, "amount", 0.0, GLOW_AMOUNT_MAX); + } + Filter::HaloGlow { on_mask, precise, width, spread, opacity, color } => { + switch(on_mask, "usedOnMask")?; + *precise = two_way(p, "mode", "soft", "precise", cmd)?.unwrap_or(*precise); + set(width, "width", -1.0, 1.0); + set(spread, "spread", 0.0, 1.0); + set(opacity, "opacity", 0.0, 1.0); + shade(color)?; + } + Filter::DropShadow { angle: direction, distance, size, spread, opacity, color } => { + angle(direction); + set(distance, "distance", -Filter::SHADOW_DISTANCE_MAX, Filter::SHADOW_DISTANCE_MAX); + set(size, "size", 0.0, 1.0); + set(spread, "spread", 0.0, 1.0); + set(opacity, "opacity", 0.0, 1.0); + shade(color)?; } Filter::ReplaceColor { from, to, tolerance, softness } => { for (key, slot) in [("from", from), ("to", to)] { - if let Some(v) = color_param(cmd, p, key)? { - *slot = v.map(|x| x.clamp(0.0, 1.0)); + if let Some(rgb) = color_param(cmd, p, key)? { + *slot = rgb.map(|x| x.clamp(0.0, 1.0)); } } set(tolerance, "tolerance", 0.0, 1.0); set(softness, "softness", 0.0, 1.0); } - Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } => { - if let Some(v) = f32p(p, "azimuth") { - *azimuth = v.rem_euclid(360.0); + Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, stylized } => { + if let Some(degrees) = f32p(p, "azimuth") { + *azimuth = degrees.rem_euclid(FULL_TURN_DEGREES); } - set(elevation, "elevation", -90.0, 90.0); - set(light, "light", 0.0, 10.0); - set(ambient, "ambient", 0.0, 10.0); + + // A light past the zenith comes from the far side: the angle wraps like the horizontal one + if let Some(degrees) = f32p(p, "elevation") { + *elevation = degrees.rem_euclid(FULL_TURN_DEGREES); + } + set(light, "light", 0.0, SUN_INTENSITY_MAX); + set(ambient, "ambient", 0.0, SKY_INTENSITY_MAX); set(occlusion, "occlusion", 0.0, 1.0); + + // A Baked Lighting saved before the stylized settings takes them lit as it was + if crate::stylized_lighting_params::sets_any(p) { + crate::stylized_lighting_params::apply(p, stylized.get_or_insert_with(|| Box::new(StylizedLighting::PLAIN)), cmd)?; + } } - Filter::DirectionalWarp { intensity, angle: a, scale, seed: s } => { - set(intensity, "intensity", 0.0, 256.0); - angle(a); - set(scale, "scale", 0.01, 1000.0); - seed(s); + Filter::EnvironmentLighting { horizontal, vertical, exposure, height_intensity, ambient_occlusion, specular_occlusion } => { + for (key, slot) in [("horizontalRotation", horizontal), ("verticalRotation", vertical)] { + if let Some(degrees) = f32p(p, key) { + *slot = degrees.rem_euclid(FULL_TURN_DEGREES); + } + } + set(exposure, "exposure", -Filter::ENVIRONMENT_EXPOSURE_STOPS, Filter::ENVIRONMENT_EXPOSURE_STOPS); + set(height_intensity, "heightIntensity", 0.0, HEIGHT_INTENSITY_MAX); + set(ambient_occlusion, "ambientOcclusion", 0.0, 1.0); + set(specular_occlusion, "specularOcclusion", 0.0, 1.0); + } + Filter::DirectionalWarp { intensity, angle: direction, scale, seed: noise_seed, divider: intensity_divider } => { + set(intensity, "intensity", 0.0, TEXELS_MAX); + angle(direction); + set(scale, "scale", Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX); + seed(noise_seed); + divider(intensity_divider)?; } } Ok(()) @@ -338,19 +1091,85 @@ mod tests { #[test] fn every_filter_builds_and_finds_by_id_or_label() { - for f in FILTERS { - let kind = build(f.id, &Value::Null).unwrap_or_else(|e| panic!("{}: {e}", f.id)); - // Material finishes are content only; other filters also run on masks, where some - // (grayscale, normal invert) change nothing and are not offered. - assert_eq!(kind.content_only().is_none(), f.mask || matches!(kind, EffectKind::Filter(_)), "{}", f.id); - assert_eq!(find(f.label).map(|d| d.id), Some(f.id)); + for def in FILTERS { + let kind = build(def.id, &Value::Null).unwrap_or_else(|err| panic!("{}: {err}", def.id)); + + // Material finishes are content only; other filters also run on masks, where some (normal invert) change nothing and are not offered + assert_eq!(kind.content_only().is_none(), def.mask || matches!(kind, EffectKind::Filter(_)), "{}", def.id); + assert_eq!(find(def.label).map(|found| found.id), Some(def.id)); } + + let EffectKind::Filter(Filter::Posterize { levels, .. }) = build("posterize", &json!({"levels": 1000})).unwrap() else { panic!() }; + assert_eq!(levels, POSTERIZE_LEVELS_MAX); + assert!(build("nope", &Value::Null).is_err()); - let EffectKind::Filter(Filter::Posterize { levels }) = build("posterize", &json!({"levels": 1000})).unwrap() else { panic!() }; - assert_eq!(levels, 64.0); assert!(build("gradientMap", &json!({"colors": []})).is_err()); assert!(build("colorBalance", &json!({"shadows": "x"})).is_err()); - let EffectKind::Filter(Filter::GradientMap { colors }) = build("gradientMap", &json!({"colors": [[0, 0, 0], "#ffffff"]})).unwrap() else { panic!() }; + + let EffectKind::Filter(Filter::GradientMap { colors, .. }) = build("gradientMap", &json!({"colors": [[0, 0, 0], "#ffffff"]})).unwrap() else { + panic!() + }; + assert_eq!(colors.len(), 2); } + + #[test] + fn a_new_gradient_given_colors_and_a_quantity_spaces_them_evenly() { + let five = [[0.0; 3], [0.25; 3], [0.5; 3], [0.75; 3], [1.0; 3]]; + for (given, quantity, expected) in [(&five[..2], 2, vec![0.0, 1.0]), (&five[..], 5, vec![0.0, 0.25, 0.5, 0.75, 1.0])] { + let params = json!({"colors": given, "quantity": quantity}); + + let EffectKind::Filter(Filter::GradientMap { positions, quantity: used, .. }) = build("gradientMap", ¶ms).unwrap() else { panic!() }; + + assert_eq!(positions, expected, "{params}"); + assert_eq!(used, Some(quantity)); + } + } + + /// A gradient given its colors and their places ramps through all of them, not the library's three + #[test] + fn a_new_gradient_given_colors_and_places_uses_every_color() { + let five = [[0.0; 3], [0.25; 3], [0.5; 3], [0.75; 3], [1.0; 3]]; + let places = [0.0, 0.1, 0.2, 0.3, 1.0]; + + let EffectKind::Filter(filter) = build("gradientMap", &json!({"colors": five, "positions": places})).unwrap() else { panic!() }; + + assert_eq!(filter.ramp_colors().len(), five.len()); + assert!(matches!(&filter, Filter::GradientMap { positions, .. } if positions[..] == places)); + } + + /// Raising Color Quantity leaves the colors the gradient had where they were, placed or not + #[test] + fn raising_the_quantity_keeps_colors_without_a_place_where_they_were() { + let three = json!({"colors": [[0, 0, 0], [1, 0, 0], [1, 1, 1]], "positions": [0.0]}); + let EffectKind::Filter(mut filter) = build("gradientMap", &three).unwrap() else { panic!() }; + let middle = filter.ramp_at(0.5); + + apply(&json!({"quantity": 4}), &mut filter, "effect.set").unwrap(); + + assert_eq!(filter.ramp_at(0.5), middle); + assert!(matches!(&filter, Filter::GradientMap { positions, .. } if positions[..] == [0.0, 0.5, 1.0, 1.0]), "{filter:?}"); + } + + #[test] + fn every_filter_row_reads_a_reference_name_without_an_internal_unit() { + let old_saves = [ + Filter::Warp { intensity: 8.0, scale: 4.0, seed: 1, divider: 1 }, + Filter::SlopeBlur { radius: 8.0, scale: 4.0, seed: 1, divider: 1 }, + Filter::DirectionalWarp { intensity: 8.0, angle: 0.0, scale: 4.0, seed: 1, divider: 1 }, + Filter::EdgeDetect { width: 2.0 }, + Filter::Bevel { width: 8.0, wrap: false }, + Filter::Glow { radius: 16.0, amount: 1.0 }, + ]; + let library = FILTERS.iter().filter_map(|def| match build(def.id, &Value::Null) { + Ok(EffectKind::Filter(filter)) => Some(filter), + _ => None, + }); + for filter in old_saves.into_iter().chain(library) { + for (key, label, ..) in scalar_params(&filter) { + let title_case = label.split([' ', '/']).filter(|word| !word.is_empty()).all(|word| word.starts_with(|c: char| !c.is_lowercase())); + assert!(title_case && !label.contains("texels") && !label.contains("degrees"), "{key}: {label}"); + } + } + } } diff --git a/crates/engine/src/stylized_lighting_params.rs b/crates/engine/src/stylized_lighting_params.rs new file mode 100644 index 00000000..6a6b6b78 --- /dev/null +++ b/crates/engine/src/stylized_lighting_params.rs @@ -0,0 +1,99 @@ +//! `effect.set` keys of Baked Lighting Stylized past Baked Lighting's sun and ambient + +use serde_json::Value; +use texturecraft_core::{DirectionalLight, LightingOutput, StylizedLighting}; + +use crate::Result; +use crate::commands::{bad, f32p}; +use crate::filter_lib::{choice, set_color, two_way}; +use crate::layer_cmds::FULL_TURN_DEGREES; + +/// The keys that give a Baked Lighting saved before them its stylized settings +pub(crate) const KEYS: [&str; 17] = [ + "sunColor", + "skyColor", + "horizonColor", + "groundColor", + "light1", + "light2", + "diffuseCavity", + "specularAo", + "specularCavity", + "cavitySmoothness", + "edgesIntensity", + "edgesSmoothness", + "input", + "output", + "dielectricReflectance", + "normalDetails", + "heightToNormal", +]; + +/// The highest Dielectric Reflectance, Cavity Smoothness and Height to Normal Intensity +pub const MAX_DIELECTRIC_REFLECTANCE: f32 = 0.16; +pub const MAX_CAVITY_SMOOTHNESS: f32 = 4.0; +pub const MAX_HEIGHT_TO_NORMAL: f32 = 3.0; + +/// The highest intensity of Light 1 and Light 2 +pub const MAX_LIGHT_INTENSITY: f32 = 2.0; + +/// Whether `p` sets any stylized setting +pub(crate) fn sets_any(p: &Value) -> bool { + KEYS.iter().any(|key| p.get(*key).is_some()) +} + +/// Set the stylized settings `p` names on `lighting`, clamped; a bad color or choice is refused +pub(crate) fn apply(p: &Value, lighting: &mut StylizedLighting, cmd: &str) -> Result<()> { + let set = |slot: &mut f32, key: &str, high: f32| { + if let Some(value) = f32p(p, key) { + *slot = value.clamp(0.0, high); + } + }; + + for (key, slot) in [ + ("sunColor", &mut lighting.sun_color), + ("skyColor", &mut lighting.sky_color), + ("horizonColor", &mut lighting.horizon_color), + ("groundColor", &mut lighting.ground_color), + ] { + set_color(p, key, slot, cmd)?; + } + + for (key, light) in ["light1", "light2"].into_iter().zip(lighting.lights.iter_mut()) { + if let Some(params) = p.get(key) { + set_light(params, light, key, cmd)?; + } + } + + set(&mut lighting.diffuse_cavity, "diffuseCavity", 1.0); + set(&mut lighting.specular_ao, "specularAo", 1.0); + set(&mut lighting.specular_cavity, "specularCavity", 1.0); + set(&mut lighting.cavity_smoothness, "cavitySmoothness", MAX_CAVITY_SMOOTHNESS); + set(&mut lighting.edges_intensity, "edgesIntensity", 1.0); + set(&mut lighting.edges_smoothness, "edgesSmoothness", 1.0); + set(&mut lighting.dielectric_reflectance, "dielectricReflectance", MAX_DIELECTRIC_REFLECTANCE); + set(&mut lighting.height_to_normal, "heightToNormal", MAX_HEIGHT_TO_NORMAL); + + lighting.specular_glossiness = two_way(p, "input", "metalRoughness", "specularGlossiness", cmd)?.unwrap_or(lighting.specular_glossiness); + lighting.output = choice(p, "output", &LightingOutput::ALL, LightingOutput::id, cmd)?.unwrap_or(lighting.output); + lighting.mesh_only = two_way(p, "normalDetails", "meshHeightNormal", "mesh", cmd)?.unwrap_or(lighting.mesh_only); + Ok(()) +} + +/// Light 1 or Light 2 from `{azimuth, elevation, intensity, color}` (any of them) +fn set_light(p: &Value, light: &mut DirectionalLight, key: &str, cmd: &str) -> Result<()> { + if !p.is_object() { + return Err(bad(cmd, format!("`{key}` must be an object {{azimuth, elevation, intensity, color}}"))); + } + + if let Some(degrees) = f32p(p, "azimuth") { + light.azimuth = degrees.rem_euclid(FULL_TURN_DEGREES); + } + if let Some(degrees) = f32p(p, "elevation") { + light.elevation = degrees.rem_euclid(FULL_TURN_DEGREES); + } + if let Some(intensity) = f32p(p, "intensity") { + light.intensity = intensity.clamp(0.0, MAX_LIGHT_INTENSITY); + } + set_color(p, "color", &mut light.color, cmd) +} diff --git a/crates/engine/tests/it/filter_stylize.rs b/crates/engine/tests/it/filter_stylize.rs new file mode 100644 index 00000000..13b28c90 --- /dev/null +++ b/crates/engine/tests/it/filter_stylize.rs @@ -0,0 +1,242 @@ +//! Anisotropic Kuwahara, PBR Validate (Metallic Roughness), Height To Normal and Color Match + +use serde_json::json; +use texturecraft_engine::core::{ + AnisotropicKuwahara, Channel, ColorMatch, Filter, HeightToNormal, PbrValidate, SourceColorMode, TargetColorMode, ValidationMode, +}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, refused, session, set, sized_session}; + +/// The composited base color at texel `(x, y)` +fn base_color(s: &mut Session, (x, y): (u32, u32)) -> [f32; 3] { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, x, y) +} + +/// Texels across a set fine enough for filters measured in texels at 2K (Kuwahara's radius, a height's slope) +const FINE_SET_SIZE: u32 = 512; + +/// A new Anisotropic Kuwahara starts where the reference does, takes every setting (one undo step) and smooths a noisy fill +#[test] +fn anisotropic_kuwahara_takes_its_settings_and_smooths() { + let mut s = sized_session(FINE_SET_SIZE); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap(); + let pattern = json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds", "scale": 64, "low": [0, 0, 0], "high": [1, 1, 1]}); + execute(&mut s, "layer.fill.set", &pattern).unwrap(); + let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect(); + let before: Vec = texels.iter().map(|t| base_color(&mut s, *t)[0]).collect(); + + let effect = add_filter(&mut s, json!({"filter": "Anisotropic Kuwahara"})); + assert_eq!(filter_of(&s, effect), Filter::AnisotropicKuwahara(AnisotropicKuwahara::LIBRARY)); + + set(&mut s, effect, json!({"radius": AnisotropicKuwahara::MAX_RADIUS})); + let after: Vec = texels.iter().map(|t| base_color(&mut s, *t)[0]).collect(); + let steps = |v: &[f32]| v.windows(2).map(|w| (w[1] - w[0]).abs()).sum::(); + assert!(steps(&after) < steps(&before) * 0.9, "smoother: {} vs {}", steps(&after), steps(&before)); + + let all = json!({"extractDirection": "customInput", "radius": 20.0, "smoothness": 0.5, "sharpness": 0.1, + "tensorSmoothness": 0.3, "anisotropy": 0.4, "angle": 390.0}); + set(&mut s, effect, all); + let expected = AnisotropicKuwahara { + custom_input: true, + radius: AnisotropicKuwahara::MAX_RADIUS, + smoothness: 0.5, + sharpness: 0.25, + tensor_smoothness: 0.3, + anisotropy: 0.4, + angle: 30.0, + }; + assert_eq!(filter_of(&s, effect), Filter::AnisotropicKuwahara(expected), "clamped, the angle wrapped"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "extractDirection": "luma"})).is_err()); + + let read = base_color(&mut s, texels[0]); + assert!(read.iter().all(|v| v.is_finite()), "a flat Custom Input reads no direction: {read:?}"); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + let Filter::AnisotropicKuwahara(undone) = filter_of(&s, effect) else { panic!("still Kuwahara") }; + assert_eq!(undone, AnisotropicKuwahara { radius: AnisotropicKuwahara::MAX_RADIUS, ..AnisotropicKuwahara::LIBRARY }, "one undo step"); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Anisotropic Kuwahara")); +} + +/// PBR Validate starts with the Color and Metal pills on, shows a too dark non-metal base color in red, leaves the metal as it is and takes its three switches +#[test] +fn pbr_validate_marks_implausible_base_colors() { + let mut s = session(); + let texel = (SIZE / 4, SIZE / 2); + + // sRGB 20: darker than both dark thresholds + let dark = 0.007; + execute(&mut s, "layer.add.fill", &json!({"color": [dark, dark, dark], "metallic": 0.0})).unwrap(); + let effect = add_filter(&mut s, json!({"filter": "pbrValidate"})); + assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate::LIBRARY)); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Metallic) && off.contains(&Channel::Roughness), "{off:?}"); + assert_eq!(base_color(&mut s, texel), PbrValidate::INVALID, "too dark"); + assert_eq!(s.caches[0].composite.value(Channel::Metallic, texel.0, texel.1)[0], 0.0, "the metal is left as it is"); + + set(&mut s, effect, json!({"validationMode": "metal"})); + let shown = base_color(&mut s, texel); + assert!((shown[0] - dark).abs() < 1e-3, "Metal leaves non-metal colors unchecked: {shown:?}"); + + set(&mut s, effect, json!({"validationMode": "albedo", "albedoDarkRangeThreshold": 50, "metalReflectanceRange": 70})); + assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate { mode: ValidationMode::Albedo, albedo_dark: 50, metal_low: 70 })); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "albedoDarkRangeThreshold": 40})).is_err()); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "validationMode": "all"})).is_err()); +} + +/// The composited packed normal at texel `(x, y)` +fn normal(s: &mut Session, (x, y): (u32, u32)) -> [f32; 3] { + s.update(); + s.caches[0].composite.value(Channel::Normal, x, y) +} + +/// How far the packed normals of `texels` tilt from flat, summed +fn tilt(s: &mut Session, texels: &[(u32, u32)]) -> f32 { + texels.iter().map(|texel| normal(s, *texel)).map(|[x, y, _]| (x - 0.5).abs() + (y - 0.5).abs()).sum() +} + +/// Height To Normal starts with the Normal pill only, turns the layer's height into its normal, overwrites or overlays it, one undo step +#[test] +fn height_to_normal_turns_the_height_into_the_normal() { + let mut s = sized_session(FINE_SET_SIZE); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap(); + let bumps = json!({"layer": fill, "channel": "height", "procedural": "Clouds", "scale": 16, "low": [-0.05, -0.05, -0.05], "high": [0.05, 0.05, 0.05]}); + execute(&mut s, "layer.fill.set", &bumps).unwrap(); + let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect(); + assert!(tilt(&mut s, &texels) < 1e-3, "a fill's own normal is flat"); + + let color = base_color(&mut s, texels[0]); + + let effect = add_filter(&mut s, json!({"filter": "heightToNormal"})); + assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(HeightToNormal::LIBRARY)); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::Normal) && off.contains(&Channel::BaseColor) && off.contains(&Channel::Height), "{off:?}"); + + let made = tilt(&mut s, &texels); + assert!(made > 0.01, "the bumps tilt the normal: {made}"); + assert_eq!(base_color(&mut s, texels[0]), color, "the base color is left as it is"); + + set(&mut s, effect, json!({"heightDepth": 64.0})); + assert!(tilt(&mut s, &texels) > made * 1.5, "deeper heights tilt more"); + + set(&mut s, effect, json!({"useWorldUnits": false, "normalIntensity": 0.0})); + assert!(tilt(&mut s, &texels) < 1e-3, "no intensity: flat"); + + execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap(); + assert!(tilt(&mut s, &texels) < 1e-3, "Overwrite Existing Normal replaces the fill's normal"); + + set(&mut s, effect, json!({"overwriteExistingNormal": false})); + assert!((normal(&mut s, texels[0])[0] - 0.7).abs() < 0.02, "laid over the fill's normal: {:?}", normal(&mut s, texels[0])); + + let all = json!({"overwriteExistingNormal": true, "useWorldUnits": true, "surfaceSize": 0.0, "heightDepth": 500.0, + "normalIntensity": 70.0}); + set(&mut s, effect, all); + let expected = HeightToNormal { + surface_size: 1.0, + height_depth: HeightToNormal::MAX_HEIGHT_DEPTH, + intensity: HeightToNormal::MAX_INTENSITY, + ..HeightToNormal::LIBRARY + }; + assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(expected), "clamped"); + assert!(normal(&mut s, texels[0]).iter().all(|v| v.is_finite())); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + let Filter::HeightToNormal(undone) = filter_of(&s, effect) else { panic!("still Height To Normal") }; + assert!(!undone.overwrite && undone.surface_size == 300.0, "one undo step: {undone:?}"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "useWorldUnits": "yes"})).is_err()); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Height To Normal")); +} + +/// Color Match starts with the Color pill only and moves the colors to its target keeping their pattern, all of them at the Color Variation's 0, keeping each texel's difference from the whole texture's mean without Custom Color Variation; Parameter and Image Input modes read their colors +#[test] +fn color_match_moves_the_colors_to_the_target() { + let mut s = session(); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap(); + let reds = json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds", "scale": 8, "low": [0.3, 0.02, 0.02], "high": [0.9, 0.1, 0.1]}); + execute(&mut s, "layer.fill.set", &reds).unwrap(); + let texels: Vec<(u32, u32)> = (0..24).map(|k| (SIZE / 4 + k * 2, SIZE / 2)).collect(); + let before: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + let spread = |colors: &[[f32; 3]]| colors.iter().map(|c| c[0]).fold(f32::MIN, f32::max) - colors.iter().map(|c| c[0]).fold(f32::MAX, f32::min); + assert!(spread(&before) > 0.05, "the clouds vary: {before:?}"); + + let effect = add_filter(&mut s, json!({"filter": "Color Match"})); + assert_eq!(filter_of(&s, effect), Filter::ColorMatch(ColorMatch::LIBRARY)); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness), "{off:?}"); + + let new: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&new) > 0.02, "a new Color Match keeps the pattern: {new:?}"); + + let redness = new.iter().map(|c| c[0] - c[2]).sum::() / new.len() as f32; + assert!(redness.abs() < 0.05, "around the gray target: {redness} {new:?}"); + + // Color Variation at 0: every texel is the target itself + set(&mut s, effect, json!({"hue": 0.0, "chroma": 0.0, "luma": 0.0})); + let gray = ColorMatch::LIBRARY.target_color; + for texel in &texels { + let color = base_color(&mut s, *texel); + assert!(color.iter().zip(gray).all(|(v, g)| (v - g).abs() < 2e-3), "Color Variation 0: the target itself, {color:?}"); + } + + // Without Custom Color Variation the texels keep their differences from the mean, now around the target + set(&mut s, effect, json!({"customColorVariation": false})); + let kept: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&kept) > 0.02, "variation kept: {kept:?}"); + + let redness = kept.iter().map(|c| c[0] - c[2]).sum::() / kept.len() as f32; + assert!(redness.abs() < 0.05, "the reds are gray on average now: {redness} {kept:?}"); + + let brighter = |colors: &[[f32; 3]], a: usize, b: usize| colors[a][0] + colors[a][1] > colors[b][0] + colors[b][1]; + let (lightest, darkest) = + (0..texels.len()).fold((0, 0), |(hi, lo), k| (if before[k][0] > before[hi][0] { k } else { hi }, if before[k][0] < before[lo][0] { k } else { lo })); + assert!(brighter(&kept, lightest, darkest), "the lightest red stays the lightest"); + + // Source Color Parameter: the texels of that color land on the target + let source = before[lightest]; + set(&mut s, effect, json!({"sourceColorMode": "parameter", "sourceColor": source, "targetColor": [0.05, 0.1, 0.6]})); + let landed = base_color(&mut s, texels[lightest]); + assert!((landed[2] - 0.6).abs() < 0.01 && (landed[0] - 0.05).abs() < 0.01, "{landed:?}"); + + // Image Input: mid gray until a source is set + let all = json!({"sourceColorMode": "input", "targetColorMode": "imageInput", "customColorVariation": true, "hue": 400.0, + "chroma": 2.0, "luma": -1.0}); + set(&mut s, effect, all); + let expected = ColorMatch { + source_mode: SourceColorMode::Input, + source_color: source, + target_mode: TargetColorMode::ImageInput, + target_color: [0.05, 0.1, 0.6], + custom_variation: true, + hue: 360.0, + chroma: 1.0, + luma: 0.0, + }; + assert_eq!(filter_of(&s, effect), Filter::ColorMatch(expected), "clamped"); + + set(&mut s, effect, json!({"chroma": 0.0, "hue": 0.0})); + let image = base_color(&mut s, texels[0]); + assert!(image.iter().all(|v| (v - 0.5).abs() < 2e-3), "the Image Input's mid gray: {image:?}"); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + let Filter::ColorMatch(undone) = filter_of(&s, effect) else { panic!("still Color Match") }; + assert_eq!((undone.hue, undone.chroma), (360.0, 1.0), "one undo step: {undone:?}"); + + refused( + &mut s, + effect, + &[json!({"sourceColorMode": "median"}), json!({"targetColorMode": "input"}), json!({"customColorVariation": 1}), json!({"targetColor": "red"})], + ); + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Color Match")); +} diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index df495231..e37b8e79 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -1,9 +1,13 @@ //! What the filter tests share: their sessions and reading the composite +//! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite use texturecraft_engine::Session; use texturecraft_engine::core::Channel; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; /// The texture set side the filter tests paint on pub(crate) const SIZE: u32 = 128; @@ -45,3 +49,46 @@ pub(crate) fn center(s: &mut Session, channel: Channel) -> [f32; 3] { let uv = center_uv(s); s.caches[0].composite.value(channel, (uv.x * SIZE as f32) as u32, (uv.y * SIZE as f32) as u32) } + +/// The composited roughness at texel `(x, y)` +pub(crate) fn roughness(s: &mut Session, (x, y): (u32, u32)) -> f32 { + s.update(); + s.caches[0].composite.value(Channel::Roughness, x, y)[0] +} + +/// Content filter `params` on the selected layer: the effect +pub(crate) fn add_filter(s: &mut Session, params: Value) -> LayerId { + let mut params = params; + params["target"] = json!("content"); + LayerId(execute(s, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) +} + +/// A fill layer of base color `color` and roughness 0.3 under content filter `params`: the effect +pub(crate) fn filtered(s: &mut Session, color: [f32; 3], params: Value) -> LayerId { + execute(s, "layer.add.fill", &json!({"color": color, "roughness": 0.3})).unwrap(); + add_filter(s, params) +} + +/// The filter `effect` holds +pub(crate) fn filter_of(s: &Session, effect: LayerId) -> Filter { + match &s.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Filter(filter) => filter.clone(), + other => panic!("not a filter: {other:?}"), + } +} + +/// `effect.set` on `effect` with `params`, which must succeed +pub(crate) fn set(s: &mut Session, effect: LayerId, params: Value) { + let mut params = params; + params["effect"] = json!(effect.0); + execute(s, "effect.set", ¶ms).unwrap(); +} + +/// Each of `bad` is refused by `effect.set` on `effect` +pub(crate) fn refused(s: &mut Session, effect: LayerId, bad: &[Value]) { + for bad in bad { + let mut params = bad.clone(); + params["effect"] = json!(effect.0); + assert!(execute(s, "effect.set", ¶ms).is_err(), "{bad}"); + } +} From 32654f417e3378e896d321bc40a85b4bf6b654aa Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:48 +0000 Subject: [PATCH 036/153] Folders and instances: Contents Scale and Rotation, Randomize seeds, the instance's source card --- crates/engine/src/folder_cmds.rs | 246 +++++++++++++++++++ crates/engine/tests/it/folder_contents.rs | 179 ++++++++++++++ crates/ui-egui/src/folder_properties.rs | 45 ++++ crates/ui-egui/src/instance_properties.rs | 100 ++++++++ crates/ui-egui/tests/it/folder_properties.rs | 121 +++++++++ 5 files changed, 691 insertions(+) create mode 100644 crates/engine/src/folder_cmds.rs create mode 100644 crates/engine/tests/it/folder_contents.rs create mode 100644 crates/ui-egui/src/folder_properties.rs create mode 100644 crates/ui-egui/src/instance_properties.rs create mode 100644 crates/ui-egui/tests/it/folder_properties.rs diff --git a/crates/engine/src/folder_cmds.rs b/crates/engine/src/folder_cmds.rs new file mode 100644 index 00000000..599f2c5e --- /dev/null +++ b/crates/engine/src/folder_cmds.rs @@ -0,0 +1,246 @@ +//! A folder's actions on everything inside it: the Scale and Rotation laid on its fills, and new seeds for its patterns + +use std::collections::{HashMap, HashSet}; + +use serde_json::{Value, json}; +use texturecraft_core::project::MAX_DEPTH; +use texturecraft_core::{ContentsOffset, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, Project, RandomizedSeed, Source}; + +use crate::commands::{CommandSpec, bad, f32p, has_layer, layer_param}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "folder.contents.set", + "Folder contents", + [], + None, + "{layer?: folder (default selected), scale?: 0.01..100 multiplying every fill's tiling inside, rotation?: degrees added to every fill's angle inside (wrapped to -180..180), merge?} — relative to each fill's own and never written into the fills; one undo step", + has_layer, + set_contents + ), + cmd!( + "folder.contents.reset", + "Reset folder contents", + [], + None, + "{layer?: folder (default selected)} — drop the folder's Scale and Rotation: every fill inside back to its own, and put back the seeds its Randomize seeds changed (a seed changed since, or a layer moved out, keeps its own), in one undo step", + has_layer, + reset_contents + ), + cmd!( + "folder.randomizeSeeds", + "Randomize seeds", + [], + None, + "{layer?: folder (default selected)} — a new seed for every pattern, generator and noise filter inside the folder (fills, masks, effects, nested folders; instanced sources stay), in one undo step; seeds that were equal stay equal; the folder keeps each seed's value from before so its Contents reset can put it back. Returns {seeds: how many changed}", + has_layer, + randomize_seeds + ), + ] +} + +/// The folder a command acts on: the `layer` param or the selected layer, refused unless it is a folder +fn folder_param(s: &Session, cmd: &str, p: &Value) -> Result { + let id = layer_param(s, cmd, p)?; + match s.doc.project.layers.get(&id) { + Some(layer) if layer.is_group() => Ok(id), + _ => Err(bad(cmd, format!("layer {} is not a folder", id.0))), + } +} + +/// The Scale and Rotation folder `id` lays on its fills +fn contents_mut(project: &mut Project, id: LayerId) -> Option<&mut ContentsOffset> { + match &mut project.layers.get_mut(&id)?.kind { + LayerKind::Group { contents, .. } => Some(contents), + _ => None, + } +} + +/// The seeds inside folder `id` that its Randomize seeds changed +fn randomized_mut(project: &mut Project, id: LayerId) -> Option<&mut Vec> { + match &mut project.layers.get_mut(&id)?.kind { + LayerKind::Group { randomized, .. } => Some(randomized), + _ => None, + } +} + +/// Whether folder `id`'s Contents differ from a new folder's: a Scale or Rotation laid on its fills, or seeds its Randomize seeds changed +pub fn contents_changed(project: &Project, id: LayerId) -> bool { + match project.layers.get(&id).map(|layer| &layer.kind) { + Some(LayerKind::Group { contents, randomized, .. }) => !contents.is_none() || !randomized.is_empty(), + _ => false, + } +} + +fn set_contents(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "folder.contents.set"; + let id = folder_param(s, CMD, p)?; + let (scale, rotation) = (f32p(p, "scale"), f32p(p, "rotation")); + if scale.is_none() && rotation.is_none() { + return Err(bad(CMD, "give `scale` and/or `rotation`")); + } + + let current = s.doc.project.contents_offset(id); + let offset = ContentsOffset::new(scale.unwrap_or(current.scale), rotation.unwrap_or(current.rotation)); + let reply = json!({ "scale": offset.scale, "rotation": offset.rotation }); + if offset == current { + return Ok(reply); + } + + s.edit("Folder contents", |s| { + let contents = contents_mut(&mut s.doc.project, id).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", id.0)))?; + *contents = offset; + Ok(()) + })?; + Ok(reply) +} + +fn reset_contents(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "folder.contents.reset"; + let id = folder_param(s, CMD, p)?; + if !contents_changed(&s.doc.project, id) { + return Ok(Value::Null); + } + + let mut descended = Vec::new(); + descendants(&s.doc.project, id, 0, &mut descended); + let inside: HashSet = descended.into_iter().collect(); + s.edit("Reset folder contents", |s| { + let contents = contents_mut(&mut s.doc.project, id).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", id.0)))?; + *contents = ContentsOffset::NONE; + let randomized = randomized_mut(&mut s.doc.project, id).map(std::mem::take).unwrap_or_default(); + for record in randomized.iter().filter(|record| inside.contains(&record.layer)) { + let Some(layer) = s.doc.project.layers.get_mut(&record.layer) else { continue }; + + // Only a seed still at the value Randomize seeds gave it goes back: one changed since keeps the artist's pick + if let Some(seed) = layer_seeds(layer).into_iter().nth(record.index as usize).filter(|seed| **seed == record.after) { + *seed = record.before; + } + } + Ok(()) + })?; + Ok(Value::Null) +} + +fn randomize_seeds(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "folder.randomizeSeeds"; + let folder = folder_param(s, CMD, p)?; + let mut inside = Vec::new(); + descendants(&s.doc.project, folder, 0, &mut inside); + let seeds: usize = inside.iter().filter_map(|id| s.doc.project.layers.get(id)).map(seed_count).sum(); + if seeds == 0 { + return Ok(json!({ "seeds": 0 })); + } + + // One mixing key per folder: a seed maps to the same new seed wherever it is, so patterns that lined up still do + let key = next_seed(folder.0 as u32 ^ (folder.0 >> 32) as u32); + s.edit("Randomize seeds", |s| { + let mut randomized = randomized_mut(&mut s.doc.project, folder).map(std::mem::take).unwrap_or_default(); + let mut positions = randomized.iter().enumerate().map(|(position, record)| ((record.layer, record.index), position)).collect(); + for id in &inside { + let Some(layer) = s.doc.project.layers.get_mut(id) else { continue }; + for (index, seed) in (0u32..).zip(layer_seeds(layer)) { + let after = next_seed(*seed ^ key); + remember(&mut randomized, &mut positions, RandomizedSeed { layer: *id, index, before: *seed, after }); + *seed = after; + } + } + *randomized_mut(&mut s.doc.project, folder).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", folder.0)))? = randomized; + Ok(()) + })?; + Ok(json!({ "seeds": seeds })) +} + +/// Adds `change` to the folder's randomized seeds, found by (layer, seed index) in `positions`; a seed randomized again keeps its first `before` (what the reset puts back), unless it was changed by hand in between +fn remember(randomized: &mut Vec, positions: &mut HashMap<(LayerId, u32), usize>, change: RandomizedSeed) { + match positions.get(&(change.layer, change.index)).and_then(|position| randomized.get_mut(*position)) { + Some(record) if record.after == change.before => record.after = change.after, + Some(record) => *record = change, + None => { + positions.insert((change.layer, change.index), randomized.len()); + randomized.push(change); + } + } +} + +/// Whether folder `id` holds anything its Contents act on: a fill (layer, content or mask fill) or a seed +pub fn has_contents(project: &Project, id: LayerId) -> bool { + let mut inside = Vec::new(); + descendants(project, id, 0, &mut inside); + inside.iter().filter_map(|id| project.layers.get(id)).any(|layer| { + let fills = matches!(layer.kind, LayerKind::Fill(_)) + || layer + .content_effects + .iter() + .chain(layer.mask.iter().flat_map(|mask| mask.effects.iter())) + .any(|effect| matches!(effect.kind, EffectKind::Fill { .. } | EffectKind::Material(_))); + fills || seed_count(layer) > 0 + }) +} + +/// Every layer inside folder `id`, nested folders' children too (instances' sources are not followed: they live elsewhere) +fn descendants(project: &Project, id: LayerId, depth: usize, out: &mut Vec) { + if depth > MAX_DEPTH { + return; + } + + for child in project.layers.get(&id).map(|folder| folder.children().to_vec()).unwrap_or_default() { + out.push(child); + descendants(project, child, depth + 1, out); + } +} + +/// The seeds of a layer's fill, content effects and mask effects +fn layer_seeds(layer: &mut Layer) -> Vec<&mut u32> { + let Layer { kind, content_effects, mask, .. } = layer; + let mut seeds = Vec::new(); + if let LayerKind::Fill(fill) = kind { + seeds.extend(fill.sources.values_mut().filter_map(source_seed)); + } + let effects = content_effects.iter_mut().chain(mask.iter_mut().flat_map(|mask| mask.effects.iter_mut())); + for effect in effects { + match &mut effect.kind { + EffectKind::Fill { source, .. } => seeds.extend(source_seed(source)), + EffectKind::Material(fill) => seeds.extend(fill.sources.values_mut().filter_map(source_seed)), + EffectKind::Generator(generator) => seeds.push(&mut generator.seed), + EffectKind::Filter(Filter::Warp { seed, .. } | Filter::SlopeBlur { seed, .. } | Filter::DirectionalWarp { seed, .. }) => seeds.push(seed), + _ => {} + } + } + seeds +} + +/// How many seeds [`layer_seeds`] gives for `layer`, read without borrowing it mutably (the panel asks every frame) +fn seed_count(layer: &Layer) -> usize { + let fill_seeds = |fill: &Fill| fill.sources.values().filter(|source| matches!(source, Source::Procedural { .. })).count(); + let own = match &layer.kind { + LayerKind::Fill(fill) => fill_seeds(fill), + _ => 0, + }; + let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| mask.effects.iter())); + let effect_seeds: usize = effects + .map(|effect| match &effect.kind { + EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })), + EffectKind::Material(fill) => fill_seeds(fill), + _ => 0, + }) + .sum(); + own + effect_seeds +} + +fn source_seed(source: &mut Source) -> Option<&mut u32> { + match source { + Source::Procedural { pattern, .. } => Some(&mut pattern.seed), + _ => None, + } +} + +/// A new seed that looks random but follows from `seed` (SplitMix32's mixing step), so tests and replays get the same seeds +pub fn next_seed(seed: u32) -> u32 { + let mut z = seed.wrapping_add(0x9e37_79b9); + z = (z ^ (z >> 16)).wrapping_mul(0x85eb_ca6b); + z = (z ^ (z >> 13)).wrapping_mul(0xc2b2_ae35); + z ^ (z >> 16) +} diff --git a/crates/engine/tests/it/folder_contents.rs b/crates/engine/tests/it/folder_contents.rs new file mode 100644 index 00000000..0ad960ef --- /dev/null +++ b/crates/engine/tests/it/folder_contents.rs @@ -0,0 +1,179 @@ +//! A folder's Scale and Rotation over the fills inside it (stored on the folder, reset drops it) and Randomize seeds as one undo step + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, ContentsOffset, EffectKind, Filter, LayerId, LayerKind, Projection, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The test project's texture size +const RESOLUTION: u32 = 128; + +/// Texels between two base colour samples, across and down +const SAMPLE_STRIDE: usize = 9; + +fn id(v: Value, key: &str) -> LayerId { + LayerId(v[key].as_u64().unwrap()) +} + +/// A folder holding a Clouds fill (base color and roughness on one seed) with a warp filter in its mask; returns (session, folder, fill) +fn folder_with_fill() -> (Session, LayerId, LayerId) { + let mut s = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap(); + let fill = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + for channel in ["baseColor", "roughness"] { + execute(&mut s, "layer.fill.set", &json!({"layer": fill.0, "channel": channel, "procedural": "Clouds", "seed": 7})).unwrap(); + } + execute(&mut s, "layer.fill.projection", &json!({"layer": fill.0, "projection": "uv", "scale": [2.0, 2.0], "rotation": 10.0})).unwrap(); + execute(&mut s, "mask.add.white", &json!({"layer": fill.0})).unwrap(); + execute(&mut s, "effect.add.filter", &json!({"layer": fill.0, "target": "mask", "filter": "warp"})).unwrap(); + let folder = id(execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); + s.update(); + (s, folder, fill) +} + +fn projection(s: &Session, fill: LayerId) -> Projection { + match &s.doc.project.layer(fill).unwrap().kind { + LayerKind::Fill(f) => f.projection.clone(), + other => panic!("not a fill: {other:?}"), + } +} + +fn base_colors(s: &Session) -> Vec<[f32; 3]> { + let composite = &s.caches[s.ts()].composite; + let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE); + samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() +} + +#[test] +fn a_folders_scale_and_rotation_lay_on_its_fills_without_changing_them_and_reset_drops_them() { + let (mut s, folder, fill) = folder_with_fill(); + let own = projection(&s, fill); + let before = base_colors(&s); + let steps = s.history_labels().len(); + + let set = execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 1.5, "rotation": 30.0})).unwrap(); + assert_eq!(set, json!({"scale": 1.5, "rotation": 30.0})); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(s.doc.project.contents_around(fill), ContentsOffset::new(1.5, 30.0)); + assert_eq!(projection(&s, fill), own, "the fill keeps its own values"); + s.update(); + let turned = base_colors(&s); + assert_ne!(turned, before, "the fill renders scaled and turned"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""contents":{"rotation":30.0,"scale":1.5}"#), "{inspect}"); + + // A drag continues its step; one value given keeps the other + execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "rotation": 400.0, "merge": true})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1); + assert_eq!(s.doc.project.contents_offset(folder), ContentsOffset::new(1.5, 40.0)); + + // The values it already has add no step + let unchanged = execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 1.5, "rotation": 40.0})).unwrap(); + assert_eq!(unchanged, json!({"scale": 1.5, "rotation": 40.0})); + assert_eq!(s.history_labels().len(), steps + 1, "no step for the same values"); + + execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap(); + assert!(s.doc.project.contents_offset(folder).is_none()); + s.update(); + assert_eq!(base_colors(&s), before, "reset gives every fill its own back"); + let steps = s.history_labels().len(); + execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "nothing to drop, no step"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.contents_offset(folder), ContentsOffset::new(1.5, 40.0)); + + // Only folders take an offset, and it needs a value + assert!(execute(&mut s, "folder.contents.set", &json!({"layer": fill.0, "scale": 2.0})).is_err()); + assert!(execute(&mut s, "folder.contents.set", &json!({"layer": folder.0})).is_err()); + assert!(execute(&mut s, "folder.randomizeSeeds", &json!({"layer": fill.0})).is_err()); +} + +#[test] +fn randomize_seeds_gives_every_pattern_inside_a_new_seed_in_one_undo_step() { + let (mut s, folder, fill) = folder_with_fill(); + + // The folder inside another: its seeds are inside that one too + let outer = id(execute(&mut s, "layer.group", &json!({"layer": folder.0})).unwrap(), "layer"); + let before = fill_seeds(&s, fill); + let steps = s.history_labels().len(); + + let out = execute(&mut s, "folder.randomizeSeeds", &json!({"layer": outer.0})).unwrap(); + assert_eq!(out["seeds"], 3); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + let after = fill_seeds(&s, fill); + assert!(after.0 != before.0 && after.2 != before.2, "{before:?} -> {after:?}"); + assert_eq!(after.0, after.1, "channels on one seed stay on one seed"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill_seeds(&s, fill), before, "one undo takes every seed back"); + + // A folder with nothing seeded inside adds no step + let empty = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + let steps = s.history_labels().len(); + assert_eq!(execute(&mut s, "folder.randomizeSeeds", &json!({"layer": empty.0})).unwrap()["seeds"], 0); + assert_eq!(s.history_labels().len(), steps); +} + +/// The seeds of fill layer `id`'s base color and roughness patterns and of its mask's warp filter +fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) { + let layer = s.doc.project.layer(id).unwrap(); + let LayerKind::Fill(fill) = &layer.kind else { panic!("not a fill") }; + let pattern = |channel| match fill.sources.get(&channel) { + Some(Source::Procedural { pattern, .. }) => pattern.seed, + other => panic!("not a pattern: {other:?}"), + }; + let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind { + _ => None, + }); + (pattern(Channel::BaseColor), pattern(Channel::Roughness), warp.unwrap()) +} + +#[test] +fn the_contents_reset_puts_back_the_seeds_randomize_seeds_changed_in_one_undo_step() { + let (mut s, folder, fill) = folder_with_fill(); + let before = fill_seeds(&s, fill); + let pictured = base_colors(&s); + assert!(!texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "a new folder's contents are at their defaults"); + + // Randomized twice, with a Scale laid on top: the reset still goes back to the seeds from before the first + execute(&mut s, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap(); + execute(&mut s, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap(); + execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 2.0})).unwrap(); + let randomized = fill_seeds(&s, fill); + assert!(randomized.0 != before.0 && randomized.2 != before.2, "{before:?} -> {randomized:?}"); + assert!(texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "the reset is lit"); + + // Old projects: the record is saved with the folder and read back + let saved = serde_json::to_value(&s.doc.project).unwrap(); + assert!(saved.to_string().contains("randomized"), "the folder keeps its seeds from before in the project"); + + let steps = s.history_labels().len(); + execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(fill_seeds(&s, fill), before, "every seed is back"); + assert!(s.doc.project.contents_offset(folder).is_none(), "the Scale is dropped too"); + assert!(!texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "nothing left to reset"); + s.update(); + assert_eq!(base_colors(&s), pictured, "the fill looks as it did before Randomize seeds"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill_seeds(&s, fill), randomized, "one undo brings the random seeds and the Scale back"); + assert_eq!(s.doc.project.contents_offset(folder).scale, 2.0); + + // A seed the artist set by hand after randomizing keeps their pick; the others go back + execute(&mut s, "layer.fill.set", &json!({"layer": fill.0, "channel": "roughness", "procedural": "Clouds", "seed": 42})).unwrap(); + execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap(); + let after = fill_seeds(&s, fill); + assert_eq!((after.0, after.1, after.2), (before.0, 42, before.2)); +} + +/// A project saved before folders kept their randomized seeds opens with none and saves the folder as before +#[test] +fn a_folder_saved_without_randomized_seeds_opens_and_saves_unchanged() { + let (s, folder, _) = folder_with_fill(); + let saved = serde_json::to_value(&s.doc.project.layers[&folder]).unwrap(); + assert!(saved.to_string().contains("\"children\"") && !saved.to_string().contains("randomized"), "nothing new is written: {saved}"); + let read: texturecraft_engine::core::Layer = serde_json::from_value(saved.clone()).unwrap(); + assert!(matches!(&read.kind, LayerKind::Group { randomized, .. } if randomized.is_empty())); + assert_eq!(serde_json::to_value(&read).unwrap(), saved); +} diff --git a/crates/ui-egui/src/folder_properties.rs b/crates/ui-egui/src/folder_properties.rs new file mode 100644 index 00000000..b205fc0e --- /dev/null +++ b/crates/ui-egui/src/folder_properties.rs @@ -0,0 +1,45 @@ +//! Properties of a folder: CONTENTS, the Scale and Rotation laid on every fill inside on top of their own (the round reset drops them and puts back the seeds Randomize seeds changed), and Randomize seeds + +use egui::Ui; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{ContentsOffset, LayerId}; +use texturecraft_engine::folder_cmds::{contents_changed, has_contents}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; + +/// Halvings and doublings the Scale track spans each way from ×1 (typed values go to the engine's range) +const SCALE_DOUBLINGS: f32 = 2.0; + +/// The properties of folder `folder`; every change goes through the `folder.*` commands +pub(crate) fn folder_properties(app: &mut TextureCraftApp, ui: &mut Ui, folder: LayerId) { + let project = &app.session.doc.project; + if !has_contents(project, folder) { + crate::widgets::empty_note(ui, tr("No properties found")); + return; + } + + let offset = project.contents_offset(folder); + let changed = contents_changed(project, folder); + + PropertySheet::show(ui, ("folder_sheet", folder.0), |sheet| { + if sheet.section_reset(tr("Contents"), changed) { + app.run("folder.contents.reset", json!({"layer": folder.0})); + } + let (low, high) = ContentsOffset::SCALE_RANGE; + let mut scale = offset.scale; + if let Some(merge) = sheet.factor_slider(tr("Scale"), &mut scale, SCALE_DOUBLINGS, low..=high) { + app.run("folder.contents.set", json!({"layer": folder.0, "scale": scale, "merge": merge})); + } + let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE; + let mut rotation = offset.rotation; + if let Some(merge) = sheet.relative_angle(tr("Rotation"), &mut rotation, turn_start..=turn_end) { + app.run("folder.contents.set", json!({"layer": folder.0, "rotation": rotation, "merge": merge})); + } + if sheet.button(ic::DICE_FIVE, tr("Randomize seeds")).clicked() { + app.run("folder.randomizeSeeds", json!({"layer": folder.0})); + } + }); +} diff --git a/crates/ui-egui/src/instance_properties.rs b/crates/ui-egui/src/instance_properties.rs new file mode 100644 index 00000000..2040f5e6 --- /dev/null +++ b/crates/ui-egui/src/instance_properties.rs @@ -0,0 +1,100 @@ +//! Properties of an instance: INSTANCE OF, the card of the layer it draws (a click goes to it), or a missing layer where the source is gone + +use egui::epaint::RectShape; +use egui::{Color32, CornerRadius, Painter, Rect, TextureId, Ui, pos2}; +use serde_json::json; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, Layer, LayerId, Project}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::slot_thumbnail::{THUMB_RADIUS, paint_empty_slot}; +use crate::theme::Tokens; + +/// The properties of instance `layer`: where it draws from +pub(crate) fn instance_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { + let Some(source) = layer.instance_source() else { return }; + let project = &app.session.doc.project; + let missing = !project.layers.contains_key(&source); + let name = project.layers.get(&source).map_or_else(|| tr("Missing layer").to_string(), |source_layer| source_layer.name.clone()); + + // A missing source has no texture set left; the instance's own names where it was + let set = set_name(project, if missing { layer.id } else { source }); + let picture = if missing { + None + } else { + app.layer_panel.texture_outside(ui.ctx(), &app.session, ThumbTarget::Content { layer: source, channel: Channel::BaseColor }) + }; + let tokens = Tokens::get(ui.ctx()); + let thumbnail = |painter: &Painter, rect: Rect| paint_thumbnail(painter, rect, picture, missing, &tokens); + + let clicked = PropertySheet::show(ui, ("instance_sheet", layer.id.0), |sheet| { + sheet.section(tr("Instance of"), false); + sheet.source_card(&thumbnail, &name, &set, missing) + }); + if clicked { + app.run("layer.select", json!({"layer": source.0, "target": "content"})); + } +} + +/// The name of the texture set holding `layer`, empty when none does +fn set_name(project: &Project, layer: LayerId) -> String { + project.locate(layer).and_then(|(set_index, _, _)| project.texture_sets.get(set_index)).map(|texture_set| texture_set.name.clone()).unwrap_or_default() +} + +/// The source's thumbnail with rounded corners (the field colour until it is rendered), or an empty outlined square for a missing source +fn paint_thumbnail(painter: &Painter, rect: Rect, picture: Option, missing: bool, tokens: &Tokens) { + if missing { + paint_empty_slot(painter, rect, tokens); + return; + } + + let radius = CornerRadius::same(THUMB_RADIUS); + match picture { + Some(texture) => { + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + painter.add(RectShape::filled(rect, radius, Color32::WHITE).with_texture(texture, uv)); + } + None => { + painter.rect_filled(rect, radius, tokens.field); + } + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use serde_json::json; + use texturecraft_engine::compose::ThumbTarget; + use texturecraft_engine::core::{Channel, LayerId}; + + use crate::docking::Panel; + + #[test] + fn the_source_card_renders_its_picture_while_layers_is_closed() { + // Long enough for the render worker on a busy machine + const ATTEMPTS: usize = 500; + const WAIT: Duration = Duration::from_millis(10); + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = crate::frame_gizmo::tests::ball_app(false); + let source = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + let instance = harness.state_mut().run("layer.instance", json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + harness.state_mut().run("layer.select", json!({"layer": instance, "target": "content"})).unwrap(); + harness.state_mut().ui.dock.close(Panel::Layers); + let target = ThumbTarget::Content { layer: LayerId(source), channel: Channel::BaseColor }; + + let rendered = (0..ATTEMPTS).any(|_| { + harness.step(); + let fresh = harness.state().layer_panel.service().is_fresh(target); + if !fresh { + std::thread::sleep(WAIT); + } + fresh + }); + + assert!(!harness.state().ui.dock.is_open(Panel::Layers), "Layers stays closed"); + assert!(rendered, "the Instance card's source picture renders without the Layers panel"); + } +} diff --git a/crates/ui-egui/tests/it/folder_properties.rs b/crates/ui-egui/tests/it/folder_properties.rs new file mode 100644 index 00000000..721a5dfd --- /dev/null +++ b/crates/ui-egui/tests/it/folder_properties.rs @@ -0,0 +1,121 @@ +//! The folder in Properties: CONTENTS with Scale and Rotation over every fill inside (a drag is one undo step, the round reset drops them) and Randomize seeds (the reset also puts back the seeds it changed); an empty folder has no properties + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{Channel, ContentsOffset, LayerId, LayerKind, Source}; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// How near a dragged Scale and Rotation land to the track's value (a drag ends a pixel or so off it) +const SCALE_TOLERANCE: f32 = 0.05; +const ROTATION_TOLERANCE_DEGREES: f32 = 3.0; + +/// Hovers a drag passes through on its way, so the slider follows it as a hand would +const DRAG_MOVES: usize = 3; + +/// A folder holding a Clouds fill (or nothing), the folder selected: (harness, folder, fill) +fn folder_harness(with_fill: bool) -> (Harness<'static, TextureCraftApp>, LayerId, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let fill = LayerId(execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "layer.fill.set", &json!({"layer": fill.0, "channel": "baseColor", "procedural": "Clouds", "seed": 7})).unwrap(); + let folder = if with_fill { + LayerId(execute(&mut session, "layer.group", &json!({"layer": fill.0})).unwrap()["layer"].as_u64().unwrap()) + } else { + LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap()) + }; + execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "content"})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, folder, fill) +} + +fn offset(harness: &Harness<'_, TextureCraftApp>, folder: LayerId) -> ContentsOffset { + harness.state().session.doc.project.contents_offset(folder) +} + +/// Drags the slider labelled `label` from its middle to `to` (0 = its left end, 1 = its right end), hovering on the way +fn drag(harness: &mut Harness<'_, TextureCraftApp>, label: &str, to: f32) { + let track = harness.get_by_role_and_label(Role::Slider, label).rect(); + let at = |t: f32| egui::pos2(track.left() + SLIDER_END_INSET + (track.width() - 2.0 * SLIDER_END_INSET) * t, track.center().y); + harness.drag_at(at(0.5)); + harness.run_steps(DRAG_STEP_FRAMES); + for step in 1..=DRAG_MOVES { + harness.hover_at(at(0.5 + (to - 0.5) * step as f32 / DRAG_MOVES as f32)); + harness.run_steps(DRAG_STEP_FRAMES); + } + harness.drop_at(at(to)); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn scale_and_rotation_drags_are_one_undo_step_each_and_the_reset_drops_them() { + let (mut harness, folder, fill) = folder_harness(true); + let steps = harness.state().session.history_labels().len(); + drag(&mut harness, "Scale", 1.0); + let scaled = offset(&harness, folder); + assert!((scaled.scale - 4.0).abs() < SCALE_TOLERANCE, "the right end is x4: {scaled:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); + drag(&mut harness, "Rotation", 0.75); + let turned = offset(&harness, folder); + assert!((turned.rotation - 90.0).abs() < ROTATION_TOLERANCE_DEGREES && turned.scale == scaled.scale, "{turned:?}"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2); + let LayerKind::Fill(own) = &harness.state().session.doc.project.layer(fill).unwrap().kind else { panic!("not a fill") }; + assert_eq!(own.projection, Default::default(), "the fill keeps its own projection"); + + harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(offset(&harness, folder).is_none(), "the reset drops the offset"); + assert_eq!(harness.state().session.history_labels().len(), steps + 3); +} + +#[test] +fn randomize_seeds_is_one_undo_step_the_contents_reset_puts_them_back_and_an_empty_folder_has_no_properties() { + let (mut harness, _, fill) = folder_harness(true); + let seed = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.layer(fill).unwrap().kind { + LayerKind::Fill(fill_layer) => match fill_layer.sources.get(&Channel::BaseColor) { + Some(Source::Procedural { pattern, .. }) => pattern.seed, + other => panic!("not a pattern: {other:?}"), + }, + other => panic!("not a fill: {other:?}"), + }; + let steps = harness.state().session.history_labels().len(); + harness.get_by_role_and_label(Role::Button, "Randomize seeds").click(); + harness.run_steps(SETTLE_FRAMES); + assert_ne!(seed(&harness), 7); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); + + // The Contents reset lights up and puts the seed back, in one undo step + let reset = harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults"); + assert!(!reset.accesskit_node().is_disabled(), "randomized seeds light the reset"); + reset.click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(seed(&harness), 7, "the seed from before Randomize seeds"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2); + assert!(harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults").accesskit_node().is_disabled(), "nothing left to reset"); + + let (harness, _, _) = folder_harness(false); + assert!(harness.query_by_label("No properties found").is_some()); + assert!(harness.query_by_role_and_label(Role::Slider, "Scale").is_none()); +} + +/// An empty folder's note starts at the Properties header name's left edge, as the note with no project open does (it was centred) +#[test] +fn an_empty_folders_note_starts_at_its_header_names_left_edge() { + let (harness, _, _) = folder_harness(false); + + let painted_left = |wanted: &dyn Fn(&str) -> bool| { + harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if wanted(text.galley.text()) => Some(text.pos.x), + _ => None, + }) + }; + let note = painted_left(&|text| text == "No properties found"); + let header = painted_left(&|text| text.starts_with("PROPERTIES")); + + assert!(note.is_some() && note == header, "the note starts at {note:?}, the header name at {header:?}"); +} From 73ac56a987ee4e467fc3d37e964180e3ed10ea1a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:00 +0000 Subject: [PATCH 037/153] Filters: the FILTER panel, its card, picker and parameters --- crates/ui-egui/src/filter_properties.rs | 1160 +++++++++++++++++ crates/ui-egui/src/filter_slot.rs | 97 +- crates/ui-egui/src/filter_transform_rows.rs | 91 ++ .../src/property_sheet/attribute_rows.rs | 60 + .../src/property_sheet/gradient_rows.rs | 120 ++ crates/ui-egui/tests/it/filter_card.rs | 105 ++ crates/ui-egui/tests/it/filter_gradient.rs | 163 +++ crates/ui-egui/tests/it/filter_inputs.rs | 114 ++ crates/ui-egui/tests/it/filter_picker.rs | 73 +- crates/ui-egui/tests/it/filter_support.rs | 68 + 10 files changed, 1947 insertions(+), 104 deletions(-) create mode 100644 crates/ui-egui/src/filter_properties.rs create mode 100644 crates/ui-egui/src/filter_transform_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/attribute_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/gradient_rows.rs create mode 100644 crates/ui-egui/tests/it/filter_card.rs create mode 100644 crates/ui-egui/tests/it/filter_gradient.rs create mode 100644 crates/ui-egui/tests/it/filter_inputs.rs diff --git a/crates/ui-egui/src/filter_properties.rs b/crates/ui-egui/src/filter_properties.rs new file mode 100644 index 00000000..028af176 --- /dev/null +++ b/crates/ui-egui/src/filter_properties.rs @@ -0,0 +1,1160 @@ +//! The Filter effect's properties: FILTER over the channel pills (content), the filter card holding its parameters and Attributes, then its image inputs' cards + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect, Stroke, StrokeKind, Ui}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + AnisotropicKuwahara, Bevel, BevelBlur, BevelCorner, BevelDirection, BevelSmooth, Channel, ColorMatch, ConversionMode, CurvePreset, DirectionalLight, + EffectKind, Filter, GrayscaleConversion, GrayscaleMode, HeightToNormal, HighpassSpace, ImageInput, LayerId, LightingOutput, MaskOutline, Mirror, + MirrorCorner, MirrorMode, OutlinePosition, PbrValidate, SlopeBlending, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedLighting, TargetColorMode, + ThresholdMode, ValidationMode, WarpBlending, WarpMode, WarpSourceMode, +}; +use texturecraft_engine::filter_lib::{ + BEVEL_SMOOTHING_MAX, BLUR_INTENSITY_SLIDER_MAX, DISTANCE_BEVEL_SMOOTHING_MAX, FilterDef, GRADIENT_QUANTITY_MIN, MAX_CAVITY_SMOOTHNESS, + MAX_DIELECTRIC_REFLECTANCE, MAX_HEIGHT_TO_NORMAL, MAX_LIGHT_INTENSITY, SKY_INTENSITY_SLIDER_MAX, SMOOTH_DISTANCE_MAX, SOURCE_TILING_MAX, SOURCE_TILING_MIN, + SUN_INTENSITY_MAX, build, find, scalar_params, +}; +use texturecraft_engine::paint::FULL_TURN_DEGREES; + +use crate::TextureCraftApp; +use crate::fill_material_panel::pill_name; +use crate::i18n::{tr, trf}; +use crate::property_sheet::PropertySheet; +use crate::theme::{AXIS_COLORS, OPPOSITE_COLORS, Tokens}; + +/// Where TextureCraft's filters come from: the repository, without its scheme +const AUTHOR_URL: &str = "github.com/storytold/texturecraft"; + +/// What a filter's angle rows span, in degrees: one full turn of their dial +pub(crate) const DIAL_DEGREES: RangeInclusive = 0.0..=FULL_TURN_DEGREES; + +/// The decimals Height To Normal's Normal Intensity shows +const INTENSITY_DECIMALS: usize = 2; + +/// The widest Divider chip text: the chip keeps one width whatever it shows +const WIDEST_DIVIDER: &str = "÷1000"; + +/// The properties of filter effect `effect` (`filter`), with its channel pills when it sits on the layer content +pub(crate) fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, filter: &Filter) { + let on_mask = crate::filter_slot::is_on_mask(app, effect.0); + PropertySheet::show(ui, ("filter_sheet", effect.0), |sheet| { + sheet.section(tr("Filter"), false); + if !on_mask { + let off: Vec = app.session.doc.project.effect(effect).map(|(_, found)| found.off_channels.iter().copied().collect()).unwrap_or_default(); + channel_pills(app, sheet, effect, &off); + } + let def = find(filter.label()); + let defaults = def.and_then(defaults_of); + let changed = defaults.as_ref().is_some_and(|defaults| defaults != filter); + if filter_card(app, sheet, effect, filter, def, changed) { + app.run("effect.filter.restoreDefaults", json!({"effect": effect.0})); + } + if *filter == Filter::Empty { + return; + } + + // The card holds the filter's settings, as a material channel's card does: sub-groups are captions in it, Attributes its last folded row + sheet.slot_rule(); + sheet.hold_card(); + parameters(app, sheet, effect.0, filter); + if sheet.closing_fold(tr("Attributes")) { + attributes(app, sheet, def); + } + sheet.release_card(); + + // Inputs every mode reads: their own slot cards after the filter's + for input in ImageInput::of(filter).into_iter().filter(|input| !input.by_mode) { + input_slot(app, sheet, effect, input, false); + } + if let Filter::GradientDynamic { color, .. } = filter { + gradient_source(app, sheet, effect.0, *color); + } + }); +} + +/// The filter's read-only Attributes (library entry `def`): what it does, who made it, the words it is found by and the size it works at +fn attributes(app: &TextureCraftApp, sheet: &mut PropertySheet<'_>, def: Option<&FilterDef>) { + let about = def.and_then(|def| def.about()); + if let Some(about) = about { + sheet.attribute_text(tr("Description"), tr(about.description)); + } + sheet.attribute(tr("Category"), tr("Filter")); + sheet.attribute(tr("Author"), "TextureCraft"); + sheet.attribute(tr("Author URL"), AUTHOR_URL); + if let Some(about) = about { + sheet.attribute(tr("Tags"), &about.tags.iter().map(|tag| tr(tag)).collect::>().join(", ")); + } + if let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) { + sheet.attribute(tr("Size"), &format!("{0} × {0}", texture_set.resolution)); + } +} + +/// The slot card of image input `input` of filter effect `effect` (its row only, inside the card open now, when `in_card`): the source it reads, picked like a mask fill's +fn input_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect: LayerId, input: ImageInput, in_card: bool) { + let Some((reader, source)) = app.session.doc.project.effect(effect).map(|(owner, found)| (owner, found.input(&input))) else { return }; + crate::fill_material_panel::source_card(app, sheet, source, &json!({"effect": effect.0}), crate::source_slot::SourceSlot::Input(input), reader, in_card); +} + +/// The library defaults of filter `def` +fn defaults_of(def: &FilterDef) -> Option { + match build(def.id, &Value::Null) { + Ok(EffectKind::Filter(defaults)) => Some(defaults), + _ => None, + } +} + +/// One pill per texture set channel, lit where the filter works; Alt+click keeps only the clicked one +fn channel_pills(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect: LayerId, off: &[Channel]) { + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + let names: Vec<&str> = channels.iter().map(|channel| tr(pill_name(*channel))).collect(); + let on: Vec = channels.iter().map(|channel| !off.contains(channel)).collect(); + let Some((index, solo)) = sheet.channel_pills(&names, &on) else { return }; + let Some(clicked) = channels.get(index) else { return }; + + let switched: serde_json::Map = if solo { + channels.iter().map(|channel| (channel.id().to_string(), json!(channel == clicked))).collect() + } else { + std::iter::once((clicked.id().to_string(), json!(!on.get(index).copied().unwrap_or(true)))).collect() + }; + app.run("effect.set", json!({"effect": effect.0, "channels": switched})); +} + +/// How soon a filter card whose picture is still rendering looks for it again +const THUMBNAIL_POLL: std::time::Duration = std::time::Duration::from_millis(100); + +/// The hourglass size on a slot whose picture is still rendering +const WAITING_GLYPH_SIZE: f32 = 12.0; + +/// How round a filter card's picture and a swatch's corners are, in points +const SWATCH_CORNER_RADIUS: u8 = 3; + +/// The width of a picture's outline, in points +const OUTLINE_WIDTH: f32 = 1.0; + +/// The card naming the filter (or None; `def` its library entry): a click opens the filter picker under it, × empties it; returns whether its ⟲ (live while `changed`) was clicked +fn filter_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect: LayerId, filter: &Filter, def: Option<&FilterDef>, changed: bool) -> bool { + let ctx = sheet.ui.ctx().clone(); + let empty = *filter == Filter::Empty; + let thumbnail = def.and_then(|def| app.thumbs.filter(&ctx, def.id)); + let tokens = Tokens::get(&ctx); + let picture = |painter: &Painter, rect: Rect| match &thumbnail { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + // A picked filter whose picture is still rendering: a filled square, so it never reads as the empty card's outline + None if !empty => { + painter.rect_filled(rect.shrink(OUTLINE_WIDTH), SWATCH_CORNER_RADIUS, tokens.button); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::HOURGLASS_MEDIUM, + egui::FontId::proportional(WAITING_GLYPH_SIZE), + tokens.text_dim, + ); + ctx.request_repaint_after(THUMBNAIL_POLL); + } + None => { + painter.rect_stroke(rect.shrink(OUTLINE_WIDTH), SWATCH_CORNER_RADIUS, Stroke::new(OUTLINE_WIDTH, tokens.text_dim), StrokeKind::Inside); + } + }; + let (name, source) = if empty { (tr("Filter"), tr("None")) } else { (tr(filter.label()), tr("Filter")) }; + let slot = if empty { sheet.slot(&picture, name, source, None, false, false) } else { sheet.slot_restorable(&picture, name, source, changed) }; + if slot.clear { + app.run("effect.set", json!({"effect": effect.0, "filter": texturecraft_engine::mask_cmds::EMPTY_FILTER})); + } + crate::filter_slot::picker(app, &slot.pick, effect.0, def.map(|def| def.id)); + slot.reset +} + +/// The seed of a legacy seeded filter as stored ([`scalar_params`] hands it over as an f32, which rounds seeds past 2^24) +fn legacy_seed(filter: &Filter) -> Option { + match filter { + Filter::Warp { seed, .. } | Filter::DirectionalWarp { seed, .. } | Filter::SlopeBlur { seed, .. } => Some(*seed), + _ => None, + } +} + +/// The filter's own rows: Seed first, Intensity with its Divider chip, angles with their dial, then the color editors +fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter) { + 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); + }; + match filter { + Filter::ColorBalance { shadows, midtones, highlights } => return color_balance(app, sheet, id, [highlights, midtones, shadows]), + Filter::ColorCorrect { shadows, midtones, highlights } => return color_correct(app, sheet, id, [shadows, midtones, highlights]), + Filter::Hsl { hue, saturation, lightness, perceptive } => return hsl(app, sheet, id, [*hue, *saturation, *lightness], *perceptive), + Filter::GradientMap { .. } => return gradient(app, sheet, id, filter), + Filter::GradientCurve { preset, invert, balance, contrast } => return gradient_curve(app, sheet, id, *preset, *invert, [*balance, *contrast]), + Filter::GradientDynamic { vertical, position, .. } => return gradient_dynamic(app, sheet, id, *vertical, *position), + Filter::HaloGlow { on_mask, precise, color, .. } => return glow(app, sheet, id, filter, (*on_mask, *precise), *color), + Filter::DropShadow { color, .. } => return drop_shadow(app, sheet, id, filter, *color), + Filter::BakedLighting { .. } => return baked_lighting_stylized(app, sheet, id, filter), + Filter::Threshold { level, mode } => return threshold(app, sheet, id, *level, *mode), + Filter::Mirror(mirror) => return mirror_rows(app, sheet, id, mirror), + Filter::Transform(transform) => return crate::filter_transform_rows::transform_rows(app, sheet, id, transform), + Filter::MaskOutline(outline) => return mask_outline(app, sheet, id, outline), + Filter::DistanceBevel(bevel) => return bevel_rows(app, sheet, id, bevel), + Filter::BevelSmooth(smooth) => return bevel_smooth(app, sheet, id, smooth), + Filter::SourceWarp(warp) => return source_warp(app, sheet, id, warp), + Filter::SourceSlopeBlur(slope) => return slope_blur(app, sheet, id, slope), + Filter::HighPass { radius, space, alpha } => return highpass(app, sheet, id, *radius, *space, *alpha), + Filter::GrayscaleConversion(conversion) => return grayscale_conversion(app, sheet, id, conversion), + Filter::Grayscale => return grayscale_conversion(app, sheet, id, &GrayscaleConversion::of_luminance()), + Filter::AnisotropicKuwahara(kuwahara) => return anisotropic_kuwahara(app, sheet, id, kuwahara), + Filter::PbrValidate(validate) => return pbr_validate(app, sheet, id, validate), + Filter::HeightToNormal(filter) => return height_to_normal(app, sheet, id, filter), + Filter::ColorMatch(matcher) => return color_match(app, sheet, id, matcher), + _ => {} + } + let params = scalar_params(filter); + + // Invert leads its filter's rows (Invert, Height Adjust) + let leading = match filter { + Filter::Invert | Filter::InvertOff => Some(*filter == Filter::Invert), + Filter::HeightAdjust { invert, .. } => Some(*invert), + _ => None, + }; + if let Some(mut on) = leading + && sheet.toggle(tr("Invert"), &mut on) + { + set(app, "invert", json!(on), false); + } + if let Some(&(_, label, ..)) = params.iter().find(|(key, ..)| *key == "seed") + && let Some(mut seed) = legacy_seed(filter) + && sheet.seed(tr(label), &mut seed) + { + set(app, "seed", json!(seed), false); + } + let divided = divided_key(filter); + for (key, label, mut value, min, max) in params.into_iter().filter(|(key, ..)| *key != "seed") { + let edit = match divided { + Some((divided_param, divider)) if divided_param == key => intensity_row(app, sheet, id, &mut value, min..=max, divider), + _ if matches!(key, "angle" | "azimuth" | "horizontalRotation" | "verticalRotation") => sheet.angle(tr(label), &mut value, min..=max), + _ => range_slider(sheet, tr(label), &mut value, min..=max, decimals(key, min, max)), + }; + if let Some(merge) = edit { + set(app, key, json!(value), merge); + } + } + + // Switches under the sliders: Blur and Bevel reading past the texture's edges, Posterize, Pixelate and FXAA changing the coverage, Histogram Scan's direction + let trailing = match filter { + Filter::Blur { wrap, .. } => Some(("wrap", tr("Blur Wrap"), *wrap)), + Filter::Bevel { wrap, .. } => Some(("wrap", tr("Bevel Wrap"), *wrap)), + Filter::Posterize { alpha, .. } => Some(("applyToAlpha", tr("Apply to Alpha"), *alpha)), + Filter::Mosaic { alpha, .. } => Some(("applyToAlpha", tr("Apply To Alpha"), *alpha)), + Filter::Fxaa { alpha } => Some(("affectAlphaChannel", tr("Affect Alpha Channel"), *alpha)), + Filter::HistogramScan { invert_position, .. } => Some(("invertPosition", tr("Invert Position"), *invert_position)), + _ => None, + }; + if let Some((key, label, mut on)) = trailing + && sheet.toggle(label, &mut on) + { + set(app, key, json!(on), false); + } + + if let Filter::ReplaceColor { from, to, .. } = filter { + replace_colors(app, sheet, id, *from, *to); + } +} + +/// Highpass: Color Space, Radius (in Blur Intensity's unit) and Apply To Alpha +fn highpass(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, radius: f32, space: HighpassSpace, alpha: bool) { + if let (Some(picked), _) = sheet.dropdown(tr("Color Space"), space, &HighpassSpace::ALL, |space| tr(space.label()).to_owned(), None) { + app.run("effect.set", json!({"effect": id, "colorSpace": picked.id()})); + } + slider_rows(app, sheet, id, &[("intensity", tr("Radius"), radius / Filter::BLUR_INTENSITY, 0.0..=BLUR_INTENSITY_SLIDER_MAX)]); + let mut alpha = alpha; + if sheet.toggle(tr("Apply To Alpha"), &mut alpha) { + app.run("effect.set", json!({"effect": id, "applyToAlpha": alpha})); + } +} + +/// Grayscale Conversion: Channel Input (its Custom Input right under it), Invert, Balance, Contrast, Mode and the Channels Weights +fn grayscale_conversion(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, conversion: &GrayscaleConversion) { + let inputs = [tr("Current Channel"), tr("Custom Input")]; + if let Some(picked) = sheet.switch(tr("Channel Input"), &inputs, usize::from(conversion.custom_input)) { + app.run("effect.set", json!({"effect": id, "channelInput": if picked == 1 { "customInput" } else { "currentChannel" }})); + } + if conversion.custom_input { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_INPUT, true); + } + let mut invert = conversion.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + slider_rows(app, sheet, id, &[("balance", tr("Balance"), conversion.balance, 0.0..=1.0), ("contrast", tr("Contrast"), conversion.contrast, 0.0..=1.0)]); + if let (Some(picked), _) = sheet.dropdown(tr("Mode"), conversion.mode, &ConversionMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + app.run("effect.set", json!({"effect": id, "mode": picked.id()})); + } + if conversion.mode == ConversionMode::ChannelsWeights { + let [red, green, blue, alpha] = conversion.weights; + let rows = [ + ("red", tr("Red"), red, 0.0..=1.0), + ("green", tr("Green"), green, 0.0..=1.0), + ("blue", tr("Blue"), blue, 0.0..=1.0), + ("alpha", tr("Alpha"), alpha, 0.0..=1.0), + ]; + slider_rows(app, sheet, id, &rows); + } +} + +/// Anisotropic Kuwahara: Extract Direction (its Custom Input right under it), Radius, Smoothness, Sharpness, Tensor Smoothness, Anisotropy and its Angle +fn anisotropic_kuwahara(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, kuwahara: &AnisotropicKuwahara) { + let inputs = [tr("Current Channel"), tr("Custom Input")]; + if let Some(picked) = sheet.switch(tr("Extract Direction"), &inputs, usize::from(kuwahara.custom_input)) { + app.run("effect.set", json!({"effect": id, "extractDirection": if picked == 1 { "customInput" } else { "currentChannel" }})); + } + if kuwahara.custom_input { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_INPUT, true); + } + let rows = [ + ("radius", tr("Radius"), kuwahara.radius, 0.0..=AnisotropicKuwahara::MAX_RADIUS), + ("smoothness", tr("Smoothness"), kuwahara.smoothness, 0.0..=1.0), + ("sharpness", tr("Sharpness"), kuwahara.sharpness, AnisotropicKuwahara::MIN_SHARPNESS..=1.0), + ("tensorSmoothness", tr("Tensor Smoothness"), kuwahara.tensor_smoothness, 0.0..=1.0), + ("anisotropy", tr("Anisotropy"), kuwahara.anisotropy, 0.0..=1.0), + ]; + slider_rows(app, sheet, id, &rows); + let mut angle = kuwahara.angle; + if let Some(merge) = sheet.angle(tr("Anisotropy Angle"), &mut angle, DIAL_DEGREES) { + app.run("effect.set", json!({"effect": id, "angle": angle, "merge": merge})); + } +} + +/// PBR Validate (Metallic Roughness): Validation Mode, Albedo Dark Range Threshold and Metal Reflectance Range, each label above its switch +fn pbr_validate(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, validate: &PbrValidate) { + let modes: Vec<&str> = ValidationMode::ALL.iter().map(|mode| tr(mode.label())).collect(); + let mode = ValidationMode::ALL.iter().position(|mode| *mode == validate.mode).unwrap_or_default(); + if let Some(picked) = sheet.stacked_switch(tr("Validation Mode"), &modes, mode).and_then(|index| ValidationMode::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "validationMode": picked.id()})); + } + let dark = PbrValidate::ALBEDO_DARK.iter().position(|value| *value == validate.albedo_dark).unwrap_or_default(); + if let Some(picked) = sheet.stacked_switch(tr("Albedo Dark Range Threshold"), &[tr("50 sRGB"), tr("30 sRGB")], dark) { + app.run("effect.set", json!({"effect": id, "albedoDarkRangeThreshold": PbrValidate::ALBEDO_DARK.get(picked)})); + } + let low = PbrValidate::METAL_LOW.iter().position(|value| *value == validate.metal_low).unwrap_or_default(); + if let Some(picked) = sheet.stacked_switch(tr("Metal Reflectance Range"), &[tr("70-100% Reflective"), tr("60-100% Reflective")], low) { + app.run("effect.set", json!({"effect": id, "metalReflectanceRange": PbrValidate::METAL_LOW.get(picked)})); + } +} + +/// Height To Normal: Overwrite Existing Normal, Use World Units, then Surface Size and Height Depth (whole cm) or Normal Intensity +fn height_to_normal(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &HeightToNormal) { + for (key, label, on) in + [("overwriteExistingNormal", tr("Overwrite Existing Normal"), filter.overwrite), ("useWorldUnits", tr("Use World Units"), filter.world_units)] + { + let mut on = on; + if sheet.toggle(label, &mut on) { + app.run("effect.set", json!({"effect": id, key: on})); + } + } + let rows = if filter.world_units { + vec![ + ("surfaceSize", tr("Surface Size (cm)"), filter.surface_size, HeightToNormal::MIN_SURFACE_SIZE..=HeightToNormal::MAX_SURFACE_SIZE, true), + ("heightDepth", tr("Height Depth (cm)"), filter.height_depth, 0.0..=HeightToNormal::MAX_HEIGHT_DEPTH, true), + ] + } else { + vec![("normalIntensity", tr("Normal Intensity"), filter.intensity, 0.0..=HeightToNormal::MAX_INTENSITY, false)] + }; + for (key, label, stored, range, whole_centimetres) in rows { + let mut value = stored; + let decimals = if whole_centimetres { 0 } else { INTENSITY_DECIMALS }; + let slid = sheet.slider(label, &mut value, range, decimals); + if !whole_centimetres { + if let Some(merge) = slid { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + continue; + } + + // Whole centimetres: a press's first whole-number change starts its undo step, changes that round to the stored value apply nothing + let value = value.round(); + let press = sheet.ui.make_persistent_id(("height_to_normal_press", id, key)); + if let Some(merge) = crate::widgets::press_edit(sheet.ui, press, slid.is_some() && value != stored) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } +} + +/// Color Match: each Color Mode with its color or image slot right under it, Custom Color Variation and, while it is on, the Color Variation card (Hue with its dial, Chroma, Luma) +fn color_match(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, matcher: &ColorMatch) { + let color = |app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, key: &str, label: &str, linear: [f32; 3]| { + let pick = sheet.color_bar_led(label, linear, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, key: picked, "merge": pick.merge})); + } + }; + if let (Some(picked), _) = sheet.dropdown(tr("Source Color Mode"), matcher.source_mode, &SourceColorMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + app.run("effect.set", json!({"effect": id, "sourceColorMode": picked.id()})); + } + match matcher.source_mode { + SourceColorMode::Parameter => color(app, sheet, "sourceColor", tr("Source Color"), matcher.source_color), + SourceColorMode::Input => input_slot(app, sheet, LayerId(id), ImageInput::SOURCE_INPUT, true), + SourceColorMode::Average => {} + } + let targets: Vec<&str> = TargetColorMode::ALL.iter().map(|mode| tr(mode.label())).collect(); + let target = usize::from(matcher.target_mode == TargetColorMode::ImageInput); + if let Some(picked) = sheet.switch(tr("Target Color Mode"), &targets, target).and_then(|index| TargetColorMode::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "targetColorMode": picked.id()})); + } + match matcher.target_mode { + TargetColorMode::Parameter => color(app, sheet, "targetColor", tr("Target Color"), matcher.target_color), + TargetColorMode::ImageInput => input_slot(app, sheet, LayerId(id), ImageInput::TARGET_INPUT, true), + } + let mut custom = matcher.custom_variation; + if sheet.toggle(tr("Custom Color Variation"), &mut custom) { + app.run("effect.set", json!({"effect": id, "customColorVariation": custom})); + } + if !matcher.custom_variation { + return; + } + + if sheet.card(tr("Color Variation"), Some(true)) { + let mut hue = matcher.hue; + if let Some(merge) = sheet.angle(tr("Hue"), &mut hue, DIAL_DEGREES) { + app.run("effect.set", json!({"effect": id, "hue": hue, "merge": merge})); + } + slider_rows(app, sheet, id, &[("chroma", tr("Chroma"), matcher.chroma, 0.0..=1.0), ("luma", tr("Luma"), matcher.luma, 0.0..=1.0)]); + } + sheet.close_card(); +} + +/// Threshold: its level, then the Mode comparing a value with it (>, ≥, <, ≤) +fn threshold(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, level: f32, mode: ThresholdMode) { + let mut level = level; + if let Some(merge) = sheet.slider(tr("Threshold"), &mut level, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "level": level, "merge": merge})); + } + let signs = ThresholdMode::ALL.map(ThresholdMode::sign); + let current = ThresholdMode::ALL.iter().position(|candidate| *candidate == mode).unwrap_or_default(); + if let Some(picked) = sheet.switch(tr("Mode"), &signs, current).and_then(|index| ThresholdMode::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "mode": picked.id()})); + } +} + +/// Mirror: Display Debug and Mode, then the axis's offset and Invert switch, or the Corner Type of a corner mirror +fn mirror_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, mirror: &Mirror) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let mut debug = mirror.debug; + if sheet.toggle(tr("Display Debug"), &mut debug) { + set(app, "displayDebug", json!(debug), false); + } + if let (Some(picked), _) = sheet.dropdown(tr("Mode"), mirror.mode, &MirrorMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + set(app, "mode", json!(picked.id()), false); + } + let ([x_offset, y_offset], [x_invert, y_invert]) = (mirror.offset, mirror.invert); + let (offset_key, offset_label, mut offset, invert_key, invert_label, mut invert) = match mirror.mode { + MirrorMode::AxisX => ("axisXOffset", tr("Axis X Offset"), x_offset, "invertAxisX", tr("Invert Axis X"), x_invert), + MirrorMode::AxisY => ("axisYOffset", tr("Axis Y Offset"), y_offset, "invertAxisY", tr("Invert Axis Y"), y_invert), + MirrorMode::Corner => { + let name = |corner: MirrorCorner| tr(corner.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Corner Type"), mirror.corner, &MirrorCorner::ALL, name, None) { + set(app, "cornerType", json!(picked.id()), false); + } + return; + } + }; + if let Some(merge) = sheet.slider(offset_label, &mut offset, 0.0..=1.0, 2) { + set(app, offset_key, json!(offset), merge); + } + if sheet.toggle(invert_label, &mut invert) { + set(app, invert_key, json!(invert), false); + } +} + +/// Mask Outline: Mask Position and Start From Black, then the band's Threshold, Width, Blur and Curve Shape +fn mask_outline(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, outline: &MaskOutline) { + let names = OutlinePosition::ALL.map(|position| tr(position.label())); + let current = OutlinePosition::ALL.iter().position(|position| *position == outline.position).unwrap_or_default(); + if let Some(picked) = sheet.switch(tr("Mask Position"), &names, current).and_then(|index| OutlinePosition::ALL.get(index)) { + app.run("effect.set", json!({"effect": id, "maskPosition": picked.id()})); + } + let mut from_black = outline.from_black; + if sheet.toggle(tr("Start From Black"), &mut from_black) { + app.run("effect.set", json!({"effect": id, "startFromBlack": from_black})); + } + for (key, label, value) in [("threshold", tr("Threshold"), outline.threshold), ("width", tr("Width"), outline.width), ("blur", tr("Blur"), outline.blur)] { + let mut value = value; + if let Some(merge) = sheet.slider(label, &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } + let mut curve = outline.curve; + if let Some(merge) = sheet.signed_slider(tr("Curve Shape"), &mut curve, -1.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "curveShape": curve, "merge": merge})); + } +} + +/// A choice's shown name and the id the command takes for it +type ChoiceNames = (fn(T) -> &'static str, fn(T) -> &'static str); + +/// A switch among `all` (named by `label`) setting `key` to the picked one's `id` +fn choice_switch( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + (label, key): (&str, &str), + all: &[T], + current: T, + (name, id_of): ChoiceNames, +) { + let names: Vec<&str> = all.iter().map(|choice| tr(name(*choice))).collect(); + let current_index = all.iter().position(|choice| *choice == current).unwrap_or_default(); + if let Some(picked) = sheet.switch(label, &names, current_index).and_then(|index| all.get(index)) { + app.run("effect.set", json!({"effect": id, key: id_of(*picked)})); + } +} + +/// Sliders setting `effect.set` keys: (key, label, value, range), signed ranges filling from their middle +fn slider_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, rows: &[(&str, &str, f32, std::ops::RangeInclusive)]) { + for (key, label, value, range) in rows { + let mut value = *value; + if let Some(merge) = range_slider(sheet, label, &mut value, range.clone(), 2) { + app.run("effect.set", json!({"effect": id, *key: value, "merge": merge})); + } + } +} + +/// A slider over `range`, filling from its middle when the range is signed +fn range_slider(sheet: &mut PropertySheet<'_>, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> Option { + if *range.start() < 0.0 { sheet.signed_slider(label, value, range, decimals) } else { sheet.slider(label, value, range, decimals) } +} + +/// The Bevel Wrap switch of a bevel +fn bevel_wrap(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, wrap: bool) { + let mut wrap = wrap; + if sheet.toggle(tr("Bevel Wrap"), &mut wrap) { + app.run("effect.set", json!({"effect": id, "wrap": wrap})); + } +} + +/// Bevel: Bevel Wrap, the signed Distance (inwards below 0), Corner Type, Smoothing and Blur Mode +fn bevel_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, bevel: &Bevel) { + bevel_wrap(app, sheet, id, bevel.wrap); + slider_rows(app, sheet, id, &[("distance", tr("Distance"), bevel.distance, -1.0..=1.0)]); + choice_switch(app, sheet, id, (tr("Corner Type"), "cornerType"), &BevelCorner::ALL, bevel.corner, (BevelCorner::label, BevelCorner::id)); + slider_rows(app, sheet, id, &[("smoothing", tr("Smoothing"), bevel.smoothing, 0.0..=DISTANCE_BEVEL_SMOOTHING_MAX)]); + choice_switch(app, sheet, id, (tr("Blur Mode"), "blurMode"), &BevelBlur::ALL, bevel.blur, (BevelBlur::label, BevelBlur::id)); +} + +/// Bevel Smooth: Direction, the ramp's Distance, Smoothing, Curve Offset and Shape, Mask Threshold, Distance Map Multiplier and Bevel Wrap +fn bevel_smooth(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, smooth: &BevelSmooth) { + choice_switch(app, sheet, id, (tr("Direction"), "direction"), &BevelDirection::ALL, smooth.direction, (BevelDirection::label, BevelDirection::id)); + slider_rows( + app, + sheet, + id, + &[ + ("distance", tr("Distance"), smooth.distance, 0.0..=SMOOTH_DISTANCE_MAX), + ("smoothing", tr("Smoothing"), smooth.smoothing, 0.0..=BEVEL_SMOOTHING_MAX), + ("curveOffset", tr("Curve Offset"), smooth.curve_offset, -1.0..=1.0), + ("curveShape", tr("Curve Shape"), smooth.curve_shape, -1.0..=1.0), + ("maskThreshold", tr("Mask Threshold"), smooth.threshold, 0.0..=1.0), + ("distanceMapMultiplier", tr("Distance Map Multiplier"), smooth.multiplier, 0.0..=1.0), + ], + ); + bevel_wrap(app, sheet, id, smooth.wrap); +} + +/// Warp: Seed, Warp Mode, Intensity with its Divider, the directional modes' Angle (Multi Directional's Directions, Blending Mode), then Source Parameters +fn source_warp(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, warp: &SourceWarp) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let mut seed = warp.seed; + if sheet.seed(tr("Seed"), &mut seed) { + set(app, "seed", json!(seed), false); + } + if let (Some(picked), _) = sheet.dropdown(tr("Warp Mode"), warp.mode, &WarpMode::ALL, |mode| tr(mode.label()).to_owned(), None) { + set(app, "warpMode", json!(picked.id()), false); + } + let mut intensity = warp.intensity; + if let Some(merge) = intensity_row(app, sheet, id, &mut intensity, 0.0..=1.0, warp.divider) { + set(app, "intensity", json!(intensity), merge); + } + if warp.mode != WarpMode::Warp { + let mut angle = warp.angle; + if let Some(merge) = sheet.angle(tr("Angle"), &mut angle, DIAL_DEGREES) { + set(app, "angle", json!(angle), merge); + } + } + if warp.mode == WarpMode::MultiDirectional { + let counts = SourceWarp::DIRECTIONS.map(|count| count.to_string()); + let names: Vec<&str> = counts.iter().map(String::as_str).collect(); + let current_index = SourceWarp::DIRECTIONS.iter().position(|count| *count == warp.directions).unwrap_or_default(); + if let Some(picked) = sheet.switch(tr("Directions"), &names, current_index).and_then(|index| SourceWarp::DIRECTIONS.get(index)) { + set(app, "directions", json!(picked), false); + } + let name = |blending: WarpBlending| tr(blending.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), warp.blending, &WarpBlending::ALL, name, None) { + set(app, "blendingMode", json!(picked.id()), false); + } + } + if sheet.card(tr("Source Parameters"), Some(true)) { + let source = &warp.source; + let name = |mode: WarpSourceMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Source Mode"), source.mode, &WarpSourceMode::ALL, name, None) { + set(app, "sourceMode", json!(picked.id()), false); + } + if source.mode == WarpSourceMode::CustomNoise { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_NOISE, true); + } + slider_rows( + app, + sheet, + id, + &[ + ("sourceBlur", tr("Source Blur"), source.blur, 0.0..=1.0), + ("sourceBalance", tr("Source Balance"), source.balance, 0.0..=1.0), + ("sourceContrast", tr("Source Contrast"), source.contrast, 0.0..=1.0), + ("sourceTiling", tr("Source Tiling"), source.tiling, SOURCE_TILING_MIN..=SOURCE_TILING_MAX), + ], + ); + } + sheet.close_card(); +} + +/// Blur Slope: Seed, Intensity with its Divider, Blending Mode (each drawn as what it does to a bar), Quality, then Source Parameters +fn slope_blur(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, slope: &SourceSlopeBlur) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let mut seed = slope.seed; + if sheet.seed(tr("Seed"), &mut seed) { + set(app, "seed", json!(seed), false); + } + let mut intensity = slope.intensity; + if let Some(merge) = intensity_row(app, sheet, id, &mut intensity, 0.0..=1.0, slope.divider) { + set(app, "intensity", json!(intensity), merge); + } + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = |painter: &Painter, rect: Rect, blending: SlopeBlending| slope_blending_picture(painter, rect, blending, &tokens); + let name = |blending: SlopeBlending| tr(blending.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), slope.blending, &SlopeBlending::ALL, name, Some(&picture)) { + set(app, "blendingMode", json!(picked.id()), false); + } + slider_rows(app, sheet, id, &[("quality", tr("Quality"), slope.quality, 0.0..=1.0)]); + if sheet.card(tr("Source Parameters"), Some(true)) { + let source = &slope.source; + let name = |mode: WarpSourceMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Source Type"), source.mode, &WarpSourceMode::ALL, name, None) { + set(app, "sourceMode", json!(picked.id()), false); + } + if source.mode == WarpSourceMode::CustomNoise { + input_slot(app, sheet, LayerId(id), ImageInput::CUSTOM_NOISE, true); + } + let mut shown_blur = source.blur * SLOPE_SOURCE_BLUR_DISPLAY_MAX; + if let Some(merge) = sheet.slider(tr("Blur"), &mut shown_blur, 0.0..=SLOPE_SOURCE_BLUR_DISPLAY_MAX, 2) { + set(app, "sourceBlur", json!(shown_blur / SLOPE_SOURCE_BLUR_DISPLAY_MAX), merge); + } + slider_rows( + app, + sheet, + id, + &[ + ("sourceBalance", tr("Position"), source.balance, 0.0..=1.0), + ("sourceContrast", tr("Contrast"), source.contrast, 0.0..=1.0), + ("sourceTiling", tr("Source Tiling"), source.tiling, SOURCE_TILING_MIN..=SOURCE_TILING_MAX), + ], + ); + } + sheet.close_card(); +} + +/// The reference shows this blur on 0..20; stored on Warp's shared 0..1 source scale +const SLOPE_SOURCE_BLUR_DISPLAY_MAX: f32 = 20.0; + +/// A light bar on the field after the slope pass: smeared (Blur), eaten away (Min) or grown (Max) +fn slope_blending_picture(painter: &Painter, rect: Rect, blending: SlopeBlending, tokens: &Tokens) { + painter.rect_filled(rect, 0, tokens.field); + let bar = |left: f32, right: f32| { + let (top, bottom) = (rect.top() + rect.height() * SLOPE_BAR_TOP, rect.top() + rect.height() * (1.0 - SLOPE_BAR_TOP)); + Rect::from_min_max(egui::pos2(rect.left() + rect.width() * left, top), egui::pos2(rect.left() + rect.width() * right, bottom)) + }; + match blending { + SlopeBlending::Blur => { + for (step, spread) in SLOPE_BLUR_SPREADS.iter().enumerate() { + let share = (step + 1) as f32 / SLOPE_BLUR_SPREADS.len() as f32; + let tint = tokens.text.gamma_multiply(share * SLOPE_BLUR_LAYER_ALPHA); + painter.rect_filled( + bar(BLUR_BAR.0 - spread, BLUR_BAR.1 + spread).expand2(egui::vec2(0.0, spread * rect.height() * SLOPE_BLUR_VERTICAL_SHARE)), + SLOPE_BLUR_LAYER_ROUNDING, + tint, + ); + } + } + SlopeBlending::Min => { + painter.rect_filled(bar(MIN_BAR.0, MIN_BAR.1), 0, tokens.text); + } + SlopeBlending::Max => { + painter.rect_filled(bar(MAX_BAR.0, MAX_BAR.1), 0, tokens.text); + } + } + painter.rect_stroke(rect, 0, Stroke::new(OUTLINE_WIDTH, tokens.field_border), StrokeKind::Inside); +} + +/// Where a blending picture's bar starts down its square (and ends as far from the bottom) +const SLOPE_BAR_TOP: f32 = 0.25; + +/// How far each soft layer of the Blur picture's bar spreads past the bar (shares of the square), widest first +const SLOPE_BLUR_SPREADS: [f32; 4] = [0.12, 0.08, 0.04, 0.0]; + +/// How opaque the Blur picture's soft layers stack up to +const SLOPE_BLUR_LAYER_ALPHA: f32 = 0.45; + +/// How much of a Blur layer's sideways spread it also grows up and down: half, so the smear reads wider than tall +const SLOPE_BLUR_VERTICAL_SHARE: f32 = 0.5; + +/// How round a Blur layer's corners are, in points: soft, where the Min and Max bars are square +const SLOPE_BLUR_LAYER_ROUNDING: u8 = 1; + +/// The left and right ends of each slope blur mode's bar, as shares of the pictogram's width +const BLUR_BAR: (f32, f32) = (0.3, 0.62); +const MIN_BAR: (f32, f32) = (0.42, 0.58); +const MAX_BAR: (f32, f32) = (0.18, 0.82); + +/// The tone groups' names and the `effect.set` keys they edit, in the order a panel shows them +const SHADOWS: (&str, &str) = ("Shadows", "shadows"); +const MIDTONES: (&str, &str) = ("Midtones", "midtones"); +const HIGHLIGHTS: (&str, &str) = ("Highlights", "highlights"); + +/// Color Balance: a card per tone (Highlights, Midtones, Shadows), each with Cyan ↔ Red, Magenta ↔ Green and Yellow ↔ Blue +fn color_balance(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, tones: [&[f32; 3]; 3]) { + let ends = [(tr("Cyan"), tr("Red")), (tr("Magenta"), tr("Green")), (tr("Yellow"), tr("Blue"))]; + let rights = ends.map(|(_, right)| right); + for ((name, key), values) in [HIGHLIGHTS, MIDTONES, SHADOWS].into_iter().zip(tones) { + if !sheet.card(tr(name), Some(true)) { + sheet.close_card(); + continue; + } + + let mut balance = *values; + let mut edit = None; + for (component, (value, (left, right))) in balance.iter_mut().zip(ends).enumerate() { + let (left_tint, right_tint) = + (OPPOSITE_COLORS.get(component).copied().unwrap_or_default(), AXIS_COLORS.get(component).copied().unwrap_or_default()); + edit = edit.or(sheet.tinted_slider((left, left_tint), (right, right_tint), &rights, value)); + } + sheet.close_card(); + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, key: balance, "merge": merge})); + } + } +} + +/// Color Correct: a card per tone (Shadows, Midtones, Highlights), each with Contrast, Luminosity and Saturation +fn color_correct(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, tones: [&[f32; 3]; 3]) { + for ((name, key), values) in [SHADOWS, MIDTONES, HIGHLIGHTS].into_iter().zip(tones) { + if !sheet.card(tr(name), Some(true)) { + sheet.close_card(); + continue; + } + + let [mut contrast, mut luminosity, mut saturation] = *values; + let edit = sheet + .signed_slider(tr("Contrast"), &mut contrast, -1.0..=1.0, 2) + .or(sheet.signed_slider(tr("Luminosity"), &mut luminosity, -1.0..=1.0, 2)) + .or(sheet.slider(tr("Saturation"), &mut saturation, 0.0..=1.0, 2)); + sheet.close_card(); + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, key: [contrast, luminosity, saturation], "merge": merge})); + } + } +} + +/// HSL Perceptive: Mode (Regular | Perceptive), then Hue, Saturation and Lightness on 0..1 with 0.5 leaving them as they are +fn hsl(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, [hue, saturation, lightness]: [f32; 3], perceptive: bool) { + if let Some(mode) = sheet.switch(tr("Mode"), &[tr("Regular"), tr("Perceptive")], usize::from(perceptive)) { + app.run("effect.set", json!({"effect": id, "mode": if mode == 1 { "perceptive" } else { "regular" }})); + } + + // Shown around 0.5: the hue as half a turn either way (a stored turn past half wraps round), saturation and lightness as −1..1 halved + let rows = [ + ("hue", tr("Hue"), (hue + 0.5).rem_euclid(1.0), 1.0), + ("saturation", tr("Saturation"), 0.5 + saturation / 2.0, 2.0), + ("lightness", tr("Lightness"), 0.5 + lightness / 2.0, 2.0), + ]; + for (key, label, shown, scale) in rows { + let mut value = shown.clamp(0.0, 1.0); + if let Some(merge) = sheet.centered_slider(label, &mut value, 0.0..=1.0, 0.5, 2) { + app.run("effect.set", json!({"effect": id, key: (value - 0.5) * scale, "merge": merge})); + } + } +} + +/// Gradient: Display Gradient (Debug), the Input Transformation card, then the Colors card (the ramp, Color Quantity, Blend Color in Linear and a row per color) +fn gradient(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter) { + let Filter::GradientMap { colors, positions, input, linear, debug, .. } = filter else { return }; + let set = |app: &mut TextureCraftApp, params: Value| { + let mut params = params; + params["effect"] = json!(id); + app.run("effect.set", params); + }; + let mut shown = *debug; + if sheet.toggle(tr("Display Gradient (Debug)"), &mut shown) { + set(app, json!({"debug": shown})); + } + + if sheet.card(tr("Input Transformation"), Some(true)) { + let name = |mode: GrayscaleMode| tr(mode.label()).to_owned(); + if let (Some(mode), _) = sheet.dropdown(tr("Grayscale Mode"), input.mode, &GrayscaleMode::ALL, name, None) { + set(app, json!({"grayscaleMode": mode.id()})); + } + for (key, label, value) in + [("blur", tr("Blur Intensity"), input.blur), ("balance", tr("Balance"), input.balance), ("contrast", tr("Contrast"), input.contrast)] + { + let mut value = value; + let range = if key == "blur" { 0.0..=BLUR_INTENSITY_SLIDER_MAX } else { 0.0..=1.0 }; + if let Some(merge) = sheet.slider(label, &mut value, range, 2) { + set(app, json!({key: value, "merge": merge})); + } + } + let mut invert = input.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + set(app, json!({"invert": invert})); + } + } + sheet.close_card(); + + if sheet.card(tr("Colors"), Some(true)) { + let used = filter.ramp_colors(); + + // An evenly spaced ramp (projects saved before) shows its places, and keeps them once one moves + let last = used.len().saturating_sub(1).max(1) as f32; + let mut places: Vec = (0..colors.len()).map(|index| positions.get(index).copied().unwrap_or(index as f32 / last)).collect(); + if let Some(drag) = sheet.gradient_ramp(used, &places, &|t| filter.ramp_at(t).unwrap_or([0.0; 3])) { + if let Some(place) = places.get_mut(drag.index) { + *place = drag.position; + } + set(app, json!({"positions": places, "merge": drag.merge})); + } + let mut quantity = used.len() as f32; + let slid = sheet.slider(tr("Color Quantity"), &mut quantity, f32::from(GRADIENT_QUANTITY_MIN)..=f32::from(Filter::MAX_GRADIENT_COLORS), 0).is_some(); + let quantity = quantity.round(); + + // A press's first whole-number change starts its undo step: changes that round to the count it has apply nothing + let press = sheet.ui.make_persistent_id(("color_quantity_press", id)); + if let Some(merge) = crate::widgets::press_edit(sheet.ui, press, slid && quantity as usize != used.len()) { + set(app, json!({"quantity": quantity, "merge": merge})); + } + let mut in_linear = *linear; + if sheet.toggle(tr("Blend Color in Linear"), &mut in_linear) { + set(app, json!({"linear": in_linear})); + } + for (index, color) in used.iter().enumerate() { + let label = trf("Color {number}", &[("number", &(index + 1))]); + let mut place = places.get(index).copied().unwrap_or(0.0); + let (pick, moved) = sheet.color_stop(&label, *color, &mut place, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + let mut recolored = colors.clone(); + if let Some(slot) = recolored.get_mut(index) { + *slot = picked; + } + set(app, json!({"colors": recolored, "merge": pick.merge})); + } + if let Some(merge) = moved { + if let Some(slot) = places.get_mut(index) { + *slot = place; + } + set(app, json!({"positions": places, "merge": merge})); + } + } + } + sheet.close_card(); +} + +/// Gradient Curve: Preset (each drawn as its curve), Invert, Balance and Contrast +fn gradient_curve(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, preset: CurvePreset, invert: bool, [balance, contrast]: [f32; 2]) { + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = |painter: &Painter, rect: Rect, preset: CurvePreset| curve_picture(painter, rect, preset, &tokens); + let name = |preset: CurvePreset| tr(preset.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Preset"), preset, &CurvePreset::ALL, name, Some(&picture)) { + app.run("effect.set", json!({"effect": id, "preset": picked.id()})); + } + let mut inverted = invert; + if sheet.toggle(tr("Invert"), &mut inverted) { + app.run("effect.set", json!({"effect": id, "invert": inverted})); + } + for (key, label, value) in [("balance", tr("Balance"), balance), ("contrast", tr("Contrast"), contrast)] { + let mut value = value; + if let Some(merge) = sheet.slider(label, &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } +} + +/// A curve preset's shape over a dark square +fn curve_picture(painter: &Painter, rect: Rect, preset: CurvePreset, tokens: &Tokens) { + painter.rect_filled(rect, CURVE_PICTURE_ROUNDING, tokens.field); + let inner = rect.shrink(CURVE_PICTURE_INSET); + let points: Vec = (0..=CURVE_PICTURE_STEPS) + .map(|step| { + let t = step as f32 / CURVE_PICTURE_STEPS as f32; + egui::pos2(inner.left() + inner.width() * t, inner.bottom() - inner.height() * preset.at(t)) + }) + .collect(); + painter.add(egui::Shape::line(points, Stroke::new(CURVE_PICTURE_STROKE, tokens.accent))); +} + +/// A curve picture's inset in its square, in points +const CURVE_PICTURE_INSET: f32 = 2.0; + +/// How round a curve picture's square is, in points +const CURVE_PICTURE_ROUNDING: u8 = 2; + +/// How many straight pieces a curve picture's line is drawn with +const CURVE_PICTURE_STEPS: usize = 30; + +/// The width of a curve picture's line, in points +const CURVE_PICTURE_STROKE: f32 = 1.5; + +/// Gradient Dynamic: Gradient Orientation and Gradient Input Position (its Gradient Source is a card after the filter's) +fn gradient_dynamic(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, vertical: bool, position: f32) { + if let Some(picked) = sheet.switch(tr("Gradient Orientation"), &[tr("Horizontal"), tr("Vertical")], usize::from(vertical)) { + app.run("effect.set", json!({"effect": id, "orientation": if picked == 1 { "vertical" } else { "horizontal" }})); + } + let mut value = position; + if let Some(merge) = sheet.slider(tr("Gradient Input Position"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "position": value, "merge": merge})); + } +} + +/// Gradient Dynamic's Gradient Source: its own slot card after the filter's, a uniform color whose bar opens the picker +fn gradient_source(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, color: [f32; 3]) { + let swatch = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, SWATCH_CORNER_RADIUS, crate::fill_material_panel::shown_color(color)); + }; + + // The card's row opens the picker of the colour bar under it: its source is a uniform color only + let card = sheet.slot(&swatch, tr("Gradient Source"), tr("Uniform"), None, false, false); + let pick = sheet.color_bar(tr("Gradient Source"), color, app.picking_color, &app.session.doc.project.swatches); + if card.pick.clicked() { + sheet.open_color_picker(pick.id, color); + } + sheet.close_card(); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, "color": picked, "merge": pick.merge})); + } +} + +/// Glow: Used on a Mask, Mode (Soft | Precise), Width (inner below 0), Spread, Opacity and its Color +fn glow(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter, (on_mask, precise): (bool, bool), color: [f32; 3]) { + let mut used = on_mask; + if sheet.toggle(tr("Used on a Mask"), &mut used) { + app.run("effect.set", json!({"effect": id, "usedOnMask": used})); + } + if let Some(mode) = sheet.switch(tr("Mode"), &[tr("Soft"), tr("Precise")], usize::from(precise)) { + app.run("effect.set", json!({"effect": id, "mode": if mode == 1 { "precise" } else { "soft" }})); + } + for (key, label, mut value, min, max) in scalar_params(filter) { + if let Some(merge) = range_slider(sheet, tr(label), &mut value, min..=max, 2) { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } + color_row(app, sheet, id, color); +} + +/// Drop Shadow: Angle with its dial, Distance (either way), Size, Spread, Opacity and its Color +fn drop_shadow(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter, color: [f32; 3]) { + for (key, label, mut value, min, max) in scalar_params(filter) { + let edit = if key == "angle" { sheet.angle(tr(label), &mut value, min..=max) } else { range_slider(sheet, tr(label), &mut value, min..=max, 2) }; + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + } + } + color_row(app, sheet, id, color); +} + +/// Baked Lighting Stylized: a card each for the Sun, the Sky, Light 1 and 2, Occlusion and cavity, the Material and Normal details (one saved before shows its plain settings) +fn baked_lighting_stylized(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, filter: &Filter) { + let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, stylized } = filter else { return }; + let lighting = stylized.as_deref().unwrap_or(&StylizedLighting::PLAIN); + let set = |app: &mut TextureCraftApp, params: Value| { + let mut params = params; + params["effect"] = json!(id); + app.run("effect.set", params); + }; + + if sheet.card(tr("Sun"), Some(true)) { + let mut value = *light; + if let Some(merge) = sheet.slider(tr("Sun Intensity"), &mut value, 0.0..=SUN_INTENSITY_MAX, 2) { + set(app, json!({"light": value, "merge": merge})); + } + for (key, label, value) in + [("azimuth", tr("Sun Horizontal Angle"), *azimuth), ("elevation", tr("Sun Vertical Angle"), elevation.rem_euclid(FULL_TURN_DEGREES))] + { + let mut value = value; + if let Some(merge) = sheet.angle(label, &mut value, DIAL_DEGREES) { + set(app, json!({key: value, "merge": merge})); + } + } + let pick = sheet.color_bar_led(tr("Sun Color"), lighting.sun_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + set(app, json!({"sunColor": picked, "merge": pick.merge})); + } + } + sheet.close_card(); + + if sheet.card(tr("Sky"), Some(true)) { + let mut value = *ambient; + if let Some(merge) = sheet.slider(tr("Sky Intensity"), &mut value, 0.0..=SKY_INTENSITY_SLIDER_MAX, 2) { + set(app, json!({"ambient": value, "merge": merge})); + } + for (key, label, color) in [ + ("skyColor", tr("Sky Color"), lighting.sky_color), + ("horizonColor", tr("Horizon Color"), lighting.horizon_color), + ("groundColor", tr("Ground Color"), lighting.ground_color), + ] { + let pick = sheet.color_bar_led(label, color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + set(app, json!({key: picked, "merge": pick.merge})); + } + } + } + sheet.close_card(); + + for (key, title, extra) in [("light1", tr("Light 1"), lighting.lights[0]), ("light2", tr("Light 2"), lighting.lights[1])] { + if sheet.card(title, Some(true)) { + extra_light(app, sheet, id, key, extra); + } + sheet.close_card(); + } + + if sheet.card(tr("Occlusion and cavity"), Some(true)) { + let rows = [ + ("occlusion", tr("Diffuse AO"), *occlusion, 1.0), + ("diffuseCavity", tr("Diffuse Cavity"), lighting.diffuse_cavity, 1.0), + ("specularAo", tr("Specular AO"), lighting.specular_ao, 1.0), + ("specularCavity", tr("Specular Cavity"), lighting.specular_cavity, 1.0), + ("cavitySmoothness", tr("Cavity Smoothness"), lighting.cavity_smoothness, MAX_CAVITY_SMOOTHNESS), + ("edgesIntensity", tr("Edges Intensity"), lighting.edges_intensity, 1.0), + ("edgesSmoothness", tr("Edges Smoothness"), lighting.edges_smoothness, 1.0), + ]; + for (key, label, value, max) in rows { + let mut value = value; + if let Some(merge) = sheet.slider(label, &mut value, 0.0..=max, 2) { + set(app, json!({key: value, "merge": merge})); + } + } + } + sheet.close_card(); + + if sheet.card(tr("Material"), Some(true)) { + let input = |glossiness: bool| tr(if glossiness { "Specular / Glossiness" } else { "Metal / Roughness" }).to_owned(); + if let (Some(glossiness), _) = sheet.dropdown(tr("Input"), lighting.specular_glossiness, &[false, true], input, None) { + set(app, json!({"input": if glossiness { "specularGlossiness" } else { "metalRoughness" }})); + } + let output = |output: LightingOutput| tr(output.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Output"), lighting.output, &LightingOutput::ALL, output, None) { + set(app, json!({"output": picked.id()})); + } + let mut value = lighting.dielectric_reflectance; + if let Some(merge) = sheet.slider(tr("Dielectric Reflectance"), &mut value, 0.0..=MAX_DIELECTRIC_REFLECTANCE, 2) { + set(app, json!({"dielectricReflectance": value, "merge": merge})); + } + } + sheet.close_card(); + + if sheet.card(tr("Normal details"), Some(true)) { + let details = |mesh_only: bool| tr(if mesh_only { "Mesh only" } else { "Mesh + Height + Normal" }).to_owned(); + if let (Some(mesh_only), _) = sheet.dropdown(tr("Normal Details Type"), lighting.mesh_only, &[true, false], details, None) { + set(app, json!({"normalDetails": if mesh_only { "mesh" } else { "meshHeightNormal" }})); + } + let mut value = lighting.height_to_normal; + if let Some(merge) = sheet.slider(tr("Height to Normal Intensity"), &mut value, 0.0..=MAX_HEIGHT_TO_NORMAL, 2) { + set(app, json!({"heightToNormal": value, "merge": merge})); + } + } + sheet.close_card(); +} + +/// Light 1 or 2's rows (`key` names it to `effect.set`): Horizontal and Vertical Angle with their dials, Intensity and Color +fn extra_light(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, key: &str, light: DirectionalLight) { + let set = |app: &mut TextureCraftApp, part: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: part, "merge": merge})); + }; + for (part, label, value) in + [("azimuth", tr("Horizontal Angle"), light.azimuth), ("elevation", tr("Vertical Angle"), light.elevation.rem_euclid(FULL_TURN_DEGREES))] + { + let mut value = value; + if let Some(merge) = sheet.angle(label, &mut value, DIAL_DEGREES) { + set(app, json!({part: value}), merge); + } + } + let mut intensity = light.intensity; + if let Some(merge) = sheet.slider(tr("Intensity"), &mut intensity, 0.0..=MAX_LIGHT_INTENSITY, 2) { + set(app, json!({"intensity": intensity}), merge); + } + let pick = sheet.color_bar_led(tr("Color"), light.color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + set(app, json!({"color": picked}), pick.merge); + } +} + +/// A light or shadow filter's Color: its bar opens the colour picker, the eyedropper picks from the screen +fn color_row(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, color: [f32; 3]) { + let pick = sheet.color_bar_led(tr("Color"), color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, "color": picked, "merge": pick.merge})); + } +} + +/// The parameter a filter's Divider divides and the divider it has +fn divided_key(filter: &Filter) -> Option<(&'static str, u16)> { + match filter { + Filter::Warp { divider, .. } | Filter::DirectionalWarp { divider, .. } => Some(("intensity", *divider)), + Filter::SlopeBlur { divider, .. } => Some(("radius", *divider)), + _ => None, + } +} + +/// Intensity with its "÷10" Divider chip before the value; the chip's list picks 1, 10, 100 or 1000 +fn intensity_row( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + value: &mut f32, + range: std::ops::RangeInclusive, + divider: u16, +) -> Option { + let shown = |divider: u16| format!("÷{divider}"); + let (edit, chip) = sheet.slider_with_chip(tr("Intensity"), value, range, 2, &shown(divider), WIDEST_DIVIDER); + let (picked, _) = sheet.hanging_list(&chip, divider, &Filter::DIVIDERS, &shown, None); + if let Some(divider) = picked { + app.run("effect.set", json!({"effect": id, "divider": divider})); + } + edit +} + +/// A range wider than this shows one decimal +const WIDE_RANGE: f32 = 10.0; + +/// Decimals a parameter's value shows: whole numbers for counts, two for blur intensities, one for wide ranges +fn decimals(key: &str, min: f32, max: f32) -> usize { + if matches!(key, "levels" | "pixelsAmount") { + 0 + } else if key == "intensity" { + 2 + } else if max - min > WIDE_RANGE { + 1 + } else { + 2 + } +} + +/// Replace Color's two colors: each bar opens the colour picker, its eyedropper picks from the screen +fn replace_colors(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, from: [f32; 3], to: [f32; 3]) { + for (key, label, linear) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { + let pick = sheet.color_bar_led(label, linear, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = crate::fill_material_panel::take_color_pick(app, pick) { + app.run("effect.set", json!({"effect": id, key: picked, "merge": pick.merge})); + } + } +} diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index de81ca34..daa99d27 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -1,10 +1,9 @@ -//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it +//! The filter picker hanging from the filter card: a grid of the library's filters that swaps the effect's filter -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::{filter_effects, find}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::filter_lib::filter_effects; use crate::TextureCraftApp; use crate::i18n::tr; @@ -12,46 +11,19 @@ use crate::picker_group::PickerGroup; use crate::picker_tab::PickerTab; use crate::resource_picker; use crate::resource_picker_item::ResourcePickerItem; -use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::tile_picture::TilePicture; -use crate::widgets::elided; -pub(crate) 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; -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; -/// 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) { - let ctx = ui.ctx().clone(); +/// The filter picker of filter effect `effect` (library filter `current` now), hanging from its card's row `pick`: a pick runs `effect.set {filter}`, masks offer only mask filters +pub(crate) fn picker(app: &mut TextureCraftApp, pick: &egui::Response, effect: u64, current: Option<&'static str>) { + let ctx = pick.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)); - - let popup = ui.make_persistent_id(("filter_picker", effect)); + let popup = pick.id.with(("filter_picker", effect)); let open_requested = take_open_request(&ctx, effect); - - if response.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) { + if pick.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().map(egui::TextureHandle::id), (tr("Filter"), name)); - let tabs = |thumbs: &mut Thumbs| { let mut items: Vec> = filter_effects() .iter() @@ -69,6 +41,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: vec![PickerTab { icon: ic::FUNNEL, name: tr("Filters"), groups: vec![PickerGroup { header: None, items }] }] }; let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); + let picked = resource_picker::show(pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); if let Some(id) = picked.filter(|id| Some(*id) != current) { app.run("effect.set", json!({"effect": effect, "filter": id})); } @@ -80,13 +53,20 @@ pub(crate) fn open_picker_when_shown(ctx: &egui::Context, effect: u64) { 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 +/// Whether an open request for `effect`'s slot is waiting, removing it; a request for another effect stays for that effect's slot, one 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())); + ctx.data_mut(|data| { + let Some((requested_effect, requested_frame)) = data.get_temp::<(u64, u64)>(open_request_id()) else { return false }; - // 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) + // Properties can draw before or after the menu that asked, so a request lives for this frame and the next + let lapsed = frame > requested_frame.saturating_add(1); + let for_this_slot = requested_effect == effect; + if lapsed || for_this_slot { + data.remove_temp::<(u64, u64)>(open_request_id()); + } + for_this_slot && !lapsed + }) } /// Where the effect whose slot should open its picker waits @@ -95,37 +75,24 @@ fn open_request_id() -> egui::Id { } /// Whether filter effect `effect` sits in a mask rather than the layer content -fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { +pub(crate) 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)) } -/// A slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, `caption` over `name`, caret (fill source slots share it) -pub(crate) fn paint(ui: &Ui, rect: Rect, (highlighted, focused): (bool, bool), thumbnail: Option, (caption, name): (&str, &str)) { - let tokens = Tokens::get(ui.ctx()); - let painter = ui.painter(); - let (fill, border) = if highlighted { (tokens.row_hover, tokens.button_border) } else { (tokens.field, tokens.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); - } +#[cfg(test)] +mod tests { + use super::*; - 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, image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); - } + /// Two filter sheets drawn in one frame: the one for another effect leaves the request to the slot it is for + #[test] + fn an_open_request_waits_for_its_own_slot() { + let ctx = egui::Context::default(); + open_picker_when_shown(&ctx, 2); - // 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 = [(caption, CAPTION_FONT_SIZE, tokens.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tokens.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); + assert!(!take_open_request(&ctx, 1), "not the requested slot"); + assert!(take_open_request(&ctx, 2), "the requested slot still finds it"); + assert!(!take_open_request(&ctx, 2), "taken once"); } - - let caret_color = if highlighted { tokens.text } else { tokens.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/src/filter_transform_rows.rs b/crates/ui-egui/src/filter_transform_rows.rs new file mode 100644 index 00000000..68bdb4bd --- /dev/null +++ b/crates/ui-egui/src/filter_transform_rows.rs @@ -0,0 +1,91 @@ +//! The Transform filter's rows: Scaling and Offset beside a preview of the moved tile, Tile Safe Rotation, Rotation, Repeat mode and Flip mode + +use std::ops::RangeInclusive; + +use egui::{Painter, Rect, pos2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{FlipMode, RepeatMode, TileTransform, UvWrap}; + +use crate::TextureCraftApp; +use crate::fill_pictures::{lattice_preview, wrap_picture}; +use crate::filter_properties::DIAL_DEGREES; +use crate::i18n::tr; +use crate::property_sheet::{PreviewLower, PreviewSize, PropertySheet}; +use crate::theme::Tokens; + +/// What the Scaling track spans (a fill's Tiling track); typing reaches the filter's whole range +const SCALING_TRACK: RangeInclusive = 0.01..=5.0; + +/// What the Offset track spans, in tiles: one tile either way covers every position of a repeating tile +const OFFSET_TRACK: RangeInclusive = -1.0..=1.0; + +/// The rows in the reference's order: Scaling (linked) and Offset beside the preview, Tile Safe Rotation, Rotation, Repeat mode, Flip mode +pub(crate) fn transform_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, transform: &TileTransform) { + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + app.run("effect.set", json!({"effect": id, key: value, "merge": merge})); + }; + let tokens = Tokens::get(sheet.ui.ctx()); + + let link_id = sheet.ui.make_persistent_id(("transform_scaling_link", id)); + let mut linked = sheet.ui.data(|data| data.get_temp::(link_id)).unwrap_or(transform.scaling[0] == transform.scaling[1]); + let was_linked = linked; + let (low, high) = TileTransform::SCALING; + let mut scaling = transform.scaling; + let size = PreviewSize { label: tr("Scaling"), values: &mut scaling, range: SCALING_TRACK, typed: low..=high, decimals: 2, linked: &mut linked }; + let mut offset = transform.offset; + let reach = TileTransform::MAX_OFFSET; + let lower = PreviewLower::Offset { values: &mut offset, range: OFFSET_TRACK, typed: -reach..=reach }; + let (map, repeat) = (transform.affine(), transform.repeat == RepeatMode::HorizontallyAndVertically); + let picture = |painter: &Painter, rect: Rect| lattice_preview(painter, rect, map, repeat, &tokens); + let edit = sheet.preview_block(&picture, size, lower); + if linked != was_linked { + sheet.ui.data_mut(|data| data.insert_temp(link_id, linked)); + } + if let Some(merge) = edit.size + && scaling != transform.scaling + { + set(app, "scaling", json!(scaling), merge); + } + if let Some(merge) = edit.lower + && offset != transform.offset + { + set(app, "offset", json!(offset), merge); + } + + let mut tile_safe = transform.tile_safe; + if sheet.toggle(tr("Tile Safe Rotation"), &mut tile_safe) { + set(app, "tileSafeRotation", json!(tile_safe), false); + } + let mut degrees = transform.rotation; + if let Some(merge) = sheet.angle(tr("Rotation"), &mut degrees, DIAL_DEGREES) { + set(app, "rotation", json!(degrees), merge); + } + + let repeat_picture = |painter: &Painter, rect: Rect, mode: RepeatMode| { + let wrap = if mode == RepeatMode::None { UvWrap::None } else { UvWrap::Repeat }; + wrap_picture(painter, rect, wrap, &tokens); + }; + let name = |mode: RepeatMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Repeat mode"), transform.repeat, &RepeatMode::ALL, name, Some(&repeat_picture)) { + set(app, "repeatMode", json!(picked.id()), false); + } + let flip_picture = |painter: &Painter, rect: Rect, mode: FlipMode| flip_picture(painter, rect, mode, &tokens); + let name = |mode: FlipMode| tr(mode.label()).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Flip mode"), transform.flip, &FlipMode::ALL, name, Some(&flip_picture)) { + set(app, "flipMode", json!(picked.id()), false); + } +} + +/// An L, turned over the way the flip mode turns the tile (no letters, so it reads in any language) +fn flip_picture(painter: &Painter, rect: Rect, mode: FlipMode, tokens: &Tokens) { + const L_SHAPE: [[f32; 2]; 6] = [[0.3, 0.2], [0.45, 0.2], [0.45, 0.65], [0.75, 0.65], [0.75, 0.8], [0.3, 0.8]]; + let [across, down] = mode.sides(); + + // An L is not convex: two rectangles draw it + let [top, _, joint, _, far, bottom] = L_SHAPE.map(|[u, v]| { + let (u, v) = (if across { 1.0 - u } else { u }, if down { 1.0 - v } else { v }); + pos2(rect.left() + u * rect.width(), rect.top() + v * rect.height()) + }); + painter.rect_filled(Rect::from_two_pos(top, pos2(joint.x, bottom.y)), 0, tokens.accent); + painter.rect_filled(Rect::from_two_pos(joint, far), 0, tokens.accent); +} diff --git a/crates/ui-egui/src/property_sheet/attribute_rows.rs b/crates/ui-egui/src/property_sheet/attribute_rows.rs new file mode 100644 index 00000000..82255146 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/attribute_rows.rs @@ -0,0 +1,60 @@ +//! Read-only rows (an asset's Attributes): a label and its value as dim text, nothing to edit + +use egui::text::{LayoutJob, TextFormat, TextWrapping}; +use egui::{FontId, Galley, Sense, pos2}; +use std::sync::Arc; + +use super::{PropertySheet, TEXT_SIZE}; + +/// Height of the label line above a wrapped text +const TEXT_LABEL_LINE: f32 = 18.0; + +/// From the label line's top to the label's centre +const TEXT_LABEL_CENTER: f32 = 8.0; + +/// Air above a wrapped text's label +const TEXT_LABEL_AIR: f32 = 4.0; + +/// Height of a wrapped text's lines +const TEXT_LINE_HEIGHT: f32 = 18.0; + +/// Air under a wrapped text's last line +const TEXT_AIR_BELOW: f32 = 6.0; + +impl PropertySheet<'_> { + /// `label` beside its value as dim text, cut with "…" where it would pass the right edge (the whole value then shows on hover) + pub(crate) fn attribute(&mut self, label: &str, value: &str) { + let (rect, center_y) = self.row(label); + let galley = self.dim_text(value, rect.width(), Some(1)); + let cut = galley.elided; + self.ui.painter().galley(pos2(rect.left(), center_y - galley.size().y / 2.0), galley, self.tokens.text_dim); + let response = self.ui.interact(rect, self.id.with(("attribute", label)), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label}: {value}"))); + if cut { + self.tip(response, value); + } + } + + /// `label` on its own line, then `text` wrapped across the panel in dim lines + pub(crate) fn attribute_text(&mut self, label: &str, text: &str) { + self.space(TEXT_LABEL_AIR); + let line = self.take(TEXT_LABEL_LINE); + let color = self.tokens.text; + self.ui.painter().text(pos2(self.left, line.top() + TEXT_LABEL_CENTER), egui::Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), color); + let galley = self.dim_text(text, self.right - self.left, None); + let body = self.take(galley.size().y.max(TEXT_LINE_HEIGHT) + TEXT_AIR_BELOW); + let response = self.ui.interact(body, self.id.with(("attribute", label)), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{label}: {text}"))); + self.ui.painter().galley(pos2(self.left, body.top()), galley, self.tokens.text_dim); + self.drawn(body.bottom() - TEXT_AIR_BELOW); + } + + /// `text` laid out dim in `width`, wrapped on lines [`TEXT_LINE_HEIGHT`] apart, at most `rows` of them (the last cut with "…") + fn dim_text(&self, text: &str, width: f32, rows: Option) -> Arc { + let format = + TextFormat { font_id: FontId::proportional(TEXT_SIZE), color: self.tokens.text_dim, line_height: Some(TEXT_LINE_HEIGHT), ..Default::default() }; + let mut job = LayoutJob::single_section(text.to_owned(), format); + job.wrap = TextWrapping { max_width: width, max_rows: rows.unwrap_or(usize::MAX), break_anywhere: rows.is_some(), overflow_character: Some('…') }; + self.ui.painter().layout_job(job) + } +} diff --git a/crates/ui-egui/src/property_sheet/gradient_rows.rs b/crates/ui-egui/src/property_sheet/gradient_rows.rs new file mode 100644 index 00000000..a99a4cb2 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/gradient_rows.rs @@ -0,0 +1,120 @@ +//! A gradient's ramp with a marker per color, and a color's row with its place on the ramp + +use std::ops::RangeInclusive; + +use egui::{CornerRadius, Id, Mesh, Rect, Sense, Shape, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use super::PropertySheet; +use super::marker_drag::MarkerDrag; +use super::slider::KNOB_RADIUS; +use super::track::Track; +use crate::color_picker::ColorPick; +use crate::fill_material_panel::shown_color; + +/// The ramp's inset from the rows' edges, so the end markers stay inside them +const RAMP_INSET: f32 = 5.0; + +/// Height of the ramp, the air under it, and a marker's height and half width +const RAMP_HEIGHT: f32 = 16.0; +const MARKER_AIR: f32 = 2.0; +const MARKER_HEIGHT: f32 = 12.0; +const MARKER_HALF: f32 = 5.0; + +/// How far beyond a marker's sides it still answers a drag +const MARKER_HIT_MARGIN: f32 = 1.0; + +/// From the marker's tip to where its sides turn straight down +const MARKER_SHOULDER: f32 = 6.0; + +/// The whole ramp block: ramp, markers and the air under them +const RAMP_BLOCK: f32 = 40.0; + +/// Slices the ramp is drawn in (colors blend between them) +const RAMP_SLICES: usize = 64; + +/// Width of a color row's swatch and its height +const SWATCH_WIDTH: f32 = 44.0; +const SWATCH_HEIGHT: f32 = 18.0; + +/// From the controls column to the eyedropper's centre and to the position track +const EYEDROPPER_X: f32 = 56.0; +const STOP_TRACK_X: f32 = 72.0; + +impl PropertySheet<'_> { + /// The ramp as `at` (linear colors along 0..1) draws it, with a marker under it for each of `colors` at its place in `positions`; a marker drags along it + pub(crate) fn gradient_ramp(&mut self, colors: &[[f32; 3]], positions: &[f32], at: &dyn Fn(f32) -> [f32; 3]) -> Option { + let block = self.take(RAMP_BLOCK); + let (x0, x1) = (self.left + RAMP_INSET, self.right - RAMP_INSET); + let ramp = Rect::from_min_max(pos2(x0, block.top()), pos2(x1, block.top() + RAMP_HEIGHT)); + let tokens = self.tokens; + let mut mesh = Mesh::default(); + for slice in 0..=RAMP_SLICES { + let share = slice as f32 / RAMP_SLICES as f32; + let x = x0 + (x1 - x0) * share; + let color = shown_color(at(share)); + mesh.colored_vertex(pos2(x, ramp.top()), color); + mesh.colored_vertex(pos2(x, ramp.bottom()), color); + if slice > 0 { + let base = (slice as u32) * 2; + mesh.add_triangle(base - 2, base - 1, base); + mesh.add_triangle(base - 1, base, base + 1); + } + } + let painter = self.ui.painter().clone(); + painter.add(Shape::mesh(mesh)); + painter.rect_stroke(ramp, CornerRadius::ZERO, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + + let mut drag = None; + for (index, color) in colors.iter().enumerate() { + let position = positions.get(index).copied().unwrap_or(0.0).clamp(0.0, 1.0); + let x = x0 + (x1 - x0) * position; + let top = ramp.bottom() + MARKER_AIR; + let hit = Rect::from_min_max(pos2(x - MARKER_HALF - MARKER_HIT_MARGIN, top), pos2(x + MARKER_HALF + MARKER_HIT_MARGIN, top + MARKER_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::drag()); + response.widget_info(|| WidgetInfo::slider(true, f64::from(position), crate::i18n::trf("Color {number}", &[("number", &(index + 1))]))); + let moved_to = response + .interact_pointer_pos() + .filter(|_| response.dragged()) + .map(|pointer| ((pointer.x - x0) / (x1 - x0).max(1.0)).clamp(0.0, 1.0)) + .filter(|picked| *picked != position); + if let Some(merge) = crate::widgets::press_edit(self.ui, response.id, moved_to.is_some()) + && let Some(moved_to) = moved_to + { + drag = Some(MarkerDrag { index, position: moved_to, merge }); + } + let outline = if response.hovered() || response.dragged() { tokens.accent } else { tokens.text_dim }; + let points = vec![ + pos2(x, top), + pos2(x + MARKER_HALF, top + MARKER_SHOULDER), + pos2(x + MARKER_HALF, top + MARKER_HEIGHT), + pos2(x - MARKER_HALF, top + MARKER_HEIGHT), + pos2(x - MARKER_HALF, top + MARKER_SHOULDER), + ]; + painter.add(Shape::convex_polygon(points, shown_color(*color), Stroke::new(1.0, outline))); + } + self.drawn(ramp.bottom() + MARKER_AIR + MARKER_HEIGHT); + drag + } + + /// Color N: its swatch (a click opens the picker) and eyedropper, then its place on the ramp; returns the pick and the place's edit + pub(crate) fn color_stop( + &mut self, + label: &str, + linear: [f32; 3], + position: &mut f32, + eyedropping: Option, + swatches: &[[f32; 3]], + ) -> (ColorPick, Option) { + let (control, center_y) = self.row(label); + let swatch = Rect::from_min_size(pos2(control.left(), center_y - SWATCH_HEIGHT / 2.0), vec2(SWATCH_WIDTH, SWATCH_HEIGHT)); + let pick = self.color_bar_at(swatch, control.left() + EYEDROPPER_X, label, linear, eyedropping, swatches); + + let id = self.next_id(); + let range: RangeInclusive = 0.0..=1.0; + let track = Track { start: control.left() + STOP_TRACK_X + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dragged = self.track(id, label, &track, position, &range); + let typed = self.value_field(id, label, center_y, *position, &range, 2, ""); + (pick, Self::apply_typed(position, typed, dragged)) + } +} diff --git a/crates/ui-egui/tests/it/filter_card.rs b/crates/ui-egui/tests/it/filter_card.rs new file mode 100644 index 00000000..6c78e409 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_card.rs @@ -0,0 +1,105 @@ +//! The Filter effect card in Properties: channel pills, Intensity's Divider chip, the card holding the parameters with its ⟲ beside × and Attributes as its last row + +use crate::filter_support::{WINDOW_HEIGHT, app_with, click_at, filter_of}; +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{Channel, Filter, SourceWarp}; + +#[test] +fn a_pill_switches_its_channel_and_the_chip_picks_the_divider() { + let (mut harness, effect) = app_with("warp", "content", WINDOW_HEIGHT); + let rough = harness.get_by_role_and_label(Role::CheckBox, "Rough").rect(); + + click_at(&mut harness, rough.center()); + + assert!(harness.state().session.doc.project.effect(effect).unwrap().1.off_channels.contains(&Channel::Roughness)); + + let chip = harness.get_by_role_and_label(Role::ComboBox, "÷10").rect(); + click_at(&mut harness, chip.center()); + assert!(egui::Popup::is_any_open(&harness.ctx), "the chip opens its list"); + + let hundred = harness.get_by_role_and_label(Role::ListBoxOption, "÷100").rect(); + click_at(&mut harness, hundred.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::SourceWarp(SourceWarp { divider: 100, .. })), "{:?}", filter_of(&harness, effect)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "picking closes the list"); +} + +#[test] +fn restore_defaults_and_clear_on_the_card() { + let (mut harness, effect) = app_with("blur", "content", WINDOW_HEIGHT); + let defaults = filter_of(&harness, effect); + + let restore = harness.get_by_role_and_label(Role::Button, "Restore defaults"); + assert!(restore.accesskit_node().is_disabled(), "inert at the defaults"); + let restore = restore.rect(); + let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect(); + assert!((restore.center().y - clear.center().y).abs() < 0.5 && restore.right() < clear.left(), "⟲ beside × on the card"); + + harness.state_mut().run("effect.set", json!({"effect": effect.0, "radius": 40.0})); + harness.run_steps(3); + let restore = harness.get_by_role_and_label(Role::Button, "Restore defaults").rect(); + click_at(&mut harness, restore.center()); + + assert_eq!(filter_of(&harness, effect), defaults); + + let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect(); + click_at(&mut harness, clear.center()); + + assert_eq!(filter_of(&harness, effect), Filter::Empty); + assert!(harness.query_by_label("Attributes").is_none(), "an empty filter has no settings"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Filter").is_some(), "the card reads Filter over None"); +} + +/// How far a card reaches past its rows on each side (the panel style's card bleed) +const CARD_BLEED: f32 = 6.0; + +/// The filter's card holds its rows: no Parameters band, every row and the Attributes row inside the card's edges, Attributes last +#[test] +fn the_filter_card_holds_its_parameters() { + let (harness, _) = app_with("slopeBlur", "content", WINDOW_HEIGHT); + assert!(harness.query_by_label("Parameters").is_none(), "no Parameters band"); + + let card = harness.get_by_role_and_label(Role::ComboBox, "Blur Slope").rect(); + let attributes = harness.get_by_role_and_label(Role::Button, "Attributes").rect(); + let sub_group = harness.get_by_role_and_label(Role::Button, "Source Parameters").rect(); + + // A row inside the card keeps the card's bleed on both sides; a band would span the panel + assert_eq!(attributes.left(), card.left() + CARD_BLEED, "{attributes:?} {card:?}"); + assert_eq!(sub_group.left(), attributes.left(), "a sub-group is a caption in the card, not a card of its own"); + for slider in harness.query_all_by_role(Role::Slider) { + assert!(slider.rect().bottom() <= attributes.top(), "Attributes is the card's last row: {:?}", slider.rect()); + } +} + +/// Air between the bottom of slider `last` and the top of the Attributes row under it, with library filter `filter` shown +fn air_under(filter: &str, last: &str) -> f32 { + let (harness, _) = app_with(filter, "content", WINDOW_HEIGHT); + let slider = harness.get_by_role_and_label(Role::Slider, last).rect(); + harness.get_by_role_and_label(Role::Button, "Attributes").rect().top() - slider.bottom() +} + +#[test] +fn a_generic_filter_ends_its_parameters_like_a_dedicated_one() { + // Sharpen's rows come from the library's parameters, Mask Outline's from its own rows; both end on a slider + assert_eq!(air_under("sharpen", "Sharpen Intensity"), air_under("maskOutline", "Curve Shape")); +} + +#[test] +fn replace_colors_two_colors_are_colour_bars_with_their_eyedroppers() { + let (mut harness, effect) = app_with("replaceColor", "content", WINDOW_HEIGHT); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Pick color").count(), 2, "an eyedropper beside each color"); + + let bar = harness.get_by_role_and_label(Role::Button, "Replacement color").rect(); + click_at(&mut harness, bar.center()); + let hex = harness.get_by_role_and_label(Role::TextInput, "Hex color").rect(); + click_at(&mut harness, hex.center()); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text("FF0000".into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + let Filter::ReplaceColor { to, .. } = filter_of(&harness, effect) else { panic!("a Replace Color filter") }; + assert_eq!(to, [1.0, 0.0, 0.0], "the bar's picker sets the replacement color"); +} diff --git a/crates/ui-egui/tests/it/filter_gradient.rs b/crates/ui-egui/tests/it/filter_gradient.rs new file mode 100644 index 00000000..9a485c56 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_gradient.rs @@ -0,0 +1,163 @@ +//! The gradient filters in Properties: Gradient Map's rows (the ramp's markers, Color Quantity, Input Transformation, the color rows), Gradient Curve's +//! Preset list, Invert and Balance, and Gradient Dynamic's orientation and Gradient Input Position + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, drag_through, filter_of, lowest, topmost, undo, undo_depth}; +use egui::accesskit::Role; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{CurvePreset, Filter, GrayscaleMode}; +use texturecraft_engine::filter_lib::GRADIENT_QUANTITY_MIN; + +/// Dragging Color 2's marker along the ramp moves its place, and one undo puts it back +#[test] +fn a_gradient_marker_drags_its_color_along_the_ramp() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + + // Color 2's row has a place track named Color 2 too: the ramp's marker is the topmost + let marker = topmost(&harness, Role::Slider, "Color 2"); + drag(&mut harness, marker.center(), marker.center() + egui::vec2(60.0, 0.0)); + + let Filter::GradientMap { positions, .. } = filter_of(&harness, effect) else { panic!() }; + let moved = positions.get(1).copied().unwrap(); + assert!(moved > 0.6, "dragged right: {positions:?}"); + + undo(&mut harness); + + let Filter::GradientMap { positions, .. } = filter_of(&harness, effect) else { panic!() }; + assert_eq!(positions.get(1), Some(&0.5), "one undo step for the drag"); +} + +/// Color Quantity at its right end shows ten color rows +#[test] +fn color_quantity_adds_color_rows() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + assert!(harness.query_by_label("Color 4").is_none()); + + let track = harness.get_by_role_and_label(Role::Slider, "Color Quantity").rect(); + click_at(&mut harness, along(track, 1.0)); + + assert_eq!(filter_of(&harness, effect).ramp_colors().len(), 10); + assert!(harness.query_all_by_label("Color 10").next().is_some(), "the tenth color has its row"); +} + +/// egui's click distance (`InputOptions::max_click_dist`): a press whose pointer travels further is a drag +const DRAG_THRESHOLD: f32 = 6.0; + +/// A Color Quantity drag whose first change rounds to the count it had starts its own undo step: undo leaves the edit before it alone +#[test] +fn a_color_quantity_drag_is_its_own_undo_step() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + let linear = harness.get_by_role_and_label(Role::CheckBox, "Blend Color in Linear").rect(); + click_at(&mut harness, linear.center()); + assert!(matches!(filter_of(&harness, effect), Filter::GradientMap { linear: false, .. })); + let depth = undo_depth(&harness); + + // From 2.6 colors to 3.2 (both round to the 3 it has), then to 4.2 + let track = harness.get_by_role_and_label(Role::Slider, "Color Quantity").rect(); + let (least, most) = (f32::from(GRADIENT_QUANTITY_MIN), f32::from(Filter::MAX_GRADIENT_COLORS)); + let at = |colors: f32| along(track, (colors - least) / (most - least)); + assert!(at(3.2).x - at(2.6).x > DRAG_THRESHOLD, "the first move already drags: {track:?}"); + + drag_through(&mut harness, at(2.6), &[at(3.2), at(4.2)]); + + assert_eq!(filter_of(&harness, effect).ramp_colors().len(), 4); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + let filter = filter_of(&harness, effect); + assert_eq!(filter.ramp_colors().len(), 3, "the drag undone"); + assert!(matches!(filter, Filter::GradientMap { linear: false, .. }), "Blend Color in Linear stays off: {filter:?}"); +} + +/// Input Transformation's Grayscale Mode list, Blur Intensity and Invert, Display Gradient (Debug), Blend Color in Linear and a color row's place track each set their own setting +#[test] +fn gradient_map_rows_set_their_own_setting() { + let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); + + let list = harness.get_by_role_and_label(Role::ComboBox, "Average").rect(); + click_at(&mut harness, list.center()); + let max = harness.get_by_label("Max").rect(); + click_at(&mut harness, max.center()); + let blur = harness.get_by_role_and_label(Role::Slider, "Blur Intensity").rect(); + click_at(&mut harness, along(blur, 0.5)); + for toggle in ["Invert", "Display Gradient (Debug)", "Blend Color in Linear"] { + let rect = harness.get_by_role_and_label(Role::CheckBox, toggle).rect(); + click_at(&mut harness, rect.center()); + } + + // Color 2's row is the lower of the two Color 2 tracks (the ramp's marker is the upper) + let row = lowest(&harness, Role::Slider, "Color 2"); + click_at(&mut harness, along(row, 1.0)); + + let Filter::GradientMap { input, debug, linear, positions, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert_eq!((input.mode, input.invert, debug, linear), (GrayscaleMode::Max, true, true, false)); + assert!((input.blur - 8.0).abs() < 0.05, "the middle of 0..16: {}", input.blur); + assert_eq!(positions.get(1), Some(&1.0), "Color 2 moved to the end: {positions:?}"); + assert_eq!((input.balance, input.contrast), (0.5, 0.0), "the others stay"); +} + +/// Gradient Curve's Preset list picks a curve +#[test] +fn gradient_curve_preset_list_picks_a_curve() { + let (mut harness, effect) = app_with("gradientCurve", "content", WINDOW_HEIGHT); + let list = harness.get_by_role_and_label(Role::ComboBox, "Round").rect(); + click_at(&mut harness, list.center()); + let bump = harness.get_by_label("Bump").rect(); + + click_at(&mut harness, bump.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::GradientCurve { preset: CurvePreset::Bump, .. }), "{:?}", filter_of(&harness, effect)); +} + +/// Gradient Curve's Invert and Balance set their own setting +#[test] +fn gradient_curve_invert_and_balance() { + let (mut harness, effect) = app_with("gradientCurve", "content", WINDOW_HEIGHT); + + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + click_at(&mut harness, invert.center()); + let balance = harness.get_by_role_and_label(Role::Slider, "Balance").rect(); + click_at(&mut harness, along(balance, 1.0)); + + let Filter::GradientCurve { invert, balance, contrast, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(invert && balance > 0.99 && contrast == 0.0, "{invert} {balance} {contrast}"); +} + +/// Gradient Dynamic's Gradient Input Position follows its track +#[test] +fn gradient_dynamic_input_position_follows_its_track() { + let (mut harness, effect) = app_with("gradientDynamic", "content", WINDOW_HEIGHT); + let position = harness.get_by_role_and_label(Role::Slider, "Gradient Input Position").rect(); + + click_at(&mut harness, along(position, 0.5)); + + assert!( + matches!(filter_of(&harness, effect), Filter::GradientDynamic { position, .. } if (position - 0.5).abs() < 0.01), + "{:?}", + filter_of(&harness, effect) + ); +} + +/// Gradient Dynamic's orientation turns vertical: a boxed switch at the panel's width, Vertical one click away +#[test] +fn gradient_dynamic_orientation_turns_vertical() { + let (mut harness, effect) = app_with("gradientDynamic", "content", WINDOW_HEIGHT); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Horizontal").is_none(), "both choices fit side by side"); + + let vertical = harness.get_by_label("Vertical").rect(); + click_at(&mut harness, vertical.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::GradientDynamic { vertical: true, .. }), "{:?}", filter_of(&harness, effect)); +} + +#[test] +fn gradient_dynamic_source_card_opens_the_color_picker() { + let (mut harness, _) = app_with("gradientDynamic", "content", WINDOW_HEIGHT); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Gradient Source").is_none(), "no picker yet"); + + // Through the pointer, on the card's name: the card's whole row picks its source + let card = harness.get_by_role_and_label(Role::ComboBox, "Gradient Source").rect(); + click_at(&mut harness, card.center()); + harness.run_steps(4); + + assert!(harness.query_by_role_and_label(Role::TitleBar, "Gradient Source").is_some(), "the card opens the colour picker of its bar"); +} diff --git a/crates/ui-egui/tests/it/filter_inputs.rs b/crates/ui-egui/tests/it/filter_inputs.rs new file mode 100644 index 00000000..b3ff2d4f --- /dev/null +++ b/crates/ui-egui/tests/it/filter_inputs.rs @@ -0,0 +1,114 @@ +//! Filter image inputs and Attributes in Properties: Bevel Smooth's Distance Map card after the filter's, Warp's Custom Noise slot under its Source Mode, the read-only Attributes row ending the filter card + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{LayerId, ProceduralKind, Source}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, lowest, pick, topmost}; + +/// The source effect `effect` holds in its input `id` +fn input(harness: &Harness<'_, TextureCraftApp>, effect: LayerId, id: &str) -> Option { + harness.state().session.doc.project.effect(effect).unwrap().1.inputs.get(id).cloned() +} + +/// A click on the control of `role` named `label` (the lowest, where a list above shows the same name) +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + let at = lowest(harness, role, label).center(); + click_at(harness, at); +} + +/// The Distance Map slot picks a pattern from the source picker, × puts it back to white, its ramp sets a gray +#[test] +fn the_distance_map_slot_picks_its_source() { + let (mut harness, effect) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_label("Image inputs").is_none(), "an input every mode reads is a card of its own, no band"); + assert!(lowest(&harness, Role::ComboBox, "Distance Map").top() > topmost(&harness, Role::Button, "Attributes").bottom(), "after the filter card"); + + click(&mut harness, Role::ComboBox, "Distance Map"); + assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "the slot opens the source picker"); + click(&mut harness, Role::ListBoxOption, "Clouds"); + + let Some(Source::Procedural { pattern, low, high, .. }) = input(&harness, effect, "distanceMap") else { panic!("a procedural") }; + assert_eq!((pattern.kind, low, high), (ProceduralKind::Clouds, [0.0; 3], [1.0; 3])); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); + + // The filter card has its own ×: the slot's is the lower one + click(&mut harness, Role::Button, "Clear"); + assert_eq!(input(&harness, effect, "distanceMap"), None, "back to its default white"); + + let ramp = harness.get_by_role_and_label(Role::Slider, "Distance Map").rect(); + click_at(&mut harness, along(ramp, 0.0)); + + let Some(Source::Uniform([gray, ..])) = input(&harness, effect, "distanceMap") else { panic!("a gray") }; + assert!(gray < 0.05, "{gray}"); +} + +/// Warp shows its Custom Noise slot right under Source Mode only in that mode, above the source's sliders; a pattern picked there shows its Scale and Contrast +#[test] +fn the_custom_noise_slot_follows_the_source_mode() { + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Noise").is_none()); + + pick(&mut harness, "Default Noise", "Custom Noise"); + + let slot = lowest(&harness, Role::ComboBox, "Custom Noise"); + let blur = harness.get_by_role_and_label(Role::Slider, "Source Blur").rect(); + assert!(slot.bottom() <= blur.top(), "the slot sits above Source Blur"); + + click_at(&mut harness, slot.center()); + click(&mut harness, Role::ListBoxOption, "Clouds"); + + let Some(Source::Procedural { pattern, .. }) = input(&harness, effect, "customNoise") else { panic!("a procedural custom noise") }; + assert!(harness.query_by_label("Image inputs").is_none(), "a mode's input is not under Image inputs"); + + // The picked pattern's Scale and Contrast show inside the mode's card, like every slot's, and set the pattern + let scale = harness.get_by_role_and_label(Role::Slider, "Scale").rect(); + assert!(scale.top() >= slot.bottom() && harness.query_by_role_and_label(Role::Slider, "Contrast").is_some()); + + click_at(&mut harness, along(scale, 0.0)); + + let Some(Source::Procedural { pattern: scaled, .. }) = input(&harness, effect, "customNoise") else { panic!("still a procedural") }; + assert!(scaled.scale < pattern.scale, "{} -> {}", pattern.scale, scaled.scale); +} + +/// Attributes is closed at first; a click on the filter card's last row shows the filter's read-only rows in the card, above the input cards; another hides them +#[test] +fn the_attributes_row_opens_on_a_click() { + let (mut harness, _) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + let category = "Category: Filter"; + assert!(harness.query_by_label(category).is_none(), "closed by default"); + let band = topmost(&harness, Role::Button, "Attributes"); + assert!(band.bottom() < lowest(&harness, Role::ComboBox, "Distance Map").top(), "above the input's card"); + + click_at(&mut harness, band.center()); + + assert!(harness.query_by_label(category).is_some()); + assert!(harness.query_by_label("Description: Draws a smooth ramp from the edge of the shapes.").is_some()); + assert!(harness.query_by_label("Tags: bevel, edge, ramp").is_some()); + assert!(harness.query_by_label("Size: 256 × 256").is_some(), "the texture set's size"); + assert!(harness.get_by_label(category).rect().top() > band.bottom(), "the rows hang under the row"); + assert!(harness.get_by_label(category).rect().bottom() < lowest(&harness, Role::ComboBox, "Distance Map").top(), "inside the filter card"); + + click_at(&mut harness, band.center()); + + assert!(harness.query_by_label(category).is_none()); +} + +/// An open section that makes the panel scroll keeps its rows in place from frame to frame (the scroll bar refits no row) +#[test] +fn the_sheet_keeps_its_layout_when_the_scroll_bar_comes_in() { + let (mut harness, _) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + let attributes = topmost(&harness, Role::Button, "Attributes").center(); + click_at(&mut harness, attributes); + let layout = |harness: &Harness<'_, TextureCraftApp>| -> Vec { + harness.query_all_by_role(Role::ComboBox).chain(harness.query_all_by_role(Role::Button)).map(|node| node.rect()).collect() + }; + let first = layout(&harness); + + for frame in 0..3 { + harness.run_steps(1); + assert_eq!(layout(&harness), first, "frame {frame}"); + } +} diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index dfb895a8..2dcee134 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -4,33 +4,21 @@ 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::core::{Filter, LayerId}; use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; +use crate::filter_support::{WINDOW_HEIGHT, WINDOW_WIDTH, app_with, click_at, filter_of}; + /// 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() + app_with("invert", "content", WINDOW_HEIGHT) } /// 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); + let at = harness.get_by_role_and_label(Role::ComboBox, "Invert").rect().center(); + click_at(harness, at); assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); } @@ -44,10 +32,10 @@ fn picking_from_the_slot_swaps_the_filter() { 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); + let at = harness.get_by_label("Sharpen").rect().center(); + click_at(&mut harness, at); - assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect)); + assert!(matches!(filter_of(&harness, effect), Filter::Sharpen { .. }), "{:?}", filter_of(&harness, effect)); assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); } @@ -63,16 +51,18 @@ fn escape_closes_the_picker_without_changes() { harness.run_steps(3); assert!(!egui::Popup::is_any_open(&harness.ctx)); - assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); + assert!(matches!(filter_of(&harness, effect), Filter::Invert)); } /// Opens the wand's Add effect menu and clicks Filter fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_role_and_label(Role::Button, "Add effect").click(); - harness.run_steps(3); + let at = harness.get_by_role_and_label(Role::Button, "Add effect").rect().center(); + click_at(harness, at); harness.get_by_role_and_label(Role::Button, "Filter").click(); - harness.run_steps(3); + let at = harness.get_by_role_and_label(Role::Button, "Filter").rect().center(); + click_at(harness, at); } #[test] @@ -81,20 +71,20 @@ fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { 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!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Filter").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)); + let at = harness.get_by_label("Sharpen").rect().center(); + click_at(&mut harness, at); + assert!(matches!(filter_of(&harness, added), Filter::Sharpen { .. }), "{:?}", filter_of(&harness, added)); } #[test] -fn escape_after_add_filter_keeps_the_neutral_filter() { +fn escape_after_add_filter_keeps_the_empty_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"); @@ -104,16 +94,17 @@ fn escape_after_add_filter_keeps_the_neutral_filter() { 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)); + assert!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&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"); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the empty 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); @@ -123,9 +114,10 @@ fn add_filter_on_a_mask_adds_it_to_the_mask() { 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!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&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"); + assert!(harness.query_by_label("Normal Invert").is_none(), "the picker leaves out content-only filters"); + assert!(harness.query_by_label("Grayscale Conversion").is_some(), "masks take Grayscale Conversion"); } #[test] @@ -137,7 +129,7 @@ fn add_filter_reopens_closed_properties_to_show_its_picker() { add_filter_from_the_wand(&mut harness); - assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Add filter reveals Properties"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Filter").is_some(), "Add filter reveals Properties"); assert!(harness.query_by_label("Sharpen").is_some(), "the picker opens immediately"); } @@ -158,10 +150,13 @@ fn keyboard_opens_the_slot_and_outside_click_closes_it() { } harness.run_steps(3); assert!(!egui::Popup::is_any_open(&harness.ctx)); - assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); + assert!(matches!(filter_of(&harness, effect), Filter::Invert)); } } +/// The snapshots' window height: a usual desktop window, the picker opening over the views +const SNAPSHOT_HEIGHT: f32 = 960.0; + #[test] #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] fn filter_picker_snapshots_and_frame_timings() { @@ -170,7 +165,7 @@ fn filter_picker_snapshots_and_frame_timings() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|cc| { + let mut harness = Harness::builder().with_size(egui::vec2(WINDOW_WIDTH, SNAPSHOT_HEIGHT)).wgpu().build_eframe(|cc| { eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info()); TextureCraftApp::new(cc, session) }); @@ -193,7 +188,7 @@ fn filter_picker_snapshots_and_frame_timings() { harness.event(egui::Event::Text("sharp".into())); harness.run_steps(3); harness.render().unwrap().save(output.join("filter-picker-search.png")).unwrap(); - harness.get_by_label("Sharpen").click(); - harness.run_steps(3); + let at = harness.get_by_label("Sharpen").rect().center(); + click_at(&mut harness, at); harness.render().unwrap().save(output.join("filter-picker-selected.png")).unwrap(); } diff --git a/crates/ui-egui/tests/it/filter_support.rs b/crates/ui-egui/tests/it/filter_support.rs index 912e2017..cd8a750e 100644 --- a/crates/ui-egui/tests/it/filter_support.rs +++ b/crates/ui-egui/tests/it/filter_support.rs @@ -1,8 +1,48 @@ //! Helpers the filter panel tests share +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 test window's width: the dock at its usual size beside the views +pub(crate) const WINDOW_WIDTH: f32 = 1600.0; + +/// A window tall enough for a filter's rows and its Attributes in the docked Properties panel +pub(crate) const WINDOW_HEIGHT: f32 = 1400.0; + +/// A window tall enough for the filters with many cards (Baked Lighting Stylized, Color Match) to show every row unscrolled +pub(crate) const TALL_WINDOW_HEIGHT: f32 = 2400.0; + +/// The app `height` tall with library filter `filter` on a fill layer's `target` ("content" or "mask", a white mask added), selected so Properties shows it +pub(crate) fn app_with(filter: &str, target: &str, height: f32) -> (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(); + if target == "mask" { + execute(&mut session, "mask.add.white", &json!({"layer": layer["layer"]})).unwrap(); + } + let effect = execute(&mut session, "effect.add.filter", &json!({"target": target, "filter": filter})).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(WINDOW_WIDTH, height)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + (harness, effect) +} + +/// The filter effect `effect` holds now +pub(crate) fn filter_of(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Filter { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Filter(filter) => filter.clone(), + other => panic!("not a filter: {other:?}"), + } +} + /// A real pointer click at `pos`: move there, press, one frame, release, then frames for the edit to show pub(crate) fn click_at(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Pos2) { let modifiers = egui::Modifiers::NONE; @@ -13,6 +53,18 @@ pub(crate) fn click_at(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Po harness.run_steps(3); } +/// Pick `option` of a setting shown as a boxed switch where its words fit, or as a dropdown showing `current` where they don't +pub(crate) fn pick(harness: &mut Harness<'_, TextureCraftApp>, current: &str, option: &str) { + if let Some(segment) = harness.query_by_role_and_label(Role::RadioButton, option).map(|node| node.rect()) { + click_at(harness, segment.center()); + } else { + let list = harness.get_by_role_and_label(Role::ComboBox, current).rect(); + click_at(harness, list.center()); + let choice = harness.get_by_label(option).rect(); + click_at(harness, choice.center()); + } +} + /// A press at `from`, a drag to `to` in steps and a release, as the pointer does it pub(crate) fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) { let steps: Vec = (1..=DRAG_STEPS).map(|step| from + (to - from) * (step as f32 / DRAG_STEPS as f32)).collect(); @@ -42,6 +94,16 @@ pub(crate) fn along(track: egui::Rect, share: f32) -> egui::Pos2 { egui::pos2(track.left() + SLIDER_TRACK_INSET + (track.width() - 2.0 * SLIDER_TRACK_INSET) * share, track.center().y) } +/// The rect of the topmost of the widgets with `role` and `label` (a name a later row repeats) +pub(crate) fn topmost(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> egui::Rect { + harness.get_all_by_role_and_label(role, label).map(|node| node.rect()).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap() +} + +/// The rect of the lowest of the widgets with `role` and `label` +pub(crate) fn lowest(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> egui::Rect { + harness.get_all_by_role_and_label(role, label).map(|node| node.rect()).max_by(|a, b| a.top().total_cmp(&b.top())).unwrap() +} + /// Moves a drag makes on its way, one frame each, so a press makes several changes const DRAG_STEPS: usize = 4; @@ -49,3 +111,9 @@ const DRAG_STEPS: usize = 4; pub(crate) fn undo_depth(harness: &Harness<'_, TextureCraftApp>) -> usize { harness.state().session.history_labels().len() } + +/// Undoes the last step, then frames for the panel to show it +pub(crate) fn undo(harness: &mut Harness<'_, TextureCraftApp>) { + harness.state_mut().session.undo().unwrap(); + harness.run_steps(2); +} From f49ff387f13d2824873a538201be7180bfdbcecb Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:49 +0000 Subject: [PATCH 038/153] Effects, masks and folders: engine evaluation and the remaining tests --- crates/compose/src/below.rs | 21 +- crates/compose/src/effect_histogram.rs | 95 +++ crates/compose/src/eval.rs | 686 ++++++++++++++---- crates/compose/src/lib.rs | 9 +- crates/compose/src/mask_gray.rs | 41 ++ crates/compose/src/solo.rs | 9 +- crates/compose/src/store.rs | 9 + crates/compose/src/thumb.rs | 2 +- crates/compose/tests/cache_and_instances.rs | 66 +- crates/core/src/color_selection.rs | 132 ++++ crates/core/src/compare_source.rs | 60 ++ crates/core/src/contents_offset.rs | 116 +++ crates/core/src/layer.rs | 272 ++++++- crates/core/src/lib.rs | 8 + crates/core/src/project.rs | 89 ++- crates/core/src/selection_background.rs | 58 ++ crates/engine/src/add_mask_cmds.rs | 65 ++ crates/engine/src/color_selection_cmds.rs | 78 +- crates/engine/src/effect_blending_cmds.rs | 203 ++++++ crates/engine/src/fill_material_cmds.rs | 5 + crates/engine/src/fill_reset_cmds.rs | 1 + crates/engine/src/id_mask_view.rs | 43 ++ crates/engine/src/inspect.rs | 47 +- crates/engine/src/layer_cmds.rs | 138 +++- crates/engine/src/layer_cmds/fill_target.rs | 9 - crates/engine/src/layer_selection.rs | 2 +- crates/engine/src/lib.rs | 5 + crates/engine/src/mask_owner.rs | 8 + crates/engine/src/material_lib.rs | 3 +- crates/engine/src/materials.rs | 1 + crates/engine/src/painting.rs | 29 +- crates/engine/src/path_tool.rs | 60 +- crates/engine/src/resource_cmds.rs | 3 +- crates/engine/src/session.rs | 63 +- crates/engine/src/tool_cmds.rs | 47 +- crates/engine/src/warp_cmds.rs | 1 + crates/engine/tests/it/add_mask_items.rs | 109 +++ crates/engine/tests/it/color_selection.rs | 108 ++- crates/engine/tests/it/compare_mask.rs | 130 ++++ crates/engine/tests/it/effect_blending.rs | 142 ++++ crates/engine/tests/it/fill_projections.rs | 2 +- crates/engine/tests/it/main.rs | 7 + crates/engine/tests/it/mask_paint_image.rs | 119 +++ crates/engine/tests/it/painter_gaps.rs | 19 +- crates/engine/tests/it/resources_used.rs | 74 ++ crates/paint/src/commit.rs | 153 ++-- crates/ui-egui/src/dock.rs | 361 +++++---- crates/ui-egui/src/exact_entry_open.rs | 5 + crates/ui-egui/src/fill_material_panel.rs | 24 +- crates/ui-egui/src/fill_pictures.rs | 1 + crates/ui-egui/src/filter_slot.rs | 16 +- crates/ui-egui/src/gpu.rs | 77 +- crates/ui-egui/src/lib.rs | 13 + crates/ui-egui/src/move_on_model.rs | 26 + crates/ui-egui/src/orb_environment.rs | 9 +- .../ui-egui/src/property_sheet/action_row.rs | 62 ++ .../src/property_sheet/action_row_response.rs | 9 + .../src/property_sheet/factor_slider.rs | 25 + crates/ui-egui/src/property_sheet/mod.rs | 16 + .../ui-egui/src/property_sheet/name_field.rs | 48 ++ crates/ui-egui/src/property_sheet/row.rs | 9 + crates/ui-egui/src/property_sheet/slider.rs | 5 + crates/ui-egui/src/property_sheet/slot.rs | 1 + .../ui-egui/src/property_sheet/source_card.rs | 67 ++ .../src/property_sheet/switch_control.rs | 6 + crates/ui-egui/src/property_sheet/tests.rs | 141 +++- crates/ui-egui/src/round_gizmo.rs | 46 ++ crates/ui-egui/src/slot_thumbnail.rs | 12 + crates/ui-egui/src/source_slot.rs | 9 + crates/ui-egui/src/theme.rs | 63 +- crates/ui-egui/src/thumbs.rs | 51 +- crates/ui-egui/src/viewport.rs | 42 +- crates/ui-egui/tests/it/anchor_point.rs | 103 +++ crates/ui-egui/tests/it/compare_mask_rows.rs | 85 +++ crates/ui-egui/tests/it/effect_rows.rs | 71 +- crates/ui-egui/tests/it/effect_sliders.rs | 26 +- crates/ui-egui/tests/it/empty_start.rs | 2 + crates/ui-egui/tests/it/fill_channel_image.rs | 20 +- crates/ui-egui/tests/it/filter_picker.rs | 2 +- .../ui-egui/tests/it/instance_properties.rs | 65 ++ crates/ui-egui/tests/it/layers_panel.rs | 8 +- crates/ui-egui/tests/it/levels_editor.rs | 126 +++- crates/ui-egui/tests/it/main.rs | 15 +- .../ui-egui/tests/it/mask_paint_grayscale.rs | 82 +++ crates/ui-egui/tests/it/popup_press_close.rs | 13 + crates/ui-egui/tests/it/source_picker.rs | 14 + .../ui-egui/tests/it/tile_generator_panel.rs | 35 +- crates/ui-egui/tests/ui_snapshots.rs | 550 ++++++++++++++ docs/control-protocol.md | 5 +- 89 files changed, 4928 insertions(+), 785 deletions(-) create mode 100644 crates/compose/src/effect_histogram.rs create mode 100644 crates/compose/src/mask_gray.rs create mode 100644 crates/core/src/color_selection.rs create mode 100644 crates/core/src/compare_source.rs create mode 100644 crates/core/src/contents_offset.rs create mode 100644 crates/core/src/selection_background.rs create mode 100644 crates/engine/src/add_mask_cmds.rs create mode 100644 crates/engine/src/effect_blending_cmds.rs create mode 100644 crates/engine/src/id_mask_view.rs delete mode 100644 crates/engine/src/layer_cmds/fill_target.rs create mode 100644 crates/engine/src/mask_owner.rs create mode 100644 crates/engine/tests/it/add_mask_items.rs create mode 100644 crates/engine/tests/it/compare_mask.rs create mode 100644 crates/engine/tests/it/effect_blending.rs create mode 100644 crates/engine/tests/it/mask_paint_image.rs create mode 100644 crates/engine/tests/it/resources_used.rs create mode 100644 crates/ui-egui/src/exact_entry_open.rs create mode 100644 crates/ui-egui/src/property_sheet/action_row.rs create mode 100644 crates/ui-egui/src/property_sheet/action_row_response.rs create mode 100644 crates/ui-egui/src/property_sheet/factor_slider.rs create mode 100644 crates/ui-egui/src/property_sheet/name_field.rs create mode 100644 crates/ui-egui/src/property_sheet/source_card.rs create mode 100644 crates/ui-egui/tests/it/anchor_point.rs create mode 100644 crates/ui-egui/tests/it/compare_mask_rows.rs create mode 100644 crates/ui-egui/tests/it/instance_properties.rs create mode 100644 crates/ui-egui/tests/it/mask_paint_grayscale.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 4a2187ed..993c4e9a 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -142,18 +142,21 @@ impl StackKey { let mut referenced_images = BTreeSet::new(); if !images.is_empty() { - let mut record_image_reference = |source: &Source| { - referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name)); + let mut record_image_name = |name: &str| { + if let Some((name, _)) = images.get_key_value(name) { + referenced_images.insert(name); + } }; for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) { if let LayerKind::Fill(fill) = &layer.kind { - fill.sources.values().for_each(&mut record_image_reference); + fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name); } for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { match &effect.kind { - EffectKind::Fill { source, .. } => record_image_reference(source), - EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference), - EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference), + EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), + EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } } @@ -182,9 +185,11 @@ impl StackKey { if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images { return None; } + if self.pixels.len() != other.pixels.len() { return None; } + let size = self.set.size(); let mut changed = BTreeSet::new(); for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { @@ -363,8 +368,8 @@ impl BelowCache { let project = inp.project; let set = project.texture_set(inp.ts).ok()?; - // Anchor readers depend on the stack below them - if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) { + // Anchor readers and compare masks reading layers depend on the stack below them + if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_stack)) { return None; } diff --git a/crates/compose/src/effect_histogram.rs b/crates/compose/src/effect_histogram.rs new file mode 100644 index 00000000..83f948d6 --- /dev/null +++ b/crates/compose/src/effect_histogram.rs @@ -0,0 +1,95 @@ +//! The distribution of the values entering an effect, as the levels editor draws it + +use texturecraft_core::lum; + +/// Bucket counts over 0..1 of the values entering an effect, pooled and per part of a colour +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EffectHistogram { + /// Every value, a colour's three components pooled + pub all: Vec, + /// Red, green and blue on their own; empty for a one-value channel or a mask + pub components: Vec>, + /// Each colour's luminance; a one-value channel's or a mask's values (the same as `all`) + pub luminance: Vec, +} + +impl EffectHistogram { + /// `bins` empty buckets (at least one), with per-component buckets when it counts colours + pub fn new(bins: usize, color: bool) -> EffectHistogram { + let bins = bins.max(1); + EffectHistogram { all: vec![0; bins], components: if color { vec![vec![0; bins]; 3] } else { Vec::new() }, luminance: vec![0; bins] } + } + + /// Counts one value of a one-value channel or a mask + pub fn add_value(&mut self, value: f32) { + bump(&mut self.all, value); + bump(&mut self.luminance, value); + } + + /// Counts one colour: each component pooled and on its own, and its luminance + pub fn add_color(&mut self, color: [f32; 3]) { + for (index, component) in color.into_iter().enumerate() { + bump(&mut self.all, component); + if let Some(counts) = self.components.get_mut(index) { + bump(counts, component); + } + } + bump(&mut self.luminance, lum(color)); + } + + /// Both histograms' counts together (they have the same buckets) + pub fn merged(mut self, other: &EffectHistogram) -> EffectHistogram { + add_counts(&mut self.all, &other.all); + for (counts, more) in self.components.iter_mut().zip(&other.components) { + add_counts(counts, more); + } + add_counts(&mut self.luminance, &other.luminance); + self + } +} + +/// One more count in the bucket of `value` (clamped to 0..1) +fn bump(counts: &mut [u32], value: f32) { + let bins = counts.len(); + let index = ((value.clamp(0.0, 1.0) * bins as f32) as usize).min(bins.saturating_sub(1)); + if let Some(count) = counts.get_mut(index) { + *count = count.saturating_add(1); + } +} + +fn add_counts(counts: &mut [u32], more: &[u32]) { + for (count, extra) in counts.iter_mut().zip(more) { + *count = count.saturating_add(*extra); + } +} + +#[cfg(test)] +mod tests { + use super::EffectHistogram; + + #[test] + fn a_colour_counts_each_component_pooled_and_alone_and_its_luminance() { + let mut histogram = EffectHistogram::new(4, true); + + histogram.add_color([1.0, 0.0, 0.3]); + let merged = histogram.clone().merged(&histogram); + + assert_eq!(histogram.all, vec![1, 1, 0, 1]); + assert_eq!(histogram.components, vec![vec![0, 0, 0, 1], vec![1, 0, 0, 0], vec![0, 1, 0, 0]]); + assert_eq!(histogram.luminance, vec![0, 1, 0, 0], "luminance 0.33 lands in the second bucket"); + assert_eq!(merged.all, vec![2, 2, 0, 2]); + assert_eq!(merged.components.first(), Some(&vec![0, 0, 0, 2])); + } + + #[test] + fn a_value_has_no_components() { + let mut histogram = EffectHistogram::new(2, false); + + histogram.add_value(f32::NAN); + histogram.add_value(0.9); + + assert_eq!(histogram.all, vec![1, 1]); + assert_eq!(histogram.luminance, histogram.all); + assert!(histogram.components.is_empty()); + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index eaf04ca2..52305968 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -22,10 +22,12 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; +use crate::effect_histogram::EffectHistogram; use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_place::FillPlace; use crate::held_fields::HeldFields; +use crate::mask_gray::MaskGray; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; @@ -104,8 +106,8 @@ pub struct StrokePreview { pub erase: bool, /// Values painted per channel (layer targets). pub values: BTreeMap, - /// Gray value painted into a mask. - pub mask_value: f32, + /// Gray painted into a mask + pub mask_gray: MaskGray, /// Projection tool: base color (and alpha) come from a screen-pinned image. pub stencil: Option, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). @@ -244,7 +246,8 @@ enum Content<'a> { struct EffectPlan<'a> { /// The effect id (an anchor point records under it). id: LayerId, - kind: &'a EffectKind, + /// The effect, a fill's with the Scale and Rotation of the folders around its layer laid on + kind: Cow<'a, EffectKind>, blend: BlendMode, opacity: f32, data: Option>, @@ -262,6 +265,8 @@ struct EffectPlan<'a> { struct MaskPlan<'a> { background: f32, effects: Vec>, + /// The layer's own content in the channels its compare effects read (planned only when one reads the stack) + layer: Option<(Content<'a>, Vec>)>, /// A neighbourhood filter (blur, sharpen) precomputed over the region: continue the stack /// after effect `.0` starting from the field's value. start: Option<(usize, &'a Field)>, @@ -322,14 +327,13 @@ enum Op { Slope { scale: f32, seed: u32 }, } -/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]) +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } /// Below this a coverage weight counts as no coverage at all. const MIN_COVERAGE_WEIGHT: f32 = 1e-6; - /// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. const FILTER_SIZE_RESOLUTION: f32 = 2048.0; /// The smallest radius a filter runs at, in texels. @@ -606,18 +610,33 @@ fn stroke_at(preview: Option<&[u16]>, o: usize) -> f32 { preview.and_then(|t| t.get(o)).map(|v| from_u16(*v)).unwrap_or(0.0) } -/// The full stack of tile (tx, ty) when `layer` reads anchor points (empty otherwise): evaluated -/// up to the layer, it records the anchors below it. -fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { - match inp.project.texture_set(inp.ts) { - Ok(set) if reads_anchor(inp.project, id) => plan(inp, &set.stack, channels, tx, ty, 0, fields), - _ => Vec::new(), +/// The full stack of tile (tx, ty) in `channels` and the channels the layer's mask compares, when the layer reads the stack below it (else empty) +fn anchor_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { + let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; + if !reads_stack(inp.project, id) { + return Vec::new(); } + + let compare_effects = layer_mask(inp.project, id).into_iter().flat_map(|mask| mask.effects.iter()); + let planned = compared_channels(compare_effects, channels.to_vec()); + plan(inp, &set.stack, &planned, tx, ty, 0, fields) } -/// Whether layer `id` (its own mask, or the content it draws) reads an anchor point. -pub(crate) fn reads_anchor(p: &Project, id: LayerId) -> bool { - p.layers.get(&id).is_some_and(Layer::reads_anchor) || p.content_layer(id).is_some_and(Layer::reads_anchor) +/// `channels` with every channel the Compare effects among `effects` compare added once +fn compared_channels<'e>(effects: impl IntoIterator, mut channels: Vec) -> Vec { + for effect in effects { + if let EffectKind::Compare { channel, .. } = effect.kind + && !channels.contains(&channel) + { + channels.push(channel); + } + } + channels +} + +/// Whether layer `id` (its own mask, or the content it draws) reads the stack below it: an anchor point, or a compare mask's layer sides +pub(crate) fn reads_stack(p: &Project, id: LayerId) -> bool { + p.layers.get(&id).is_some_and(Layer::reads_stack) || p.content_layer(id).is_some_and(Layer::reads_stack) } /// The mask layer `id` draws with: its own, or an instance source's. @@ -727,6 +746,11 @@ fn filter_region( (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { + let channel = match job { + Job::Mask(_) => None, + Job::Content(channel) => Some(channel), + }; + let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); @@ -756,7 +780,10 @@ fn filter_region( let mut generator_sizes = None; match job { Job::Mask(layer_mask) => { - let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() }; + // The layer's own filtered content, for a compare of it (this mask's field is not built yet) + let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), inputs.project.contents_around(id)) else { + return Vec::new(); + }; generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); mask_stack.effects.truncate(index); @@ -1054,27 +1081,44 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], til for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; + let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); - 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), filtered); + // A mask comparing the layer's own content reads it filtered, so its field comes after the content's + let compares_content = mask.is_some_and(|mask| mask.effects.iter().any(|effect| effect.visible && compares_this_layer(&effect.kind))); + if !compares_content { + insert_mask_field(inp, channels, &mut out, id, mask, tiles); } - if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { - continue; - } - - 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); + if !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some() { + 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); + } } } + + if compares_content { + insert_mask_field(inp, channels, &mut out, id, mask, tiles); + } } out } +/// Layer `id`'s filtered `mask` field put into `fields` (nothing without a mask or a field) +fn insert_mask_field(inp: &Inputs, channels: &[Channel], fields: &mut Fields, id: LayerId, mask: Option<&Mask>, tiles: &[(u32, u32)]) { + if let Some(mask) = mask + && let Some(filtered) = field(inp, channels, fields, id, Job::Mask(mask), tiles) + { + fields.insert(FieldKey::Mask(id), filtered); + } +} + +/// Whether a mask effect compares the layer's own content +fn compares_this_layer(kind: &EffectKind) -> bool { + matches!(kind, EffectKind::Compare { left, right, .. } if *left == CompareSource::ThisLayer || *right == CompareSource::ThisLayer) +} + /// 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 visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); @@ -1100,10 +1144,9 @@ struct Node<'a> { content: Content<'a>, chans: Vec>, mask: Option>, - /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an - /// anchor with visible effects above it) with its content cut after `k` visible effects. + /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an anchor with visible effects above it) with its content cut after `k` visible effects anchors: Vec<(LayerId, Option)>, - /// The node or one of its children records an anchor. + /// The node or one of its children records an anchor has_anchor: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). @@ -1113,6 +1156,14 @@ 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: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { +fn effect_plans<'a>( + inp: &Inputs<'a>, + effects: &'a [Effect], + tile_x: u32, + tile_y: u32, + channel: Option, + around: ContentsOffset, +) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -1133,9 +1184,9 @@ fn effect_plans<'a>(inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u }; EffectPlan { id: effect.id, - kind: &effect.kind, - blend: effect.blend, - opacity: effect.opacity, + kind: offset_effect(&effect.kind, around), + blend: blend.mode, + opacity: blend.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), curvature_sizes, @@ -1147,6 +1198,26 @@ fn effect_plans<'a>(inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u .collect() } +/// `kind` with the folders' Scale and Rotation `around` laid on its projection (borrowed where that changes nothing) +fn offset_effect(kind: &EffectKind, around: ContentsOffset) -> Cow<'_, EffectKind> { + match kind { + EffectKind::Fill { source, projection, sampling } if !around.is_none() => { + Cow::Owned(EffectKind::Fill { source: source.clone(), projection: around.apply(projection), sampling: *sampling }) + } + EffectKind::Material(fill) if !around.is_none() => Cow::Owned(EffectKind::Material(offset_fill(fill, around).into_owned())), + _ => Cow::Borrowed(kind), + } +} + +/// `fill` with the folders' Scale and Rotation `around` laid on its projection (borrowed where that changes nothing) +fn offset_fill(fill: &Fill, around: ContentsOffset) -> Cow<'_, Fill> { + if around.is_none() { + return Cow::Borrowed(fill); + } + + Cow::Owned(Fill { projection: around.apply(&fill.projection), ..fill.clone() }) +} + /// Whether the live stroke paints `target` in this composite (a stroke on a layer instanced in a /// set of another size does not show there). fn previews(inp: &Inputs, target: PaintTarget) -> bool { @@ -1172,33 +1243,59 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann } fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { +/// The plan of layer `id`'s `mask` for tile (tx, ty), its fills under the Scale and Rotation `around` of the folders holding the layer +fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>, around: ContentsOffset) -> Option> { if !mask.enabled { return None; } let background = if mask.background == MaskBackground::White { 1.0 } else { 0.0 }; - let mut effects = effect_plans(inp, &mask.effects, tx, ty, None); + let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, around); let filtered = fields.and_then(|fields| fields.get(&FieldKey::Mask(id))); for effect in &mut effects { effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(id, _)| *id == effect.id).map(|(_, field)| field)); } let start = filtered.and_then(|field| neighbourhood(&mask.effects, inp.gbuf.width).map(|(index, _, _)| (index, field))); - Some(MaskPlan { background, effects, start }) + let compared = compared_channels(mask.effects.iter().filter(|effect| effect.visible && effect.kind.reads_stack()), Vec::new()); + + // A folder's own content is its children: its compare sides read the stack below it + let layer = if compared.is_empty() { + None + } else { + inp.project.content_layer(id).and_then(|l| plan_content(inp, id, l, &compared, tx, ty, 0, fields, false, around)) + }; + Some(MaskPlan { background, effects, layer, start }) } -fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { +/// The plans of sibling layers `list` (under the Scale and Rotation of the folders holding them) +fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { + let around = list.first().map_or(ContentsOffset::NONE, |id| inp.project.contents_around(*id)); + plan_in(inp, list, channels, tx, ty, depth, fields, around) +} + +/// [`plan`] of sibling layers held by folders whose Scale and Rotation make `around` +#[allow(clippy::too_many_arguments)] +fn plan_in<'a>( + inp: &Inputs<'a>, + list: &[LayerId], + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + around: ContentsOffset, +) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, around)).collect() } -/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are -/// planned when `kids`. +/// The plan of layer `id` at `depth` (None where it draws nothing), its fills under the Scale and Rotation `around` of the folders holding it; a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( - inp: &EvaluationInputs<'a>, + inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, @@ -1206,6 +1303,7 @@ fn plan_node<'a>( depth: usize, fields: Option<&'a Fields>, kids: bool, + around: ContentsOffset, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; @@ -1215,38 +1313,11 @@ fn plan_node<'a>( return None; } - let paint = matches!(layer.kind, LayerKind::Paint); - let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); - let fx_start = if fx { neighbourhood(&layer.content_effects, inp.gbuf.width).map(|n| n.0) } else { None }; - let chans = channels - .iter() - .filter_map(|c| { - let b = layer.blend(*c)?; - if b.mode == BlendMode::Disable || b.opacity <= 0.0 { - return None; - } - - let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; - let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c)) } else { Vec::new() }; - let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c)))); - Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start }) - }) - .collect::>(); - let content = match &layer.kind { - LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, - LayerKind::Fill(f) => { - let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); - Content::Fill { fill: Box::new(Cow::Borrowed(f)), depth, covers_all } - } - LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), - - // `content_layer` already followed instance links - LayerKind::Instance { .. } => return None, - }; - let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields)); + let (content, chans) = plan_content(inp, id, layer, channels, tx, ty, depth, fields, kids, around)?; + let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields, around)); // Anchors in the mask record even where the layer draws nothing - let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Anchor))); + let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(*e.kind, EffectKind::Anchor))); // An empty paint layer still matters if its mask records an anchor if let Content::Paint { preview: false } = content @@ -1260,6 +1331,7 @@ fn plan_node<'a>( return None; } + let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() }; let has_anchor = !anchors.is_empty() || mask_anchor || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); @@ -1268,6 +1340,54 @@ fn plan_node<'a>( Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask, parts }) } +/// The content of `layer` (layer `id`'s own, or its instance source's; None for an unfollowed instance) and its plan per drawn channel of `channels`, its fills under the Scale and Rotation `around` of the folders holding `id`; a folder's children are planned when `kids` +#[allow(clippy::too_many_arguments)] +fn plan_content<'a>( + inp: &Inputs<'a>, + id: LayerId, + layer: &'a Layer, + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + kids: bool, + around: ContentsOffset, +) -> Option<(Content<'a>, Vec>)> { + let paint = matches!(layer.kind, LayerKind::Paint); + let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); + let fx_start = if fx { neighbourhood(&layer.content_effects, inp.gbuf.width).map(|n| n.0) } else { None }; + let chans = channels + .iter() + .filter_map(|c| { + let b = layer.blend(*c)?; + if b.mode == BlendMode::Disable || b.opacity <= 0.0 { + return None; + } + + let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; + let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), around) } else { Vec::new() }; + let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c)))); + Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start }) + }) + .collect::>(); + let content = match &layer.kind { + LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, + LayerKind::Fill(f) => { + let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); + Content::Fill { fill: Box::new(Cow::Borrowed(f)), depth, covers_all } + Content::Fill { fill: Box::new(offset_fill(f, around)), depth, covers_all } + } + LayerKind::Group { children, contents, .. } => { + Content::Group(if kids { plan_in(inp, children, channels, tx, ty, depth + 1, fields, around.then(*contents)) } else { Vec::new() }) + } + + // `content_layer` already followed instance links + LayerKind::Instance { .. } => return None, + }; + Some((content, chans)) +} + /// The visible anchor points of a content stack with where they cut it: after their index among /// the visible effects, or None for anchors with only anchors above them (they record the /// layer's full result). @@ -1294,7 +1414,7 @@ fn plan_levels<'a>(inp: &EvaluationInputs<'a>, levels: &[Level], channels: &[Cha .enumerate() .map(|(d, l)| LevelPlan { below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last), + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, inp.project.contents_around(l.at)), above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), }) .collect() @@ -1354,6 +1474,8 @@ struct Texel<'a, 'b> { stop: Option, /// Stack values recorded by the anchor points evaluated so far; true marks a mask anchor (gray, not channel values). anchors: Vec<(LayerId, Acc, bool)>, + /// The stack below the layer whose mask compares its channels (recorded by `eval` there, or where it stops) + below: Option, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip @@ -1588,6 +1710,15 @@ impl<'a, 'b> Texel<'a, 'b> { self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales) } + /// This texel's ID color: from image resource `image` (nearest, as stored), or from the ID mesh map without one + fn id_color(&self, image: Option<&str>) -> Option<[f32; 3]> { + let Some(name) = image else { return self.baked_color(BakedMap::Id) }; + let image = self.inp.images.get(name)?; + let [red, green, blue, _] = + image.sample_nearest((self.x as f32 + 0.5) / self.res.max(1) as f32, (self.y as f32 + 0.5) / self.inp.gbuf.height.max(1) as f32); + Some([red, green, blue]) + } + /// Where `proj` samples this texel: its coordinates, or for a projection from a frame on the surface (placed planar, warp) its place in the frame, and how much backface culling and the shape crop let through fn projected(&mut self, proj: &Projection) -> (Coords, f32) { let c = self.coords(); @@ -1890,7 +2021,7 @@ impl<'a, 'b> Texel<'a, 'b> { } // Replay the prefix to record anchors skipped by the precomputed filter - if let Some(last) = plan.effects.iter().take(skip).rposition(|e| matches!(e.kind, EffectKind::Anchor)) { + if let Some(last) = plan.effects.iter().take(skip).rposition(|e| matches!(*e.kind, EffectKind::Anchor)) { self.mask_effects(plan, plan.background, 0, last + 1); } self.mask_effects(plan, value, skip, plan.effects.len()) @@ -1908,7 +2039,7 @@ impl<'a, 'b> Texel<'a, 'b> { } let opacity = effect.opacity.clamp(0.0, 1.0); - match effect.kind { + match &*effect.kind { EffectKind::Paint | EffectKind::Path(_) => { let (mut painted, mut coverage) = 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))), @@ -1923,7 +2054,10 @@ impl<'a, 'b> Texel<'a, 'b> { coverage *= 1.0 - stroke; } else { // Clone and smudge show the values they carry instead of the mask gray - let deposited = preview.carried_mask.as_ref().map_or(preview.mask_value, |carried| from_u16(carried.get(self.x, self.y)[0])); + let deposited = preview.carried_mask.as_ref().map_or_else( + || preview.mask_gray.at(self.x, self.y, (self.inp.gbuf.width, self.inp.gbuf.height)), + |carried| from_u16(carried.get(self.x, self.y)[0]), + ); painted = deposited * stroke + painted * (1.0 - stroke); coverage = stroke + coverage * (1.0 - stroke); } @@ -1953,20 +2087,15 @@ impl<'a, 'b> Texel<'a, 'b> { 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 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::ColorSelection(selection) => { + let (selected, cover) = selection.value(self.id_color(selection.id_map.as_deref())); + value += (blend1(effect.blend, value, selected) - value) * opacity * cover; } - EffectKind::Compare { op, value: compared, tolerance } => { - let pass = match op { - CompareOp::LesserThan => value < *compared, - CompareOp::GreaterThan => value > *compared, - CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, - }; - let result = if pass { 1.0 } else { 0.0 }; - value += (result - value) * opacity; + EffectKind::Compare { op, value: constant, tolerance, left, right, channel, hardness } => { + let left = self.compare_side(*left, *channel, plan, value, *constant); + let right = self.compare_side(*right, *channel, plan, value, *constant); + let compared = op.mask(left, right, *tolerance, *hardness); + value += (blend1(effect.blend, value, compared) - value) * opacity; } // Every channel of a mask anchor reads the mask's gray @@ -1979,13 +2108,42 @@ impl<'a, 'b> Texel<'a, 'b> { value.clamp(0.0, 1.0) } + /// What one side of a compare effect in mask `plan` reads at this texel (0..1): `mask` is the mask so far + fn compare_side(&mut self, side: CompareSource, channel: Channel, plan: &MaskPlan, mask: f32, constant: f32) -> f32 { + let stack_below = self.below; + let below = || stack_below.and_then(|acc| acc.get(channel.index()).copied()).unwrap_or_else(|| channel.default_value()); + let read = match side { + CompareSource::ThisMask => return mask, + CompareSource::Constant => return constant, + CompareSource::LayersBelow => below(), + CompareSource::ThisLayer => { + let own = plan.layer.as_ref().and_then(|(content, chans)| { + let chan_plan = chans.iter().find(|chan_plan| chan_plan.ch == channel.index())?; + self.content(content, chan_plan) + }); + + // Where the layer is empty (or thin) it shows the stack below it + let below = below(); + own.map_or(below, |(value, coverage)| mix3(below, value, coverage)) + } + }; + match channel.kind() { + ChannelKind::Color | ChannelKind::NormalMap => lum(read), + ChannelKind::Scalar => read[0], + ChannelKind::Signed => read[0] * 0.5 + 0.5, + } + } + /// Composite `nodes` over `acc`, recording anchors; true when it reached the `stop` layer (`acc` then holds the stack below it) fn eval(&mut self, nodes: &[Node], acc: &mut Acc) -> bool { for node in nodes { if self.stop == Some(node.id) { + self.below = Some(*acc); return true; } - + if node.mask.as_ref().is_some_and(|mask| mask.layer.is_some()) { + self.below = Some(*acc); + } let mask = self.tape_mask(node); match &node.content { // Masked-out groups still run when they record anchors or hold the stop layer @@ -2229,7 +2387,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// Apply one content effect to a channel's straight value and coverage fn content_effect(&mut self, effect: &EffectPlan, chan_plan: &ChanPlan, value: [f32; 3], coverage: f32) -> ([f32; 3], f32) { let opacity = effect.opacity.clamp(0.0, 1.0); - match effect.kind { + match &*effect.kind { EffectKind::Paint | EffectKind::Path(_) => { let (painted, painted_coverage) = self.painted(effect.data.as_deref(), chan_plan, effect.preview); over(chan_plan, effect.blend, value, coverage, painted, painted_coverage * opacity) @@ -2243,6 +2401,10 @@ impl<'a, 'b> Texel<'a, 'b> { None => (value, coverage), }, EffectKind::Levels(levels) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), + EffectKind::Levels(levels) => match Channel::ALL.get(chan_plan.ch) { + Some(&channel) if levels.remaps(channel) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), + _ => (value, coverage), + }, // Baked lighting reads the texel's normal and occlusion, and lights the base color only EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { @@ -2255,7 +2417,7 @@ impl<'a, 'b> Texel<'a, 'b> { // Neighbourhood filters come precomputed through `ChanPlan::start` EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), // Anchors are recorded by `eval`; mask-only effects leave content as it is - EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => { + EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection(_) | EffectKind::Compare { .. } => { (value, coverage) } } @@ -2957,7 +3119,7 @@ fn mask_tile<'a>( (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 plan = mask_plan(inputs, id, mask, tile_x, tile_y, Some(fields), inputs.project.contents_around(id)); 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) }; @@ -2986,15 +3148,88 @@ fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> { all.into_iter().step_by(stride).collect() } -/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask -/// below it, or (a content effect) the layer's `channel` below it where the layer has content, -/// color components pooled and signed values mapped to 0..1. Over the texels the mesh covers -/// (in an even sample of tiles on large sets); None for an unknown effect. -pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option> { +/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask below it, or (a content effect) the layer's `channel` below it where the layer has content, signed values mapped to 0..1, a color's components pooled, on their own and as luminance. Over the texels the mesh covers (in an even sample of tiles on large sets); None for an unknown effect +pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option { let (owner, _) = inp.project.effect(effect)?; let bins = bins.max(1); - // Evaluate the layer forced visible, its mask enabled, cut just below the effect. - let mut cut = inp.project.clone(); + let (cut, in_mask) = cut_below(inp.project, owner, effect)?; + let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; + let channels = cut.texture_set(inp.ts).map(|set| set.channel_list()).unwrap_or_default(); + let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); + let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); + let color = !in_mask && channel.kind() == ChannelKind::Color; + + let histogram = tiles + .par_iter() + .map(|&(tx, ty)| { + let mut own = None; + let fields = histogram_tile_fields(shared.as_ref(), &mut own, &cut_inp, &channels, (tx, ty)); + let mut histogram = EffectHistogram::new(bins, color); + + // The mask is planned on its own: a layer with nothing drawn plans no node + let mask = if in_mask { + layer_mask(&cut, owner).and_then(|mask| mask_plan(&cut_inp, owner, mask, tx, ty, Some(fields), cut.contents_around(owner))) + } else { + None + }; + let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) }; + let content = nodes + .first() + .and_then(|node| node.chans.iter().find(|chan_plan| Channel::ALL.get(chan_plan.ch) == Some(&channel)).map(|chan_plan| (node, chan_plan))); + if mask.is_none() && content.is_none() { + return histogram; + } + + let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); + for (x, y, offset) in tile_texels(inp.gbuf, tx, ty) { + let mut texel = Texel::new(&cut_inp, x, y, offset, 0.0); + if !full.is_empty() { + texel.anchors_below(&full, owner); + } + if let Some(mask) = &mask { + histogram.add_value(texel.mask(mask)); + } else if let Some((node, chan_plan)) = content + && let Some((value, _)) = texel.content(&node.content, chan_plan) + { + // As levels reads them (`per_unit`); normal maps pass through levels unchanged + match chan_plan.kind { + ChannelKind::Color => histogram.add_color(value), + ChannelKind::Scalar => histogram.add_value(value[0]), + ChannelKind::Signed => histogram.add_value(value[0] * 0.5 + 0.5), + ChannelKind::NormalMap => {} + } + } + } + histogram + }) + .reduce(|| EffectHistogram::new(bins, color), |left, right| left.merged(&right)); + Some(histogram) +} + +/// The neighbourhood fields every sampled tile of a histogram shares; None with only local neighbourhood filters below, where each tile builds its own +fn shared_histogram_fields(inp: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Option { + // A field covers the bounding box of the tiles it is built for, the whole set for a scattered sample + let probe = neighbourhood_fields(inp, channels, tiles.get(..1).unwrap_or_default()); + if probe.is_empty() { + return Some(probe); + } + + // A stage reading the whole set builds it for every tile: once for the whole sample instead + let whole_set = probe.values().any(|field| field.w >= inp.gbuf.width && field.h >= inp.gbuf.height); + whole_set.then(|| neighbourhood_fields(inp, channels, tiles)) +} + +/// The fields histogram tile `tile` reads: the `shared` ones, else its own built into `own` +fn histogram_tile_fields<'f>(shared: Option<&'f Fields>, own: &'f mut Option, inp: &Inputs, channels: &[Channel], tile: (u32, u32)) -> &'f Fields { + match shared { + Some(fields) => fields, + None => own.insert(neighbourhood_fields(inp, channels, &[tile])), + } +} + +/// The project with layer `owner` forced visible, its mask enabled, cut just below its effect `effect`, and whether the effect is in the mask +fn cut_below(project: &Project, owner: LayerId, effect: LayerId) -> Option<(Project, bool)> { + let mut cut = project.clone(); let l = cut.layers.get_mut(&owner)?; l.visible = true; let in_mask = match l.mask.as_mut().and_then(|m| m.effects.iter().position(|e| e.id == effect).map(|k| (m, k))) { @@ -3009,66 +3244,72 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u false } }; + Some((cut, in_mask)) +} + +/// Histograms (`bins` buckets over 0..1) of what compare mask `effect` reads on its left and right, over [`effect_histogram`]'s texels (None for another effect) +pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option<[Vec; 2]> { + let (owner, found) = inp.project.effect(effect)?; + let EffectKind::Compare { left, right, channel, value: constant, .. } = found.kind else { return None }; + let bins = bins.max(1); + let (cut, in_mask) = cut_below(inp.project, owner, effect)?; + let set = cut.texture_set(inp.ts).ok()?; + if !in_mask { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); - let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + let mut channels = set.channel_list(); + if !channels.contains(&channel) { + channels.push(channel); + } + let reads_stack = found.kind.reads_stack(); 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 - // is the whole set: with a neighbourhood filter below, each tile gets its own. let probe = evaluation_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); - let shared = probe.is_empty().then_some(probe); - let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); - let hist = tiles + let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); + let empty = || [EffectHistogram::new(bins, false), EffectHistogram::new(bins, false)]; + + let [left_counts, right_counts] = tiles .par_iter() .map(|&(tx, ty)| { - let own; - let fields = match &shared { - Some(f) => f, - None => { own = evaluation_fields(&cut_inp, &channels, &[(tx, ty)]); - &own - } + let mut own = None; + let fields = histogram_tile_fields(shared.as_ref(), &mut own, &cut_inp, &channels, (tx, ty)); + let mut sides = empty(); + + // The mask under the compare, and (sides reading layers) the layer's content and the stack below it + let Some(mut mask) = layer_mask(&cut, owner).and_then(|mask| mask_plan(&cut_inp, owner, mask, tx, ty, Some(fields), cut.contents_around(owner))) + else { + return sides; }; - let mut h = vec![0u32; bins]; - // The mask is planned on its own: a layer with nothing drawn plans no node. - let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(fields))) } else { None }; - let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) }; - let content = nodes.first().and_then(|n| n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)).map(|c| (n, c))); - if mask.is_none() && content.is_none() { - return h; + + // Every channel, so the content also serves the compares under this one + if reads_stack { + mask.layer = cut + .content_layer(owner) + .and_then(|layer| plan_content(&cut_inp, owner, layer, &channels, tx, ty, 0, Some(fields), false, cut.contents_around(owner))); } - let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(&cut_inp, x, y, o, 0.0); + + // The stack below, for this compare's sides and for the anchors and compares under it + let mut full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); + if reads_stack && full.is_empty() { + full = plan(&cut_inp, &set.stack, &channels, tx, ty, 0, Some(fields)); + } + + for (x, y, offset) in tile_texels(inp.gbuf, tx, ty) { + let mut texel = Texel::new(&cut_inp, x, y, offset, 0.0); if !full.is_empty() { - tex.anchors_below(&full, owner); + texel.anchors_below(&full, owner); } - if let Some(m) = &mask { - if let Some(b) = h.get_mut(bin(tex.mask(m))) { - *b += 1; - } - } else if let Some((n, c)) = content - && let Some((v, _)) = tex.content(&n.content, c) - { - // As levels reads them (`per_unit`); normal maps pass through levels unchanged. - let (vals, signed) = match c.kind { - ChannelKind::Color => (&v[..], false), - ChannelKind::Scalar => (&v[..1], false), - ChannelKind::Signed => (&v[..1], true), - ChannelKind::NormalMap => (&v[..0], false), - }; - for x in vals { - if let Some(b) = h.get_mut(bin(if signed { x * 0.5 + 0.5 } else { *x })) { - *b += 1; - } - } + let so_far = texel.mask(&mask); + for (side, histogram) in [left, right].into_iter().zip(sides.iter_mut()) { + histogram.add_value(texel.compare_side(side, channel, &mask, so_far, constant)); } } - h + sides }) - .reduce(|| vec![0u32; bins], |a, b| a.iter().zip(&b).map(|(x, y)| x.saturating_add(*y)).collect()); - Some(hist) + .reduce(empty, |[left, right], [more_left, more_right]| [left.merged(&more_left), right.merged(&more_right)]); + Some([left_counts.all, right_counts.all]) } /// One flattened tile of one channel: (channel, tile, premultiplied value + coverage data). @@ -3419,7 +3660,7 @@ mod tests { opacity: 1.0, erase: false, values: [(Channel::BaseColor, [0.0, 0.0, 1.0])].into_iter().collect(), - mask_value: 1.0, + mask_gray: MaskGray::Value(1.0), stencil: None, carried: BTreeMap::new(), carried_mask: None, @@ -3939,7 +4180,12 @@ soft {soft:?}" fn groups_pass_through_with_opacity() { let mut f = fixture(); let gid = f.project.alloc_id(); - let g = Layer::new(gid, "G", LayerKind::Group { children: vec![], collapsed: false }, &[Channel::BaseColor]); + let g = Layer::new( + gid, + "G", + LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, + &[Channel::BaseColor], + ); f.project.insert_layer(0, g, None, false).unwrap(); f.project.layer_mut(gid).unwrap().channels.insert(Channel::BaseColor, ChannelBlend { mode: BlendMode::Passthrough, opacity: 0.5 }); let cid = f.project.alloc_id(); @@ -4149,6 +4395,89 @@ soft {soft:?}" assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); } + #[test] + fn a_compares_histogram_reads_the_compares_under_it_against_the_stack() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.5; 3], 0.8); + let top = fill_layer(&mut f.project, [1.0; 3], 0.2); + let compare = |left, right| EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.5, + tolerance: 0.0, + left, + right, + channel: Channel::Roughness, + hardness: 1.0, + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(f.project.alloc_id(), compare(CompareSource::LayersBelow, CompareSource::Constant))); + let reader = Effect::new(f.project.alloc_id(), compare(CompareSource::ThisMask, CompareSource::Constant)); + let reader_id = reader.id; + mask.effects.push(reader); + f.project.layer_mut(top).unwrap().mask = Some(mask); + let images = ImageStore::default(); + + let [mask_so_far, _] = compare_histograms(&inputs(&f, &images, None), reader_id, 4).unwrap(); + + // The roughness below (0.8) passes the first compare everywhere: the mask so far is white + let white = *mask_so_far.last().unwrap(); + + assert!(white > 0 && mask_so_far.iter().sum::() == white, "{mask_so_far:?}"); + } + + #[test] + fn a_filtered_mask_compares_the_layers_filtered_content() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.5; 3], 0.5); + let top = fill_layer(&mut f.project, [1.0; 3], 0.9); + content_fx(&mut f, top, EffectKind::Filter(Filter::EdgeDetect { width: 64.0 })); + let compare = EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.7, + tolerance: 0.0, + left: CompareSource::ThisLayer, + right: CompareSource::Constant, + channel: Channel::Roughness, + hardness: 1.0, + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(f.project.alloc_id(), compare)); + f.project.layer_mut(top).unwrap().mask = Some(mask); + + let color = run(&f, None).value(Channel::BaseColor, 30, 30); + + // Uniform roughness 0.9 has no edges: black after the edge detection, it fails the compare and the layer below shows + assert!(close(color, [0.5; 3]), "{color:?}"); + } + + #[test] + fn a_compare_mask_blends_onto_the_mask_with_its_blend_mode() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.5; 3], 0.8); + let top = fill_layer(&mut f.project, [1.0; 3], 0.2); + + // The roughness below (0.8) passes everywhere, but a white compare multiplied onto a black mask stays black + let mut compare = Effect::new( + f.project.alloc_id(), + EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.5, + tolerance: 0.0, + left: CompareSource::LayersBelow, + right: CompareSource::Constant, + channel: Channel::Roughness, + hardness: 1.0, + }, + ); + compare.blend = BlendMode::Multiply; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(compare); + f.project.layer_mut(top).unwrap().mask = Some(mask); + + let color = run(&f, None).value(Channel::BaseColor, 30, 30); + assert!(close(color, [0.5; 3]), "the layer under shows: {color:?}"); + } + #[test] fn geometry_masks_show_layers_on_chosen_parts_only() { let mut f = fixture(); @@ -4385,6 +4714,71 @@ soft {soft:?}" } } + #[test] + fn fills_inside_folders_take_the_folders_scale_and_rotation_on_top_of_their_own() { + // Nested folders (x2 turned 30, then x1.5 turned -10) around a procedural fill with a procedural mask fill + let build = |outer: ContentsOffset, inner: ContentsOffset, projection: Projection| { + let mut f = fixture(); + let folder = |f: &mut Fixture, contents: ContentsOffset| { + let id = f.project.alloc_id(); + Layer::new(id, "G", LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, &[Channel::BaseColor]) + }; + let outer = folder(&mut f, outer); + let outer = f.project.insert_layer(0, outer, None, false).unwrap(); + let inner = folder(&mut f, inner); + let inner = f.project.insert_layer(0, inner, Some(outer), true).unwrap(); + let pattern = |seed| Source::Procedural { + pattern: Procedural { seed, ..Procedural::new(ProceduralKind::Perlin) }, + low: [0.0; 3], + high: [1.0; 3], + ramp: Vec::new(), + }; + let mut fill = Fill { projection: projection.clone(), ..Fill::default() }; + fill.sources.insert(Channel::BaseColor, pattern(3)); + let id = f.project.alloc_id(); + let mut layer = Layer::new(id, "C", LayerKind::Fill(fill), &[Channel::BaseColor]); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source: pattern(9), projection, sampling: Default::default() })); + layer.mask = Some(mask); + f.project.insert_layer(0, layer, Some(inner), true).unwrap(); + run(&f, None) + }; + let own = Projection::Uv { scale: [2.0, 1.0], rotation: 15.0, offset: [0.1, 0.0] }; + let (outer, inner) = (ContentsOffset::new(2.0, 30.0), ContentsOffset::new(1.5, -10.0)); + let none = ContentsOffset::NONE; + let offset = build(outer, inner, own.clone()); + let written = build(none, none, Projection::Uv { scale: [6.0, 3.0], rotation: 35.0, offset: [0.1, 0.0] }); + assert_eq!(offset, written, "the folders' offset renders as if it were written into the fills"); + assert_ne!(offset, build(none, none, own), "without the offset every fill keeps its own"); + } + + #[test] + fn folder_mask_anchor_points_record_even_where_the_folder_is_masked_out() { + let mut fixture = fixture(); + let group_id = fixture.project.alloc_id(); + let folder = Layer::new( + group_id, + "G", + LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, + &[Channel::BaseColor, Channel::Roughness], + ); + fixture.project.insert_layer(0, folder, None, false).unwrap(); + let child = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([0.0; 3])); + fixture.project.insert_layer(0, Layer::new(child, "C", LayerKind::Fill(fill), &[Channel::BaseColor]), Some(group_id), true).unwrap(); + let (gray, anchor, last) = (fixture.project.alloc_id(), fixture.project.alloc_id(), fixture.project.alloc_id()); + let uniform = |value: f32| EffectKind::Fill { source: Source::Uniform([value; 3]), projection: Projection::default(), sampling: Default::default() }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects = vec![Effect::new(gray, uniform(0.4)), Effect::new(anchor, EffectKind::Anchor), Effect::new(last, uniform(0.0))]; + fixture.project.layer_mut(group_id).unwrap().mask = Some(mask); + anchor_reader(&mut fixture, anchor); + + // The folder's mask ends at 0 (its black child hides), the reader above shows at 0.4 over the 0.5 base + let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); + } + /// A fixture under a decal fill of image "decal" framed on the plane's middle, its projection changed by `change` fn decal_fixture(change: impl FnOnce(&mut Fill)) -> Fixture { let mut fixture = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ccf2d252..c40ce2f7 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -13,6 +13,7 @@ pub mod below; mod curvature_size_level; pub mod curvature_sizes; pub mod display; +mod effect_histogram; pub mod eval; mod fabric; pub mod fill_copies; @@ -22,6 +23,7 @@ pub mod frame_placement; mod fur_lock; mod held_fields; mod image_identity; +mod mask_gray; pub mod mip_level; mod organic; pub mod pattern; @@ -41,13 +43,14 @@ pub mod warp; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; +pub use effect_histogram::EffectHistogram; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, - composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, - stack_reads_neighbours, + BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, + covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; +pub use mask_gray::MaskGray; pub use pattern_context::PatternContext; -pub use projector_depth_cache::ProjectorDepthCache; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/mask_gray.rs b/crates/compose/src/mask_gray.rs new file mode 100644 index 00000000..3cadf807 --- /dev/null +++ b/crates/compose/src/mask_gray.rs @@ -0,0 +1,41 @@ +//! The gray a mask stroke paints + +use std::sync::Arc; + +use texturecraft_core::lum; + +use crate::ImageRes; + +/// The gray a mask stroke paints: one value, or the gray of an image laid once over the texture by its UVs +#[derive(Clone, Debug, PartialEq)] +pub enum MaskGray { + Value(f32), + /// Image resource `name`, read as its gray like a mask fill reads an image + Image { + name: String, + image: Arc, + }, +} + +impl MaskGray { + /// The gray painted at texel (`x`, `y`) of a `width` × `height` texture (the image read at the texel's centre) + pub fn at(&self, x: u32, y: u32, (width, height): (u32, u32)) -> f32 { + match self { + MaskGray::Value(value) => value.clamp(0.0, 1.0), + MaskGray::Image { image, .. } => { + let u = (x as f32 + 0.5) / width.max(1) as f32; + let v = (y as f32 + 0.5) / height.max(1) as f32; + let [r, g, b, _] = image.sample(u, v); + lum([r, g, b]).clamp(0.0, 1.0) + } + } + } + + /// The image resource painted, None for one value + pub fn image_name(&self) -> Option<&str> { + match self { + MaskGray::Value(_) => None, + MaskGray::Image { name, .. } => Some(name), + } + } +} diff --git a/crates/compose/src/solo.rs b/crates/compose/src/solo.rs index c9d17f5a..11427c3a 100644 --- a/crates/compose/src/solo.rs +++ b/crates/compose/src/solo.rs @@ -114,7 +114,8 @@ mod tests { fn solo_keeps_the_folders_around_a_layer_and_everything_inside_a_soloed_folder() { let mut p = project(); let outside = add(&mut p, 0, LayerKind::Paint, None, false); - let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let folder = + add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false); let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false); let view = solo_project(&p, inner, false).unwrap(); @@ -131,7 +132,8 @@ mod tests { #[test] fn ignoring_the_mask_disables_it_on_the_layer_and_its_folders_only() { let mut p = project(); - let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let folder = + add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false); let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let other = add(&mut p, 0, LayerKind::Paint, None, false); for id in [folder, inner, other] { @@ -163,7 +165,8 @@ mod tests { #[test] fn a_soloed_instance_of_a_folder_keeps_the_folders_contents_drawn() { let mut p = project(); - let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let folder = + add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false); let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false); let view = solo_project(&p, instance, false).unwrap(); diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index e7b78d3b..07229ab5 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -128,6 +128,15 @@ impl ImageRes { bilinear(&self.rgba, self.width, self.height, u, v, (true, true)) } + /// The texel under (`u`, `v`) as stored, wrapping (an ID map's colors must not blend) + pub fn sample_nearest(&self, u: f32, v: f32) -> [f32; 4] { + if !u.is_finite() || !v.is_finite() { + return [0.0; 4]; + } + + self.nearest(u, v, (true, true)) + } + /// The texel under (`u`, `v`), on the axes that do not `repeat` the edge texel past the edge fn nearest(&self, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] { self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat) diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index b4c59a15..afa677d6 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -60,7 +60,7 @@ fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option LayerId { mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position)))); mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask)); - let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false }, None); + let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); for b in f.project.layer_mut(group).unwrap().channels.values_mut() { b.mode = BlendMode::Passthrough; } @@ -226,7 +228,7 @@ fn mask_with_height_follows_the_layer_height() { } fn group(f: &mut Fixture, folder: Option, mode: BlendMode, opacity: f32, mask: Option) -> LayerId { - let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false }, mask); + let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, mask); blend(f, id, mode, opacity); id } @@ -338,7 +340,7 @@ fn stroke(target: LayerId) -> StrokePreview { opacity: 0.9, erase: false, values: [(Channel::BaseColor, [1.0, 0.1, 0.1]), (Channel::Roughness, [0.2; 3])].into_iter().collect(), - mask_value: 1.0, + mask_gray: MaskGray::Value(1.0), stencil: None, carried: BTreeMap::new(), carried_mask: None, @@ -904,16 +906,66 @@ fn generator_input_image_changes_invalidate_stack_key() { let original = key(&images); images.insert("unrelated".into(), image(0.5)); - assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged"); let old_image = Arc::downgrade(&images["used"]); images.insert("used".into(), image(0.9)); - assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels"); assert!(key(&images) != original, "replacing a generator input must invalidate the cache"); images.remove("used"); - assert!(key(&images) != original, "removing a generator input must invalidate the cache"); } + +#[test] +fn compare_masks_reading_layers_fall_back_to_full_evaluation() { + let mut f = fixture(); + let n = nested_stack(&mut f); + let compare = effect( + &mut f, + EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.5, + tolerance: 0.0, + left: CompareSource::LayersBelow, + right: CompareSource::ThisLayer, + channel: Channel::Roughness, + hardness: 1.0, + }, + ); + + // A mask above the hot layer compares the stack below it + f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(compare); + + for hot in [n.deep, n.top] { + assert!(check_cached(&f, 0, hot).is_empty(), "compare masks read the stack: nothing cached"); + } +} + +/// The key of set 0's whole stack over `images` +fn stack_key(fixture: &Fixture, images: &texturecraft_compose::ImageStore) -> texturecraft_compose::StackKey { + let roots = &fixture.project.texture_sets[0].stack; + texturecraft_compose::StackKey::new(&fixture.project, &fixture.pixels, &Default::default(), images, 0, roots).unwrap() +} + +/// A flat image resource of `value` +fn flat_image(value: f32) -> std::sync::Arc { + std::sync::Arc::new(texturecraft_compose::ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)) +} + +#[test] + let mut fixture = fixture(); + heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); + selection.id_map = Some("id".into()); + let selection = effect(&mut fixture, EffectKind::ColorSelection(selection)); + let layer = fixture.project.layer_mut(bottom_layer).unwrap(); + layer.mask = Some(Mask::new(MaskBackground::White)); + layer.mask.as_mut().unwrap().effects.push(selection); + let mut images = texturecraft_compose::ImageStore::default(); + images.insert("id".into(), flat_image(0.1)); + + let original = stack_key(&fixture, &images); + +} diff --git a/crates/core/src/color_selection.rs b/crates/core/src/color_selection.rs new file mode 100644 index 00000000..df2390a4 --- /dev/null +++ b/crates/core/src/color_selection.rs @@ -0,0 +1,132 @@ +//! A mask effect that selects the parts of an ID map whose colors are in its list + +use serde::{Deserialize, Serialize}; + +use crate::SelectionBackground; + +/// Selects ID-map colors within a tolerance: the selected parts get the output value, the rest the background +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ColorSelection { + /// The selected ID colors, as the ID map stores them + pub colors: Vec<[f32; 3]>, + /// How far each component may be from a selected color and still count as it + pub tolerance: f32, + /// The value selected parts get + #[serde(default = "full", skip_serializing_if = "is_full")] + pub output: f32, + /// 1 is a hard edge (what selections saved before hardness did); lower ramps over 1 − hardness past the tolerance + #[serde(default = "full", skip_serializing_if = "is_full")] + pub hardness: f32, + #[serde(default, skip_serializing_if = "SelectionBackground::is_default")] + pub background: SelectionBackground, + /// The image resource read as the ID map; none reads the texture set's ID mesh map + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id_map: Option, +} + +fn full() -> f32 { + 1.0 +} + +/// Whether an output or hardness is what selections saved before it existed had (not saved then, so they save as they were) +fn is_full(value: &f32) -> bool { + *value == full() +} + +impl ColorSelection { + /// A selection of `colors` with the defaults of a new one + pub fn new(colors: Vec<[f32; 3]>, tolerance: f32) -> ColorSelection { + ColorSelection { colors, tolerance, output: 1.0, hardness: 1.0, background: SelectionBackground::Black, id_map: None } + } + + /// How much ID color `id` is selected, 0..1 (none: no ID map there) + pub fn amount(&self, id: Option<[f32; 3]>) -> f32 { + let Some(id) = id else { return 0.0 }; + let distance = self + .colors + .iter() + // A NaN component matches nothing (f32::max would drop it), as the old strict comparison did + .map(|picked| { + picked + .iter() + .zip(id) + .map(|(picked, component)| (picked - component).abs()) + .fold(0.0f32, |far, gap| if gap.is_nan() || gap > far { gap } else { far }) + }) + .fold(f32::INFINITY, f32::min); + if !distance.is_finite() { + return 0.0; + } + + let past = distance - self.tolerance; + if past <= 0.0 { + return 1.0; + } + + // A NaN tolerance or hardness (only a hand-edited file holds one) selects nothing, as a NaN component does + let width = 1.0 - self.hardness.clamp(0.0, 1.0); + let ramp = if width <= 0.0 { 0.0 } else { (1.0 - past / width).clamp(0.0, 1.0) }; + if ramp.is_nan() { 0.0 } else { ramp } + } + + /// The gray this selection gives ID color `id` and how much of it covers the mask below (a transparent background covers only the selection) + pub fn value(&self, id: Option<[f32; 3]>) -> (f32, f32) { + let amount = self.amount(id); + match self.background.value() { + Some(background) => (background + (self.output - background) * amount, 1.0), + None => (self.output, amount), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::EffectKind; + + #[test] + fn a_selection_saved_before_loads_hard_on_black_from_the_mesh_map() { + let saved = r#"{"ColorSelection":{"colors":[[1.0,0.0,0.0]],"tolerance":0.1}}"#; + let EffectKind::ColorSelection(selection) = serde_json::from_str::(saved).unwrap() else { panic!("not a color selection") }; + assert_eq!(selection, ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1)); + assert_eq!(serde_json::to_string(&EffectKind::ColorSelection(selection)).unwrap(), saved, "it saves as it was saved"); + } + + #[test] + fn the_hard_edge_selects_as_before_and_softness_ramps_past_the_tolerance() { + let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); + assert_eq!(selection.value(Some([0.95, 0.05, 0.0])), (1.0, 1.0)); + assert_eq!(selection.value(Some([0.8, 0.0, 0.0])), (0.0, 1.0)); + assert_eq!(selection.value(None), (0.0, 1.0)); + assert_eq!(selection.value(Some([f32::NAN, 0.0, 0.0])), (0.0, 1.0)); + selection.hardness = 0.8; + let (ramped, _) = selection.value(Some([0.8, 0.0, 0.0])); + assert!((ramped - 0.5).abs() < 1e-5, "{ramped}"); + selection.colors.clear(); + assert_eq!(selection.value(Some([1.0, 0.0, 0.0])), (0.0, 1.0)); + } + + #[test] + fn a_nan_tolerance_or_hardness_selects_nothing() { + let mut nan_tolerance = ColorSelection::new(vec![[1.0, 0.0, 0.0]], f32::NAN); + nan_tolerance.hardness = 0.5; + let mut nan_hardness = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); + nan_hardness.hardness = f32::NAN; + + for selection in [nan_tolerance, nan_hardness] { + assert_eq!(selection.amount(Some([0.8, 0.0, 0.0])), 0.0); + } + } + + #[test] + fn the_output_and_background_set_both_sides_and_transparent_covers_only_the_selection() { + let mut selection = ColorSelection::new(vec![[0.0, 0.0, 1.0]], 0.1); + selection.output = 0.25; + selection.background = SelectionBackground::White; + assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0)); + assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (1.0, 1.0)); + selection.background = SelectionBackground::Transparent; + assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0)); + assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (0.25, 0.0)); + } +} diff --git a/crates/core/src/compare_source.rs b/crates/core/src/compare_source.rs new file mode 100644 index 00000000..794e7c6f --- /dev/null +++ b/crates/core/src/compare_source.rs @@ -0,0 +1,60 @@ +//! What one side of a compare mask reads + +use serde::{Deserialize, Serialize}; + +/// One side of a compare mask's comparison +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum CompareSource { + /// The compared channel of the stack below the layer + LayersBelow, + /// The compared channel of the layer's own content, laid over the stack below by its coverage + ThisLayer, + /// The mask so far (the effects under the compare) + ThisMask, + /// The compare's constant + Constant, +} + +impl CompareSource { + /// Menu order + pub const ALL: [CompareSource; 4] = [CompareSource::LayersBelow, CompareSource::ThisLayer, CompareSource::ThisMask, CompareSource::Constant]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + CompareSource::LayersBelow => "layersBelow", + CompareSource::ThisLayer => "thisLayer", + CompareSource::ThisMask => "thisMask", + CompareSource::Constant => "constant", + } + } + + pub fn from_id(id: &str) -> Option { + CompareSource::ALL.into_iter().find(|source| source.id() == id) + } + + /// Reads a material channel of the stack (the layer or the layers below) + pub fn reads_stack(self) -> bool { + matches!(self, CompareSource::LayersBelow | CompareSource::ThisLayer) + } + + /// The left side of compare masks saved before sources existed + pub(crate) fn saved_left() -> CompareSource { + CompareSource::ThisMask + } + + /// The right side of compare masks saved before sources existed + pub(crate) fn saved_right() -> CompareSource { + CompareSource::Constant + } + + /// Whether a left side reads what saved compare masks did (not saved then) + pub(crate) fn is_saved_left(&self) -> bool { + *self == CompareSource::saved_left() + } + + /// Whether a right side reads what saved compare masks did (not saved then) + pub(crate) fn is_saved_right(&self) -> bool { + *self == CompareSource::saved_right() + } +} diff --git a/crates/core/src/contents_offset.rs b/crates/core/src/contents_offset.rs new file mode 100644 index 00000000..033071b0 --- /dev/null +++ b/crates/core/src/contents_offset.rs @@ -0,0 +1,116 @@ +//! A folder's Scale and Rotation for the fills inside it + +use serde::{Deserialize, Serialize}; + +use crate::layer::Projection; + +/// Scale and Rotation a folder lays on every fill inside it, on top of each fill's own: the tiling is multiplied by `scale` and `rotation` (degrees) is added to the fill's angle; the fills themselves never change, so dropping the offset gives each its own back +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ContentsOffset { + pub scale: f32, + pub rotation: f32, +} + +impl Default for ContentsOffset { + /// Nothing changed, as in every folder saved before folders had an offset + fn default() -> Self { + ContentsOffset::NONE + } +} + +impl ContentsOffset { + /// The offset that changes nothing + pub const NONE: ContentsOffset = ContentsOffset { scale: 1.0, rotation: 0.0 }; + + /// The smallest and largest Scale a folder takes + pub const SCALE_RANGE: (f32, f32) = (0.01, 100.0); + + /// The Rotation a folder takes, in degrees: a half turn each way + pub const ROTATION_RANGE: (f32, f32) = (-180.0, 180.0); + + /// Whether the offset changes nothing + pub fn is_none(&self) -> bool { + *self == ContentsOffset::NONE + } + + /// An offset with `scale` kept in [`ContentsOffset::SCALE_RANGE`] and `rotation` wrapped into [`ContentsOffset::ROTATION_RANGE`] (non-finite values change nothing) + pub fn new(scale: f32, rotation: f32) -> ContentsOffset { + let (low, high) = ContentsOffset::SCALE_RANGE; + let scale = if scale.is_finite() { scale.clamp(low, high) } else { 1.0 }; + let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE; + let rotation = if rotation.is_finite() { (rotation - turn_start).rem_euclid(turn_end - turn_start) + turn_start } else { 0.0 }; + ContentsOffset { scale, rotation } + } + + /// The offset of a folder inside one with offset `self` (`inner` is the inner folder's own): scales multiply, rotations add, and the result stays in range however deep folders nest + pub fn then(self, inner: ContentsOffset) -> ContentsOffset { + ContentsOffset::new(self.scale * inner.scale, self.rotation + inner.rotation) + } + + /// `projection` with this offset laid on its tiling and rotation (a projection stretched once over each UV tile has neither) + pub fn apply(self, projection: &Projection) -> Projection { + // A loaded offset never went through `new` + let offset = ContentsOffset::new(self.scale, self.rotation); + let mut out = projection.clone(); + match &mut out { + Projection::Uv { scale, rotation, .. } => { + *scale = scale.map(|s| s * offset.scale); + *rotation += offset.rotation; + } + Projection::UvTile => {} + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => { + uv.tiling = uv.tiling.map(|t| t * offset.scale); + uv.rotation += offset.rotation; + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::layer::UvTransform; + + #[test] + fn an_offset_multiplies_the_tiling_and_adds_to_the_angle_of_every_projection() { + let offset = ContentsOffset::new(1.5, 30.0); + let uv = offset.apply(&Projection::Uv { scale: [2.0, 4.0], rotation: 10.0, offset: [0.25, 0.0] }); + assert_eq!(uv, Projection::Uv { scale: [3.0, 6.0], rotation: 40.0, offset: [0.25, 0.0] }); + let spherical = Projection::Spherical { + scale: 1.0, + uv: UvTransform { tiling: [2.0, 1.0], rotation: -5.0, offset: [0.0; 2] }, + offset: [0.0; 3], + projector: Default::default(), + }; + let Projection::Spherical { scale, uv, .. } = offset.apply(&spherical) else { panic!("expected a spherical projection") }; + assert_eq!((scale, uv.tiling, uv.rotation), (1.0, [3.0, 1.5], 25.0)); + assert_eq!(offset.apply(&Projection::UvTile), Projection::UvTile); + assert_eq!(ContentsOffset::NONE.apply(&spherical), spherical); + } + + #[test] + fn nested_offsets_combine_and_hostile_values_are_kept_in_range() { + let both = ContentsOffset::new(2.0, 170.0).then(ContentsOffset::new(1.5, 20.0)); + assert_eq!((both.scale, both.rotation), (3.0, -170.0)); + assert_eq!(ContentsOffset::new(f32::NAN, f32::INFINITY), ContentsOffset::NONE); + assert_eq!(ContentsOffset::new(1e9, 190.0), ContentsOffset { scale: 100.0, rotation: -170.0 }); + assert_eq!(ContentsOffset::new(-3.0, -180.0), ContentsOffset { scale: 0.01, rotation: -180.0 }); + assert!(ContentsOffset::default().is_none()); + } + + #[test] + fn deep_nesting_and_loaded_offsets_keep_the_scale_in_range() { + let deep = (0..17).fold(ContentsOffset::NONE, |around, _| around.then(ContentsOffset::new(100.0, 0.0))); + assert_eq!(deep.scale, ContentsOffset::SCALE_RANGE.1); + + let loaded: ContentsOffset = serde_json::from_str(r#"{"scale":0,"rotation":0}"#).unwrap(); + let tiled = loaded.apply(&Projection::Uv { scale: [2.0, 2.0], rotation: 0.0, offset: [0.0; 2] }); + assert_eq!(tiled, Projection::Uv { scale: [0.02, 0.02], rotation: 0.0, offset: [0.0; 2] }, "a loaded Scale of 0 is kept at the smallest"); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 7d380e4c..56520585 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -129,7 +129,16 @@ pub enum LayerKind { /// A procedural or uniform material applied everywhere (shaped by the mask). Fill(Fill), /// A folder of layers, bottom → top. - Group { children: Vec, collapsed: bool }, + Group { + children: Vec, + collapsed: bool, + /// Scale and Rotation laid on every fill inside (none in folders saved before folders had one) + #[serde(default, skip_serializing_if = "ContentsOffset::is_none")] + contents: ContentsOffset, + /// The seeds inside that its Randomize seeds changed, until its Contents reset puts them back (none in folders saved before) + #[serde(default, skip_serializing_if = "Vec::is_empty")] + randomized: Vec, + }, /// A linked instance of `source` (possibly in another texture set): renders the source's /// content, content effects and channel blending, and its mask unless the instance has its /// own. Edits to the source show in every instance. @@ -137,6 +146,11 @@ pub enum LayerKind { } impl LayerKind { + /// A new folder: empty, open, with no Scale or Rotation laid on its contents + pub fn folder() -> LayerKind { + LayerKind::Group { children: Vec::new(), collapsed: false, contents: ContentsOffset::NONE, randomized: Vec::new() } + } + pub fn name(&self) -> &'static str { match self { LayerKind::Paint => "paint", @@ -697,6 +711,11 @@ impl Source { _ => None, } } + + /// Whether this source reads anchor point `anchor` (any anchor point when None) + pub fn reads_anchor(&self, anchor: Option) -> bool { + self.anchor().is_some_and(|found| anchor.is_none_or(|wanted| wanted == found)) + } } /// A fill layer's material: one source per channel, plus how it is projected. @@ -834,19 +853,51 @@ pub struct Levels { pub gamma: f32, pub out_low: f32, pub out_high: f32, + /// The one channel a content levels remaps; none remaps every channel (as levels saved before the choice did) and a mask's one value + #[serde(default, skip_serializing_if = "Option::is_none")] + pub affects: Option, + /// Values past the input handles stop at the output ends; off, the remap's line carries on past them (older saves load clamped) + #[serde(default = "saved_levels_clamp", skip_serializing_if = "is_true")] + pub clamp: bool, +} + +/// What levels saved before [`Levels::clamp`] existed did +fn saved_levels_clamp() -> bool { + true } impl Default for Levels { fn default() -> Self { - Levels { in_low: 0.0, in_high: 1.0, gamma: 1.0, out_low: 0.0, out_high: 1.0 } + Levels { in_low: 0.0, in_high: 1.0, gamma: 1.0, out_low: 0.0, out_high: 1.0, affects: None, clamp: false } } } impl Levels { + /// The gamma a levels effect takes, typed or dragged + pub const GAMMA_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + + /// Narrowest input range the remap divides by, so handles on one value never divide by zero + const MIN_INPUT_RANGE: f32 = 1e-5; + + /// Smallest gamma the remap raises by, so a zero gamma read from a file never divides by zero + const MIN_GAMMA: f32 = 1e-3; + pub fn apply(&self, x: f32) -> f32 { - let t = ((x - self.in_low) / (self.in_high - self.in_low).max(1e-5)).clamp(0.0, 1.0); - let t = t.powf(1.0 / self.gamma.max(1e-3)); - self.out_low + (self.out_high - self.out_low) * t + let between = (x - self.in_low) / (self.in_high - self.in_low).max(Self::MIN_INPUT_RANGE); + + // Past the input handles an unclamped remap carries on in a straight line (gamma only bends the part between them) + let between = if self.clamp || (0.0..=1.0).contains(&between) { between.clamp(0.0, 1.0).powf(1.0 / self.gamma.max(Self::MIN_GAMMA)) } else { between }; + self.out_low + (self.out_high - self.out_low) * between + } + + /// Whether these levels remap `channel` of a layer's content + pub fn remaps(&self, channel: Channel) -> bool { + self.affects.is_none_or(|affects| affects == channel) + } + + /// The handles back at their defaults, keeping the channel and the clamp + pub fn reset(&self) -> Levels { + Levels { affects: self.affects, clamp: self.clamp, ..Levels::default() } } } @@ -1125,6 +1176,10 @@ pub enum Filter { }, } +fn is_true(on: &bool) -> bool { + *on +} + /// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1. fn shift_unit(x: f32, amount: f32) -> f32 { let a = amount.clamp(-1.0, 1.0); @@ -1378,15 +1433,24 @@ pub enum EffectKind { Levels(Levels), Filter(Filter), /// Select ID-map colors within a tolerance. - ColorSelection { - colors: Vec<[f32; 3]>, - tolerance: f32, - }, - /// Compare the mask with a constant. + ColorSelection(crate::ColorSelection), + /// Compare one channel (or the mask so far, or a constant) on two sides: 1 where the comparison holds, softened by `hardness` Compare { op: CompareOp, + /// The constant a [`CompareSource::Constant`] side reads value: f32, + /// How far apart two values may be and still count as equal ([`CompareOp::WithinTolerance`]) tolerance: f32, + #[serde(default = "CompareSource::saved_left", skip_serializing_if = "CompareSource::is_saved_left")] + left: CompareSource, + #[serde(default = "CompareSource::saved_right", skip_serializing_if = "CompareSource::is_saved_right")] + right: CompareSource, + /// The channel a layer side reads + #[serde(default = "saved_compare_channel", skip_serializing_if = "is_saved_compare_channel")] + channel: Channel, + /// 1 is a hard step (what compare masks saved before hardness did); lower ramps over 1 − hardness + #[serde(default = "saved_compare_hardness", skip_serializing_if = "is_saved_compare_hardness")] + hardness: f32, }, /// Content only: a material fill (one source per channel; channels without a source are /// left as they are). @@ -1421,6 +1485,66 @@ pub enum CompareOp { GreaterThan, } +impl CompareOp { + /// Menu order + pub const ALL: [CompareOp; 3] = [CompareOp::LesserThan, CompareOp::WithinTolerance, CompareOp::GreaterThan]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + CompareOp::LesserThan => "lesser", + CompareOp::WithinTolerance => "within", + CompareOp::GreaterThan => "greater", + } + } + + pub fn from_id(id: &str) -> Option { + match id { + // mask.add.compare took "less" as well as "lesser" before the ids were the op names + "less" => Some(CompareOp::LesserThan), + _ => CompareOp::ALL.into_iter().find(|op| op.id() == id), + } + } + + /// The mask value of `left` compared with `right`: a hard 0/1 at hardness 1, else a ramp over 1 − hardness past the edge + pub fn mask(self, left: f32, right: f32, tolerance: f32, hardness: f32) -> f32 { + // How far past the edge of the passing range `left` is (positive passes) + let past = match self { + CompareOp::LesserThan => right - left, + CompareOp::GreaterThan => left - right, + CompareOp::WithinTolerance => tolerance - (left - right).abs(), + }; + let width = (1.0 - hardness).clamp(0.0, 1.0); + let pass = if self == CompareOp::WithinTolerance { past >= 0.0 } else { past > 0.0 }; + if width.is_nan() || width <= 0.0 || past.is_nan() { + return if pass { 1.0 } else { 0.0 }; + } + + let ramp = if self == CompareOp::WithinTolerance { 1.0 + past / width } else { past / width }; + ramp.clamp(0.0, 1.0) + } +} + +/// The channel of compare masks saved before the channel choice (their sides read no channel) +fn saved_compare_channel() -> Channel { + Channel::Height +} + +/// The hardness of compare masks saved before hardness existed (a hard step) +fn saved_compare_hardness() -> f32 { + 1.0 +} + +/// Whether a compare mask reads the channel saved ones did (not saved then) +fn is_saved_compare_channel(channel: &Channel) -> bool { + *channel == saved_compare_channel() +} + +/// Whether a compare mask is the hard step saved ones were (not saved then) +fn is_saved_compare_hardness(hardness: &f32) -> bool { + *hardness == saved_compare_hardness() +} + impl EffectKind { pub fn name(&self) -> &'static str { match self { @@ -1437,6 +1561,11 @@ impl EffectKind { } } + /// Whether the effect has a blend mode and opacity of its own (levels and anchor points do not) + pub fn blends(&self) -> bool { + !matches!(self, EffectKind::Levels(_) | EffectKind::Anchor) + } + /// Whether the effect belongs in a layer's content stack (`true`), its mask (`false`), or /// both (`None`). pub fn content_only(&self) -> Option { @@ -1452,12 +1581,15 @@ impl EffectKind { matches!(self, EffectKind::Paint | EffectKind::Path(_)) } - /// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point. - fn reads_anchor(&self) -> bool { + /// Whether a source of this effect reads anchor point `anchor` (any anchor point when None) + pub fn reads(&self, anchor: Option) -> bool { match self { - EffectKind::Fill { source, .. } => source.anchor().is_some(), - EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()), - EffectKind::Generator(generator) => generator.micro.is_some() || generator.inputs.values().any(|source| source.anchor().is_some()), + EffectKind::Fill { source, .. } => source.reads_anchor(anchor), + EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)), + EffectKind::Generator(generator) => { + generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor)) + || generator.inputs.values().any(|source| source.reads_anchor(anchor)) + } _ => false, } } @@ -1485,7 +1617,7 @@ impl EffectKind { anchors } - /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input) + /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input, a colour selection's ID map) pub fn images_read(&self) -> impl Iterator { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], @@ -1493,7 +1625,16 @@ impl EffectKind { EffectKind::Generator(generator) => generator.inputs.values().collect(), _ => Vec::new(), }; - sources.into_iter().flat_map(Source::images) + let id_map = match self { + EffectKind::ColorSelection(selection) => selection.id_map.as_deref(), + _ => None, + }; + sources.into_iter().flat_map(Source::images).chain(id_map) + } + + /// Reads a channel of the layer or of the stack below it (a compare mask's layer sides) + pub fn reads_stack(&self) -> bool { + matches!(self, EffectKind::Compare { left, right, .. } if left.reads_stack() || right.reads_stack()) } } @@ -1501,10 +1642,14 @@ impl Layer { /// Whether any source of the layer (fill, mask or content effects) reads an anchor point. pub fn reads_anchor(&self) -> bool { let fill = match &self.kind { - LayerKind::Fill(f) => f.sources.values().any(|s| s.anchor().is_some()), + LayerKind::Fill(fill) => fill.sources.values().any(|source| source.reads_anchor(None)), _ => false, }; - fill || self.mask.iter().flat_map(|m| m.effects.iter()).chain(self.content_effects.iter()).any(|e| e.kind.reads_anchor()) + } + + /// Whether the layer's result depends on the stack below it: it reads an anchor point, or its mask compares channels of the stack + pub fn reads_stack(&self) -> bool { + self.reads_anchor() || self.mask.iter().flat_map(|mask| mask.effects.iter()).any(|effect| effect.visible && effect.kind.reads_stack()) } } @@ -1516,12 +1661,20 @@ pub struct Effect { pub kind: EffectKind, pub blend: BlendMode, pub opacity: f32, + /// A content effect's channels that blend apart from `blend` and `opacity` (none in projects saved before they existed) + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub channel_blends: BTreeMap, } impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { // Generators and fills that build a mask usually add on top of the background - Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0 } + } + + /// How the effect blends on `channel` of its layer's content, or on its mask (`None`) + pub fn blend_of(&self, channel: Option) -> ChannelBlend { + let shared = ChannelBlend { mode: self.blend, opacity: self.opacity }; + channel.and_then(|channel| self.channel_blends.get(&channel).copied()).unwrap_or(shared) } } @@ -1559,6 +1712,12 @@ mod tests { assert_eq!(effect.images_read().collect::>(), vec!["material.png"]); } + #[test] + let mut selection = crate::ColorSelection::new(Vec::new(), 0.0); + selection.id_map = Some("id.png".into()); + + } + #[test] fn generator_offset_shifts_the_mask_value() { let mut g = Generator::new(GeneratorKind::Position); @@ -1648,7 +1807,7 @@ mod tests { #[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 }; + let l = Levels { in_low: 0.2, in_high: 0.6, clamp: true, ..Levels::default() }; assert!((l.apply(0.4) - 0.5).abs() < 1e-6); assert_eq!(l.apply(0.0), 0.0); assert_eq!(l.apply(1.0), 1.0); @@ -1661,6 +1820,18 @@ mod tests { assert!(d.apply(0.7).is_finite()); } + #[test] + fn unclamped_levels_carry_on_past_the_input_handles() { + let clamped = Levels { in_low: 0.2, in_high: 0.6, clamp: true, ..Levels::default() }; + let open = Levels { clamp: false, ..clamped }; + assert_eq!(clamped.apply(0.0), 0.0); + assert!((open.apply(0.0) + 0.5).abs() < 1e-6, "0.2 below the black handle is half a range below black"); + assert!((open.apply(0.8) - 1.5).abs() < 1e-6); + assert!((open.apply(0.4) - clamped.apply(0.4)).abs() < 1e-6, "between the handles both remap alike"); + let bent = Levels { gamma: 2.0, ..open }; + assert!((bent.apply(0.0) + 0.5).abs() < 1e-6, "gamma bends only the part between the handles"); + } + #[test] fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { let fills = [ @@ -1679,6 +1850,9 @@ mod tests { let effects = [ r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, + r#"{"Levels":{"in_low":0.2,"in_high":0.6,"gamma":1.0,"out_low":0.0,"out_high":1.0}}"#, + r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#, + r#"{"ColorSelection":{"colors":[[1.0,0.0,0.0]],"tolerance":0.1}}"#, r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, ]; for saved in effects { @@ -1688,6 +1862,23 @@ mod tests { } } + #[test] + fn levels_saved_before_the_channel_and_clamp_load_as_they_rendered() { + let saved = serde_json::json!({"in_low": 0.2, "in_high": 0.6, "gamma": 1.0, "out_low": 0.0, "out_high": 1.0}); + let loaded: Levels = serde_json::from_value(saved.clone()).unwrap(); + assert!(loaded.clamp, "they stopped at the output ends"); + assert_eq!(loaded.affects, None, "they remapped every channel"); + assert!(Channel::ALL.iter().all(|&channel| loaded.remaps(channel))); + let saved_again = serde_json::to_value(loaded).unwrap(); + assert!(saved_again.get("affects").is_none(), "no channel is saved, as before: {saved_again}"); + assert!(saved_again.get("clamp").is_none(), "a clamped level is saved as before: {saved_again}"); + assert_eq!(serde_json::from_value::(saved_again).unwrap(), loaded); + let unclamped = serde_json::to_value(Levels { clamp: false, ..loaded }).unwrap(); + assert_eq!(serde_json::from_value::(unclamped).unwrap(), Levels { clamp: false, ..loaded }, "an unclamped level keeps its choice"); + let base = Levels { affects: Some(Channel::BaseColor), ..loaded }; + assert!(base.remaps(Channel::BaseColor) && !base.remaps(Channel::Roughness)); + } + #[test] fn hsl_adjust_shifts_hue_saturation_and_lightness() { let close = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-4); @@ -1711,13 +1902,17 @@ mod tests { let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 }; assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0])); assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3])); + let gm = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] }; assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0])); assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0])); assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing"); + assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); + let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); @@ -1737,6 +1932,7 @@ mod tests { assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0])); + for f in [Filter::Blur { radius: 1.0 }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0 }, Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }] { assert!(f.is_neighbourhood() && f.point(c, [0.5; 3]).is_none()); } @@ -1772,29 +1968,53 @@ mod tests { assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false)); assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); - let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); assert!(!fill_layer.reads_anchor()); - let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }; fill_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })], ..Mask::new(MaskBackground::Black) }); - assert!(fill_layer.reads_anchor()); + let reader = fill_layer.mask.as_ref().map(|mask| &mask.effects[0].kind); + assert!(reader.is_some_and(|reader| reader.reads(Some(LayerId(9))) && reader.reads(None) && !reader.reads(Some(LayerId(8))))); // A generator with micro detail reads its anchor too let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); - assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); + assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9))) && !EffectKind::Generator(generator.clone()).reads(Some(LayerId(8)))); generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); - assert!(generator_layer.reads_anchor()); } + #[test] + fn compare_masks_saved_before_sources_compare_the_mask_with_the_constant_hard() { + let saved = r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#; + let kind: EffectKind = serde_json::from_str(saved).unwrap(); + let EffectKind::Compare { left, right, channel, hardness, .. } = kind else { panic!("{kind:?}") }; + assert_eq!((left, right, channel, hardness), (CompareSource::ThisMask, CompareSource::Constant, Channel::Height, 1.0)); + assert_eq!(serde_json::to_string(&kind).unwrap(), saved, "an unedited compare saves only its op, value and tolerance"); + let round_trip: EffectKind = serde_json::from_str(&serde_json::to_string(&kind).unwrap()).unwrap(); + assert_eq!(round_trip, kind); + } + + #[test] + fn a_hard_compare_is_the_old_step_and_a_soft_one_ramps() { + // Hardness 1 keeps the strict comparisons compare masks always made + for (left, right) in [(0.4, 0.5), (0.5, 0.5), (0.6, 0.5), (f32::NAN, 0.5)] { + let step = |pass: bool| if pass { 1.0 } else { 0.0 }; + assert_eq!(CompareOp::GreaterThan.mask(left, right, 0.1, 1.0), step(left > right)); + assert_eq!(CompareOp::LesserThan.mask(left, right, 0.1, 1.0), step(left < right)); + assert_eq!(CompareOp::WithinTolerance.mask(left, right, 0.05, 1.0), step((left - right).abs() <= 0.05)); + } + assert!((CompareOp::GreaterThan.mask(0.55, 0.5, 0.1, 0.9) - 0.5).abs() < 1e-5, "halfway up a 0.1 ramp"); + assert_eq!(CompareOp::GreaterThan.mask(0.45, 0.5, 0.1, 0.0), 0.0, "below the edge stays 0 however soft"); + assert_eq!(CompareOp::GreaterThan.mask(0.6, 0.5, 0.1, f32::NAN), 1.0, "a NaN hardness compares hard"); + assert!((CompareOp::WithinTolerance.mask(0.65, 0.5, 0.1, 0.9) - 0.5).abs() < 1e-5, "0.05 past the tolerance"); + } + #[test] fn height_mask_keeps_the_ends_and_follows_height() { let off = HeightMask::default(); diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 1c877b7b..c1fc86f6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,6 +12,9 @@ pub mod bake; pub mod blend; mod block_scales; pub mod channel; +pub mod color_selection; +pub mod compare_source; +pub mod contents_offset; pub mod cook_resolution; pub mod depth_culling; mod env_alignment; @@ -22,6 +25,7 @@ pub mod projector; pub mod randomized_seed; mod saved_decal; mod saved_projection; +pub mod selection_background; mod shadow_mode; pub mod shape_crop; pub mod symmetry_kind; @@ -39,6 +43,9 @@ pub use bake::{ }; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use color_selection::ColorSelection; +pub use compare_source::CompareSource; +pub use contents_offset::ContentsOffset; pub use cook_resolution::CookResolution; pub use depth_culling::DepthCulling; pub use fill_symmetry::FillSymmetry; @@ -54,6 +61,7 @@ pub use project::{ }; pub use projector::Projector; pub use randomized_seed::RandomizedSeed; +pub use selection_background::SelectionBackground; pub use shape_crop::ShapeCrop; pub use symmetry_kind::SymmetryKind; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index df5aa54a..794a5915 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -641,6 +641,21 @@ impl Project { self.layers.values().find_map(|l| l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()).find(|e| e.id == id).map(|e| (l.id, e))) } + /// What reads anchor point `anchor`, bottom to top in its texture set: (layer, the effect reading it, or None for the layer's own fill) + pub fn anchor_readers(&self, anchor: LayerId) -> Vec<(LayerId, Option)> { + let Some((ts, _, _)) = self.effect(anchor).and_then(|(owner, _)| self.locate(owner)) else { return Vec::new() }; + let mut out = Vec::new(); + for layer in self.walk(ts).into_iter().filter_map(|(id, _)| self.layers.get(&id)) { + if let LayerKind::Fill(fill) = &layer.kind + && fill.sources.values().any(|s| s.anchor() == Some(anchor)) + { + out.push((layer.id, None)); + } + let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()); + } + out + } + pub fn effect_mut(&mut self, id: LayerId) -> Option<&mut Effect> { self.layers.values_mut().find_map(|l| { let in_mask = l.mask.as_mut().and_then(|m| m.effects.iter_mut().find(|e| e.id == id)); @@ -712,6 +727,27 @@ impl Project { self.layers.values().filter_map(|l| Some((l.id, l.instance_source()?))).find(|(id, s)| self.render_tree(&[*s]).contains(id)).map(|(id, _)| id) } + /// The Scale and Rotation folder `id` lays on the fills inside it (none for any other layer) + pub fn contents_offset(&self, id: LayerId) -> ContentsOffset { + match self.layers.get(&id).map(|l| &l.kind) { + Some(LayerKind::Group { contents, .. }) => *contents, + _ => ContentsOffset::NONE, + } + } + + /// The Scale and Rotation the folders holding layer `id` lay on its fills, combined from the outermost in + pub fn contents_around(&self, id: LayerId) -> ContentsOffset { + let mut folders = Vec::new(); + let mut at = id; + while folders.len() <= MAX_DEPTH + && let Some((_, Some(parent), _)) = self.locate(at) + { + folders.push(parent); + at = parent; + } + folders.iter().rev().fold(ContentsOffset::NONE, |around, folder| around.then(self.contents_offset(*folder))) + } + /// The layer whose content `id` draws: itself, or an instance's source. pub fn content_layer(&self, id: LayerId) -> Option<&Layer> { let mut l = self.layers.get(&id)?; @@ -762,25 +798,19 @@ mod tests { let b = paint(&mut p, "b"); let b = p.insert_layer(0, b, None, false).unwrap(); let gid = p.alloc_id(); - let g = Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &Channel::DEFAULT_SET); + let g = Layer::new(gid, "g", LayerKind::folder(), &Channel::DEFAULT_SET); p.insert_layer(0, g, Some(a), false).unwrap(); - assert_eq!(p.texture_sets[0].stack, vec![a, gid, b]); - p.move_above(b, Some(gid), true).unwrap(); - assert_eq!(p.texture_sets[0].stack, vec![a, gid]); assert_eq!(p.layer(gid).unwrap().children(), &[b]); assert_eq!(p.locate(b), Some((0, Some(gid), 0))); assert!(p.move_above(gid, Some(b), true).is_err(), "a group cannot go inside itself"); - p.validate().unwrap(); let removed = p.remove_layer(gid).unwrap(); - assert_eq!(removed, vec![gid, b]); assert_eq!(p.texture_sets[0].stack, vec![a]); assert!(p.layer(b).is_err()); - p.validate().unwrap(); } @@ -844,10 +874,15 @@ mod tests { p.insert_layer(0, top, Some(id), false).unwrap(); let json = serde_json::to_string(&p).unwrap(); let back: Project = serde_json::from_str(&json).unwrap(); - assert_eq!(back, p); assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id)); + // The mask fill of the layer above reads it + let top = back.layers.values().find(|l| l.name == "y").unwrap(); + let reader = top.mask.as_ref().unwrap().effects[0].id; + assert_eq!(back.anchor_readers(anchor), vec![(top.id, Some(reader))]); + assert!(back.anchor_readers(LayerId(999)).is_empty()); + // Projects saved before content effects existed load with empty stacks let mut v: serde_json::Value = serde_json::from_str(&json).unwrap(); for l in v["layers"].as_object_mut().unwrap().values_mut() { @@ -866,23 +901,49 @@ mod tests { let a = p.insert_layer(0, a, None, false).unwrap(); let inst = Layer::new(p.alloc_id(), "a", LayerKind::Instance { source: a }, &[]); let inst = p.insert_layer(1, inst, None, false).unwrap(); - assert_eq!(p.content_layer(inst).map(|l| l.id), Some(a)); assert_eq!(p.sets_drawing(a), vec![0, 1]); assert_eq!(p.sets_drawing(inst), vec![1]); - p.validate().unwrap(); - // A folder holding an instance of itself draws itself + // A folder holding an instance of itself draws itself. let gid = p.alloc_id(); - p.insert_layer(1, Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &[]), None, false).unwrap(); + p.insert_layer(1, Layer::new(gid, "g", LayerKind::folder(), &[]), None, false).unwrap(); let loop_id = p.alloc_id(); p.insert_layer(1, Layer::new(loop_id, "g", LayerKind::Instance { source: gid }, &[]), Some(gid), true).unwrap(); - assert_eq!(p.instance_cycle(), Some(loop_id)); assert!(p.validate().is_err()); assert!(p.content_layer(LayerId(999)).is_none()); } + #[test] + fn folder_offsets_load_as_none_from_old_saves_save_only_when_set_and_combine_inward() { + let mut p = project(); + let folder = |p: &mut Project, contents: ContentsOffset| { + Layer::new(p.alloc_id(), "g", LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, &[]) + }; + let outer = folder(&mut p, ContentsOffset::new(2.0, 30.0)); + let outer = p.insert_layer(0, outer, None, false).unwrap(); + let inner = folder(&mut p, ContentsOffset::new(1.5, -10.0)); + let inner = p.insert_layer(0, inner, Some(outer), true).unwrap(); + let a = paint(&mut p, "a"); + let a = p.insert_layer(0, a, Some(inner), true).unwrap(); + let top = paint(&mut p, "top"); + let top = p.insert_layer(0, top, None, false).unwrap(); + assert_eq!(p.contents_around(a), ContentsOffset { scale: 3.0, rotation: 20.0 }); + assert_eq!(p.contents_around(inner), ContentsOffset::new(2.0, 30.0)); + assert_eq!( + (p.contents_around(outer), p.contents_around(top), p.contents_offset(a)), + (ContentsOffset::NONE, ContentsOffset::NONE, ContentsOffset::NONE) + ); + + // A folder saved before folders had an offset has none, and one without an offset saves as before + let old: LayerKind = serde_json::from_str(r#"{"Group":{"children":[],"collapsed":true}}"#).unwrap(); + assert_eq!(old, LayerKind::Group { children: vec![], collapsed: true, contents: ContentsOffset::NONE, randomized: Vec::new() }); + assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"Group":{"children":[],"collapsed":true}}"#); + let saved = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&saved).unwrap().contents_around(a), p.contents_around(a)); + } + #[test] fn tile_grids_map_mesh_uvs_to_atlas_blocks() { assert_eq!(TileGrid::of(&[]), None); diff --git a/crates/core/src/selection_background.rs b/crates/core/src/selection_background.rs new file mode 100644 index 00000000..1661ecf2 --- /dev/null +++ b/crates/core/src/selection_background.rs @@ -0,0 +1,58 @@ +//! What a color selection gives the parts it does not select + +use serde::{Deserialize, Serialize}; + +/// The value a color selection gives outside its colors; transparent leaves the mask below as it is +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SelectionBackground { + Transparent, + /// What color selections did before the choice existed + #[default] + Black, + White, + Gray, +} + +impl SelectionBackground { + /// Menu order + pub const ALL: [SelectionBackground; 4] = + [SelectionBackground::Transparent, SelectionBackground::Black, SelectionBackground::White, SelectionBackground::Gray]; + + /// Whether it is what selections saved before the choice had (not saved then) + pub fn is_default(&self) -> bool { + *self == SelectionBackground::default() + } + + /// Command id + pub fn id(self) -> &'static str { + match self { + SelectionBackground::Transparent => "transparent", + SelectionBackground::Black => "black", + SelectionBackground::White => "white", + SelectionBackground::Gray => "gray", + } + } + + pub fn from_id(id: &str) -> Option { + SelectionBackground::ALL.into_iter().find(|background| background.id() == id) + } + + pub fn label(self) -> &'static str { + match self { + SelectionBackground::Transparent => "Transparent", + SelectionBackground::Black => "Black", + SelectionBackground::White => "White", + SelectionBackground::Gray => "Gray", + } + } + + /// The gray it gives, none for transparent + pub fn value(self) -> Option { + match self { + SelectionBackground::Transparent => None, + SelectionBackground::Black => Some(0.0), + SelectionBackground::White => Some(1.0), + SelectionBackground::Gray => Some(0.5), + } + } +} diff --git a/crates/engine/src/add_mask_cmds.rs b/crates/engine/src/add_mask_cmds.rs new file mode 100644 index 00000000..ee2e8404 --- /dev/null +++ b/crates/engine/src/add_mask_cmds.rs @@ -0,0 +1,65 @@ +//! The layer toolbar's Add mask items that add a mask with an effect in it (a bitmap, a height combination) and Add effect's colour selection + +use serde_json::Value; +use texturecraft_core::{BlendMode, EffectKind, Sampling, Source}; +use texturecraft_paint::alphas; + +use crate::commands::{CommandSpec, bad, has_layer, strp}; +use crate::mask_cmds::{color_selection, mask_target, new_compare, push_effect_as, push_own_mask_effect}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "mask.add.bitmap", + "Add bitmap mask", + ["Layers", "Mask"], + None, + "{layer?, image: image resource name | alpha: library alpha id or name (its picture becomes the image resource alpha_.png), projection? (see effect.add.fill)} → {effect} — a mask fill reading the image's gray, in the layer's mask (a new black one if it has none); selected", + has_layer, + add_bitmap + ), + cmd!( + "mask.add.heightCombination", + "Add mask with height combination", + ["Layers", "Mask"], + None, + "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected", + has_layer, + |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |_| Ok(())) + ), + cmd!( + "effect.add.colorSelection", + "Add color selection", + ["Layers", "Effects"], + None, + "{layer?, color?: a first ID color as [r,g,b] linear or \"#rrggbb\" sRGB (default: none), tolerance?} → {effect} — in the layer's mask (a new black one if it has none; colour selections go on masks only); selected", + has_layer, + |s, p| push_effect_as(s, &mask_target(p), color_selection("effect.add.colorSelection", p)?, BlendMode::Normal, "Add color selection") + ), + ] +} + +/// A mask fill reading an image resource or a library alpha, in one undo step with the alpha's resource +fn add_bitmap(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "mask.add.bitmap"; + let (name, library) = match (strp(p, "image"), strp(p, "alpha")) { + (Some(_), Some(_)) => return Err(bad(CMD, "give `image` or `alpha`, not both")), + (Some(image), None) => { + if !s.images.contains_key(image) { + return Err(bad(CMD, format!("no image resource `{image}` (import it first)"))); + } + + (image.to_owned(), None) + } + (None, Some(alpha)) => { + let alpha = alphas::find(alpha).ok_or_else(|| bad(CMD, format!("unknown alpha `{alpha}`")))?; + (crate::fill_alpha::resource_name(alpha), Some(alpha)) + } + (None, None) => return Err(bad(CMD, "`image` or `alpha` is required")), + }; + let projection = crate::layer_cmds::projection_from(p, CMD, None, || crate::warp_cmds::fitted_frame(&s.mesh))?; + let kind = EffectKind::Fill { source: Source::Image { name, normal_format: Default::default() }, projection, sampling: Sampling::default() }; + let add_library = |s: &mut Session| library.map_or(Ok(()), |alpha| s.add_library_alpha(alpha).map(|_| ())); + push_own_mask_effect(s, p, kind, "Add bitmap mask", add_library) +} diff --git a/crates/engine/src/color_selection_cmds.rs b/crates/engine/src/color_selection_cmds.rs index 2b9f9eaf..7e7e53be 100644 --- a/crates/engine/src/color_selection_cmds.rs +++ b/crates/engine/src/color_selection_cmds.rs @@ -1,11 +1,11 @@ //! Color selection effects: the ID colors they select, picked from the ID mesh map use serde_json::{Value, json}; -use texturecraft_core::{BakedMap, EffectKind, LayerId}; +use texturecraft_core::{BakedMap, ColorSelection, EffectKind, LayerId, SelectionBackground}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::surface_at; -use crate::commands::{CommandSpec, bad, f32p, has_layer}; +use crate::commands::{CommandSpec, bad, f32p, has_layer, strp}; use crate::mask_cmds::effect_id; use crate::tool_cmds::viewport_of; use crate::{Result, Session, cmd}; @@ -25,23 +25,45 @@ pub fn specs() -> Vec { )] } -/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection -pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> { +/// Applies `effect.set`'s color selection params; `id_map` is the checked `idMap` ([`id_map_param`]) +pub(crate) fn apply_params(params: &Value, selection: &mut ColorSelection, id_map: Option>) -> Result<()> { + const CMD: &str = "effect.set"; if let Some(list) = params.get("colors") { - *colors = colors_param(list)?; + selection.colors = colors_param(list)?; } - if let Some(value) = f32p(params, "tolerance") { - *tolerance = value.clamp(0.0, 1.0); + for (key, value) in [("tolerance", &mut selection.tolerance), ("output", &mut selection.output), ("hardness", &mut selection.hardness)] { + if let Some(given) = f32p(params, key) { + *value = given.clamp(0.0, 1.0); + } + } + if let Some(id) = strp(params, "background") { + selection.background = + SelectionBackground::from_id(id).ok_or_else(|| bad(CMD, format!("unknown background \"{id}\": transparent, black, white or gray")))?; + } + if let Some(id_map) = id_map { + selection.id_map = id_map; } Ok(()) } -/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1 +/// `effect.set`'s `idMap`: absent, null (the ID mesh map) or the name of an image resource +pub(crate) fn id_map_param(session: &Session, params: &Value) -> Result>> { + const CMD: &str = "effect.set"; + match params.get("idMap") { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(Value::String(name)) if session.images.contains_key(name) => Ok(Some(Some(name.clone()))), + Some(Value::String(name)) => Err(bad(CMD, format!("no image resource \"{name}\": import it first"))), + Some(_) => Err(bad(CMD, "`idMap` must be an image resource name or null")), + } +} + +/// A `[[r, g, b], ...]` list (empty selects nothing) of finite values, clamped to 0..1 fn colors_param(list: &Value) -> Result> { const CMD: &str = "effect.set"; let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?; - if items.is_empty() || items.len() > MAX_SELECTED_COLORS { - return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors"))); + if items.len() > MAX_SELECTED_COLORS { + return Err(bad(CMD, format!("`colors` holds at most {MAX_SELECTED_COLORS} colors"))); } items @@ -57,9 +79,9 @@ fn colors_param(list: &Value) -> Result> { fn pick(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.colorSelection.pick"; let effect = effect_id(session, params, CMD)?; - let (owner, color_count) = match session.doc.project.effect(effect) { + let (owner, color_count, id_map) = match session.doc.project.effect(effect) { Some((owner, found)) => match &found.kind { - EffectKind::ColorSelection { colors, .. } => (owner, colors.len()), + EffectKind::ColorSelection(selection) => (owner, selection.colors.len(), selection.id_map.clone()), other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))), }, None => return Err(bad(CMD, format!("no effect {}", effect.0))), @@ -76,13 +98,13 @@ fn pick(session: &mut Session, params: &Value) -> Result { None => None, }; - let color = id_color_at(session, params, owner)?; + let color = id_color_at(session, params, owner, id_map.as_deref())?; session.edit("Pick ID color", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; - if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind { - match index.and_then(|index| colors.get_mut(index)) { + if let EffectKind::ColorSelection(selection) = &mut edited.kind { + match index.and_then(|index| selection.colors.get_mut(index)) { Some(slot) => *slot = color, - None => colors.push(color), + None => selection.colors.push(color), } } Ok(()) @@ -90,15 +112,19 @@ fn pick(session: &mut Session, params: &Value) -> Result { Ok(json!({ "color": color, "index": index.unwrap_or(color_count) })) } -/// The ID map color of the texel a color selection on `owner` reads at the picked point -fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> { +/// The ID map color of the texel a color selection on `owner` reading `id_map` (none: the ID mesh map) reads at the picked point +fn id_color_at(session: &Session, params: &Value, owner: LayerId, id_map: Option<&str>) -> Result<[f32; 3]> { const CMD: &str = "effect.colorSelection.pick"; let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?; let set = session.doc.project.texture_set(set_index)?; let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id)); - let Some(baked) = baked else { - return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name))); + let image = match id_map { + Some(name) => Some(session.images.get(name).ok_or_else(|| bad(CMD, format!("the ID map image \"{name}\" is gone: choose another")))?), + None => None, }; + if image.is_none() && baked.is_none() { + return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name))); + } let uv = match params.get("uv") { Some(uv) => uv_param(uv)?, @@ -122,7 +148,17 @@ fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32 if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) { return Err(bad(CMD, "that point is outside the texture set's UV space")); } - baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there")) + let (x, y) = (texel[0] as u32, texel[1] as u32); + let color = match (image, baked) { + (Some(image), _) => { + // The texel's centre, as the mask reads it + let [red, green, blue, _] = image.sample_nearest((x as f32 + 0.5) / size.0.max(1) as f32, (y as f32 + 0.5) / size.1.max(1) as f32); + Some([red, green, blue]) + } + (None, Some(baked)) => baked.sample_working(BakedMap::Id, x, y, size, &set.block_scales()), + (None, None) => None, + }; + color.ok_or_else(|| bad(CMD, "no ID color there")) } /// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray diff --git a/crates/engine/src/effect_blending_cmds.rs b/crates/engine/src/effect_blending_cmds.rs new file mode 100644 index 00000000..2d46fde0 --- /dev/null +++ b/crates/engine/src/effect_blending_cmds.rs @@ -0,0 +1,203 @@ +//! An effect's blending per channel: the Blending options of an effect row (one channel's blending on every channel, copy and paste) + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_core::{BlendMode, Channel, ChannelBlend, Effect, LayerId, Project}; + +use crate::commands::{CommandSpec, bad, channel_param, has_layer}; +use crate::mask_cmds::effect_id; +use crate::session::StackTarget; +use crate::{Result, Session, cmd}; + +/// The undo step of every Blending options command +const UNDO_LABEL: &str = "Blending options"; + +/// What a copy of channel blending holds: the blending shared by the channels, and the channels that blend apart +pub type CopiedBlending = (ChannelBlend, BTreeMap); + +pub fn specs() -> Vec { + vec![ + cmd!( + "effect.blending.modeToEveryChannel", + "Use this blend mode on every channel", + [], + None, + "{effect?: the selected content effect, channel?: the channel whose blend mode every channel takes (default baseColor)}", + content_effect_selected, + mode_to_every_channel + ), + cmd!( + "effect.blending.opacityToEveryChannel", + "Use this opacity on every channel", + [], + None, + "{effect?: the selected content effect, channel?: the channel whose opacity every channel takes (default baseColor)}", + content_effect_selected, + opacity_to_every_channel + ), + cmd!( + "effect.blending.bothToEveryChannel", + "Use both on every channel", + [], + None, + "{effect?: the selected content effect, channel?: the channel whose blend mode and opacity every channel takes (default baseColor)}", + content_effect_selected, + both_to_every_channel + ), + cmd!( + "effect.blending.copy", + "Copy channel blending", + [], + None, + "{effect?: the selected effect} — every channel's blend mode and opacity", + blending_effect_selected, + copy + ), + cmd!( + "effect.blending.paste", + "Paste channel blending", + [], + None, + "{effect?: the selected effect} — the copied blend modes and opacities (a mask effect takes the shared ones)", + can_paste, + paste + ), + ] +} + +/// Sets `effect`'s blend `mode` and `opacity` where given: on `channel` alone, or on every channel (`None`, a mask effect's only one); channels left blending like the others stop blending apart +pub fn set_blending(effect: &mut Effect, channel: Option, mode: Option, opacity: Option) { + let edit = |blend: &mut ChannelBlend| { + if let Some(mode) = mode { + blend.mode = mode; + } + if let Some(opacity) = opacity { + blend.opacity = opacity.clamp(0.0, 1.0); + } + }; + match channel { + Some(channel) => { + let mut blend = effect.blend_of(Some(channel)); + edit(&mut blend); + effect.channel_blends.insert(channel, blend); + } + None => { + let mut shared = effect.blend_of(None); + edit(&mut shared); + effect.blend = shared.mode; + effect.opacity = shared.opacity; + effect.channel_blends.values_mut().for_each(edit); + } + } + let shared = effect.blend_of(None); + effect.channel_blends.retain(|_, blend| *blend != shared); +} + +/// Whether effect `id` is in a layer's mask (it then blends one channel) +pub fn on_mask(project: &Project, id: LayerId) -> bool { + project.layers.values().any(|layer| layer.mask.as_ref().is_some_and(|mask| mask.effects.iter().any(|effect| effect.id == id))) +} + +/// Whether the selected effect has blending (and with `content_only`, is a content effect); with no effect selected, a command names its effect +fn selected_blending_effect(s: &Session, content_only: bool) -> std::result::Result<(), String> { + let StackTarget::Effect(id) = s.target else { return has_layer(s) }; + let Some((_, effect)) = s.doc.project.effect(id) else { return has_layer(s) }; + blending_refusal(&s.doc.project, id, effect, content_only) +} + +/// Why effect `id` (`effect`) can't take a Blending options command: it has no blending or, with `content_only`, it is a mask effect +fn blending_refusal(project: &Project, id: LayerId, effect: &Effect, content_only: bool) -> std::result::Result<(), String> { + if !effect.kind.blends() { + return Err(format!("{} has no blending", effect.kind.name().to_ascii_lowercase())); + } + + if content_only && on_mask(project, id) { + return Err("a mask effect blends one channel".into()); + } + + Ok(()) +} + +fn content_effect_selected(s: &Session) -> std::result::Result<(), String> { + selected_blending_effect(s, true) +} + +fn blending_effect_selected(s: &Session) -> std::result::Result<(), String> { + selected_blending_effect(s, false) +} + +fn can_paste(s: &Session) -> std::result::Result<(), String> { + if s.blending_clipboard.is_none() { + return Err("no channel blending is copied".into()); + } + + blending_effect_selected(s) +} + +/// Effect `effect` (or the selected one) of command `cmd`, checked to have blending and, with `content_only`, to be a content effect +fn blending_effect(s: &Session, p: &Value, cmd: &str, content_only: bool) -> Result { + let id = effect_id(s, p, cmd)?; + let (_, effect) = s.doc.project.effect(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + blending_refusal(&s.doc.project, id, effect, content_only).map_err(|refusal| bad(cmd, refusal))?; + Ok(id) +} + +/// Every channel of the content effect in `p` takes what `copied` picks (a blend mode, an opacity or both) from the `channel` in `p` +fn to_every_channel(s: &mut Session, p: &Value, cmd: &str, copied: fn(ChannelBlend) -> (Option, Option)) -> Result { + let id = blending_effect(s, p, cmd, true)?; + let channel = channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor); + let (_, current) = s.doc.project.effect(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + let mut changed = current.clone(); + let (mode, opacity) = copied(changed.blend_of(Some(channel))); + set_blending(&mut changed, None, mode, opacity); + replace_blending(s, id, cmd, changed) +} + +/// Effect `id` replaced by `changed`, in one undo step; no step when nothing changes +fn replace_blending(s: &mut Session, id: LayerId, cmd: &str, changed: Effect) -> Result { + let (_, current) = s.doc.project.effect(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + if *current == changed { + return Ok(Value::Null); + } + + s.edit(UNDO_LABEL, |s| { + let effect = s.doc.project.effect_mut(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + *effect = changed; + Ok(()) + })?; + Ok(Value::Null) +} + +fn mode_to_every_channel(s: &mut Session, p: &Value) -> Result { + to_every_channel(s, p, "effect.blending.modeToEveryChannel", |source| (Some(source.mode), None)) +} + +fn opacity_to_every_channel(s: &mut Session, p: &Value) -> Result { + to_every_channel(s, p, "effect.blending.opacityToEveryChannel", |source| (None, Some(source.opacity))) +} + +fn both_to_every_channel(s: &mut Session, p: &Value) -> Result { + to_every_channel(s, p, "effect.blending.bothToEveryChannel", |source| (Some(source.mode), Some(source.opacity))) +} + +fn copy(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.blending.copy"; + let id = blending_effect(s, p, CMD, false)?; + let (_, effect) = s.doc.project.effect(id).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?; + s.blending_clipboard = Some((effect.blend_of(None), effect.channel_blends.clone())); + Ok(json!({ "copied": id.0 })) +} + +fn paste(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.blending.paste"; + let (shared, channels) = s.blending_clipboard.clone().ok_or_else(|| bad(CMD, "no channel blending is copied"))?; + let id = blending_effect(s, p, CMD, false)?; + let mask = on_mask(&s.doc.project, id); + let (_, current) = s.doc.project.effect(id).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?; + let mut changed = current.clone(); + changed.blend = shared.mode; + changed.opacity = shared.opacity; + changed.channel_blends = if mask { BTreeMap::new() } else { channels }; + replace_blending(s, id, CMD, changed) +} diff --git a/crates/engine/src/fill_material_cmds.rs b/crates/engine/src/fill_material_cmds.rs index 77d538b1..c4141934 100644 --- a/crates/engine/src/fill_material_cmds.rs +++ b/crates/engine/src/fill_material_cmds.rs @@ -46,6 +46,7 @@ fn set_material(s: &mut Session, p: &Value) -> Result { // A fill effect changes a channel while it has a source: its channels stay on, at their defaults FillTarget::Effect(_) => edited.sources.iter_mut().for_each(|(channel, source)| *source = Source::uniform_of(*channel)), FillTarget::Layer(_) => edited.sources.clear(), + FillTarget::Layer(_) | FillTarget::Mask(_) => edited.sources.clear(), } Ok(()) })?; @@ -101,6 +102,7 @@ fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMat Some(EffectKind::Material(fill)) => (fill, None), _ => return Err(bad(CMD, "not a content fill effect")), }, + FillTarget::Mask(_) => return Err(bad(CMD, "a mask fill has one grayscale source and no channels or material")), }; if fill.material.as_deref() != material.map(|found| found.id) { return Ok(false); @@ -125,6 +127,9 @@ fn target_set(s: &Session, target: FillTarget) -> Result { let owner = match target { FillTarget::Layer(id) => id, FillTarget::Effect(id) => s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?, + FillTarget::Effect(id) | FillTarget::Mask(id) => { + s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))? + } }; s.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0))) } diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index 6d50a4c4..5c1d4c6d 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -14,6 +14,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", + "{layer? | effect?: content or mask fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", has_layer, reset_projection )] diff --git a/crates/engine/src/id_mask_view.rs b/crates/engine/src/id_mask_view.rs new file mode 100644 index 00000000..d7d58e85 --- /dev/null +++ b/crates/engine/src/id_mask_view.rs @@ -0,0 +1,43 @@ +//! The view a color selection picks from while its ID Mask is an image chosen by hand: that image laid on its texture set as the mask reads it + +use std::sync::Arc; + +use texturecraft_compose::ImageRes; +use texturecraft_core::{EffectKind, LayerId}; + +use crate::Session; + +impl Session { + /// The texture set of color selection `effect` and the image it reads as its ID mask (None for another effect, the ID mesh map or a missing image) + pub fn id_mask_image(&self, effect: LayerId) -> Option<(usize, &Arc)> { + let (owner, found) = self.doc.project.effect(effect)?; + let EffectKind::ColorSelection(selection) = &found.kind else { return None }; + let image = self.images.get(selection.id_map.as_deref()?)?; + let (texture_set, _, _) = self.doc.project.locate(owner)?; + Some((texture_set, image)) + } + + /// RGBA8 of [`Session::id_mask_image`] on its texture set at `size²`, the stored values unconverted like the ID mesh map's view + pub fn id_mask_view_rgba(&self, effect: LayerId, size: u32) -> Option> { + let (texture_set, image) = self.id_mask_image(effect)?; + let (width, height) = self.doc.project.texture_sets.get(texture_set)?.size(); + let size = size.max(1); + + // Each view pixel shows the color its texture set texel reads, sampled at that texel's centre as the mask and a pick do + let texel_centre = |pixel: u32, extent: u32| { + let extent = extent.max(1); + let texel = ((pixel as f32 + 0.5) / size as f32 * extent as f32).floor().min((extent - 1) as f32); + (texel + 0.5) / extent as f32 + }; + let mut rgba = Vec::with_capacity(size as usize * size as usize * 4); + for y in 0..size { + let v = texel_centre(y, height); + for x in 0..size { + let color = image.sample_nearest(texel_centre(x, width), v); + rgba.extend(color[..3].iter().map(|value| (value.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); + rgba.push(u8::MAX); + } + } + Some(rgba) + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 3f16e843..87ccb68e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -69,15 +69,39 @@ fn placement_json(projection: &Projection, sampling: &Sampling, out: &mut Value) /// A mask or content (`content`) effect 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 }); + if !effect.channel_blends.is_empty() { + let channels = + effect.channel_blends.iter().map(|(channel, blend)| (channel.id().to_string(), json!({ "blend": blend.mode.label(), "opacity": blend.opacity }))); + out["channelBlends"] = Value::Object(channels.collect()); + } 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::ColorSelection { colors, tolerance } => { - out["colors"] = json!(colors); - out["tolerance"] = json!(tolerance); + EffectKind::Levels(levels) => { + out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]); + out["affects"] = levels.affects.map_or(json!("all"), |channel| json!(channel.id())); + out["clamp"] = json!(levels.clamp); + } + EffectKind::ColorSelection(selection) => { + out["colors"] = json!(selection.colors); + out["tolerance"] = json!(selection.tolerance); + out["output"] = json!(selection.output); + out["hardness"] = json!(selection.hardness); + out["background"] = json!(selection.background.id()); + out["idMap"] = json!(selection.id_map); + } + EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { + out["compare"] = json!({ + "left": left.id(), + "op": op.id(), + "right": right.id(), + "compareChannel": channel.id(), + "value": value, + "tolerance": tolerance, + "hardness": hardness, + }); } EffectKind::Path(paths) => { out["paths"] = json!( @@ -100,7 +124,15 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { _ => {} } } - _ => {} + EffectKind::Anchor => { + let readers = session + .doc + .project + .anchor_readers(effect.id) + .into_iter() + .map(|(layer, reader)| json!({ "layer": layer.0, "effect": reader.map(|reader| reader.0) })); + out["references"] = Value::Array(readers.collect()); + } } out } @@ -167,6 +199,11 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { if !l.content_effects.is_empty() { v["contentEffects"] = json!(l.content_effects.iter().map(|e| effect_json(s, e, true)).collect::>()); } + if let LayerKind::Group { contents, .. } = &l.kind + && !contents.is_none() + { + v["contents"] = json!({ "scale": contents.scale, "rotation": contents.rotation }); + } if depth < texturecraft_core::project::MAX_DEPTH { let kids: Vec = l.children().iter().rev().filter_map(|c| s.doc.project.layers.get(c)).map(|c| layer_json(s, c, depth + 1)).collect(); if l.is_group() { diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index b8b2ae93..dbdac206 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -7,6 +7,7 @@ use texturecraft_core::{ Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; use texturecraft_paint::alphas; +use texturecraft_paint::alphas::{self, LibraryAlpha}; use crate::commands::{ CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, normal_format_param, strp, u64p, @@ -35,6 +36,9 @@ const MAX_CORNER_REACH: f32 = 100.0; /// The largest Projection Depth, in lengths of the frame's longer side pub(crate) const MAX_PROJECTION_DEPTH: f32 = 100.0; +/// The `layer.fill.set` keys a one-source grayscale fill (a mask fill or a filter's image input) has no use for +const GRAY_REFUSED_KEYS: [&str; 4] = ["channel", "enabled", "solo", "normalFormat"]; + pub fn specs() -> Vec { vec![ cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint), @@ -128,6 +132,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", + "{layer? | effect?: content or mask fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", has_layer, fill_projection ), @@ -191,11 +196,8 @@ fn add_group(s: &mut Session, p: &Value) -> Result { let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Folder")); let id = s.edit("Add folder", |s| { let id = s.doc.project.alloc_id(); - let mut l = Layer::new(id, name, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels_of(s)); - for b in l.channels.values_mut() { - b.mode = BlendMode::Passthrough; - } - insert_selected(s, l) + let channels = channels_of(s); + insert_selected(s, new_folder(id, name, &channels)) })?; Ok(json!({ "layer": id.0 })) } @@ -258,23 +260,28 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { fn group(s: &mut Session, p: &Value) -> Result { let ids = batch_param(s, "layer.group", p, true)?; - let g = s.edit("Group layers", |s| { + let folder = s.edit("Group layers", |s| { // The folder takes the top layer's place and parent; the others follow it in, in stack order let id = ids.first().copied().ok_or_else(|| bad("layer.group", "no layer to group"))?; let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?; - let gid = s.doc.project.alloc_id(); + let folder = s.doc.project.alloc_id(); let name = s.doc.project.next_layer_name(ts, "Folder"); let channels = s.doc.project.texture_set(ts)?.channel_list(); - let mut gl = Layer::new(gid, name, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); - for b in gl.channels.values_mut() { - b.mode = BlendMode::Passthrough; - } - s.doc.project.insert_layer(ts, gl, Some(id), false)?; - move_stacked(&mut s.doc.project, &ids, Some(gid), true)?; - s.select_one(ts, gid); - Ok(gid) + s.doc.project.insert_layer(ts, new_folder(folder, name, &channels), Some(id), false)?; + move_stacked(&mut s.doc.project, &ids, Some(folder), true)?; + s.select_one(ts, folder); + Ok(folder) })?; - Ok(json!({ "layer": g.0 })) + Ok(json!({ "layer": folder.0 })) +} + +/// An empty folder `id` whose channels pass the blending of its contents through +fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer { + let mut folder = Layer::new(id, name, LayerKind::folder(), channels); + for blend in folder.channels.values_mut() { + blend.mode = BlendMode::Passthrough; + } + folder } fn select(s: &mut Session, p: &Value) -> Result { @@ -518,11 +525,14 @@ pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result match s.doc.project.effect(effect).map(|(_, found)| &found.kind) { Some(EffectKind::Material(_)) => Ok(FillTarget::Effect(effect)), _ => Err(bad(cmd, format!("{} is not a content fill effect", effect.0))), + Some(EffectKind::Fill { .. }) => Ok(FillTarget::Mask(effect)), + _ => Err(bad(cmd, format!("{} is not a fill effect", effect.0))), }, None => Ok(FillTarget::Layer(content_param(s, cmd, p)?)), } } +/// The material of the fill at `target`; a mask fill has none pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { match target { FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind { @@ -533,17 +543,35 @@ pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> Some(EffectKind::Material(f)) => Ok(f), _ => Err(EngineError::Other("not a content fill effect".into())), }, + FillTarget::Mask(_) => Err(EngineError::Other("a mask fill has one grayscale source and no channels or material".into())), } } /// How the fill at `target` is projected and sampled: every fill has both pub(crate) fn placement_mut(s: &mut Session, target: FillTarget) -> Result<(&mut Projection, &mut Sampling)> { + if let FillTarget::Mask(effect) = target { + return match s.doc.project.effect_mut(effect).map(|found| &mut found.kind) { + Some(EffectKind::Fill { projection, sampling, .. }) => Ok((projection, sampling)), + _ => Err(EngineError::Other("not a mask fill effect".into())), + }; + } let fill = fill_mut(s, target)?; Ok((&mut fill.projection, &mut fill.sampling)) } +/// The grayscale source of the mask fill effect `effect` +fn mask_source_mut(s: &mut Session, effect: LayerId) -> Result<&mut Source> { + match s.doc.project.effect_mut(effect).map(|found| &mut found.kind) { + Some(EffectKind::Fill { source, .. }) => Ok(source), + _ => Err(EngineError::Other("not a mask fill effect".into())), + } +} + fn fill_set(session: &mut Session, params: &Value) -> Result { let target = fill_target(session, params, FILL_SET)?; + if let FillTarget::Mask(effect) = target { + return mask_fill_set(session, params, effect); + } let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; @@ -600,6 +628,7 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { let source = with_ramp(channel, current, source, colors)?; match target { + FillTarget::Mask(_) => return Err(bad(FILL_SET, "a mask fill has no channels")), // A fill effect's channel is on while it has a source FillTarget::Effect(_) if enabled == Some(false) => { fill.sources.remove(&channel); @@ -634,6 +663,81 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { Ok(Value::Null) } +/// `layer.fill.set` on mask fill effect `effect`: its one grayscale source (no `channel`, `enabled`, `solo` or `normalFormat`) +fn mask_fill_set(s: &mut Session, p: &Value, effect: LayerId) -> Result { + refuse_gray_keys(p, "a mask fill")?; + + let current = mask_source_mut(s, effect)?.clone(); + let (source, library_alpha) = gray_source(s, p, effect, current.clone())?; + + // Setting what the fill already reads adds no undo step + if source == current && library_alpha_present(s, library_alpha) { + return Ok(Value::Null); + } + + s.edit("Set fill", |s| { + if let Some(alpha) = library_alpha { + s.add_library_alpha(alpha)?; + } + *mask_source_mut(s, effect)? = source; + Ok(()) + })?; + Ok(Value::Null) +} + +/// Refuses the [`GRAY_REFUSED_KEYS`] for `subject`, a fill with one grayscale source +fn refuse_gray_keys(p: &Value, subject: &str) -> Result<()> { + if GRAY_REFUSED_KEYS.iter().any(|key| p.get(key).is_some()) { + let keys = GRAY_REFUSED_KEYS.map(|key| format!("`{key}`")).join(", "); + return Err(bad(FILL_SET, format!("{subject} has one grayscale source: leave out {keys}"))); + } + + Ok(()) +} + +/// Whether the project already holds `library_alpha`'s image (true when there is none to add) +fn library_alpha_present(s: &Session, library_alpha: Option<&LibraryAlpha>) -> bool { + library_alpha.is_none_or(|alpha| s.doc.resources.contains_key(&crate::fill_alpha::resource_name(alpha))) +} + +/// The grayscale source `p` asks for in place of `current` (read by a mask or filter effect `effect`), and the library alpha it needs added +fn gray_source(s: &Session, p: &Value, effect: LayerId, current: Source) -> Result<(Source, Option<&'static LibraryAlpha>)> { + let low = color_param(FILL_SET, p, "low")?; + let high = color_param(FILL_SET, p, "high")?; + let color = color_param(FILL_SET, p, "color")?; + let value = color_param(FILL_SET, p, "value")?; + if let Some(kind) = strp(p, "procedural") { + let kind = ProceduralKind::parse(kind).ok_or_else(|| bad(FILL_SET, format!("unknown procedural `{kind}`")))?; + Ok((procedural_from(p, kind, Some(¤t), [low, high])?, None)) + } else if let Some(gray) = color.or(value) { + Ok((Source::Uniform(gray.map(|component| component.clamp(0.0, 1.0))), None)) + } else if let Some(name) = strp(p, "image") { + Ok((Source::image(name.to_string()), None)) + } else if let Some(name) = strp(p, "alpha") { + let alpha = alphas::find(name).ok_or_else(|| bad(FILL_SET, format!("unknown alpha `{name}`")))?; + Ok((Source::image(crate::fill_alpha::resource_name(alpha)), Some(alpha))) + } else if let Some(anchor) = u64p(p, "anchor") { + let reader = s.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(FILL_SET, "the effect is not in a layer"))?; + + // A gray reads one channel of the anchor's stack: the one it read, else Height + let kept = match current { + Source::Anchor { channel, .. } => channel, + _ => Channel::Height, + }; + let channel = channel_param(FILL_SET, p, "anchorChannel")?.unwrap_or(kept); + Ok((crate::mask_cmds::anchor_source(s, FILL_SET, reader, LayerId(anchor), channel)?, None)) + } else if crate::procedural_params::has_pattern_settings(p) { + // Pattern settings alone edit the current pattern + let Source::Procedural { pattern, .. } = ¤t else { + return Err(bad(FILL_SET, "the source has no pattern: give `procedural` with its settings")); + }; + + Ok((procedural_from(p, pattern.kind, Some(¤t), [None, None])?, None)) + } else { + Err(bad(FILL_SET, "give `value`, `procedural`, `image`, `alpha` or `anchor`")) + } +} + /// The procedural source `params` ask for with `low`/`high` already parsed: a pattern of the same kind as `current` keeps what `params` do not give; another kind starts from its defaults fn procedural_from(params: &Value, kind: ProceduralKind, current: Option<&Source>, [low, high]: [Option<[f32; 3]>; 2]) -> Result { let (mut pattern, current_low, current_high) = match current { @@ -680,7 +784,7 @@ fn fill_source_from( if let Some(anchor) = u64p(params, "anchor") { let reader = match target { FillTarget::Layer(id) => Some(id), - FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), + FillTarget::Effect(effect) | FillTarget::Mask(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), }; let reader = reader.ok_or_else(|| bad(FILL_SET, "the fill is not in a layer"))?; let anchor_channel = channel_param(FILL_SET, params, "anchorChannel")?.unwrap_or(channel); diff --git a/crates/engine/src/layer_cmds/fill_target.rs b/crates/engine/src/layer_cmds/fill_target.rs deleted file mode 100644 index a92e52ec..00000000 --- a/crates/engine/src/layer_cmds/fill_target.rs +++ /dev/null @@ -1,9 +0,0 @@ -use texturecraft_core::LayerId; - -/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's -/// (`effect`). -#[derive(Clone, Copy)] -pub(crate) enum FillTarget { - Layer(LayerId), - Effect(LayerId), -} diff --git a/crates/engine/src/layer_selection.rs b/crates/engine/src/layer_selection.rs index e4012afc..e766fe0e 100644 --- a/crates/engine/src/layer_selection.rs +++ b/crates/engine/src/layer_selection.rs @@ -105,7 +105,7 @@ fn push_rows(project: &Project, list: &[LayerId], expanded_only: bool, depth: us for id in list.iter().rev() { let Some(layer) = project.layers.get(id) else { continue }; rows.push(*id); - if let LayerKind::Group { children, collapsed } = &layer.kind + if let LayerKind::Group { children, collapsed, .. } = &layer.kind && !(expanded_only && *collapsed) { push_rows(project, children, expanded_only, depth + 1, rows); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a8173320..53c87e71 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,6 +8,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod add_mask_cmds; pub mod bake; pub mod bake_preview; pub mod brush_preset_cmds; @@ -15,6 +16,7 @@ pub mod camera_cmds; pub mod color_selection_cmds; pub mod commands; pub mod decal_cmds; +pub mod effect_blending_cmds; pub mod effect_clipboard; pub mod file_cmds; pub mod fill_alpha; @@ -23,7 +25,9 @@ pub mod fill_material_cmds; pub mod fill_mode; pub mod fill_reset_cmds; pub mod filter_lib; +pub mod folder_cmds; mod frame_target; +pub mod id_mask_view; pub mod inspect; pub mod instance_cmds; pub mod layer_cmds; @@ -36,6 +40,7 @@ mod log_level; mod mask_bitmap; pub mod mask_cmds; pub mod mask_export; +mod mask_owner; mod mask_preview_pixel; pub mod material_lib; mod material_preview_pixel; diff --git a/crates/engine/src/mask_owner.rs b/crates/engine/src/mask_owner.rs new file mode 100644 index 00000000..433eea33 --- /dev/null +++ b/crates/engine/src/mask_owner.rs @@ -0,0 +1,8 @@ +//! Whose mask a new mask effect goes in + +/// Whose mask a mask effect goes in: an instance without a mask of its own shares its source's, unless the effect starts the instance's own +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum MaskOwner { + Shared, + Own, +} diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 8a1c2f77..e3638c2f 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -36,7 +36,7 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and their patterns, mask fills and generator inputs) +/// Image resources a layer subtree uses (fill sources and their patterns, mask or content effects and the images its paths paint with) pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; @@ -54,6 +54,7 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.kind.images_read().map(str::to_string)); + out.extend(crate::path_tool::path_images(&effect.kind)); } for child in layer.children() { diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 6640df26..64d8d752 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -842,6 +842,7 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { } else { let folder_id = s.doc.project.alloc_id(); let mut folder = Layer::new(folder_id, material.label, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); + let mut folder = Layer::new(folder_id, material.label, LayerKind::folder(), &channels); for blend in folder.channels.values_mut() { *blend = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; } diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 42909bd9..e6e253da 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use texturecraft_compose::PaintTarget; +use texturecraft_compose::{MaskGray, PaintTarget}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, Source}; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ @@ -189,6 +189,15 @@ impl Session { Some(Pickup::from_snapshot(PickupMode::Clone { offset: [0; 2] }, snapshot, self.caches.get(ts)?.gbuf.clone(), values.keys().copied())) } + /// What mask strokes paint: the tool's image while it is loaded, else its gray + pub(crate) fn mask_gray(&self) -> MaskGray { + let image = self.tool.mask_image.as_ref().and_then(|name| Some((name, self.images.get(name)?))); + match image { + Some((name, image)) => MaskGray::Image { name: name.clone(), image: image.clone() }, + None => MaskGray::Value(self.tool.mask_value), + } + } + fn stroke_values(&self, target: PaintTarget) -> BTreeMap { let ts = self.ts(); let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() }; @@ -332,6 +341,7 @@ impl Session { camera: self.camera, viewport, values, + mask_gray: self.mask_gray(), erase, stencil, before, @@ -525,16 +535,17 @@ impl Session { let Some(st) = self.stroke.as_mut() else { return }; let recent = std::mem::take(&mut st.canvas.recent); let (ts, target) = (st.ts, st.target); - let Some(t) = target else { + let Some(paint_target) = target else { self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); return; }; + let gbuf = self.caches.get(ts).map(|c| c.gbuf.clone()); - let (pixels, mask_value) = (&self.doc.pixels, self.tool.mask_value); + let pixels = &self.doc.pixels; let mut staging = std::mem::take(&mut st.staging); - with_commit_source(st, gbuf.as_deref(), &self.mesh, &recent, |src| match t { + with_commit_source(st, gbuf.as_deref(), &self.mesh, &recent, |src| match paint_target { PaintTarget::Layer(id) => staging.stage_layer(pixels, id, &st.values, &src), - PaintTarget::Mask(eid) => staging.stage_mask(pixels, eid, mask_value, &src), + PaintTarget::Mask(effect) => staging.stage_mask(pixels, effect, &st.mask_gray, &src), }); st.staging = staging; self.mark_painted(ts, target, recent); @@ -556,7 +567,6 @@ impl Session { let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone()); let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut st.staging); - let mask_value = self.tool.mask_value; match st.target { Some(PaintTarget::Layer(id)) => { let pixels = &mut self.doc.pixels; @@ -564,7 +574,7 @@ impl Session { } Some(PaintTarget::Mask(eid)) => { let pixels = &mut self.doc.pixels; - with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| commit_mask(pixels, eid, size, mask_value, src, &mut staging)); + with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| commit_mask(pixels, eid, size, &st.mask_gray, src, &mut staging)); } None => { with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| self.commit_quick_mask(st.ts, size, src)); @@ -658,7 +668,10 @@ impl Session { 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()), + PaintTarget::Mask(effect) => { + let mask_gray = self.mask_gray(); + commit_mask(&mut self.doc.pixels, effect, size, &mask_gray, source, &mut Staging::default()) + } } Ok(()) } diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 5398501f..19157759 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -156,14 +156,20 @@ impl PathState { #[derive(Clone)] pub(crate) struct PathCache { pub(crate) eid: LayerId, - // Alpha image resources are not part of this cache key - // Replacing an alpha takes effect when a cached path changes + // A change to the mask images `below` paints with drops the cache (Session::invalidate_changed) key: (u64, Option<(u32, u32)>), below: Vec, mask: Option, layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, } +impl PathCache { + /// The image resources the cached paths painted their mask with + pub(crate) fn images(&self) -> impl Iterator + '_ { + self.below.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image) + } +} + /// What a stored path is painted with ([`PathShape::paint`]). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct PathPaint { @@ -171,6 +177,8 @@ struct PathPaint { values: BTreeMap, enabled: BTreeSet, mask_value: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + mask_image: Option, camera: OrbitCamera, } @@ -337,6 +345,7 @@ fn edit_path(s: &mut Session, p: &Value) -> Result { s.tool.values = paint.values; s.tool.enabled = paint.enabled; s.tool.mask_value = paint.mask_value; + s.tool.mask_image = paint.mask_image; s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) }; s.path_steps = Default::default(); s.target = StackTarget::Effect(eid); @@ -369,6 +378,12 @@ fn read_paint(shape: &PathShape) -> Result { Ok(paint) } +/// The image resources a path sublayer's paths paint their mask with (none for any other effect) +pub(crate) fn path_images(kind: &EffectKind) -> Vec { + let EffectKind::Path(shapes) = kind else { return Vec::new() }; + shapes.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image).collect() +} + /// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); @@ -459,7 +474,14 @@ impl Session { /// The Path tool's curve with the current brush and material, as painted from `camera`. fn path_shape(&self, camera: OrbitCamera, viewport: Vec2) -> PathShape { let (t, path) = (&self.tool, &self.tool.path); - let paint = PathPaint { brush: t.brush.clone(), values: t.values.clone(), enabled: t.enabled.clone(), mask_value: t.mask_value, camera }; + let paint = PathPaint { + brush: t.brush.clone(), + values: t.values.clone(), + enabled: t.enabled.clone(), + mask_value: t.mask_value, + mask_image: t.mask_image.clone(), + camera, + }; PathShape { points: path.points.iter().map(|p| p.to_array()).collect(), corners: path.corner_flags(), @@ -1008,6 +1030,7 @@ impl Session { self.tool.values = paint.values; self.tool.enabled = paint.enabled; self.tool.mask_value = paint.mask_value; + self.tool.mask_image = paint.mask_image; self.camera = camera; self.tool.path = state_of(shape); self.paint_path(viewport) @@ -1213,6 +1236,37 @@ mod tests { assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles"); } + #[test] + fn removing_a_cached_paths_mask_image_repaints_it_with_the_mask_value() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + s.update(); + let layer = execute(&mut s, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + let white = texturecraft_formats::gray16_png(1, 1, [1.0].into_iter()).unwrap(); + let image = s.import_resource_bytes("brush.png", white).unwrap(); + execute(&mut s, "tool.material", &json!({"maskImage": image, "maskValue": 0.5})).unwrap(); + let mut eid = 0; + for v in [0.3, 0.7] { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + eid = r["committed"]["effect"].as_u64().unwrap(); + } + let eid = LayerId(eid); + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.6], [0.9, 0.6]]})).unwrap(); + assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1), "the bottom path is cached"); + + execute(&mut s, "resource.remove", &json!({"name": image})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.65], [0.9, 0.65]]})).unwrap(); + let mask = |s: &Session| format!("{:?}", s.doc.pixels.masks.get(&eid)); + let edited = mask(&s); + s.path_cache = None; + s.render_paths(eid, 0).unwrap(); + + assert_eq!(edited, mask(&s), "the bottom path paints the mask value as a full repaint does"); + } + #[test] fn failed_edit_releases_cached_path_tiles() { let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 12, 6), "builtin:test", None, 128).unwrap(); diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index e1f352c7..dd59c1d8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -256,7 +256,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Drop resources unused by layers, mask effects, the brush alpha, the stencil or the environment. +/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) fn remove_unused(s: &mut Session, _: &Value) -> Result { let mut used = Vec::new(); for set in &s.doc.project.texture_sets { @@ -266,6 +266,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { } used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone())); used.extend(s.tool.brush.alpha_image.clone()); + used.extend(s.tool.mask_image.clone()); used.extend(s.doc.project.display.environment_resource().map(str::to_string)); let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); if !unused.is_empty() { diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 2668cb1f..1a51a38a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -236,6 +236,9 @@ pub struct ToolState { pub material: Option, /// Gray painted into masks. pub mask_value: f32, + /// Image resource whose gray is painted into masks in place of `mask_value` + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mask_image: Option, pub fill_mode: FillMode, /// How a polygon fill box decides which polygons it selects #[serde(default)] @@ -310,6 +313,7 @@ impl Default for ToolState { enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(), material: None, mask_value: 1.0, + mask_image: None, fill_mode: FillMode::Triangle, fill_hit_test: Default::default(), fill_visible_only: default_fill_visible_only(), @@ -351,6 +355,8 @@ pub(crate) struct ActiveStroke { pub camera: OrbitCamera, pub viewport: Vec2, pub values: BTreeMap, + /// What a mask stroke paints, resolved once so staging, preview and commit read one image + pub mask_gray: texturecraft_compose::MaskGray, pub erase: bool, /// Projection tool: the stencil captured with the stroke's camera. pub stencil: Option, @@ -449,6 +455,8 @@ pub struct Session { pub(crate) stroke: Option, /// Layer clipboard: a document snapshot and the copied layer (or effect). pub clipboard: Option<(Document, LayerId)>, + /// Channel blending copied from an effect (see [`crate::effect_blending_cmds`]) + pub blending_clipboard: Option, /// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`). pub images: texturecraft_compose::ImageStore, /// Temporary texel mask limiting paint strokes (not saved, not in the history). @@ -533,6 +541,7 @@ impl Session { viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, + blending_clipboard: None, images: Default::default(), quick_mask: Default::default(), painting_paths: false, @@ -743,6 +752,15 @@ impl Session { self.path_cache = None; } + // Cached path pixels were painted with the mask images their paths name + let resource_changed = |name: &str| match (previous_document.resources.get(name), self.doc.resources.get(name)) { + (Some(previous), Some(current)) => !Arc::ptr_eq(previous, current), + (previous, current) => previous.is_some() != current.is_some(), + }; + if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(|name| resource_changed(&name))) { + self.path_cache = None; + } + // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); @@ -754,27 +772,23 @@ impl Session { return; } - let added_resource_names: BTreeSet<_> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).collect(); - let uses_added_resource = |texture_set_index: usize| { - use texturecraft_core::{EffectKind, Fill, Source}; + let added_resource_names: BTreeSet<&str> = + self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); + let is_added = |name: &str| added_resource_names.contains(name); + use texturecraft_core::{EffectKind, Fill}; - let uses_source = |source: &Source| source.images().into_iter().any(|name| added_resource_names.iter().any(|added| added.as_str() == name)); - let uses_fill = - |fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package)); - let project = &self.doc.project; - !added_resource_names.is_empty() - && project.texture_sets.get(texture_set_index).is_some_and(|set| { - project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { - matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) - || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind { - EffectKind::Fill { source, .. } => uses_source(source), - EffectKind::Material(fill) => uses_fill(fill), - EffectKind::Generator(generator) => generator.inputs.values().any(uses_source), - _ => false, - }) + let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); + let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); + let project = &self.doc.project; + !added_resource_names.is_empty() + && project.texture_sets.get(texture_set_index).is_some_and(|set| { + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) + || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| { + }) + }) }) - }) - }; + }; let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default()); let stack_key = |document: &Document, texture_set_index: usize| { let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default(); @@ -1012,7 +1026,7 @@ impl Session { opacity: stroke.stroke.settings.opacity, erase: stroke.erase, values: stroke.values.clone(), - mask_value: self.tool.mask_value, + mask_gray: stroke.mask_gray.clone(), stencil: stroke.stencil.clone(), carried_mask: stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()).cloned(), carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(), @@ -1223,12 +1237,19 @@ impl Session { /// 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> { + pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option { let (owner, _) = self.doc.project.effect(effect)?; let (ts, _, _) = self.doc.project.locate(owner)?; self.with_inputs(ts, |inp| texturecraft_compose::effect_histogram(inp, effect, channel, bins)) } + /// Histograms (`bins` buckets over 0..1) of what the two sides of compare mask `effect` read, left then right (None for an unknown effect or one that is no compare mask) + pub fn compare_histograms(&self, effect: LayerId, bins: usize) -> Option<[Vec; 2]> { + let (owner, _) = self.doc.project.effect(effect)?; + let (ts, _, _) = self.doc.project.locate(owner)?; + self.with_inputs(ts, |inp| texturecraft_compose::compare_histograms(inp, effect, bins)) + } + pub fn baked(&self, ts: usize) -> Option<&BakedMaps> { self.doc.baked.get(&ts) } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 9ca84090..a9142fa4 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Tool material", [], None, - "{channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1} or {material: id or label of a simple material (see material.list, smart: false)} — the brush paints that material's pattern (colour, metallic, roughness, height…, fixed to the surface, its size following the brush size) in the channels that are on; no layer is added, smart materials are refused (add them with material.apply)", + "{channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1, maskImage?: image resource | null (paint its gray into masks; null = maskValue)} or {material: id or label of a simple material (see material.list, smart: false)} — the brush paints that material's pattern (colour, metallic, roughness, height…, fixed to the surface, its size following the brush size) in the channels that are on; no layer is added, smart materials are refused (add them with material.apply)", always, material ), @@ -315,6 +315,22 @@ fn material(s: &mut Session, p: &Value) -> Result { let channel = channel_param("tool.material", p, "channel")?; let color = color_param("tool.material", p, "color")?; let value = color_param("tool.material", p, "value")?; + + // Every param is checked before the tool changes, so a refused call changes nothing + let mask_image = match p.get("maskImage") { + Some(Value::Null) => Some(None), + Some(name) => { + let name = name.as_str().ok_or_else(|| bad("tool.material", "maskImage must be an image resource name or null"))?; + + // The brush reads the decoded image: a resource that is not one (an environment, a linked package) is refused + if !s.images.contains_key(name) { + return Err(bad("tool.material", format!("no image resource '{name}'"))); + } + + Some(Some(name.to_owned())) + } + None => None, + }; if let Some(id) = strp(p, "material") { let values = crate::materials::brush_values(id).ok_or_else(|| { bad("tool.material", format!("`{id}` is not a simple material (a brush paints plain values; add smart materials with material.apply)")) @@ -332,35 +348,40 @@ fn material(s: &mut Session, p: &Value) -> Result { } s.tool.material = Some(crate::materials::find(id).map_or_else(|| id.to_string(), |m| m.id.to_string())); } - if let Some(v) = f32p(p, "maskValue") { - s.tool.mask_value = v.clamp(0.0, 1.0); + if let Some(mask_value) = f32p(p, "maskValue") { + s.tool.mask_value = mask_value.clamp(0.0, 1.0); } - if let Some(c) = channel { - if let Some(v) = color.or(value) { - let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) }; - s.tool.values.insert(c, v); - s.tool.enabled.insert(c); + if let Some(mask_image) = mask_image { + s.tool.mask_image = mask_image; + } + if let Some(channel) = channel { + if let Some(picked) = color.or(value) { + let picked = + if channel == Channel::Height { picked.map(|component| component.clamp(-1.0, 1.0)) } else { picked.map(|component| component.clamp(0.0, 1.0)) }; + s.tool.values.insert(channel, picked); + s.tool.enabled.insert(channel); s.tool.material = None; } match boolp(p, "enabled") { Some(true) => { - s.tool.enabled.insert(c); + s.tool.enabled.insert(channel); } Some(false) => { - s.tool.enabled.remove(&c); + s.tool.enabled.remove(&channel); } None => {} } if boolp(p, "solo") == Some(true) { - s.tool.enabled = std::iter::once(c).collect(); + s.tool.enabled = std::iter::once(channel).collect(); } } s.revision = s.revision.wrapping_add(1); Ok(json!({ "material": s.tool.material, - "values": s.tool.values.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::>(), - "enabled": s.tool.enabled.iter().map(|c| c.id()).collect::>(), + "values": s.tool.values.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>(), + "enabled": s.tool.enabled.iter().map(|channel| channel.id()).collect::>(), "maskValue": s.tool.mask_value, + "maskImage": s.tool.mask_image, })) } diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 6a3e18b0..11b4ceaa 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -18,6 +18,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", + "{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", has_layer, reset_frame )] diff --git a/crates/engine/tests/it/add_mask_items.rs b/crates/engine/tests/it/add_mask_items.rs new file mode 100644 index 00000000..ec0e6e53 --- /dev/null +++ b/crates/engine/tests/it/add_mask_items.rs @@ -0,0 +1,109 @@ +//! The layer toolbar's Add mask items that add a mask with an effect in it, and Add effect's colour selection: one undo step each, the new effect selected + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; +use texturecraft_engine::fill_alpha::resource_name; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::paint::alphas; +use texturecraft_engine::{Session, StackTarget, execute}; + +fn fill() -> (Session, LayerId) { + let mut s = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + (s, layer) +} + +/// A 2 × 2 mid-gray picture +fn gray_png() -> Vec { + let image = image::RgbaImage::from_pixel(2, 2, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// The effect `command` added and selected, and its kind +fn added(s: &mut Session, command: &str, params: Value) -> (LayerId, EffectKind) { + let steps = s.history_labels().len(); + let effect = LayerId(execute(s, command, ¶ms).unwrap()["effect"].as_u64().unwrap()); + assert_eq!(s.history_labels().len(), steps + 1, "{command} is one undo step"); + assert_eq!(s.target, StackTarget::Effect(effect), "{command} selects the effect it adds"); + let kind = s.doc.project.effect(effect).unwrap().1.kind.clone(); + (effect, kind) +} + +#[test] +fn a_bitmap_mask_is_a_black_mask_with_a_fill_reading_the_picked_alpha() { + let (mut s, layer) = fill(); + let name = resource_name(alphas::find("scratches").unwrap()); + let (_, kind) = added(&mut s, "mask.add.bitmap", json!({"layer": layer.0, "alpha": "scratches"})); + assert!(matches!(kind, EffectKind::Fill { source: Source::Image { name: ref read, .. }, .. } if *read == name), "{kind:?}"); + let mask = s.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert_eq!(mask.background, MaskBackground::Black); + assert!(s.doc.resources.contains_key(&name)); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.is_none(), "one undo takes the mask back"); + assert!(!s.doc.resources.contains_key(&name), "and the alpha's picture with it"); + + // Without a picture there is nothing to add + assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0})).is_err()); + assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0, "image": "missing.png"})).is_err()); + let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); + assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0, "image": image, "alpha": "scratches"})).is_err(), "one picture, not two"); + assert!(s.doc.project.layer(layer).unwrap().mask.is_none()); +} + +#[test] +fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_below() { + let (mut s, layer) = fill(); + let (_, kind) = added(&mut s, "mask.add.heightCombination", json!({"layer": layer.0})); + match kind { + EffectKind::Compare { left, right, channel, hardness, .. } => { + assert_eq!((left, right, channel, hardness), (CompareSource::ThisLayer, CompareSource::LayersBelow, Channel::Height, 0.9)); + } + other => panic!("not a compare mask: {other:?}"), + } + assert_eq!(s.history_labels().last().map(String::as_str), Some("Add mask with height combination")); +} + +#[test] +fn color_selections_go_in_the_mask_and_are_selected() { + let (mut s, layer) = fill(); + let (first, kind) = added(&mut s, "mask.add.colorSelection", json!({"layer": layer.0})); + assert!(matches!(kind, EffectKind::ColorSelection(_))); + assert_eq!(s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().background, MaskBackground::Black, "as colour selection masks were"); + + // Add effect's item adds another to the same mask, whatever target it is given + let (second, kind) = added(&mut s, "effect.add.colorSelection", json!({"layer": layer.0, "target": "content"})); + assert!(matches!(kind, EffectKind::ColorSelection(_))); + let mask: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask, vec![first, second]); + assert!(s.doc.project.layer(layer).unwrap().content_effects.is_empty()); +} + +/// An instance with no mask of its own: the Add mask items start one on the instance and leave the source's mask (or its lack of one) alone +#[test] +fn add_mask_on_an_instance_starts_its_own_mask() { + for source_mask in [None, Some("mask.add.white")] { + for (command, params) in [ + ("mask.add.heightCombination", json!({})), + ("mask.add.colorSelection", json!({"color": [1.0, 0.0, 0.0]})), + ("mask.add.bitmap", json!({"alpha": "scratches"})), + ] { + let (mut s, source) = fill(); + if let Some(add) = source_mask { + execute(&mut s, add, &json!({"layer": source.0})).unwrap(); + } + let before = s.doc.project.layer(source).unwrap().mask.clone(); + let instance = LayerId(execute(&mut s, "layer.instance", &json!({"layer": source.0})).unwrap()["layer"].as_u64().unwrap()); + + let mut params = params; + params["layer"] = json!(instance.0); + let (effect, _) = added(&mut s, command, params); + + assert_eq!(s.doc.project.layer(source).unwrap().mask, before, "{command} left the source's mask as it was"); + let own = s.doc.project.layer(instance).unwrap().mask.as_ref().map(|mask| mask.effects.iter().map(|effect| effect.id).collect::>()); + assert_eq!(own, Some(vec![effect]), "{command} started the instance's own mask"); + } + } +} diff --git a/crates/engine/tests/it/color_selection.rs b/crates/engine/tests/it/color_selection.rs index bdb984b5..97039c9e 100644 --- a/crates/engine/tests/it/color_selection.rs +++ b/crates/engine/tests/it/color_selection.rs @@ -51,14 +51,14 @@ fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) } let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap()); - execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap(); - let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + let added = execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); (layer, effect) } fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> { match &session.doc.project.effect(effect).unwrap().1.kind { - EffectKind::ColorSelection { colors, .. } => colors.clone(), + EffectKind::ColorSelection(selection) => selection.colors.clone(), other => panic!("not a color selection: {other:?}"), } } @@ -88,7 +88,8 @@ fn a_uv_pick_adds_the_color_there_or_replaces_one() { let (_, effect) = masked_layer(&mut session, true); execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap(); - assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID)); + let [_, picked] = colors(&session, effect)[..] else { panic!("the pick adds one color to the first") }; + assert_close(picked, stored(TOP_LEFT_ID)); let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap(); assert_eq!(replaced["index"], json!(0)); @@ -108,7 +109,7 @@ fn the_colors_param_replaces_the_list_in_one_undo_step() { execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap(); assert_eq!(colors(&session, effect), edited.to_vec()); let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") }; - assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2)); + assert!(matches!(&found.kind, EffectKind::ColorSelection(selection) if selection.tolerance == 0.2)); execute(&mut session, "edit.undo", &Value::Null).unwrap(); assert_eq!(colors(&session, effect), vec![NO_PART]); @@ -118,7 +119,7 @@ fn the_colors_param_replaces_the_list_in_one_undo_step() { fn bad_colors_are_refused_and_change_nothing() { let mut session = session(); let (_, effect) = masked_layer(&mut session, false); - let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")]; + let refused = [json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")]; for colors_param in &refused { assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}"); @@ -307,3 +308,98 @@ fn benchmark_color_selection_edits() { } } } + +#[test] +fn a_new_color_selection_selects_nothing_until_a_color_is_picked() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap(); + let added = execute(&mut session, "mask.add.colorSelection", &Value::Null).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); + assert_eq!(colors(&session, effect), Vec::<[f32; 3]>::new()); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1.0, 0.0, 0.0]]})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": []})).unwrap(); + assert_eq!(colors(&session, effect), Vec::<[f32; 3]>::new(), "the last color can be removed"); +} + +#[test] +fn an_image_resource_can_be_the_id_map_without_a_mesh_map() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, false); + let image = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + let pick = json!({"effect": effect.0, "uv": [0.75, 0.25]}); + assert!(execute(&mut session, "effect.colorSelection.pick", &pick).is_err(), "no ID map yet"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": "missing.png"})).is_err()); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": image})).unwrap(); + execute(&mut session, "effect.colorSelection.pick", &pick).unwrap(); + let [_, picked] = colors(&session, effect)[..] else { panic!("the pick adds one color to the first") }; + assert_close(picked, stored(TOP_RIGHT_ID)); + let (width, height) = session.caches[0].size; + let top_right = ((width as f32 * 0.75) as u32, (height as f32 * 0.25) as u32); + let bottom = ((width as f32 * 0.25) as u32, (height as f32 * 0.75) as u32); + assert_eq!(session.mask_at(layer, &[top_right, bottom]).unwrap(), vec![1.0, 0.0]); + assert_eq!(execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string().matches(&format!("\"idMap\":\"{image}\"")).count(), 1); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": null})).unwrap(); + assert_eq!(session.mask_at(layer, &[top_right]).unwrap(), vec![0.0], "back on the missing mesh map"); +} + +#[test] +fn output_hardness_and_background_shape_the_mask_in_one_undo_step_each() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, true); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [stored(TOP_LEFT_ID)]})).unwrap(); + let (width, height) = session.caches[0].size; + let texels = [((width as f32 * 0.25) as u32, (height as f32 * 0.25) as u32), ((width as f32 * 0.25) as u32, (height as f32 * 0.75) as u32)]; + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![1.0, 0.0], "selected part, background"); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "output": 0.5, "background": "white"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 1.0]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "gray"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 0.5]); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 1.0], "one undo step"); + + // A transparent background leaves the mask below it: the black mask background here + execute(&mut session, "effect.set", &json!({"effect": effect.0, "output": 1.0, "background": "transparent"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![1.0, 0.0]); + + // The bottom part is far from the picked color: a soft edge reaches it only when wide enough + execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "black", "tolerance": 0.0, "hardness": 0.0})).unwrap(); + let soft = session.mask_at(layer, &texels).unwrap(); + assert_eq!(soft[0], 1.0); + let far = (200.0f32 - 10.0) / 255.0; + assert!((soft[1] - (1.0 - far)).abs() < 1e-2, "{soft:?}"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "purple"})).is_err()); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + for key in ["\"output\":1.0", "\"hardness\":0.0", "\"background\":\"black\""] { + assert!(inspected.contains(key), "{key} in {inspected}"); + } +} + +#[test] +fn the_id_mask_view_shows_the_chosen_image_where_the_mask_reads_it() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + assert!(session.id_mask_view_rgba(effect, 16).is_none(), "the ID mesh map is no image"); + + let image = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": image})).unwrap(); + assert_eq!(session.id_mask_image(effect).map(|(texture_set, _)| texture_set), Some(0)); + let rgba = session.id_mask_view_rgba(effect, 16).unwrap(); + assert_eq!(rgba.len(), 16 * 16 * 4); + let pixel = |x: usize, y: usize| -> [u8; 3] { + let start = (y * 16 + x) * 4; + [rgba[start], rgba[start + 1], rgba[start + 2]] + }; + assert_eq!(pixel(1, 1), TOP_LEFT_ID); + assert_eq!(pixel(14, 1), TOP_RIGHT_ID); + assert_eq!(pixel(8, 14), BOTTOM_ID); + + // Each view pixel shows the color a pick at the same UV adds + let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [14.5 / 16.0, 1.5 / 16.0]})).unwrap(); + let picked: Vec = serde_json::from_value(picked["color"].clone()).unwrap(); + assert_close([picked[0], picked[1], picked[2]], stored(pixel(14, 1))); +} diff --git a/crates/engine/tests/it/compare_mask.rs b/crates/engine/tests/it/compare_mask.rs new file mode 100644 index 00000000..fd00fa03 --- /dev/null +++ b/crates/engine/tests/it/compare_mask.rs @@ -0,0 +1,130 @@ +//! Compare masks: one channel of the layer, the layers below, the mask so far or a constant on each side + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const SIZE: u32 = 256; +const BELOW_COLOR: [f32; 3] = [0.0, 0.0, 1.0]; +const LAYER_COLOR: [f32; 3] = [1.0, 0.0, 0.0]; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, SIZE).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// The texel under the viewport centre +fn center_texel(session: &mut Session) -> (u32, u32) { + session.update(); + let hit = session.pick(Vec2::new(200.0, 200.0), session.viewport).unwrap(); + ((hit.uv.x * SIZE as f32) as u32, (hit.uv.y * SIZE as f32) as u32) +} + +fn base_color(session: &mut Session) -> [f32; 3] { + let (x, y) = center_texel(session); + session.caches[0].composite.value(Channel::BaseColor, x, y) +} + +fn mask(session: &mut Session, layer: LayerId) -> f32 { + let texel = center_texel(session); + session.mask_at(layer, &[texel]).unwrap()[0] +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +fn close(actual: f32, expected: f32) -> bool { + (actual - expected).abs() < 2e-3 +} + +/// A blue fill of `below` roughness, a red fill of `own` roughness over it with a default compare mask on roughness: (below, layer, compare) +fn two_layers(session: &mut Session, below: f32, own: f32) -> (LayerId, LayerId, LayerId) { + let bottom = id(execute(session, "layer.add.fill", &json!({"color": BELOW_COLOR, "roughness": below})).unwrap(), "layer"); + let top = id(execute(session, "layer.add.fill", &json!({"color": LAYER_COLOR, "roughness": own})).unwrap(), "layer"); + let compare = id(execute(session, "effect.add.compare", &json!({"layer": top, "compareChannel": "roughness"})).unwrap(), "effect"); + (LayerId(bottom), LayerId(top), LayerId(compare)) +} + +#[test] +fn this_layer_is_compared_with_the_layers_below() { + let mut session = session(); + let (bottom, top, compare) = two_layers(&mut session, 0.2, 0.6); + assert!(close(mask(&mut session, top), 1.0), "0.6 > 0.2 holds: {}", mask(&mut session, top)); + assert_eq!(base_color(&mut session), LAYER_COLOR, "the layer shows where its mask compares true"); + + execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "lesser"})).unwrap(); + assert!(close(mask(&mut session, top), 0.0)); + assert_eq!(base_color(&mut session), BELOW_COLOR, "the layer is hidden where the comparison fails"); + + // Changing the layers below changes the mask above them (no stale cached stack) + execute(&mut session, "layer.fill.set", &json!({"layer": bottom.0, "channel": "roughness", "value": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "0.6 < 0.9 holds: {}", mask(&mut session, top)); + assert_eq!(base_color(&mut session), LAYER_COLOR); +} + +#[test] +fn hardness_ramps_the_mask_past_the_edge() { + let mut session = session(); + + // 0.6 is 0.03 past 0.57: a third of the default hardness 0.9's 0.1 ramp + let (_, top, compare) = two_layers(&mut session, 0.57, 0.6); + assert!(close(mask(&mut session, top), 0.3), "{}", mask(&mut session, top)); + + execute(&mut session, "effect.set", &json!({"effect": compare.0, "hardness": 1.0})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "a hard step: {}", mask(&mut session, top)); + + execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "within", "tolerance": 0.02, "hardness": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 0.9), "0.01 past the tolerance of 0.1's ramp: {}", mask(&mut session, top)); +} + +#[test] +fn a_constant_side_and_the_mask_so_far() { + let mut session = session(); + let (_, top, compare) = two_layers(&mut session, 0.2, 0.6); + execute(&mut session, "effect.set", &json!({"effect": compare.0, "right": "constant", "value": 0.7, "hardness": 1.0})).unwrap(); + assert!(close(mask(&mut session, top), 0.0), "0.6 > 0.7 fails"); + execute(&mut session, "effect.set", &json!({"effect": compare.0, "left": "thisMask", "value": 0.5})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "a white mask (1) > 0.5 holds"); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + for part in ["\"left\":\"thisMask\"", "\"op\":\"greater\"", "\"right\":\"constant\"", "\"compareChannel\":\"roughness\"", "\"hardness\":1.0"] { + assert!(inspected.contains(part), "inspect shows {part}"); + } +} + +#[test] +fn compare_parameters_are_one_undo_step_and_refuse_unknown_values() { + let mut session = session(); + let (_, top, compare) = two_layers(&mut session, 0.2, 0.6); + execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "lesser", "right": "constant", "value": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "0.6 < 0.9"); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "back to 0.6 > layers below 0.2"); + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"op\":\"greater\"") && inspected.contains("\"right\":\"layersBelow\""), "one undo step restores both"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": compare.0, "left": "elsewhere"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": compare.0, "compareChannel": "nope"})).is_err()); + assert!(execute(&mut session, "effect.add.compare", &json!({"layer": top.0, "target": "content"})).is_err(), "compare masks go on masks"); +} + +#[test] +fn the_histogram_counts_what_each_side_reads() { + let mut session = session(); + let (_, _, compare) = two_layers(&mut session, 0.25, 0.65); + let histogram = execute(&mut session, "effect.histogram", &json!({"effect": compare.0, "bins": 10})).unwrap(); + let busiest = |side: &str| { + let counts: Vec = histogram["compare"][side].as_array().unwrap().iter().map(|count| count.as_u64().unwrap()).collect(); + assert!(counts.iter().sum::() > 0, "{side} counts texels"); + counts.iter().enumerate().max_by_key(|(_, count)| **count).map(|(bucket, _)| bucket).unwrap() + }; + assert_eq!(busiest("left"), 6, "this layer's roughness 0.65"); + assert_eq!(busiest("right"), 2, "the layers below's roughness 0.25"); +} diff --git a/crates/engine/tests/it/effect_blending.rs b/crates/engine/tests/it/effect_blending.rs new file mode 100644 index 00000000..f90bd380 --- /dev/null +++ b/crates/engine/tests/it/effect_blending.rs @@ -0,0 +1,142 @@ +//! A content effect's blending per channel and the Blending options commands, through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const SIZE: u32 = 128; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, SIZE).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// Composited value of `channel` under the viewport center +fn center(s: &mut Session, channel: Channel) -> [f32; 3] { + s.update(); + let hit = s.pick(Vec2::new(200.0, 200.0), s.viewport).unwrap(); + s.caches[0].composite.value(channel, (hit.uv.x * SIZE as f32) as u32, (hit.uv.y * SIZE as f32) as u32) +} + +fn assert_close(actual: [f32; 3], expected: [f32; 3], what: &str) { + assert!((0..3).all(|i| (actual[i] - expected[i]).abs() < 4e-3), "{what}: {actual:?}, expected {expected:?}"); +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +/// A red fill layer of roughness 0.2 under a content fill effect of grey 0.5 and roughness 0.8: (layer, effect) +fn layer_with_content_fill(s: &mut Session) -> (u64, u64) { + let layer = id(execute(s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer"); + let effect = id(execute(s, "effect.add.fill", &json!({"target": "content", "color": [0.5, 0.5, 0.5], "roughness": 0.8})).unwrap(), "effect"); + (layer, effect) +} + +/// What inspect shows of content effect `effect`'s per-channel blending, in `layer`'s row +fn channel_blends(s: &mut Session, layer: u64, effect: u64) -> Value { + let inspect = execute(s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); + let shown = row["contentEffects"].as_array().unwrap().iter().find(|shown| shown["id"] == effect).unwrap().clone(); + shown["channelBlends"].clone() +} + +/// Setting one channel's blend mode or opacity leaves the others' as they are, and inspect shows it +#[test] +fn a_content_effect_blends_each_channel_on_its_own() { + let mut s = session(); + let (layer, effect) = layer_with_content_fill(&mut s); + assert_close(center(&mut s, Channel::BaseColor), [0.5; 3], "normal at 100%"); + assert_close(center(&mut s, Channel::Roughness), [0.8; 3], "normal at 100%"); + + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "baseColor", "opacity": 0.5})).unwrap(); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.25, 0.25], "base color at half opacity"); + assert_close(center(&mut s, Channel::Roughness), [0.8; 3], "roughness keeps its full opacity"); + + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply"})).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.16; 3], "roughness multiplies"); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.25, 0.25], "base color stays normal"); + let blends = channel_blends(&mut s, layer, effect); + assert_eq!(blends["baseColor"]["opacity"], json!(0.5), "{blends}"); + assert_eq!(blends["roughness"]["blend"], json!("Multiply"), "{blends}"); + + // Without a channel the edit reaches every channel, and channels left alike stop blending apart + execute(&mut s, "effect.set", &json!({"effect": effect, "opacity": 1.0, "blend": "Normal"})).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.8; 3], "every channel back to normal at 100%"); + assert_close(center(&mut s, Channel::BaseColor), [0.5; 3], "every channel back to normal at 100%"); + assert!(channel_blends(&mut s, layer, effect).is_null(), "no channel blends apart any more"); + + // Saved per channel, loaded as saved; an effect saved before has none + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply"})).unwrap(); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); + let effect = s.doc.project.effect(LayerId(effect)).unwrap().1; + assert_eq!(effect.blend_of(Some(Channel::BaseColor)), effect.blend_of(None), "unset channels share the effect's blending"); +} + +/// The three "on every channel" items take the chosen channel's blend mode, opacity or both, each in one undo step +#[test] +fn one_channels_blending_goes_to_every_channel_in_one_undo_step() { + let mut s = session(); + let (layer, effect) = layer_with_content_fill(&mut s); + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "baseColor", "opacity": 0.5})).unwrap(); + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply"})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + + execute(&mut s, "effect.blending.opacityToEveryChannel", &json!({"channel": "baseColor"})).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.18; 3], "roughness multiplies at half opacity"); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.25, 0.25], "base color unchanged"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.16; 3], "one undo puts the opacity back"); + + execute(&mut s, "effect.blending.modeToEveryChannel", &json!({"channel": "roughness"})).unwrap(); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.0, 0.0], "base color multiplies at its own half opacity"); + + execute(&mut s, "effect.blending.bothToEveryChannel", &json!({"channel": "roughness"})).unwrap(); + assert_close(center(&mut s, Channel::BaseColor), [0.5, 0.0, 0.0], "base color multiplies at full opacity"); + assert!(channel_blends(&mut s, layer, effect).is_null(), "every channel blends alike"); + + // Nothing left to change: no empty undo step + let steps = s.history_labels().len(); + execute(&mut s, "effect.blending.bothToEveryChannel", &json!({"channel": "roughness"})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "every channel already blends alike"); +} + +/// Copy and paste carry every channel's blending to another effect; masks, levels and anchors take what applies to them +#[test] +fn channel_blending_copies_and_pastes_between_effects() { + let mut s = session(); + let (layer, effect) = layer_with_content_fill(&mut s); + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply", "opacity": 0.5})).unwrap(); + assert!(execute(&mut s, "effect.blending.paste", &json!({"effect": effect})).is_err(), "nothing copied yet"); + execute(&mut s, "effect.blending.copy", &json!({"effect": effect})).unwrap(); + + let other = id(execute(&mut s, "effect.add.fill", &json!({"layer": layer, "target": "content", "roughness": 0.8})).unwrap(), "effect"); + execute(&mut s, "effect.blending.paste", &json!({"effect": other})).unwrap(); + let pasted = s.doc.project.effect(LayerId(other)).unwrap().1; + assert_eq!(pasted.blend_of(Some(Channel::Roughness)), s.doc.project.effect(LayerId(effect)).unwrap().1.blend_of(Some(Channel::Roughness))); + assert_eq!(pasted.blend_of(Some(Channel::BaseColor)), pasted.blend_of(None)); + let steps = s.history_labels().len(); + execute(&mut s, "effect.blending.paste", &json!({"effect": other})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "pasting the blending it already has adds no undo step"); + + // A mask effect has one channel: it takes the shared blending and refuses a channel of its own + execute(&mut s, "mask.add.white", &json!({"layer": layer})).unwrap(); + let masked = id(execute(&mut s, "effect.add.fill", &json!({"layer": layer})).unwrap(), "effect"); + execute(&mut s, "effect.blending.paste", &json!({"effect": masked})).unwrap(); + assert!(s.doc.project.effect(LayerId(masked)).unwrap().1.channel_blends.is_empty()); + assert!(execute(&mut s, "effect.set", &json!({"effect": masked, "channel": "roughness", "opacity": 0.5})).is_err()); + assert!(execute(&mut s, "effect.blending.modeToEveryChannel", &json!({"effect": masked})).is_err()); + + // Levels and anchor points have no blending + let levels = id(execute(&mut s, "effect.add.levels", &json!({"layer": layer, "target": "content"})).unwrap(), "effect"); + assert!(execute(&mut s, "effect.blending.copy", &json!({"effect": levels})).is_err()); + execute(&mut s, "layer.select", &json!({"layer": layer, "target": levels})).unwrap(); + assert!((texturecraft_engine::commands::find("effect.blending.paste").unwrap().enabled)(&s).is_err(), "greyed for levels"); +} diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 23711592..3c7e6267 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -515,7 +515,7 @@ fn an_axis_planar_reading_a_pattern_is_not_placed() { let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); let effect = added["effect"].as_u64().unwrap(); execute(&mut s, "effect.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); - + execute(&mut s, "layer.fill.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index bae8985c..f45226e8 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,6 +1,7 @@ //! One integration-test executable avoids linking the same dependencies for every feature. //! Keep feature tests in their own modules; the standalone session.rs target remains available. +mod add_mask_items; mod bake; mod bake_checks; mod bake_resolution; @@ -9,7 +10,9 @@ mod bake_tiles; mod brush_material; mod closed_session; mod color_selection; +mod compare_mask; mod content_effects; +mod effect_blending; mod export_colour_space; mod export_file_types; mod export_maps; @@ -21,6 +24,7 @@ mod fill_whole_material; mod filter_support; mod filter_swap; mod filters; +mod folder_contents; mod frame_selection; mod generator_inputs; mod gradient_map; @@ -29,6 +33,8 @@ mod instances; mod layer_multi_select; mod mask_clone_smudge; mod mask_export; +mod mask_fill_source; +mod mask_paint_image; mod materialcraft_link; mod materialx; mod materialx_import; @@ -40,6 +46,7 @@ mod pbr_import; mod perf; mod polygon_fill; mod project_recovery; +mod resources_used; mod sample; mod solo; mod swatches; diff --git a/crates/engine/tests/it/mask_paint_image.rs b/crates/engine/tests/it/mask_paint_image.rs new file mode 100644 index 00000000..61f16f29 --- /dev/null +++ b/crates/engine/tests/it/mask_paint_image.rs @@ -0,0 +1,119 @@ +//! Painting a mask with an image: the tool's Grayscale slot set to an image paints its gray per texel + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const RESOLUTION: u32 = 256; + +/// An 8 × 8 picture: black on its left half, white on its right half +fn halves_png() -> Vec { + let image = image::RgbaImage::from_fn(8, 8, |x, _| if x < 4 { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) }); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A paint layer under a black mask, the mask selected for painting, a big brush +fn masked_layer() -> (Session, LayerId) { + let mut session = Session::new_project("Mask image", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 40.0, "spacing": 5.0, "hardness": 100})).unwrap(); + (session, layer) +} + +/// The mask at texture coordinates (`u`, `v`) +fn mask_at(session: &Session, layer: LayerId, u: f32, v: f32) -> f32 { + let texel = ((u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32); + session.mask_at(layer, &[texel]).unwrap()[0] +} + +#[test] +fn a_mask_stroke_paints_the_tools_image_gray_and_null_goes_back_to_the_value() { + let (mut session, layer) = masked_layer(); + let image = session.import_resource_bytes("halves.png", halves_png()).unwrap(); + let set = execute(&mut session, "tool.material", &json!({"maskImage": image})).unwrap(); + assert_eq!(set["maskImage"], json!(image)); + assert!(execute(&mut session, "tool.material", &json!({"maskImage": "missing.png"})).is_err(), "an unknown image is refused"); + assert!(execute(&mut session, "tool.material", &json!({"maskImage": 3})).is_err()); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.1, 0.5], [0.9, 0.5]]})).unwrap(); + let (left, right) = (mask_at(&session, layer, 0.25, 0.5), mask_at(&session, layer, 0.75, 0.5)); + assert!(left < 0.05 && right > 0.95, "the image's halves: left {left}, right {right}"); + + // Back to one value: the next stroke paints white on the left too + let set = execute(&mut session, "tool.material", &json!({"maskImage": null})).unwrap(); + assert_eq!(set["maskImage"], Value::Null); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.1, 0.5], [0.9, 0.5]]})).unwrap(); + assert!(mask_at(&session, layer, 0.25, 0.5) > 0.95); +} + +#[test] +fn a_refused_mask_image_leaves_the_mask_value_as_it_was() { + let (mut session, _) = masked_layer(); + execute(&mut session, "tool.material", &json!({"maskValue": 0.25})).unwrap(); + + let refused = execute(&mut session, "tool.material", &json!({"maskValue": 0.75, "maskImage": "missing.png"})); + + assert!(refused.is_err()); + assert_eq!(execute(&mut session, "tool.material", &Value::Null).unwrap()["maskValue"], json!(0.25)); +} + +#[test] +fn a_resource_that_is_no_image_is_refused_as_the_mask_image() { + let (mut session, _) = masked_layer(); + session.doc.resources.insert("notes.png".to_string(), std::sync::Arc::new(b"not a picture".to_vec())); + session.sync_images(); + + let refused = execute(&mut session, "tool.material", &json!({"maskImage": "notes.png"})); + + assert!(refused.is_err(), "the brush could not read it"); + assert_eq!(execute(&mut session, "tool.material", &Value::Null).unwrap()["maskImage"], Value::Null); +} + +#[test] +fn a_mask_image_that_is_gone_paints_the_value() { + let (mut session, layer) = masked_layer(); + let image = session.import_resource_bytes("halves.png", halves_png()).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": image, "maskValue": 0.5})).unwrap(); + session.images.remove(&image); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.1, 0.5], [0.9, 0.5]]})).unwrap(); + let painted = mask_at(&session, layer, 0.25, 0.5); + assert!((painted - 0.5).abs() < 0.02, "painted {painted}"); +} + +/// A one-colour picture, `level` 0 for black or 255 for white +fn plain_png(level: u8) -> Vec { + let image = image::RgbaImage::from_pixel(8, 8, image::Rgba([level, level, level, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +#[test] +fn a_mask_stroke_paints_the_image_it_began_with_when_the_resource_is_replaced_mid_stroke() { + let mut session = Session::new_project("Mask image", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.white", &json!({"layer": layer.0})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 40.0, "spacing": 5.0, "hardness": 100})).unwrap(); + let image = session.import_resource_bytes("brush.png", plain_png(0)).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": image})).unwrap(); + + session.begin_stroke_uv(Vec2::new(0.1, 0.5), 1.0).unwrap(); + session.continue_stroke_uv(Vec2::new(0.4, 0.5), 1.0); + execute(&mut session, "resource.remove", &json!({"name": image})).unwrap(); + let replaced = session.import_resource_bytes("brush.png", plain_png(255)).unwrap(); + session.continue_stroke_uv(Vec2::new(0.9, 0.5), 1.0); + session.end_stroke().unwrap(); + + assert_eq!(replaced, image, "the white picture took the black one's name"); + let (left, right) = (mask_at(&session, layer, 0.25, 0.5), mask_at(&session, layer, 0.75, 0.5)); + assert!(left < 0.05 && right < 0.05, "the whole stroke is black: left {left}, right {right}"); +} diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 6c4be47f..c22a0d42 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -80,33 +80,44 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); + assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); + execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it. + // A gradient map recolors the content; effect.set edits it and inspect shows it let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); + execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); + execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped. + // Posterize on the mask; its steps are clamped let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0)); - // Material finishes fill the content's roughness and height. + + // Material finishes fill the content's roughness and height let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); + assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - // A directional blur, slope blur and warp composite without trouble on a sphere. + + // A directional blur, slope blur and warp composite without trouble on a sphere for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"radius": 30})), diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs new file mode 100644 index 00000000..9d57d1d6 --- /dev/null +++ b/crates/engine/tests/it/resources_used.rs @@ -0,0 +1,74 @@ + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const RESOLUTION: u32 = 128; + +fn session() -> Session { + Session::new_project("Resources", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, RESOLUTION).unwrap() +} + +/// A 4 × 4 white picture +fn white_png() -> Vec { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A red fill layer whose mask selects white on `id_map` +fn selecting_layer(session: &mut Session, id_map: &str) -> LayerId { + let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap()["layer"].as_u64().unwrap()); + let selection = execute(session, "mask.add.colorSelection", &Value::Null).unwrap()["effect"].as_u64().unwrap(); + execute(session, "effect.set", &json!({"effect": selection, "idMap": id_map, "colors": [[1.0, 1.0, 1.0]], "tolerance": 0.05})).unwrap(); + layer +} + +#[test] + let mut session = session(); + + // A path on the mask is painted with one image, then the brush moves on to another + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": path})).unwrap(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": brush})).unwrap(); + + let reply = execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(reply["removed"], json!([unused]), "only the image nothing reads goes"); +} + +#[test] + let mut session = session(); + let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); + let bytes = session.smart_material_bytes(layer, "Parts").unwrap(); + + let mut other = self::session(); + other.add_smart_material_bytes(&bytes).unwrap(); + + assert!(other.doc.resources.contains_key(&id_map), "the ID map comes along"); +} + +#[test] +fn importing_the_id_map_a_selection_reads_again_redraws_its_mask() { + let mut session = session(); + let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); + selecting_layer(&mut session, &id_map); + assert!(red_in_the_view(&mut session), "white is selected"); + execute(&mut session, "resource.remove", &json!({"name": id_map})).unwrap(); + assert!(!red_in_the_view(&mut session), "no ID map, nothing selected"); + + let imported = session.import_resource_bytes("id.png", white_png()).unwrap(); + + assert_eq!(imported, id_map); + assert!(red_in_the_view(&mut session), "the image is read again"); +} + +/// Whether the composite the views show is the masked layer's red in the middle of the texture +fn red_in_the_view(session: &mut Session) -> bool { + session.update(); + let [red, green, _] = session.caches[0].composite.value(Channel::BaseColor, RESOLUTION / 2, RESOLUTION / 2); + red > 0.85 && green < 0.15 +} diff --git a/crates/paint/src/commit.rs b/crates/paint/src/commit.rs index 8351ca8f..e7df85cf 100644 --- a/crates/paint/src/commit.rs +++ b/crates/paint/src/commit.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use rayon::prelude::*; -use texturecraft_compose::PixelStore; +use texturecraft_compose::{MaskGray, PixelStore}; use texturecraft_core::{Channel, ChannelKind, LayerId}; use texturecraft_texel::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed}; @@ -19,14 +19,13 @@ pub(crate) fn enc(kind: ChannelKind, v: f32) -> u16 { if kind == ChannelKind::Signed { to_u16_signed(v) } else { to_u16(v) } } -/// What one image receives: its channel kind, the painted value (unused when erasing or for -/// coverage images), whether a stencil's color replaces it (base color) and the values a clone -/// or smudge stroke carries for it. +/// What one image receives: its channel kind, the painted value (unused when erasing or for coverage images), whether a stencil's color replaces it (base color) and the values a clone or smudge stroke carries for it, and the image whose gray a mask stroke paints in place of `value` struct Blend<'a> { kind: ChannelKind, value: &'a [f32], stencil_color: bool, carried: Option<&'a TileImage>, + gray: Option<&'a MaskGray>, } /// Blend `alpha × opacity` into one image of `n` value components plus coverage. With a @@ -70,42 +69,47 @@ fn over(img: &mut TileImage, b: &Blend, src: &CommitSource, mut staged: Option) { - let n = comps.saturating_sub(1); - let opacity = src.opacity.clamp(0.0, 1.0); +/// Blend the stroke's alpha tile `stroke_alpha` into tile `(tx, ty)` of an image (`dst`, `components` per texel) +fn blend_tile(dst: &mut [u16], components: usize, stroke_alpha: &[u16], (tx, ty): (u32, u32), blend: &Blend, source: &CommitSource, carried: Option<&[u16]>) { + // The last component is the coverage, the ones before it the value + let value_count = components.saturating_sub(1); + let opacity = source.opacity.clamp(0.0, 1.0); for i in 0..TILE_AREA { - let mut m = from_u16(a.get(i).copied().unwrap_or(0)) * opacity; - if m <= 0.0 { + let mut weight = from_u16(stroke_alpha.get(i).copied().unwrap_or(0)) * opacity; + if weight <= 0.0 { continue; } - let mut color = None; - if let Some(f) = src.per_texel { - let (x, y) = (tx * TILE + i as u32 % TILE, ty * TILE + i as u32 / TILE); - match f(x, y) { - Some((c, af)) => { - m *= af; - color = Some(c); + + let mut stencil = None; + let (x, y) = (tx * TILE + i as u32 % TILE, ty * TILE + i as u32 / TILE); + if let Some(per_texel) = source.per_texel { + match per_texel(x, y) { + Some((color, alpha_factor)) => { + weight *= alpha_factor; + stencil = Some(color); } None => continue, } - if m <= 0.0 { + if weight <= 0.0 { continue; } } - let Some(px) = dst.get_mut(i * comps..(i + 1) * comps) else { continue }; - let cov = from_u16(px[n]); - for k in 0..n { - let p = dec(b.kind, px[k]); - let target = match (carried, color) { - (Some(t), _) => dec(b.kind, t.get(i * n + k).copied().unwrap_or(0)), - (None, Some(c)) if b.stencil_color => c.get(k).copied().unwrap_or(0.0), - _ => b.value.get(k).copied().unwrap_or(0.0), + + let Some((coverage_slot, values)) = dst.get_mut(i * components..(i + 1) * components).and_then(<[u16]>::split_last_mut) else { continue }; + let gray = blend.gray.map(|gray| gray.at(x, y, (source.alpha.width(), source.alpha.height()))); + let coverage = from_u16(*coverage_slot); + for (component, slot) in values.iter_mut().enumerate() { + let previous = dec(blend.kind, *slot); + let target = match (carried, stencil) { + (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(i * value_count + component).copied().unwrap_or(0)), + (None, _) if let Some(gray) = gray => gray, + (None, Some(color)) if blend.stencil_color => color.get(component).copied().unwrap_or(0.0), + _ => blend.value.get(component).copied().unwrap_or(0.0), }; - let v = if src.erase { p * (1.0 - m) } else { target * m + p * (1.0 - m) }; - px[k] = enc(b.kind, v); + let blended = if source.erase { previous * (1.0 - weight) } else { target * weight + previous * (1.0 - weight) }; + *slot = enc(blend.kind, blended); } - px[n] = to_u16(if src.erase { cov * (1.0 - m) } else { m + cov * (1.0 - m) }); + *coverage_slot = to_u16(if source.erase { coverage * (1.0 - weight) } else { weight + coverage * (1.0 - weight) }); } } @@ -134,13 +138,15 @@ fn fill_from(dst: &mut Vec, from: Option<&[u16]>, empty: &[u16]) { #[derive(Clone, Debug, PartialEq)] struct BlendKey { value: Vec, + image: Option, opacity: f32, erase: bool, } impl BlendKey { fn new(b: &Blend, src: &CommitSource) -> BlendKey { - BlendKey { value: b.value.to_vec(), opacity: src.opacity, erase: src.erase } + let image = b.gray.and_then(MaskGray::image_name).map(str::to_owned); + BlendKey { value: b.value.to_vec(), image, opacity: src.opacity, erase: src.erase } } } @@ -240,11 +246,10 @@ impl Staging { } } - /// Prepare tiles `src.tiles` of the mask paint effect a [`commit_mask`] of `effect` with - /// the same arguments will write. - pub fn stage_mask(&mut self, pixels: &PixelStore, effect: LayerId, value: f32, src: &CommitSource) { - let value = [value.clamp(0.0, 1.0)]; - let b = Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask }; + /// Prepare tiles `src.tiles` of the mask paint effect a [`commit_mask`] of `effect` with the same arguments will write + pub fn stage_mask(&mut self, pixels: &PixelStore, effect: LayerId, gray: &MaskGray, src: &CommitSource) { + let value = mask_value(gray); + let b = Blend { carried: src.carried_mask, ..mask_blend(gray, &value) }; self.images.entry(None).or_default().stage(pixels.masks.get(&effect), 2, &b, src); } @@ -273,9 +278,24 @@ fn layer_blend<'a>(c: Channel, values: &'a BTreeMap, src: &Co value: value.get(..c.components()).unwrap_or(value), stencil_color: c == Channel::BaseColor, carried: src.carried.and_then(|m| m.get(&c)), + gray: None, } } +/// The one value a mask stroke painting `gray` blends (0 under an image, which gives its own per texel) +fn mask_value(gray: &MaskGray) -> [f32; 1] { + match gray { + MaskGray::Value(value) => [value.clamp(0.0, 1.0)], + MaskGray::Image { .. } => [0.0], + } +} + +/// How a mask stroke painting `gray` blends (`value` from [`mask_value`]) +fn mask_blend<'a>(gray: &'a MaskGray, value: &'a [f32; 1]) -> Blend<'a> { + let gray = matches!(gray, MaskGray::Image { .. }).then_some(gray); + Blend { kind: ChannelKind::Scalar, value, stencil_color: false, carried: None, gray } +} + /// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint. pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<([f32; 3], f32)> + Sync); @@ -309,16 +329,16 @@ pub fn commit_layer(pixels: &mut PixelStore, layer: LayerId, size: (u32, u32), v images.into_par_iter().for_each(|(c, img, staged)| over(img, &layer_blend(c, values, &src), &src, staged)); } -/// Commit a stroke into the paint effect `effect` of a mask, painting gray `value`. -pub fn commit_mask(pixels: &mut PixelStore, effect: LayerId, size: (u32, u32), value: f32, src: CommitSource, staging: &mut Staging) { +/// Commit a stroke into the paint effect `effect` of a mask, painting `gray` +pub fn commit_mask(pixels: &mut PixelStore, effect: LayerId, size: (u32, u32), gray: &MaskGray, src: CommitSource, staging: &mut Staging) { let img = pixels.mask_mut(effect, size); - let value = [value.clamp(0.0, 1.0)]; - over(img, &Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask }, &src, staging.take(None)); + let value = mask_value(gray); + over(img, &Blend { carried: src.carried_mask, ..mask_blend(gray, &value) }, &src, staging.take(None)); } -/// Commit a stroke into a coverage-only image (1 component), e.g. the quick mask. +/// Commit a stroke into a coverage-only image (1 component), e.g. the quick mask pub fn commit_coverage(img: &mut TileImage, src: CommitSource) { - over(img, &Blend { kind: ChannelKind::Scalar, value: &[], stencil_color: false, carried: None }, &src, None); + over(img, &Blend { kind: ChannelKind::Scalar, value: &[], stencil_color: false, carried: None, gray: None }, &src, None); } #[cfg(test)] @@ -371,9 +391,9 @@ mod tests { fn mask_commit_and_untouched_tiles_stay_shared() { let mut px = PixelStore::default(); let (a, tiles) = alpha(1.0); - commit_mask(&mut px, LayerId(9), (64, 64), 1.0, src(&a, &tiles, 1.0, false), &mut Staging::default()); + commit_mask(&mut px, LayerId(9), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); let before = px.clone(); - commit_mask(&mut px, LayerId(9), (64, 64), 0.0, src(&a, &tiles, 1.0, true), &mut Staging::default()); + commit_mask(&mut px, LayerId(9), (64, 64), &MaskGray::Value(0.0), src(&a, &tiles, 1.0, true), &mut Staging::default()); assert_eq!(from_u16(before.masks[&LayerId(9)].get(5, 5)[1]), 1.0); assert_eq!(px.masks[&LayerId(9)].get(5, 5)[1], 0); } @@ -406,7 +426,7 @@ mod tests { let source = CommitSource { carried: Some(&carried), ..src(&alpha, &tiles, 1.0, false) }; let mut pixels = PixelStore::default(); - commit_mask(&mut pixels, LayerId(1), (64, 64), 1.0, source, &mut Staging::default()); + commit_mask(&mut pixels, LayerId(1), (64, 64), &MaskGray::Value(1.0), source, &mut Staging::default()); assert_eq!(pixels.masks[&LayerId(1)].get(5, 5)[0], u16::MAX); } @@ -417,7 +437,7 @@ mod tests { let (a, tiles) = alpha(0.7); let mut base = PixelStore::default(); commit_layer(&mut base, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default()); - commit_mask(&mut base, LayerId(2), (64, 64), 0.5, src(&a, &tiles, 1.0, false), &mut Staging::default()); + commit_mask(&mut base, LayerId(2), (64, 64), &MaskGray::Value(0.5), src(&a, &tiles, 1.0, false), &mut Staging::default()); let carried: BTreeMap = vals.keys().map(|c| (*c, a.clone())).collect(); // Staged when the stroke started, then again after the alpha changed (pre-blended // tiles re-blend), and staged once more with its last alpha change left out (that @@ -428,20 +448,20 @@ mod tests { let mut staging = Staging::default(); let c = carry.then_some(&carried); staging.stage_layer(&staged, LayerId(1), &vals, &source(&a, &tiles, c, erase)); - staging.stage_mask(&staged, LayerId(2), 1.0, &source(&a, &tiles, c, erase)); + staging.stage_mask(&staged, LayerId(2), &MaskGray::Value(1.0), &source(&a, &tiles, c, erase)); a.set(7, 9, &[to_u16(0.3)]); staging.stage_layer(&staged, LayerId(1), &vals, &source(&a, &tiles, c, erase)); - staging.stage_mask(&staged, LayerId(2), 1.0, &source(&a, &tiles, c, erase)); + staging.stage_mask(&staged, LayerId(2), &MaskGray::Value(1.0), &source(&a, &tiles, c, erase)); a.set(8, 9, &[to_u16(0.9)]); if stage_last { staging.stage_layer(&staged, LayerId(1), &vals, &source(&a, &tiles, c, erase)); - staging.stage_mask(&staged, LayerId(2), 1.0, &source(&a, &tiles, c, erase)); + staging.stage_mask(&staged, LayerId(2), &MaskGray::Value(1.0), &source(&a, &tiles, c, erase)); } let mut plain = base.clone(); commit_layer(&mut plain, LayerId(1), (64, 64), &vals, source(&a, &tiles, c, erase), &mut Staging::default()); - commit_mask(&mut plain, LayerId(2), (64, 64), 1.0, source(&a, &tiles, c, erase), &mut Staging::default()); + commit_mask(&mut plain, LayerId(2), (64, 64), &MaskGray::Value(1.0), source(&a, &tiles, c, erase), &mut Staging::default()); commit_layer(&mut staged, LayerId(1), (64, 64), &vals, source(&a, &tiles, c, erase), &mut staging); - commit_mask(&mut staged, LayerId(2), (64, 64), 1.0, source(&a, &tiles, c, erase), &mut staging); + commit_mask(&mut staged, LayerId(2), (64, 64), &MaskGray::Value(1.0), source(&a, &tiles, c, erase), &mut staging); assert_eq!((&staged.layers, &staged.masks), (&plain.layers, &plain.masks), "erase {erase}, carried {carry}, staged last {stage_last}"); } // Tiles staged before the layer changed or with another value are stale: the commit @@ -449,13 +469,40 @@ mod tests { let mut px = base.clone(); let mut staging = Staging::default(); staging.stage_layer(&px, LayerId(1), &vals, &src(&a, &tiles, 1.0, false)); - staging.stage_mask(&px, LayerId(2), 0.25, &src(&a, &tiles, 1.0, false)); + staging.stage_mask(&px, LayerId(2), &MaskGray::Value(0.25), &src(&a, &tiles, 1.0, false)); commit_layer(&mut px, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default()); let mut expected = px.clone(); commit_layer(&mut expected, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default()); - commit_mask(&mut expected, LayerId(2), (64, 64), 1.0, src(&a, &tiles, 1.0, false), &mut Staging::default()); + commit_mask(&mut expected, LayerId(2), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); commit_layer(&mut px, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut staging); - commit_mask(&mut px, LayerId(2), (64, 64), 1.0, src(&a, &tiles, 1.0, false), &mut staging); + commit_mask(&mut px, LayerId(2), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut staging); assert_eq!((&px.layers, &px.masks), (&expected.layers, &expected.masks)); } + + #[test] + fn a_mask_stroke_paints_an_images_gray_per_texel_staged_or_not() { + use std::sync::Arc; + use texturecraft_compose::ImageRes; + + // A 2 × 1 image: black on the left half of the texture, white on the right + let image = |name: &str, left: f32| MaskGray::Image { name: name.into(), image: Arc::new(ImageRes::new(2, 1, vec![[left; 4], [1.0; 4]], false)) }; + let mut a = TileImage::new(64, 64, 1); + for (x, y) in [(16, 5), (48, 5)] { + a.set(x, y, &[to_u16(1.0)]); + } + let tiles: BTreeSet<(u32, u32)> = [(0, 0)].into_iter().collect(); + let gray_at = |px: &PixelStore, x| from_u16(px.masks[&LayerId(4)].get(x, 5)[0]); + + let mut plain = PixelStore::default(); + commit_mask(&mut plain, LayerId(4), (64, 64), &image("scratches", 0.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); + assert!(gray_at(&plain, 16) < 0.05 && gray_at(&plain, 48) > 0.95, "left {} right {}", gray_at(&plain, 16), gray_at(&plain, 48)); + + // Staged with another image first: the commit blends the image it is given + let mut staged = PixelStore::default(); + let mut staging = Staging::default(); + staging.stage_mask(&staged, LayerId(4), &image("other", 0.5), &src(&a, &tiles, 1.0, false)); + staging.stage_mask(&staged, LayerId(4), &image("scratches", 0.0), &src(&a, &tiles, 1.0, false)); + commit_mask(&mut staged, LayerId(4), (64, 64), &image("scratches", 0.0), src(&a, &tiles, 1.0, false), &mut staging); + assert_eq!(staged.masks, plain.masks); + } } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b564144f..15e59218 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -25,8 +25,6 @@ use crate::theme::{Tokens, caption}; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; -/// 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; /// The most colors `effect.set {colors}` takes for a gradient map @@ -138,75 +136,12 @@ const LAYER_TOOLBAR_GAP: f32 = 2.0; /// Least height of the drop space under the layer rows, so a drop to the bottom always has a target const BOTTOM_DROP_MIN_HEIGHT: f32 = 24.0; -/// The add-mask commands, for the selected layer or (`row`) the layer whose mask slot was clicked. -fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { - let enabled = row.is_some() || app.session.selected_layer().is_some(); - for (label, id) in - [(tr("Add white mask"), "mask.add.white"), (tr("Add black mask"), "mask.add.black"), (tr("Add mask with color selection"), "mask.add.colorSelection")] - { - if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { - if let Some(layer) = row { - app.run("layer.select", json!({ "layer": layer })); - } - app.run(id, Value::Null); - ui.close(); - } - } -} - pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); - // Wrap in a narrow column so rows stay within the panel - let project_open = app.session.project_open; - ui.add_enabled_ui(project_open, |ui| { - ui.horizontal_wrapped(|ui| { - // Keep menu buttons as compact as the adjacent icon buttons - ui.spacing_mut().button_padding.x = 4.0; - ui.spacing_mut().item_spacing.x = TOOLBAR_SPACING; - let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - - // The channel box takes what the six buttons leave, so the toolbar stays on one row in a narrow column - let buttons = 2.0 * (MENU_BUTTON_WIDTH + TOOLBAR_SPACING) + 4.0 * (TOOLBAR_ICON_SIZE + TOOLBAR_SPACING); - let channel_width = (ui.available_width() - buttons).clamp(CHANNEL_BOX_MIN_WIDTH, CHANNEL_BOX_WIDTH); - ui.allocate_ui(vec2(channel_width, ICON_BUTTON_SIZE), |ui| { - egui::ComboBox::from_id_salt("layer_channel").width(channel_width).truncate().selected_text(tr(app.ui.layer_channel.label())).show_ui( - ui, - |ui| { - for channel in channels { - ui.selectable_value(&mut app.ui.layer_channel, channel, tr(channel.label())); - } - }, - ); - }); - ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| { - let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); - match &selected { - Some(layer) => effect_menu(app, ui, layer), - None => { - ui.label(RichText::new(tr("Select a layer")).color(tokens.text_dim)); - } - } - }) - .response - .on_hover_text(tr("Add effect")); - ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); - if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.paint", Value::Null); - } - if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.fill", Value::Null); - } - if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.group", Value::Null); - } - if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.remove", Value::Null); - } - }) - }); - // The empty state has no layers: the toolbar stays, greyed + let project_open = app.session.project_open; + ui.add_enabled_ui(project_open, |ui| crate::layer_toolbar::show(app, ui)); if !project_open { return; } @@ -301,45 +236,6 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "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 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 go where the others do - let items = [ - (tr("Add generator"), "effect.add.generator", json!({})), - (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!({"target": target})), - ]; - for (label, command, params) in items { - if !ui.button(label).clicked() { - continue; - } - - if app.session.selected_layer() != Some(layer.id) { - app.run("layer.select", 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()) - { - app.ui.dock.focus(crate::docking::Panel::Properties); - crate::filter_slot::open_picker_when_shown(ui.ctx(), effect); - } - - ui.close(); - } -} - /// Layer rows alternate between two shades so neighbours read as separate items. fn row_shade(tokens: &Tokens, index: usize) -> Color32 { if index.is_multiple_of(2) { tokens.row } else { tokens.row.lerp_to_gamma(tokens.row_hover, ALTERNATE_LAYER_SHADE) } @@ -361,14 +257,6 @@ pub fn layer_eye_colors(tokens: &Tokens, visible: bool) -> (Color32, Option Option<[(&'static str, &'static str); 3]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; @@ -1932,6 +1854,15 @@ pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static s let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false)) } + StackTarget::Effect(effect) => mask_fill_of(project, effect).map(|_| crate::fill_panel::fill_tabs(true)), + _ => None, + } +} + +/// Effect `effect`'s source, projection and sampling when it is a mask fill the Properties panel lays out like a fill (a decal's placed fill keeps its own rows) +fn mask_fill_of(project: &texturecraft_engine::core::Project, effect: LayerId) -> Option<(&Source, &Projection, Sampling)> { + match &project.effect(effect)?.1.kind { + EffectKind::Fill { source, projection, sampling } if projection.placed().is_none() => Some((source, projection, *sampling)), _ => None, } } @@ -1959,19 +1890,38 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { match (&selected, app.session.target) { // Polygon fill shows its own settings and says what it fills into, wherever it can fill _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), - (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Effect(effect)) if mask_fill_of(&app.session.doc.project, effect).is_some() => mask_fill_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Effect(effect)) => { + effect_properties(app, ui, layer, effect); + let painted = app.session.doc.project.effect(effect).is_some_and(|(_, effect)| matches!(effect.kind, EffectKind::Paint | EffectKind::Path(_))); + if painted && grayscale_tab_open(app) { + crate::mask_paint_panel::grayscale_sheet(app, ui); + } + } (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { - 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(layer), StackTarget::Content) if layer.instance_source().is_some() => legacy_body(ui, |ui| instance_properties(app, ui, layer)), (Some(layer), StackTarget::Mask) => legacy_body(ui, |ui| { - height_mask_section(app, ui, layer); - if tool_usable { - ui.separator(); - tool_properties(app, ui); + (Some(layer), StackTarget::Content) if layer.is_group() => crate::folder_properties::folder_properties(app, ui, layer.id), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => crate::instance_properties::instance_properties(app, ui, layer), + (Some(layer), StackTarget::Mask) => { + legacy_body(ui, |ui| { + // Add mask > Height combination took its place; a layer saved with it on can still turn it off here + let height_shown = app.session.doc.project.content_layer(layer.id).is_some_and(|content| content.height_mask.enabled); + if height_shown { + height_mask_section(app, ui, layer); + } + if tool_usable { + if height_shown { + ui.separator(); + } + tool_properties(app, ui); + } + }); + if tool_usable && grayscale_tab_open(app) { + crate::mask_paint_panel::grayscale_sheet(app, ui); } - }), + } (None, _) if !tool_usable => legacy_body(ui, |ui| { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); }), @@ -1979,25 +1929,9 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// An instance draws its source: point there for edits. -fn instance_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { - let tk = Tokens::get(ui.ctx()); - let Some(src) = layer.instance_source() else { return }; - let p = &app.session.doc.project; - let name = p.layers.get(&src).map_or_else(|| tr("a missing layer").to_string(), |l| format!("\"{}\"", l.name)); - let set = p.locate(src).and_then(|(ts, _, _)| p.texture_sets.get(ts)).map(|t| t.name.clone()).unwrap_or_default(); - ui.label(caption(tr("Instance"))); - ui.label( - RichText::new(format!( - "{} {}", - ic::LINK, - trf("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", &[("name", &name), ("set", &set)]) - )) - .color(tk.text_dim), - ); - if ui.button(tr("Select source")).clicked() { - app.run("layer.select", json!({"layer": src.0})); - } +/// Whether the tool panel's third tab is open while a mask is painted: its Grayscale tab, drawn under the tool's rows +fn grayscale_tab_open(app: &TextureCraftApp) -> bool { + app.ui.props_tab == PropsTab::Material && !targets_content(app) } /// Mask with height: the layer's height shapes its mask transitions. @@ -2052,6 +1986,8 @@ const BRUSH_PREVIEW_GAP: f32 = 4.0; fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); + let content = targets_content(app); + // Brush preview: a stroke and a sphere with the tool's material let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); let painter = ui.painter(); @@ -2070,14 +2006,28 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { painter.add(egui::Shape::line(points, Stroke::new(stroke_width, Color32::from_white_alpha(alpha.max(PREVIEW_STROKE_MIN_ALPHA))))); let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); - // The sphere sits in the middle of the preview's right half - crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); + // A mask stroke shows the gray it lays down and no material + let gray = match (content, &app.session.tool.mask_image) { + (false, None) => (app.session.tool.mask_value.clamp(0.0, 1.0) * 255.0).round() as u8, + _ => u8::MAX, + }; + let stroke_color = Color32::from_rgba_unmultiplied(gray, gray, gray, alpha.max(PREVIEW_STROKE_MIN_ALPHA)); + painter.add(egui::Shape::line(points, Stroke::new(stroke_width, stroke_color))); + if content { + let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + + // The sphere sits in the middle of the preview's right half + crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); + } ui.add_space(BRUSH_PREVIEW_GAP); ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; + + // Painting a mask, the material tab becomes the Grayscale tab + let material = if content { (ic::SPHERE, tr("Material")) } else { (ic::SQUARE_HALF, tr("Grayscale")) }; 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"))] + [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, material.0, material.1)] { if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { app.ui.props_tab = tab; @@ -2107,7 +2057,9 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { match app.ui.props_tab { PropsTab::Brush => brush_section(app, ui), PropsTab::Alpha => alpha_section(app, ui), - PropsTab::Material => material_section(app, ui), + PropsTab::Material if content => material_section(app, ui), + // A mask's Grayscale tab is a property sheet, drawn by the caller past this panel's margins + PropsTab::Material => {} } } @@ -2669,7 +2621,7 @@ fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec Value { merged } -/// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). +/// Anchor points (content and mask ones) below layer `reader` in its texture set: (effect id, its name, or "layer / name" where two share a name; marked off in a mask turned off) pub(crate) fn anchors_below(project: &texturecraft_engine::core::Project, reader: LayerId) -> Vec<(LayerId, String)> { let Some((texture_set, _, _)) = project.locate(reader) else { return Vec::new() }; - project + + // (id, layer name, anchor name, in a mask, the mask off) + let anchors: Vec<(LayerId, &str, &str, bool, bool)> = project .walk(texture_set) .into_iter() .map(|(id, _)| id) .take_while(|id| *id != reader) .filter_map(|id| project.layers.get(&id)) .flat_map(|layer| { - let mask = layer.mask.iter().flat_map(|mask| { - mask.effects.iter().filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(move |effect| { - let label = trf("{layer} / mask / {name}", &[("layer", &layer.name), ("name", &effect.name)]); - (effect.id, if mask.enabled { label } else { format!("{label} ({})", tr("Off")) }) - }) - }); - let content = layer - .content_effects - .iter() - .filter(|effect| matches!(effect.kind, EffectKind::Anchor)) - .map(|effect| (effect.id, format!("{} / {}", layer.name, effect.name))); - content.chain(mask).collect::>() + let content = layer.content_effects.iter().map(|effect| (effect, false, false)); + let mask = layer.mask.iter().flat_map(|mask| mask.effects.iter().map(move |effect| (effect, true, !mask.enabled))); + content + .chain(mask) + .filter(|(effect, _, _)| matches!(effect.kind, EffectKind::Anchor)) + .map(move |(effect, in_mask, off)| (effect.id, layer.name.as_str(), effect.name.as_str(), in_mask, off)) + }) + .collect(); + let shared = |name: &str| anchors.iter().filter(|anchor| anchor.2 == name).count() > 1; + anchors + .iter() + .map(|&(id, layer, name, in_mask, off)| { + let label = match (shared(name), in_mask) { + (false, _) => name.to_owned(), + (true, false) => format!("{layer} / {name}"), + (true, true) => trf("{layer} / mask / {name}", &[("layer", &layer), ("name", &name)]), + }; + (id, if off { format!("{label} ({})", tr("Off")) } else { label }) }) .collect() } @@ -2883,6 +2835,18 @@ pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Chan if mask_anchor_enabled(app, anchor) == Some(false) { format!("{label} ({})", tr("Off")) } else { label } } +/// A mask fill effect: its Fill, Symmetry and Grayscale sections as one sheet (its blending is on its row) +fn mask_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { + let Some((source, projection, sampling)) = + mask_fill_of(&app.session.doc.project, effect_id).map(|(source, projection, sampling)| (source.clone(), projection.clone(), sampling)) + else { + return; + }; + PropertySheet::show(ui, ("mask_fill_sheet", effect_id.0), |sheet| { + crate::mask_fill_panel::mask_fill_sheet(app, sheet, effect_id, source, projection, sampling, layer.id); + }); +} + /// Slider range of a fill's scale or tiling const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; @@ -3104,31 +3068,30 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe match &effect.kind { EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), EffectKind::Levels(levels) => legacy_body(ui, |ui| crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels)), + EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); let name = match source { Source::Anchor { anchor, channel, .. } => { - let project = &app.session.doc.project; let owner = project.effect(*anchor).and_then(|(owner, _)| project.layers.get(&owner)); let read = if anchor_in_mask(app, *anchor) { "Mask" } else { channel.label() }; format!("{} · {}", owner.map_or_else(|| tr("missing").to_string(), |layer| layer.name.clone()), tr(read)) - } + let current = match source { + Source::Anchor { anchor, channel, .. } => anchor_label(app, *anchor, *channel), Source::Uniform(_) => tr("Uniform value").to_string(), Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), Source::Image { name, .. } => name.clone(), + Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]), }; - // Main's Grayscale slot on the new picker: patterns, images and a uniform value, or the anchor points below let (rect, source_response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::filter_slot::SLOT_HEIGHT), Sense::click()); source_response.widget_info(|| egui::WidgetInfo { current_text_value: Some(name.clone()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, tr("Grayscale")) - }); let (ctx, popup) = (ui.ctx().clone(), ui.make_persistent_id(("fill_source_picker", id))); if source_response.clicked() { crate::resource_picker::toggle(&ctx, popup); - } let highlighted = source_response.hovered() || egui::Popup::is_id_open(&ctx, popup); crate::filter_slot::paint(ui, rect, (highlighted, source_response.has_focus()), None, (tr("Grayscale"), &name)); let current = crate::fill_material_panel::source_choice(source); @@ -3137,7 +3100,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe let mut tabs = crate::fill_material_panel::source_tabs(thumbs, &ctx, &images, &anchors, Color32::from_gray(204)); tabs.iter_mut().for_each(|tab| tab.groups.retain(|group| group.header != Some(tr("Alphas")))); tabs - }); let anchor_channel = if let Source::Anchor { channel, .. } = source { *channel } else { Channel::Height }; let params = match picked.filter(|choice| *choice != current) { Some(SourceChoice::Procedural(kind)) => Some(json!({"effect": id, "procedural": kind.label()})), @@ -3145,14 +3107,20 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe Some(SourceChoice::Uniform) => Some(json!({"effect": id, "uniform": 1.0})), Some(SourceChoice::Anchor(anchor)) => Some(json!({"effect": id, "anchor": anchor.0, "anchorChannel": anchor_channel.id()})), Some(SourceChoice::Import) => { - crate::menus::invoke(app, &ctx, "resource.import"); None + let source_response = combo(ui, tr("Source"), current, |ui| { + if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "value": 1.0})); } Some(SourceChoice::Alpha(_)) | None => None, - }; if let Some(params) = params { - app.run("effect.set", params); - } + if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "image": name})); + } + }); // The source selector accepts image drops from the Assets panel if let Some(name) = image_drop(ui, &source_response.interact(Sense::hover())) { @@ -3200,19 +3168,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe }); } EffectKind::Anchor => legacy_body(ui, |ui| { - ui.label(caption(tr("Anchor point"))); - let text = if anchor_in_mask(app, effect_id) { - tr("Records the mask value at this point. Fill effects and generators in masks above can read it.") - } else { - tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.") - }; - ui.label(RichText::new(text).color(tokens.text_dim)); - }), + EffectKind::Anchor => crate::anchor_properties::anchor_properties(app, ui, effect_id, &effect.name), EffectKind::Paint => legacy_body(ui, |ui| { let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { 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.") + tr("Paint on the mesh to edit this mask.") }; ui.label(RichText::new(hint).color(tokens.text_dim)); if app.session.tool_usable(app.session.tool.tool) { @@ -3247,6 +3208,18 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), EffectKind::ColorSelection { colors, tolerance } => { legacy_body(ui, |ui| crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance)) + EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), + EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { + let settings = crate::compare_settings::CompareSettings { + op: *op, + constant: *value, + tolerance: *tolerance, + left: *left, + right: *right, + channel: *channel, + hardness: *hardness, + }; + crate::compare_properties::compare_properties(app, ui, layer, effect_id, settings); } other => legacy_body(ui, |ui| { ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); diff --git a/crates/ui-egui/src/exact_entry_open.rs b/crates/ui-egui/src/exact_entry_open.rs new file mode 100644 index 00000000..67abc1b5 --- /dev/null +++ b/crates/ui-egui/src/exact_entry_open.rs @@ -0,0 +1,5 @@ +//! The Levels editor's mark that its exact-entry fields are shown + +/// Marks the exact-entry fields as shown; they appear on a handle's double-click or Enter and close when typing ends +#[derive(Clone, Copy)] +pub(crate) struct ExactEntryOpen; diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index c58c9807..4d4db43e 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -179,6 +179,7 @@ pub(crate) fn source_line(app: &TextureCraftApp, source: &Source) -> String { } /// One source's card (a channel's): its slot (the row opens the source picker), then the source's own settings; `in_card`: only its slot row, inside the card open now +/// One source's card (a channel's, a mask fill's grayscale or a filter's image input): its slot (the row opens the source picker), then the source's own settings; `in_card`: only its slot row, inside the card open now pub(crate) fn source_card( app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, @@ -260,11 +261,23 @@ pub(crate) fn source_card( } } } + Source::Anchor { anchor, channel, .. } if slot_of == SourceSlot::Grayscale && !crate::dock::anchor_in_mask(app, anchor) => { + anchor_channel_row(app, sheet, base, reader, channel); + } Source::Image { .. } | Source::Anchor { .. } => {} } sheet.close_card(); } +/// The channel a mask fill reads from a content anchor point as gray (a mask anchor point reads its mask's one gray) +fn anchor_channel_row(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, base: &Value, reader: LayerId, channel: Channel) { + let project = &app.session.doc.project; + let channels = project.locate(reader).and_then(|(set, _, _)| project.texture_set(set).ok()).map(|set| set.channel_list()).unwrap_or_default(); + if let (Some(picked), _) = sheet.dropdown(tr("Channel"), channel, &channels, |option| tr(option.label()).to_string(), None) { + app.run("effect.set", with(base, json!({"anchorChannel": picked.id()}))); + } +} + /// Runs the fill command `choice` asks for on the slot (Import opens the import dialog) fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSlot, choice: SourceChoice, set: &impl Fn(Value) -> Value) { match choice { @@ -290,6 +303,7 @@ fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSl /// The picker's choice `source` is: a library alpha's image is its alpha pub(crate) fn source_choice(source: &Source) -> SourceChoice { +fn source_choice(source: &Source) -> SourceChoice { match source { Source::Uniform(_) => SourceChoice::Uniform, Source::Procedural { pattern, .. } => SourceChoice::Procedural(pattern.kind), @@ -306,6 +320,7 @@ pub(crate) fn source_tabs( anchors: &[(LayerId, String)], uniform: Color32, ) -> Vec> { +fn source_tabs(thumbs: &mut Thumbs, ctx: &egui::Context, images: &ImageStore, anchors: &[(LayerId, String)], uniform: Color32) -> Vec> { let procedurals = ProceduralKind::ALL.into_iter().map(|kind| tile(SourceChoice::Procedural(kind), tr(kind.label()), None, TilePicture::Procedural(kind))).collect(); let textures = ResourcePickerItem::textures(images, SourceChoice::Import, |name| SourceChoice::Image(name.to_owned())); @@ -419,8 +434,15 @@ fn procedural_rows( let mut edited = pattern.clone(); let mut edit = scale_and_contrast(sheet, &mut edited); - if sheet.fold(tr("Attributes"), None, false) { + + // A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes + if gray { edit = edit.or(balance_and_seed(sheet, &mut edited)); + } + if sheet.fold(tr("Attributes"), None, false) { + if !gray { + edit = edit.or(balance_and_seed(sheet, &mut edited)); + } if sheet.toggle(tr("Invert"), &mut edited.invert) { edit = edit.or(Some(("invert", json!(edited.invert), false))); } diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 43b0a9d5..5a9fa0d7 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -370,6 +370,7 @@ mod tests { use super::*; + /// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another #[test] fn the_ring_spaces_its_copies_as_the_engine_does() { let symmetry = FillSymmetry { on: true, kind: SymmetryKind::Radial, count: 6, span: 720.0, ..FillSymmetry::OFF }; diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index c41b7021..1fa4929f 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -60,9 +60,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: match groups.last_mut() { Some(group) if group.header == Some(tr(def.group)) => group.items.push(item), _ => groups.push(PickerGroup { header: Some(tr(def.group)), items: vec![item] }), - } - } vec![PickerTab { icon: ic::FUNNEL, name: tr("Filter"), groups }] + let mut items: Vec> = filter_effects() + .iter() + .filter(|def| def.mask || !on_mask) + .map(|def| ResourcePickerItem { + id: def.id, + label: tr(def.label).to_owned(), + caption: None, + picture: TilePicture::Texture(thumbs.filter(&ctx, def.id)), + }) + .collect(); + + // One kind of resource: one grid in name order, no group captions + items.sort_by_cached_key(|item| item.label.to_lowercase()); + vec![PickerTab { icon: ic::FUNNEL, name: tr("Filters"), groups: vec![PickerGroup { header: None, items }] }] }; let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); if let Some(id) = picked.filter(|id| Some(*id) != current) { diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 60e5a7b4..dce44a17 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -9,7 +9,7 @@ use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor use rayon::prelude::*; use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, kinds_for, tile_bytes}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, LayerId}; use texturecraft_engine::geom::Mesh; use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu}; @@ -19,11 +19,13 @@ use crate::bake_scene::{BakeSceneLink, CageUpload}; #[derive(Clone, Copy, Debug, PartialEq)] pub enum AuxView { MeshMap(BakedMap), - Mask(texturecraft_engine::core::LayerId), + Mask(LayerId), /// The quick mask being edited, over the base color. QuickMask, /// The project image of the view picker's "Other..." (`Session::view_image`) Image, + /// The image a color selection reads as its ID mask on its texture set, the ID mesh map on the others (its pick mode) + IdMask(LayerId), } /// A texture set's texels across and down, and its mesh material. @@ -286,29 +288,10 @@ impl GpuLink { } match aux_map { - Some(AuxView::MeshMap(map)) => { - for texture_set in 0..session.caches.len() { - // Streamed bake maps replace document maps while the bake is visible - let preview = session.bake_preview_baked(texture_set); - let baked = preview.or_else(|| session.doc.baked.get(&texture_set)); - let have = baked.and_then(|baked| baked.maps.get(&map)); - let revision = have.map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); - let key = (format!("{map:?}{}", if preview.is_some() { "~" } else { "" }), revision); - if self.aux.get(&texture_set) == Some(&key) { - continue; - } - - let Some(cache) = session.caches.get(texture_set) else { continue }; - - let resolution = texturecraft_render::aux_size(cache.size); - let rgba = if preview.is_some() && have.is_none() { - texturecraft_render::mesh_maps::neutral_rgba(map, resolution) - } else { - texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, resolution, cache.size, &cache.composite.block_scales) - }; - out.aux.push((texture_set, resolution, rgba)); - self.aux.insert(texture_set, key); - } + Some(AuxView::MeshMap(map)) => self.sync_mesh_maps(session, map, None, &mut out), + Some(AuxView::IdMask(effect)) => { + let shown = self.sync_id_mask(session, effect, &mut out); + self.sync_mesh_maps(session, BakedMap::Id, shown, &mut out); } Some(AuxView::Mask(id)) => { if let Some((texture_set, _, _)) = session.doc.project.locate(id) { @@ -382,6 +365,50 @@ impl GpuLink { self.bake_scene.sync(session, bake, &mut out); out } + + /// Queues mesh map `map` for every texture set but `skip` whose aux texture shows something else + fn sync_mesh_maps(&mut self, session: &Session, map: BakedMap, skip: Option, out: &mut SceneSync) { + for texture_set in 0..session.caches.len() { + if skip == Some(texture_set) { + continue; + } + + // Streamed bake maps replace document maps while the bake is visible + let preview = session.bake_preview_baked(texture_set); + let baked = preview.or_else(|| session.doc.baked.get(&texture_set)); + let have = baked.and_then(|baked| baked.maps.get(&map)); + let revision = have.map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}{}", if preview.is_some() { "~" } else { "" }), revision); + if self.aux.get(&texture_set) == Some(&key) { + continue; + } + + let Some(cache) = session.caches.get(texture_set) else { continue }; + let resolution = texturecraft_render::aux_size(cache.size); + let rgba = if preview.is_some() && have.is_none() { + texturecraft_render::mesh_maps::neutral_rgba(map, resolution) + } else { + texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, resolution, cache.size, &cache.composite.block_scales) + }; + out.aux.push((texture_set, resolution, rgba)); + self.aux.insert(texture_set, key); + } + } + + /// Queues the image color selection `effect` reads as its ID mask on its texture set; the texture set it shows on, None when it reads the ID mesh map + fn sync_id_mask(&mut self, session: &Session, effect: LayerId, out: &mut SceneSync) -> Option { + let (texture_set, image) = session.id_mask_image(effect)?; + let cache = session.caches.get(texture_set)?; + let resolution = texturecraft_render::aux_size(cache.size); + let key = (format!("idMask{}:{resolution}", effect.0), Arc::as_ptr(image) as u64); + if self.aux.get(&texture_set) != Some(&key) + && let Some(rgba) = session.id_mask_view_rgba(effect, resolution) + { + out.aux.push((texture_set, resolution, rgba)); + self.aux.insert(texture_set, key); + } + Some(texture_set) + } } fn record_recreated_uploads(recreated: &mut BTreeMap>, reset: &[usize], sync: &SceneSync) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2206f55e..db514466 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/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 anchor_properties; mod angle_dial; mod ask; mod bake_job; @@ -18,6 +19,8 @@ mod bake_scene; mod color_management; mod color_picker; mod color_selection_editor; +mod compare_properties; +mod compare_settings; pub mod control; mod decal_drop; mod display_settings; @@ -25,6 +28,7 @@ pub mod dock; pub mod docking; mod drawn_icon; mod environment_picker; +mod exact_entry_open; mod export_panel; pub mod export_templates; mod export_window; @@ -35,27 +39,35 @@ mod fill_panel; mod fill_pictures; mod fill_symmetry_panel; mod filter_slot; +mod folder_properties; pub mod fonts; mod frame_gizmo; mod generator_panel; pub mod gpu; mod gray_slider; mod grid_tile; +mod histogram_cache; pub mod i18n; pub mod id_color_pick; #[cfg(not(target_arch = "wasm32"))] mod import_resources; mod inactive_set_hint; +mod instance_properties; pub mod keymap; pub mod layer_panel; +mod layer_toolbar; mod layout_dialog; +mod levels_display; mod levels_editor; mod levels_handle; mod levels_properties; mod line_snap; mod list_action; pub mod log_panel; +mod mask_fill_panel; +mod mask_paint_panel; mod mask_preview_image; +mod mask_source_choice; mod material_orb; mod material_preview_image; pub mod menus; @@ -101,6 +113,7 @@ pub mod properties_popup; mod property_sheet; mod query_field; mod rail_popup; +mod reference; pub mod render_mode; mod resolution_band; mod resource_panel; diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs index 37a15b5c..b42bdbfb 100644 --- a/crates/ui-egui/src/move_on_model.rs +++ b/crates/ui-egui/src/move_on_model.rs @@ -350,6 +350,32 @@ mod tests { assert_eq!(projection(&harness, layer), slid, "no mode is left on"); } + /// A mask fill's warp frame moves with the hold as a fill layer's does: the frame slides, not only the image inside it + #[test] + fn holding_a_mask_fills_pad_slides_its_frame() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("mask.add.black", json!({"layer": layer.0})).unwrap(); + let effect = harness.state_mut().run("effect.add.fill", json!({"layer": layer.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + harness.state_mut().run("layer.fill.projection", json!({"effect": effect, "projection": "warp"})).unwrap(); + harness.state_mut().run("layer.select", json!({"layer": layer.0, "target": effect})).unwrap(); + harness.run_steps(4); + let mask_projection = |harness: &Harness| match &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Fill { projection, .. } => projection.clone(), + other => panic!("a mask fill: {other:?}"), + }; + let Projection::Warp { frame: before, uv: uv_before, .. } = mask_projection(&harness) else { panic!("a warp") }; + + let mut pointer = press_the_button(&mut harness); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel { layer, effect: Some(LayerId(effect)) }), "a press starts the hold"); + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + + let Projection::Warp { frame: after, uv: uv_after, .. } = mask_projection(&harness) else { panic!("still a warp") }; + assert_ne!(after.offset, before.offset, "the frame slid"); + assert_eq!(uv_after, uv_before, "not only the image inside it"); + } + /// Losing the focus mid-hold (Alt+Tab) ends it as letting go does: one undo step, the pointer shown, and moves after it (egui still has the button down) leave the projection alone #[test] fn losing_the_window_focus_mid_hold_ends_it_as_letting_go_does() { diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index e0bd4da4..0e05486f 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -33,14 +33,11 @@ impl OrbEnvironment { fn from_hdr(bytes: &[u8]) -> Option { let decoded = image::load_from_memory_with_format(bytes, image::ImageFormat::Hdr).inspect_err(|e| log::warn!("the orb studio did not load: {e}")).ok()?; - - let rgb = decoded.into_rgb32f(); - let (pixels, _) = rgb.as_raw().as_chunks::<3>(); let rgba: Vec<[f32; 4]> = pixels.iter().map(|&[red, green, blue]| [red, green, blue, 1.0]).collect(); let env = EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false)?; - drop(rgb); - - Some(OrbEnvironment::of(&env)) + let rgb = decoded.to_rgb32f(); + let rgba: Vec<[f32; 4]> = rgb.pixels().map(|pixel| [pixel[0], pixel[1], pixel[2], 1.0]).collect(); + EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false).map(|env| OrbEnvironment::of(&env)) } /// The built-in procedural studio, should the bundled one ever fail to decode diff --git a/crates/ui-egui/src/property_sheet/action_row.rs b/crates/ui-egui/src/property_sheet/action_row.rs new file mode 100644 index 00000000..8eaf51cd --- /dev/null +++ b/crates/ui-egui/src/property_sheet/action_row.rs @@ -0,0 +1,62 @@ +//! A row of section actions: buttons as wide as their words from the left, an on/off with its label at the right end + +use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use super::switch_control::PILL_SIZE; +use super::{ActionRowResponse, CONTROL_HEIGHT, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; + +/// Air on each side of a button's word +const BUTTON_WORD_AIR: f32 = 9.0; + +/// Air between two buttons +const BUTTON_GAP: f32 = 6.0; + +/// Air between the toggle's label and its pill +const TOGGLE_LABEL_AIR: f32 = 9.0; + +/// From the right edge to the toggle's centre (the pill ends on the edge), and to its label's end +const TOGGLE_CENTER_INSET: f32 = PILL_SIZE.x / 2.0; +const TOGGLE_LABEL_INSET: f32 = PILL_SIZE.x + TOGGLE_LABEL_AIR; + +impl PropertySheet<'_> { + /// `buttons` (word, enabled) from the left edge, then `toggle_label` and its toggle at the right end + pub(crate) fn action_row(&mut self, buttons: &[(&str, bool)], toggle_label: &str, on: &mut bool) -> ActionRowResponse { + let row = self.take(ROW_HEIGHT); + let center_y = row.center().y; + self.drawn(center_y + CONTROL_HEIGHT / 2.0); + let font = FontId::proportional(TEXT_SIZE); + let tokens = self.tokens; + + let mut clicked = None; + let mut x = self.left; + for (index, (word, enabled)) in buttons.iter().enumerate() { + let width = self.text_width(word, font.clone()) + 2.0 * BUTTON_WORD_AIR; + let button = Rect::from_min_size(pos2(x, center_y - CONTROL_HEIGHT / 2.0), vec2(width, CONTROL_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(button, id, if *enabled { Sense::click() } else { Sense::hover() }); + response.widget_info(|| WidgetInfo::labeled(Role::Button, *enabled, *word)); + if *enabled && response.clicked() { + clicked = Some(index); + } + + let fill = if *enabled && response.hovered() { tokens.row_hover } else { tokens.button }; + let painter = self.ui.painter(); + painter.rect(button, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + painter.text(button.center(), Align2::CENTER_CENTER, *word, font.clone(), if *enabled { tokens.text } else { tokens.text_dim }); + x = button.right() + BUTTON_GAP; + } + + let label_end = self.right - TOGGLE_LABEL_INSET; + let pill = pos2(self.right - TOGGLE_CENTER_INSET, center_y); + let hit = Rect::from_min_max(pos2(label_end - self.text_width(toggle_label, font.clone()), row.top()), pos2(self.right, row.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, toggle_label)); + self.ui.painter().text(pos2(label_end, center_y), Align2::RIGHT_CENTER, toggle_label, font, tokens.text); + self.pill(pill, *on, true); + ActionRowResponse { clicked, toggled: response.clicked() } + } +} diff --git a/crates/ui-egui/src/property_sheet/action_row_response.rs b/crates/ui-egui/src/property_sheet/action_row_response.rs new file mode 100644 index 00000000..fe7a383b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/action_row_response.rs @@ -0,0 +1,9 @@ +//! What happened on an action row this frame + +/// What an action row's user did this frame +pub(crate) struct ActionRowResponse { + /// The button clicked + pub(crate) clicked: Option, + /// Whether the toggle flipped + pub(crate) toggled: bool, +} diff --git a/crates/ui-egui/src/property_sheet/factor_slider.rs b/crates/ui-egui/src/property_sheet/factor_slider.rs new file mode 100644 index 00000000..eddf9f72 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/factor_slider.rs @@ -0,0 +1,25 @@ +//! A factor slider: ×1 in the middle, halving to the left and doubling to the right + +use std::ops::RangeInclusive; + +use super::PropertySheet; +use super::slider::{KNOB_RADIUS, kept_in}; +use super::track::Track; + +impl PropertySheet<'_> { + /// A factor (×1.50) on a track `doublings` halvings or doublings each way from ×1 (marked by the zero tick); a typed value may go past the track's ends, within `typed`. `Some(merge)` when it changed + pub(crate) fn factor_slider(&mut self, label: &str, factor: &mut f32, doublings: f32, typed: RangeInclusive) -> Option { + let (control, center_y) = self.row(label); + let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; + let track_range = -doublings..=doublings; + let mut along = kept_in(factor.max(f32::MIN_POSITIVE).log2(), &track_range); + let dragged = self.track(id, label, &track, &mut along, &track_range); + if dragged.is_some() { + *factor = along.exp2(); + } + let shown = format!("×{:.2}", *factor); + let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, 2); + Self::apply_typed(factor, entered, dragged) + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 65806206..fe8a47dd 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -1,16 +1,24 @@ //! The Properties panel's rows, groups and controls, shared by every panel so they line up +mod action_row; +mod action_row_response; mod axis_rows; mod band_response; mod button_icon; mod choice; mod color_bar; mod color_picker_rows; +mod compare_row; +mod compare_row_response; mod eye_toggle; +mod factor_slider; mod group; mod hold_pad; +mod id_color_row; +mod id_color_row_response; mod info_icon; mod material_rows; +mod name_field; mod number_field; mod open_card; mod preview_block; @@ -18,6 +26,7 @@ mod preview_edit; mod preview_lower; mod preview_size; mod ramp_edit; +mod reference_row; mod row; mod row_lead; mod section_tabs; @@ -25,6 +34,7 @@ mod sheet_measure; mod slider; mod slot; mod slot_response; +mod source_card; mod stack_slider; mod switch_control; mod tooltip; @@ -35,8 +45,11 @@ mod value_text_draft; #[cfg(test)] mod tests; +pub(crate) use action_row_response::ActionRowResponse; pub(crate) use band_response::BandResponse; pub(crate) use button_icon::ButtonIcon; +pub(crate) use compare_row_response::CompareRowResponse; +pub(crate) use id_color_row_response::IdColorRowResponse; pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; pub(crate) use preview_size::PreviewSize; @@ -111,6 +124,9 @@ const ROW_HIT_HALF_HEIGHT: f32 = 10.0; /// Size of a row's glyph button glyphs (eyedropper, remove, arrow) const GLYPH_SIZE: f32 = 13.0; +/// Corner radius of a hovered row's face +const ROW_RADIUS: u8 = 6; + /// Corner radius of dropdowns, fields and buttons const CONTROL_RADIUS: u8 = 4; diff --git a/crates/ui-egui/src/property_sheet/name_field.rs b/crates/ui-egui/src/property_sheet/name_field.rs new file mode 100644 index 00000000..6435fc3b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/name_field.rs @@ -0,0 +1,48 @@ +//! A name typed in place: a field in the controls column, outlined in the accent while it is typed in + +use egui::{CornerRadius, Stroke, StrokeKind}; + +use super::{CONTROL_RADIUS, PropertySheet, TEXT_SIZE}; +use crate::theme::semibold; + +/// Air before the field's text +const TEXT_INSET: i8 = 8; + +impl PropertySheet<'_> { + /// A field holding `name`; returns the new name once typing ends (Enter or a click elsewhere) with a changed, non-blank name. Escape keeps the old one + pub(crate) fn name_field(&mut self, label: &str, name: &str) -> Option { + let (control, _) = self.row(label); + let typing_id = self.next_id().with("typed"); + let typing = self.ui.memory(|memory| memory.has_focus(typing_id)); + + // The draft is read even when the focus already left (Shift+Tab, a field built earlier this frame took it): it commits below; it lasts one frame without the focus. Escape drops it, read from the frame's raw input as an app shortcut may already have taken the key + let escaped = + self.ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if escaped { + self.ui.data_mut(|data| data.remove::(typing_id)); + } + let mut text = self.ui.data(|data| data.get_temp::(typing_id)).unwrap_or_else(|| name.to_owned()); + + let tokens = self.tokens; + let outline = Stroke::new(1.0, if typing { tokens.accent } else { tokens.field_border }); + self.ui.painter().rect(control, CornerRadius::same(CONTROL_RADIUS), tokens.field, outline, StrokeKind::Inside); + let edit = egui::TextEdit::singleline(&mut text) + .id(typing_id) + .font(semibold(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(TEXT_INSET, 0))) + .align(egui::Align2::LEFT_CENTER); + let response = self.ui.put(control.shrink(1.0), edit); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, label)); + self.drawn(control.bottom()); + + if response.has_focus() { + self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + return None; + } + + self.ui.data_mut(|data| data.remove::(typing_id)); + let typed = text.trim(); + (response.lost_focus() && !escaped && !typed.is_empty() && typed != name).then(|| typed.to_owned()) + } +} diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index bd1f5cc4..be6936e2 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -195,6 +195,7 @@ impl PropertySheet<'_> { self.seen.label_width = self.seen.label_width.max(width); } + let text = self.tokens.text; if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { self.paint_info(center_y); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); @@ -215,6 +216,14 @@ impl PropertySheet<'_> { self.left } + /// A dim caption line above its control (Offset, Size…) + pub(crate) fn caption(&mut self, text: &str) { + let rect = self.take(CAPTION_LINE); + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(self.left, rect.top() + CAPTION_LINE / 2.0), Align2::LEFT_CENTER, text, FontId::proportional(SMALL_TEXT_SIZE), dim); + self.drawn(rect.bottom()); + } + /// A caret pointing down (open) or right (folded), centred on `center` pub(super) fn caret(&self, center: egui::Pos2, open: bool, color: egui::Color32) { let glyph = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 08f7eb58..14b8d740 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -75,6 +75,11 @@ impl PropertySheet<'_> { self.angle_shown(lead, degrees, range, false) } + /// An angle added to others: a signed track over `range` with its zero tick, the dial, and the value with its sign ("+30°") + pub(crate) fn relative_angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_shown(RowLead::label(label), degrees, range, true) + } + /// [`Self::angle_led`], the value shown with its sign when `plus` fn angle_shown(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive, plus: bool) -> Option { let (control, center_y) = self.row_with(lead); diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 6717eb3c..468e42a1 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -276,6 +276,7 @@ impl PropertySheet<'_> { if dice_response.clicked() { *seed = next_seed(*seed); + *seed = texturecraft_engine::folder_cmds::next_seed(*seed); changed = true; } changed diff --git a/crates/ui-egui/src/property_sheet/source_card.rs b/crates/ui-egui/src/property_sheet/source_card.rs new file mode 100644 index 00000000..fc152f25 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/source_card.rs @@ -0,0 +1,67 @@ +//! A card for the layer something draws: its thumbnail, its name over a link and its texture set, and an arrow; a click goes to it + +use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::group::CARD_RADIUS; +use super::slot::THUMB_SIZE; +use super::{GROUP_GAP, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Height of the card: 11 px of air above and below the thumbnail, as a slot card has +const CARD_HEIGHT: f32 = 48.0; + +/// Air between the section caption and the card, as above a slot card +const CARD_TOP_AIR: f32 = 6.0; + +/// From the left edge to the name, to the link glyph's centre and to the texture set +const NAME_LEFT: f32 = 36.0; +const LINK_CENTER: f32 = 41.0; +const SET_LEFT: f32 = 51.0; + +/// From the card's centre line up to the name's and down to the texture set's +const NAME_RISE: f32 = 7.0; +const SET_DROP: f32 = 9.0; + +/// Size of the link glyph and of the arrow +const LINK_SIZE: f32 = 12.0; +const ARROW_SIZE: f32 = 14.0; + +/// From the right edge to the arrow's centre +const ARROW_INSET: f32 = 7.0; + +impl PropertySheet<'_> { + /// The card of `name` in texture set `set`, right under its section caption; a `missing` one is dim, shows a broken link and takes no click. Returns true when it was clicked + pub(crate) fn source_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, set: &str, missing: bool) -> bool { + self.close_card(); + self.space(CARD_TOP_AIR); + let rect = self.take(CARD_HEIGHT); + let center_y = rect.center().y; + let face = self.bled_row(rect); + let id = self.next_id(); + let mut response = self.ui.interact(face, id, if missing { Sense::hover() } else { Sense::click() }); + if !missing { + response = response.on_hover_cursor(egui::CursorIcon::PointingHand); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !missing, format!("{name} {set}"))); + let hovered = !missing && response.hovered(); + + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + painter.rect_filled(face, CornerRadius::same(CARD_RADIUS), if hovered { tokens.button } else { tokens.row }); + thumbnail(&painter, Rect::from_min_size(pos2(self.left, center_y - THUMB_SIZE / 2.0), vec2(THUMB_SIZE, THUMB_SIZE))); + let (name_font, name_color) = if missing { (FontId::proportional(TEXT_SIZE), tokens.text_dim) } else { (semibold(TEXT_SIZE), tokens.text) }; + painter.text(pos2(self.left + NAME_LEFT, center_y - NAME_RISE), Align2::LEFT_CENTER, name, name_font, name_color); + let link = if missing { ic::LINK_BREAK } else { ic::LINK }; + painter.text(pos2(self.left + LINK_CENTER, center_y + SET_DROP), Align2::CENTER_CENTER, link, FontId::proportional(LINK_SIZE), tokens.text_dim); + painter.text(pos2(self.left + SET_LEFT, center_y + SET_DROP), Align2::LEFT_CENTER, set, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); + if !missing { + let arrow_color = if hovered { tokens.text } else { tokens.text_dim }; + painter.text(pos2(self.right - ARROW_INSET, center_y), Align2::CENTER_CENTER, ic::ARROW_RIGHT, FontId::proportional(ARROW_SIZE), arrow_color); + } + self.drawn(rect.bottom()); + self.space(GROUP_GAP); + self.air_at = Some(self.cursor_y()); + response.clicked() + } +} diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 1792d9e5..98b278e1 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -105,6 +105,12 @@ impl PropertySheet<'_> { self.dropdown_built(label, selected, || 0..options.len(), name, None).0 } + /// A boxed switch across the whole panel; the chosen word takes its colours from `tints` (several colours split the word between them) + pub(crate) fn wide_switch(&mut self, options: &[&str], selected: usize, tints: &[&[Color32]]) -> Option { + let control = self.wide_row(); + self.segments(control, options, selected, |index| tints.get(index).copied().unwrap_or_default(), None) + } + /// A row's control box, `CONTROL_HEIGHT` tall, from the left padding to the right one pub(super) fn wide_row(&mut self) -> Rect { let row = self.take(ROW_HEIGHT); diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index d47ab16a..67c55f5e 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -7,6 +7,7 @@ use super::number_field::shown_number; use super::slot::next_seed; use super::{NumberField, PropertySheet}; use crate::theme::{Accent, Brightness, Tokens}; +use texturecraft_engine::folder_cmds::next_seed; mod filtering; mod gallery; @@ -99,11 +100,13 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { } } - sheet.toggle("Wrap", &mut state.wrap); - sheet.toggle("Shape Crop", &mut state.crop); - sheet.info(DEPTH_CULLING_TIP); - sheet.picture_toggle(&swatch(Color32::from_gray(160)), "Depth Culling", &mut state.depth_culling); - sheet.picture_toggle(&swatch(Color32::from_gray(100)), "Backface Culling", &mut state.backface_culling); + if sheet.fold("Edges", None, true) { + sheet.toggle("Wrap", &mut state.wrap); + sheet.toggle("Shape Crop", &mut state.crop); + sheet.info(DEPTH_CULLING_TIP); + sheet.picture_toggle(&swatch(Color32::from_gray(160)), "Depth Culling", &mut state.depth_culling); + sheet.picture_toggle(&swatch(Color32::from_gray(100)), "Backface Culling", &mut state.backface_culling); + } sheet.slot(&swatch(Color32::from_rgb(0xb0, 0x5a, 0x3a)), "Base color", "Uniform color", Some(&mut state.channel_on), false, false); sheet.slider("Value", &mut state.channel_value, 0.0..=1.0, 2); @@ -115,6 +118,7 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { } let band = sheet.band("Parameters", true, None, Some("3")); if band.open { + sheet.caption("Offset"); sheet.signed_slider("Horizontal", &mut state.offset, -1.0..=1.0, 2); if sheet.fold("Attributes", Some("Default"), false) { sheet.button(ic::DOT, "No attributes"); @@ -159,38 +163,6 @@ fn toggles_switches_and_pills_change_their_state() { assert_eq!(harness.state().channels, [true, true, true, true, true]); } -#[test] -fn keyboard_focus_is_visible_on_switches_toggles_and_channel_pills() { - let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - for brightness in [Brightness::MediumDark, Brightness::Light] { - let mut harness = builder(brightness).build_ui(|ui| { - ui.set_width(PANEL_WIDTH); - PropertySheet::show(ui, "keyboard", |sheet| { - sheet.switch("Scale", &["Tiling", "Physical size"], 0); - sheet.toggle("Shape Crop", &mut false); - sheet.channel_pills(&["Normal"], &[true]); - }); - }); - harness.run_steps(3); - - for label in ["Tiling", "Physical size", "Shape Crop", "Normal"] { - harness.key_press(egui::Key::Tab); - harness.run_steps(2); - - let node = harness.get_by_label(label); - assert!(node.is_focused(), "{label} receives keyboard focus"); - - let rect = node.rect(); - assert!( - harness.output().shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.stroke.width > 1.0 && shape.rect.center().distance(rect.center()) < 1.0) - }), - "{label} paints a visible focus outline" - ); - } - } -} - /// A toggle's pill starts on the controls column, where a dropdown's button starts (it sat 3 px in) #[test] fn a_toggles_pill_starts_where_a_dropdown_starts() { @@ -234,6 +206,40 @@ fn culling_rows(ui: &mut egui::Ui, on: &mut [bool; 2]) { }); } +/// A section caption's switch and an action row's toggle over a dropdown +fn right_end_switches(ui: &mut egui::Ui, mirror: &mut bool) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "right end", |sheet| { + sheet.section_switch("Symmetry", true); + sheet.action_row(&[("Reset", true)], "Mirror", mirror); + sheet.dropdown("Filtering", Filtering::Nearest, &[Filtering::Nearest], Filtering::name, None); + }); + }); +} + +/// A switch at a caption's or a row's right end ends on the right padding, where a dropdown ends (they sat 3 px in) +#[test] +fn right_end_switches_end_where_a_dropdown_ends() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui_state(right_end_switches, false); + harness.run_steps(3); + + let dropdown_right = harness.get_by_label("Nearest").rect().right(); + let pill_rights: Vec = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Rect(rect) if rect.rect.size() == super::switch_control::PILL_SIZE => Some(rect.rect.right()), + _ => None, + }) + .collect(); + + assert_eq!(pill_rights, [dropdown_right; 2], "the pills end at {pill_rights:?}, the dropdown at {dropdown_right}"); +} + /// A culling name too long for the label column moves every culling row's picture and switch, so the switches stay one column #[test] fn culling_rows_keep_their_switches_in_one_column_when_a_name_is_long() { @@ -246,6 +252,39 @@ fn culling_rows_keep_their_switches_in_one_column_when_a_name_is_long() { assert_eq!(short.right(), long.right(), "both switches end at one x: {short:?} vs {long:?}"); } +/// Under a section caption, an instance card (`instance` true) or a slot card; records where its thumbnail was painted +fn card_under_caption(ui: &mut egui::Ui, state: &mut (bool, std::cell::Cell>)) { + let (instance, thumbnail) = state; + let record = |_: &Painter, rect: Rect| thumbnail.set(Some(rect)); + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "card", |sheet| { + sheet.section("Caption", false); + if *instance { + sheet.source_card(&record, "Layer", "Set", false); + } else { + } + }); + }); +} + +/// Where the card under a caption paints its thumbnail +fn thumbnail_under_caption(instance: bool) -> Rect { + let mut harness = builder(Brightness::MediumDark).build_ui_state(card_under_caption, (instance, std::cell::Cell::new(None))); + harness.run_steps(3); + harness.state().1.get().unwrap_or_else(|| panic!("the card (instance: {instance}) paints no thumbnail")) +} + +/// The instance card keeps a card's air under its caption and above its thumbnail, as a slot card does (it sat 6 px higher) +#[test] +fn an_instance_card_sits_under_its_caption_as_a_slot_card_does() { + let slot = thumbnail_under_caption(false); + let instance = thumbnail_under_caption(true); + + assert_eq!(instance.top(), slot.top(), "the thumbnails start at one y: {instance:?} vs {slot:?}"); +} + /// A gray slider in a panel-wide column; records the column's right edge fn gray_row(ui: &mut egui::Ui, state: &mut (f32, f32)) { ui.set_width(PANEL_WIDTH); @@ -764,6 +803,34 @@ fn the_pickers_hex_field_ends_on_the_colour_fields_right_edge() { assert_eq!(hex.right(), field.right(), "the hex field ends at {}, the colour field at {}", hex.right(), field.right()); } +/// A comparison's two sources, its operators beside the first +fn compare_rows(ui: &mut egui::Ui) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "compare", |sheet| { + let names = ["Left source", "Right source", "Other source"]; + let name = |index: usize| names.get(index).copied().unwrap_or_default().to_owned(); + sheet.compare_rows((0, 1), &[0, 1, 2], name, [Color32::RED, Color32::BLUE], (&["Min", "Max"], 0)); + }); + }); +} + +/// A compare source's tagged button shows its value where its open list's options start, a dropdown's value x (it sat 2 px right) +#[test] +fn a_compare_sources_value_starts_where_its_lists_options_do() { + let mut harness = builder(Brightness::MediumDark).build_ui(compare_rows); + harness.run_steps(3); + let button = harness.get_by_role_and_label(egui::Role::ComboBox, "Left source").rect(); + + click_at(&mut harness, button.center()); + harness.run_steps(2); + + let button_word = painted_at(&harness, "Left source").into_iter().find(|at| button.contains(*at)).map(|at| at.x); + let option_word = painted_at(&harness, "Other source").first().map(|at| at.x); + assert!(button_word.is_some() && option_word == button_word, "the option's word at {option_word:?}, the button's at {button_word:?}"); +} + /// A linked Tiling and Offset block over a ramp fn ramp_under_tiling(ui: &mut egui::Ui, state: &mut ([f32; 2], [f32; 2], bool, f32)) { let (tiling, offset, linked, gray) = state; diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index d0497fdf..21541abe 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -431,6 +431,7 @@ pub(crate) mod tests { use super::*; use crate::frame_gizmo::tests::{drag, drag_frames, fill_app, fill_app_with, panel_xyz, press_and_move, projection}; + use crate::frame_gizmo::tests::{ball_app, drag, drag_frames, fill_app, fill_app_with, panel_xyz, press_and_move, projection}; fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> RoundGizmo { RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() @@ -670,6 +671,26 @@ pub(crate) mod tests { assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows"); } + /// A paint layer on the ball whose mask holds a fill effect (selected) projecting `kind`: painting there paints the mask + fn mask_fill_app(kind: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let mut harness = ball_app(false); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = harness.state_mut().session.import_resource_bytes("decal.png", png).unwrap(); + harness.state_mut().run("layer.add.decal", json!({"image": image, "channel": "mask", "size": 0.5})).unwrap(); + let texturecraft_engine::StackTarget::Effect(effect) = harness.state().session.target else { panic!("the mask fill is selected") }; + harness.state_mut().run("layer.fill.projection", json!({"effect": effect.0, "projection": kind})).unwrap(); + harness.run_steps(2); + (harness, effect) + } + + fn effect_projection(harness: &egui_kittest::Harness<'_, TextureCraftApp>, effect: LayerId) -> Projection { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + texturecraft_engine::core::EffectKind::Fill { projection, .. } => projection.clone(), + other => panic!("a fill effect: {other:?}"), + } + } + /// A point on the model clear of every handle of the shown gizmo pub(crate) fn on_the_model_off_the_handles(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> Pos2 { let app = harness.state(); @@ -687,6 +708,31 @@ pub(crate) mod tests { .expect("the model shows past the handles") } + /// With every projection, a drag on the model away from the gizmo leaves the projection put (and paints nothing: no tool acts on a selected fill effect); only a drag that starts on a handle moves the projection + #[test] + fn only_a_handle_moves_the_projection_and_any_other_drag_on_the_model_leaves_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["planar", "warp", "triplanar", "spherical", "cylindrical"] { + let (mut harness, effect) = mask_fill_app(kind); + let rect = harness.state().viewport_rect; + let before = effect_projection(&harness, effect); + let steps = harness.state().session.history_labels().len(); + + let from = on_the_model_off_the_handles(&harness); + drag(&mut harness, from, from + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(effect_projection(&harness, effect), before, "{kind}: a drag off the handles leaves the projection alone"); + assert_eq!(harness.state().session.history_labels().len(), steps, "{kind}: and adds no undo step"); + + let center = match RoundGizmo::of(harness.state(), rect) { + Some(round) => round.center, + None => crate::frame_gizmo::FrameGizmo::of(harness.state(), rect).unwrap_or_else(|| panic!("{kind}: a gizmo shows")).center, + }; + drag(&mut harness, center, center + vec2(0.0, -30.0), Modifiers::NONE); + assert_ne!(effect_projection(&harness, effect), before, "{kind}: the centre square moves it"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "{kind}: one step, no stroke"); + } + } + /// A sphere has one size handle (it only scales evenly); a tri-planar box scales evenly from its corner and along one direction from a face's double arrow #[test] fn a_sphere_scales_from_one_dot_and_a_tri_planar_box_from_its_corner_and_faces() { diff --git a/crates/ui-egui/src/slot_thumbnail.rs b/crates/ui-egui/src/slot_thumbnail.rs index d739e42a..16cebc02 100644 --- a/crates/ui-egui/src/slot_thumbnail.rs +++ b/crates/ui-egui/src/slot_thumbnail.rs @@ -1,6 +1,7 @@ //! The picture a slot card shows of a fill channel's source use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, TextureHandle, TextureId, pos2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Stroke, StrokeKind, TextureHandle, TextureId, pos2}; use egui_phosphor::regular as ic; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::Source; @@ -38,6 +39,12 @@ pub(crate) fn thumbnail(app: &mut TextureCraftApp, ctx: &egui::Context, source: /// The glyph size of a slot without a picture const GLYPH_SIZE: f32 = 14.0; +/// Corner radius of a rounded slot picture and of the empty square +pub(crate) const THUMB_RADIUS: u8 = 3; + +/// How far the empty square's outline sits inside the slot's square +const EMPTY_SLOT_INSET: f32 = 1.0; + /// The whole of a texture, as the part of it a picture shows pub(crate) const FULL_UV: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); @@ -60,3 +67,8 @@ pub(crate) fn paint_thumbnail(painter: &Painter, rect: Rect, thumbnail: &SlotThu } } } + +/// A slot without a picture (no ID map, a missing source): an empty outlined square +pub(crate) fn paint_empty_slot(painter: &Painter, rect: Rect, tokens: &Tokens) { + painter.rect_stroke(rect.shrink(EMPTY_SLOT_INSET), CornerRadius::same(THUMB_RADIUS), Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); +} diff --git a/crates/ui-egui/src/source_slot.rs b/crates/ui-egui/src/source_slot.rs index b52bf7a3..4f353f73 100644 --- a/crates/ui-egui/src/source_slot.rs +++ b/crates/ui-egui/src/source_slot.rs @@ -9,6 +9,8 @@ use crate::i18n::tr; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum SourceSlot { Channel(Channel), + /// A mask fill's source, read as gray 0..1 + Grayscale, } impl SourceSlot { @@ -16,6 +18,7 @@ impl SourceSlot { pub(crate) fn name(self) -> &'static str { match self { SourceSlot::Channel(channel) => tr(channel.label()), + SourceSlot::Grayscale => tr("Grayscale"), } } @@ -27,9 +30,11 @@ impl SourceSlot { } /// The value Uniform and the slot's × give it + /// The value Uniform and the slot's × give it: a new mask fill's white for a grayscale pub(crate) fn default_value(self) -> [f32; 3] { match self { SourceSlot::Channel(channel) => channel.default_value(), + SourceSlot::Grayscale => [1.0; 3], } } @@ -39,6 +44,7 @@ impl SourceSlot { } /// A procedural's two ends when it is picked: a softer part of the channel's range + /// A procedural's two ends when it is picked: a gray fill spans the whole range, a channel a softer part of it pub(crate) fn procedural_ends(self) -> ([f32; 3], [f32; 3]) { /// Base color stays off pure black and white, which read as unlit or blown out const BASE_COLOR_ENDS: ([f32; 3], [f32; 3]) = ([0.15; 3], [0.85; 3]); @@ -57,9 +63,11 @@ impl SourceSlot { } /// The fill command's fields naming the slot + /// The fill command's fields naming the slot (a grayscale has no channel) pub(crate) fn fields(self) -> Value { match self { SourceSlot::Channel(channel) => json!({"channel": channel.id()}), + SourceSlot::Grayscale => json!({}), } } @@ -67,6 +75,7 @@ impl SourceSlot { pub(crate) fn key(self) -> &'static str { match self { SourceSlot::Channel(channel) => channel.id(), + SourceSlot::Grayscale => "grayscale", } } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 33f94c62..05b2eb8f 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -397,45 +397,12 @@ pub const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; /// The axes' letters, as the Axis switches and the 3D fields' tags show them pub const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; -/// Cyan, magenta and yellow: the opposites of [`AXIS_COLORS`] at the same brightness (Color Balance's color names) -pub const OPPOSITE_COLORS: [Color32; 3] = [Color32::from_rgb(0x52, 0xb8, 0xc4), Color32::from_rgb(0xc4, 0x6a, 0xc8), Color32::from_rgb(0xd2, 0xb8, 0x52)]; - /// `from` moved `amount` of the way to `to` in gamma space, opaque pub(crate) fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount).round().clamp(0.0, 255.0) as u8; Color32::from_rgb(mix(from.r(), to.r()), mix(from.g(), to.g()), mix(from.b(), to.b())) } -/// Least contrast a tinted color name keeps against its background (the WCAG ratio for normal text: the names are regular 12 pt lettering) -const TINT_MIN_CONTRAST: f32 = 4.5; - -/// How finely [`legible_tint`] walks from the tint to the text colour: a tenth of the way at a time keeps as much of the tint as reads -const TINT_STEPS: u8 = 10; - -/// `tint` moved toward `text` just enough to read on `background` (Color Balance's yellow and cyan names on a light card); a tint that already reads stays as it is -pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color32 { - (0..=TINT_STEPS) - .map(|step| tint.lerp_to_gamma(text, f32::from(step) / f32::from(TINT_STEPS))) - .find(|color| contrast_ratio(*color, background) >= TINT_MIN_CONTRAST) - .unwrap_or(text) -} - -/// WCAG's flare term, added to both luminances so black still has a ratio -const WCAG_FLARE: f32 = 0.05; - -/// The WCAG contrast ratio of two opaque colors (1..21) -fn contrast_ratio(a: Color32, b: Color32) -> f32 { - let luminance = |color: Color32| { - let linear = egui::Rgba::from(color); - - // Rec. 709 luminance - 0.2126 * linear.r() + 0.7152 * linear.g() + 0.0722 * linear.b() - }; - let (first, second) = (luminance(a), luminance(b)); - let (high, low) = (first.max(second), first.min(second)); - (high + WCAG_FLARE) / (low + WCAG_FLARE) -} - /// A section caption inside a panel: semibold in the strong colour, as written (no capitals). pub fn caption(text: &str) -> egui::RichText { egui::RichText::new(text).font(semibold(12.5)).strong() @@ -445,23 +412,6 @@ pub fn caption(text: &str) -> egui::RichText { mod tests { use super::*; - #[test] - fn tint_names_reach_normal_text_contrast_and_a_tint_that_already_reads_stays_as_it_is() { - for theme in [Brightness::Light, Brightness::MediumLight, Brightness::MediumDark, Brightness::Dark] { - let tokens = Tokens::for_brightness(theme); - for tint in OPPOSITE_COLORS.into_iter().chain(AXIS_COLORS) { - let shown = legible_tint(tint, tokens.row, tokens.text); - assert!(contrast_ratio(shown, tokens.row) >= TINT_MIN_CONTRAST, "{theme:?} {tint:?} -> {shown:?}"); - if contrast_ratio(tint, tokens.row) >= TINT_MIN_CONTRAST { - assert_eq!(shown, tint, "{theme:?}: a tint that already reads stays as it is"); - } - } - } - - let light = Tokens::for_brightness(Brightness::Light); - assert_ne!(legible_tint(OPPOSITE_COLORS[2], light.row, light.text), OPPOSITE_COLORS[2], "yellow darkens on a light card"); - } - #[test] fn settings_round_trip_and_unknown_values_load_the_defaults() { for b in Brightness::ALL { @@ -479,7 +429,18 @@ mod tests { #[test] fn every_brightness_and_accent_reads() { - let contrast = contrast_ratio; + // Relative luminance (WCAG) and contrast ratio. + let lum = |c: Color32| { + let ch = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b()) + }; + let contrast = |a: Color32, b: Color32| { + let (x, y) = (lum(a), lum(b)); + (x.max(y) + 0.05) / (x.min(y) + 0.05) + }; for b in Brightness::ALL { for a in Accent::ALL { let t = Tokens::for_brightness(b).with_accent(a); diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 9014c9a3..b85e073a 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -8,7 +8,7 @@ use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::compose::{ImageRes, ImageStore}; -use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::{BakedMap, ProceduralKind}; use texturecraft_engine::paint::presets::BrushPreset; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; @@ -50,6 +50,8 @@ pub struct Thumbs { saved_files_epoch: u64, images: HashMap, TextureHandle)>, images_revision: Option, + /// Each texture set's ID mesh map preview, with the map it shows (a rebake's new map replaces it) + id_maps: HashMap>, TextureHandle)>, /// (frame, thumbnails rendered in it) budget: (u64, usize), /// Renders the orb thumbnails and the big previews @@ -91,6 +93,30 @@ impl Thumbs { texture } + /// Cached preview of texture set `set_index`'s ID mesh map, its colors as stored (the ID view's); a rebake makes a new one + pub fn id_mesh_map(&mut self, ctx: &egui::Context, set_index: usize, baked: &texturecraft_engine::compose::BakedMaps) -> Option { + let data = baked.maps.get(&BakedMap::Id)?; + + // The weak reference keeps the shown map's allocation, so a new map never takes its address + if let Some((shown, texture)) = self.id_maps.get(&set_index) + && std::ptr::eq(shown.as_ptr(), Arc::as_ptr(data)) + { + return Some(texture.clone()); + } + + let mut image = ColorImage::filled([IMAGE_PX, IMAGE_PX], Color32::TRANSPARENT); + for (index, pixel) in image.pixels.iter_mut().enumerate() { + let uv = [((index % IMAGE_PX) as f32 + 0.5) / IMAGE_PX as f32, ((index / IMAGE_PX) as f32 + 0.5) / IMAGE_PX as f32]; + if let Some(color) = baked.sample_uv(BakedMap::Id, uv) { + let [red, green, blue] = color.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8); + *pixel = Color32::from_rgb(red, green, blue); + } + } + let texture = ctx.load_texture(format!("mesh_id_{set_index}"), image, TextureOptions::NEAREST); + self.id_maps.insert(set_index, (Arc::downgrade(data), texture.clone())); + Some(texture) + } + /// Cached preview of an image resource (64 px, letterboxed) pub fn image(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { if let Some((cached_image, texture)) = self.images.get(name) @@ -403,8 +429,11 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) { #[cfg(test)] mod tests { use super::*; + use std::collections::BTreeMap; use std::sync::atomic::{AtomicUsize, Ordering}; + use texturecraft_engine::compose::BakedMaps; + use crate::orb_shape::OrbShape; static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); @@ -612,4 +641,24 @@ mod tests { eprintln!("cached previews after clearing resources: {}", thumbs.images.len()); assert!(thumbs.images.is_empty()); } + + /// A 2 × 2 ID map of one red, in a map of its own + fn id_map() -> BakedMaps { + BakedMaps { resolution: 2, maps: BTreeMap::from([(BakedMap::Id, Arc::new([1.0, 0.0, 0.0].repeat(4)))]) } + } + + #[test] + fn an_id_map_preview_is_kept_while_its_map_lives_and_a_rebaked_map_gets_a_new_one() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs::default(); + let baked = id_map(); + + let first = thumbs.id_mesh_map(&ctx, 0, &baked).map(|texture| texture.id()); + let shared = thumbs.id_mesh_map(&ctx, 0, &baked.clone()).map(|texture| texture.id()); + let rebaked = thumbs.id_mesh_map(&ctx, 0, &id_map()).map(|texture| texture.id()); + + assert!(first.is_some()); + assert_eq!(shared, first, "the same map keeps its cached preview"); + assert_ne!(rebaked, first, "a new map of the same texture set, even of equal texels, gets a new preview"); + } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 13bf3900..47b7ab56 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -45,6 +45,21 @@ pub fn set_focus_picking(ctx: &egui::Context, on: bool) { ctx.data_mut(|d| d.insert_temp(focus_pick_id(), on)); } +/// What the views' aux texture shows: the quick mask being edited, a mesh map, the image a pending ID pick reads instead of the ID mesh map, or a mask +fn aux_view(app: &TextureCraftApp) -> Option { + match (app.session.view, app.picking_id_color) { + _ if quick_mask_shown(app) => Some(crate::gpu::AuxView::QuickMask), + (ViewMode::MeshMap(BakedMap::Id), Some(pick)) => Some(crate::gpu::AuxView::IdMask(pick.effect)), + (ViewMode::MeshMap(map), _) => Some(crate::gpu::AuxView::MeshMap(map)), + (ViewMode::Mask(id), _) => Some(crate::gpu::AuxView::Mask(id)), + (ViewMode::Image, _) => Some(crate::gpu::AuxView::Image), + _ if app.ui.mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => { + Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)) + } + _ => None, + } +} + /// 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; @@ -98,14 +113,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { finish_unavailable_tool_gestures(app, pending_2d_endpoint); crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); - let aux_view = match app.session.view { - _ if quick_mask_shown(app) => Some(crate::gpu::AuxView::QuickMask), - ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), - ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), - ViewMode::Image => Some(crate::gpu::AuxView::Image), - _ if mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)), - _ => None, - }; + let aux_view = aux_view(app); let mut sync = PendingSync(Some(aux_view)); let full = ui.available_rect_before_wrap(); path_keys(app, ui); @@ -2623,6 +2631,24 @@ mod tests { assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view"); } + #[test] + fn picking_shows_the_id_mask_its_color_selection_reads() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + use texturecraft_engine::{StackTarget, execute}; + + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!(null)).unwrap(); + let effect = texturecraft_engine::core::LayerId(execute(&mut session, "mask.add.colorSelection", &json!(null)).unwrap()["effect"].as_u64().unwrap()); + session.target = StackTarget::Effect(effect); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(2); + + crate::id_color_pick::IdColorPick::start(harness.state_mut(), effect, None); + assert_eq!(aux_view(harness.state()), Some(crate::gpu::AuxView::IdMask(effect)), "the pick's own ID mask"); + crate::id_color_pick::IdColorPick::end(harness.state_mut()); + assert_eq!(aux_view(harness.state()), None, "the earlier view"); + } + /// A click in the 2D view while a colour bar's eyedropper waits paints nothing: the pick keeps waiting, as over the 3D view #[test] fn a_waiting_eyedropper_keeps_a_2d_view_click_from_painting() { diff --git a/crates/ui-egui/tests/it/anchor_point.rs b/crates/ui-egui/tests/it/anchor_point.rs new file mode 100644 index 00000000..2e7d7f3a --- /dev/null +++ b/crates/ui-egui/tests/it/anchor_point.rs @@ -0,0 +1,103 @@ +//! The anchor point in Properties: its name typed in place, and the References band listing what reads it (a click selects that) + +use egui::accesskit::Role; +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// A fill with an anchor point in its mask, read by the mask fill of a layer above, the anchor point selected: (harness, anchor, reading layer, reading effect) +fn anchor_harness() -> (Harness<'static, TextureCraftApp>, LayerId, LayerId, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let low = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.2})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": low, "name": "Cavity Dirt"})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": low, "target": "mask", "value": 0.4})).unwrap(); + let anchor = LayerId(execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "mask"})).unwrap()["effect"].as_u64().unwrap()); + let top = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": top, "name": "Rust"})).unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap(); + let reader = LayerId(execute(&mut session, "effect.add.fill", &json!({"layer": top, "anchor": anchor.0})).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": low, "target": anchor.0})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, anchor, LayerId(top.as_u64().unwrap()), reader) +} + +fn anchor_name(harness: &Harness<'_, TextureCraftApp>, anchor: LayerId) -> String { + harness.state().session.doc.project.effect(anchor).unwrap().1.name.clone() +} + +/// Clicks the name field, selects its text and types `text` +fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + harness.get_by_role_and_label(Role::TextInput, "Anchor point name").click(); + harness.run_steps(SETTLE_FRAMES); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_name_field_renames_on_enter_in_one_undo_step_and_escape_keeps_it() { + let (mut harness, anchor, _, _) = anchor_harness(); + assert_eq!(anchor_name(&harness, anchor), "Cavity Dirt mask", "a mask anchor point is named after its layer"); + let steps = harness.state().session.history_labels().len(); + type_name(&mut harness, "Edges"); + assert_eq!(anchor_name(&harness, anchor), "Cavity Dirt mask", "nothing changes while typing"); + harness.key_press(Key::Enter); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + + type_name(&mut harness, "Never applied"); + harness.key_press(Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges", "Escape keeps the name"); +} + +#[test] +fn a_click_on_a_reference_selects_what_reads_the_anchor_point() { + let (mut harness, _, top, reader) = anchor_harness(); + assert!(harness.state().session.selected_layer() != Some(top)); + harness.get_by_role_and_label(Role::Button, "Rust Mask fill").click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(top)); + assert_eq!(harness.state().session.target, StackTarget::Effect(reader)); +} + +/// A reader's name longer than the band is cut short before its kind, and hovering the row shows it in full +#[test] +fn a_long_reference_name_is_cut_short_and_shows_in_full_on_hover() { + const LONG_NAME: &str = "Rust along every lower edge of the hull plates where rain water collects and runs"; + // Frames past the tooltip delay + const TOOLTIP_FRAMES: usize = 60; + let (mut harness, _, top, _) = anchor_harness(); + harness.state_mut().run("layer.rename", json!({"layer": top.0, "name": LONG_NAME})); + harness.run_steps(REDRAW_FRAMES); + let row = harness.get_by_role_and_label(Role::Button, &format!("{LONG_NAME} Mask fill")).rect(); + let before = harness.query_all_by_label(LONG_NAME).count(); + + harness.hover_at(row.center()); + harness.run_steps(TOOLTIP_FRAMES); + + // The row's own label is its name and kind; the Layers row shows the name too + assert_eq!(harness.query_all_by_label(LONG_NAME).count(), before + 1, "the tooltip carries the full name"); +} + +#[test] +fn a_name_typed_then_left_with_shift_tab_is_kept() { + let (mut harness, anchor, _, _) = anchor_harness(); + let steps = harness.state().session.history_labels().len(); + type_name(&mut harness, "Edges"); + + // The focus moves back to a control drawn before the field: the field never sees itself focused again + harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges", "the typed name is kept"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "in one undo step"); +} diff --git a/crates/ui-egui/tests/it/compare_mask_rows.rs b/crates/ui-egui/tests/it/compare_mask_rows.rs new file mode 100644 index 00000000..daf7af52 --- /dev/null +++ b/crates/ui-egui/tests/it/compare_mask_rows.rs @@ -0,0 +1,85 @@ +//! The compare mask in Properties: channel, the two sources with the operator between them, the constant, tolerance and hardness rows + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{Channel, CompareOp, CompareSource, EffectKind, LayerId}; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// A fill over a fill, a compare mask on the top one, selected: (harness, compare effect) +fn compare_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"roughness": 0.2})).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap()["layer"].clone(); + let effect = LayerId(execute(&mut session, "effect.add.compare", &json!({"layer": layer})).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect.0})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); + (harness, effect) +} + +/// (left, op, right, channel, constant, tolerance, hardness) of compare mask `effect` +fn compare(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> (CompareSource, CompareOp, CompareSource, Channel, f32, f32, f32) { + match harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Compare { left, op, right, channel, value, tolerance, hardness } => (left, op, right, channel, value, tolerance, hardness), + ref other => panic!("a compare mask, found {other:?}"), + } +} + +fn undo_steps(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} + +fn has_slider(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.query_by_role_and_label(Role::Slider, label).is_some() +} + +/// Opens the list of the source showing `name` and picks `option` +fn pick_source(harness: &mut Harness<'_, TextureCraftApp>, name: &str, option: &str) { + harness.get_by_role_and_label(Role::ComboBox, name).click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_role_and_label(Role::ListBoxOption, option).click(); + harness.run_steps(REDRAW_FRAMES); +} + +#[test] +fn the_rows_show_and_edit_the_comparison_one_undo_step_each() { + let (mut harness, effect) = compare_harness(); + assert!(crate::levels_editor::painted_text(&harness, "COMPARE MASK"), "the section caption"); + assert_eq!(compare(&harness, effect).0, CompareSource::ThisLayer); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Layers below").is_some(), "the right source"); + assert!(has_slider(&harness, "Hardness") && !has_slider(&harness, "Constant") && !has_slider(&harness, "Tolerance")); + + let steps = undo_steps(&harness); + pick_source(&mut harness, "Layers below", "Constant"); + assert_eq!(compare(&harness, effect).2, CompareSource::Constant); + assert_eq!(undo_steps(&harness), steps + 1, "one undo step"); + assert!(has_slider(&harness, "Constant"), "a constant side shows its value"); + + pick_source(&mut harness, "This layer", "This mask"); + assert_eq!(compare(&harness, effect).0, CompareSource::ThisMask); + + harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("≈")).click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(compare(&harness, effect).1, CompareOp::WithinTolerance); + assert!(has_slider(&harness, "Tolerance"), "within tolerance shows its tolerance"); + + pick_source(&mut harness, "Height", "Roughness"); + assert_eq!(compare(&harness, effect).3, Channel::Roughness); + assert_eq!(undo_steps(&harness), steps + 4); +} + +#[test] +fn a_source_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click_outside() { + let (mut harness, effect) = compare_harness(); + crate::assert_list_leaves_the_wheel_and_closes(&mut harness, |harness| { + harness.get_by_role_and_label(Role::ComboBox, "Layers below").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_role_and_label(Role::ComboBox, "Layers below").rect() + }); + assert_eq!(compare(&harness, effect).2, CompareSource::LayersBelow, "nothing changed"); +} diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index fdd04351..ba6c7372 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,7 +1,7 @@ -//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right. +//! Effect rows in the layer stack: dragging one reorders its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; @@ -11,6 +11,11 @@ fn id(v: Value, key: &str) -> u64 { v[key].as_u64().unwrap() } +/// The blending the rows show and set: the displayed channel's (base color by default) +fn base_color_blend(effect: &texturecraft_engine::core::Effect) -> texturecraft_engine::core::ChannelBlend { + effect.blend_of(Some(texturecraft_engine::core::Channel::BaseColor)) +} + /// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { let start = harness.get_by_label(from).rect().center(); @@ -51,7 +56,7 @@ fn dragging_an_effect_row_reorders_its_stack() { assert_eq!(order(&harness), [a, c, b]); } -/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows. +/// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows #[test] fn an_effect_row_sets_its_blend_mode_and_opacity() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -62,6 +67,8 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); assert_eq!(effect, effect_of(&harness).id.0); + harness.state_mut().ui.layer_material_view = false; + harness.run_steps(2); // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field let row = harness.get_by_label("Effect A").rect(); @@ -73,7 +80,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.run_steps(2); harness.get_by_label("Multiply").click(); harness.run_steps(3); - assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply); + assert_eq!(base_color_blend(&effect_of(&harness)).mode, texturecraft_engine::core::BlendMode::Multiply, "the row sets the displayed channel's"); + let roughness = effect_of(&harness).blend_of(Some(texturecraft_engine::core::Channel::Roughness)).mode; + assert_eq!(roughness, texturecraft_engine::core::BlendMode::Normal, "the other channels keep theirs"); let history = harness.state().session.history_labels().len(); let opacity_at = egui::pos2(pair_right - 20.0, row.center().y); @@ -83,7 +92,8 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.run_steps(2); harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); harness.run_steps(3); - assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); + let opacity = base_color_blend(&effect_of(&harness)).opacity; + assert!(opacity < 0.9, "dragging the field to the left lowers the opacity: {opacity}"); assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); } @@ -106,14 +116,57 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { harness.run_steps(2); harness.hover_at(opacity_at + egui::vec2(8.0, 8.0)); harness.run_steps(2); - assert_eq!(effect_of(&harness).opacity, 1.0, "the drag started without changing the opacity"); + assert_eq!(base_color_blend(&effect_of(&harness)).opacity, 1.0, "the drag started without changing the opacity"); harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); harness.run_steps(2); harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); harness.run_steps(3); - assert!(effect_of(&harness).opacity < 0.9, "the drag lowered the opacity: {}", effect_of(&harness).opacity); + let opacity = base_color_blend(&effect_of(&harness)).opacity; + assert!(opacity < 0.9, "the drag lowered the opacity: {opacity}"); assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step"); harness.state_mut().session.undo().unwrap(); - assert_eq!(effect_of(&harness).opacity, 1.0); - assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); + assert_eq!(base_color_blend(&effect_of(&harness)).opacity, 1.0); + assert_eq!(base_color_blend(&effect_of(&harness)).mode, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); +} + +/// An effect row's menu holds Blending options: the channel the Layers panel shows lends its blend mode to every channel (none in the Material view), and Paste waits for a Copy +#[test] +fn an_effect_rows_blending_options_reach_every_channel() { + use texturecraft_engine::core::{BlendMode, Channel}; + + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": effect, "channel": "baseColor", "blend": "Multiply"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect_of(&harness).blend_of(Some(Channel::Roughness)).mode, BlendMode::Normal); + + let open_blending_options = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.get_by_label("Effect A").click_secondary(); + harness.run_steps(3); + harness.get_by_label("Blending options").click(); + harness.run_steps(3); + }; + open_blending_options(&mut harness); + assert!(harness.get_by_label("Use this blend mode on every channel").accesskit_node().is_disabled(), "the Material view shows no channel to lend"); + assert!(harness.get_by_label("Paste channel blending").accesskit_node().is_disabled(), "nothing is copied yet"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // With Base color shown, the row reads its Multiply and lends it to every channel + harness.state_mut().ui.layer_material_view = false; + harness.run_steps(3); + open_blending_options(&mut harness); + harness.get_by_label("Use this blend mode on every channel").click(); + harness.run_steps(3); + assert_eq!(effect_of(&harness).blend_of(Some(Channel::Roughness)).mode, BlendMode::Multiply); + + open_blending_options(&mut harness); + harness.get_by_label("Copy channel blending").click(); + harness.run_steps(3); + open_blending_options(&mut harness); + assert!(!harness.get_by_label("Paste channel blending").accesskit_node().is_disabled(), "a copy can be pasted"); } diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index 3a4a2e63..a2b4e0de 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -7,7 +7,7 @@ use serde_json::json; use texturecraft_engine::core::{EffectKind, LayerId}; use texturecraft_ui_egui::TextureCraftApp; -/// The sample session with its first generator effect selected, and that effect's id. +/// The sample session with its first generator effect selected, and that effect's id fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session @@ -80,28 +80,6 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } -/// The combo box in the row of the levels editor's Reset button. -fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = harness.get_by_label("Reset").rect().center().y; - harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() -} - -/// A content levels effect offers a channel for its histogram; picking one keeps it selected. -#[test] -fn content_levels_pick_the_histogram_channel() { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); - texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); - harness.run_steps(4); - assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); - channel_picker(&harness).click(); - harness.run_steps(2); - harness.get_by_label("Roughness").click(); - harness.run_steps(3); - assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays"); -} - #[test] fn clicking_a_slider_track_applies_it() { let (mut harness, effect) = selected_generator(); @@ -113,7 +91,7 @@ fn clicking_a_slider_track_applies_it() { assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); } -/// The number field in the row of the slider labelled `label`. +/// The number field in the row of the slider labelled `label` fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { let row = harness.get_by_label(label).rect().center().y; harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index eedbb9c2..a52a385b 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -107,6 +107,8 @@ fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { // The picker shows "Material" right of the tool shelf and the Assets panel and left of the right column: one per view in the split layout let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && (300.0..1200.0).contains(x)).count(); + // The picker shows "Material" right of the tool shelf and the Assets panel: one per view in the split layout + let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && *x > 400.0).count(); assert_eq!(pickers, 2, "each of the two views keeps its view picker"); diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index bd7222b8..6863656e 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -7,6 +7,7 @@ use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; use texturecraft_ui_egui::TextureCraftApp; use crate::fill_support::click_node; +use crate::fill_support::{click_label, click_node}; /// Opens the Roughness slot's source picker on the Material tab and types `search` into its search field, which has the focus fn open_roughness_source_menu(harness: &mut Harness<'_, TextureCraftApp>, search: &str) { @@ -126,35 +127,32 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - // The mask fill's slot opens the source picker - harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").scroll_to_me(); - harness.run_steps(30); - harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); - harness.run_steps(3); // The search field has the focus: it brings the tile into the grid's view + // The mask fill's Grayscale slot opens the source picker; its search finds the image + click_node(&mut harness, egui::Role::ComboBox, "Grayscale"); + harness.run_steps(2); harness.event(egui::Event::Text("mask".into())); harness.run_steps(2); harness.get_by_role_and_label(egui::Role::ListBoxOption, &image_name).click(); + click_node(&mut harness, egui::Role::ListBoxOption, &image_name); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { source: Source::Image { name, .. }, .. } if name == &image_name)); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("UV projection")).unwrap().click(); + click_node(&mut harness, egui::Role::ComboBox, "UV projection"); harness.run_steps(2); - harness.get_by_label("Tri-planar projection").click(); + click_label(&mut harness, "Tri-planar projection"); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { projection: Projection::Triplanar { .. }, .. })); - assert_eq!(harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").value().as_deref(), Some(image_name.as_str()), "the slot names the image"); - harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); - harness.run_steps(3); // The search field has the focus: it brings the tile into the grid's view harness.event(egui::Event::Text("uniform".into())); - harness.run_steps(2); harness.get_by_role_and_label(egui::Role::ListBoxOption, "Uniform value").click(); + // The slot's × puts the mask fill back to a uniform value + click_node(&mut harness, egui::Role::Button, "Clear"); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 36abe572..2efe721f 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -66,7 +66,7 @@ fn escape_closes_the_picker_without_changes() { assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); } -/// Opens the wand's Add effect menu and clicks Add filter +/// Opens the wand's Add effect menu and clicks 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); diff --git a/crates/ui-egui/tests/it/instance_properties.rs b/crates/ui-egui/tests/it/instance_properties.rs new file mode 100644 index 00000000..15ece0a7 --- /dev/null +++ b/crates/ui-egui/tests/it/instance_properties.rs @@ -0,0 +1,65 @@ +//! The instance in Properties: INSTANCE OF holds the card of the layer it draws, a click on it selects that layer; a source that is gone shows a missing layer that takes no click + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// No layer has this id +const GONE: LayerId = LayerId(999_999); + +/// A fill named Steel and an instance of it (its source swapped for a layer that is gone when `dangling`), the instance selected: (harness, instance, source) +fn instance_harness(dangling: bool) -> (Harness<'static, TextureCraftApp>, LayerId, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let source = LayerId(execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "layer.rename", &json!({"layer": source.0, "name": "Steel"})).unwrap(); + let instance = LayerId(execute(&mut session, "layer.instance", &json!({"layer": source.0})).unwrap()["layer"].as_u64().unwrap()); + if dangling { + session.doc.project.layers.get_mut(&instance).unwrap().kind = LayerKind::Instance { source: GONE }; + } + execute(&mut session, "layer.select", &json!({"layer": instance.0, "target": "content"})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, instance, source) +} + +/// The name of the texture set holding `layer` +fn set_name(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> String { + let project = &harness.state().session.doc.project; + let (set, _, _) = project.locate(layer).unwrap(); + project.texture_set(set).unwrap().name.clone() +} + +#[test] +fn the_source_card_names_the_source_and_its_texture_set_and_a_click_selects_it() { + let (mut harness, instance, source) = instance_harness(false); + assert_eq!(harness.state().session.selected_layer(), Some(instance)); + let card = format!("Steel {}", set_name(&harness, source)); + harness.get_by_role_and_label(Role::Button, &card).click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(source), "the click goes to the source"); +} + +#[test] +fn a_source_that_is_gone_shows_a_missing_layer_that_takes_no_click() { + let (mut harness, instance, _) = instance_harness(true); + let card = format!("Missing layer {}", set_name(&harness, instance)); + let missing = harness.get_by_role_and_label(Role::Button, &card); + assert!(missing.accesskit_node().is_disabled(), "a missing source can't be gone to"); + + // A real press and release on the card + let steps = harness.state().session.history_labels().len(); + let at = missing.rect().center(); + harness.drag_at(at); + harness.run_steps(1); + harness.drop_at(at); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(instance)); + assert_eq!(harness.state().session.history_labels().len(), steps, "the click ran nothing"); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 02416390..036d1f5f 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -267,13 +267,7 @@ fn layer_toolbar_stays_on_one_row_in_a_1280_by_800_window() { let h = narrow_harness(); let buttons = ["Add paint layer", "Add fill layer", "Add folder"].map(|label| h.get_by_label(label).rect()); - // The effect menu button is the wand left of the paint button (effect rows draw wands too) - let wand = h - .query_all_by_label(egui_phosphor::regular::MAGIC_WAND) - .map(|n| n.rect()) - .filter(|r| r.right() < buttons[0].left()) - .max_by(|a, b| a.right().total_cmp(&b.right())) - .expect("the effect menu button"); + let wand = h.get_by_label("Add effect").rect(); let remove = h.query_all_by_label_contains("Remove layer").next().expect("the remove button").rect(); for rect in buttons.into_iter().chain([remove]) { assert!((rect.center().y - wand.center().y).abs() < 1.0, "the toolbar wrapped: {rect:?} against {wand:?}"); diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs index 3fef7357..d117abc8 100644 --- a/crates/ui-egui/tests/it/levels_editor.rs +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -8,7 +8,9 @@ use texturecraft_engine::core::{Channel, EffectKind, LayerId, Levels}; use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; -/// Histogram buckets and Auto's share, as in levels_properties.rs +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Histogram buckets (histogram_cache.rs) and Auto's share (levels_properties.rs) const HISTOGRAM_BUCKETS: usize = 64; const AUTO_MIN_SHARE: f64 = 0.001; @@ -20,7 +22,7 @@ const HANDLE_POINTER_CORNERS: usize = 5; /// A clouds mask under a levels effect added by `command` with `params`, selected, and its id fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); for (id, params) in [ ("layer.add.fill", json!({"color": [0.8, 0.3, 0.1]})), ("mask.add.black", Value::Null), @@ -38,8 +40,8 @@ fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraft execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); // Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); - harness.run_steps(4); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); (harness, effect) } @@ -161,7 +163,7 @@ fn reset_and_invert_are_one_undo_step_each() { button(&harness, "Invert").click(); harness.run_steps(3); - assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2 }); + assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2, ..Levels::default() }); assert_eq!(undo_steps(&harness), steps + 1); button(&harness, "Reset").click(); @@ -174,7 +176,7 @@ fn reset_and_invert_are_one_undo_step_each() { #[test] fn auto_fits_the_input_range_to_the_histogram() { let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "gamma": 1.5})); - let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap(); + let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap().all; let total: u32 = counts.iter().sum(); let holds = |count: &u32| f64::from(*count) > f64::from(total) * AUTO_MIN_SHARE; let low = counts.iter().position(holds).unwrap() as f32 / HISTOGRAM_BUCKETS as f32; @@ -195,6 +197,19 @@ fn auto_fits_the_input_range_to_the_histogram() { assert_eq!(undo_steps(&harness), steps, "Auto again changes nothing, so it adds no undo step"); } +/// How many of the five exact-entry fields are shown +fn open_fields(harness: &Harness<'_, TextureCraftApp>) -> usize { + HANDLE_LABELS.iter().filter(|label| harness.query_by_role_and_label(Role::TextInput, label).is_some()).count() +} + +/// Opens the number fields from `label`'s handle with the keyboard (focus, Enter) +fn open_exact_entry(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_role_and_label(Role::Slider, label).focus(); + harness.run_steps(SETTLE_FRAMES); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); +} + /// Double-clicks `label`'s handle, then types `text` into its number field with the value selected fn type_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { let at = handle(harness, label); @@ -220,18 +235,24 @@ fn a_value_typed_after_double_clicking_a_handle_applies() { assert_eq!(levels(&harness, effect).gamma, 2.5); assert_eq!(undo_steps(&harness), steps + 1); + assert_eq!(open_fields(&harness), 0, "Enter commits and closes the fields"); } #[test] -fn focusing_exact_entry_moves_nothing_in_the_panel() { +fn exact_entry_opens_on_a_double_click_and_closes_with_typing() { let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); let buttons = |harness: &Harness<'_, TextureCraftApp>| ["Reset", "Auto", "Invert"].map(|label| button(harness, label).rect()); let before = buttons(&harness); + assert_eq!(open_fields(&harness), 0, "no number fields until a handle asks for them"); type_value(&mut harness, "Output low", ""); - assert!(harness.query_all(by().role(Role::TextInput)).any(|node| node.is_focused()), "the number field has focus"); - assert_eq!(buttons(&harness), before); + assert_eq!(open_fields(&harness), HANDLE_LABELS.len()); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(open_fields(&harness), 0, "Escape closes the fields"); + assert_eq!(buttons(&harness), before, "the buttons go back where they were"); } #[test] @@ -296,7 +317,8 @@ fn the_hovered_handle_is_painted_on_top() { #[test] fn number_fields_are_labelled_and_stay_in_one_row() { - let (harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + open_exact_entry(&mut harness, "Gamma"); let fields = HANDLE_LABELS.map(|label| harness.get_by_role_and_label(Role::TextInput, label).rect()); let row = fields[0].center().y; @@ -405,6 +427,7 @@ fn dragging_near_a_handle_uses_the_larger_target() { fn number_fields_commit_on_focus_loss() { let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inLow": 0.2, "inHigh": 0.8})); let steps = undo_steps(&harness); + open_exact_entry(&mut harness, "Gamma"); harness.get_by_role_and_label(Role::TextInput, "Input low").focus(); harness.run_steps(2); @@ -427,6 +450,87 @@ fn replacing_effects_releases_old_histograms() { harness.run_steps(3); } - let cached = harness.ctx.data(|data| data.count::<(u64, std::sync::Arc>)>()); + let cached = harness.ctx.data(|data| data.count::<(u64, std::sync::Arc)>()); assert_eq!(cached, 1, "only the current effect's histogram remains cached"); } + +/// Whether `text` was painted this frame (section captions are painted, not widgets) +pub(crate) fn painted_text(harness: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + harness.output().shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Text(painted) if painted.galley.text() == text)) +} + +/// The Affects list: the combo box its row describes as "Affects", not the Layers channel list +pub(crate) fn affects_list<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> Option> { + harness.query_by(|node| node.role() == Role::ComboBox && node.description().as_deref() == Some("Affects")) +} + +/// A fill layer with a content levels, selected +fn content_levels_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap(); + execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); + let effect = levels_effect(&session); + open(session, effect) +} + +#[test] +fn a_content_levels_picks_the_channel_it_affects() { + let (mut harness, effect) = content_levels_harness(); + assert_eq!(levels(&harness, effect).affects, Some(Channel::BaseColor)); + assert!(painted_text(&harness, "LEVELS - BASE COLOR"), "the caption names the channel"); + assert!(harness.query_by_label("Blending").is_none(), "levels have no blending"); + for view in ["Colors", "RGB", "R", "G", "B", "Lum"] { + assert!(harness.query_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some(view)).is_some(), "{view} on the display switch"); + } + + // The display switch only changes the view + let steps = undo_steps(&harness); + harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("R")).click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(undo_steps(&harness), steps); + assert!( + harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("R")).accesskit_node().toggled() + == Some(egui::accesskit::Toggled::True), + "the switch shows red only" + ); + + assert_eq!(affects_list(&harness).and_then(|list| list.accesskit_node().label()).as_deref(), Some("Base color")); + affects_list(&harness).unwrap().click(); + harness.run_steps(SETTLE_FRAMES); + assert!( + harness.query_by(|node| node.role() == Role::ListBoxOption && node.label().as_deref() == Some("Normal")).is_none(), + "levels pass normal maps through" + ); + harness.get_by(|node| node.role() == Role::ListBoxOption && node.label().as_deref() == Some("Roughness")).click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(levels(&harness, effect).affects, Some(Channel::Roughness)); + assert_eq!(undo_steps(&harness), steps + 1); + assert!(painted_text(&harness, "LEVELS - ROUGHNESS")); + assert!(harness.query_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("Colors")).is_none(), "one value: no display choice"); +} + +#[test] +fn clamp_is_one_undo_step() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert!(painted_text(&harness, "LEVELS - MASK")); + assert!(affects_list(&harness).is_none() && !painted_text(&harness, "Affects"), "a mask has no channel to pick"); + assert!(!levels(&harness, effect).clamp, "new levels carry on past their handles"); + let steps = undo_steps(&harness); + harness.get_by_role_and_label(Role::CheckBox, "Clamp").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(levels(&harness, effect).clamp); + assert_eq!(undo_steps(&harness), steps + 1); +} + +#[test] +fn the_affects_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click_outside() { + let (mut harness, effect) = content_levels_harness(); + crate::assert_list_leaves_the_wheel_and_closes(&mut harness, |harness| { + let list = affects_list(harness).unwrap(); + let button = list.rect(); + list.click(); + harness.run_steps(SETTLE_FRAMES); + button + }); + assert_eq!(levels(&harness, effect).affects, Some(Channel::BaseColor), "nothing changed"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8b642d36..3e9a0d64 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. mod alpha_parameters; +mod anchor_point; mod bake_job_mesh; mod bake_mode; mod bake_presets; @@ -12,6 +13,7 @@ mod clone_source_view; mod close_unsaved; mod color_picker; mod color_selection_editor; +mod compare_mask_rows; mod curvature_generator; mod display_environment; mod display_post_effects; @@ -32,20 +34,25 @@ mod fill_support; mod fill_symmetry_rows; mod filter_picker; mod filter_support; +mod folder_properties; mod frame_selection; mod generator_panel; mod help_menu_664; mod history_panel; mod import_resources; mod inactive_set_hint; +mod instance_properties; mod layer_blending_options; mod layer_clipboard; mod layer_multi_select; mod layer_rename; +mod layer_toolbar; mod layers_panel; mod levels_editor; mod log_panel_680; mod mask_export; +mod mask_fill_rows; +mod mask_paint_grayscale; mod mask_value_swap; mod named_layouts; mod nav_buttons; @@ -85,7 +92,6 @@ mod split_divider; mod temp_dir; mod template_invert; mod templates_681; -mod tile_generator_panel; mod tool_availability; mod tool_settings_saved; mod toolbar; @@ -98,6 +104,7 @@ mod window_menu_684; mod stencil; mod symmetry; mod symmetry_2d; +mod tile_generator_panel; /// eframe's in-memory storage, shared by the tests that save and restore the UI state #[path = "../../src/ui_state_store/memory_storage.rs"] @@ -114,6 +121,9 @@ const PROPERTIES_WINDOW: egui::Vec2 = egui::vec2(1600.0, 1400.0); const TEXTURE_RESOLUTION: u32 = 256; const BAKE_RESOLUTION: u32 = 64; +/// One frame at 60 Hz, so timed steps run as on a common display +const FRAME_SECONDS: f32 = 1.0 / 60.0; + /// Frames for the first layout and fonts to settle const STARTUP_FRAMES: usize = 4; @@ -123,6 +133,9 @@ const SETTLE_FRAMES: usize = 3; /// Frames between the moves of a drag, and between a press and its release const DRAG_STEP_FRAMES: usize = 2; +/// How far in from a slider track's ends a drag's points stay, so they land on the track +const SLIDER_END_INSET: f32 = 5.0; + /// Frames for an input that redraws Properties (another selection, source or operator) to show const REDRAW_FRAMES: usize = 4; diff --git a/crates/ui-egui/tests/it/mask_paint_grayscale.rs b/crates/ui-egui/tests/it/mask_paint_grayscale.rs new file mode 100644 index 00000000..e2e28236 --- /dev/null +++ b/crates/ui-egui/tests/it/mask_paint_grayscale.rs @@ -0,0 +1,82 @@ +//! A folder's mask selected: the paint tool's third tab is Grayscale, a slot card for the gray a stroke paints (its ramp and invert) or an image picked from the slot's picker + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::PropsTab; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// An 8 × 8 gray picture +fn gray_png() -> Vec { + let image = image::RgbaImage::from_pixel(8, 8, image::Rgba([90, 90, 90, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A folder with a white mask, the mask selected and the tool's Grayscale tab open: (harness, the imported image's name) +fn folder_mask_harness() -> (Harness<'static, TextureCraftApp>, String) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let image = session.import_resource_bytes("scratches.png", gray_png()).unwrap(); + let folder = LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.white", &json!({"layer": folder.0})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "mask"})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.props_tab = PropsTab::Material; + harness.run_steps(STARTUP_FRAMES); + (harness, image) +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_grayscale_slot_paints_one_gray_its_ramp_drags_and_inverts() { + let (mut harness, _) = folder_mask_harness(); + assert!(harness.query_by_label("Mask value (gray)").is_none(), "the old slider is gone"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Grayscale").is_some(), "the Grayscale slot card"); + + click(&mut harness, Role::Button, "Invert"); + assert_eq!(harness.state().session.tool.mask_value, 0.0, "white inverts to black"); + + // A real drag along the ramp to its right end + let track = harness.get_by_role_and_label(Role::Slider, "Grayscale").rect(); + let at = |t: f32| egui::pos2(track.left() + SLIDER_END_INSET + (track.width() - 2.0 * SLIDER_END_INSET) * t, track.center().y); + harness.drag_at(at(0.1)); + harness.run_steps(DRAG_STEP_FRAMES); + for t in [0.6, 1.0] { + harness.hover_at(at(t)); + harness.run_steps(DRAG_STEP_FRAMES); + } + harness.drop_at(at(1.0)); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().session.tool.mask_value > 0.95, "dragged to {}", harness.state().session.tool.mask_value); +} + +#[test] +fn the_slot_picks_an_image_to_paint_and_clear_goes_back_to_the_gray() { + let (mut harness, image) = folder_mask_harness(); + click(&mut harness, Role::ComboBox, "Grayscale"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Import...").is_some(), "Textures starts with Import..."); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Import...").is_none(), "Escape closes the picker"); + assert_eq!(harness.state().session.tool.mask_image, None); + + click(&mut harness, Role::ComboBox, "Grayscale"); + click(&mut harness, Role::ListBoxOption, &image); + assert_eq!(harness.state().session.tool.mask_image.as_deref(), Some(image.as_str())); + assert!(harness.query_by_role_and_label(Role::Slider, "Grayscale").is_none(), "an image has no ramp"); + + click(&mut harness, Role::Button, "Clear"); + assert_eq!(harness.state().session.tool.mask_image, None); + assert!(harness.query_by_role_and_label(Role::Slider, "Grayscale").is_some(), "the ramp is back"); +} diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index b56d3c91..b909b013 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -1,6 +1,7 @@ //! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the tool's colour, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart use eframe::App as _; +use egui::accesskit::Role; use egui::{Event, Modifiers, PointerButton, Pos2, Vec2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -124,6 +125,18 @@ fn an_alt_orbit_keeps_the_tool_colour_popup_open() { assert!(egui::Popup::is_any_open(&harness.ctx), "an Alt+drag orbits the camera and keeps the popup, like the colour picker"); } +#[test] +fn a_stroke_on_the_model_closes_the_add_effect_menu() { + let mut harness = app(&MemoryStorage::default()); + harness.get_by_role_and_label(Role::Button, "Add effect").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(egui::Popup::is_any_open(&harness.ctx), "the menu opens"); + + stroke_on_model(&mut harness, Modifiers::NONE); + + assert!(!egui::Popup::is_any_open(&harness.ctx), "the stroke closes the menu"); +} + #[test] fn a_stroke_on_the_model_closes_the_symmetry_settings() { let mut harness = app(&MemoryStorage::default()); diff --git a/crates/ui-egui/tests/it/source_picker.rs b/crates/ui-egui/tests/it/source_picker.rs index af9cdb4b..f40afea9 100644 --- a/crates/ui-egui/tests/it/source_picker.rs +++ b/crates/ui-egui/tests/it/source_picker.rs @@ -144,6 +144,20 @@ fn the_anchor_points_tab_lists_the_stacks_anchors() { assert!(matches!(source(&harness, reader, Channel::Roughness), Source::Anchor { .. })); } +#[test] +fn the_anchor_points_tab_lists_mask_anchor_points_by_name() { + let (mut harness, _) = app_with_fill(|session, layer| { + texturecraft_engine::execute(session, "effect.add.anchor", &json!({"layer": layer.0, "target": "mask", "name": "Dirt mask"})).unwrap(); + texturecraft_engine::execute(session, "layer.add.fill", &json!({})).unwrap(); + }); + let reader = harness.state().session.selected_layer().unwrap(); + click_slot(&mut harness, "Roughness"); + click_widget(&mut harness, Role::Tab, "Anchor points"); + let anchor = harness.get_all_by_role(Role::ListBoxOption).find_map(|node| node.accesskit_node().label().filter(|label| label.starts_with("Dirt mask"))); + click_tile(&mut harness, &anchor.expect("the mask anchor point below is offered under its own name")); + assert!(matches!(source(&harness, reader, Channel::Roughness), Source::Anchor { .. })); +} + #[test] fn escape_or_a_click_outside_closes_it_and_the_wheel_still_zooms_the_view() { let (mut harness, layer) = app_with_fill(|_, _| {}); diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 7e8dabd5..48b3be42 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -60,6 +60,11 @@ fn pick(harness: &mut Harness<'_, TextureCraftApp>, tile: &str) { harness.run_steps(3); } +/// The lowest control labelled `label`: the slot's rows show a pattern's Scale, Contrast and ⟲ above the Tile Generator's own +fn lowest<'h>(harness: &'h Harness<'_, TextureCraftApp>, label: &'h str) -> egui_kittest::Node<'h> { + harness.get_all_by_label(label).max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() +} + /// Where a slider's track is grabbed, from its label's left end and bottom, and how far it is dragged (points) const TRACK_GRAB_INSET: f32 = 20.0; const TRACK_BELOW_LABEL: f32 = 10.0; @@ -113,18 +118,16 @@ fn the_anchor_points_tab_picks_an_anchor() { harness.get_by_label("Anchor points").click(); harness.run_steps(3); - // An anchor tile is labelled " / ", as the anchors below a layer are listed - let project = &harness.state().session.doc.project; - let owner = project.layers.values().find(|layer| layer.content_effects.iter().any(|effect| effect.name == "Height")).unwrap(); - let label = format!("{} / Height", owner.name); harness.get_by_role_and_label(Role::ListBoxOption, &label).click(); + // An anchor tile is labelled with the anchor's name; its layer is named only where two anchors share a name + harness.get_by_role_and_label(Role::ListBoxOption, "Height").click(); harness.run_steps(3); assert!(source(&harness, effect).anchor().is_some()); } -/// An anchor in a mask records the mask's gray whatever the channel, so the slot names the mask +/// An anchor in a mask records the mask's gray whatever the channel, so the slot names the anchor and no channel #[test] -fn the_slot_names_the_mask_for_an_anchor_in_a_mask() { +fn the_slot_names_the_anchor_in_a_mask_it_reads() { let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); session.active_set = 1; let lower = execute(&mut session, "layer.add.fill", &json!({"name": "Lower"})).unwrap()["layer"].as_u64().unwrap(); @@ -141,7 +144,7 @@ fn the_slot_names_the_mask_for_an_anchor_in_a_mask() { let slot = harness.get_by_role_and_label(Role::ComboBox, "Grayscale"); - assert_eq!(slot.value().as_deref(), Some("Lower · Mask")); + assert_eq!(slot.value().as_deref(), Some("Anchor · Wear")); } #[test] @@ -156,9 +159,9 @@ fn an_amount_drag_is_one_undo_step_and_restore_defaults_puts_the_tiles_back() { assert!(tile.amount[0] > TileGenerator::default().amount[0], "the drag adds columns: {:?}", tile.amount); assert_eq!(harness.state().session.history_labels().len(), history + 1, "one drag is one undo step"); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); + lowest(&harness, "Restore defaults").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + lowest(&harness, "Restore defaults").click(); harness.run_steps(3); assert_eq!(*pattern(&harness, effect).tile.unwrap(), TileGenerator::default()); } @@ -205,10 +208,9 @@ fn typing_tile_contrast_then_clicking_invert_preserves_both_edits() { let (mut harness, effect) = harness(false); execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); harness.run_steps(3); - let contrast = harness.get_by_label("Contrast"); - contrast.scroll_to_me(); + lowest(&harness, "Contrast").scroll_to_me(); harness.run_steps(12); - let row = harness.get_by_label("Contrast").rect().center().y; + let row = lowest(&harness, "Contrast").rect().center().y; let at = harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap().rect().center(); harness.drag_at(at); @@ -257,13 +259,6 @@ fn tile_generator_snapshots() { } harness.state_mut().ui.prefs.brightness = Brightness::Dark; - // Open, the section also holds a menu labelled "Resolution": its title is the first one - harness.get_by_label("Resolution").click(); - harness.run_steps(6); - harness.render().unwrap().save(directory.join("tile-resolution.png")).unwrap(); - harness.get_all_by_label("Resolution").next().unwrap().click(); - harness.run_steps(6); - for (sections, name) in [(["Pattern", "Size"], "pattern-size"), (["Position", "Rotation"], "position-rotation")] { for section in sections { // A section's title can also be a control's label above it ("Position"): the title is the last one diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 3789cf98..c451ea98 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -798,6 +798,52 @@ fn i18n_snapshots() { texturecraft_ui_egui::i18n::set_language("en"); } +/// The merged effect panel selects an image and exposes its projection controls +#[test] +#[ignore] +fn mask_fill_image_snapshot() { + use serde_json::json; + use texturecraft_engine::{ + core::{EffectKind, LayerId, Source}, + execute, + }; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png_bytes = Vec::new(); + image::RgbaImage::from_fn(16, 16, |x, y| { + let value = if (x / 4 + y / 4) % 2 == 0 { 255 } else { 32 }; + image::Rgba([value, value, value, 255]) + }) + .write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png) + .unwrap(); + let name = session.import_resource_bytes("Mask checker.png", png_bytes).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + let effect = execute(&mut session, "effect.add.fill", &json!({"target": "mask", "value": 1.0})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + + // The Grayscale slot opens the source picker; its search finds the image + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.event(egui::Event::Text("checker".into())); + harness.run_steps(3); + save(&mut harness, &output_dir, "mask-fill-image-menu"); + + harness.get_by_role_and_label(egui::Role::ListBoxOption, &name).click(); + harness.run_steps(4); + + let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; + assert_eq!(*source, Source::image(name)); + assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); + save(&mut harness, &output_dir, "mask-fill-image-selected"); +} + /// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered #[test] #[ignore] @@ -1657,6 +1703,510 @@ fn popup_tabs_snapshots() { } } +/// Screen 07: a mask fill effect's Grayscale section from each kind of source (Uniform, image, procedural, anchor), its picker open with a tile hovered, and its Fill section; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn mask_fill_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + let scratches = image::RgbaImage::from_fn(64, 64, |x, y| { + let gray = 90 + ((x * 13 + y * 7) % 90) as u8; + image::Rgba([gray, gray, gray, 255]) + }); + scratches.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let scratches = session.import_resource_bytes("scratches.png", png).unwrap(); + let below = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": below, "name": "Cavity Dirt"})).unwrap()["effect"].clone(); + let layer = execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].clone(); + let effect = execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "mask"})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + save(&mut harness, &output_dir, "mask-fill-fill"); + harness.get_by_role_and_label(egui::Role::Tab, "Grayscale").click(); + harness.run_steps(30); + + let shot = |harness: &mut Harness<'_, TextureCraftApp>, mut source: serde_json::Value, name: &str| { + source["effect"] = effect.clone(); + execute(&mut harness.state_mut().session, "layer.fill.set", &source).unwrap(); + harness.run_steps(3); + settle_thumbnails(harness); + save(harness, &output_dir, name); + }; + shot(&mut harness, json!({"value": 1.0}), "mask-fill-uniform"); + shot(&mut harness, json!({"image": scratches}), "mask-fill-image"); + shot(&mut harness, json!({"procedural": "Clouds", "scale": 4.0, "seed": 12}), "mask-fill-procedural"); + + // The procedural's Resolution list open (Relative factors and Fixed sizes) with a size hovered + let click_in_view = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(3); + }; + click_in_view(&mut harness, egui::Role::ComboBox, "Texture set · 256"); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "×2 · 512").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "mask-fill-resolution-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The picker opened from the slot in view (Properties still scrolled to the card), a tile hovered + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + settle_thumbnails(&mut harness); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Clouds").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "mask-fill-picker"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("mask-fill-picker-{name}")); + } + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + shot(&mut harness, json!({"anchor": anchor}), "mask-fill-anchor"); + + // Again once the anchored stack's picture has rendered + settle_thumbnails(&mut harness); + save(&mut harness, &output_dir, "mask-fill-anchor"); + + shot(&mut harness, json!({"value": 1.0}), "mask-fill-uniform-again"); +} + +/// Screen 09: a compare mask at its defaults, within tolerance, its right source's list open with Constant hovered, then Constant picked +#[test] +#[ignore] +fn compare_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut layer = json!(null); + for (low, high) in [(-0.7, 0.1), (-0.2, 0.6)] { + layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let (low, high) = (json!([low, low, low]), json!([high, high, high])); + execute(&mut session, "layer.fill.set", &json!({"layer": layer, "channel": "height", "procedural": "Clouds", "scale": 3.0, "low": low, "high": high})) + .unwrap(); + } + let compare = execute(&mut session, "effect.add.compare", &json!({"layer": layer})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": compare})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + save(&mut harness, &output_dir, "compare-default"); + + harness.get_by(|node| node.role() == egui::Role::RadioButton && node.label().as_deref() == Some("≈")).click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "compare-within"); + harness.get_by(|node| node.role() == egui::Role::RadioButton && node.label().as_deref() == Some(">")).click(); + harness.run_steps(4); + + harness.get_by_role_and_label(egui::Role::ComboBox, "Layers below").click(); + harness.run_steps(3); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Constant").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "compare-source-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Constant").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "compare-constant"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("compare-constant-{name}")); + } + } +} + +/// Screen 11: a new anchor point on a fill's content being renamed, then a mask anchor point read by two layers above (a reference hovered) +#[test] +#[ignore] +fn anchor_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let low = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": low, "name": "Cavity Dirt"})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"layer": low, "generator": "dirt"})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "mask"})).unwrap()["effect"].clone(); + for name in ["Fill layer 2", "Rust"] { + let reader = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": reader, "name": name})).unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": reader, "anchor": anchor})).unwrap(); + } + let fresh = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let content = execute(&mut session, "effect.add.anchor", &json!({"layer": fresh})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": fresh, "target": content})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + harness.get_by_role_and_label(egui::Role::TextInput, "Anchor point name").click(); + harness.run_steps(3); + save(&mut harness, &output_dir, "anchor-new-renaming"); + + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = texturecraft_engine::StackTarget::Content; + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": low, "target": anchor})).unwrap(); + harness.run_steps(6); + let row = harness.get_by_role_and_label(egui::Role::Button, "Rust Mask fill").rect().center(); + harness.hover_at(row); + save(&mut harness, &output_dir, "anchor-mask-references"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("anchor-mask-references-{name}")); + } + } +} + +/// Screen 15: a folder of fills at rest, scaled x1.5 and turned +30 with the reset hovered, and an empty folder +#[test] +#[ignore] +fn folder_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let empty = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].clone(); + let fill = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.move", &json!({"layer": fill, "above": empty, "inside": false})).unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds"})).unwrap(); + let folder = execute(&mut session, "layer.group", &json!({"layer": fill})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": folder, "target": "content"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + save(&mut harness, &output_dir, "folder-rest"); + + execute(&mut harness.state_mut().session, "folder.contents.set", &json!({"layer": folder, "scale": 1.5, "rotation": 30.0})).unwrap(); + harness.run_steps(4); + let reset = harness.get_by_role_and_label(egui::Role::Button, "Contents: Reset to defaults").rect().center(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "folder-offset-reset-hovered"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("folder-offset-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": empty, "target": "content"})).unwrap(); + harness.run_steps(4); + save(&mut harness, &output_dir, "folder-empty"); +} + +/// Screen 16: an instance of an orange fill named Steel (at rest, its card hovered), then one whose source is gone +#[test] +#[ignore] +fn instance_snapshots() { + use serde_json::json; + use texturecraft_engine::core::{LayerId, LayerKind}; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let source = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": source, "name": "Steel"})).unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": source, "channel": "baseColor", "color": [0.78, 0.29, 0.09]})).unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": instance, "target": "content"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + save(&mut harness, &output_dir, "instance-rest"); + let set = harness.state().session.doc.project.texture_sets[0].name.clone(); + let card = harness.get_by_role_and_label(egui::Role::Button, &format!("Steel {set}")).rect().center(); + harness.hover_at(card); + save(&mut harness, &output_dir, "instance-hovered"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("instance-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + + let id = LayerId(instance.as_u64().unwrap()); + harness.state_mut().session.doc.project.layers.get_mut(&id).unwrap().kind = LayerKind::Instance { source: LayerId(999_999) }; + harness.hover_at(egui::pos2(10.0, 10.0)); + save(&mut harness, &output_dir, "instance-missing"); +} + +/// Screen 17: a folder's mask selected with the paint tool's Grayscale tab open: painting white, black, then an image (the slot hovered), then the slot's picker open +#[test] +#[ignore] +fn folder_mask_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let scratches = image::RgbaImage::from_fn(64, 64, |x, y| { + let value = (((x * 7 + y * 13) ^ (x * y)) % 200 + 40) as u8; + image::Rgba([value, value, value, 255]) + }); + let mut bytes = Vec::new(); + scratches.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let image = session.import_resource_bytes("scratches.png", bytes).unwrap(); + let folder = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": folder})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": folder, "target": "mask"})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.props_tab = texturecraft_ui_egui::state::PropsTab::Material; + harness.run_steps(6); + save(&mut harness, &output_dir, "foldermask-white"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("foldermask-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + execute(&mut harness.state_mut().session, "tool.material", &json!({"maskValue": 0.0})).unwrap(); + save(&mut harness, &output_dir, "foldermask-black"); + execute(&mut harness.state_mut().session, "tool.material", &json!({"maskImage": image})).unwrap(); + let slot = harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").rect().center(); + harness.hover_at(slot); + save(&mut harness, &output_dir, "foldermask-image"); + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "foldermask-picker"); +} + +/// Screen 10: a new color selection without an ID map, then three colors on the ID mesh map (a row hovered, a row picking again, the Background list open) +#[test] +#[ignore] +fn color_selection_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let shoot = |with_id_map: bool| { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + if !with_id_map { + execute(&mut session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); + } + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let added = execute(&mut session, "mask.add.colorSelection", &json!({"layer": layer})).unwrap(); + let effect = texturecraft_engine::core::LayerId(added["effect"].as_u64().unwrap()); + if with_id_map { + let colors = json!([[214.0 / 255.0, 1.0, 0.0], [1.0, 49.0 / 255.0, 0.0], [1.0, 0.0, 247.0 / 255.0]]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors})).unwrap(); + } + execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect.0})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + harness + }; + + let mut harness = shoot(false); + save(&mut harness, &output_dir, "colorsel-new"); + + // Picking with an ID Mask image chosen by hand and nothing baked: the model shows that image + let quarters = image::RgbaImage::from_fn(8, 8, |x, y| match (x < 4, y < 4) { + (true, true) => image::Rgba([214, 255, 0, 255]), + (false, true) => image::Rgba([255, 49, 0, 255]), + (true, false) => image::Rgba([255, 0, 247, 255]), + (false, false) => image::Rgba([20, 90, 255, 255]), + }); + let mut png = Vec::new(); + quarters.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut harness = shoot(false); + let effect = match harness.state().session.target { + texturecraft_engine::StackTarget::Effect(effect) => effect, + other => panic!("the color selection is selected, not {other:?}"), + }; + harness.state_mut().session.doc.baked.clear(); + let name = harness.state_mut().session.import_resource_bytes("parts.png", png).unwrap(); + harness.state_mut().run("effect.set", json!({"effect": effect.0, "idMap": name})); + harness.run_steps(4); + harness.get_by_label("Pick color").click(); + harness.run_steps(8); + save(&mut harness, &output_dir, "colorsel-image-pick"); + + let mut harness = shoot(true); + let row = harness.get_by_label("Pick color R 255 G 49 B 0").rect().center(); + harness.hover_at(row); + harness.run_steps(2); + save(&mut harness, &output_dir, "colorsel-hover"); + let first = harness.get_by_label("Pick color R 214 G 255 B 0").rect().center(); + harness.get_by_label("Pick color R 214 G 255 B 0").click(); + harness.run_steps(4); + harness.hover_at(first); + harness.run_steps(2); + save(&mut harness, &output_dir, "colorsel-repick"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + harness.get_by_role_and_label(egui::Role::ComboBox, "Black").click(); + harness.run_steps(3); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Transparent").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "colorsel-background-list"); + if std::env::var_os("TC_UI_THEMES").is_some() { + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("colorsel-{name}")); + } + } +} + +/// Screen 08: a mask's levels, then a content levels on Base color (Colors, red only with Clamp on, its Affects list open with an option hovered) and on Roughness +#[test] +#[ignore] +fn levels_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.5})).unwrap()["layer"].clone(); + for (channel, low, high) in + [("baseColor", json!([0.1, 0.2, 0.45]), json!([0.85, 0.5, 0.2])), ("roughness", json!([0.25, 0.25, 0.25]), json!([0.7, 0.7, 0.7]))] + { + execute(&mut session, "layer.fill.set", &json!({"layer": layer, "channel": channel, "procedural": "Clouds", "scale": 3.0, "low": low, "high": high})) + .unwrap(); + } + execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "mask", "procedural": "clouds"})).unwrap(); + let mask_levels = execute(&mut session, "effect.add.levels", &json!({"layer": layer, "target": "mask"})).unwrap()["effect"].clone(); + let content_levels = execute(&mut session, "effect.add.levels", &json!({"layer": layer, "target": "content"})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": mask_levels})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + save(&mut harness, &output_dir, "levels-mask"); + + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": content_levels})).unwrap(); + harness.run_steps(6); + save(&mut harness, &output_dir, "levels-colors"); + let switch = |harness: &mut Harness<'_, TextureCraftApp>, view: &str| { + harness.get_by(|node| node.role() == egui::Role::RadioButton && node.label().as_deref() == Some(view)).click(); + harness.run_steps(3); + }; + switch(&mut harness, "R"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Clamp").click(); + harness.run_steps(3); + save(&mut harness, &output_dir, "levels-red-clamp"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Clamp").click(); + switch(&mut harness, "Colors"); + lowest_list(&harness, "Base color").click(); + harness.run_steps(3); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Roughness").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "levels-affects-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Roughness").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "levels-roughness"); + harness.get_by_role_and_label(egui::Role::Slider, "Gamma").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + save(&mut harness, &output_dir, "levels-exact-entry"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("levels-roughness-{name}")); + } + } +} + +/// Screen 14: the Layers panel's top row (Add fill layer hovered), Add effect on a layer and on its mask, Add mask, and Bitmap's texture picker; the panel's left edge goes to stderr for cropping +#[test] +#[ignore] +fn layer_toolbar_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let dirt = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": dirt, "name": "Dirt"})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"layer": dirt, "generator": "dirt"})).unwrap(); + let fill = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": fill})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.run_steps(3); + eprintln!("toolbar at {:?}", harness.get_by_role_and_label(egui::Role::Button, "Add effect").rect()); + let hover = |harness: &mut Harness<'_, TextureCraftApp>, label: &str| { + let at = harness.get_by_role_and_label(egui::Role::Button, label).rect().center(); + harness.hover_at(at); + }; + let open = |harness: &mut Harness<'_, TextureCraftApp>, menu: &str| { + harness.get_by_role_and_label(egui::Role::Button, menu).click(); + harness.run_steps(3); + }; + hover(&mut harness, "Add fill layer"); + save(&mut harness, &output_dir, "toolbar-rest"); + open(&mut harness, "Add effect"); + hover(&mut harness, "Filter"); + save(&mut harness, &output_dir, "toolbar-effect-content"); + harness.key_press(egui::Key::Escape); + execute(&mut harness.state_mut().session, "mask.add.white", &json!({"layer": fill})).unwrap(); + harness.run_steps(3); + open(&mut harness, "Add effect"); + hover(&mut harness, "Compare mask"); + save(&mut harness, &output_dir, "toolbar-effect-mask"); + harness.key_press(egui::Key::Escape); + execute(&mut harness.state_mut().session, "edit.undo", &json!({})).unwrap(); + harness.run_steps(3); + open(&mut harness, "Add mask"); + hover(&mut harness, "Height combination"); + save(&mut harness, &output_dir, "toolbar-mask"); + harness.get_by_role_and_label(egui::Role::Button, "Bitmap").click(); + harness.run_steps(3); + save(&mut harness, &output_dir, "toolbar-bitmap"); + if std::env::var_os("TC_UI_THEMES").is_some() { + harness.key_press(egui::Key::Escape); + open(&mut harness, "Add effect"); + hover(&mut harness, "Filter"); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("toolbar-effect-content-{name}")); + } + } +} + #[test] #[ignore = "writes the material picker (Material mode) to TC_UI_SNAPSHOTS; run with --ignored"] /// A whole-material fill's card opens the material picker: grouped under its categories, Copper chosen and Brass hovered, then a search diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bc2cc695..9b88b0f8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -589,16 +589,13 @@ with `material.apply` instead. The fill remembers the material (`Fill.material`, - `effect.blending.modeToEveryChannel`, `opacityToEveryChannel` and `bothToEveryChannel {effect?, channel?}` give every channel of a content effect one channel's blend mode, opacity or both; `effect.blending.copy` and `effect.blending.paste {effect?}` carry every channel's blending between effects (a mask effect takes - the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending and - `effect.set {effect, channels: {roughness: false}}` switches a content effect's channels on or off. + the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending. - `mask.add.bitmap {layer?, image | alpha, projection?}` adds a mask fill reading an image's gray; `effect.set {effect, idMap: image resource | null}` gives a colour selection its own ID map in place of the baked one; `tool.material {maskImage: image resource | null}` paints an image's gray into masks. - `effect.add.colorSelection {layer?, color?, tolerance?}` and `mask.add.heightCombination {layer?}` add a colour selection or a compare mask (this layer's height against the layers below) to a layer's mask, making the mask first when it has none; both return `{effect}`. -- `effect.filter.restoreDefaults {effect?}` puts a filter's parameters back to its defaults (name, - channels and blending stay) and returns `{changed}`. - `layer.fill.resetProjection {layer? | effect?}` puts the Fill section back to a new fill's (same projection kind; a placed frame, the symmetry and the sources stay); `layer.fill.resetFrame` puts a warp's frame back around the mesh with its corners unpulled. Each is one undo step, or none when From b4d810ddcf39854c4533d099129f0a2725edfd04 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 039/153] Filters: engine evaluation, commands, docs and the remaining tests --- crates/compose/src/below.rs | 27 +- crates/compose/src/eval.rs | 1783 +++++++++++++++-- crates/compose/src/eval/evaluation_inputs.rs | 23 - crates/compose/src/lib.rs | 9 +- crates/compose/src/shape_distance.rs | 386 ++++ crates/compose/src/slope_texel.rs | 45 + crates/compose/tests/cache_and_instances.rs | 61 +- crates/core/src/anisotropic_kuwahara.rs | 92 + crates/core/src/bevel.rs | 98 + crates/core/src/bevel_blur.rs | 35 + crates/core/src/bevel_corner.rs | 35 + crates/core/src/bevel_direction.rs | 39 + crates/core/src/bevel_smooth.rs | 117 ++ crates/core/src/conversion_mode.rs | 63 + crates/core/src/curve_preset.rs | 142 ++ crates/core/src/directional_distance.rs | 59 + crates/core/src/directional_light.rs | 31 + crates/core/src/gradient_input.rs | 151 ++ crates/core/src/grayscale_conversion.rs | 90 + crates/core/src/grayscale_mode.rs | 58 + crates/core/src/height_to_normal.rs | 80 + crates/core/src/highpass_space.rs | 84 + crates/core/src/image_input.rs | 88 + crates/core/src/layer.rs | 661 +++++- crates/core/src/lib.rs | 86 + crates/core/src/lighting_output.rs | 49 + crates/core/src/mask_outline.rs | 92 + crates/core/src/mirror.rs | 99 + crates/core/src/mirror_corner.rs | 49 + crates/core/src/mirror_mode.rs | 39 + crates/core/src/oklab.rs | 40 + crates/core/src/outline_position.rs | 48 + crates/core/src/pbr_validate.rs | 78 + crates/core/src/project.rs | 3 +- crates/core/src/slope_blending.rs | 39 + crates/core/src/source_color_mode.rs | 36 + crates/core/src/source_slope_blur.rs | 65 + crates/core/src/stylized_lighting.rs | 157 ++ crates/core/src/sun_and_sky.rs | 11 + crates/core/src/target_color_mode.rs | 33 + crates/core/src/threshold_mode.rs | 90 + crates/core/src/tile_transform.rs | 225 +++ crates/core/src/tile_transform/flip_mode.rs | 49 + crates/core/src/tile_transform/repeat_mode.rs | 33 + crates/core/src/validation_mode.rs | 46 + crates/core/src/warp_blending.rs | 42 + crates/core/src/warp_mode.rs | 39 + crates/core/src/warp_source_mode.rs | 39 + crates/engine/src/filter_about.rs | 85 + crates/engine/src/folder_cmds.rs | 6 + crates/engine/src/inspect.rs | 10 +- crates/engine/src/layer_cmds.rs | 44 +- crates/engine/src/lib.rs | 3 + crates/engine/src/mask_cmds.rs | 76 +- crates/engine/src/material_lib.rs | 4 +- crates/engine/src/preview.rs | 49 +- crates/engine/src/session.rs | 43 +- crates/engine/src/tile_transform_params.rs | 52 + crates/engine/src/view_cmds.rs | 20 +- crates/engine/tests/it/content_effects.rs | 23 +- crates/engine/tests/it/filter_card.rs | 140 ++ crates/engine/tests/it/filter_colour.rs | 100 + crates/engine/tests/it/filter_gradient.rs | 168 ++ crates/engine/tests/it/filter_inputs.rs | 109 + crates/engine/tests/it/filter_light.rs | 204 ++ crates/engine/tests/it/filter_shape.rs | 364 ++++ crates/engine/tests/it/filter_simple.rs | 319 +++ crates/engine/tests/it/filter_swap.rs | 156 +- crates/engine/tests/it/filter_transform.rs | 78 + crates/engine/tests/it/folder_contents.rs | 1 + crates/engine/tests/it/main.rs | 9 + crates/engine/tests/it/painter_gaps.rs | 24 +- crates/engine/tests/it/resources_used.rs | 17 + crates/engine/tests/session.rs | 174 ++ crates/render/src/ibl.rs | 152 +- crates/render/src/renderer.rs | 2 +- crates/ui-egui/src/anchor_properties.rs | 22 + crates/ui-egui/src/dock.rs | 109 +- crates/ui-egui/src/fill_material_panel.rs | 1 + crates/ui-egui/src/fill_pictures.rs | 35 + crates/ui-egui/src/i18n.rs | 4 + crates/ui-egui/src/layer_toolbar.rs | 2 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/material_orb.rs | 2 + .../ui-egui/src/property_sheet/color_bar.rs | 11 + crates/ui-egui/src/property_sheet/group.rs | 89 + .../ui-egui/src/property_sheet/marker_drag.rs | 8 + crates/ui-egui/src/property_sheet/mod.rs | 3 + crates/ui-egui/src/property_sheet/row.rs | 5 +- crates/ui-egui/src/property_sheet/row_lead.rs | 4 + crates/ui-egui/src/property_sheet/slider.rs | 69 + crates/ui-egui/src/property_sheet/slot.rs | 7 + .../src/property_sheet/switch_control.rs | 13 +- crates/ui-egui/src/property_sheet/tests.rs | 44 +- .../src/property_sheet/tests/gallery.rs | 4 + crates/ui-egui/src/source_slot.rs | 10 + crates/ui-egui/src/theme.rs | 63 +- crates/ui-egui/tests/it/filter_colour.rs | 85 + crates/ui-egui/tests/it/filter_light.rs | 118 ++ crates/ui-egui/tests/it/filter_shape.rs | 307 +++ crates/ui-egui/tests/it/filter_simple.rs | 240 +++ crates/ui-egui/tests/it/filter_stylize.rs | 178 ++ crates/ui-egui/tests/it/filter_transform.rs | 86 + crates/ui-egui/tests/it/main.rs | 12 +- crates/ui-egui/tests/it/properties_lists.rs | 265 +++ crates/ui-egui/tests/ui_snapshots.rs | 642 ++++++ docs/control-protocol.md | 5 +- 107 files changed, 9956 insertions(+), 665 deletions(-) delete mode 100644 crates/compose/src/eval/evaluation_inputs.rs create mode 100644 crates/compose/src/shape_distance.rs create mode 100644 crates/compose/src/slope_texel.rs create mode 100644 crates/core/src/anisotropic_kuwahara.rs create mode 100644 crates/core/src/bevel.rs create mode 100644 crates/core/src/bevel_blur.rs create mode 100644 crates/core/src/bevel_corner.rs create mode 100644 crates/core/src/bevel_direction.rs create mode 100644 crates/core/src/bevel_smooth.rs create mode 100644 crates/core/src/conversion_mode.rs create mode 100644 crates/core/src/curve_preset.rs create mode 100644 crates/core/src/directional_distance.rs create mode 100644 crates/core/src/directional_light.rs create mode 100644 crates/core/src/gradient_input.rs create mode 100644 crates/core/src/grayscale_conversion.rs create mode 100644 crates/core/src/grayscale_mode.rs create mode 100644 crates/core/src/height_to_normal.rs create mode 100644 crates/core/src/highpass_space.rs create mode 100644 crates/core/src/image_input.rs create mode 100644 crates/core/src/lighting_output.rs create mode 100644 crates/core/src/mask_outline.rs create mode 100644 crates/core/src/mirror.rs create mode 100644 crates/core/src/mirror_corner.rs create mode 100644 crates/core/src/mirror_mode.rs create mode 100644 crates/core/src/oklab.rs create mode 100644 crates/core/src/outline_position.rs create mode 100644 crates/core/src/pbr_validate.rs create mode 100644 crates/core/src/slope_blending.rs create mode 100644 crates/core/src/source_color_mode.rs create mode 100644 crates/core/src/source_slope_blur.rs create mode 100644 crates/core/src/stylized_lighting.rs create mode 100644 crates/core/src/sun_and_sky.rs create mode 100644 crates/core/src/target_color_mode.rs create mode 100644 crates/core/src/threshold_mode.rs create mode 100644 crates/core/src/tile_transform.rs create mode 100644 crates/core/src/tile_transform/flip_mode.rs create mode 100644 crates/core/src/tile_transform/repeat_mode.rs create mode 100644 crates/core/src/validation_mode.rs create mode 100644 crates/core/src/warp_blending.rs create mode 100644 crates/core/src/warp_mode.rs create mode 100644 crates/core/src/warp_source_mode.rs create mode 100644 crates/engine/src/filter_about.rs create mode 100644 crates/engine/src/tile_transform_params.rs create mode 100644 crates/engine/tests/it/filter_card.rs create mode 100644 crates/engine/tests/it/filter_colour.rs create mode 100644 crates/engine/tests/it/filter_gradient.rs create mode 100644 crates/engine/tests/it/filter_inputs.rs create mode 100644 crates/engine/tests/it/filter_light.rs create mode 100644 crates/engine/tests/it/filter_shape.rs create mode 100644 crates/engine/tests/it/filter_simple.rs create mode 100644 crates/engine/tests/it/filter_transform.rs create mode 100644 crates/ui-egui/src/property_sheet/marker_drag.rs create mode 100644 crates/ui-egui/tests/it/filter_colour.rs create mode 100644 crates/ui-egui/tests/it/filter_light.rs create mode 100644 crates/ui-egui/tests/it/filter_shape.rs create mode 100644 crates/ui-egui/tests/it/filter_simple.rs create mode 100644 crates/ui-egui/tests/it/filter_stylize.rs create mode 100644 crates/ui-egui/tests/it/filter_transform.rs create mode 100644 crates/ui-egui/tests/it/properties_lists.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 05d1cafc..4d8f01c1 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeSet, HashMap, VecDeque}; use std::sync::Arc; use texturecraft_core::project::MAX_DEPTH; -use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{BakedMap, Channel, EffectKind, Filter, Layer, LayerId, LayerKind, Project, Source, TextureSet}; use texturecraft_texel::TileImage; use crate::eval::{Inputs, PaintTarget}; @@ -98,6 +98,8 @@ pub struct StackKey { pixels: Vec<(LayerId, Option, Shared)>, baked: (u32, Vec<(BakedMap, usize)>), images: Vec<(String, ImageIdentity)>, + /// The viewport environment, its rotation (bits) and its image when it is an imported one, where Baked Lighting Environment lights with them + environment: Option<(String, u32, Option)>, } impl StackKey { @@ -152,6 +154,8 @@ impl StackKey { fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name); } for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + // A filter's image inputs, also one its mode leaves unread: that only empties the cache more often + effect.inputs.values().flat_map(Source::images).for_each(&mut record_image_name); match &effect.kind { EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), @@ -166,6 +170,16 @@ impl StackKey { let image_identities = referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect(); + let lit = render_tree + .iter() + .filter_map(|id| project.layers.get(id)) + .flat_map(|layer| layer.content_effects.iter()) + .any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. }))); + let environment = lit.then(|| { + let image = project.display.environment_resource().and_then(|name| images.get(name)).map(ImageIdentity::new); + (project.display.environment.clone(), project.display.env_rotation.to_bits(), image) + }); + Some(StackKey { set, roots, @@ -173,6 +187,7 @@ impl StackKey { pixels: pixel_handles, baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()), images: image_identities, + environment, }) } } @@ -182,14 +197,18 @@ impl StackKey { /// changed (same set, roots, layers, baked maps and images; the same images by id, channel /// and size). None when anything else differs: the caller recomposites everything. pub fn changed_tiles(&self, other: &StackKey) -> Option> { - if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images { + if self.set != other.set + || self.roots != other.roots + || self.layers != other.layers + || self.baked != other.baked + || self.images != other.images + || self.environment != other.environment + { return None; } - if self.pixels.len() != other.pixels.len() { return None; } - let size = self.set.size(); let mut changed = BTreeSet::new(); for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index d0cdb0f2..ffe4a3d3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -14,15 +14,20 @@ use texturecraft_core::{ BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, ShapeCrop, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, + CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, + HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, Project, Projection, + RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, + TileTransform, blend1, blend3, lum, mix3, per_unit, posterize, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; -use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::effect_histogram::EffectHistogram; +use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_place::FillPlace; @@ -32,8 +37,10 @@ use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, procedur use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; use crate::projector_depth::ProjectorDepth; +use crate::shape_distance::distance_filter; +use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; -use evaluation_inputs::EvaluationInputs; +use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; const NCH: usize = Channel::ALL.len(); @@ -46,6 +53,12 @@ const SEAM_JUMP_SHARE: f32 = 0.25; /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; +/// How tall a baked height of 1 stands, as a fraction of a UV tile, when Baked Lighting Stylized tilts normals by its slope +const HEIGHT_RELIEF: f32 = 1.0 / 32.0; + +/// The Height Intensity of Baked Lighting Environment that tilts the normals as Baked Lighting Stylized's Height to Normal Intensity 1 does (its default) +const ENVIRONMENT_HEIGHT_UNIT: f32 = 4.0; + /// What a live stroke paints into. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PaintTarget { @@ -260,6 +273,12 @@ struct EffectPlan<'a> { depth: Option>, /// Whether a fill or material effect covers every texel (see [`covers_every_texel`]), so no texel asks covers_all: bool, + /// The viewport environment's light, for Baked Lighting Environment + environment: Option, + /// Baked Lighting Stylized's settings worked out once for every texel it shades + stylized: Option, + /// The source a point filter's image input reads (Grayscale Conversion's Custom Input) + input: Option, } struct MaskPlan<'a> { @@ -317,36 +336,63 @@ impl FieldKey { pub type Fields = HashMap; -/// How a neighbourhood filter reads around a texel. +/// How a neighbourhood filter reads around a texel #[derive(Clone, Copy)] enum Op { - /// Box blurs (≈ Gaussian), sharpening by the amount when given. + /// Box blurs (≈ Gaussian), sharpening by the amount when given Blur(Option), - /// The value minus its box blur, around the channel's mid value. - HighPass, - /// Values ramped down towards their shape's edge, from the box blur. + /// The value minus its box blur, around the channel's mid value: colors in `space`, the coverage too when `alpha` + HighPass { space: HighpassSpace, alpha: bool }, + /// Values ramped down towards their shape's edge, from the box blur Bevel, - /// The value plus its box blur times the amount. + /// The value plus its box blur times the amount Glow(f32), - /// The value at the center of its cell (`r` texels across). - Mosaic, - /// Average along a direction (unit vector in texels). + /// The value at the center of its cell (`r` texels across); the texel's own coverage kept unless `alpha` + Mosaic { alpha: bool }, + /// Stair-stepped edges blended across (FXAA); the texel's own coverage kept unless `alpha` + Fxaa { alpha: bool }, + /// The mean of the calmest sector of an ellipse along the local direction (see [`kuwahara_texel`]) + Kuwahara(AnisotropicKuwahara), + /// Average along a direction (unit vector in texels) Line([f32; 2]), - /// Read at an offset given by a noise vector field, or by noise along a direction. + /// Read at an offset given by a noise vector field, or by noise along a direction Warp { scale: f32, seed: u32, dir: Option<[f32; 2]> }, - /// Gradient magnitude from central differences. + /// Gradient magnitude from central differences Edge, - /// Average downhill along a noise height field. + /// Average downhill along a noise height field Slope { scale: f32, seed: u32 }, + /// Box blurs, then the effect's own point filter on the blurred value (a gradient's Blur Intensity) + PreBlur, + /// A halo from the box blur of the shapes, laid around (or inside) them + Halo, + /// The shapes moved by `offset` (whole texels), box blurred and laid under them + Shadow { offset: [i32; 2] }, + /// Each UV tile's texels read from where `mirror` sends them in their tile (`block` texels across the set's atlas blocks) + Mirror { mirror: Mirror, block: u32 }, + /// Each UV tile's texels read from where `transform` sends them (its `affine`, worked out once), repeating round the tile or empty past it + Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]), block: u32 }, + /// A band along the edge of the shapes past a threshold, from the box blur of the shapes + Outline(MaskOutline), + /// Drawn from the distance to the shapes' edge (see [`distance_filter`]) + Distance, + /// Read from where a warp's source sends each texel (see [`warp_texel`]) + SourceWarp(SourceWarp), + /// The values downhill of each texel along a source's slope, blended (see [`slope_texel`]) + SourceSlopeBlur(SourceSlopeBlur), + /// The normal of the slopes of the layer's Height (see [`height_to_normal_texel`]) + HeightToNormal(HeightToNormal), + /// Colors moved from a source color to a target color; the source the whole set's mean in Source Color Mode Average (see [`color_match`]) + ColorMatch(ColorMatch), } -/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]) fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } -/// Below this a coverage weight counts as no coverage at all. -const MIN_COVERAGE_WEIGHT: f32 = 1e-6; +/// Below this squared length an unpacked baked normal is no direction (an unbaked texel) +const MIN_NORMAL_LENGTH_SQUARED: f32 = 1e-6; + /// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. const FILTER_SIZE_RESOLUTION: f32 = 2048.0; /// The smallest radius a filter runs at, in texels. @@ -359,29 +405,70 @@ const MIN_SHARPEN_RADIUS: f32 = 0.75; fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); 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::Blur { radius, .. }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), EffectKind::Filter(Filter::Sharpen { amount }) => { Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), 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::Warp { intensity, scale, seed, divider }) if *intensity > 0.0 => { + Some((index, texels(divided(*intensity, *divider)), 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::DirectionalWarp { intensity, angle, scale, seed, divider }) if *intensity > 0.0 => { + Some((index, texels(divided(*intensity, *divider)), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) } - EffectKind::Filter(Filter::HighPass { radius }) => Some((index, texels(*radius), Op::HighPass)), + EffectKind::Filter(Filter::SourceWarp(warp)) if warp.move_texels(res) > 0.0 => Some((index, warp.reach(res).max(0.5), Op::SourceWarp(*warp))), + EffectKind::Filter(Filter::SourceSlopeBlur(slope)) if slope.move_texels(res) > 0.0 => { + Some((index, slope.reach(res).max(0.5), Op::SourceSlopeBlur(*slope))) + } + EffectKind::Filter(Filter::HighPass { radius, space, alpha }) => Some((index, texels(*radius), Op::HighPass { space: *space, alpha: *alpha })), 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::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)), - // Use reference-resolution reach so all callers classify the same filters as stages + EffectKind::Filter(Filter::Mosaic { size, alpha }) => Some((index, texels(*size), Op::Mosaic { alpha: *alpha })), + EffectKind::Filter(Filter::Fxaa { alpha }) => Some((index, FXAA_SEARCH as f32 + 1.0, Op::Fxaa { alpha: *alpha })), + // The ellipse reaches up to twice the radius along a clear direction, and the direction is read around its reach + EffectKind::Filter(Filter::AnisotropicKuwahara(kuwahara)) if kuwahara.radius > 0.0 => { + Some((index, texels(kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS)) * (2.0 + kuwahara.tensor_reach()) + 1.0, Op::Kuwahara(*kuwahara))) + } + + // The slopes come from the heights right around a texel + EffectKind::Filter(Filter::HeightToNormal(filter)) => Some((index, 1.0, Op::HeightToNormal(*filter))), + // Average reads the mean color of the whole set; the other modes read the texel alone + EffectKind::Filter(Filter::ColorMatch(matcher)) => { + Some((index, if matcher.source_mode == SourceColorMode::Average { WHOLE_SET } else { 1.0 }, Op::ColorMatch(*matcher))) + } + // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) } - EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { - Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) + // A mirror reads anywhere in its UV tile + EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror, block: res })), + // A transform reads anywhere in its UV tile; one that changes nothing is skipped + EffectKind::Filter(Filter::Transform(transform)) if !transform.is_identity() => { + Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine(), block: res })) + } + + // Three box passes reach the band's width + EffectKind::Filter(Filter::MaskOutline(outline)) => { + Some((index, (outline.width * res as f32 / BLUR_BOX_PASSES as f32).max(MIN_FILTER_RADIUS), Op::Outline(*outline))) + } + + // Three box passes' reach covers the distance and its smoothing + EffectKind::Filter(filter @ (Filter::DistanceBevel(_) | Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))) => { + Some((index, distance_reach(filter, res) / BLUR_BOX_PASSES as f32 + 1.0, Op::Distance)) + } + EffectKind::Filter(Filter::HaloGlow { width, .. }) => Some((index, texels(width.abs() * Filter::HALO_REACH), Op::Halo)), + EffectKind::Filter(Filter::DropShadow { angle, distance, size, .. }) => { + // Cast away from the light: `distance` of a UV tile, against the light's direction + let [dx, dy] = direction(*angle); + let reach = distance.clamp(-Filter::SHADOW_DISTANCE_MAX, Filter::SHADOW_DISTANCE_MAX) * res as f32; + let offset = [(-dx * reach).round() as i32, (-dy * reach).round() as i32]; + Some((index, texels(size * Filter::HALO_REACH), Op::Shadow { offset })) + } + EffectKind::Filter(Filter::GradientMap { input, debug: false, .. }) if input.blur > 0.0 => Some((index, texels(input.blur), Op::PreBlur)), + EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed, divider }) if *radius > 0.0 => { + Some((index, texels(divided(*radius, *divider)), Op::Slope { scale: *scale, seed: *seed })) } _ => None, }) @@ -403,9 +490,27 @@ pub fn stack_reads_neighbours(project: &Project, texture_set_index: usize) -> bo }) } +/// A neighbourhood radius that reaches the whole set ([`filter_extent`] caps it at the set's longest side) +const WHOLE_SET: f32 = 65_536.0; + +/// How many texels around a texel distance filter `filter` reads at `res` texels across a UV tile: its reach and its smoothing's three box passes +fn distance_reach(filter: &Filter, res: u32) -> f32 { + match filter { + Filter::DistanceBevel(bevel) => bevel.reach(res) + BLUR_BOX_PASSES as f32 * bevel.smoothing_texels(res), + Filter::BevelSmooth(smooth) => smooth.reach(res) + BLUR_BOX_PASSES as f32 * smooth.smoothing_texels(res), + Filter::DirectionalDistance(trail) => trail.reach(res), + _ => 0.0, + } +} + +/// `size` over its intensity divider (a divider of 0 from a hostile file counts as 1) +fn divided(size: f32, divider: u16) -> f32 { + size / f32::from(divider.max(1)) +} + /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn /// counterclockwise on screen. -fn direction(angle: f32) -> [f32; 2] { +pub(crate) fn direction(angle: f32) -> [f32; 2] { let (sn, cs) = angle.to_radians().sin_cos(); [cs, -sn] } @@ -417,36 +522,79 @@ const MAP_GAIN: f32 = 2.0; 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; +pub(crate) const LINE_SAMPLES: i32 = 24; /// Fractal noise over texel position `(x, y)` (`res` texels per UV unit, `scale` features per /// UV unit), shifted by `d` in noise space. -fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 { - let k = if scale.is_finite() { scale.clamp(0.01, 1000.0) } else { 1.0 } / res.max(1) as f32; - noise::fbm([x * k + d[0], y * k + d[1], 0.0], 3, seed, noise::perlin) +pub(crate) fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 { + let per_texel = if scale.is_finite() { scale.clamp(Filter::NOISE_SCALE_MIN, Filter::NOISE_SCALE_MAX) } else { 1.0 } / res.max(1) as f32; + noise::fbm([x * per_texel + d[0], y * per_texel + d[1], 0.0], 3, seed, noise::perlin) } -/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a -/// field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their -/// `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in. -/// Positions are absolute texel coordinates, so a texel's result does not depend on the region. +/// Gain on a noise warp's value around mid gray: values a third away from it already move the whole radius, as the noise seldom strays further +const WARP_NOISE_GAIN: f32 = 3.0; + +/// Mixed into a noise warp's seed for its vertical move, so it differs from the horizontal one (any odd constant does) +const WARP_Y_SALT: u32 = 0x5BD1_E995; + +/// How far apart, in noise space, a slope blur measures its noise's slope +const SLOPE_NOISE_PROBE: f32 = 0.01; + +/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in; positions are absolute texel coordinates, so a texel's result does not depend on the region #[allow(clippy::too_many_arguments)] -fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u32, u32, u32, u32), r: f32, res: u32, opacity: f32) -> Vec { +fn gather( + op: Op, + (orig, cover, grays): (&[f32], &[f32], &[f32]), + comps: usize, + (x0, y0, w, h): (u32, u32, u32, u32), + r: f32, + res: u32, + opacity: f32, +) -> Vec { let mut data = orig.to_vec(); - let (wu, hu) = (w as usize, h as usize); - // Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight). + let (width, height) = (w as usize, h as usize); + + // The filter's image input at absolute texel position (fx, fy), bilinear over the covered texels; None off them + let input = |fx: f32, fy: f32| -> Option { + if !(fx.is_finite() && fy.is_finite()) { + return None; + } + + let (bx, by) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - bx, fy - by); + let (mut sum, mut weight) = (0.0f32, 0.0f32); + for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { + let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0)); + if k <= 0.0 || cx < 0 || cy < 0 || cx >= width as i64 || cy >= height as i64 { + continue; + } + + let i = cy as usize * width + cx as usize; + if let (Some(covered), Some(gray)) = (cover.get(i), grays.get(i)) + && *covered > 0.0 + { + sum += gray * k; + weight += k; + } + } + (weight > MIN_READ_WEIGHT).then(|| sum / weight) + }; + + // Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight) let sample = |fx: f32, fy: f32, acc: &mut [f32; 5]| { if !(fx.is_finite() && fy.is_finite()) { return; } + let (bx, by) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - bx, fy - by); for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] { let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0)); - if k <= 0.0 || cx < 0 || cy < 0 || cx >= wu as i64 || cy >= hu as i64 { + if k <= 0.0 || cx < 0 || cy < 0 || cx >= width as i64 || cy >= height as i64 { continue; } - let i = cy as usize * wu + cx as usize; + + let i = cy as usize * width + cx as usize; let (Some(c), Some(px)) = (cover.get(i), orig.get(i * comps..(i + 1) * comps)) else { continue }; for (a, v) in acc.iter_mut().zip(px) { *a += v * k; @@ -454,11 +602,12 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 acc[4] += c * k; } }; - data.par_chunks_mut((comps * wu).max(1)).enumerate().for_each(|(row, line)| { - for col in 0..wu { - if cover.get(row * wu + col).is_none_or(|c| *c <= 0.0) { + data.par_chunks_mut((comps * width).max(1)).enumerate().for_each(|(row, line)| { + for col in 0..width { + if cover.get(row * width + col).is_none_or(|c| *c <= 0.0) { continue; } + let (x, y) = ((x0 as usize + col) as f32, (y0 as usize + row) as f32); let mut acc = [0.0f32; 5]; let n = (r.ceil() as i32).clamp(1, LINE_SAMPLES); @@ -471,53 +620,92 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 } } Op::Warp { scale, seed, dir } => { - let off = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * 3.0).clamp(-1.0, 1.0) * r; + let noise_offset = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * WARP_NOISE_GAIN).clamp(-1.0, 1.0) * r; match dir { Some(d) => { - let t = off(0); + let t = noise_offset(0); sample(x + d[0] * t, y + d[1] * t, &mut acc); } - None => sample(x + off(0), y + off(0x5BD1_E995), &mut acc), + None => sample(x + noise_offset(0), y + noise_offset(WARP_Y_SALT), &mut acc), } } Op::Edge => { - let center = orig.get((row * wu + col) * comps..(row * wu + col + 1) * comps).unwrap_or(&[]); + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); let at = |dx: f32, dy: f32| { - let mut a = [0.0f32; 5]; - sample(x + dx, y + dy, &mut a); - a + let mut read = [0.0f32; 5]; + sample(x + dx, y + dy, &mut read); + read }; - let (l, rt, u, d) = (at(-r, 0.0), at(r, 0.0), at(0.0, -r), at(0.0, r)); - // A side outside the UV island reads the texel itself: seams are not edges. - let val = |a: &[f32; 5], k: usize| if a[4] > 1e-6 { a[k] / a[4] } else { center.get(k).copied().unwrap_or(0.0) }; - let mag = |k: usize| (val(&rt, k) - val(&l, k)).hypot(val(&d, k) - val(&u, k)).min(1.0); - // Content stays premultiplied by its own coverage; masks are one value. - let cov = if comps == 4 { center.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - for (k, a) in acc.iter_mut().enumerate().take(comps.min(3)) { - *a = mag(k) * cov; + let (left, right, up, down) = (at(-r, 0.0), at(r, 0.0), at(0.0, -r), at(0.0, r)); + + // A side outside the UV island reads the texel itself: seams are not edges + let component = |read: &[f32; 5], k: usize| { + if read[4] > MIN_READ_WEIGHT { read[k] / read[4] } else { center.get(k).copied().unwrap_or(0.0) } + }; + let magnitude = |k: usize| (component(&right, k) - component(&left, k)).hypot(component(&down, k) - component(&up, k)).min(1.0); + + // Content stays premultiplied by its own coverage; masks are one value + let coverage = if comps == 4 { center.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + for (k, slot) in acc.iter_mut().enumerate().take(comps.min(3)) { + *slot = magnitude(k) * coverage; } if comps == 4 { - acc[3] = cov; + acc[3] = coverage; } acc[4] = 1.0; } Op::Slope { scale, seed } => { - let e = 0.01; - let hgt = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed); - // Downhill; a flat spot keeps its value. - let d = Vec2::new(hgt(-e, 0.0) - hgt(e, 0.0), hgt(0.0, -e) - hgt(0.0, e)).try_normalize().unwrap_or(Vec2::ZERO); + let noise_height = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed); + let probe = SLOPE_NOISE_PROBE; + + // Downhill; a flat spot keeps its value + let downhill = Vec2::new(noise_height(-probe, 0.0) - noise_height(probe, 0.0), noise_height(0.0, -probe) - noise_height(0.0, probe)); + let d = downhill.try_normalize().unwrap_or(Vec2::ZERO); for s in 0..=n { let t = s as f32 * step; sample(x + d.x * t, y + d.y * t, &mut acc); } } - Op::Mosaic => { + Op::Mosaic { alpha } => { let center = |v: f32| ((v / r).floor() + 0.5) * r - 0.5; sample(center(x), center(y), &mut acc); + if !alpha { + keep_coverage(&mut acc, comps, orig.get((row * width + col) * comps + 3)); + } } - Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_) => {} + Op::Fxaa { alpha } => { + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); + fxaa_texel((x, y), comps, center, &mut acc, &sample); + if !alpha { + keep_coverage(&mut acc, comps, center.get(3)); + } + } + Op::Mirror { mirror, block } => { + mirror_texel(&mirror, (x, y), (block, res), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample) + } + Op::Transform { transform, affine, block } => transform_texel(&transform, affine, (x, y), (block, res), &mut acc, &sample), + Op::SourceWarp(warp) => warp_texel(&warp, (x, y), (res, comps), &mut acc, (&sample, &input)), + Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), &mut acc, (&sample, &input)), + Op::HeightToNormal(filter) => { + let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); + height_to_normal_texel(&filter, (x, y), (res, center), &mut acc, &input); + } + Op::Kuwahara(kuwahara) => { + let radius = (kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS) * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); + kuwahara_texel(&kuwahara, (x, y), (radius, comps), &mut acc, (&sample, &input)); + } + Op::ColorMatch(_) + | Op::Blur(_) + | Op::HighPass { .. } + | Op::Bevel + | Op::Glow(_) + | Op::PreBlur + | Op::Halo + | Op::Shadow { .. } + | Op::Outline(_) + | Op::Distance => {} } - if acc[4] > 1e-6 + if acc[4] > MIN_READ_WEIGHT && let Some(px) = line.get_mut(col * comps..(col + 1) * comps) { for (slot, a) in px.iter_mut().zip(acc) { @@ -529,6 +717,411 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 data } +/// The linear colors `source` gives over texel region `(x0, y0, w, h)` (its tiles `tiles`), row by row +fn input_colors(inp: &Inputs, source: &Source, tiles: &[(u32, u32)], (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec<[f32; 3]> { + let parts: Vec> = tiles + .par_iter() + .map(|&(tx, ty)| { + let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); + tile_texels(inp.gbuf, tx, ty) + .map(|(x, y, offset)| { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); + (x, y, texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color)) + }) + .collect() + }) + .collect(); + let mut colors = vec![[0.0f32; 3]; (w * h) as usize]; + for &(x, y, color) in parts.iter().flatten() { + if let (Some(dx), Some(dy)) = (x.checked_sub(x0), y.checked_sub(y0)) + && let Some(slot) = colors.get_mut((dy * w + dx) as usize) + { + *slot = color; + } + } + colors +} + +/// Color Match's per-texel source or target colors (None: one color for the whole region) +type MatchColors = Option>; + +/// Color Match over premultiplied `data` (`comps` values a texel): each covered color moved from its source (the region's mean or its Input color) to its target (Target Color or its Image Input color), mixed in by `opacity` +fn color_match(data: &mut [f32], comps: usize, matcher: &ColorMatch, (sources, targets): (&MatchColors, &MatchColors), opacity: f32) { + if comps != 4 || opacity <= 0.0 { + return; + } + + // The mean of the covered colors (premultiplied, so a texel counts by its coverage) + let (sum, covered) = data + .par_chunks(4) + .fold( + || ([0.0f64; 3], 0.0f64), + |(mut sum, mut covered), px| { + if let [r, g, b, a] = *px + && a > 0.0 + && a.is_finite() + { + for (slot, v) in sum.iter_mut().zip([r, g, b]) { + *slot += f64::from(v); + } + covered += f64::from(a); + } + (sum, covered) + }, + ) + .reduce(|| ([0.0; 3], 0.0), |(a, ca), (b, cb)| ([a[0] + b[0], a[1] + b[1], a[2] + b[2]], ca + cb)); + let mean = if covered > 0.0 { sum.map(|v| (v / covered) as f32) } else { matcher.target_color }; + data.par_chunks_mut(4).enumerate().for_each(|(i, px)| { + let [r, g, b, a] = *px else { return }; + if a <= 0.0 || !a.is_finite() { + return; + } + + let source = match matcher.source_mode { + SourceColorMode::Average => mean, + SourceColorMode::Parameter => matcher.source_color, + SourceColorMode::Input => sources.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.source_color), + }; + let target = match matcher.target_mode { + TargetColorMode::Parameter => matcher.target_color, + TargetColorMode::ImageInput => targets.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.target_color), + }; + let moved = matcher.apply([r, g, b].map(|v| v / a), source, target); + for (slot, v) in px.iter_mut().zip(moved) { + *slot += (v * a - *slot) * opacity; + } + }); +} + +/// Height To Normal at texel `(x, y)` into `acc`: the 3×3 Sobel normal of the heights `height` reads, laid over normal `center` unless it overwrites it +fn height_to_normal_texel( + filter: &HeightToNormal, + (x, y): (f32, f32), + (res, center): (u32, &[f32]), + acc: &mut [f32; 5], + height: &dyn Fn(f32, f32) -> Option, +) { + let (Some(own), [red, green, blue, cov]) = (height(x, y), center) else { return }; + if *cov <= 0.0 { + return; + } + + let at = |dx: f32, dy: f32| height(x + dx, y + dy).unwrap_or(own); + + // Sobel gradients over the kernel's weight sum + let gx = (at(1.0, -1.0) + 2.0 * at(1.0, 0.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(-1.0, 0.0) - at(-1.0, 1.0)) / 8.0; + let gy = (at(-1.0, 1.0) + 2.0 * at(0.0, 1.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(0.0, -1.0) - at(1.0, -1.0)) / 8.0; + let made = filter.normal([gx, gy], res).map(|v| v * 0.5 + 0.5); + let packed = if filter.overwrite { made } else { texturecraft_core::blend::rnm([red, green, blue].map(|v| v / cov), made) }; + for (slot, value) in acc.iter_mut().zip(packed) { + *slot = value * cov; + } + acc[3] = *cov; + acc[4] = 1.0; +} + +/// Gathered sample `acc` (premultiplied, then weight) recoloured over the texel's own coverage `own` (content only; a sample with no coverage leaves it) +fn keep_coverage(acc: &mut [f32; 5], comps: usize, own: Option<&f32>) { + let Some(&own) = own.filter(|_| comps == 4) else { return }; + if acc[3] <= MIN_READ_WEIGHT { + acc[4] = 0.0; + return; + } + + let scale = own * acc[4] / acc[3]; + for component in acc.iter_mut().take(3) { + *component *= scale; + } + acc[3] = own * acc[4]; +} + +/// Sample rows (and columns) on each side of the middle Anisotropic Kuwahara reads its ellipse with at most +const KUWAHARA_STEPS: i32 = 6; + +/// Below this, a structure tensor has no direction +const MIN_TENSOR: f32 = 1e-12; + +/// How fast a Kuwahara sample's gaussian weight falls with its squared distance across the ellipse (e^-2 at the rim) +const KUWAHARA_FALLOFF: f32 = 2.0; + +/// A spread of one in a sector, in 8-bit steps: what Anisotropic Kuwahara's sector weights are measured in +const KUWAHARA_SPREAD_SCALE: f32 = 255.0; + +/// Anisotropic Kuwahara at texel `(x, y)` (`radius` texels, `comps` components) into `acc`: an ellipse along the gray's direction, its sectors' means weighed by their calm +fn kuwahara_texel( + kuwahara: &AnisotropicKuwahara, + (x, y): (f32, f32), + (radius, comps): (f32, usize), + acc: &mut [f32; 5], + (sample, input): (Sample<'_>, Input<'_>), +) { + // A straight value at an offset; None off the UV island + let read = |fx: f32, fy: f32| -> Option<[f32; 4]> { + let mut sum = [0.0f32; 5]; + sample(fx, fy, &mut sum); + (sum[4] > MIN_READ_WEIGHT).then(|| std::array::from_fn(|k| if k < comps.min(4) { sum[k] / sum[4] } else { 0.0 })) + }; + let gray = |fx: f32, fy: f32| if kuwahara.custom_input { input(fx, fy) } else { read(fx, fy).map(|px| fxaa_luma(&px[..comps.min(4)])) }; + + // Structure tensor: the gray's gradients over a 3×3 grid spread by Tensor Smoothness, the middle weighing most + let spread = kuwahara.tensor_reach() * radius; + let (mut xx, mut xy, mut yy) = (0.0f32, 0.0f32, 0.0f32); + for gy in -1i32..=1 { + for gx in -1i32..=1 { + let (px, py) = (x + gx as f32 * spread, y + gy as f32 * spread); + let own = gray(px, py); + let at = |dx: f32, dy: f32| gray(px + dx, py + dy).or(own); + let (Some(left), Some(right), Some(up), Some(down)) = (at(-1.0, 0.0), at(1.0, 0.0), at(0.0, -1.0), at(0.0, 1.0)) else { continue }; + // Central differences over two texels + let (dx, dy) = ((right - left) * 0.5, (down - up) * 0.5); + + // A 1-2-1 binomial kernel in each direction: the middle 4, the sides 2, the corners 1 + let weight = (4 >> (gx.abs() + gy.abs())) as f32; + xx += weight * dx * dx; + xy += weight * dx * dy; + yy += weight * dy * dy; + } + } + let root = ((xx - yy).powi(2) + 4.0 * xy * xy).sqrt(); + let clear = if xx + yy > MIN_TENSOR { root / (xx + yy) } else { 0.0 }; + + // Strokes run across the steepest change; Anisotropy Angle turns the ellipse counterclockwise on screen + let along = 0.5 * (2.0 * xy).atan2(xx - yy) + std::f32::consts::FRAC_PI_2 - kuwahara.angle.to_radians(); + let (sin, cos) = if along.is_finite() { along.sin_cos() } else { (0.0, 1.0) }; + let (major, minor) = kuwahara.axes(radius, if clear.is_finite() { clear } else { 0.0 }); + + // Each sector's weighted sum, squared sum and weight + let mut sums = [[0.0f32; 5]; AnisotropicKuwahara::SECTORS]; + let mut squares = [0.0f32; AnisotropicKuwahara::SECTORS]; + let steps = (major.ceil() as i32).clamp(1, KUWAHARA_STEPS); + let exponent = kuwahara.sector_exponent(); + let colors = comps.min(3); + for j in -steps..=steps { + for i in -steps..=steps { + let (u, v) = (i as f32 / steps as f32, j as f32 / steps as f32); + let distance = u * u + v * v; + if distance > 1.0 { + continue; + } + + let (ox, oy) = (u * major, v * minor); + let Some(px) = read(x + ox * cos - oy * sin, y + ox * sin + oy * cos) else { continue }; + let falloff = (-KUWAHARA_FALLOFF * distance).exp(); + let heading = v.atan2(u); + for (k, (sum, square)) in sums.iter_mut().zip(&mut squares).enumerate() { + // The middle texel belongs to every sector; the others to the sectors they face, fading towards their sides + let facing = (heading - k as f32 * std::f32::consts::TAU / AnisotropicKuwahara::SECTORS as f32).cos(); + let weight = if distance <= 0.0 { + falloff + } else if facing > 0.0 { + falloff * facing.powf(exponent) + } else { + continue; + }; + for (slot, value) in sum.iter_mut().zip(&px) { + *slot += weight * value; + } + sum[4] += weight; + *square += weight * px.iter().take(colors).map(|value| value * value).sum::(); + } + } + } + + // Calmer sectors weigh more, sharper the higher the Sharpness (in logs, so the powers can't overflow) + let sharpness = kuwahara.sharpness_exponent(); + let logs: [Option; AnisotropicKuwahara::SECTORS] = std::array::from_fn(|sector| { + let (sum, square) = (sums.get(sector)?, squares.get(sector)?); + (sum[4] > MIN_READ_WEIGHT).then(|| { + let mean = sum.iter().take(colors).map(|value| (value / sum[4]).powi(2)).sum::(); + let spread = (square / sum[4] - mean).max(0.0).sqrt(); + -sharpness * (1.0 + KUWAHARA_SPREAD_SCALE * spread).ln() + }) + }); + let Some(top) = logs.iter().flatten().copied().reduce(f32::max) else { return }; + let mut total = [0.0f32; 5]; + for (sum, log) in sums.iter().zip(&logs) { + let Some(log) = log else { continue }; + let weight = (log - top).exp(); + for (slot, value) in total.iter_mut().zip(sum.iter().take(4)) { + *slot += weight * value / sum[4]; + } + total[4] += weight; + } + *acc = total; +} + +/// Texels an FXAA edge search walks each way along an edge at most +const FXAA_SEARCH: i32 = 8; + +/// The least luma contrast around a texel FXAA smooths +const FXAA_EDGE_MIN: f32 = 0.0312; + +/// The least luma contrast around a texel FXAA smooths, as a share of its brightest neighbour +const FXAA_EDGE_RELATIVE: f32 = 0.125; + +/// How much a lone texel (subpixel aliasing) is blended into its neighbours at most +const FXAA_SUBPIXEL: f32 = 0.75; + +/// Luma of premultiplied texel components (a mask's value) +fn fxaa_luma(px: &[f32]) -> f32 { + match px { + [value] => *value, + [r, g, b, ..] => lum([*r, *g, *b]), + _ => 0.0, + } +} + +/// FXAA (the public luma-edge method) at texel `(x, y)` with components `center` into `acc`: read across its edge by how near the edge's end is +fn fxaa_texel((x, y): (f32, f32), comps: usize, center: &[f32], acc: &mut [f32; 5], sample: &dyn Fn(f32, f32, &mut [f32; 5])) { + let own = fxaa_luma(center); + + // Luma at an offset from the texel; off the UV island the texel's own, so seams are not edges + let luma = |dx: f32, dy: f32| { + let mut read = [0.0f32; 5]; + sample(x + dx, y + dy, &mut read); + if read[4] <= MIN_READ_WEIGHT { + return own; + } + + let mut px = [0.0f32; 4]; + for (slot, v) in px.iter_mut().zip(&read).take(comps.min(4)) { + *slot = v / read[4]; + } + fxaa_luma(&px[..comps.min(4)]) + }; + let (n, s, w, e) = (luma(0.0, -1.0), luma(0.0, 1.0), luma(-1.0, 0.0), luma(1.0, 0.0)); + let (hi, lo) = (own.max(n).max(s).max(w).max(e), own.min(n).min(s).min(w).min(e)); + let range = hi - lo; + if !range.is_finite() || range < FXAA_EDGE_MIN.max(hi * FXAA_EDGE_RELATIVE) { + return; + } + + let (nw, ne, sw, se) = (luma(-1.0, -1.0), luma(1.0, -1.0), luma(-1.0, 1.0), luma(1.0, 1.0)); + + // An edge running across (values changing down the rows) or down (values changing along them) + let across = 2.0 * (n - 2.0 * own + s).abs() + (nw - 2.0 * w + sw).abs() + (ne - 2.0 * e + se).abs(); + let down = 2.0 * (w - 2.0 * own + e).abs() + (nw - 2.0 * n + ne).abs() + (sw - 2.0 * s + se).abs(); + let horizontal = across >= down; + let (before, after) = if horizontal { (n, s) } else { (w, e) }; + let (sign, side) = if (before - own).abs() >= (after - own).abs() { (-1.0, before) } else { (1.0, after) }; + let (perp, along) = if horizontal { ([0.0, sign], [1.0, 0.0]) } else { ([sign, 0.0], [0.0, 1.0]) }; + + // Walk the edge's midline both ways until its luma leaves the edge's + let edge = 0.5 * (own + side); + let enough = 0.25 * (side - own).abs(); + let walk = |way: f32| { + let mut end = (FXAA_SEARCH as f32, 0.0); + for step in 1..=FXAA_SEARCH { + let t = step as f32 * way; + let delta = luma(perp[0] * 0.5 + along[0] * t, perp[1] * 0.5 + along[1] * t) - edge; + end = (step as f32, delta); + if delta.abs() >= enough { + break; + } + } + end + }; + let ((back, back_delta), (ahead, ahead_delta)) = (walk(-1.0), walk(1.0)); + let (nearest, delta) = if back < ahead { (back, back_delta) } else { (ahead, ahead_delta) }; + let edge_blend = if (delta < 0.0) != (own < edge) { 0.5 - nearest / (back + ahead) } else { 0.0 }; + + // A texel unlike all its neighbours blends in by its own contrast (sides weigh twice the corners) + let average = (2.0 * (n + s + w + e) + nw + ne + sw + se) / 12.0; + let contrast = ((average - own).abs() / range).clamp(0.0, 1.0); + let eased = crate::organic::smoothstep(0.0, 1.0, contrast); + let blend = edge_blend.max(eased * eased * FXAA_SUBPIXEL); + if blend > 0.0 { + sample(x + perp[0] * blend, y + perp[1] * blend, acc); + } +} + +/// Mirror `mirror` at texel `(x, y)` into `acc`: the texel it reads in its UV tile (`res` texels from its `block`'s top left), or white on a debug axis +fn mirror_texel( + mirror: &Mirror, + (x, y): (f32, f32), + (block, res): (u32, u32), + comps: usize, + alpha: Option<&f32>, + acc: &mut [f32; 5], + sample: &dyn Fn(f32, f32, &mut [f32; 5]), +) { + let (block, size) = (block.max(1) as f32, res.max(1) as f32); + let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); + let (local_x, local_y) = (x - origin_x, y - origin_y); + if local_x >= size || local_y >= size { + return; + } + + let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + let line = (Mirror::DEBUG_HALF_WIDTH * size / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size; + if mirror.debug && mirror.on_axis(uv, line) { + // Content stays premultiplied by its own coverage; masks are one value + let cover = if comps == 4 { alpha.copied().unwrap_or(0.0) } else { 1.0 }; + for slot in acc.iter_mut().take(comps) { + *slot = cover; + } + acc[4] = 1.0; + return; + } + + let [u, v] = mirror.source(uv); + + // Whole texels, so an even mirror copies texels exactly + let at = |origin: f32, along: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0); + sample(at(origin_x, u), at(origin_y, v), acc); +} + +/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`res` texels from its `block`'s top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty +fn transform_texel( + transform: &TileTransform, + (columns, shift): ([[f32; 2]; 2], [f32; 2]), + (x, y): (f32, f32), + (block, res): (u32, u32), + acc: &mut [f32; 5], + sample: &dyn Fn(f32, f32, &mut [f32; 5]), +) { + let (block, size) = (block.max(1) as f32, res.max(1) as f32); + let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); + let (local_x, local_y) = (x - origin_x, y - origin_y); + if local_x >= size || local_y >= size { + return; + } + + let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + + // Texel space of the tile, centres at whole numbers + let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size - 0.5); + if !at.iter().all(|a| a.is_finite()) { + return; + } + + let (base_x, base_y) = (at[0].floor(), at[1].floor()); + let (tx, ty) = (at[0] - base_x, at[1] - base_y); + let repeat = transform.repeat == RepeatMode::HorizontallyAndVertically; + let mut total = [0.0f32; 5]; + for (dx, dy, k) in [(0.0, 0.0, (1.0 - tx) * (1.0 - ty)), (1.0, 0.0, tx * (1.0 - ty)), (0.0, 1.0, (1.0 - tx) * ty), (1.0, 1.0, tx * ty)] { + if k <= 0.0 { + continue; + } + + let (cx, cy) = (base_x + dx, base_y + dy); + let inside = (0.0..size).contains(&cx) && (0.0..size).contains(&cy); + if !repeat && !inside { + // Empty: no value, full weight + total[4] += k; + continue; + } + + // One whole texel: the sample's own weights, so this matches its bilinear read + let mut one = [0.0f32; 5]; + sample(origin_x + cx.rem_euclid(size), origin_y + cy.rem_euclid(size), &mut one); + for (slot, value) in total.iter_mut().zip(one) { + *slot += value * k; + } + } + *acc = total; +} + /// Fixed-point scale of the blur. Integer running sums make a texel's result independent of /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; @@ -635,6 +1228,17 @@ fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel] plan(inp, &set.stack, &planned, tx, ty, 0, fields) } +/// [`anchor_plan`], or the plain set stack when `lit` (a layer lit by its material reads the stack below it too) +fn below_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], (tx, ty): (u32, u32), fields: Option<&'a Fields>, lit: bool) -> Vec> { + let anchors = anchor_plan(inp, id, channels, tx, ty, fields); + if !anchors.is_empty() || !lit { + return anchors; + } + + let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; + plan(inp, &set.stack, channels, tx, ty, 0, fields) +} + /// `channels` with every channel the Compare effects among `effects` compare added once fn compared_channels<'e>(effects: impl IntoIterator, mut channels: Vec) -> Vec { for effect in effects { @@ -700,12 +1304,20 @@ fn field( margins[index] += margins[index + 1]; } + // A wrapping filter reads across the set's edges, so it and every filter under it cover the whole set along an axis it crosses + let own_wraps: Vec = filters.iter().map(|filter| wraps(effects, filter.0)).collect(); + let mut wrapping = own_wraps.clone(); + for index in (0..wrapping.len().saturating_sub(1)).rev() { + wrapping[index] |= wrapping[index + 1]; + } + let mut previous: Option<(usize, Field)> = None; let mut anchor_stages = Vec::new(); - for (&filter, &margin) in filters.iter().zip(&margins) { - let region = region_around(inp, tiles, margin)?; + for (((&filter, &margin), &wrap), &own_wrap) in filters.iter().zip(&margins).zip(&wrapping).zip(&own_wraps) { + let region = region_around(inp, tiles, margin, wrap)?; let start = previous.as_ref().map(|(index, field)| (*index, field)); let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, region, start)?; + let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, own_wrap, region, start)?; // Preserve only stages with anchors before the next filter overwrites their value if let Some((previous_index, previous_field)) = previous.take() @@ -728,32 +1340,84 @@ fn 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)> { +/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set; with `wrap`, an axis the margin crosses an edge of spans the whole set (the filter reads the far side there) +fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32, wrap: bool) -> 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 axis = |first: u32, last: u32, size: u32| { + let end = last.saturating_add(1).saturating_add(margin).saturating_mul(TILE); + if wrap && (first < margin || end > size) { + return (0, size); + } + + (first.saturating_sub(margin).saturating_mul(TILE), end.min(size)) + }; + let ((x0, x1), (y0, y1)) = (axis(first_x, last_x, inp.gbuf.width), axis(first_y, last_y, 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. +/// Whether the neighbourhood filter at `index` among the visible effects reads past the set's edges from the far side +fn wraps(effects: &[Effect], index: usize) -> bool { + matches!( + effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| &effect.kind), + Some(EffectKind::Filter( + Filter::Blur { wrap: true, .. } + | Filter::Bevel { wrap: true, .. } + | Filter::DistanceBevel(Bevel { wrap: true, .. }) + | Filter::BevelSmooth(BevelSmooth { wrap: true, .. }) + )) + ) +} + +/// `data` (`w` × `h` texels of `comps` values) with `pad_x` and `pad_y` texels added around it, read from the opposite side +fn wrap_pad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (usize, usize)) -> Vec { + let (padded_w, padded_h) = (w + 2 * pad_x, h + 2 * pad_y); + let mut out = vec![0.0f32; padded_w * padded_h * comps]; + out.par_chunks_mut(padded_w * comps).enumerate().for_each(|(y, row)| { + let source_y = (y + h * pad_y.div_ceil(h.max(1)) - pad_y) % h.max(1); + for (x, pixel) in row.chunks_mut(comps).enumerate() { + let source_x = (x + w * pad_x.div_ceil(w.max(1)) - pad_x) % w.max(1); + let at = (source_y * w + source_x) * comps; + if let Some(source) = data.get(at..at + comps) { + pixel.copy_from_slice(source); + } + } + }); + out +} + +/// The `w` × `h` texels inside [`wrap_pad`]'s border +fn unpad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (usize, usize)) -> Vec { + let padded_w = w + 2 * pad_x; + (pad_y..pad_y + h).flat_map(|y| data.get((y * padded_w + pad_x) * comps..(y * padded_w + pad_x + w) * comps).unwrap_or_default()).copied().collect() +} + +/// 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) + + // A shadow also reads the shapes it was moved from + let moved = match op { + Op::Shadow { offset: [dx, dy] } => dx.unsigned_abs().max(dy.unsigned_abs()).min(longest_side), + _ => 0, + }; + (radius_texels, reach + moved) } -/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples). +/// One evaluated texel of a filter's region: its position, its premultiplied value and the gray its image input reads there +type RegionTexel = (u32, u32, [f32; 4], f32); + +/// 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(_)) + matches!(op, Op::Blur(_) | Op::HighPass { .. } | Op::Bevel | Op::Glow(_) | Op::PreBlur | Op::Halo | Op::Shadow { .. } | Op::Outline(_) | Op::Distance) } -/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. +/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given; `wrap` when the filter reads past the set's edges from the far side #[allow(clippy::too_many_arguments)] fn filter_region( inputs: &EvaluationInputs, @@ -763,6 +1427,7 @@ fn filter_region( job: Job, effects: &[Effect], (index, radius, op): (usize, f32, Op), + wrap: bool, (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { @@ -773,7 +1438,19 @@ fn filter_region( let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); let opacity = filter_effect.map(|effect| effect.blend_of(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); + let filter = filter_effect.and_then(|effect| match &effect.kind { + EffectKind::Filter(filter) => Some(filter), + _ => None, + }); + let opacity = filter_effect.map(|effect| effect.applied_blend(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + + // Height To Normal makes the Normal only (and reads the layer's Height as its gray); other channels pass + let heights = matches!(op, Op::HeightToNormal(_)) && channel == Some(Channel::Normal); + let opacity = if matches!(op, Op::HeightToNormal(_)) && !heights { 0.0 } else { opacity }; + + // Color Match moves colors only; other channels pass + let opacity = if matches!(op, Op::ColorMatch(_)) && channel.map(Channel::kind) != Some(ChannelKind::Color) { 0.0 } else { opacity }; + let (radius_texels, reach) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); // Generator stages keep their ramp beside the mask stack below let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) { @@ -786,15 +1463,24 @@ fn filter_region( Job::Content(_) => 4, }; - // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) + // The gray the filter's image input reads (its first; the filters that read one have one) + let input = filter_effect.zip(filter).and_then(|(effect, filter)| ImageInput::of(filter).first().map(|input| effect.input(input))); + + let lit_prefix = + channel == Some(Channel::BaseColor) && effects.iter().filter(|effect| effect.visible).take(index).any(|effect| lights_material(&effect.kind)); + + // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage), and its image input let (region_right, region_bottom) = (region_x + width, region_y + height); let region_tiles: Vec<(u32, u32)> = (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect(); - let parts: Vec> = region_tiles + let parts: Vec> = region_tiles .par_iter() .map(|&(tile_x, tile_y)| { - let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below)); + // A base colour lit by its material below the filter lights it as the full render does + let lit_layer = if lit_prefix { plan(inputs, &[id], channels, tile_x, tile_y, 0, Some(below)).into_iter().find(|node| node.lights) } else { None }; + let anchor_nodes = below_plan(inputs, id, channels, (tile_x, tile_y), Some(below), lit_layer.is_some()); let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); + let height_nodes = if heights { plan(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below)) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); let mut generator_sizes = None; @@ -824,6 +1510,9 @@ fn filter_region( if !anchor_nodes.is_empty() { texel.anchors_below(&anchor_nodes, id); } + if let Some(layer) = &lit_layer { + texel.light(layer); + } let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { @@ -836,7 +1525,22 @@ fn filter_region( }, (None, None) => [0.0; 4], }; - (x, y, value) + let gray = match height_nodes.first() { + // Heights are signed and premultiplied by their coverage, so an edge slopes down to 0 + Some(node) => { + let mut height = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + height.anchors_below(&anchor_nodes, id); + } + node.chans.first().and_then(|chan| height.content(&node.content, chan)).map_or(0.0, |(value, cov)| value[0] * cov) + } + None => { + let gray = + input.as_ref().map_or(1.0, |source| texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Scalar)[0]); + gray.clamp(0.0, 1.0) + } + }; + (x, y, value, gray) }) .collect() }) @@ -846,27 +1550,60 @@ fn filter_region( let texel_count = (width * height) as usize; let mut stack_values = vec![0.0f32; texel_count * components]; let mut cover = vec![0.0f32; texel_count]; + let mut grays = vec![0.0f32; texel_count]; let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize; let band = (TILE * width) as usize; - stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| { - for &(x, y, value) in row.iter().flatten() { - let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; - if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) { - *covered = 1.0; - pixel.copy_from_slice(&value[..components]); + stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(grays.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each( + |(((stack_values, cover), grays), row)| { + for &(x, y, value, gray) in row.iter().flatten() { + let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; + if let (Some(covered), Some(read), Some(pixel)) = + (cover.get_mut(texel), grays.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) + { + *covered = 1.0; + *read = gray; + pixel.copy_from_slice(&value[..components]); + } } - } - }); + }, + ); // Release tile scatter data before allocating filter buffers drop(parts); + // Color Match's Input and Image Input colors over the region, when its modes read them + let match_inputs = match (op, filter_effect) { + (Op::ColorMatch(matcher), Some(effect)) if opacity > 0.0 => { + let read = + |on: bool, input: ImageInput| on.then(|| input_colors(inputs, &effect.input(&input), ®ion_tiles, (region_x, region_y, width, height))); + [ + read(matcher.source_mode == SourceColorMode::Input, ImageInput::SOURCE_INPUT), + read(matcher.target_mode == TargetColorMode::ImageInput, ImageInput::TARGET_INPUT), + ] + } + _ => [None, None], + }; + // High pass centers on the channel's middle value (0 for signed channels like height) let middle = match job { Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; + // A Highpass in sRGB filters its colors encoded (decoded again below); one with Apply To Alpha keeps the colors on the new coverage + let (space, highpass_alpha) = match (op, job) { + (Op::HighPass { space, alpha }, Job::Content(channel)) if components == 4 => { + (if channel.kind() == ChannelKind::Color { space } else { HighpassSpace::Working }, alpha) + } + _ => (HighpassSpace::Working, false), + }; + let covered = highpass_alpha.then(|| stack_values.clone()); + recode(&mut stack_values, components, |rgb| space.encode(rgb)); + + // A wrapped axis pads by the reach up to one period (past it the far side repeats), so a set pads to 3x its size at most + let pad_x = if wrap && region_x == 0 && width == inputs.gbuf.width { reach.min(width) } else { 0 }; + let pad_y = if wrap && region_y == 0 && height == inputs.gbuf.height { reach.min(height) } else { 0 }; + // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1); @@ -875,43 +1612,92 @@ fn filter_region( return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); } - let scaled_radius = neighbourhood_filters(effects, tile_resolution) - .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, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity); + let scaled = neighbourhood_filters(effects, tile_resolution).find(|filter| filter.0 == index); + let scaled_radius = scaled.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); + if let Op::ColorMatch(matcher) = op { + let mut matched = stack_values.clone(); + color_match(&mut matched, components, &matcher, (&match_inputs[0], &match_inputs[1]), opacity); + return matched; } - // Weighted so uncovered texels don't bleed in - let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize); - let mut weights = cover.clone(); + if !is_box_blur(op) { + return gather( + op, + (&stack_values, &cover, &grays), + components, + (region_x, region_y, width, height), + scaled_radius as f32, + tile_resolution, + opacity, + ); + } + + // Weighted so uncovered texels don't bleed in; a wrapping filter reads a border copied from the far side + let pad = (pad_x as usize, pad_y as usize); + let unpadded = (width as usize, height as usize); + let (stack_values, cover, grays) = if pad == (0, 0) { + (Cow::Borrowed(&stack_values), Cow::Borrowed(&cover), Cow::Borrowed(&grays)) + } else { + let padded = |values: &[f32], components: usize| Cow::Owned(wrap_pad(values, components, unpadded, pad)); + (padded(&stack_values, components), padded(&cover, 1), padded(&grays, 1)) + }; + let (columns, rows, blur_radius) = (unpadded.0 + 2 * pad.0, unpadded.1 + 2 * pad.1, scaled_radius as usize); + if let (Some((_, _, scaled_op @ (Op::Halo | Op::Shadow { .. }))), Some(filter)) = (scaled, filter) { + let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); + let mut lit_values = stack_values.to_vec(); + halo(&mut lit_values, &cover, components, (columns, rows, blur_radius), (scaled_op, filter, kind), opacity); + return if pad == (0, 0) { lit_values } else { unpad(&lit_values, components, unpadded, pad) }; + } + + if let (Some((_, _, Op::Distance)), Some(filter)) = (scaled, filter) { + let mut distance_values = stack_values.to_vec(); + distance_filter(&mut distance_values, (&cover, &grays), components, (columns, rows), filter, tile_resolution, opacity); + return if pad == (0, 0) { distance_values } else { unpad(&distance_values, components, unpadded, pad) }; + } + + if let Some((_, _, Op::Outline(outline))) = scaled { + let mut outline_values = stack_values.to_vec(); + mask_outline(&mut outline_values, &cover, components, (columns, rows, blur_radius), &outline, opacity); + return if pad == (0, 0) { outline_values } else { unpad(&outline_values, components, unpadded, pad) }; + } + + // A pre-blur takes the blur whole; the effect's opacity mixes its mapped result below + let blurred_opacity = if matches!(op, Op::PreBlur) { 1.0 } else { opacity }; + let mut weights = cover.to_vec(); blur(&mut weights, columns, rows, blur_radius); - let mut filtered_values = stack_values.clone(); + let mut filtered_values = stack_values.to_vec(); for component in 0..components { let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); blur(&mut sums, columns, rows, blur_radius); filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { // Content is premultiplied, so the middle value is too (coverage itself is kept) let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *weight > MIN_COVERAGE_WEIGHT + if *weight > MIN_READ_WEIGHT && let Some(slot) = pixel.get_mut(component) { 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 + middle * coverage, + Op::HighPass { .. } if component < 3 => original - blurred + middle * coverage, + Op::HighPass { alpha: true, .. } => (original - blurred + 0.5).clamp(0.0, 1.0), // 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, + Op::HighPass { .. } | Op::Bevel | Op::Glow(_) => original, _ => blurred, }; - *slot = original + (result - original) * opacity; + *slot = original + (result - original) * blurred_opacity; } }); } - filtered_values + if matches!(op, Op::PreBlur) + && let Some(filter) = filter + { + let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); + map_blurred(&mut filtered_values, &stack_values, components, filter, kind, opacity); + } + if pad == (0, 0) { filtered_values } else { unpad(&filtered_values, components, unpadded, pad) } }; // Each block keeps the result at its tile's scale (blocks are TILE aligned) @@ -940,6 +1726,11 @@ fn filter_region( }); } + // Laid on the new coverage first, so the decode divides by the alpha the colours now carry + if let Some(before) = covered { + recover(&mut result, &before, middle); + } + recode(&mut result, field_components, |rgb| space.decode(rgb)); unpremultiply(&mut result, field_components); Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } @@ -970,7 +1761,7 @@ fn generator_region( let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); blur(&mut sums, columns, rows, blur_radius); ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_COVERAGE_WEIGHT { + if *weight > MIN_READ_WEIGHT { *ramp = sum / weight; } }); @@ -1012,7 +1803,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, } } } - sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight)) + sums.into_iter().map(|(sum, weight)| (weight > MIN_READ_WEIGHT).then(|| sum / weight)) }) .collect(); let average = |column: isize, row: isize| -> Option { @@ -1042,7 +1833,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, Some(value) => (sum + value * corner_weight, weight + corner_weight), None => (sum, weight), }); - if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } + if weight > MIN_READ_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } }) .collect() } @@ -1055,6 +1846,175 @@ fn finish_generator(generator: &Generator, ramp: f32) -> f32 { (value + offset).clamp(0.0, 1.0) } +/// Straight colours a colour space map must leave alone to be the identity +const IDENTITY_PROBE: [f32; 3] = [0.25, 0.5, 0.75]; + +/// Premultiplied content `data` (four components a texel) with each straight color mapped by `map` (nothing for masks or an identity space) +fn recode(data: &mut [f32], comps: usize, map: impl Fn([f32; 3]) -> [f32; 3] + Sync) { + if comps != 4 || map(IDENTITY_PROBE) == IDENTITY_PROBE { + return; + } + + data.par_chunks_mut(4).for_each(|pixel| { + if let [r, g, b, a] = pixel + && *a > MIN_READ_WEIGHT + { + let mapped = map([*r / *a, *g / *a, *b / *a]); + [*r, *g, *b] = mapped.map(|component| component * *a); + } + }); +} + +/// Premultiplied content `data` whose coverage a Highpass changed: its colors laid on the new coverage (mid gray where there was none, as `before`) +fn recover(data: &mut [f32], before: &[f32], mid: f32) { + data.par_chunks_mut(4).zip(before.par_chunks(4)).for_each(|(pixel, old)| { + let (Some(&own), Some(&new)) = (old.get(3), pixel.get(3)) else { return }; + let scale = if own > MIN_READ_WEIGHT { new / own } else { 0.0 }; + for component in pixel.iter_mut().take(3) { + *component = if own > MIN_READ_WEIGHT { *component * scale } else { mid * new }; + } + }); +} + +/// Below this cover a texel is empty and has no straight colour +pub(crate) const MIN_ALPHA: f32 = 1e-5; + +/// The blurred value a precise halo is solid from +const PRECISE_EDGE: f32 = 0.5; + +/// How soft a full spread leaves a halo: its least hardness +const HALO_SOFTEST: f32 = 0.01; + +/// The shapes' blurred share at their edge +const OUTLINE_EDGE_SHARE: f32 = 0.5; + +/// Lay halo glow or drop shadow `filter` (`op` its move) over premultiplied `data` in the tint of a channel of `kind`, mixed in by `opacity` +fn halo( + data: &mut [f32], + cover: &[f32], + comps: usize, + (width, height, radius): (usize, usize, usize), + (op, filter, kind): (Op, &Filter, ChannelKind), + opacity: f32, +) { + let (inner, precise, spread, strength, color, mask_white) = match *filter { + Filter::HaloGlow { on_mask, precise, width, spread, opacity, color } => (width < 0.0, precise, spread, opacity, color, on_mask), + Filter::DropShadow { spread, opacity, color, .. } => (false, false, spread, opacity, color, true), + _ => return, + }; + + // Rec. 709 luminance, unlike `lum`'s weights on purpose + let luminance = 0.2126 * color[0] + 0.7152 * color[1] + 0.0722 * color[2]; + let tint = match (comps, kind) { + (4, ChannelKind::Color) => color, + (4, _) => [luminance; 3], + _ if mask_white => [1.0; 3], + _ => [luminance; 3], + }; + + // The shapes: the content's coverage or the mask's value (the outside of them for an inner glow) + let shape = |texel: usize| { + let value = data.get(texel * comps + comps - 1).copied().unwrap_or(0.0); + let value = if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; + if inner { 1.0 - value } else { value } + }; + let offset = match op { + Op::Shadow { offset } => offset, + _ => [0, 0], + }; + let moved = |texel: usize| -> Option { + let (x, y) = ((texel % width.max(1)) as i64 - i64::from(offset[0]), (texel / width.max(1)) as i64 - i64::from(offset[1])); + (x >= 0 && y >= 0 && (x as usize) < width && (y as usize) < height).then(|| y as usize * width + x as usize) + }; + let texels = width * height; + let mut weights: Vec = (0..texels).map(|texel| moved(texel).and_then(|from| cover.get(from).copied()).unwrap_or(0.0)).collect(); + let mut sums: Vec = (0..texels).map(|texel| moved(texel).map_or(0.0, |from| shape(from) * cover.get(from).copied().unwrap_or(0.0))).collect(); + blur(&mut weights, width, height, radius); + blur(&mut sums, width, height, radius); + + let hardness = (1.0 - spread.clamp(0.0, 1.0)).max(HALO_SOFTEST); + let strength = strength.clamp(0.0, 1.0); + data.par_chunks_mut(comps).zip(sums.par_iter().zip(weights.par_iter())).for_each(|(pixel, (sum, weight))| { + let blurred = if *weight > MIN_READ_WEIGHT { (sum / weight).clamp(0.0, 1.0) } else { 0.0 }; + let shaped = if precise { crate::organic::smoothstep(0.0, PRECISE_EDGE, blurred) } else { blurred }; + let glow = (shaped / hardness).min(1.0) * strength; + let cov = pixel.last().copied().unwrap_or(0.0).clamp(0.0, 1.0); + let mut before = [0.0f32; 4]; + for (was, value) in before.iter_mut().zip(pixel.iter()) { + *was = *value; + } + if inner { + // Inside the shapes, towards the tint (content premultiplied by its coverage) + let weight = if comps == 4 { glow } else { glow * cov }; + for (slot, tint) in pixel.iter_mut().zip(tint).take(comps.min(3)) { + let target = if comps == 4 { tint * cov } else { tint }; + *slot += (target - *slot) * weight; + } + } else { + // Under the shapes: it shows where they leave room + let under = glow * (1.0 - cov); + for (slot, tint) in pixel.iter_mut().zip(tint).take(comps.min(3)) { + *slot += tint * under; + } + if comps == 4 + && let Some(alpha) = pixel.get_mut(3) + { + *alpha += under; + } + } + for (slot, was) in pixel.iter_mut().zip(before) { + *slot = was + (*slot - was) * opacity; + } + }); +} + +/// Lay Mask Outline `outline` over premultiplied `data` (shapes of content from its luminance), mixed in by `opacity` +fn mask_outline(data: &mut [f32], cover: &[f32], comps: usize, (width, height, radius): (usize, usize, usize), outline: &MaskOutline, opacity: f32) { + let value = |pixel: &[f32]| match pixel { + [r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]), + [value] => *value, + _ => 0.0, + }; + let inside: Vec = data.par_chunks(comps).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && outline.inside(value(pixel))).collect(); + let fade_curve = outline.fade_curve(); + let mut weights = cover.to_vec(); + let mut sums: Vec = inside.par_iter().zip(cover.par_iter()).map(|(inside, covered)| if *inside { *covered } else { 0.0 }).collect(); + blur(&mut weights, width, height, radius); + blur(&mut sums, width, height, radius); + data.par_chunks_mut(comps).zip(inside.par_iter()).zip(sums.par_iter().zip(weights.par_iter())).for_each(|((pixel, inside), (sum, weight))| { + // The shapes' share around a texel is a half at their edge and none (outside) or all (inside) past the band + let share = if *weight > MIN_READ_WEIGHT { (sum / weight).clamp(0.0, 1.0) } else { 0.0 }; + let closeness = if *inside { (1.0 - share) / OUTLINE_EDGE_SHARE } else { share / OUTLINE_EDGE_SHARE }; + let band = outline.band(fade_curve, *inside, closeness); + + // Content is premultiplied by its coverage, which stays + let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + for slot in pixel.iter_mut().take(comps.min(3)) { + let before = if comps == 4 { if cov > MIN_ALPHA { *slot / cov } else { 0.0 } } else { *slot }; + let result = outline.apply(before, band); + *slot = (before + (result - before) * opacity) * cov; + } + }); +} + +/// Run point filter `filter` on blurred texels `data` (premultiplied content or masks) and mix the result over the unblurred `orig` by `opacity` +fn map_blurred(data: &mut [f32], orig: &[f32], comps: usize, filter: &Filter, kind: ChannelKind, opacity: f32) { + let straight = |value: f32, cover: f32| if cover > MIN_ALPHA { value / cover } else { 0.0 }; + data.par_chunks_mut(comps).zip(orig.par_chunks(comps)).for_each(|(pixel, original)| match (pixel, original) { + ([value], [before]) => { + let mapped = filter.point(kind, [*value; 3]).map_or(*value, |gray| gray[0]); + *value = before + (mapped - before) * opacity; + } + ([r, g, b, cover], [r0, g0, b0, cover0]) => { + let before = [straight(*r0, *cover0), straight(*g0, *cover0), straight(*b0, *cover0)]; + let blurred = [straight(*r, *cover), straight(*g, *cover), straight(*b, *cover)]; + let mixed = mix3(before, filter.point(kind, blurred).unwrap_or(before), opacity); + [*r, *g, *b, *cover] = [mixed[0] * cover0, mixed[1] * cover0, mixed[2] * cover0, *cover0]; + } + _ => {} + }); +} + /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. fn unpremultiply(data: &mut [f32], comps: usize) { // Avoid amplifying rounding error near transparent texels @@ -1176,6 +2136,8 @@ struct Node<'a> { anchors: Vec<(LayerId, Option)>, /// The node or one of its children records an anchor has_anchor: bool, + /// Its base colour has an effect lit by the layer's material (see [`lights_material`]) + lights: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). parts: Option>, @@ -1210,6 +2172,15 @@ fn effect_plans<'a>( _ => (None, false), }; let blend = effect.blend_of(channel); + let environment = match &effect.kind { + EffectKind::Filter(Filter::EnvironmentLighting { .. }) => Some(EnvironmentSh::of(&inp.project.display, inp.images)), + _ => None, + }; + let stylized = match &effect.kind { + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => filter.stylized_lighting().map(|(settings, light)| settings.shading(light)), + _ => None, + }; + let blend = effect.applied_blend(channel); EffectPlan { id: effect.id, kind: offset_effect(&effect.kind, around), @@ -1221,6 +2192,12 @@ fn effect_plans<'a>( filtered_mask: None, depth, covers_all, + environment, + stylized, + input: match &effect.kind { + EffectKind::Filter(filter) if !filter.is_neighbourhood() => ImageInput::of(filter).first().map(|input| effect.input(input)), + _ => None, + }, } }) .collect() @@ -1370,10 +2347,21 @@ fn plan_node<'a>( let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() }; let has_anchor = !anchors.is_empty() || mask_anchor || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); + let base = Channel::BaseColor.index(); + let lights = chans.iter().any(|chan_plan| chan_plan.ch == base && chan_plan.effects.iter().any(|effect| lights_material(&effect.kind))); // The geometry mask is the layer's own (an instance in another set has other parts) let parts = own.geometry_mask.as_ref().map(|names| inp.mesh.submeshes.iter().map(|s| names.contains(&s.name)).collect()); - Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask, parts }) + Some(Node { id, content, chans, mask, anchors, has_anchor, lights, height_mask: layer.height_mask, parts }) +} + +/// Whether a base colour effect reads the layer's other channels as its material: Baked Lighting Stylized's highlights, Environment Lighting, PBR Validate's metal +fn lights_material(kind: &EffectKind) -> bool { + match kind { + EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => filter.stylized_lighting().is_some_and(|(stylized, _)| stylized.output.specular()), + EffectKind::Filter(Filter::EnvironmentLighting { .. } | Filter::PbrValidate(_)) => true, + _ => false, + } } /// The content of `layer` (layer `id`'s own, or its instance source's; None for an unfollowed instance) and its plan per drawn channel of `channels`, its fills under the Scale and Rotation `around` of the folders holding `id`; a folder's children are planned when `kids` @@ -1525,6 +2513,8 @@ struct Texel<'a, 'b> { anchors: Vec<(LayerId, Acc, bool)>, /// The stack below the layer whose mask compares its channels (recorded by `eval` there, or where it stops) below: Option, + /// The material Baked Lighting Stylized reads its highlights from: the stack with the layer it lights (its other channels) laid on + lit: Option, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip @@ -1559,9 +2549,13 @@ impl<'t> Tape<'t> { } } +/// Each channel's content (value and coverage) where the layer has one +type ChannelContents = [Option<([f32; 3], f32)>; NCH]; + impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, tape: Tape::Off, copy: None } + Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, lit: None, tape: Tape::Off, copy: None } } /// Run `f` with `tape` as this texel's tape. @@ -1751,6 +2745,41 @@ impl<'a, 'b> Texel<'a, 'b> { (value.map(|v| v / cover), cover) } + /// The normal Baked Lighting Stylized lights: the mesh's (no `relief`), or (Mesh + Height + Normal) its [`Texel::detail_normal`] at `relief` + fn lit_normal(&mut self, relief: Option) -> [f32; 3] { + match relief { + Some(relief) => self.detail_normal(relief), + None => self.coords().nrm.to_array(), + } + } + + /// The baked world normal (the mesh's without one) tilted by the baked height's slope times `relief` + fn detail_normal(&mut self, relief: f32) -> [f32; 3] { + let mesh = self.coords().nrm; + let detail = self + .baked_color(BakedMap::WorldNormal) + .map(|packed| Vec3::from(packed) * 2.0 - Vec3::ONE) + .filter(|n| n.length_squared() > MIN_NORMAL_LENGTH_SQUARED); + let nrm = detail.map_or(mesh, Vec3::normalize); + let i = (self.y * self.inp.gbuf.width + self.x) as usize; + let (Some(surface), Some(slope)) = (self.surface(i), self.height_slope()) else { return nrm.to_array() }; + let tangent = surface.tangent.truncate(); + let bitangent = nrm.cross(tangent) * surface.tangent.w; + let tilted = nrm - (tangent * slope[0] + bitangent * slope[1]) * HEIGHT_RELIEF * relief; + tilted.try_normalize().unwrap_or(nrm).to_array() + } + + /// The baked height's change per UV unit along U and V at this texel (central differences); None without a height bake + fn height_slope(&self) -> Option<[f32; 2]> { + let (width, height) = (self.res, self.inp.gbuf.height); + let at = |x: u32, y: u32| self.inp.baked.sample_working(BakedMap::Height, x, y, (width, height), &self.inp.block_scales).map(|h| h[0]); + let (left, right) = (self.x.saturating_sub(1), (self.x + 1).min(width.saturating_sub(1))); + let (up, down) = (self.y.saturating_sub(1), (self.y + 1).min(height.saturating_sub(1))); + let du = (at(right, self.y)? - at(left, self.y)?) / (right - left).max(1) as f32 * width as f32; + let dv = (at(self.x, down)? - at(self.x, up)?) / (down - up).max(1) as f32 * height as f32; + Some([du, dv]).filter(|slope| slope.iter().all(|s| s.is_finite())) + } + fn baked(&self, m: BakedMap) -> Option { self.baked_color(m).map(|value| value[0]) } @@ -2131,6 +3160,17 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, generated) - value) * opacity; } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { + let ramp = filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map_or(value, lum); + value += (ramp - value) * opacity; + } + EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { + let read = match &effect.input { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color), + None => [value; 3], + }; + value += (conversion.gray(read, 1.0) - 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]); @@ -2209,13 +3249,19 @@ impl<'a, 'b> Texel<'a, 'b> { } Content::Fill { .. } | Content::Paint { .. } if mask > 0.0 => { let before = if node.anchors.iter().any(|(_, cut)| cut.is_some()) { Some(*acc) } else { None }; - for chan_plan in &node.chans { - if let Some((value, coverage)) = self.tape_content(&node.content, chan_plan) { - apply(acc, chan_plan, value, coverage, mask); + // A layer lit by its material evaluates its other channels first (see `Texel::lit_content`) + if node.lights { + self.lit_content(node, acc, mask); + } else { + self.lit = None; + for chan_plan in &node.chans { + if let Some((value, coverage)) = self.tape_content(&node.content, chan_plan) { + apply(acc, chan_plan, value, coverage, mask); + } } } - // Anchors inside the content stack read the stack cut at that point + // Anchors inside the content stack read the stack cut at that point, lit by the same material for (anchor, cut) in &node.anchors { let recorded = match (cut, before) { (Some(cut), Some(mut cut_acc)) => { @@ -2230,6 +3276,7 @@ impl<'a, 'b> Texel<'a, 'b> { }; self.anchors.push((*anchor, recorded, false)); } + self.lit = None; continue; } _ => {} @@ -2241,6 +3288,48 @@ impl<'a, 'b> Texel<'a, 'b> { false } + /// Lay a layer lit by its material over `acc` under `mask`: its other channels go first, each evaluated once, and `self.lit` holds them over the stack below for its base colour's lighting + #[inline(never)] + fn lit_content(&mut self, node: &Node, acc: &mut Acc, mask: f32) { + let base = Channel::BaseColor.index(); + let (material, others) = self.material(node, *acc, mask); + self.lit = Some(material); + + for chan_plan in &node.chans { + let content = match others.get(chan_plan.ch) { + Some(other) if chan_plan.ch != base => *other, + _ => self.tape_content(&node.content, chan_plan), + }; + if let Some((value, coverage)) = content { + apply(acc, chan_plan, value, coverage, mask); + } + } + } + + /// Layer `node`'s other channels than its base colour laid over `below` under `mask`, and each one's content + fn material(&mut self, node: &Node, below: Acc, mask: f32) -> (Acc, ChannelContents) { + let base = Channel::BaseColor.index(); + let mut others = [None; NCH]; + let mut material = below; + for chan_plan in node.chans.iter().filter(|chan_plan| chan_plan.ch != base) { + let content = self.tape_content(&node.content, chan_plan); + if let Some((value, coverage)) = content { + apply(&mut material, chan_plan, value, coverage, mask); + } + if let Some(slot) = others.get_mut(chan_plan.ch) { + *slot = content; + } + } + (material, others) + } + + /// Light layer `node`'s base colour as the full render does, after [`Texel::anchors_below`] recorded the stack below it + fn light(&mut self, node: &Node) { + let below = self.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + let mask = self.node_mask(node); + self.lit = Some(self.material(node, below, mask).0); + } + /// [`Texel::eval`] of the whole stack over `acc`, split along the path to the hot layer /// (`levels`, top level first). Cold (`warm` false) it evaluates everything, leaving in /// `accs` the stack before the path layer of each level and recording on `tape` the masks @@ -2458,11 +3547,69 @@ impl<'a, 'b> Texel<'a, 'b> { EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); - let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) + let lit = match &effect.stylized { + Some(stylized) => { + let nrm = self.lit_normal(stylized.relief()); + let curvature = self.baked(BakedMap::Curvature).unwrap_or(FLAT_CURVATURE); + let material = self.lit.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + stylized.shade(value, nrm, [ao, curvature], &material) + } + None => { + let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); + value.map(|x| (x * factor).clamp(0.0, 1.0)) + } + }; + (mix3(value, lit, opacity), coverage) } _ => (value, coverage), }, + // Environment lighting reads the texel's normal, occlusion and metal, and lights the base color only + EffectKind::Filter(Filter::EnvironmentLighting { horizontal, vertical, exposure, height_intensity, ambient_occlusion, specular_occlusion }) => { + match (Channel::ALL.get(chan_plan.ch), &effect.environment) { + (Some(Channel::BaseColor), Some(environment)) => { + let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); + let nrm = Vec3::from(self.detail_normal(height_intensity / ENVIRONMENT_HEIGHT_UNIT)); + let light = environment.irradiance(nrm, horizontal.to_radians(), vertical.to_radians()) + * exposure.clamp(-Filter::ENVIRONMENT_EXPOSURE_STOPS, Filter::ENVIRONMENT_EXPOSURE_STOPS).exp2(); + let material = self.lit.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + let lit = EnvironmentSh::shade(value, light, ao, [*ambient_occlusion, *specular_occlusion], &material); + (mix3(value, lit, opacity), coverage) + } + _ => (value, coverage), + } + } + + // PBR Validate checks the base color against the layer's metal and leaves the other channels as they are + EffectKind::Filter(Filter::PbrValidate(validate)) => match Channel::ALL.get(chan_plan.ch) { + Some(Channel::BaseColor) => { + let metal = self.lit.and_then(|material| material.get(Channel::Metallic.index()).map(|metal| metal[0])).unwrap_or(0.0); + (mix3(value, validate.check(value, metal), opacity), coverage) + } + _ => (value, coverage), + }, + // A gradient's debug view shows its ramp left to right across each UV tile + EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { + let ramp = + filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map(|color| if chan_plan.kind == ChannelKind::Color { color } else { [lum(color); 3] }); + (ramp.map_or(value, |ramp| mix3(value, ramp, opacity)), coverage) + } + + // Posterize with Apply to Alpha steps the content's coverage too + EffectKind::Filter(filter @ Filter::Posterize { levels, alpha: true }) => { + let stepped = coverage + (posterize(coverage, *levels) - coverage) * opacity; + (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), stepped) + } + + // Grayscale Conversion weighs the coverage as Alpha, or reads its Custom Input + EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { + let (custom_input, alpha) = match &effect.input { + Some(source) => (Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color)), 1.0), + None => (None, coverage), + }; + (mix3(value, conversion.channel_value(chan_plan.kind, value, custom_input, alpha), opacity), coverage) + } + // Neighbourhood filters come precomputed through `ChanPlan::start` EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), // Anchors are recorded by `eval`; mask-only effects leave content as it is @@ -3410,7 +4557,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti .map(|&(tx, ty)| { let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); let Some(n) = nodes.first() else { return Vec::new() }; - let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields)); + let full = below_plan(&visible_inputs, id, &channels, (tx, ty), Some(&fields), n.lights); let mut buffers: Vec<(Channel, Vec, bool)> = n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); for (ch, buffer, _) in &mut buffers { @@ -3426,6 +4573,9 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti if !full.is_empty() { tex.anchors_below(&full, id); } + if n.lights { + tex.light(n); + } let m = tex.node_mask(n); for (c, (ch, buffer, any)) in n.chans.iter().zip(buffers.iter_mut()) { let Some((v, cov)) = tex.content(&n.content, c) else { continue }; @@ -3457,6 +4607,9 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti mod tests { use super::*; use texturecraft_core::{ChannelBlend, CompareOp, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; + use texturecraft_core::{ + ChannelBlend, CompareOp, Effect, Layer, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, TextureSet, + }; use texturecraft_geom::primitives; struct Fixture { @@ -3611,7 +4764,7 @@ mod tests { let layer = fill_layer(&mut fixture.project, [color; 3], 0.5); let mut mask = Mask::new(MaskBackground::White); for radius in [8.0, 4.0, 2.0] { - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius, wrap: false }))); if record_anchors && radius != 2.0 { mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Anchor)); } @@ -3922,10 +5075,9 @@ mod tests { 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 }] { + for filter in [Filter::Blur { radius: 64.0, wrap: false }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }] { 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); @@ -3942,7 +5094,7 @@ mod tests { 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], ramp: Vec::new() }; - let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }; let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let mut masked = |filters: &[Filter]| { let mut mask = Mask::new(MaskBackground::Black); @@ -3958,7 +5110,7 @@ mod tests { }; let warped = masked(std::slice::from_ref(&warp)); - let blurred_then_warped = masked(&[Filter::Blur { radius: 64.0 }, warp]); + let blurred_then_warped = masked(&[Filter::Blur { radius: 64.0, wrap: false }, 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"); } @@ -3973,7 +5125,7 @@ mod tests { Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, ); - let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }; let warp_effect = content_fx(&mut fixture, layer, EffectKind::Filter(warp)); let row = |fixture: &Fixture| -> Vec { let composite = run(fixture, None); @@ -3981,7 +5133,7 @@ mod tests { }; let warped = row(&fixture); - content_fx(&mut fixture, layer, EffectKind::Filter(Filter::Blur { radius: 64.0 })); + content_fx(&mut fixture, layer, EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false })); 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); @@ -4199,20 +5351,14 @@ mod tests { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); assert!(!stack_reads_neighbours(&f.project, 0)); - let mut mask = Mask::new(MaskBackground::White); let eid = f.project.alloc_id(); - mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); + mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); - assert!(stack_reads_neighbours(&f.project, 0)); - f.project.layer_mut(id).unwrap().mask = None; - assert!(!stack_reads_neighbours(&f.project, 0)); - - content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0 })); - + content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0, alpha: true })); assert!(stack_reads_neighbours(&f.project, 0)); } @@ -4233,7 +5379,7 @@ mod tests { )); f.project.layer_mut(id).unwrap().mask = Some(mask.clone()); let hard: Vec = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect(); - mask.effects.push(Effect::new(e2, EffectKind::Filter(Filter::Blur { radius: 64.0 }))); + mask.effects.push(Effect::new(e2, EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); let soft_img = run(&f, None); let soft: Vec = (0..64).map(|x| soft_img.value(Channel::BaseColor, x, 20)[0]).collect(); @@ -4288,7 +5434,7 @@ soft {soft:?}" fn content_filters_hsl_and_opacity_change_layer_values() { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); - content_fx(&mut f, id, EffectKind::Filter(Filter::Hsl { hue: 1.0 / 3.0, saturation: 0.0, lightness: 0.0 })); + content_fx(&mut f, id, EffectKind::Filter(Filter::Hsl { hue: 1.0 / 3.0, saturation: 0.0, lightness: 0.0, perceptive: false })); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 5, 5), [0.0, 1.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 5, 5)); assert!(close(out.value(Channel::Roughness, 5, 5), [0.2; 3]), "a hue shift leaves scalars alone"); @@ -4307,14 +5453,85 @@ soft {soft:?}" assert!(close(out.value(Channel::Roughness, 5, 5), [0.5; 3])); } + /// Posterize steps a paint layer's coverage only with Apply to Alpha + #[test] + fn posterize_steps_the_coverage_when_it_applies_to_alpha() { + let mut f = fixture(); + let id = f.project.alloc_id(); + let l = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]); + f.project.insert_layer(0, l, None, false).unwrap(); + + // Half-covered red over the default mid gray + f.pixels.layer_mut(id, Channel::BaseColor, (64, 64)).set(3, 3, &[to_u16(0.5), 0, 0, to_u16(0.5)]); + let posterize = content_fx(&mut f, id, EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: false })); + assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [0.75, 0.25, 0.25]), "the coverage stays as it is"); + f.project.effect_mut(posterize).unwrap().kind = EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: true }); + assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [1.0, 0.0, 0.0]), "half coverage rounds up to whole"); + } + + /// A paint layer with base color texels set by `paint` (x, y -> Some(linear color, coverage)) + fn painted(f: &mut Fixture, paint: impl Fn(u32, u32) -> Option<([f32; 3], f32)>) -> LayerId { + let id = f.project.alloc_id(); + let l = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]); + f.project.insert_layer(0, l, None, false).unwrap(); + let tile = f.pixels.layer_mut(id, Channel::BaseColor, (64, 64)); + for (x, y) in (0..64).flat_map(|y| (0..64).map(move |x| (x, y))) { + if let Some((color, cover)) = paint(x, y) { + tile.set(x, y, &[to_u16(color[0] * cover), to_u16(color[1] * cover), to_u16(color[2] * cover), to_u16(cover)]); + } + } + id + } + + /// Pixelate steps the coverage into its cells only with Apply To Alpha; off, each texel keeps its own + #[test] + fn pixelate_keeps_each_texels_coverage_without_apply_to_alpha() { + let mut f = fixture(); + + // One red texel in a cell of 4 × 4 texels (128 texels at 2K at 64 across), whose center reads it a quarter + let id = painted(&mut f, |x, y| ((x, y) == (1, 1)).then_some(([1.0, 0.0, 0.0], 1.0))); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 128.0, alpha: true })); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 1, 1), [0.625, 0.375, 0.375]), "the cell's coverage: {:?}", out.value(Channel::BaseColor, 1, 1)); + assert!(close(out.value(Channel::BaseColor, 2, 2), [0.625, 0.375, 0.375]), "spread over the cell"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Mosaic { size: 128.0, alpha: false }); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 1, 1), [1.0, 0.0, 0.0]), "the texel keeps its whole coverage"); + assert!(close(out.value(Channel::BaseColor, 2, 2), [0.5; 3]), "an uncovered texel stays uncovered"); + } + + /// FXAA blends a stair-stepped edge and leaves flat areas; the coverage only with Affect Alpha Channel + #[test] + fn fxaa_smooths_stair_steps() { + let stairs = |x: u32, y: u32| x >= 20 + y / 4; + let mids = |out: &Composite| (0..64 * 64).filter(|i| (0.05..0.95).contains(&out.value(Channel::BaseColor, i % 64, i / 64)[0])).count(); + + // Black and white, both covered: the edge gets in-between values + let mut f = fixture(); + let id = painted(&mut f, |x, y| Some((if stairs(x, y) { [1.0; 3] } else { [0.0; 3] }, 1.0))); + assert_eq!(mids(&run(&f, None)), 0); + content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); + let out = run(&f, None); + assert!(mids(&out) > 16, "{} texels blended", mids(&out)); + assert!(close(out.value(Channel::BaseColor, 2, 30), [0.0; 3]) && close(out.value(Channel::BaseColor, 60, 30), [1.0; 3]), "flat areas stay"); + + // White shapes on nothing: the coverage changes only with Affect Alpha Channel + let mut f = fixture(); + let id = painted(&mut f, |x, y| stairs(x, y).then_some(([1.0; 3], 1.0))); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); + let plain = |out: &Composite| (0..64 * 64).all(|i| [0.5, 1.0].iter().any(|v| (out.value(Channel::BaseColor, i % 64, i / 64)[0] - v).abs() < 2e-4)); + assert!(plain(&run(&f, None)), "each texel keeps its coverage"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Fxaa { alpha: true }); + assert!(!plain(&run(&f, None)), "the coverage is smoothed"); + } + #[test] fn hsl_on_a_mask_changes_its_lightness() { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); let mut mask = Mask::new(MaskBackground::White); - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5 }))); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5, perceptive: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.75; 3])); } @@ -4333,19 +5550,142 @@ soft {soft:?}" (0..64).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>() }; let hard = row(&f); - content_fx(&mut f, id, EffectKind::Filter(Filter::Blur { radius: 64.0 })); + content_fx(&mut f, id, EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false })); let soft = row(&f); let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.05 && **x < 0.95).count(); assert!(mids(&soft) > mids(&hard) + 4, "hard {hard:?}\nsoft {soft:?}"); assert!(soft.iter().all(|v| (0.0..=1.0).contains(v))); } + /// A fill layer of a black and white checker on Roughness, under `filter` when given + fn checker_roughness(fixture: &mut Fixture, filter: Option) { + let id = fixture.project.alloc_id(); + let mut fill = Fill::default(); + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; + fill.sources.insert(Channel::Roughness, checker); + fixture.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap(); + if let Some(filter) = filter { + content_fx(fixture, id, EffectKind::Filter(filter)); + } + } + + #[test] + fn a_wrapping_blur_reads_the_far_side_of_the_texture() { + let row = |wrap: Option| { + let mut f = fixture(); + checker_roughness(&mut f, wrap.map(|wrap| Filter::Blur { radius: 96.0, wrap })); + let out = run(&f, None); + (0..64).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>() + }; + + // The checker tiles: its period P repeats across the whole row + let hard = row(None); + let period = (1..64).find(|&p| (0..64 - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= 32, "{hard:?}"); + + // Wrapped, the blur at the texture's edge sees the far side, so the result keeps tiling; clipped, the edge differs + let wrapped = row(Some(true)); + assert!((0..64 - period).all(|x| (wrapped[x] - wrapped[x + period]).abs() < 0.02), "{wrapped:?}"); + let clipped = row(Some(false)); + assert!((clipped[0] - clipped[period]).abs() > 0.05, "{clipped:?}"); + assert!((12..52).all(|x| (clipped[x] - wrapped[x]).abs() < 0.02), "away from the edges, wrap changes nothing"); + } + + /// A set several tiles wide: a tile at its edge composited alone reads the far side as the whole set does, so the result keeps tiling across the edge + #[test] + fn a_wrapping_filter_reads_the_far_side_of_a_set_several_tiles_wide() { + const WIDTH: u32 = 256; + const HEIGHT: u32 = 64; + let row_of = |out: &Composite| (0..WIDTH).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>(); + let composite = |filter: Option<&Filter>, tiles: &[(u32, u32)]| { + let mut f = fixture(); + f.gbuf = UvGBuffer::new(&f.mesh, 0, WIDTH, HEIGHT); + f.project.texture_sets[0].resolution = WIDTH; + checker_roughness(&mut f, filter.cloned()); + let images = ImageStore::default(); + let mut out = Composite::with_size(&f.project.texture_sets[0].channel_list(), WIDTH, HEIGHT); + composite_tiles(&inputs(&f, &images, None), &mut out, tiles); + row_of(&out) + }; + let hard = composite(None, &all_tiles(WIDTH, HEIGHT)); + let period = (1..WIDTH as usize).find(|&p| (0..WIDTH as usize - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= WIDTH as usize / 2, "the checker tiles across the set: {hard:?}"); + + let wrapping = [ + Filter::Blur { radius: 96.0, wrap: true }, + Filter::DistanceBevel(Bevel { wrap: true, ..Bevel::LIBRARY }), + Filter::BevelSmooth(BevelSmooth { wrap: true, ..BevelSmooth::LIBRARY }), + ]; + for filter in wrapping { + let whole = composite(Some(&filter), &all_tiles(WIDTH, HEIGHT)); + let edge_tile = composite(Some(&filter), &[(0, 0)]); + + let label = filter.label(); + assert!((0..TILE as usize).all(|x| (edge_tile[x] - whole[x]).abs() < 1e-3), "{label}: the edge tile alone\n{edge_tile:?}\nwhole\n{whole:?}"); + assert!((0..WIDTH as usize - period).all(|x| (whole[x] - whole[x + period]).abs() < 0.02), "{label} keeps tiling: {whole:?}"); + } + } + + #[test] + fn a_gradients_blur_intensity_blurs_what_it_looks_up() { + let row = |filter: Option| { + let mut f = fixture(); + checker_roughness(&mut f, filter); + let out = run(&f, None); + (16..48).map(|x| out.value(Channel::Roughness, x, 20)[0]).collect::>() + }; + let mut gradient = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); + let hard = row(Some(gradient.clone())); + assert!(hard.iter().zip(row(None)).all(|(a, b)| (a - b).abs() < 1e-3), "a black to white ramp keeps a scalar as it is"); + + // Blurred first, then looked up: the same as a blur of that size + if let Filter::GradientMap { input, .. } = &mut gradient { + input.blur = 8.0; + } + let blurred = row(Some(gradient)); + let reference = row(Some(Filter::Blur { radius: 8.0, wrap: false })); + assert!(blurred.iter().zip(&reference).all(|(a, b)| (a - b).abs() < 0.02), "{blurred:?} vs {reference:?}"); + assert!(blurred.iter().zip(&hard).any(|(a, b)| (a - b).abs() > 0.1), "{blurred:?}"); + } + + #[test] + fn highpass_works_in_its_color_space_and_applies_to_alpha() { + // Uniform content has no detail: mid gray in the working space, sRGB mid gray (linear 0.214) in sRGB + let mut f = fixture(); + let below = fill_layer(&mut f.project, [0.0; 3], 0.0); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + assert_ne!(below, id); + let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::SrgbFromLinear, alpha: false })); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 30, 30), [texturecraft_texel::srgb_to_linear(0.5); 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); + assert!(close(out.value(Channel::Roughness, 30, 30), [0.5; 3]), "scalar channels stay in the working space"); + + // Apply To Alpha: full coverage minus its blur, around 0.5, lays the layer at half over the black one below + f.project.effect_mut(hp).unwrap().kind = EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::Working, alpha: true }); + let out = run(&f, None); + assert!(close(out.value(Channel::Roughness, 30, 30), [0.25; 3]), "{:?}", out.value(Channel::Roughness, 30, 30)); + } + + #[test] + fn highpass_in_srgb_applied_to_alpha_decodes_on_the_new_coverage() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.0; 3], 0.0); + let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); + content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::SrgbFromLinear, alpha: true })); + + let out = run(&f, None); + + // sRGB mid gray (linear 0.214) at half coverage over the black layer below + let expected = texturecraft_texel::srgb_to_linear(0.5) * 0.5; + assert!(close(out.value(Channel::BaseColor, 30, 30), [expected; 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); + } + #[test] fn high_pass_edge_detect_directional_warp_grayscale_and_normal_invert() { // Uniform content gives mid gray high pass and black edge detection let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); - let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0 })); + let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::Working, alpha: false })); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 30, 30), [0.5; 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); assert!(close(out.value(Channel::Roughness, 30, 30), [0.5; 3])); @@ -4368,15 +5708,12 @@ soft {soft:?}" let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 })); let out = run(&f, None); let vals: Vec = (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| out.value(Channel::Roughness, x, y)[0]).collect(); - assert!(vals.iter().all(|v| (0.0..=1.0).contains(v))); assert!(vals.iter().filter(|v| **v > 0.5).count() > 64 && vals.iter().filter(|v| **v < 0.01).count() > 64, "{vals:?}"); - f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != edges); - content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 })); + content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 })); let warped = run(&f, None); let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2)); - assert!(differs, "the warp moves the checker"); // Point filters @@ -4396,6 +5733,59 @@ soft {soft:?}" assert_eq!(rc.point(ChannelKind::Scalar, [0.8; 3]), Some([0.8; 3])); } + #[test] + fn a_halo_glow_lights_around_a_masks_shapes_and_a_drop_shadow_lands_under_them_away_from_the_light() { + let row_of = |filter: Option| { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0; 3], 1.0); + let mut mask = Mask::new(MaskBackground::Black); + let fill = EffectKind::Fill { + source: Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + sampling: Default::default(), + }; + mask.effects.push(Effect::new(f.project.alloc_id(), fill)); + if let Some(filter) = filter { + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(filter))); + } + f.project.layer_mut(id).unwrap().mask = Some(mask); + let out = run(&f, None); + (0..64 * 64).map(|i| out.value(Channel::BaseColor, i % 64, i / 64)[0]).collect::>() + }; + let plain = row_of(None); + let (low, high) = plain.iter().fold((f32::MAX, f32::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + let dark = |v: f32| v < low + 0.01; + + // A glow only adds, and lights the dark texels beside the shapes + let glow = Filter::HaloGlow { on_mask: true, precise: false, width: 1.0, spread: 0.0, opacity: 1.0, color: [1.0; 3] }; + let glowing = row_of(Some(glow)); + assert!(glowing.iter().zip(&plain).all(|(g, p)| *g >= p - 1e-4), "a glow only adds"); + let lit = (0..64 * 64).filter(|&i| dark(plain[i]) && glowing[i] > low + 0.1 * (high - low)).count(); + assert!(lit > 64, "{lit} dark texels lit"); + + // A shadow from a light above lands below the shapes: dark texels under a shape take it, those above one do not + let shadow = Filter::DropShadow { angle: 90.0, distance: 0.1, size: 0.0, spread: 0.0, opacity: 0.5, color: [0.0; 3] }; + let shadowed = row_of(Some(shadow)); + assert!(shadowed.iter().zip(&plain).all(|(s, p)| *s >= p - 1e-4), "a shadow only goes under the shapes"); + let reach = 6; + let at = |x: usize, y: usize| plain[y * 64 + x]; + let (mut below, mut above) = (Vec::new(), Vec::new()); + for y in 8..56 { + for x in 0..64 { + if dark(at(x, y)) && !dark(at(x, y - reach)) && (y - 2..=y).all(|row| dark(at(x, row))) { + below.push(shadowed[y * 64 + x] - at(x, y)); + } + if dark(at(x, y)) && !dark(at(x, y + reach)) && dark(at(x, y - reach)) && (y..=y + 2).all(|row| dark(at(x, row))) { + above.push(shadowed[y * 64 + x] - at(x, y)); + } + } + } + assert!(!below.is_empty() && !above.is_empty()); + let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; + assert!(mean(&below) > 0.2 * (high - low), "under: {below:?}"); + assert!(mean(&above) < 0.05 * (high - low), "above: {above:?}"); + } + #[test] fn bevel_glow_and_mosaic() { let checker = |f: &mut Fixture| { @@ -4417,7 +5807,7 @@ soft {soft:?}" let plain = values(&f); // Bevel stays below the shape and turns edges into ramps - let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Bevel { width: 128.0 })); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Bevel { width: 128.0, wrap: false })); let bevel = values(&f); let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.05 && **x < 0.95).count(); assert!(bevel.iter().zip(&plain).all(|(b, p)| *b <= p + 1e-4 && *b >= 0.0), "a bevel only lowers values"); @@ -4425,7 +5815,7 @@ soft {soft:?}" // Mosaic reduces changes between adjacent texels f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != fx); - let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 768.0 })); + let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 768.0, alpha: true })); let mosaic = values(&f); let steps = |v: &[f32]| v.windows(2).filter(|w| (w[0] - w[1]).abs() > 0.01).count(); assert!(steps(&mosaic) < steps(&plain), "{} vs {}", steps(&mosaic), steps(&plain)); @@ -4445,7 +5835,7 @@ soft {soft:?}" let lit = |elevation: f32| { let mut f = fixture(); let id = fill_layer(&mut f.project, [0.5; 3], 0.3); - let fx = Filter::BakedLighting { azimuth: 0.0, elevation, light: 0.6, ambient: 0.4, occlusion: 1.0 }; + let fx = Filter::BakedLighting { azimuth: 0.0, elevation, light: 0.6, ambient: 0.4, occlusion: 1.0, stylized: None }; content_fx(&mut f, id, EffectKind::Filter(fx)); let out = run(&f, None); (out.value(Channel::BaseColor, 30, 30), out.value(Channel::Roughness, 30, 30)) @@ -4455,15 +5845,30 @@ soft {soft:?}" // Facing the light adds illumination; facing away keeps ambient only let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 }); assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}"); - let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 }); assert!(close(away, [0.2; 3]), "{away:?}"); - - let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5 }; + let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5, stylized: None }; assert_eq!(f.baked_light([0.0, 1.0, 0.0], 0.2), Some(0.6), "half the occlusion"); assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); } + /// Baked Lighting Stylized's highlights read the roughness of the layer it lights: a smooth layer shines brighter than a rough one under the same sun + #[test] + fn stylized_baked_lighting_highlights_read_the_layers_roughness() { + let lit = |rough: f32| { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [0.2; 3], rough); + let n = primitives::plane(2.0, 2).normals[0]; + let stylized = Some(Box::new(StylizedLighting { lights: [texturecraft_core::DirectionalLight::off(0.0); 2], ..StylizedLighting::library() })); + let elevation = if n.y > 0.0 { 90.0 } else { -90.0 }; + let fx = Filter::BakedLighting { azimuth: 0.0, elevation, light: 1.0, ambient: 0.0, occlusion: 0.0, stylized }; + content_fx(&mut f, id, EffectKind::Filter(fx)); + run(&f, None).value(Channel::BaseColor, 30, 30) + }; + let (smooth, rough) = (lit(0.15), lit(0.9)); + assert!(smooth[0] > rough[0] + 0.05, "smooth {smooth:?} rough {rough:?}"); + } + #[test] fn a_compares_histogram_reads_the_compares_under_it_against_the_stack() { let mut f = fixture(); @@ -4490,10 +5895,24 @@ soft {soft:?}" // The roughness below (0.8) passes the first compare everywhere: the mask so far is white let white = *mask_so_far.last().unwrap(); - assert!(white > 0 && mask_so_far.iter().sum::() == white, "{mask_so_far:?}"); } + #[test] + fn a_histogram_shares_one_field_of_a_stage_reading_the_whole_set() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [0.5; 3], 0.5); + let matcher = ColorMatch { source_mode: SourceColorMode::Average, ..ColorMatch::LIBRARY }; + content_fx(&mut f, id, EffectKind::Filter(Filter::ColorMatch(matcher))); + let images = ImageStore::default(); + let inp = inputs(&f, &images, None); + let channels = f.project.texture_set(0).unwrap().channel_list(); + + let shared = shared_histogram_fields(&inp, &channels, &all_tiles(64, 64)); + + assert!(shared.is_some_and(|fields| fields.contains_key(&FieldKey::Content(id, Channel::BaseColor))), "every sampled tile reads one field"); + } + #[test] fn a_filtered_mask_compares_the_layers_filtered_content() { let mut f = fixture(); @@ -4512,6 +5931,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(f.project.alloc_id(), compare)); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0 }))); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0, wrap: true }))); f.project.layer_mut(top).unwrap().mask = Some(mask); let color = run(&f, None).value(Channel::BaseColor, 30, 30); @@ -4616,18 +6036,15 @@ soft {soft:?}" let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(top).unwrap().mask = Some(mask.clone()); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // The field pre-pass reads anchors under blur, preserving flat height - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); f.project.layer_mut(top).unwrap().mask = Some(mask); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // An anchor above its reader is not evaluated yet, so it reads the channel default f.project.move_layer(low, 1).unwrap(); - assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } @@ -4660,16 +6077,14 @@ soft {soft:?}" assert!(close(run(&fixture, None).value(Channel::BaseColor, 5, 5), [0.4; 3])); // Under a blur precomputed over the region the anchor still records its own place - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); - assert!(close(color, [0.4; 3]), "{color:?}"); // An empty paint layer still records its mask anchor for the layer above fixture.project.layer_mut(low).unwrap().kind = LayerKind::Paint; let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); - assert!(close(color, [0.7; 3]), "{color:?}"); } @@ -4686,22 +6101,74 @@ soft {soft:?}" fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() }, )); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0 }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0, wrap: false }))); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); fixture.project.layer_mut(lower).unwrap().mask = Some(mask.clone()); let reader = anchor_reader(&mut fixture, anchor); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let expected = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); - assert!(expected.iter().any(|value| *value > 0.1 && *value < 0.9), "the anchor records a softened checker"); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0 }))); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0, wrap: false }))); fixture.project.layer_mut(lower).unwrap().mask = Some(mask); let actual = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); assert_eq!(actual, expected, "a filter above the anchor must not change its recorded value"); } + #[test] + fn an_anchor_between_content_effects_keeps_the_layers_own_lighting() { + let mut fixture = fixture(); + let low = fixture.project.alloc_id(); + let mut fill = Fill::default(); + + // A gray (sRGB 140) dim for a metal but valid for a dielectric: PBR Validate turns it red only with the layer's own metal + let dim_metal = [0.26; 3]; + fill.sources.insert(Channel::BaseColor, Source::Uniform(dim_metal)); + fill.sources.insert(Channel::Metallic, Source::Uniform([1.0; 3])); + let layer = Layer::new(low, "Metal", LayerKind::Fill(fill), &[Channel::BaseColor, Channel::Metallic]); + fixture.project.insert_layer(0, layer, None, false).unwrap(); + content_fx(&mut fixture, low, EffectKind::Filter(Filter::PbrValidate(PbrValidate::LIBRARY))); + let anchor = content_fx(&mut fixture, low, EffectKind::Anchor); + let reader = fixture.project.alloc_id(); + let mut read = Fill::default(); + read.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }); + let layer = Layer::new(reader, "Reader", LayerKind::Fill(read), &[Channel::BaseColor]); + fixture.project.insert_layer(0, layer, None, false).unwrap(); + let uncut = run(&fixture, None).value(Channel::BaseColor, 5, 5); + + // An effect above the anchor cuts the content stack there: the cut is checked against the same metal + content_fx(&mut fixture, low, EffectKind::Levels(Default::default())); + let cut = run(&fixture, None).value(Channel::BaseColor, 5, 5); + + assert!(close(uncut, PbrValidate::INVALID), "{uncut:?}"); + assert!(close(cut, uncut), "{cut:?}"); + } + + #[test] + fn a_filter_and_a_flatten_above_pbr_validate_keep_the_layers_own_metal() { + let mut fixture = fixture(); + let id = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([0.26; 3])); + fill.sources.insert(Channel::Metallic, Source::Uniform([1.0; 3])); + let layer = Layer::new(id, "Metal", LayerKind::Fill(fill), &[Channel::BaseColor, Channel::Metallic]); + fixture.project.insert_layer(0, layer, None, false).unwrap(); + content_fx(&mut fixture, id, EffectKind::Filter(Filter::PbrValidate(PbrValidate::LIBRARY))); + let images = ImageStore::default(); + let flat = flatten_layer(&inputs(&fixture, &images, None), id, &all_tiles(64, 64)).unwrap(); + content_fx(&mut fixture, id, EffectKind::Filter(Filter::Blur { radius: 4.0, wrap: false })); + + let blurred = run(&fixture, None).value(Channel::BaseColor, 30, 30); + + // A dim gray is valid for a dielectric only: the layer's metal makes it red in the filter's prepass and in the flattened layer + assert!(close(blurred, PbrValidate::INVALID), "{blurred:?}"); + let (_, _, data) = flat.iter().find(|(channel, tile, _)| *channel == Channel::BaseColor && *tile == (0, 0)).unwrap(); + let texel = (30 * TILE as usize + 30) * 4; + let flattened: [f32; 3] = std::array::from_fn(|i| from_u16(data[texel + i])); + assert!(flattened.iter().zip(PbrValidate::INVALID).all(|(value, invalid)| (value - invalid).abs() < 1e-3), "{flattened:?}"); + } + #[test] fn generator_micro_detail_follows_the_anchor_height() { let mut fixture = fixture(); diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs deleted file mode 100644 index 6f50f143..00000000 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ /dev/null @@ -1,23 +0,0 @@ -use std::ops::Deref; - -use super::Inputs; -use crate::ProjectorDepthCache; - -pub(super) struct EvaluationInputs<'a> { - inputs: &'a Inputs<'a>, - pub(super) projectors: &'a ProjectorDepthCache, -} - -impl<'a> EvaluationInputs<'a> { - pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self { - Self { inputs, projectors } - } -} - -impl<'a> Deref for EvaluationInputs<'a> { - type Target = Inputs<'a>; - - fn deref(&self) -> &Self::Target { - self.inputs - } -} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index c0369fd2..65cf4271 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -13,7 +13,10 @@ pub mod below; mod curvature_size_level; pub mod curvature_sizes; pub mod display; +mod distance_envelope; mod effect_histogram; +pub mod environment_sh; +pub mod environment_sky; pub mod eval; mod fabric; pub mod fill_copies; @@ -30,8 +33,10 @@ pub mod pattern; mod pattern_context; pub mod projector_cover; pub mod projector_depth; -mod projector_depth_cache; pub mod projector_view; +mod shape_distance; +mod slope_texel; +mod soft_box; pub mod solo; pub mod store; pub mod thumb; @@ -40,6 +45,8 @@ mod tile_pattern; mod tile_random_stream; mod timber; pub mod warp; +mod warp_source_sample; +mod warp_texel; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; diff --git a/crates/compose/src/shape_distance.rs b/crates/compose/src/shape_distance.rs new file mode 100644 index 00000000..0f3df3a7 --- /dev/null +++ b/crates/compose/src/shape_distance.rs @@ -0,0 +1,386 @@ +//! Filters drawn from the distance to the shapes' edge: Bevel, Bevel Smooth and Directional Distance + +use rayon::prelude::*; +use texturecraft_core::{Bevel, BevelBlur, BevelCorner, DirectionalDistance, Filter, lum}; + +use crate::distance_envelope::DistanceEnvelope; +use crate::eval::{MIN_ALPHA, blur}; + +/// From a texel's centre to the edge between it and the nearest texel across: half a texel short of their centres' distance +const EDGE_OFFSET: f32 = 0.5; + +/// Components of a texel with color and coverage (red, green, blue, alpha) +const RGBA_COMPONENTS: usize = 4; + +/// Color components of a texel, before its alpha +const COLOR_COMPONENTS: usize = 3; + +/// Where a texel's alpha sits among its components +const ALPHA_INDEX: usize = 3; + +/// What a texel becomes from its index, whether it is inside the shapes and its own value +type TexelResult<'a> = dyn Fn(usize, bool, f32) -> f32 + Sync + 'a; + +/// Lay distance filter `filter` over premultiplied `data` (`width` × `height` texels of `components`; content's shapes from its luminance), `tile_resolution` texels across a UV tile, mixed in by `opacity`; its Distance Map `grays` (0..1 a texel) scales the distance texel by texel +pub(crate) fn distance_filter( + data: &mut [f32], + (cover, grays): (&[f32], &[f32]), + components: usize, + (width, height): (usize, usize), + filter: &Filter, + tile_resolution: u32, + opacity: f32, +) { + let map = |texel: usize| grays.get(texel).copied().unwrap_or(1.0); + let value = |pixel: &[f32]| match pixel { + [r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]), + [value] => *value, + _ => 0.0, + }; + let values: Vec = data.par_chunks(components).map(value).collect(); + let shapes = |inside: &(dyn Fn(f32) -> bool + Sync)| -> Vec { + values.par_iter().zip(cover.par_iter()).map(|(value, covered)| *covered > 0.0 && inside(*value)).collect() + }; + let smoothed = |field: &mut [f32], texels: f32| { + let radius = texels.round() as usize; + if radius > 0 { + blur(field, width, height, radius); + } + }; + + // Per texel: whether it is inside the shapes, and what it becomes from its own value + let (inside, result): (Vec, Box>) = match filter { + Filter::DistanceBevel(bevel) => { + let inside = shapes(&|value| value >= Bevel::EDGE); + let edge = edge_distances(&inside, (width, height), bevel.corner == BevelCorner::Angular); + let reach = bevel.reach(tile_resolution); + let mut slope: Vec = inside.par_iter().zip(edge.par_iter()).map(|(inside, edge)| bevel.slope(*inside, *edge, reach)).collect(); + let mut blurred = slope.clone(); + smoothed(&mut blurred, bevel.smoothing_texels(tile_resolution)); + slope.par_iter_mut().zip(blurred.par_iter()).for_each(|(sharp, blurred)| { + *sharp = match bevel.blur { + BevelBlur::Uniform => *blurred, + // Sharp at the slope's foot, as blurred as Uniform at its top + BevelBlur::NonUniform => *sharp + (blurred - *sharp) * *sharp, + }; + }); + let bevel = *bevel; + (inside, Box::new(move |texel, inside, value| bevel.apply(inside, value, slope.get(texel).copied().unwrap_or(1.0)))) + } + Filter::BevelSmooth(smooth) => { + let inside = shapes(&|value| smooth.inside(value)); + let edge = edge_distances(&inside, (width, height), false); + let (reach, curve) = (smooth.reach(tile_resolution), smooth.curve()); + let mut ramp: Vec = inside + .par_iter() + .zip(edge.par_iter()) + .enumerate() + .map(|(texel, (inside, edge))| smooth.value(curve, *inside, *edge, reach * map(texel))) + .collect(); + smoothed(&mut ramp, smooth.smoothing_texels(tile_resolution)); + (inside, Box::new(move |texel, _, value| ramp.get(texel).copied().unwrap_or(value))) + } + Filter::DirectionalDistance(trail) => { + let inside = shapes(&|value| value >= DirectionalDistance::EDGE); + let along = trail_distances(&inside, (width, height), crate::eval::direction(trail.angle), trail.reach(tile_resolution)); + let trail = *trail; + + // A share of the full reach is a larger share of a texel's shorter one; no trail where the map is black, the shapes stay + let shortened = move |texel: usize| { + along.get(texel).copied().flatten().and_then(|along| match map(texel) { + _ if along <= 0.0 => Some(0.0), + gray if gray > 0.0 => Some(along / gray), + _ => None, + }) + }; + (inside, Box::new(move |texel, _, _| trail.value(shortened(texel).filter(|along| *along <= 1.0)))) + } + _ => return, + }; + + let has_alpha = components == RGBA_COMPONENTS; + data.par_chunks_mut(components).zip(inside.par_iter()).zip(cover.par_iter()).enumerate().for_each(|(texel, ((pixel, inside), covered))| { + if *covered <= 0.0 { + return; + } + + // Content is premultiplied by its coverage, which stays + let coverage = if has_alpha { pixel.get(ALPHA_INDEX).copied().unwrap_or(0.0) } else { 1.0 }; + for slot in pixel.iter_mut().take(components.min(COLOR_COMPONENTS)) { + let before = if has_alpha { if coverage > MIN_ALPHA { *slot / coverage } else { 0.0 } } else { *slot }; + let after = result(texel, *inside, before); + *slot = (before + (after - before) * opacity) * coverage; + } + }); +} + +/// Every texel's distance (texels) to the edge between it and the nearest texel on the other side of the shapes `inside`: straight-line, or the larger axis distance when `angular` +fn edge_distances(inside: &[bool], (width, height): (usize, usize), angular: bool) -> Vec { + let outside: Vec = inside.iter().map(|inside| !inside).collect(); + let (to_inside, to_outside) = if angular { + (chessboard_distances(inside, (width, height)), chessboard_distances(&outside, (width, height))) + } else { + (straight_distances(inside, (width, height)), straight_distances(&outside, (width, height))) + }; + inside + .par_iter() + .zip(to_inside.par_iter().zip(to_outside.par_iter())) + .map(|(inside, (to_inside, to_outside))| (if *inside { *to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0)) + .collect() +} + +/// Every texel's straight-line distance (texels) to the nearest texel where `feature` holds; farther than the region when none does +fn straight_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { + // Squared distances, separable: along the rows, then along the columns of those + let far = ((width + height) as f32).powi(2); + let mut rows: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + rows.par_chunks_mut(width.max(1)).for_each_init(DistanceEnvelope::default, |envelope, row| envelope.lower(row)); + let mut columns: Vec = (0..width * height).map(|at| rows.get((at % height.max(1)) * width + at / height.max(1)).copied().unwrap_or(far)).collect(); + columns.par_chunks_mut(height.max(1)).for_each_init(DistanceEnvelope::default, |envelope, column| envelope.lower(column)); + (0..width * height).map(|at| columns.get((at % width.max(1)) * height + at / width.max(1)).copied().unwrap_or(far).sqrt()).collect() +} + +/// Every texel's distance (texels, the larger of across and down) to the nearest texel where `feature` holds; farther than the region when none does +fn chessboard_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { + let far = (width + height) as f32; + let mut distances: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + + // One pass down from the texels above and left, one up from those below and right + let step = |distances: &mut [f32], (x, y): (usize, usize), neighbours: [(isize, isize); 4]| { + let nearest = neighbours + .iter() + .filter_map(|(dx, dy)| { + let (neighbour_x, neighbour_y) = (x.checked_add_signed(*dx)?, y.checked_add_signed(*dy)?); + (neighbour_x < width && neighbour_y < height).then(|| distances.get(neighbour_y * width + neighbour_x).copied()).flatten() + }) + .fold(f32::MAX, f32::min); + if let Some(slot) = distances.get_mut(y * width + x) { + *slot = slot.min(nearest + 1.0); + } + }; + for y in 0..height { + for x in 0..width { + step(&mut distances, (x, y), [(-1, 0), (-1, -1), (0, -1), (1, -1)]); + } + } + for y in (0..height).rev() { + for x in (0..width).rev() { + step(&mut distances, (x, y), [(1, 0), (1, 1), (0, 1), (-1, 1)]); + } + } + distances +} + +/// For every texel, how far (a share of `reach` texels) the nearest texel of the shapes `inside` lies behind it against `direction`, if one is in reach +fn trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec> { + let steps = trail_steps((width, height), direction, reach); + + // Each row of shapes as bits, a row without one as no words: steps landing on it find nothing + let shapes: Vec> = inside.par_chunks(width.max(1)).map(row_bits).collect(); + + let mut distances = vec![None; width * height]; + distances.par_chunks_mut(width.max(1)).enumerate().for_each(|(y, row)| trail_row(row, y, &shapes, &steps)); + distances +} + +/// The texel steps back along a trail against `direction`, nearest first, each with its share of `reach`: texel coordinates are whole, so every texel takes the same steps +fn trail_steps((width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<(isize, isize, f32)> { + // Steps of one texel along the direction's longer axis visit every column (or row) the trail crosses, so no thin shape is stepped over + let longer_axis = direction[0].abs().max(direction[1].abs()); + let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 }; + let step = if samples > 0 { reach / samples as f32 } else { 0.0 }; + + let mut steps: Vec<(isize, isize, f32)> = Vec::new(); + for sample in 0..=samples { + let back = sample as f32 * step; + + // Rounded half up, so a whole texel coordinate added to it rounds the same; a NaN direction lands nowhere + let (across, down) = ((0.5 - direction[0] * back).floor(), (0.5 - direction[1] * back).floor()); + if !(across.is_finite() && down.is_finite()) { + break; + } + + // A step as long as the region leaves it from every texel, and never comes back in + let (across, down) = (across as isize, down as isize); + if across.unsigned_abs() >= width || down.unsigned_abs() >= height { + break; + } + + // Rounding puts several samples on one texel: the nearest counts + if steps.last().is_some_and(|(last_across, last_down, _)| (*last_across, *last_down) == (across, down)) { + continue; + } + steps.push((across, down, if reach > 0.0 { back / reach } else { 0.0 })); + } + steps +} + +/// A row of shapes as bits, [`u64::BITS`] texels a word; no words when it has none +fn row_bits(row: &[bool]) -> Vec { + if !row.contains(&true) { + return Vec::new(); + } + + let mut words = vec![0u64; row.len().div_ceil(WORD_BITS)]; + for (word, texels) in words.iter_mut().zip(row.chunks(WORD_BITS)) { + *word = texels.iter().enumerate().filter(|(_, inside)| **inside).fold(0, |bits, (bit, _)| bits | 1 << bit); + } + words +} + +/// Texels in a word of a row's bits +const WORD_BITS: usize = u64::BITS as usize; + +/// Row `y`'s trail distances into `row`: a step at a time, every texel the step brings onto a shape takes its share, unless an earlier step did +fn trail_row(row: &mut [Option], y: usize, shapes: &[Vec], steps: &[(isize, isize, f32)]) { + let width = row.len(); + let mut found = vec![0u64; width.div_ceil(WORD_BITS)]; + let mut unfound = width; + + // The last word's bits past the row's end are no texels + let last_word = found.len().saturating_sub(1); + let tail = width % WORD_BITS; + let last_word_texels = if tail > 0 { (1u64 << tail) - 1 } else { u64::MAX }; + + for (across, down, share) in steps { + // A step past the region's top or bottom leaves it for good + let Some(source) = y.checked_add_signed(*down).and_then(|source_y| shapes.get(source_y)) else { break }; + if source.is_empty() { + continue; + } + + for (word, found_word) in found.iter_mut().enumerate() { + let in_row = if word == last_word { last_word_texels } else { u64::MAX }; + let landed = bits_from(source, (word * WORD_BITS) as isize + across) & !*found_word & in_row; + *found_word |= landed; + + let mut remaining = landed; + while remaining != 0 { + let bit = remaining.trailing_zeros() as usize; + remaining &= remaining - 1; + if let Some(slot) = row.get_mut(word * WORD_BITS + bit) { + *slot = Some(*share); + } + unfound = unfound.saturating_sub(1); + } + } + + if unfound == 0 { + break; + } + } +} + +/// The [`WORD_BITS`] bits of row bits `source` from texel `start` on, none past either end +fn bits_from(source: &[u64], start: isize) -> u64 { + let bits = WORD_BITS as isize; + let (word, shift) = (start.div_euclid(bits), start.rem_euclid(bits) as u32); + let at = |index: isize| usize::try_from(index).ok().and_then(|index| source.get(index)).copied().unwrap_or(0); + let low = at(word) >> shift; + if shift == 0 { low } else { low | at(word + 1) << (u64::BITS - shift) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn distances_are_straight_or_chessboard() { + // One feature texel in the middle of a 5 × 5 region + let mut feature = vec![false; 25]; + feature[12] = true; + let straight = straight_distances(&feature, (5, 5)); + let chessboard = chessboard_distances(&feature, (5, 5)); + assert_eq!((straight[12], straight[13], chessboard[13]), (0.0, 1.0, 1.0)); + assert!((straight[0] - 8f32.sqrt()).abs() < 1e-5, "{}", straight[0]); + assert_eq!(chessboard[0], 2.0, "a corner is as far as its larger axis"); + let none = straight_distances(&[false; 4], (2, 2)); + assert!(none.iter().all(|distance| *distance >= 4.0), "no feature is beyond the region"); + } + + #[test] + fn distances_keep_rows_and_columns_apart_in_a_region_wider_than_tall() { + // One feature texel at column 1, row 0 of a 7 × 3 region + let (width, height) = (7, 3); + let mut feature = vec![false; width * height]; + feature[1] = true; + let straight = straight_distances(&feature, (width, height)); + let chessboard = chessboard_distances(&feature, (width, height)); + + let at = |x: usize, y: usize| y * width + x; + assert_eq!((straight[at(1, 0)], straight[at(6, 0)], straight[at(1, 2)]), (0.0, 5.0, 2.0)); + assert!((straight[at(6, 2)] - 29f32.sqrt()).abs() < 1e-5, "{}", straight[at(6, 2)]); + assert_eq!((chessboard[at(6, 0)], chessboard[at(0, 2)], chessboard[at(6, 2)]), (5.0, 2.0, 5.0)); + } + + #[test] + fn a_trail_finds_the_nearest_shape_behind_a_texel_as_a_share_of_its_reach() { + // A shape at column 0 of a 5 × 2 region; the trail runs towards +x, so a texel looks back towards -x + let (width, height) = (5, 2); + let inside: Vec = (0..width * height).map(|texel| texel % width == 0).collect(); + let trail = trail_distances(&inside, (width, height), [1.0, 0.0], 4.0); + + assert_eq!(trail[0], Some(0.0), "on the shape"); + assert_eq!(trail[2], Some(0.5), "two texels behind, half the reach"); + assert_eq!(trail[width + 4], Some(1.0), "at the reach's end"); + } + + #[test] + fn a_long_trail_steps_over_no_thin_shape() { + // A one-texel shape at column 0 of an 8 × 1 region, with a reach far longer than the region + let (width, height) = (8, 1); + let inside: Vec = (0..width * height).map(|texel| texel == 0).collect(); + let reach = 128.0; + + let trail = trail_distances(&inside, (width, height), [1.0, 0.0], reach); + + assert_eq!(trail[3], Some(3.0 / reach), "three texels behind"); + assert!(trail.iter().all(Option::is_some), "every texel behind the shape is in its trail: {trail:?}"); + } + + /// The trail as every texel walks it on its own, one sample at a time: what the shared steps must match + fn walked_trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec> { + let longer_axis = direction[0].abs().max(direction[1].abs()); + let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 }; + let step = if samples > 0 { reach / samples as f32 } else { 0.0 }; + (0..width * height) + .into_par_iter() + .map(|texel| { + let (x, y) = ((texel % width) as f32, (texel / width) as f32); + (0..=samples) + .map(|sample| { + let back = sample as f32 * step; + (back, (x - direction[0] * back).round(), (y - direction[1] * back).round()) + }) + .take_while(|(_, sample_x, sample_y)| *sample_x >= 0.0 && *sample_y >= 0.0 && (*sample_x as usize) < width && (*sample_y as usize) < height) + .find_map(|(back, sample_x, sample_y)| inside[sample_y as usize * width + sample_x as usize].then(|| back / reach)) + }) + .collect() + } + + #[test] + fn shared_trail_steps_find_what_each_texel_walking_its_own_finds() { + // About one texel in fifty a shape, in a region whose rows end part way through a word + // Small enough that the walk's float sums round as exactly as the shared steps (thousands of texels across, a near tie can round a texel over) + let (width, height) = (150, 97); + let mut seed = 12345u32; + let inside: Vec = (0..width * height) + .map(|_| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + (seed >> 16) % 97 < 2 + }) + .collect(); + + for angle in [0.0, 17.0, 45.0, 90.0, 135.0, 200.0, 290.0, 333.0] { + for reach in [9.3, 60.0, 400.0] { + let direction = crate::eval::direction(angle); + + let shared = trail_distances(&inside, (width, height), direction, reach); + + let walked = walked_trail_distances(&inside, (width, height), direction, reach); + assert!(walked.iter().any(Option::is_some) && walked.iter().any(Option::is_none), "{angle}° {reach}: a field with texels in and out of reach"); + assert_eq!(shared, walked, "{angle}° reach {reach}"); + } + } + } +} diff --git a/crates/compose/src/slope_texel.rs b/crates/compose/src/slope_texel.rs new file mode 100644 index 00000000..0cbdd957 --- /dev/null +++ b/crates/compose/src/slope_texel.rs @@ -0,0 +1,45 @@ +//! What a Blur Slope filter reads for one texel: its source's slope, then the values downhill of it + +use texturecraft_core::{SlopeBlending, SourceSlopeBlur, SourceWarp}; + +use crate::eval::LINE_SAMPLES; +use crate::warp_source_sample::WarpSourceSample; +use crate::warp_texel::{Input, Sample, keep_extreme_read}; + +/// A source rising less than this across a texel is flat +const FLAT_STEEPNESS: f32 = 1e-6; + +/// Blur Slope `slope` at texel `(x, y)` (`res` texels across a UV tile, `comps` values a texel) into `acc`: the reads downhill of it, blended +pub(crate) fn slope_texel( + slope: &SourceSlopeBlur, + (x, y): (f32, f32), + (res, comps): (u32, usize), + acc: &mut [f32; 5], + (sample, input): (Sample<'_>, Input<'_>), +) { + let source = WarpSourceSample::new(&slope.source, slope.seed, (res, comps), (sample, input)); + let probe = SourceWarp::probe_texels(res); + let downhill = [source.at(x - probe, y) - source.at(x + probe, y), source.at(x, y - probe) - source.at(x, y + probe)]; + let steepness = downhill[0].hypot(downhill[1]); + + // A flat spot keeps its value + if steepness.is_nan() || steepness <= FLAT_STEEPNESS { + sample(x, y, acc); + return; + } + + let [dx, dy] = downhill.map(|rise| rise / steepness); + let reach = slope.move_texels(res); + let read_count = slope.samples((reach.ceil() as u32).clamp(1, LINE_SAMPLES.unsigned_abs())); + let step = reach / read_count as f32; + let along = (0..=read_count).map(|read| read as f32 * step); + if slope.blending == SlopeBlending::Blur { + for t in along { + sample(x + dx * t, y + dy * t, acc); + } + return; + } + + let reads = along.map(|t| (x + dx * t, y + dy * t)); + keep_extreme_read(reads, slope.blending == SlopeBlending::Max, comps, acc, sample); +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 29fd7115..dea9f8d6 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -7,9 +7,12 @@ use std::collections::BTreeMap; use texturecraft_compose::{ BelowCache, Composite, Inputs, MaskGray, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, }; +use texturecraft_core::project::ENV_RESOURCE_PREFIX; use texturecraft_core::{ BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, + GrayscaleConversion, HeightMask, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, + TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use texturecraft_texel::{TILE, TileImage, to_u16}; @@ -69,7 +72,7 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { ); let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position)))); - mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); + mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false }))); add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask)); let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); for b in f.project.layer_mut(group).unwrap().channels.values_mut() { @@ -83,7 +86,7 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, )); - blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 }))); + blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0, wrap: false }))); let top = add(f, 0, LayerKind::Paint, Some(blurred)); let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES)); for y in 40..200 { @@ -248,7 +251,7 @@ fn generator_mask(f: &mut Fixture, kind: GeneratorKind, blur: Option) -> Ma let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(effect(f, EffectKind::Generator(g))); if let Some(radius) = blur { - mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius }))); + mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius, wrap: false }))); } mask } @@ -312,8 +315,8 @@ fn nested_stack(f: &mut Fixture) -> Nested { blend(f, g2_above, BlendMode::Overlay, 0.7); put(f, 0, Some(g2), LayerKind::Instance { source: base }, Some(Mask::new(MaskBackground::White))); let g1_above = put(f, 0, Some(g1), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Wood, 0.2, 0.8))]), None); - let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0 })); - let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0 })); + let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0, perceptive: false })); + let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0, wrap: false })); f.project.layer_mut(g1_above).unwrap().content_effects.extend([hsl, blur]); blend(f, g1_above, BlendMode::Screen, 0.5); let mask = generator_mask(f, GeneratorKind::Position, Some(30.0)); @@ -544,7 +547,7 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() { assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything"); // Behind a blur the cut reads the filtered field; before it, the unfiltered content - let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 })); + let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0, wrap: false })); f.project.layer_mut(low).unwrap().content_effects.insert(0, blur); let blurred = reference(&f, 0); assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat"); @@ -572,12 +575,12 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { &mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, )); - slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 }))); + slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1, divider: 1 }))); let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope)); let top = add(&mut f, 0, LayerKind::Paint, None); paint_rect(&mut f, top, (30, 40), (150, 100), 0.4); let plain = reference(&f, 0); - let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3 })); + let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3, divider: 1 })); f.project.layer_mut(base).unwrap().content_effects.push(warp); let line = effect(&mut f, EffectKind::Filter(Filter::DirectionalBlur { radius: 40.0, angle: 30.0 })); f.project.layer_mut(streaks).unwrap().content_effects.push(line); @@ -671,6 +674,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap(); blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); + blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false }); let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); @@ -709,7 +713,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() { &mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() }, )); - blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); + blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false }))); add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred)); // Keep the blurred layer visible under the hot layer @@ -958,22 +962,58 @@ fn flat_image(value: f32) -> std::sync::Arc { #[test] fn id_map_image_changes_invalidate_stack_key() { +fn filter_input_and_id_map_image_changes_invalidate_stack_key() { let mut fixture = fixture(); heavy_stack(&mut fixture); let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let conversion = GrayscaleConversion { custom_input: true, ..GrayscaleConversion::LIBRARY }; + let mut filter = effect(&mut fixture, EffectKind::Filter(Filter::GrayscaleConversion(conversion))); + filter.inputs.insert(ImageInput::CUSTOM_INPUT.id.into(), Source::image("input")); let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); selection.id_map = Some("id".into()); let selection = effect(&mut fixture, EffectKind::ColorSelection(selection)); let layer = fixture.project.layer_mut(bottom_layer).unwrap(); + layer.content_effects.push(filter); layer.mask = Some(Mask::new(MaskBackground::White)); layer.mask.as_mut().unwrap().effects.push(selection); let mut images = texturecraft_compose::ImageStore::default(); + images.insert("input".into(), flat_image(0.1)); images.insert("id".into(), flat_image(0.1)); - let original = stack_key(&fixture, &images); images.insert("id".into(), flat_image(0.9)); + for name in ["input", "id"] { + let original = stack_key(&fixture, &images); + images.insert(name.into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != original, "replacing the {name} image must invalidate the cache"); + } +} assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache"); +#[test] +fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { + let mut fixture = fixture(); + heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let mut images = texturecraft_compose::ImageStore::default(); + images.insert("sky".into(), flat_image(0.5)); + fixture.project.display.environment = format!("{ENV_RESOURCE_PREFIX}sky"); + let unlit = stack_key(&fixture, &images); + + fixture.project.display.env_rotation += 90.0; + assert_eq!(stack_key(&fixture, &images), unlit, "without Baked Lighting Environment the turn changes nothing"); + + let lighting = + Filter::EnvironmentLighting { horizontal: 0.0, vertical: 0.0, exposure: 0.0, height_intensity: 0.0, ambient_occlusion: 0.0, specular_occlusion: 0.0 }; + let lighting = effect(&mut fixture, EffectKind::Filter(lighting)); + fixture.project.layer_mut(bottom_layer).unwrap().content_effects.push(lighting); + let lit = stack_key(&fixture, &images); + fixture.project.display.env_rotation += 90.0; + let turned = stack_key(&fixture, &images); + assert!(turned != lit, "turning the environment invalidates the cache"); + assert_eq!(lit.changed_tiles(&turned), None, "and recomposites every tile"); + + images.insert("sky".into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != turned, "replacing the environment image invalidates the cache"); } /// Where a blur lies on the layer inside the instanced folder @@ -988,6 +1028,7 @@ fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option, let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0 })); + let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false })); match blur_on { BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur), BlurOn::Mask => { diff --git a/crates/core/src/anisotropic_kuwahara.rs b/crates/core/src/anisotropic_kuwahara.rs new file mode 100644 index 00000000..6989a99a --- /dev/null +++ b/crates/core/src/anisotropic_kuwahara.rs @@ -0,0 +1,92 @@ +//! Anisotropic Kuwahara's settings: a painterly smoothing that follows the direction of the strokes + +use serde::{Deserialize, Serialize}; + +/// An Anisotropic Kuwahara filter: each texel takes the mean of the calmest sector of an ellipse turned along the local direction +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AnisotropicKuwahara { + /// Extract Direction Custom Input: the direction comes from the filter's Custom Input instead of the channel + pub custom_input: bool, + /// Texels at 2K the ellipse reaches (0..10) + pub radius: f32, + /// How much neighbouring sectors overlap (0 = hard sector edges) + pub smoothness: f32, + /// How strongly the calmest sector wins over the others (0.25..1) + pub sharpness: f32, + /// How far around a texel its direction is averaged, as a share of the radius + pub tensor_smoothness: f32, + /// How much the ellipse stretches along the direction where the direction is clear (0 = a circle) + pub anisotropy: f32, + /// Degrees the ellipse turns from the extracted direction + pub angle: f32, +} + +impl AnisotropicKuwahara { + /// A new Anisotropic Kuwahara + pub const LIBRARY: AnisotropicKuwahara = + AnisotropicKuwahara { custom_input: false, radius: 5.0, smoothness: 0.25, sharpness: 0.25, tensor_smoothness: 0.1, anisotropy: 1.0, angle: 0.0 }; + + /// The largest Radius, in texels at 2K + pub const MAX_RADIUS: f32 = 10.0; + + /// The least Sharpness + pub const MIN_SHARPNESS: f32 = 0.25; + + /// Sectors the ellipse is split into + pub const SECTORS: usize = 8; + + /// The sector weighing exponent at a Sharpness of 0 and of 1 (Sharpness stops at [`Self::MIN_SHARPNESS`], so the least it weighs with is 5.5) + const SHARPNESS_EXPONENT_MIN: f32 = 2.0; + const SHARPNESS_EXPONENT_MAX: f32 = 16.0; + + /// The sample falloff exponent at no Smoothness (1 at full Smoothness) + const SECTOR_EXPONENT_MAX: f32 = 16.0; + + /// How far around a texel its direction is read, as a share of the radius (Tensor Smoothness, 0..1) + pub fn tensor_reach(&self) -> f32 { + if self.tensor_smoothness.is_finite() { self.tensor_smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.tensor_smoothness } + } + + /// The exponent a sector's spread is weighed with: higher picks the calmest sector more sharply + pub fn sharpness_exponent(&self) -> f32 { + let sharpness = if self.sharpness.is_finite() { self.sharpness.clamp(Self::MIN_SHARPNESS, 1.0) } else { Self::LIBRARY.sharpness }; + Self::SHARPNESS_EXPONENT_MIN + sharpness * (Self::SHARPNESS_EXPONENT_MAX - Self::SHARPNESS_EXPONENT_MIN) + } + + /// How sharply a sample's weight falls off away from a sector's middle: smoother sectors overlap more + pub fn sector_exponent(&self) -> f32 { + let smoothness = if self.smoothness.is_finite() { self.smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.smoothness }; + 1.0 + (1.0 - smoothness) * (Self::SECTOR_EXPONENT_MAX - 1.0) + } + + /// The ellipse's semi-axes (along, across the direction) for `radius` texels where the direction is `clear` (0..1) + pub fn axes(&self, radius: f32, clear: f32) -> (f32, f32) { + let stretch = if self.anisotropy.is_finite() { self.anisotropy.clamp(0.0, 1.0) } else { Self::LIBRARY.anisotropy } * clear.clamp(0.0, 1.0); + (radius * (1.0 + stretch), radius / (1.0 + stretch)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_clear_direction_stretches_the_ellipse() { + let filter = AnisotropicKuwahara::LIBRARY; + assert_eq!(filter.axes(4.0, 0.0), (4.0, 4.0)); + assert_eq!(filter.axes(4.0, 1.0), (8.0, 2.0)); + assert_eq!(AnisotropicKuwahara { anisotropy: 0.0, ..filter }.axes(4.0, 1.0), (4.0, 4.0)); + assert!(AnisotropicKuwahara { sharpness: 1.0, ..filter }.sharpness_exponent() > filter.sharpness_exponent()); + assert!(AnisotropicKuwahara { smoothness: 1.0, ..filter }.sector_exponent() < filter.sector_exponent()); + } + + #[test] + fn sharpness_weighs_on_a_line_from_its_exponent_at_0_to_its_exponent_at_1() { + let at = |sharpness: f32| AnisotropicKuwahara { sharpness, ..AnisotropicKuwahara::LIBRARY }.sharpness_exponent(); + + assert_eq!(at(AnisotropicKuwahara::MIN_SHARPNESS), 5.5, "the least Sharpness, a quarter of the way along"); + assert_eq!(at(0.0), 5.5, "below the least, the least"); + assert_eq!(at(1.0), 16.0, "the most Sharpness weighs with the most exponent"); + } +} diff --git a/crates/core/src/bevel.rs b/crates/core/src/bevel.rs new file mode 100644 index 00000000..740a918c --- /dev/null +++ b/crates/core/src/bevel.rs @@ -0,0 +1,98 @@ +//! The Bevel filter's settings and the slope it gives a shape's edge + +use serde::{Deserialize, Serialize}; + +use crate::{BevelBlur, BevelCorner, SIZE_REFERENCE_RES}; + +/// Shapes (values at or above [`Bevel::EDGE`]) sloped at their edge: inwards for a negative distance, outwards for a positive one +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Bevel { + /// Reads past the texture's edges from the far side (Bevel Wrap) + pub wrap: bool, + /// How far the slope reaches from the edge, a fraction of the UV tile: inwards below 0, outwards above (−1..1) + pub distance: f32, + pub corner: BevelCorner, + /// How much the slope is blurred (0..5, [`Bevel::SMOOTHING_TEXELS`] texels at 2K each) + pub smoothing: f32, + pub blur: BevelBlur, +} + +impl Bevel { + /// The Bevel filter as the library adds it + pub const LIBRARY: Bevel = Bevel { wrap: false, distance: -0.1, corner: BevelCorner::Round, smoothing: 0.0, blur: BevelBlur::NonUniform }; + + /// Values at or above it are inside the shapes + pub const EDGE: f32 = 0.5; + + /// Texels at 2K a unit of Smoothing blurs over + pub const SMOOTHING_TEXELS: f32 = 4.0; + + /// The largest Smoothing + pub const SMOOTHING_MAX: f32 = 5.0; + + /// Whether the slope lies inside the shapes + pub fn inward(&self) -> bool { + self.distance <= 0.0 || self.distance.is_nan() + } + + /// How many texels the slope reaches at `res` texels across a UV tile + pub fn reach(&self, res: u32) -> f32 { + let distance = if self.distance.is_finite() { self.distance.abs().min(1.0) } else { 0.0 }; + distance * res as f32 + } + + /// How many texels the slope is blurred over at `res` texels across a UV tile + pub fn smoothing_texels(&self, res: u32) -> f32 { + let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 }; + smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES + } + + /// The slope (0..1) at a texel `edge` texels from the shapes' edge, inside them or not, rising from 0 at its foot to 1 at its top + pub fn slope(&self, inside: bool, edge: f32, reach: f32) -> f32 { + let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 }; + match (self.inward(), inside) { + (true, true) => along, + (false, false) => 1.0 - along, + (true, false) => 0.0, + (false, true) => 1.0, + } + } + + /// The result at a texel of `value`, inside the shapes or not, on `slope`: an inward slope scales the shapes, an outward one rises around them + pub fn apply(&self, inside: bool, value: f32, slope: f32) -> f32 { + match (self.inward(), inside) { + (true, true) => value * slope, + (false, false) => value.max(slope), + _ => value, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_negative_distance_slopes_inwards_and_a_positive_one_outwards() { + let inward = Bevel::LIBRARY; + assert_eq!(inward.reach(2048), 204.8); + assert_eq!((inward.slope(true, 0.0, 10.0), inward.slope(true, 5.0, 10.0), inward.slope(true, 20.0, 10.0)), (0.0, 0.5, 1.0)); + assert_eq!(inward.apply(true, 0.8, 0.5), 0.4, "inside, scaled down towards the edge"); + assert_eq!(inward.apply(false, 0.3, 0.0), 0.3, "outside untouched"); + let outward = Bevel { distance: 0.1, ..inward }; + assert_eq!((outward.slope(false, 0.0, 10.0), outward.slope(false, 5.0, 10.0), outward.slope(false, 20.0, 10.0)), (1.0, 0.5, 0.0)); + assert_eq!(outward.apply(false, 0.2, 0.5), 0.5, "rises around the shapes"); + assert_eq!(outward.apply(true, 0.7, 1.0), 0.7, "inside untouched"); + } + + #[test] + fn hostile_settings_stay_in_range() { + let bevel = Bevel { distance: f32::NAN, smoothing: f32::INFINITY, ..Bevel::LIBRARY }; + assert_eq!((bevel.reach(2048), bevel.smoothing_texels(2048)), (0.0, 0.0)); + assert_eq!(bevel.slope(true, 3.0, 0.0), 1.0, "no reach leaves the shapes whole"); + let excessive = Bevel { distance: -9.0, smoothing: 9.0, ..bevel }; + assert_eq!(excessive.reach(1024), 1024.0); + assert_eq!(excessive.smoothing_texels(2048), Bevel::SMOOTHING_MAX * Bevel::SMOOTHING_TEXELS, "smoothing stops at its largest"); + } +} diff --git a/crates/core/src/bevel_blur.rs b/crates/core/src/bevel_blur.rs new file mode 100644 index 00000000..7d5e9cf3 --- /dev/null +++ b/crates/core/src/bevel_blur.rs @@ -0,0 +1,35 @@ +//! How a Bevel's Smoothing spreads over its slope + +use serde::{Deserialize, Serialize}; + +/// Where a Bevel's Smoothing blurs its slope +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BevelBlur { + /// Sharp at the slope's foot, smoother towards its top + #[default] + NonUniform, + /// The same blur over the whole slope + Uniform, +} + +impl BevelBlur { + /// Every blur mode, in the order a switch shows them + pub const ALL: [BevelBlur; 2] = [BevelBlur::NonUniform, BevelBlur::Uniform]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + BevelBlur::NonUniform => "Non-Uniform", + BevelBlur::Uniform => "Uniform", + } + } + + /// The id `effect.set {blurMode}` takes + pub fn id(self) -> &'static str { + match self { + BevelBlur::NonUniform => "nonUniform", + BevelBlur::Uniform => "uniform", + } + } +} diff --git a/crates/core/src/bevel_corner.rs b/crates/core/src/bevel_corner.rs new file mode 100644 index 00000000..fb26e355 --- /dev/null +++ b/crates/core/src/bevel_corner.rs @@ -0,0 +1,35 @@ +//! The shape a Bevel gives the corners it rounds off + +use serde::{Deserialize, Serialize}; + +/// How a Bevel measures the distance from a shape's edge, which shows at its corners +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BevelCorner { + /// Straight-line distance: corners the bevel goes around come out round + #[default] + Round, + /// The larger of the horizontal and vertical distance: corners stay square + Angular, +} + +impl BevelCorner { + /// Every corner type, in the order a switch shows them + pub const ALL: [BevelCorner; 2] = [BevelCorner::Round, BevelCorner::Angular]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + BevelCorner::Round => "Round", + BevelCorner::Angular => "Angular", + } + } + + /// The id `effect.set {cornerType}` takes + pub fn id(self) -> &'static str { + match self { + BevelCorner::Round => "round", + BevelCorner::Angular => "angular", + } + } +} diff --git a/crates/core/src/bevel_direction.rs b/crates/core/src/bevel_direction.rs new file mode 100644 index 00000000..013e4c7b --- /dev/null +++ b/crates/core/src/bevel_direction.rs @@ -0,0 +1,39 @@ +//! Which side of a shape's edge a Bevel Smooth ramps on + +use serde::{Deserialize, Serialize}; + +/// The side of the edge a Bevel Smooth's ramp lies on +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BevelDirection { + /// From the edge outwards, the shapes staying white + #[default] + Out, + /// From the edge inwards, around the shapes staying black + In, + /// Across the edge, mid gray on it + InOut, +} + +impl BevelDirection { + /// Every direction, in the order a switch shows them + pub const ALL: [BevelDirection; 3] = [BevelDirection::Out, BevelDirection::In, BevelDirection::InOut]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + BevelDirection::Out => "Out", + BevelDirection::In => "In", + BevelDirection::InOut => "In/Out", + } + } + + /// The id `effect.set {direction}` takes + pub fn id(self) -> &'static str { + match self { + BevelDirection::Out => "out", + BevelDirection::In => "in", + BevelDirection::InOut => "inOut", + } + } +} diff --git a/crates/core/src/bevel_smooth.rs b/crates/core/src/bevel_smooth.rs new file mode 100644 index 00000000..6bf665f3 --- /dev/null +++ b/crates/core/src/bevel_smooth.rs @@ -0,0 +1,117 @@ +//! The Bevel Smooth filter's settings and the ramp it draws from a shape's edge + +use serde::{Deserialize, Serialize}; + +use crate::{BevelDirection, RampCurve, SIZE_REFERENCE_RES, at_or_above_threshold, finite_unit}; + +/// A smooth ramp from the edge of the shapes (values at or above `threshold`), outwards, inwards or across it +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BevelSmooth { + pub direction: BevelDirection, + /// How far the ramp reaches from the edge, a fraction of the UV tile (0..0.3) + pub distance: f32, + /// How much the ramp is blurred (0..10, [`BevelSmooth::SMOOTHING_TEXELS`] texels at 2K each) + pub smoothing: f32, + /// Moves the ramp up or down before its curve (−1..1) + pub curve_offset: f32, + /// Bends the ramp: below 0 it rises later, above 0 sooner (−1..1) + pub curve_shape: f32, + /// Values at or above it are inside the shapes (Mask Threshold, 0..1) + pub threshold: f32, + /// Scales the distance (Distance Map Multiplier, 0..1) + pub multiplier: f32, + /// Reads past the texture's edges from the far side (Bevel Wrap) + pub wrap: bool, +} + +impl BevelSmooth { + /// The Bevel Smooth filter as the library adds it + pub const LIBRARY: BevelSmooth = BevelSmooth { + direction: BevelDirection::Out, + distance: 0.1, + smoothing: 1.0, + curve_offset: 0.0, + curve_shape: 0.0, + threshold: 0.5, + multiplier: 1.0, + wrap: false, + }; + + /// Texels at 2K a unit of Smoothing blurs over + pub const SMOOTHING_TEXELS: f32 = 2.0; + + /// The largest Smoothing + pub const SMOOTHING_MAX: f32 = 10.0; + + /// Whether `value` is inside the shapes + pub fn inside(&self, value: f32) -> bool { + at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold) + } + + /// How many texels the ramp reaches at `res` texels across a UV tile + pub fn reach(&self, res: u32) -> f32 { + finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32 + } + + /// How many texels the ramp is blurred over at `res` texels across a UV tile + pub fn smoothing_texels(&self, res: u32) -> f32 { + let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 }; + smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES + } + + /// The curve the ramp takes (Curve Offset and Curve Shape), worked out once per filter + pub fn curve(&self) -> RampCurve { + RampCurve::new(self.curve_offset, self.curve_shape) + } + + /// The ramp at a texel `edge` texels from the shapes' edge, inside them or not, bent by [`BevelSmooth::curve`] + pub fn value(&self, curve: RampCurve, inside: bool, edge: f32, reach: f32) -> f32 { + let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 }; + let curved = curve.apply(along); + match (self.direction, inside) { + (BevelDirection::Out, true) => 1.0, + (BevelDirection::Out, false) => 1.0 - curved, + (BevelDirection::In, true) => curved, + (BevelDirection::In, false) => 0.0, + (BevelDirection::InOut, true) => 0.5 + 0.5 * curved, + (BevelDirection::InOut, false) => 0.5 - 0.5 * curved, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The ramp with the curve worked out as the filter does + fn ramp(filter: BevelSmooth, inside: bool, edge: f32, reach: f32) -> f32 { + filter.value(filter.curve(), inside, edge, reach) + } + + #[test] + fn the_ramp_lies_on_its_direction_side() { + let out = BevelSmooth::LIBRARY; + assert_eq!(out.reach(2048), 204.8); + assert!(out.inside(0.5) && !out.inside(0.49)); + assert_eq!((ramp(out, true, 3.0, 10.0), ramp(out, false, 0.0, 10.0), ramp(out, false, 5.0, 10.0), ramp(out, false, 20.0, 10.0)), (1.0, 1.0, 0.5, 0.0)); + let inward = BevelSmooth { direction: BevelDirection::In, ..out }; + assert_eq!((ramp(inward, false, 3.0, 10.0), ramp(inward, true, 5.0, 10.0), ramp(inward, true, 20.0, 10.0)), (0.0, 0.5, 1.0)); + let both = BevelSmooth { direction: BevelDirection::InOut, ..out }; + assert_eq!( + (ramp(both, true, 0.0, 10.0), ramp(both, false, 0.0, 10.0), ramp(both, true, 10.0, 10.0), ramp(both, false, 10.0, 10.0)), + (0.5, 0.5, 1.0, 0.0) + ); + } + + #[test] + fn curve_offset_and_shape_bend_the_ramp() { + let inward = BevelSmooth { direction: BevelDirection::In, ..BevelSmooth::LIBRARY }; + assert_eq!(ramp(BevelSmooth { curve_offset: 0.25, ..inward }, true, 5.0, 10.0), 0.75); + assert!(ramp(BevelSmooth { curve_shape: 0.5, ..inward }, true, 5.0, 10.0) > 0.5, "rises sooner"); + assert!(ramp(BevelSmooth { curve_shape: -0.5, ..inward }, true, 5.0, 10.0) < 0.5, "rises later"); + assert_eq!(BevelSmooth { multiplier: 0.5, ..inward }.reach(2048), 102.4); + let hostile = BevelSmooth { distance: f32::NAN, curve_offset: f32::NAN, curve_shape: f32::INFINITY, threshold: f32::NAN, ..inward }; + assert_eq!((hostile.reach(2048), ramp(hostile, true, 1.0, 0.0)), (0.0, 1.0)); + } +} diff --git a/crates/core/src/conversion_mode.rs b/crates/core/src/conversion_mode.rs new file mode 100644 index 00000000..5817373c --- /dev/null +++ b/crates/core/src/conversion_mode.rs @@ -0,0 +1,63 @@ +//! How Grayscale Conversion turns a color into gray + +use serde::{Deserialize, Serialize}; + +use crate::GrayscaleMode; + +/// The gray Grayscale Conversion reads from a color: a [`GrayscaleMode`], or its own weights per component +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ConversionMode { + /// Halfway between the lightest and darkest component + Desaturation, + /// Red, Green, Blue and Alpha times their weights, summed + #[default] + ChannelsWeights, + /// The components' mean + Average, + /// The lightest component + Max, + /// The darkest component + Min, +} + +impl ConversionMode { + /// Every mode, in the order a list shows them + pub const ALL: [ConversionMode; 5] = + [ConversionMode::Desaturation, ConversionMode::ChannelsWeights, ConversionMode::Average, ConversionMode::Max, ConversionMode::Min]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + ConversionMode::ChannelsWeights => "Channels Weights", + other => other.mode().map_or("", GrayscaleMode::label), + } + } + + /// The id `effect.set {mode}` takes + pub fn id(self) -> &'static str { + match self { + ConversionMode::ChannelsWeights => "channelsWeights", + other => other.mode().map_or("", GrayscaleMode::id), + } + } + + /// The gray of straight color `rgb` with coverage `alpha`, `weights` for Red, Green, Blue and Alpha + pub fn gray(self, rgb: [f32; 3], alpha: f32, weights: [f32; 4]) -> f32 { + match self.mode() { + Some(mode) => mode.gray(rgb), + None => rgb[0] * weights[0] + rgb[1] * weights[1] + rgb[2] * weights[2] + alpha * weights[3], + } + } + + /// The gradient's grayscale mode this one matches (None for Channels Weights) + fn mode(self) -> Option { + match self { + ConversionMode::Desaturation => Some(GrayscaleMode::Desaturation), + ConversionMode::ChannelsWeights => None, + ConversionMode::Average => Some(GrayscaleMode::Average), + ConversionMode::Max => Some(GrayscaleMode::Max), + ConversionMode::Min => Some(GrayscaleMode::Min), + } + } +} diff --git a/crates/core/src/curve_preset.rs b/crates/core/src/curve_preset.rs new file mode 100644 index 00000000..97d843c4 --- /dev/null +++ b/crates/core/src/curve_preset.rs @@ -0,0 +1,142 @@ +//! The shapes Gradient Curve remaps values through + +use serde::{Deserialize, Serialize}; + +use crate::layer::smoothstep; + +/// Stairs climbs in this many flat steps +const STAIRS_STEPS: f32 = 4.0; + +/// Triangular rises and falls this many times +const TRIANGULAR_TEETH: f32 = 2.0; + +/// A remap curve from 0..1 onto 0..1 +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CurvePreset { + /// A quarter circle: rises fast, then flattens + #[default] + Round, + /// A quarter circle the other way: flat, then rises fast + Pinch, + /// Four flat steps + Stairs, + EaseOut, + Ease, + EaseIn, + /// Up to the middle and back down, rounded at the top + PeakOut, + /// Up to the middle and back down in straight lines + Peak, + /// Up to the middle and back down, pointed at the top + PeakIn, + /// Half a sine wave + Bump, + /// Two humps + DoubleBump, + /// Two straight teeth + Triangular, +} + +impl CurvePreset { + /// Every preset, in the order the Preset list shows them + pub const ALL: [CurvePreset; 12] = [ + CurvePreset::Round, + CurvePreset::Pinch, + CurvePreset::Stairs, + CurvePreset::EaseOut, + CurvePreset::Ease, + CurvePreset::EaseIn, + CurvePreset::PeakOut, + CurvePreset::Peak, + CurvePreset::PeakIn, + CurvePreset::Bump, + CurvePreset::DoubleBump, + CurvePreset::Triangular, + ]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + CurvePreset::Round => "Round", + CurvePreset::Pinch => "Pinch", + CurvePreset::Stairs => "Stairs", + CurvePreset::EaseOut => "Ease Out", + CurvePreset::Ease => "Ease", + CurvePreset::EaseIn => "Ease In", + CurvePreset::PeakOut => "Peak Out", + CurvePreset::Peak => "Peak", + CurvePreset::PeakIn => "Peak In", + CurvePreset::Bump => "Bump", + CurvePreset::DoubleBump => "Double Bump", + CurvePreset::Triangular => "Triangular", + } + } + + /// The id `effect.set {preset}` takes + pub fn id(self) -> &'static str { + match self { + CurvePreset::Round => "round", + CurvePreset::Pinch => "pinch", + CurvePreset::Stairs => "stairs", + CurvePreset::EaseOut => "easeOut", + CurvePreset::Ease => "ease", + CurvePreset::EaseIn => "easeIn", + CurvePreset::PeakOut => "peakOut", + CurvePreset::Peak => "peak", + CurvePreset::PeakIn => "peakIn", + CurvePreset::Bump => "bump", + CurvePreset::DoubleBump => "doubleBump", + CurvePreset::Triangular => "triangular", + } + } + + /// The curve at `t` (clamped to 0..1; a non-finite `t` reads 0) + pub fn at(self, t: f32) -> f32 { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + let peak = 1.0 - (2.0 * t - 1.0).abs(); + let y = match self { + CurvePreset::Round => (1.0 - (1.0 - t) * (1.0 - t)).sqrt(), + CurvePreset::Pinch => 1.0 - (1.0 - t * t).sqrt(), + CurvePreset::Stairs => ((t * STAIRS_STEPS).floor() / (STAIRS_STEPS - 1.0)).min(1.0), + CurvePreset::EaseOut => 1.0 - (1.0 - t) * (1.0 - t), + CurvePreset::Ease => smoothstep(0.0, 1.0, t), + CurvePreset::EaseIn => t * t, + CurvePreset::PeakOut => peak.sqrt(), + CurvePreset::Peak => peak, + CurvePreset::PeakIn => peak * peak, + CurvePreset::Bump => (std::f32::consts::PI * t).sin(), + CurvePreset::DoubleBump => (2.0 * std::f32::consts::PI * t).sin().abs(), + CurvePreset::Triangular => 1.0 - ((2.0 * TRIANGULAR_TEETH * t) % 2.0 - 1.0).abs(), + }; + y.clamp(0.0, 1.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Samples across 0..1 that every curve is read at + const SAMPLES: usize = 64; + + #[test] + fn every_preset_stays_in_range_and_reads_a_non_finite_t_as_0() { + for preset in CurvePreset::ALL { + let values: Vec = (0..=SAMPLES).map(|i| preset.at(i as f32 / SAMPLES as f32)).collect(); + assert!(values.iter().all(|value| (0.0..=1.0).contains(value)), "{}", preset.id()); + assert_eq!(preset.at(f32::NAN), preset.at(0.0), "{}", preset.id()); + assert_eq!(preset.at(f32::INFINITY), preset.at(0.0), "{}", preset.id()); + } + } + + #[test] + fn stairs_has_four_levels_and_triangular_two_teeth() { + let mut levels: Vec = (0..=SAMPLES).map(|i| CurvePreset::Stairs.at(i as f32 / SAMPLES as f32)).collect(); + levels.dedup(); + assert_eq!(levels, [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); + + let triangular = |t: f32| CurvePreset::Triangular.at(t); + assert_eq!([triangular(0.0), triangular(0.25), triangular(0.5), triangular(0.75), triangular(1.0)], [0.0, 1.0, 0.0, 1.0, 0.0]); + } +} diff --git a/crates/core/src/directional_distance.rs b/crates/core/src/directional_distance.rs new file mode 100644 index 00000000..0099a483 --- /dev/null +++ b/crates/core/src/directional_distance.rs @@ -0,0 +1,59 @@ +//! The Directional Distance filter's settings and the trail it draws from the shapes + +use serde::{Deserialize, Serialize}; + +use crate::finite_unit; + +/// A trail fading away from the shapes (values at or above [`DirectionalDistance::EDGE`]) towards `angle` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DirectionalDistance { + /// How far the trail reaches, a fraction of the UV tile (0..0.3) + pub distance: f32, + /// Where the trail runs to, in degrees counterclockwise from the right (270 runs down) + pub angle: f32, + /// Hardens the trail's fade (0..1) + pub contrast: f32, + /// Scales the distance (Distance Map Multiplier, 0..1) + pub multiplier: f32, +} + +impl DirectionalDistance { + /// The Directional Distance filter as the library adds it + pub const LIBRARY: DirectionalDistance = DirectionalDistance { distance: 0.1, angle: 270.0, contrast: 0.0, multiplier: 1.0 }; + + /// Values at or above it are inside the shapes + pub const EDGE: f32 = 0.5; + + /// The most contrast reaches: a hard step, kept off a division by zero + const HARDEST: f32 = 0.99; + + /// How many texels the trail reaches at `res` texels across a UV tile + pub fn reach(&self, res: u32) -> f32 { + finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32 + } + + /// The trail where the nearest shape behind a texel is `along` of the reach away (0 on a shape), or none is in reach + pub fn value(&self, along: Option) -> f32 { + let Some(along) = along.filter(|along| along.is_finite()) else { return 0.0 }; + let fade = 1.0 - along.clamp(0.0, 1.0); + let contrast = if self.contrast.is_finite() { self.contrast.clamp(0.0, Self::HARDEST) } else { 0.0 }; + (0.5 + (fade - 0.5) / (1.0 - contrast)).clamp(0.0, 1.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_trail_fades_with_distance_and_contrast_hardens_it() { + let trail = DirectionalDistance::LIBRARY; + assert_eq!(trail.reach(2048), 204.8); + assert_eq!((trail.value(Some(0.0)), trail.value(Some(0.25)), trail.value(None)), (1.0, 0.75, 0.0)); + let hard = DirectionalDistance { contrast: 0.5, ..trail }; + assert_eq!((hard.value(Some(0.25)), hard.value(Some(0.8))), (1.0, 0.0)); + let hostile = DirectionalDistance { distance: f32::NAN, contrast: f32::INFINITY, multiplier: -1.0, ..trail }; + assert_eq!((hostile.reach(2048), hostile.value(Some(f32::NAN))), (0.0, 0.0)); + } +} diff --git a/crates/core/src/directional_light.rs b/crates/core/src/directional_light.rs new file mode 100644 index 00000000..429a78b7 --- /dev/null +++ b/crates/core/src/directional_light.rs @@ -0,0 +1,31 @@ +//! One of Baked Lighting Stylized's extra lights + +use serde::{Deserialize, Serialize}; + +/// A light from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), of strength `intensity` in `color` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct DirectionalLight { + pub azimuth: f32, + pub elevation: f32, + pub intensity: f32, + pub color: [f32; 3], +} + +impl DirectionalLight { + /// An unlit white light from `azimuth`, 45 degrees up + pub const fn off(azimuth: f32) -> DirectionalLight { + DirectionalLight { azimuth, elevation: 45.0, intensity: 0.0, color: [1.0; 3] } + } + + /// The unit direction toward the light + pub fn direction(&self) -> [f32; 3] { + toward(self.azimuth, self.elevation) + } +} + +/// The unit direction toward a light at `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees) +fn toward(azimuth: f32, elevation: f32) -> [f32; 3] { + let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos(); + let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos(); + [cos_elevation * sin_azimuth, sin_elevation, cos_elevation * cos_azimuth] +} diff --git a/crates/core/src/gradient_input.rs b/crates/core/src/gradient_input.rs new file mode 100644 index 00000000..12f99b20 --- /dev/null +++ b/crates/core/src/gradient_input.rs @@ -0,0 +1,151 @@ +//! Gradient's Input Transformation: how a texel becomes the position it reads on the ramp + +use serde::{Deserialize, Serialize}; + +use crate::finite_unit; +use crate::grayscale_mode::GrayscaleMode; + +/// Full contrast stays a finite step instead of a division by zero +const MIN_STEEPNESS: f32 = 1e-3; + +/// The balance that leaves the gray as it is +pub(crate) const NEUTRAL_BALANCE: f32 = 0.5; + +/// The gray, blurred, balanced, contrasted and maybe inverted value a gradient looks up +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct GradientInput { + /// How a color becomes gray (masks and scalar channels are gray already) + pub mode: GrayscaleMode, + /// Blurs the gray before the lookup, in texels at 2K (0..16) + pub blur: f32, + /// Shifts the gray: above 0.5 lighter, below darker + pub balance: f32, + /// Steepens the gray around its middle: 1 is a hard step + pub contrast: f32, + pub invert: bool, +} + +impl Default for GradientInput { + /// What gradients read in projects saved before the Input Transformation: luma, untouched + fn default() -> Self { + GradientInput { mode: GrayscaleMode::Luma, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false } + } +} + +impl GradientInput { + /// The library's starting transformation: the average of the components, untouched + pub const LIBRARY: GradientInput = GradientInput { mode: GrayscaleMode::Average, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false }; + + /// Whether it reads gradients as projects saved before it did (skipped when saving) + pub fn is_unchanged(&self) -> bool { + *self == GradientInput::default() + } + + /// The ramp position of gray `x` + pub fn shape(&self, x: f32) -> f32 { + // Left as it is, the gray reaches the ramp bit for bit as projects saved before read it (the ramp clamps it) + if self.balance == NEUTRAL_BALANCE && self.contrast == 0.0 && !self.invert { + return x; + } + + shape_gray(x, self.balance, self.contrast, self.invert) + } +} + +/// Gray `x` balanced (0.5 keeps it), contrasted around mid gray (0 keeps it, 1 is a step at 0.5) and maybe inverted, in 0..1 +pub fn shape_gray(x: f32, balance: f32, contrast: f32, invert: bool) -> f32 { + let balanced = finite_unit(x) + finite_unit(balance) - NEUTRAL_BALANCE; + let steep = (1.0 - finite_unit(contrast)).max(MIN_STEEPNESS); + let shaped = finite_unit((balanced - 0.5) / steep + 0.5); + if invert { 1.0 - shaped } else { shaped } +} + +/// A ramp stop's place and color +type Stop = (f32, [f32; 3]); + +/// The color at `t` on a ramp of `colors` placed at `positions` (each 0..1, evenly spaced where missing), blended in linear or sRGB +pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Option<[f32; 3]> { + let last = colors.len().checked_sub(1)?; + let even = |index: usize| if last == 0 { 0.0 } else { index as f32 / last as f32 }; + let stops = colors + .iter() + .enumerate() + .map(|(index, color)| (positions.get(index).copied().filter(|p| p.is_finite()).unwrap_or_else(|| even(index)).clamp(0.0, 1.0), *color)); + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + + // The stops each side of `t` without sorting them, per texel: the last placed at or before it and the first placed after it + let (mut before, mut after): (Option, Option) = (None, None); + for (position, color) in stops { + if position <= t { + if before.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_ge()) { + before = Some((position, color)); + } + } else if after.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_lt()) { + after = Some((position, color)); + } + } + let ((before_place, before_color), (after_place, after_color)) = match (before, after) { + (Some(before), Some(after)) => (before, after), + (Some(only), None) | (None, Some(only)) => (only, only), + (None, None) => return None, + }; + + let share = if after_place > before_place { ((t - before_place) / (after_place - before_place)).clamp(0.0, 1.0) } else { 0.0 }; + Some(if linear { + std::array::from_fn(|k| before_color[k] + (after_color[k] - before_color[k]) * share) + } else { + std::array::from_fn(|k| { + let (before, after) = (linear_to_srgb(before_color[k]), linear_to_srgb(after_color[k])); + srgb_to_linear(before + (after - before) * share) + }) + }) +} + +// A copy of texturecraft_texel's: texel and core are both layer 0, so core cannot use it + +/// sRGB transfer of a linear component +pub(crate) fn linear_to_srgb(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// Linear value of an sRGB component +pub(crate) fn srgb_to_linear(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_ramp_reads_its_stops_in_place_order_whatever_their_list_order() { + let (black, gray, white) = ([0.0; 3], [0.5; 3], [1.0; 3]); + let colors = [white, black, gray]; + let positions = [1.0, 0.0, 0.5]; + + let quarter = ramp(&colors, &positions, true, 0.25); + let ends = (ramp(&colors, &positions, true, 0.0), ramp(&colors, &positions, true, 1.0)); + let past_one_stop = ramp(&[gray, white], &[0.5, 0.5], true, 0.25); + + assert_eq!(quarter, Some([0.25; 3])); + assert_eq!(ends, (Some(black), Some(white))); + assert_eq!(past_one_stop, Some(gray), "before the first stop, its color"); + assert_eq!(ramp(&[], &[], true, 0.5), None); + } + + #[test] + fn an_untouched_input_passes_every_gray_on_bit_for_bit() { + const SAMPLES: u16 = 1000; + let untouched = [GradientInput::default(), GradientInput::LIBRARY]; + let grays = (0..=SAMPLES).map(|step| f32::from(step) / f32::from(SAMPLES)).chain([-0.25, 1.5]); + + for input in untouched { + for gray in grays.clone() { + assert_eq!(input.shape(gray).to_bits(), gray.to_bits(), "{input:?} at {gray}"); + } + } + } +} diff --git a/crates/core/src/grayscale_conversion.rs b/crates/core/src/grayscale_conversion.rs new file mode 100644 index 00000000..3f186a7d --- /dev/null +++ b/crates/core/src/grayscale_conversion.rs @@ -0,0 +1,90 @@ +//! Grayscale Conversion's settings: which gray it reads and how it shapes it + +use serde::{Deserialize, Serialize}; + +use crate::blend::lum; +use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray}; +use crate::layer::per_unit; +use crate::{ChannelKind, ConversionMode}; + +/// A Grayscale Conversion filter: the gray of the current channel (or of its Custom Input), balanced, contrasted and maybe inverted +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GrayscaleConversion { + /// Channel Input Custom Input: the gray of the filter's Custom Input instead of the channel's + pub custom_input: bool, + pub invert: bool, + pub balance: f32, + pub contrast: f32, + pub mode: ConversionMode, + /// Channels Weights' Red, Green, Blue and Alpha + pub weights: [f32; 4], +} + +impl GrayscaleConversion { + /// A new Grayscale Conversion: a third of each color component, alpha left out + pub const LIBRARY: GrayscaleConversion = GrayscaleConversion { + custom_input: false, + invert: false, + balance: NEUTRAL_BALANCE, + contrast: 0.0, + mode: ConversionMode::ChannelsWeights, + weights: [0.33, 0.33, 0.33, 0.0], + }; + + /// The settings a Grayscale filter saved before them takes on its first edit: its luminance weights, so it looks the same + pub fn of_luminance() -> GrayscaleConversion { + let [red, green, blue] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].map(lum); + GrayscaleConversion { weights: [red, green, blue, 0.0], ..Self::LIBRARY } + } + + /// The shaped gray of straight color `rgb` with coverage `alpha` + pub fn gray(&self, rgb: [f32; 3], alpha: f32) -> f32 { + shape_gray(self.mode.gray(rgb, alpha, self.weights), self.balance, self.contrast, self.invert) + } + + /// `v` of a `kind` channel (coverage `alpha`) or `custom_input` turned gray: colors gray, scalar and signed in their range, normals as they are + pub fn channel_value(&self, kind: ChannelKind, v: [f32; 3], custom_input: Option<[f32; 3]>, alpha: f32) -> [f32; 3] { + match (kind, custom_input) { + (ChannelKind::NormalMap, _) => v, + (ChannelKind::Color, None) => [self.gray(v, alpha); 3], + (ChannelKind::Color, Some(input)) => [self.gray(input, alpha); 3], + (_, None) => per_unit(kind, v, |x| self.gray([x; 3], alpha)), + (_, Some(input)) => per_unit(kind, v, |_| self.gray(input, alpha)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_saved_grayscale_keeps_its_luminance() { + let color = [0.8, 0.3, 0.1]; + assert!((GrayscaleConversion::of_luminance().gray(color, 1.0) - lum(color)).abs() < 1e-5); + } + + #[test] + fn weights_balance_contrast_and_invert_shape_the_gray() { + let only_red = GrayscaleConversion { weights: [1.0, 0.0, 0.0, 0.0], ..GrayscaleConversion::LIBRARY }; + assert!((only_red.gray([0.6, 1.0, 1.0], 1.0) - 0.6).abs() < 1e-6); + let alpha = GrayscaleConversion { weights: [0.0, 0.0, 0.0, 1.0], ..GrayscaleConversion::LIBRARY }; + assert!((alpha.gray([1.0; 3], 0.25) - 0.25).abs() < 1e-6, "Alpha weighs the coverage"); + let inverted = GrayscaleConversion { invert: true, mode: ConversionMode::Max, ..GrayscaleConversion::LIBRARY }; + assert!((inverted.gray([0.2, 0.7, 0.1], 1.0) - 0.3).abs() < 1e-6); + let contrasted = GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..GrayscaleConversion::LIBRARY }; + assert_eq!(contrasted.gray([0.6; 3], 1.0), 1.0); + } + + #[test] + fn only_colors_turn_gray() { + let conversion = GrayscaleConversion::LIBRARY; + + let height = conversion.channel_value(ChannelKind::Signed, [-0.6; 3], None, 1.0); + let normal = conversion.channel_value(ChannelKind::NormalMap, [0.2, 0.7, 0.9], None, 1.0); + + assert!(height.iter().all(|x| (x + 0.6).abs() < 0.02), "a signed height keeps its sign: {height:?}"); + assert_eq!(normal, [0.2, 0.7, 0.9]); + } +} diff --git a/crates/core/src/grayscale_mode.rs b/crates/core/src/grayscale_mode.rs new file mode 100644 index 00000000..53d06ec6 --- /dev/null +++ b/crates/core/src/grayscale_mode.rs @@ -0,0 +1,58 @@ +//! How a color becomes the gray a gradient looks up + +use serde::{Deserialize, Serialize}; + +/// The gray a color reads as, before a gradient maps it +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GrayscaleMode { + /// Halfway between the lightest and darkest component + Desaturation, + /// Weighted by how bright each component looks (what gradients read in projects saved before the modes) + #[default] + Luma, + /// The components' mean + Average, + /// The lightest component + Max, + /// The darkest component + Min, +} + +impl GrayscaleMode { + /// Every mode, in the order a list shows them + pub const ALL: [GrayscaleMode; 5] = [GrayscaleMode::Desaturation, GrayscaleMode::Luma, GrayscaleMode::Average, GrayscaleMode::Max, GrayscaleMode::Min]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + GrayscaleMode::Desaturation => "Desaturation", + GrayscaleMode::Luma => "Luma", + GrayscaleMode::Average => "Average", + GrayscaleMode::Max => "Max", + GrayscaleMode::Min => "Min", + } + } + + /// The id `effect.set {grayscaleMode}` takes + pub fn id(self) -> &'static str { + match self { + GrayscaleMode::Desaturation => "desaturation", + GrayscaleMode::Luma => "luma", + GrayscaleMode::Average => "average", + GrayscaleMode::Max => "max", + GrayscaleMode::Min => "min", + } + } + + /// The gray of linear color `[r, g, b]` + pub fn gray(self, [r, g, b]: [f32; 3]) -> f32 { + match self { + GrayscaleMode::Desaturation => (r.max(g).max(b) + r.min(g).min(b)) / 2.0, + GrayscaleMode::Luma => crate::blend::lum([r, g, b]), + GrayscaleMode::Average => (r + g + b) / 3.0, + GrayscaleMode::Max => r.max(g).max(b), + GrayscaleMode::Min => r.min(g).min(b), + } + } +} diff --git a/crates/core/src/height_to_normal.rs b/crates/core/src/height_to_normal.rs new file mode 100644 index 00000000..4f72ae16 --- /dev/null +++ b/crates/core/src/height_to_normal.rs @@ -0,0 +1,80 @@ +//! Height To Normal's settings: the layer's Height turned into its Normal + +use serde::{Deserialize, Serialize}; + +/// A Height To Normal filter: the normal of the slopes of the layer's Height, over or in place of its Normal +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HeightToNormal { + /// Overwrite Existing Normal: the made normal replaces the Normal below instead of being laid over it + pub overwrite: bool, + /// Use World Units: the slope comes from Surface Size and Height Depth instead of Normal Intensity + pub world_units: bool, + /// Surface Size (cm): how wide a UV tile is on the model + pub surface_size: f32, + /// Height Depth (cm): how deep a height of 1 is + pub height_depth: f32, + /// Normal Intensity: how strongly the slopes tilt the normal without world units + pub intensity: f32, +} + +impl HeightToNormal { + /// A new Height To Normal + pub const LIBRARY: HeightToNormal = HeightToNormal { overwrite: true, world_units: true, surface_size: 300.0, height_depth: 16.0, intensity: 10.0 }; + + /// The smallest Surface Size: whole cm, so the reference's 0.1 rounds up to 1 + pub const MIN_SURFACE_SIZE: f32 = 1.0; + + /// The largest Surface Size (cm) + pub const MAX_SURFACE_SIZE: f32 = 1000.0; + + /// The largest Height Depth (cm) + pub const MAX_HEIGHT_DEPTH: f32 = 100.0; + + /// The largest Normal Intensity + pub const MAX_INTENSITY: f32 = 50.0; + + /// Height Depth over Surface Size a Normal Intensity of 1 tilts like (so the default 10 matches the default 16 cm over 300 cm) + const INTENSITY_UNIT: f32 = Self::LIBRARY.height_depth / Self::LIBRARY.surface_size / Self::LIBRARY.intensity; + + /// How much a change of height per texel tilts the normal at `res` texels across a UV tile (0 for hostile values) + pub fn strength(&self, res: u32) -> f32 { + let finite = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; + let per_tile = if self.world_units { + finite(self.height_depth, Self::MAX_HEIGHT_DEPTH) / finite(self.surface_size, Self::MAX_SURFACE_SIZE).max(Self::MIN_SURFACE_SIZE) + } else { + finite(self.intensity, Self::MAX_INTENSITY) * Self::INTENSITY_UNIT + }; + per_tile * res as f32 + } + + /// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down + pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] { + let strength = self.strength(res); + let (x, y) = (-gx * strength, gy * strength); + let length = (x * x + y * y + 1.0).sqrt(); + if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn world_units_and_normal_intensity_tilt_the_normal_up_the_slope() { + let filter = HeightToNormal::LIBRARY; + assert_eq!(filter.normal([0.0, 0.0], 2048), [0.0, 0.0, 1.0], "a flat height"); + let [x, y, z] = filter.normal([0.01, 0.0], 2048); + assert!(x < 0.0 && y == 0.0 && z > 0.0, "rising to the right faces left"); + let expected = 0.01 * 16.0 / 300.0 * 2048.0; + assert!((-x / z - expected).abs() < 1e-4, "16 cm over 300 cm"); + let intensity = HeightToNormal { world_units: false, ..filter }; + assert!((intensity.strength(2048) - filter.strength(2048)).abs() < 1e-3, "Normal Intensity 10 matches the world default"); + assert!(HeightToNormal { intensity: 20.0, ..intensity }.strength(2048) > intensity.strength(2048)); + assert!(HeightToNormal { height_depth: 32.0, ..filter }.strength(2048) > filter.strength(2048)); + assert_eq!(filter.normal([0.0, 0.01], 2048)[1].signum(), 1.0, "rising down the image faces up"); + let hostile = HeightToNormal { surface_size: f32::NAN, height_depth: f32::INFINITY, ..filter }; + assert!(hostile.normal([1.0, 1.0], 2048).iter().all(|v| v.is_finite())); + } +} diff --git a/crates/core/src/highpass_space.rs b/crates/core/src/highpass_space.rs new file mode 100644 index 00000000..7faa4f94 --- /dev/null +++ b/crates/core/src/highpass_space.rs @@ -0,0 +1,84 @@ +//! The color space a Highpass filter works in + +use serde::{Deserialize, Serialize}; + +use crate::gradient_input::{linear_to_srgb, srgb_to_linear}; + +/// ACEScg (AP1) to linear sRGB (Rec. 709) primaries, white point adapted (the published ACES matrix) +const AP1_TO_REC709: [[f32; 3]; 3] = [[1.705_05, -0.621_79, -0.083_26], [-0.130_26, 1.140_80, -0.010_55], [-0.024_00, -0.128_97, 1.152_97]]; + +/// Linear sRGB (Rec. 709) to ACEScg (AP1) primaries: the inverse of [`AP1_TO_REC709`] +const REC709_TO_AP1: [[f32; 3]; 3] = [[0.613_10, 0.339_52, 0.047_37], [0.070_19, 0.916_35, 0.013_45], [0.020_62, 0.109_57, 0.869_81]]; + +/// Where a Highpass takes its detail: in the working space (masks always), or in sRGB from linear sRGB or ACEScg colors +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum HighpassSpace { + /// The values as they are (what a Highpass did in projects saved before the Color Space) + #[default] + Working, + /// Colors read as linear sRGB, filtered sRGB encoded + SrgbFromLinear, + /// Colors read as ACEScg, filtered sRGB encoded + SrgbFromAcescg, +} + +impl HighpassSpace { + /// Every space, in the order a list shows them + pub const ALL: [HighpassSpace; 3] = [HighpassSpace::Working, HighpassSpace::SrgbFromLinear, HighpassSpace::SrgbFromAcescg]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + HighpassSpace::Working => "Working space / Mask", + HighpassSpace::SrgbFromLinear => "sRGB (from Linear sRGB)", + HighpassSpace::SrgbFromAcescg => "sRGB (from ACEScg)", + } + } + + /// The id `effect.set {colorSpace}` takes + pub fn id(self) -> &'static str { + match self { + HighpassSpace::Working => "working", + HighpassSpace::SrgbFromLinear => "srgbFromLinear", + HighpassSpace::SrgbFromAcescg => "srgbFromAcescg", + } + } + + /// Straight color `rgb` in this space + pub fn encode(self, rgb: [f32; 3]) -> [f32; 3] { + match self { + HighpassSpace::Working => rgb, + HighpassSpace::SrgbFromLinear => rgb.map(linear_to_srgb), + HighpassSpace::SrgbFromAcescg => times(&AP1_TO_REC709, rgb).map(linear_to_srgb), + } + } + + /// Straight color `rgb` of this space back in the working space + pub fn decode(self, rgb: [f32; 3]) -> [f32; 3] { + match self { + HighpassSpace::Working => rgb, + HighpassSpace::SrgbFromLinear => rgb.map(srgb_to_linear), + HighpassSpace::SrgbFromAcescg => times(&REC709_TO_AP1, rgb.map(srgb_to_linear)), + } + } +} + +/// Matrix `m` times column `v` +fn times(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] { + m.map(|row| row[0] * v[0] + row[1] * v[1] + row[2] * v[2]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_space_round_trips_a_color_in_its_gamut() { + for space in HighpassSpace::ALL { + let back = space.decode(space.encode([0.5, 0.4, 0.3])); + assert!(back.iter().zip([0.5, 0.4, 0.3]).all(|(a, b)| (a - b).abs() < 2e-3), "{space:?}: {back:?}"); + } + assert!((HighpassSpace::SrgbFromLinear.encode([0.214; 3])[0] - 0.5).abs() < 1e-2, "linear mid gray is sRGB 0.5"); + } +} diff --git a/crates/core/src/image_input.rs b/crates/core/src/image_input.rs new file mode 100644 index 00000000..d935074f --- /dev/null +++ b/crates/core/src/image_input.rs @@ -0,0 +1,88 @@ +//! An image a filter reads besides the stack it filters (its image inputs), as a source on the filter's effect + +use crate::{Filter, Source, SourceColorMode, TargetColorMode, WarpSourceMode}; + +/// One image input of a filter: the key its source is stored under on the effect, its name and the gray it reads until a source is set +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ImageInput { + pub id: &'static str, + pub label: &'static str, + /// The gray the input reads while no source is set (what the filter did before it had the input) + pub default: f32, + /// Added by a mode of the filter (shown under that mode), not one of its Image inputs + pub by_mode: bool, +} + +impl ImageInput { + /// Bevel Smooth's and Directional Distance's Distance Map: scales the distance per texel + pub const DISTANCE_MAP: ImageInput = ImageInput { id: "distanceMap", label: "Distance Map", default: 1.0, by_mode: false }; + + /// Warp's and Blur Slope's Custom Noise (Source Type Custom Noise): the source its texels move or read along; mid gray moves nothing + pub const CUSTOM_NOISE: ImageInput = ImageInput { id: "customNoise", label: "Custom Noise", default: 0.5, by_mode: true }; + + /// The Custom Input of Grayscale Conversion (the color it reads instead of the channel) and Anisotropic Kuwahara (its direction's gray); mid gray until set + pub const CUSTOM_INPUT: ImageInput = ImageInput { id: "customInput", label: "Custom Input", default: 0.5, by_mode: true }; + + /// Color Match's Input (Source Color Mode Input): the color each texel moves from; mid gray until set + pub const SOURCE_INPUT: ImageInput = ImageInput { id: "input", label: "Input", default: 0.5, by_mode: true }; + + /// Color Match's Image Input (Target Color Mode Image Input): the color each texel moves to; mid gray until set + pub const TARGET_INPUT: ImageInput = ImageInput { id: "imageInput", label: "Image Input", default: 0.5, by_mode: true }; + + /// The image inputs `filter` reads now (a mode's input only while that mode is on) + pub fn of(filter: &Filter) -> Vec { + Self::all(filter).iter().copied().filter(|input| input.is_on(filter)).collect() + } + + /// The input of `filter` stored under `id`, also while its mode is off + pub fn named(filter: &Filter, id: &str) -> Option { + Self::all(filter).iter().find(|input| input.id == id).copied() + } + + /// Every image input `filter` has, its modes' inputs also while those modes are off + fn all(filter: &Filter) -> &'static [ImageInput] { + match filter { + Filter::BevelSmooth(_) | Filter::DirectionalDistance(_) => &[Self::DISTANCE_MAP], + Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_) => &[Self::CUSTOM_NOISE], + Filter::GrayscaleConversion(_) | Filter::AnisotropicKuwahara(_) => &[Self::CUSTOM_INPUT], + Filter::ColorMatch(_) => &[Self::SOURCE_INPUT, Self::TARGET_INPUT], + _ => &[], + } + } + + /// Whether `filter` reads this input now: an input a mode adds only while that mode is on + fn is_on(&self, filter: &Filter) -> bool { + match filter { + Filter::SourceWarp(warp) => warp.source.mode == WarpSourceMode::CustomNoise, + Filter::SourceSlopeBlur(slope) => slope.source.mode == WarpSourceMode::CustomNoise, + Filter::GrayscaleConversion(conversion) => conversion.custom_input, + Filter::AnisotropicKuwahara(kuwahara) => kuwahara.custom_input, + Filter::ColorMatch(matcher) if *self == Self::SOURCE_INPUT => matcher.source_mode == SourceColorMode::Input, + Filter::ColorMatch(matcher) => matcher.target_mode == TargetColorMode::ImageInput, + _ => true, + } + } + + /// The source the input reads while none is set + pub fn default_source(&self) -> Source { + Source::Uniform([self.default; 3]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{BevelSmooth, SourceWarp, WarpSource}; + + #[test] + fn a_warp_has_its_custom_noise_only_in_that_source_mode() { + let warp = SourceWarp::LIBRARY; + assert!(ImageInput::of(&Filter::SourceWarp(warp)).is_empty()); + let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, ..warp.source }, ..warp }; + assert_eq!(ImageInput::of(&Filter::SourceWarp(custom)), vec![ImageInput::CUSTOM_NOISE]); + assert_eq!(ImageInput::named(&Filter::SourceWarp(warp), "customNoise"), Some(ImageInput::CUSTOM_NOISE), "kept while the mode is off"); + assert_eq!(ImageInput::of(&Filter::BevelSmooth(BevelSmooth::LIBRARY)), vec![ImageInput::DISTANCE_MAP]); + assert_eq!(ImageInput::named(&Filter::BevelSmooth(BevelSmooth::LIBRARY), "customNoise"), None); + assert_eq!(ImageInput::DISTANCE_MAP.default_source(), Source::Uniform([1.0; 3])); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 9d318149..aee8f43d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1,50 +1,47 @@ //! Layers, masks, effects and fill sources. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, CompareSource, ContentsOffset, DepthCulling, Projector, RandomizedSeed, ShapeCrop, lum}; +use crate::curve_preset::CurvePreset; +use crate::gradient_input::{GradientInput, ramp, shape_gray}; +use crate::{ + AnisotropicKuwahara, Backface, BakedMap, Bevel, BevelSmooth, BlendMode, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, DepthCulling, + DirectionalDistance, DirectionalLight, FillSymmetry, GrayscaleConversion, HeightToNormal, HighpassSpace, MaskOutline, Mirror, PbrValidate, Projector, + RandomizedSeed, ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, +}; mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; -mod filtering; mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; -mod sampling; -mod scale_mode; mod tile_blending; mod tile_generator; mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; -mod uv_transform; -mod uv_wrap; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; -pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; -pub use sampling::Sampling; -pub use scale_mode::ScaleMode; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; -pub use uv_transform::UvTransform; -pub use uv_wrap::UvWrap; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -1049,13 +1046,21 @@ impl Generator { pub enum Filter { Blur { radius: f32, + /// Reads past the texture's edges from its opposite side, so tiling textures stay seamless; off in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + wrap: bool, }, Sharpen { amount: f32, }, Invert, + /// Invert switched off: changes nothing until it is switched back on ([`Filter::Invert`]) + InvertOff, Threshold { level: f32, + /// Which side of `level` turns white; at or above it in projects saved before the modes + #[serde(default, skip_serializing_if = "ThresholdMode::is_default")] + mode: ThresholdMode, }, /// Hue/saturation/lightness shift (color channels; lightness only on grays and masks). /// `hue` is in turns, `saturation` and `lightness` in −1..1; all zero = unchanged. @@ -1063,25 +1068,76 @@ pub enum Filter { hue: f32, saturation: f32, lightness: f32, + /// Shifts in a perceptual color space (OKLCh), so a hue turn keeps the colors' lightness; plain HSL in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + perceptive: bool, }, /// Contrast around mid gray and a luminosity shift, both −1..1 (0 = unchanged). ContrastLuminosity { contrast: f32, luminosity: f32, }, + /// Contrast, luminosity (both −1..1, 0 = unchanged) and saturation (0..1, 0.5 = unchanged) for the shadows, midtones and highlights, each `[contrast, luminosity, saturation]`, weighted by the texel's lightness as [`Filter::ColorBalance`] + ColorCorrect { + shadows: [f32; 3], + midtones: [f32; 3], + highlights: [f32; 3], + }, /// Color offsets (−1..1 per component) weighted towards the shadows, midtones and highlights. ColorBalance { shadows: [f32; 3], midtones: [f32; 3], highlights: [f32; 3], }, - /// Luminance mapped through evenly spaced colors (linear RGB; scalars read their gray). + /// The texel's gray (after `input`) mapped through a ramp of colors (scalars read the ramp's gray) GradientMap { colors: Vec<[f32; 3]>, + /// Where each color sits on the ramp (0..1); evenly spaced in projects saved before + #[serde(default, skip_serializing_if = "Vec::is_empty")] + positions: Vec, + /// How many of `colors` the ramp uses (2..10), the rest kept for later; all of them in projects saved before + #[serde(default, skip_serializing_if = "Option::is_none")] + quantity: Option, + /// How a texel becomes the position it reads; luma, untouched, in projects saved before + #[serde(default, skip_serializing_if = "GradientInput::is_unchanged")] + input: GradientInput, + /// Blends neighbouring colors in linear RGB (off: in sRGB, as a color picker shows them); on in projects saved before + #[serde(default = "yes", skip_serializing_if = "is_true")] + linear: bool, + /// Shows the ramp itself across the texture (left to right) in place of the mapped values + #[serde(default, skip_serializing_if = "is_false")] + debug: bool, + }, + /// Values remapped through a preset curve, after balance, contrast and invert like a gradient's input + GradientCurve { + preset: CurvePreset, + invert: bool, + balance: f32, + contrast: f32, + }, + /// A color read off a gradient source at `position` across it (`vertical`: down it); the source is a uniform color + GradientDynamic { + vertical: bool, + position: f32, + color: [f32; 3], }, /// Quantize to `levels` steps (2..64). Posterize { levels: f32, + /// Steps the content's coverage too (Apply to Alpha); off in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + alpha: bool, + }, + /// The values between `min` and `max` eased from black to white (smoothstep); outside them black or white + Smoothstep { + min: f32, + max: f32, + }, + /// Heights flipped (`invert`), scaled by `multiply` and raised by `offset` around mid gray + HeightAdjust { + invert: bool, + offset: f32, + multiply: f32, }, /// Keep values within `min..max`. Clamp { @@ -1093,6 +1149,9 @@ pub enum Filter { HistogramScan { position: f32, contrast: f32, + /// Scans from the other end: the position read as 1 − position (Invert Position); off in projects saved before it + #[serde(default, skip_serializing_if = "is_false")] + invert_position: bool, }, /// The values squeezed towards `position`: `range` 1 keeps them, 0 sets them all to it. HistogramRange { @@ -1103,68 +1162,147 @@ pub enum Filter { HistogramShift { offset: f32, }, - /// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K, - /// `scale` noise features per UV unit. + /// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K, `scale` noise features per UV unit (projects saved before the warp modes; new ones are [`Filter::SourceWarp`]) Warp { intensity: f32, scale: f32, seed: u32, + /// Divides `intensity` (1, 10, 100 or 1000) for fine displacements; 1 in projects saved before it + #[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")] + divider: u16, }, /// Blur along one direction: `radius` in texels at 2K, `angle` in degrees. DirectionalBlur { radius: f32, angle: f32, }, - /// Smear values downhill along a noise height field ("slope blur"): `radius` in texels at - /// 2K, `scale` noise features per UV unit. + /// Values smeared downhill along a noise height field: `radius` in texels at 2K, `scale` noise features per UV unit (projects saved before its source settings) SlopeBlur { radius: f32, scale: f32, seed: u32, + /// Divides `radius` like [`Filter::Warp`]'s divider + #[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")] + divider: u16, }, /// The detail finer than `radius` (texels at 2K) around mid gray: the value minus its blur. HighPass { radius: f32, + /// Color Space: colors filtered in sRGB from linear sRGB or ACEScg + #[serde(default, skip_serializing_if = "is_working_space")] + space: HighpassSpace, + /// Apply To Alpha: the content's coverage takes its detail too + #[serde(default, skip_serializing_if = "is_false")] + alpha: bool, }, /// Gradient magnitude across `width` texels at 2K: edges light, flat areas black. EdgeDetect { width: f32, }, - /// Like [`Filter::Warp`], but every texel moves along one direction (`angle` in degrees). + /// Like [`Filter::Warp`], but every texel moves along one direction (`angle` in degrees; projects saved before the warp modes) DirectionalWarp { intensity: f32, angle: f32, scale: f32, seed: u32, + /// Divides `intensity` like [`Filter::Warp`]'s divider + #[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")] + divider: u16, }, - /// Colors to their luminance (scalars and masks unchanged). + /// Colors to their luminance (scalars and masks unchanged): projects saved before Grayscale Conversion's settings Grayscale, + /// The gray of every channel (or of its Custom Input) by its mode and weights, balanced, contrasted and maybe inverted + GrayscaleConversion(GrayscaleConversion), /// Flip the green component of normal maps (OpenGL ↔ DirectX); other channels unchanged. NormalInvert, /// Shapes rounded off at their edges: values ramp up from 0 at a shape's edge to their own /// level over about `width` texels at 2K (a mask's or height's bevel). Bevel { width: f32, + /// Reads past the texture's edges like [`Filter::Blur`]'s wrap + #[serde(default, skip_serializing_if = "is_false")] + wrap: bool, }, - /// Square cells `size` texels at 2K across, each the value at its center. + /// Shapes sloped at their edge, inwards or outwards over a share of the UV tile (projects saved before keep [`Filter::Bevel`]) + DistanceBevel(Bevel), + /// Texels read from where a source sends them, in one of the warp modes (projects saved before keep [`Filter::Warp`] and [`Filter::DirectionalWarp`]) + SourceWarp(SourceWarp), + /// Values read downhill along a source's slope, blended (projects saved before keep [`Filter::SlopeBlur`]) + SourceSlopeBlur(SourceSlopeBlur), + /// A smooth ramp from the shapes' edge, outwards, inwards or across it + BevelSmooth(BevelSmooth), + /// A trail fading away from the shapes in one direction + DirectionalDistance(DirectionalDistance), + /// One side of an axis (or one quarter) of each UV tile copied over the rest + Mirror(Mirror), + /// Each UV tile's content scaled, turned, moved and flipped, repeating or not + Transform(TileTransform), + /// A band along the edge where values cross a threshold + MaskOutline(MaskOutline), + /// Square cells `size` texels at 2K across, each the value at its center (Pixelate; see [`Filter::pixels_amount`]) Mosaic { size: f32, + /// Steps the content's coverage into the cells too (Apply To Alpha); on in projects saved before the switch + #[serde(default = "yes", skip_serializing_if = "is_true")] + alpha: bool, }, - /// Adds a blur of the values (`radius` texels at 2K) times `amount`: light bleeds around - /// bright areas. + /// Painterly smoothing along the strokes' direction: each texel the mean of the calmest sector around it + AnisotropicKuwahara(AnisotropicKuwahara), + /// Base colors outside the physically plausible ranges shown in red (reads the layer's metal) + PbrValidate(PbrValidate), + /// Height To Normal: the layer's Height turned into its Normal + HeightToNormal(HeightToNormal), + /// Color Match: the colors moved so a source color (the texture's mean by default) lands on a target color + ColorMatch(ColorMatch), + /// Stair-stepped edges smoothed by blending across them (FXAA) + Fxaa { + /// Smooths the content's coverage too (Affect Alpha Channel) + #[serde(default, skip_serializing_if = "is_false")] + alpha: bool, + }, + /// Adds a blur of the values (`radius` texels at 2K) times `amount`: light bleeds around bright areas (projects saved before the halo glow below) Glow { radius: f32, amount: f32, }, - /// Lighting painted into the base color: `ambient` (times the baked ambient occlusion by - /// `occlusion`) plus a directional light of strength `light` from `azimuth` around +Y - /// (degrees from +Z) and `elevation` above the horizon (degrees), on the mesh's normals. + /// A halo in `color` around the shapes (content coverage, mask values), inside them below 0 `width`; see [`Filter::HALO_REACH`] + HaloGlow { + /// Laid on a mask as white rather than the color's luminance (Used on a Mask) + on_mask: bool, + /// Ends sharper (Mode Precise) instead of fading out (Soft) + precise: bool, + width: f32, + spread: f32, + opacity: f32, + color: [f32; 3], + }, + /// The shapes in `color` laid under them, moved `distance` of a UV tile away from a light at `angle` and blurred over `size` + DropShadow { + angle: f32, + distance: f32, + size: f32, + spread: f32, + opacity: f32, + color: [f32; 3], + }, + /// Lighting painted into the base color: `ambient` (times the baked ambient occlusion by `occlusion`) plus a directional light of strength `light` from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), on the mesh's normals. `stylized` adds sky colors, more lights, cavity, edges and highlights (Baked Lighting Stylized); projects saved before have none and light as they did BakedLighting { azimuth: f32, elevation: f32, light: f32, ambient: f32, occlusion: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + stylized: Option>, + }, + /// The base color lit by the viewport environment (its diffuse light), turned `horizontal` and tilted `vertical` degrees, brighter by 2^`exposure`, on the mesh's normals tilted by the baked height (`height_intensity`) and darkened by the baked ambient occlusion (`ambient_occlusion` on the diffuse light, `specular_occlusion` on the reflections) + EnvironmentLighting { + horizontal: f32, + vertical: f32, + exposure: f32, + height_intensity: f32, + ambient_occlusion: f32, + specular_occlusion: f32, }, /// Colors near `from` (within `tolerance`, fading out over `softness`, as RGB distance /// 0..1) shifted by `to − from`, so their shading and texture stay (linear RGB). @@ -1174,13 +1312,78 @@ pub enum Filter { tolerance: f32, softness: f32, }, + /// No filter picked yet: changes nothing + Empty, +} + +/// The divider of projects saved before intensities had one +fn unit_divider() -> u16 { + 1 } /// Whether a switch is on, its default where it defaults to on (not saved then) +/// Serde default of a switch that was on in projects saved before it existed +fn yes() -> bool { + true +} + +/// Whether a switch is on, its default where it defaults to [`yes`] (not saved then) fn is_true(on: &bool) -> bool { *on } +/// Whether a high pass runs in the working color space, its default (not saved then) +fn is_working_space(space: &HighpassSpace) -> bool { + *space == HighpassSpace::Working +} + +/// Whether a switch is off, its default (not saved then) +fn is_false(on: &bool) -> bool { + !*on +} + +/// Whether `divider` leaves its intensity as it is (not saved then) +fn is_unit_divider(divider: &u16) -> bool { + *divider == 1 +} + +/// The fewest and most steps a posterize keeps +pub const POSTERIZE_LEVELS_MIN: f32 = 2.0; +pub const POSTERIZE_LEVELS_MAX: f32 = 64.0; + +/// Filter sizes are given in texels at 2K, as in the reference workflow +pub const SIZE_REFERENCE_RES: f32 = 2048.0; + +/// `x` (0..1) rounded to `levels` steps (2..64) from black to white +pub fn posterize(x: f32, levels: f32) -> f32 { + let steps = (levels.clamp(POSTERIZE_LEVELS_MIN, POSTERIZE_LEVELS_MAX).round() - 1.0).max(1.0); + let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }; + (x * steps).round() / steps +} + +/// Bounds of a smoothstep closer than this are a step: easing over a narrower span would divide by almost nothing +const MIN_SMOOTHSTEP_SPAN: f32 = 1e-6; + +/// 0 at or below `min`, 1 at or above `max`, eased between them (swapped bounds are read in order; equal bounds are a step) +pub(crate) fn smoothstep(min: f32, max: f32, x: f32) -> f32 { + let (low, high) = (finite_or(min.min(max), 0.0), finite_or(min.max(max), 1.0)); + if !x.is_finite() { + return 0.0; + } + + if high - low <= MIN_SMOOTHSTEP_SPAN { + return if x >= high { 1.0 } else { 0.0 }; + } + + let t = ((x - low) / (high - low)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// `v`, or `fallback` where it is not a number +fn finite_or(v: f32, fallback: f32) -> f32 { + if v.is_finite() { v } else { fallback } +} + /// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1. fn shift_unit(x: f32, amount: f32) -> f32 { let a = amount.clamp(-1.0, 1.0); @@ -1229,6 +1432,22 @@ pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [ [hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)] } +/// Smooth weights of the shadows, midtones and highlights at lightness `l` (0..1), summing to 1: shadows fade out and highlights in with lightness +fn tone_weights(l: f32) -> (f32, f32, f32) { + ((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l) +} + +/// [`hsl_adjust`] in OKLCh: the hue turns and the chroma scales (`saturation` −1 = gray, 1 = twice as vivid) at the color's own perceived lightness, which `lightness` then pushes towards white or black (linear 0..1 colors) +pub fn perceptive_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [f32; 3] { + let clean = |x: f32| if x.is_finite() { x } else { 0.0 }; + let [l, a, b] = crate::oklab::from_linear(rgb.map(|v| clean(v).clamp(0.0, 1.0))); + let (sin, cos) = (clean(hue) * std::f32::consts::TAU).sin_cos(); + let chroma = 1.0 + clean(saturation).clamp(-1.0, 1.0); + let (a, b) = ((a * cos - b * sin) * chroma, (a * sin + b * cos) * chroma); + let l = shift_unit(l.clamp(0.0, 1.0), clean(lightness)); + crate::oklab::to_linear([l, a, b]).map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }) +} + /// Apply a 0..1 function to each component of a channel value: signed values map through /// 0..1, normals are left alone. pub fn per_unit(kind: ChannelKind, v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] { @@ -1252,6 +1471,72 @@ pub fn gradient(colors: &[[f32; 3]], t: f32) -> Option<[f32; 3]> { } impl Filter { + /// The most Baked Lighting Environment's Exposure brightens or darkens, in stops + pub const ENVIRONMENT_EXPOSURE_STOPS: f32 = 5.0; + + /// The choices of an intensity's divider + pub const DIVIDERS: [u16; 4] = [1, 10, 100, 1000]; + + /// The most colors a gradient's Color Quantity uses + pub const MAX_GRADIENT_COLORS: u8 = 10; + + /// Texels at 2K a Blur Intensity (Blur, Blur Directional) of 1 reaches + pub const BLUR_INTENSITY: f32 = 16.0; + + /// Texels at 2K a halo glow's Width or a drop shadow's Size of 1 reaches + pub const HALO_REACH: f32 = 128.0; + + /// A drop shadow is cast at most this share of a UV tile away, either way + pub const SHADOW_DISTANCE_MAX: f32 = 0.5; + + /// The noise features per UV unit a noise-driven warp or slope blur reads, at least and at most + pub const NOISE_SCALE_MIN: f32 = 0.01; + pub const NOISE_SCALE_MAX: f32 = 1000.0; + + /// A gradient as projects saved before the Input Transformation read it: `colors` evenly spaced, luma, linear blending + pub fn even_gradient(colors: Vec<[f32; 3]>) -> Filter { + Filter::GradientMap { colors, positions: Vec::new(), quantity: None, input: GradientInput::default(), linear: true, debug: false } + } + + /// Histogram Shift's Position (0..1) for its `offset`: a shift back by 1 − position, so 1 shifts nothing (offsets above 0 saved before the Position read as themselves, the same shift but for white and black) + pub fn shift_position(offset: f32) -> f32 { + let offset = if offset.is_finite() { offset.clamp(-1.0, 1.0) } else { 0.0 }; + if offset <= 0.0 { offset + 1.0 } else { offset } + } + + /// The Histogram Shift offset a Position (0..1) sets (see [`Filter::shift_position`]) + pub fn shift_offset(position: f32) -> f32 { + let position = if position.is_finite() { position.clamp(0.0, 1.0) } else { 1.0 }; + position - 1.0 + } + + /// Pixelate's Pixels Amount (cells across a UV tile) for a cell `size` in texels at 2K + pub fn pixels_amount(size: f32) -> f32 { + SIZE_REFERENCE_RES / if size.is_finite() { size.max(1.0) } else { SIZE_REFERENCE_RES } + } + + /// The cell size in texels at 2K that a Pixels Amount (cells across a UV tile) sets + pub fn pixel_size(amount: f32) -> f32 { + SIZE_REFERENCE_RES / if amount.is_finite() { amount.clamp(1.0, SIZE_REFERENCE_RES) } else { 1.0 } + } + + /// The colors a gradient's ramp uses: the first Color Quantity of them (all of them where it has none) + pub fn ramp_colors(&self) -> &[[f32; 3]] { + match self { + Filter::GradientMap { colors, quantity, .. } => colors.get(..quantity.map_or(colors.len(), usize::from).min(colors.len())).unwrap_or(colors), + _ => &[], + } + } + + /// A gradient's color at ramp position `t` (None for other filters and an empty ramp) + pub fn ramp_at(&self, t: f32) -> Option<[f32; 3]> { + let Filter::GradientMap { positions, linear, .. } = self else { return None }; + let colors = self.ramp_colors(); + + // Evenly spaced linear ramps take the path projects saved before took, so they render bit for bit as before + if positions.is_empty() && *linear { gradient(colors, t) } else { ramp(colors, positions, *linear, t) } + } + /// Whether the filter reads neighbouring texels (the compositor runs it over a region). pub fn is_neighbourhood(&self) -> bool { matches!( @@ -1266,66 +1551,118 @@ impl Filter { | Filter::DirectionalWarp { .. } | Filter::Bevel { .. } | Filter::Mosaic { .. } + | Filter::Fxaa { .. } + | Filter::AnisotropicKuwahara(_) + | Filter::HeightToNormal(_) + | Filter::ColorMatch(_) + | Filter::DistanceBevel(_) + | Filter::SourceWarp(_) + | Filter::SourceSlopeBlur(_) + | Filter::BevelSmooth(_) + | Filter::DirectionalDistance(_) + | Filter::Mirror(_) + | Filter::Transform(_) + | Filter::MaskOutline(_) | Filter::Glow { .. } + | Filter::HaloGlow { .. } + | Filter::DropShadow { .. } ) } /// The filter applied to one value of a channel of `kind` (masks are scalars). None for /// neighbourhood filters and where it changes nothing (an empty gradient). pub fn point(&self, kind: ChannelKind, v: [f32; 3]) -> Option<[f32; 3]> { - let unit = |x: f32| if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }; + // Histogram Scan's narrowest soft cut, so near full contrast stays a finite slope + const SCAN_MIN_WIDTH: f32 = 1e-3; + + // Replace Color's least softness, so a hard edge divides by no zero + const REPLACE_MIN_SOFTNESS: f32 = 1e-6; + Some(match self { Filter::Invert => per_unit(kind, v, |x| 1.0 - x), - Filter::Threshold { level } => per_unit(kind, v, |x| if x >= *level { 1.0 } else { 0.0 }), - Filter::Hsl { hue, saturation, lightness } => match kind { + Filter::Threshold { level, mode } => per_unit(kind, v, |x| if mode.passes(x, *level) { 1.0 } else { 0.0 }), + Filter::Hsl { hue, saturation, lightness, perceptive } => match kind { + ChannelKind::Color if *perceptive => perceptive_adjust(v, *hue, *saturation, *lightness), ChannelKind::Color => hsl_adjust(v, *hue, *saturation, *lightness), _ => per_unit(kind, v, |x| hsl_adjust([x; 3], 0.0, 0.0, *lightness)[0]), }, Filter::ContrastLuminosity { contrast, luminosity } => { - let k = 1.0 + contrast.clamp(-1.0, 1.0); - per_unit(kind, v, |x| unit((x - 0.5) * k + 0.5 + luminosity)) + let slope = 1.0 + contrast.clamp(-1.0, 1.0); + per_unit(kind, v, |x| finite_unit((x - 0.5) * slope + 0.5 + luminosity)) + } + Filter::ColorCorrect { shadows, midtones, highlights } => { + // [contrast, luminosity, saturation] at the texel's lightness, weighted as color balance + let at = |lightness: f32| -> [f32; 3] { + let (in_shadows, in_midtones, in_highlights) = tone_weights(finite_unit(lightness)); + std::array::from_fn(|k| shadows[k] * in_shadows + midtones[k] * in_midtones + highlights[k] * in_highlights) + }; + let correct = |x: f32, [contrast, luminosity, _]: [f32; 3]| (x - 0.5) * (1.0 + contrast.clamp(-1.0, 1.0)) + 0.5 + luminosity.clamp(-1.0, 1.0); + match kind { + ChannelKind::Color => { + let tone = at(lum(v)); + let corrected = v.map(|x| correct(x, tone)); + let gray = lum(corrected); + let gain = 2.0 * tone[2].clamp(0.0, 1.0); + corrected.map(|x| finite_unit(gray + (x - gray) * gain)) + } + _ => per_unit(kind, v, |x| finite_unit(correct(x, at(x)))), + } } Filter::ColorBalance { shadows, midtones, highlights } => { - // Smooth weights summing to 1: shadows fade out and highlights in with lightness. - let weights = |l: f32| { - let l = unit(l); - ((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l) - }; - let shift = |k: usize, l: f32| { - let (s, m, h) = weights(l); - shadows.get(k).copied().unwrap_or(0.0) * s + midtones.get(k).copied().unwrap_or(0.0) * m + highlights.get(k).copied().unwrap_or(0.0) * h + let shift = |component: usize, lightness: f32| { + let (in_shadows, in_midtones, in_highlights) = tone_weights(finite_unit(lightness)); + shadows.get(component).copied().unwrap_or(0.0) * in_shadows + + midtones.get(component).copied().unwrap_or(0.0) * in_midtones + + highlights.get(component).copied().unwrap_or(0.0) * in_highlights }; match kind { ChannelKind::Color => { - let l = lum(v); - std::array::from_fn(|k| unit(v[k] + shift(k, l))) + let lightness = lum(v); + std::array::from_fn(|k| finite_unit(v[k] + shift(k, lightness))) } - _ => per_unit(kind, v, |x| unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)), + _ => per_unit(kind, v, |x| finite_unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)), } } - Filter::GradientMap { colors } => match kind { - ChannelKind::Color => gradient(colors, lum(v))?, - _ => per_unit(kind, v, |x| gradient(colors, x).map_or(x, lum)), + Filter::GradientMap { input, .. } => match kind { + ChannelKind::Color => self.ramp_at(input.shape(input.mode.gray(v)))?, + // A height reads the ramp at its 0..1 place, as projects saved before did + _ => per_unit(kind, v, |x| self.ramp_at(input.shape(x)).map_or(x, lum)), }, - Filter::Posterize { levels } => { - let steps = (levels.clamp(2.0, 64.0).round() - 1.0).max(1.0); - per_unit(kind, v, |x| (unit(x) * steps).round() / steps) + Filter::GradientCurve { preset, invert, balance, contrast } => per_unit(kind, v, |x| preset.at(shape_gray(x, *balance, *contrast, *invert))), + Filter::GradientDynamic { color, .. } => match kind { + ChannelKind::Color => color.map(finite_unit), + _ => per_unit(kind, v, |_| finite_unit(lum(*color))), + }, + Filter::Posterize { levels, .. } => per_unit(kind, v, |x| posterize(x, *levels)), + Filter::Smoothstep { min, max } => per_unit(kind, v, |x| smoothstep(*min, *max, x)), + Filter::HeightAdjust { invert, offset, multiply } => { + let (offset, multiply) = (finite_or(*offset, 0.0), finite_or(*multiply, 1.0)); + per_unit(kind, v, |x| { + let x = if *invert { 1.0 - x } else { x }; + finite_unit((x - 0.5) * multiply + 0.5 + offset) + }) } + Filter::InvertOff => v, Filter::Clamp { min, max } => { - let (lo, hi) = (min.min(*max), min.max(*max)); - per_unit(kind, v, |x| x.max(lo).min(hi)) + let (low, high) = (min.min(*max), min.max(*max)); + per_unit(kind, v, |x| x.max(low).min(high)) } - // Full contrast is a threshold: the position itself goes to white. - Filter::HistogramScan { position, contrast } if *contrast >= 1.0 => per_unit(kind, v, |x| if x >= *position { 1.0 } else { 0.0 }), - Filter::HistogramScan { position, contrast } => { - let width = (1.0 - contrast.clamp(0.0, 1.0)).max(1e-3); - per_unit(kind, v, |x| unit((x - position) / width + 0.5)) + + // Full contrast is a threshold: the position itself goes to white + Filter::HistogramScan { position, contrast, invert_position } => { + let position = if *invert_position { 1.0 - position } else { *position }; + if *contrast >= 1.0 { + per_unit(kind, v, |x| if x >= position { 1.0 } else { 0.0 }) + } else { + let width = (1.0 - contrast.clamp(0.0, 1.0)).max(SCAN_MIN_WIDTH); + per_unit(kind, v, |x| finite_unit((x - position) / width + 0.5)) + } } - Filter::HistogramRange { range, position } => per_unit(kind, v, |x| unit(position + (x - position) * range)), + Filter::HistogramRange { range, position } => per_unit(kind, v, |x| finite_unit(position + (x - position) * range)), Filter::HistogramShift { offset } => per_unit(kind, v, |x| { - // Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black. - let y = unit(x) + offset.clamp(-1.0, 1.0); - unit(if y > 1.0 { + // Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black + let y = finite_unit(x) + offset.clamp(-1.0, 1.0); + finite_unit(if y > 1.0 { y - 1.0 } else if y < 0.0 { y + 1.0 @@ -1337,23 +1674,26 @@ impl Filter { ChannelKind::Color => [lum(v); 3], _ => v, }, + // Read opaque here: the compositor passes the content's coverage (and a Custom Input) through `GrayscaleConversion::channel_value` + Filter::GrayscaleConversion(conversion) => conversion.channel_value(kind, v, None, 1.0), Filter::NormalInvert => match kind { ChannelKind::NormalMap => [v[0], 1.0 - v[1], v[2]], _ => v, }, Filter::ReplaceColor { from, to, tolerance, softness } => match kind { ChannelKind::Color => { - let d = ((v[0] - from[0]).powi(2) + (v[1] - from[1]).powi(2) + (v[2] - from[2]).powi(2)).sqrt() / 3f32.sqrt(); - let (t, s) = (tolerance.clamp(0.0, 1.0), softness.clamp(0.0, 1.0)); - let w = if d <= t { + // How far the color is from `from`, 1 across the whole cube + let distance = ((v[0] - from[0]).powi(2) + (v[1] - from[1]).powi(2) + (v[2] - from[2]).powi(2)).sqrt() / 3f32.sqrt(); + let (tolerance, softness) = (tolerance.clamp(0.0, 1.0), softness.clamp(0.0, 1.0)); + let weight = if distance <= tolerance { 1.0 - } else if d >= t + s { + } else if distance >= tolerance + softness { 0.0 } else { - let x = 1.0 - (d - t) / s.max(1e-6); - x * x * (3.0 - 2.0 * x) + let closeness = 1.0 - (distance - tolerance) / softness.max(REPLACE_MIN_SOFTNESS); + closeness * closeness * (3.0 - 2.0 * closeness) }; - std::array::from_fn(|k| unit(v[k] + (to[k] - from[k]) * w)) + std::array::from_fn(|k| finite_unit(v[k] + (to[k] - from[k]) * weight)) } _ => v, }, @@ -1367,8 +1707,25 @@ impl Filter { | Filter::DirectionalWarp { .. } | Filter::Bevel { .. } | Filter::Mosaic { .. } + | Filter::Fxaa { .. } + | Filter::AnisotropicKuwahara(_) + | Filter::PbrValidate(_) + | Filter::HeightToNormal(_) + | Filter::ColorMatch(_) + | Filter::DistanceBevel(_) + | Filter::SourceWarp(_) + | Filter::SourceSlopeBlur(_) + | Filter::BevelSmooth(_) + | Filter::DirectionalDistance(_) + | Filter::Mirror(_) + | Filter::Transform(_) + | Filter::MaskOutline(_) | Filter::Glow { .. } - | Filter::BakedLighting { .. } => return None, + | Filter::HaloGlow { .. } + | Filter::DropShadow { .. } + | Filter::BakedLighting { .. } + | Filter::EnvironmentLighting { .. } + | Filter::Empty => return None, }) } @@ -1376,43 +1733,97 @@ impl Filter { match self { Filter::Blur { .. } => "Blur", Filter::Sharpen { .. } => "Sharpen", - Filter::Invert => "Invert", + Filter::Invert | Filter::InvertOff => "Invert", Filter::Threshold { .. } => "Threshold", Filter::Hsl { .. } => "HSL Perceptive", - Filter::ContrastLuminosity { .. } => "Contrast/Luminosity", + Filter::ContrastLuminosity { .. } => "Contrast Luminosity", Filter::ColorBalance { .. } => "Color Balance", - Filter::GradientMap { .. } => "Gradient Map", + Filter::ColorCorrect { .. } => "Color Correct", + Filter::GradientMap { .. } => "Gradient", + Filter::GradientCurve { .. } => "Gradient Curve", + Filter::GradientDynamic { .. } => "Gradient Dynamic", Filter::Posterize { .. } => "Posterize", + Filter::Smoothstep { .. } => "Smoothstep", + Filter::HeightAdjust { .. } => "Height Adjust", Filter::Clamp { .. } => "Clamp", Filter::HistogramScan { .. } => "Histogram Scan", Filter::HistogramRange { .. } => "Histogram Range", Filter::HistogramShift { .. } => "Histogram Shift", Filter::Warp { .. } => "Warp", Filter::DirectionalBlur { .. } => "Blur Directional", - Filter::SlopeBlur { .. } => "Slope Blur", - Filter::HighPass { .. } => "High Pass", + Filter::SlopeBlur { .. } => "Blur Slope", + Filter::HighPass { .. } => "Highpass", Filter::EdgeDetect { .. } => "Edge Detect", Filter::DirectionalWarp { .. } => "Warp Directional", - Filter::Grayscale => "Grayscale", + Filter::Grayscale | Filter::GrayscaleConversion(_) => "Grayscale Conversion", Filter::NormalInvert => "Normal Invert", Filter::Bevel { .. } => "Bevel", - Filter::Mosaic { .. } => "Mosaic", - Filter::Glow { .. } => "Glow", - Filter::BakedLighting { .. } => "Baked Lighting", + Filter::Mosaic { .. } => "Pixelate", + Filter::Fxaa { .. } => "FXAA (Anti-aliasing)", + Filter::AnisotropicKuwahara(_) => "Anisotropic Kuwahara", + Filter::PbrValidate(_) => "PBR Validate (Metallic Roughness)", + Filter::HeightToNormal(_) => "Height To Normal", + Filter::ColorMatch(_) => "Color Match", + Filter::DistanceBevel(_) => "Bevel", + Filter::SourceWarp(_) => "Warp", + Filter::SourceSlopeBlur(_) => "Blur Slope", + Filter::BevelSmooth(_) => "Bevel Smooth", + Filter::DirectionalDistance(_) => "Directional Distance", + Filter::Mirror(_) => "Mirror", + Filter::Transform(_) => "Transform", + Filter::MaskOutline(_) => "Mask Outline", + Filter::Glow { .. } | Filter::HaloGlow { .. } => "Glow", + Filter::DropShadow { .. } => "Drop Shadow", + Filter::BakedLighting { .. } => "Baked Lighting Stylized", + Filter::EnvironmentLighting { .. } => "Baked Lighting Environment", Filter::ReplaceColor { .. } => "Replace Color", + Filter::Empty => "Filter (empty)", } } - /// Baked lighting's factor on the base color of a surface facing `nrm` (world space) with + /// The label this filter had before it took the reference workflow's name: effects named after it still follow a swap + pub fn former_label(&self) -> Option<&'static str> { + match self { + Filter::ContrastLuminosity { .. } => Some("Contrast/Luminosity"), + Filter::SlopeBlur { .. } | Filter::SourceSlopeBlur(_) => Some("Slope Blur"), + Filter::HighPass { .. } => Some("High Pass"), + Filter::Mosaic { .. } => Some("Mosaic"), + Filter::Grayscale => Some("Grayscale"), + Filter::GradientMap { .. } => Some("Gradient Map"), + Filter::BakedLighting { .. } => Some("Baked Lighting"), + _ => None, + } + } + + /// Baked lighting's factor on the base color of a surface facing `normal` (world space) with /// ambient occlusion `ao` (None for other filters). - pub fn baked_light(&self, nrm: [f32; 3], ao: f32) -> Option { - let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } = self else { return None }; - let (sa, ca) = azimuth.to_radians().sin_cos(); - let (se, ce) = elevation.to_radians().sin_cos(); - let facing = (nrm[0] * ce * sa + nrm[1] * se + nrm[2] * ce * ca).max(0.0); + pub fn baked_light(&self, normal: [f32; 3], ao: f32) -> Option { + let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, .. } = self else { return None }; + let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos(); + let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos(); + + // Multiplied in this order so saved projects light exactly as before + let facing = (normal[0] * cos_elevation * sin_azimuth + normal[1] * sin_elevation + normal[2] * cos_elevation * cos_azimuth).max(0.0); let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 }; - let k = ambient * (1.0 + (ao - 1.0) * occlusion.clamp(0.0, 1.0)) + light * facing; - Some(if k.is_finite() { k.max(0.0) } else { 1.0 }) + let factor = ambient * (1.0 + (ao - 1.0) * occlusion.clamp(0.0, 1.0)) + light * facing; + Some(if factor.is_finite() { factor.max(0.0) } else { 1.0 }) + } + + /// The channels a new content effect of the filter starts with on (None: all of them) + pub fn starts_on(&self) -> Option<&'static [Channel]> { + match self { + // PBR Validate reads the metal but changes only the base color, so its Metal pill would do nothing + Filter::BakedLighting { .. } | Filter::EnvironmentLighting { .. } | Filter::ColorMatch(_) | Filter::PbrValidate(_) => Some(&[Channel::BaseColor]), + Filter::HeightToNormal(_) => Some(&[Channel::Normal]), + _ => None, + } + } + + /// Baked Lighting Stylized's settings with its sun and sky (None for other filters and a Baked Lighting saved before them) + pub fn stylized_lighting(&self) -> Option<(&StylizedLighting, SunAndSky)> { + let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, stylized: Some(stylized) } = self else { return None }; + let sun = DirectionalLight { azimuth: *azimuth, elevation: *elevation, intensity: *light, color: stylized.sun_color }; + Some((stylized, SunAndSky { sun, sky_intensity: *ambient, diffuse_ao: *occlusion })) } } @@ -1647,6 +2058,7 @@ impl Layer { _ => false, }; fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.kind.reads(None)) + fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.reads(None)) } /// Whether the layer's result depends on the stack below it: it reads an anchor point, or its mask compares channels of the stack @@ -1666,12 +2078,44 @@ pub struct Effect { /// A content effect's channels that blend apart from `blend` and `opacity` (none in projects saved before they existed) #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub channel_blends: BTreeMap, + /// A content effect's channels it leaves as they are (none in projects saved before they could be switched off) + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub off_channels: BTreeSet, + /// A filter effect's image inputs set to a source, by [`crate::ImageInput`] id (the others read their default gray) + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub inputs: BTreeMap, } impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { // Generators and fills that build a mask usually add on top of the background Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0, channel_blends: BTreeMap::new() } + Effect { + id, + name: kind.name().to_string(), + visible: true, + kind, + blend: BlendMode::Normal, + opacity: 1.0, + channel_blends: BTreeMap::new(), + off_channels: BTreeSet::new(), + inputs: BTreeMap::new(), + } + } + + /// The image resources the effect reads: its kind's ([`EffectKind::images_read`]) and its filter image inputs' + pub fn images_read(&self) -> impl Iterator { + self.kind.images_read().chain(self.inputs.values().flat_map(Source::images)) + } + + /// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None) + pub fn reads(&self, anchor: Option) -> bool { + self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor)) + } + + /// The source image input `input` reads: the one set on the effect, else its default gray + pub fn input(&self, input: &crate::ImageInput) -> Source { + self.inputs.get(input.id).cloned().unwrap_or_else(|| input.default_source()) } /// How the effect blends on `channel` of its layer's content, or on its mask (`None`) @@ -1679,6 +2123,15 @@ impl Effect { let shared = ChannelBlend { mode: self.blend, opacity: self.opacity }; channel.and_then(|channel| self.channel_blends.get(&channel).copied()).unwrap_or(shared) } + + /// How the effect lays onto `channel` when composited: [`Self::blend_of`], at no opacity on a channel it is switched off for + pub fn applied_blend(&self, channel: Option) -> ChannelBlend { + let blend = self.blend_of(channel); + match channel { + Some(channel) if self.off_channels.contains(&channel) => ChannelBlend { opacity: 0.0, ..blend }, + _ => blend, + } + } } #[cfg(test)] @@ -1717,11 +2170,15 @@ mod tests { #[test] fn a_colour_selection_id_map_is_reported_as_used() { + fn a_colour_selection_id_map_and_a_filter_image_input_are_reported_as_used() { let mut selection = crate::ColorSelection::new(Vec::new(), 0.0); selection.id_map = Some("id.png".into()); let effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); + let mut effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); + effect.inputs.insert("mask".into(), Source::image("input.png")); assert_eq!(effect.kind.images_read().collect::>(), vec!["id.png"]); + assert_eq!(effect.images_read().collect::>(), vec!["id.png", "input.png"]); } #[test] @@ -1908,6 +2365,20 @@ mod tests { assert!(hsl_adjust([f32::NAN, 2.0, -1.0], f32::NAN, 5.0, -5.0).iter().all(|v| v.is_finite())); } + #[test] + fn an_untransformed_gradient_maps_bit_for_bit_as_projects_saved_before_did() { + let colors = vec![[1.0, 0.2, 0.0], [0.1, 0.4, 0.9], [0.0, 0.0, 1.0]]; + let gm = Filter::even_gradient(colors.clone()); + for step in 0..=1000 { + let x = step as f32 / 1000.0; + let color = [x, 0.5 * x, 1.0 - x]; + assert_eq!(gm.point(ChannelKind::Color, color), gradient(&colors, lum(color)), "color {color:?}"); + let height = 2.0 * x - 1.0; + let saved_before = per_unit(ChannelKind::Signed, [height; 3], |t| gradient(&colors, t).map_or(t, lum)); + assert_eq!(gm.point(ChannelKind::Signed, [height; 3]), Some(saved_before), "height {height}"); + } + } + #[test] fn point_filters_map_values_and_skip_neighbourhood_filters() { let c = ChannelKind::Color; @@ -1915,38 +2386,34 @@ mod tests { let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 }; assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0])); assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3])); - - let gm = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] }; + let gm = Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]); assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0])); assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0])); - assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing"); - - assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); + assert_eq!(Filter::even_gradient(vec![]).point(c, [0.3; 3]), None, "an empty gradient changes nothing"); + let gray_ramp = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); + assert!(close(gray_ramp.point(ChannelKind::Signed, [-0.6; 3]).unwrap(), [-0.6; 3]), "a height reads the ramp at its 0..1 place"); + assert!(close(Filter::Posterize { levels: 2.0, alpha: false }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); - - let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap(); - + let scan = |position, contrast| Filter::HistogramScan { position, contrast, invert_position: false }.point(c, [0.2, 0.5, 0.9]).unwrap(); assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); - let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); - assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); - let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); - assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); - let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0])); - - for f in [Filter::Blur { radius: 1.0 }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0 }, Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }] { + for f in [ + Filter::Blur { radius: 1.0, wrap: false }, + Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0, divider: 1 }, + Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }, + ] { assert!(f.is_neighbourhood() && f.point(c, [0.5; 3]).is_none()); } let nan = Filter::ContrastLuminosity { contrast: f32::NAN, luminosity: f32::NAN }; diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c1fc86f6..ea2c1805 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -7,32 +7,75 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod anisotropic_kuwahara; pub mod backface; pub mod bake; +pub mod bevel; +pub mod bevel_blur; +pub mod bevel_corner; +pub mod bevel_direction; +pub mod bevel_smooth; pub mod blend; mod block_scales; pub mod channel; +pub mod color_match; pub mod color_selection; pub mod compare_source; pub mod contents_offset; +pub mod conversion_mode; pub mod cook_resolution; +pub mod curve_preset; pub mod depth_culling; +pub mod directional_distance; +pub mod directional_light; mod env_alignment; pub mod fill_symmetry; +pub mod gradient_input; +pub mod grayscale_conversion; +pub mod grayscale_mode; +pub mod height_to_normal; +pub mod highpass_space; +pub mod image_input; pub mod layer; +pub mod lighting_output; +pub mod mask_outline; +pub mod mirror; +pub mod mirror_corner; +pub mod mirror_mode; +pub mod oklab; +pub mod outline_position; +pub mod pbr_validate; pub mod project; pub mod projector; +pub mod ramp_curve; pub mod randomized_seed; mod saved_decal; mod saved_projection; pub mod selection_background; mod shadow_mode; pub mod shape_crop; +pub mod slope_blending; +pub mod source_color_mode; +pub mod source_slope_blur; +pub mod source_warp; +pub mod stylized_lighting; +pub mod stylized_shading; +pub mod sun_and_sky; pub mod symmetry_kind; +pub mod target_color_mode; +pub mod threshold_mode; +pub mod tile_transform; +pub mod unit_value; +pub mod validation_mode; +pub mod warp_blending; +pub mod warp_mode; +pub mod warp_source; +pub mod warp_source_mode; /// A full turn, in degrees pub const FULL_TURN_DEGREES: f32 = 360.0; +pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, @@ -41,29 +84,72 @@ pub use bake::{ NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, }; +pub use bevel::Bevel; +pub use bevel_blur::BevelBlur; +pub use bevel_corner::BevelCorner; +pub use bevel_direction::BevelDirection; +pub use bevel_smooth::BevelSmooth; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use color_match::ColorMatch; pub use color_selection::ColorSelection; pub use compare_source::CompareSource; pub use contents_offset::ContentsOffset; +pub use conversion_mode::ConversionMode; pub use cook_resolution::CookResolution; +pub use curve_preset::CurvePreset; pub use depth_culling::DepthCulling; +pub use directional_distance::DirectionalDistance; +pub use directional_light::DirectionalLight; pub use fill_symmetry::FillSymmetry; +pub use gradient_input::GradientInput; +pub use grayscale_conversion::GrayscaleConversion; +pub use grayscale_mode::GrayscaleMode; +pub use height_to_normal::HeightToNormal; +pub use highpass_space::HighpassSpace; +pub use image_input::ImageInput; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, + OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, + Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, + hsl_adjust, per_unit, posterize, }; +pub use lighting_output::LightingOutput; +pub use mask_outline::MaskOutline; +pub use mirror::Mirror; +pub use mirror_corner::MirrorCorner; +pub use mirror_mode::MirrorMode; +pub use outline_position::OutlinePosition; +pub use pbr_validate::PbrValidate; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; pub use projector::Projector; +pub use ramp_curve::RampCurve; pub use randomized_seed::RandomizedSeed; pub use selection_background::SelectionBackground; pub use shape_crop::ShapeCrop; +pub use slope_blending::SlopeBlending; +pub use source_color_mode::SourceColorMode; +pub use source_slope_blur::SourceSlopeBlur; +pub use source_warp::SourceWarp; +pub use stylized_lighting::{DIELECTRIC_REFLECTANCE, StylizedLighting}; +pub use stylized_shading::{FLAT_CURVATURE, StylizedShading}; +pub use sun_and_sky::SunAndSky; pub use symmetry_kind::SymmetryKind; +pub use target_color_mode::TargetColorMode; +pub use threshold_mode::ThresholdMode; +pub use tile_transform::{FlipMode, RepeatMode, TileTransform}; +pub use unit_value::{at_or_above_threshold, finite_unit}; +pub use validation_mode::ValidationMode; +pub use warp_blending::WarpBlending; +pub use warp_mode::WarpMode; +pub use warp_source::WarpSource; +pub use warp_source_mode::WarpSourceMode; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum CoreError { diff --git a/crates/core/src/lighting_output.rs b/crates/core/src/lighting_output.rs new file mode 100644 index 00000000..43054a39 --- /dev/null +++ b/crates/core/src/lighting_output.rs @@ -0,0 +1,49 @@ +//! What Baked Lighting Stylized paints into the base color + +use serde::{Deserialize, Serialize}; + +/// The lit parts Baked Lighting Stylized keeps +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum LightingOutput { + /// The lit surface and its highlights + #[default] + DiffuseSpecular, + /// The lit surface only (what Baked Lighting painted before it had highlights) + Diffuse, + /// The highlights only + Specular, +} + +impl LightingOutput { + /// Every output, in the order a list shows them + pub const ALL: [LightingOutput; 3] = [LightingOutput::DiffuseSpecular, LightingOutput::Diffuse, LightingOutput::Specular]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + LightingOutput::DiffuseSpecular => "Diffuse + Specular", + LightingOutput::Diffuse => "Diffuse only", + LightingOutput::Specular => "Specular only", + } + } + + /// The id `effect.set {output}` takes + pub fn id(self) -> &'static str { + match self { + LightingOutput::DiffuseSpecular => "diffuseSpecular", + LightingOutput::Diffuse => "diffuse", + LightingOutput::Specular => "specular", + } + } + + /// Whether the lit surface is kept + pub fn diffuse(self) -> bool { + self != LightingOutput::Specular + } + + /// Whether the highlights are kept + pub fn specular(self) -> bool { + self != LightingOutput::Diffuse + } +} diff --git a/crates/core/src/mask_outline.rs b/crates/core/src/mask_outline.rs new file mode 100644 index 00000000..cbd17456 --- /dev/null +++ b/crates/core/src/mask_outline.rs @@ -0,0 +1,92 @@ +//! The Mask Outline filter's settings and the band it draws + +use serde::{Deserialize, Serialize}; + +use crate::{OutlinePosition, RampCurve, at_or_above_threshold}; + +/// A band along the edge where values cross a threshold, outside, inside or on both sides of the shapes +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MaskOutline { + pub position: OutlinePosition, + /// The band on black; otherwise it is laid over the values below + pub from_black: bool, + /// Values at or above it are inside the shapes (0..1) + pub threshold: f32, + /// How far the band reaches from the edge, a fraction of the UV tile (0..1) + pub width: f32, + /// How much of the band fades out towards its far side (0..1) + pub blur: f32, + /// Bends that fade: below 0 it falls off sooner, above 0 later (−1..1) + pub curve: f32, +} + +impl MaskOutline { + /// The Mask Outline filter as the library adds it + pub const LIBRARY: MaskOutline = MaskOutline { position: OutlinePosition::Outside, from_black: true, threshold: 1.0, width: 0.05, blur: 0.0, curve: 0.0 }; + + /// Whether `value` is inside the shapes + pub fn inside(&self, value: f32) -> bool { + at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold) + } + + /// The curve the band's fade takes (Curve), worked out once per filter + pub fn fade_curve(&self) -> RampCurve { + RampCurve::new(0.0, self.curve) + } + + /// The band at a texel inside the shapes or not, `closeness` to the edge going from 1 at it to 0 at the band's reach, its fade bent by [`MaskOutline::fade_curve`] + pub fn band(&self, fade_curve: RampCurve, inside: bool, closeness: f32) -> f32 { + let closeness = if closeness.is_finite() { closeness.clamp(0.0, 1.0) } else { 0.0 }; + if !self.position.covers(inside) || closeness <= 0.0 || !self.width.is_finite() || self.width <= 0.0 { + return 0.0; + } + + let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 }; + if blur <= 0.0 { + return 1.0; + } + + fade_curve.apply(closeness / blur) + } + + /// The result at a texel of value `value`: the band on black, or over the value + pub fn apply(&self, value: f32, band: f32) -> f32 { + if self.from_black { band } else { value.max(band) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The band with the curve worked out as the filter does + fn band(filter: MaskOutline, inside: bool, closeness: f32) -> f32 { + filter.band(filter.fade_curve(), inside, closeness) + } + + #[test] + fn the_band_lies_on_its_side_of_the_edge() { + let outline = MaskOutline::LIBRARY; + assert!(outline.inside(1.0) && !outline.inside(0.99)); + assert_eq!(band(outline, false, 0.3), 1.0, "a hard band outside"); + assert_eq!(band(outline, true, 0.3), 0.0, "nothing inside an outside band"); + assert_eq!(band(outline, false, 0.0), 0.0, "nothing past its reach"); + let inside = MaskOutline { position: OutlinePosition::Inside, ..outline }; + assert_eq!((band(inside, true, 0.3), band(inside, false, 0.3)), (1.0, 0.0)); + let both = MaskOutline { position: OutlinePosition::Both, ..outline }; + assert_eq!((band(both, true, 0.3), band(both, false, 0.3)), (1.0, 1.0)); + assert_eq!(outline.apply(0.4, 0.0), 0.0, "from black"); + assert_eq!(MaskOutline { from_black: false, ..outline }.apply(0.4, 0.0), 0.4, "over the values"); + } + + #[test] + fn blur_fades_the_band_and_curve_shape_bends_the_fade() { + let soft = MaskOutline { blur: 1.0, ..MaskOutline::LIBRARY }; + assert!((band(soft, false, 0.5) - 0.5).abs() < 1e-6, "a linear fade"); + assert!(band(MaskOutline { curve: 0.5, ..soft }, false, 0.5) > 0.5, "falls off later"); + assert!(band(MaskOutline { curve: -0.5, ..soft }, false, 0.5) < 0.5, "falls off sooner"); + assert_eq!(band(MaskOutline { blur: 0.5, ..soft }, false, 0.6), 1.0, "only the far part fades"); + assert_eq!(band(MaskOutline { width: f32::NAN, threshold: f32::NAN, ..soft }, false, 0.5), 0.0); + } +} diff --git a/crates/core/src/mirror.rs b/crates/core/src/mirror.rs new file mode 100644 index 00000000..44831b81 --- /dev/null +++ b/crates/core/src/mirror.rs @@ -0,0 +1,99 @@ +//! The Mirror filter's settings and where it reads each texel from + +use serde::{Deserialize, Serialize}; + +use crate::{MirrorCorner, MirrorMode}; + +/// A mirror filter: one side of an axis (or one quarter) of each UV tile copied over the rest +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Mirror { + /// Draws the mirror's axes over the result (Display Debug) + pub debug: bool, + pub mode: MirrorMode, + /// Where the X and Y axes sit across the tile (0..1) + pub offset: [f32; 2], + /// Copies the right (X) or bottom (Y) side instead of the left or top one + pub invert: [bool; 2], + pub corner: MirrorCorner, +} + +impl Mirror { + /// The Mirror filter as the library adds it: left onto right across the middle + pub const LIBRARY: Mirror = Mirror { debug: false, mode: MirrorMode::AxisX, offset: [0.5, 0.5], invert: [false, false], corner: MirrorCorner::TopLeft }; + + /// Half the width of a debug axis line, in texels at 2K + pub const DEBUG_HALF_WIDTH: f32 = 2.0; + + /// Where in its tile (0..1 across, 0..1 down) the texel at `uv` reads from; a copy that reaches past an edge folds back at it + pub fn source(&self, [u, v]: [f32; 2]) -> [f32; 2] { + let across = |at: f32, axis: f32, keep_after: bool| { + let copied = if keep_after { at < axis } else { at > axis }; + fold(if copied { 2.0 * axis - at } else { at }) + }; + match self.mode { + MirrorMode::AxisX => [across(u, self.axis(0), self.invert[0]), v], + MirrorMode::AxisY => [u, across(v, self.axis(1), self.invert[1])], + MirrorMode::Corner => { + let (right, bottom) = self.corner.sides(); + [across(u, 0.5, right), across(v, 0.5, bottom)] + } + } + } + + /// Whether `uv` lies within `half_width` (a fraction of the tile) of one of the mirror's axes + pub fn on_axis(&self, [u, v]: [f32; 2], half_width: f32) -> bool { + let near = |at: f32, axis: f32| (at - axis).abs() <= half_width; + match self.mode { + MirrorMode::AxisX => near(u, self.axis(0)), + MirrorMode::AxisY => near(v, self.axis(1)), + MirrorMode::Corner => near(u, 0.5) || near(v, 0.5), + } + } + + /// The axis position along `axis` (0 = X, 1 = Y), within the tile even from a hostile file + fn axis(&self, axis: usize) -> f32 { + let at = self.offset.get(axis).copied().unwrap_or(0.5); + if at.is_finite() { at.clamp(0.0, 1.0) } else { 0.5 } + } +} + +/// `at` folded back into 0..1 at the tile's edges, as a mirror reflects +fn fold(at: f32) -> f32 { + let wrapped = at.rem_euclid(2.0); + if wrapped > 1.0 { 2.0 - wrapped } else { wrapped } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_mode_reads_the_kept_side() { + let mut mirror = Mirror::LIBRARY; + assert_eq!(mirror.source([0.25, 0.4]), [0.25, 0.4], "the left side stays"); + assert_eq!(mirror.source([0.75, 0.4]), [0.25, 0.4], "the right side reads the left"); + mirror.invert[0] = true; + assert_eq!(mirror.source([0.25, 0.4]), [0.75, 0.4], "inverted, the left side reads the right"); + + mirror.offset[0] = 0.25; + mirror.invert[0] = false; + assert_eq!(mirror.source([0.75, 0.0]), [0.25, 0.0], "a copy past the left edge folds back at it"); + + mirror.mode = MirrorMode::AxisY; + assert_eq!(mirror.source([0.9, 0.75]), [0.9, 0.25], "Axis Y reads the top for the bottom"); + + mirror.mode = MirrorMode::Corner; + mirror.corner = MirrorCorner::BottomRight; + assert_eq!(mirror.source([0.25, 0.25]), [0.75, 0.75], "every quarter reads the kept one"); + assert_eq!(mirror.source([0.75, 0.75]), [0.75, 0.75]); + assert!(mirror.on_axis([0.5, 0.1], 0.01) && mirror.on_axis([0.1, 0.5], 0.01) && !mirror.on_axis([0.1, 0.1], 0.01)); + } + + #[test] + fn a_hostile_offset_stays_in_the_tile() { + let mirror = Mirror { offset: [f32::NAN, f32::INFINITY], ..Mirror::LIBRARY }; + let [u, v] = mirror.source([0.9, 0.9]); + assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)); + } +} diff --git a/crates/core/src/mirror_corner.rs b/crates/core/src/mirror_corner.rs new file mode 100644 index 00000000..43061423 --- /dev/null +++ b/crates/core/src/mirror_corner.rs @@ -0,0 +1,49 @@ +//! The quarter a corner mirror copies + +use serde::{Deserialize, Serialize}; + +/// The quarter of each UV tile a corner mirror keeps and copies over the other three +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MirrorCorner { + #[default] + TopLeft, + TopRight, + BottomLeft, + BottomRight, +} + +impl MirrorCorner { + /// Every corner, in the order a list shows them + pub const ALL: [MirrorCorner; 4] = [MirrorCorner::TopLeft, MirrorCorner::TopRight, MirrorCorner::BottomLeft, MirrorCorner::BottomRight]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + MirrorCorner::TopLeft => "Top Left", + MirrorCorner::TopRight => "Top Right", + MirrorCorner::BottomLeft => "Bottom Left", + MirrorCorner::BottomRight => "Bottom Right", + } + } + + /// The id `effect.set {cornerType}` takes + pub fn id(self) -> &'static str { + match self { + MirrorCorner::TopLeft => "topLeft", + MirrorCorner::TopRight => "topRight", + MirrorCorner::BottomLeft => "bottomLeft", + MirrorCorner::BottomRight => "bottomRight", + } + } + + /// Whether the kept quarter is on the right half and on the bottom half + pub fn sides(self) -> (bool, bool) { + match self { + MirrorCorner::TopLeft => (false, false), + MirrorCorner::TopRight => (true, false), + MirrorCorner::BottomLeft => (false, true), + MirrorCorner::BottomRight => (true, true), + } + } +} diff --git a/crates/core/src/mirror_mode.rs b/crates/core/src/mirror_mode.rs new file mode 100644 index 00000000..6ec9acca --- /dev/null +++ b/crates/core/src/mirror_mode.rs @@ -0,0 +1,39 @@ +//! Which way a mirror filter copies a texture + +use serde::{Deserialize, Serialize}; + +/// The side of an axis, or the corner, a mirror filter copies over the rest of each UV tile +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MirrorMode { + /// Across a vertical axis, left onto right + #[default] + AxisX, + /// Across a horizontal axis, top onto bottom + AxisY, + /// One quarter onto the other three + Corner, +} + +impl MirrorMode { + /// Every mode, in the order a list shows them + pub const ALL: [MirrorMode; 3] = [MirrorMode::AxisX, MirrorMode::AxisY, MirrorMode::Corner]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + MirrorMode::AxisX => "Mirror Axis X", + MirrorMode::AxisY => "Mirror Axis Y", + MirrorMode::Corner => "Mirror Corner", + } + } + + /// The id `effect.set {mode}` takes + pub fn id(self) -> &'static str { + match self { + MirrorMode::AxisX => "axisX", + MirrorMode::AxisY => "axisY", + MirrorMode::Corner => "corner", + } + } +} diff --git a/crates/core/src/oklab.rs b/crates/core/src/oklab.rs new file mode 100644 index 00000000..022f3964 --- /dev/null +++ b/crates/core/src/oklab.rs @@ -0,0 +1,40 @@ +//! The OKLab perceptual color space (Björn Ottosson's public construction): hue, chroma and lightness shifts that keep perceived lightness + +/// Linear sRGB to OKLab `[L, a, b]` +pub fn from_linear([r, g, b]: [f32; 3]) -> [f32; 3] { + let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt(); + let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt(); + let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt(); + [ + 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s, + 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s, + 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s, + ] +} + +/// OKLab `[L, a, b]` back to linear sRGB (unclamped) +pub fn to_linear([lightness, a, b]: [f32; 3]) -> [f32; 3] { + let l = (lightness + 0.396_337_78 * a + 0.215_803_76 * b).powi(3); + let m = (lightness - 0.105_561_346 * a - 0.063_854_17 * b).powi(3); + let s = (lightness - 0.089_484_18 * a - 1.291_485_5 * b).powi(3); + [ + 4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s, + -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s, + -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn colors_round_trip_and_white_has_lightness_one() { + let white = from_linear([1.0; 3]); + assert!((white[0] - 1.0).abs() < 1e-3 && white[1].abs() < 1e-3 && white[2].abs() < 1e-3, "{white:?}"); + for color in [[0.8, 0.2, 0.1], [0.05, 0.5, 0.9], [0.3, 0.3, 0.3]] { + let back = to_linear(from_linear(color)); + assert!(color.iter().zip(back).all(|(a, b)| (a - b).abs() < 1e-3), "{color:?} -> {back:?}"); + } + } +} diff --git a/crates/core/src/outline_position.rs b/crates/core/src/outline_position.rs new file mode 100644 index 00000000..8e62d6d1 --- /dev/null +++ b/crates/core/src/outline_position.rs @@ -0,0 +1,48 @@ +//! Which side of a mask's edge a Mask Outline draws on + +use serde::{Deserialize, Serialize}; + +/// The side of the threshold edge a Mask Outline's band lies on +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OutlinePosition { + /// Around the shapes, outside them + #[default] + Outside, + /// Inside the shapes, along their edge + Inside, + /// On both sides of the edge + Both, +} + +impl OutlinePosition { + /// Every position, in the order a switch shows them + pub const ALL: [OutlinePosition; 3] = [OutlinePosition::Outside, OutlinePosition::Inside, OutlinePosition::Both]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + OutlinePosition::Outside => "Outside", + OutlinePosition::Inside => "Inside", + OutlinePosition::Both => "Both", + } + } + + /// The id `effect.set {maskPosition}` takes + pub fn id(self) -> &'static str { + match self { + OutlinePosition::Outside => "outside", + OutlinePosition::Inside => "inside", + OutlinePosition::Both => "both", + } + } + + /// Whether the band covers a texel inside the shapes (`inside`) + pub fn covers(self, inside: bool) -> bool { + match self { + OutlinePosition::Outside => !inside, + OutlinePosition::Inside => inside, + OutlinePosition::Both => true, + } + } +} diff --git a/crates/core/src/pbr_validate.rs b/crates/core/src/pbr_validate.rs new file mode 100644 index 00000000..0690ada2 --- /dev/null +++ b/crates/core/src/pbr_validate.rs @@ -0,0 +1,78 @@ +//! PBR Validate (Metallic Roughness): base colors outside the physically plausible ranges shown in red + +use serde::{Deserialize, Serialize}; + +use crate::ValidationMode; +use crate::blend::lum; +use crate::gradient_input::linear_to_srgb; + +/// A PBR Validate filter: which texels it checks and the ranges it checks them against +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PbrValidate { + pub mode: ValidationMode, + /// Albedo Dark Range Threshold: the darkest valid non-metal base color, in sRGB steps of 255 (30 or 50) + pub albedo_dark: u8, + /// Metal Reflectance Range: the dimmest valid metal base color, in percent of sRGB white (60 or 70) + pub metal_low: u8, +} + +impl PbrValidate { + /// A new PBR Validate: both kinds of texel, the tolerant ranges + pub const LIBRARY: PbrValidate = PbrValidate { mode: ValidationMode::Combined, albedo_dark: 30, metal_low: 60 }; + + /// Albedo Dark Range Threshold's choices + pub const ALBEDO_DARK: [u8; 2] = [50, 30]; + + /// Metal Reflectance Range's choices + pub const METAL_LOW: [u8; 2] = [70, 60]; + + /// The brightest valid non-metal base color, in sRGB steps of 255 + const ALBEDO_BRIGHT: f32 = 240.0; + + /// Metal from this value up counts as metal + const METAL_THRESHOLD: f32 = 0.5; + + /// Metal Reflectance Range's choices are percent of sRGB white + const PERCENT: f32 = 100.0; + + /// Base Color Range's choices are sRGB steps of 255 + const SRGB_STEPS: f32 = 255.0; + + /// The color of a texel outside its range + pub const INVALID: [f32; 3] = [1.0, 0.0, 0.0]; + + /// Straight linear base color `color` of a texel with metal `metal`: its own color when valid or not checked, red when not + pub fn check(&self, color: [f32; 3], metal: f32) -> [f32; 3] { + let srgb = linear_to_srgb(lum(color).clamp(0.0, 1.0)); + let valid = if metal >= Self::METAL_THRESHOLD { + !self.mode.checks_metal() || srgb >= f32::from(self.metal_low) / Self::PERCENT + } else { + !self.mode.checks_albedo() || (f32::from(self.albedo_dark) / Self::SRGB_STEPS..=Self::ALBEDO_BRIGHT / Self::SRGB_STEPS).contains(&srgb) + }; + if valid { color } else { Self::INVALID } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gradient_input::srgb_to_linear; + + #[test] + fn colors_outside_their_range_turn_red() { + let gray = |srgb: f32| [srgb_to_linear(srgb / 255.0); 3]; + let filter = PbrValidate::LIBRARY; + assert_eq!(filter.check(gray(40.0), 0.0), gray(40.0), "above 30 sRGB"); + assert_eq!(filter.check(gray(20.0), 0.0), PbrValidate::INVALID, "too dark"); + assert_eq!(filter.check(gray(250.0), 0.0), PbrValidate::INVALID, "too bright"); + assert_eq!(PbrValidate { albedo_dark: 50, ..filter }.check(gray(40.0), 0.0), PbrValidate::INVALID); + assert_eq!(filter.check(gray(140.0), 1.0), PbrValidate::INVALID, "a dim metal"); + assert_eq!(filter.check(gray(170.0), 1.0), gray(170.0), "60% reflective"); + assert_eq!(PbrValidate { metal_low: 70, ..filter }.check(gray(170.0), 1.0), PbrValidate::INVALID); + let albedo = PbrValidate { mode: ValidationMode::Albedo, ..filter }; + assert_eq!(albedo.check(gray(140.0), 1.0), gray(140.0), "Albedo leaves metal unchecked"); + let metal = PbrValidate { mode: ValidationMode::Metal, ..filter }; + assert_eq!(metal.check(gray(20.0), 0.0), gray(20.0), "Metal leaves non-metal unchecked"); + } +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index b182682d..97d35be8 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -653,6 +653,7 @@ impl Project { } let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()); out.extend(effects.filter(|e| e.kind.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); + out.extend(effects.filter(|e| e.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); } out } @@ -868,7 +869,7 @@ mod tests { material.sources.insert(Channel::Roughness, Source::Uniform([0.2; 3])); l.content_effects = vec![ Effect::new(fill, EffectKind::Material(material)), - Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1 })), + Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1, perceptive: false })), Effect::new(anchor, EffectKind::Anchor), ]; let id = p.insert_layer(0, l, None, false).unwrap(); diff --git a/crates/core/src/slope_blending.rs b/crates/core/src/slope_blending.rs new file mode 100644 index 00000000..766016b9 --- /dev/null +++ b/crates/core/src/slope_blending.rs @@ -0,0 +1,39 @@ +//! How a Blur Slope combines what it reads downhill + +use serde::{Deserialize, Serialize}; + +/// What a Blur Slope keeps of the values it reads along the slope +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SlopeBlending { + /// Their average: the values smeared downhill + #[default] + Blur, + /// The smallest of them, per component: light shapes eaten away downhill + Min, + /// The largest of them, per component: light shapes grown downhill + Max, +} + +impl SlopeBlending { + /// Every choice, in the order a panel lists them + pub const ALL: [SlopeBlending; 3] = [SlopeBlending::Blur, SlopeBlending::Min, SlopeBlending::Max]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + SlopeBlending::Blur => "Blur", + SlopeBlending::Min => "Min", + SlopeBlending::Max => "Max", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + SlopeBlending::Blur => "blur", + SlopeBlending::Min => "min", + SlopeBlending::Max => "max", + } + } +} diff --git a/crates/core/src/source_color_mode.rs b/crates/core/src/source_color_mode.rs new file mode 100644 index 00000000..08b3da42 --- /dev/null +++ b/crates/core/src/source_color_mode.rs @@ -0,0 +1,36 @@ +//! Where Color Match takes the color it moves from + +use serde::{Deserialize, Serialize}; + +/// Color Match's Source Color Mode: the mean color of the whole texture, its Source Color, or its Input image +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SourceColorMode { + #[default] + Average, + Parameter, + Input, +} + +impl SourceColorMode { + /// Every mode, in the order a panel shows them + pub const ALL: [SourceColorMode; 3] = [SourceColorMode::Average, SourceColorMode::Parameter, SourceColorMode::Input]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + SourceColorMode::Average => "Average", + SourceColorMode::Parameter => "Parameter", + SourceColorMode::Input => "Input", + } + } + + /// The id `effect.set {sourceColorMode}` takes + pub fn id(self) -> &'static str { + match self { + SourceColorMode::Average => "average", + SourceColorMode::Parameter => "parameter", + SourceColorMode::Input => "input", + } + } +} diff --git a/crates/core/src/source_slope_blur.rs b/crates/core/src/source_slope_blur.rs new file mode 100644 index 00000000..27aeacff --- /dev/null +++ b/crates/core/src/source_slope_blur.rs @@ -0,0 +1,65 @@ +//! The Blur Slope filter's settings and how far it reads + +use serde::{Deserialize, Serialize}; + +use crate::{SlopeBlending, SourceWarp, WarpSource, WarpSourceMode, source_warp}; + +/// Values read downhill along a source's slope, averaged or kept at their smallest or largest +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceSlopeBlur { + /// The default noise's seed + pub seed: u32, + /// How far downhill a texel reads, a share of the UV tile before the divider (0..1) + pub intensity: f32, + /// Divides `intensity` (1, 10, 100 or 1000) for short smears + pub divider: u16, + pub blending: SlopeBlending, + /// The share of the reads taken along the way (0..1): fewer is faster and grainier + pub quality: f32, + pub source: WarpSource, +} + +impl SourceSlopeBlur { + /// The Blur Slope filter as the library adds it + pub const LIBRARY: SourceSlopeBlur = + SourceSlopeBlur { seed: 0, intensity: 0.3, divider: 10, blending: SlopeBlending::Blur, quality: 1.0, source: WarpSource::LIBRARY }; + + /// How many texels downhill a texel reads at most at `res` texels across a UV tile + pub fn move_texels(&self, res: u32) -> f32 { + source_warp::move_texels(self.intensity, self.divider, res) + } + + /// How many of `most` reads along the way Quality keeps (at least one past the texel itself) + pub fn samples(&self, most: u32) -> u32 { + let quality = if self.quality.is_finite() { self.quality.clamp(0.0, 1.0) } else { 1.0 }; + ((most as f32 * quality).round() as u32).clamp(1, most.max(1)) + } + + /// How many texels around a texel the filter reads at `res` texels across a UV tile: downhill, and where it measures its source's slope + pub fn reach(&self, res: u32) -> f32 { + let moves = self.move_texels(res); + if self.source.mode != WarpSourceMode::PreviousInput { + return moves; + } + + moves + SourceWarp::probe_texels(res) + self.source.blur_texels(res) * std::f32::consts::FRAC_1_SQRT_2 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_follow_intensity_quality_and_source() { + let slope = SourceSlopeBlur::LIBRARY; + assert!((slope.move_texels(2048) - 61.44).abs() < 1e-3, "0.3 ÷ 10 of the tile"); + assert_eq!((slope.samples(24), SourceSlopeBlur { quality: 0.5, ..slope }.samples(24)), (24, 12)); + assert_eq!(SourceSlopeBlur { quality: 0.0, ..slope }.samples(24), 1, "always one read downhill"); + assert_eq!(SourceSlopeBlur { quality: f32::NAN, ..slope }.samples(24), 24); + let input = SourceSlopeBlur { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..slope }; + assert!((input.reach(2048) - (61.44 + 8.0)).abs() < 1e-3, "plus where it measures the slope"); + assert_eq!(SourceSlopeBlur { intensity: f32::INFINITY, ..slope }.move_texels(2048), 0.0); + } +} diff --git a/crates/core/src/stylized_lighting.rs b/crates/core/src/stylized_lighting.rs new file mode 100644 index 00000000..3c5289d8 --- /dev/null +++ b/crates/core/src/stylized_lighting.rs @@ -0,0 +1,157 @@ +//! What Baked Lighting Stylized adds to Baked Lighting's sun and ambient: sky colors, two more lights, cavity, edges and highlights + +use serde::{Deserialize, Serialize}; + +use crate::directional_light::DirectionalLight; +use crate::lighting_output::LightingOutput; +use crate::stylized_shading::StylizedShading; +use crate::sun_and_sky::SunAndSky; + +/// Baked Lighting Stylized's settings past the sun's direction and strength, the sky's strength and Diffuse AO (kept on the filter, as Baked Lighting saved them) +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StylizedLighting { + pub sun_color: [f32; 3], + /// The ambient light from straight above, at the horizon and from below; normals between blend them + pub sky_color: [f32; 3], + pub horizon_color: [f32; 3], + pub ground_color: [f32; 3], + /// Light 1 and Light 2 + pub lights: [DirectionalLight; 2], + /// How much the cavities (concave curvature) darken the lit surface and its highlights + pub diffuse_cavity: f32, + pub specular_cavity: f32, + /// How much the baked ambient occlusion darkens the highlights + pub specular_ao: f32, + /// The concavity (and convexity, for edges) over which cavity and edges fade in: 0 is a hard step + pub cavity_smoothness: f32, + /// How much the edges (convex curvature) lighten toward white + pub edges_intensity: f32, + pub edges_smoothness: f32, + /// Reads the Specular and Glossiness channels instead of Metallic and Roughness (Input) + pub specular_glossiness: bool, + pub output: LightingOutput, + /// The reflectance of non-metals at normal incidence + pub dielectric_reflectance: f32, + /// Lights the mesh's own normals, without the baked normal and height detail (Normal Details Type Mesh only) + pub mesh_only: bool, + pub height_to_normal: f32, +} + +/// The reflectance of non-metals at normal incidence +pub const DIELECTRIC_REFLECTANCE: f32 = 0.04; + +impl StylizedLighting { + /// The settings that light exactly as Baked Lighting did: white light and sky, no extra lights, cavity, edges or highlights, the mesh's own normals + pub const PLAIN: StylizedLighting = StylizedLighting { + sun_color: [1.0; 3], + sky_color: [1.0; 3], + horizon_color: [1.0; 3], + ground_color: [1.0; 3], + lights: [DirectionalLight::off(90.0), DirectionalLight::off(180.0)], + diffuse_cavity: 0.0, + specular_cavity: 0.0, + specular_ao: 0.0, + cavity_smoothness: 0.25, + edges_intensity: 0.0, + edges_smoothness: 0.0, + specular_glossiness: false, + output: LightingOutput::Diffuse, + dielectric_reflectance: DIELECTRIC_REFLECTANCE, + mesh_only: true, + height_to_normal: 1.0, + }; + + /// A new Baked Lighting Stylized: a warm sun, a blue sky over a brown ground, highlights, and the baked normal and height detail + pub fn library() -> StylizedLighting { + StylizedLighting { + sun_color: [1.0, 0.905, 0.716], + sky_color: [0.305, 0.456, 0.791], + horizon_color: [0.644, 0.644, 0.61], + ground_color: [0.102, 0.08, 0.061], + output: LightingOutput::DiffuseSpecular, + mesh_only: false, + ..StylizedLighting::PLAIN + } + } + + /// These settings lit by `light`, worked out once for the shading of every texel + pub fn shading(&self, light: SunAndSky) -> StylizedShading { + StylizedShading::new(self, light) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Channel, Filter}; + + const UP: [f32; 3] = [0.0, 1.0, 0.0]; + + fn material(roughness: f32) -> Vec<[f32; 3]> { + let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect(); + channels[Channel::Roughness.index()] = [roughness; 3]; + channels + } + + fn light(elevation: f32, intensity: f32, sky_intensity: f32) -> SunAndSky { + SunAndSky { sun: DirectionalLight { azimuth: 0.0, elevation, intensity, color: [1.0; 3] }, sky_intensity, diffuse_ao: 0.5 } + } + + /// The plain settings light as Baked Lighting did: the base color times sun facing plus occluded ambient + #[test] + fn plain_settings_light_as_baked_lighting_did() { + let legacy = Filter::BakedLighting { azimuth: 0.0, elevation: 30.0, light: 0.6, ambient: 0.4, occlusion: 0.5, stylized: None }; + for (nrm, ao) in [(UP, 1.0), ([0.6, 0.8, 0.0], 0.3), ([0.0, -1.0, 0.0], 0.7)] { + let k = legacy.baked_light(nrm, ao).unwrap_or(f32::NAN); + let shaded = StylizedLighting::PLAIN.shading(light(30.0, 0.6, 0.4)).shade([0.5, 0.25, 1.0], nrm, [ao, 0.5], &material(0.5)); + let expected = [0.5f32, 0.25, 1.0].map(|x| (x * k).clamp(0.0, 1.0)); + assert!(shaded.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-5), "{nrm:?}: {shaded:?} vs {expected:?}"); + } + } + + /// The sky, horizon and ground colors light a surface by where it faces; Light 1 adds its color + #[test] + fn sky_colors_and_extra_lights() { + let colors = StylizedLighting { sky_color: [0.0, 0.0, 1.0], horizon_color: [0.0, 1.0, 0.0], ground_color: [1.0, 0.0, 0.0], ..StylizedLighting::PLAIN }; + let sky = light(45.0, 0.0, 1.0); + let white = [1.0; 3]; + assert_eq!(colors.shading(sky).shade(white, UP, [1.0, 0.5], &material(0.5)), [0.0, 0.0, 1.0]); + assert_eq!(colors.shading(sky).shade(white, [1.0, 0.0, 0.0], [1.0, 0.5], &material(0.5)), [0.0, 1.0, 0.0]); + assert_eq!(colors.shading(sky).shade(white, [0.0, -1.0, 0.0], [1.0, 0.5], &material(0.5)), [1.0, 0.0, 0.0]); + + let mut extra = StylizedLighting::PLAIN; + extra.lights[0] = DirectionalLight { azimuth: 0.0, elevation: 90.0, intensity: 0.5, color: [1.0, 0.0, 0.0] }; + let dark = light(45.0, 0.0, 0.0); + let lit = extra.shading(dark).shade(white, UP, [1.0, 0.5], &material(0.5)); + assert!((lit[0] - 0.5).abs() < 1e-5 && lit[1] == 0.0, "{lit:?}"); + } + + /// Highlights: a smooth surface shines brighter than a rough one; Specular only keeps them alone, Diffuse only drops them + #[test] + fn highlights_follow_roughness_and_the_output() { + let sun = light(90.0, 1.0, 0.0); + let shiny = StylizedLighting { output: LightingOutput::Specular, ..StylizedLighting::library() }; + let albedo = [0.0; 3]; + let smooth = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)); + let rough = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.9)); + assert!(smooth[0] > rough[0] + 0.1 && rough[0] > 0.0, "{smooth:?} {rough:?}"); + let diffuse = StylizedLighting { output: LightingOutput::Diffuse, ..StylizedLighting::library() }; + assert_eq!(diffuse.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)), [0.0; 3]); + } + + /// Cavities darken the lit surface by Diffuse Cavity; edges lighten toward white by Edges Intensity + #[test] + fn cavities_darken_and_edges_lighten() { + let sky = light(45.0, 0.0, 1.0); + let gray = [0.5; 3]; + let cavities = StylizedLighting { diffuse_cavity: 1.0, ..StylizedLighting::PLAIN }; + assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat: no cavity"); + assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity"); + let sun = light(90.0, 1.0, 0.0); + assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat in the sun: no cavity"); + assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity in the sun"); + let edges = StylizedLighting { edges_intensity: 1.0, ..StylizedLighting::PLAIN }; + assert_eq!(edges.shading(sky).shade(gray, UP, [1.0, 0.9], &material(0.5)), [1.0; 3], "a sharp edge"); + } +} diff --git a/crates/core/src/sun_and_sky.rs b/crates/core/src/sun_and_sky.rs new file mode 100644 index 00000000..e24245da --- /dev/null +++ b/crates/core/src/sun_and_sky.rs @@ -0,0 +1,11 @@ +//! The sun and sky Baked Lighting Stylized shades with + +use crate::directional_light::DirectionalLight; + +/// The sun and sky a [`StylizedLighting`](crate::StylizedLighting) shades with, kept on the filter as Baked Lighting saved them +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SunAndSky { + pub sun: DirectionalLight, + pub sky_intensity: f32, + pub diffuse_ao: f32, +} diff --git a/crates/core/src/target_color_mode.rs b/crates/core/src/target_color_mode.rs new file mode 100644 index 00000000..ffcafdab --- /dev/null +++ b/crates/core/src/target_color_mode.rs @@ -0,0 +1,33 @@ +//! Where Color Match takes the color it moves to + +use serde::{Deserialize, Serialize}; + +/// Color Match's Target Color Mode: its Target Color or its Image Input +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TargetColorMode { + #[default] + Parameter, + ImageInput, +} + +impl TargetColorMode { + /// Every mode, in the order a panel shows them + pub const ALL: [TargetColorMode; 2] = [TargetColorMode::Parameter, TargetColorMode::ImageInput]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + TargetColorMode::Parameter => "Parameter", + TargetColorMode::ImageInput => "Image Input", + } + } + + /// The id `effect.set {targetColorMode}` takes + pub fn id(self) -> &'static str { + match self { + TargetColorMode::Parameter => "parameter", + TargetColorMode::ImageInput => "imageInput", + } + } +} diff --git a/crates/core/src/threshold_mode.rs b/crates/core/src/threshold_mode.rs new file mode 100644 index 00000000..3dc3b05b --- /dev/null +++ b/crates/core/src/threshold_mode.rs @@ -0,0 +1,90 @@ +//! How a threshold compares a value with its level + +use serde::{Deserialize, Serialize}; + +/// Which values a threshold turns white: those above its level, at or above it, below it, or at or below it +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ThresholdMode { + Greater, + /// What thresholds did in projects saved before the modes + #[default] + GreaterOrEqual, + Lower, + LowerOrEqual, +} + +impl ThresholdMode { + /// Every mode, in the order a panel shows them + pub const ALL: [ThresholdMode; 4] = [ThresholdMode::Greater, ThresholdMode::GreaterOrEqual, ThresholdMode::Lower, ThresholdMode::LowerOrEqual]; + + /// The comparison sign a panel shows + pub fn sign(self) -> &'static str { + match self { + ThresholdMode::Greater => ">", + ThresholdMode::GreaterOrEqual => "≥", + ThresholdMode::Lower => "<", + ThresholdMode::LowerOrEqual => "≤", + } + } + + /// The name a tooltip shows + pub fn label(self) -> &'static str { + match self { + ThresholdMode::Greater => "Greater", + ThresholdMode::GreaterOrEqual => "Greater or equal", + ThresholdMode::Lower => "Lower", + ThresholdMode::LowerOrEqual => "Lower or equal", + } + } + + /// The id `effect.set {mode}` takes + pub fn id(self) -> &'static str { + match self { + ThresholdMode::Greater => "greater", + ThresholdMode::GreaterOrEqual => "greaterOrEqual", + ThresholdMode::Lower => "lower", + ThresholdMode::LowerOrEqual => "lowerOrEqual", + } + } + + /// Whether `value` turns white against `level` + pub fn passes(self, value: f32, level: f32) -> bool { + match self { + ThresholdMode::Greater => value > level, + ThresholdMode::GreaterOrEqual => value >= level, + ThresholdMode::Lower => value < level, + ThresholdMode::LowerOrEqual => value <= level, + } + } + + /// Whether it is the mode projects saved before the modes read as (it is then left out of a saved file) + pub fn is_default(&self) -> bool { + *self == ThresholdMode::default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ChannelKind, Filter}; + + #[test] + fn a_threshold_saved_before_the_modes_reads_and_saves_as_before() { + let saved = r#"{"Threshold":{"level":0.5}}"#; + let filter: Filter = serde_json::from_str(saved).unwrap(); + assert_eq!(filter, Filter::Threshold { level: 0.5, mode: ThresholdMode::GreaterOrEqual }); + assert_eq!(serde_json::to_string(&filter).unwrap(), saved); + assert_eq!(filter.point(ChannelKind::Scalar, [0.5; 3]), Some([1.0; 3]), "a value at the level turns white as before"); + } + + #[test] + fn each_mode_compares_its_way() { + let at = |mode: ThresholdMode, value: f32| Filter::Threshold { level: 0.5, mode }.point(ChannelKind::Scalar, [value; 3]).map(|v| v[0]); + assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Greater, value)), [Some(0.0), Some(0.0), Some(1.0)]); + assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Lower, value)), [Some(1.0), Some(0.0), Some(0.0)]); + assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::LowerOrEqual, value)), [Some(1.0), Some(1.0), Some(0.0)]); + let saved = serde_json::to_string(&Filter::Threshold { level: 0.01, mode: ThresholdMode::LowerOrEqual }).unwrap(); + assert!(saved.contains(r#""mode":"lowerOrEqual""#), "{saved}"); + } +} diff --git a/crates/core/src/tile_transform.rs b/crates/core/src/tile_transform.rs new file mode 100644 index 00000000..a834f7c8 --- /dev/null +++ b/crates/core/src/tile_transform.rs @@ -0,0 +1,225 @@ +//! The Transform filter's settings and where it reads each texel from + +use serde::{Deserialize, Serialize}; + +mod flip_mode; +mod repeat_mode; + +pub use flip_mode::FlipMode; +pub use repeat_mode::RepeatMode; + +/// A turn this close to a whole number of quarter turns (in quarter turns) keeps the tile's edges meeting as it is +const SQUARE_TURN_TOLERANCE: f32 = 1e-4; + +/// A shift or step this small (a share of the tile) moves no texel +const IDENTITY_TOLERANCE: f32 = 1e-6; + +/// Degrees in a quarter turn +const QUARTER_TURN_DEGREES: f32 = 90.0; + +/// A Transform filter: each UV tile's content scaled, turned and moved about the tile's centre, then flipped +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TileTransform { + pub repeat: RepeatMode, + pub flip: FlipMode, + /// How many times the content fits across and down the tile (2 = twice, half as big), as a fill's Tiling + pub scaling: [f32; 2], + /// How far the content moves, in tiles; positive reads further right and down, as a fill's Offset + pub offset: [f32; 2], + /// Turns only by angles that keep the tile's edges meeting, so a repeating result stays seamless + pub tile_safe: bool, + /// Degrees + pub rotation: f32, +} + +impl TileTransform { + /// The Transform filter as the library adds it: no change, repeating, tile safe + pub const LIBRARY: TileTransform = TileTransform { + repeat: RepeatMode::HorizontallyAndVertically, + flip: FlipMode::None, + scaling: [1.0, 1.0], + offset: [0.0, 0.0], + tile_safe: true, + rotation: 0.0, + }; + + /// The smallest and largest Scaling it renders (a hostile file's values come back within) + pub const SCALING: (f32, f32) = (0.01, 64.0); + + /// The farthest Offset it renders, in tiles + pub const MAX_OFFSET: f32 = 64.0; + + /// Where in the tile (0..1 across and down, before any repeat) the texel at `uv` reads from, as `linear · uv + shift`; the columns of `linear` are what one step across and one step down the result move in the source + pub fn affine(&self) -> ([[f32; 2]; 2], [f32; 2]) { + let finite = |value: f32, fallback: f32| if value.is_finite() { value } else { fallback }; + let (low, high) = Self::SCALING; + let scaling = self.scaling.map(|scale| finite(scale, 1.0).clamp(low, high)); + let rotation = finite(self.rotation, 0.0); + let (sin, cos) = rotation.to_radians().sin_cos(); + + // Turn, then scale (a fill's Tiling convention): one step across moves (cos, sin) scaled + let mut columns = [[cos * scaling[0], sin * scaling[1]], [-sin * scaling[0], cos * scaling[1]]]; + let quarter_turns = rotation / QUARTER_TURN_DEGREES; + let square = (quarter_turns - quarter_turns.round()).abs() < SQUARE_TURN_TOLERANCE; + + if self.tile_safe && !square { + let exact = columns; + + // Whole steps of the source per tile edge keep the edges meeting; a step can never vanish + for column in &mut columns { + let rounded = column.map(f32::round); + *column = if rounded == [0.0, 0.0] { + if column[0].abs() >= column[1].abs() { [column[0].signum(), 0.0] } else { [0.0, column[1].signum()] } + } else { + rounded + }; + } + + // Steps rounded onto one line would read a single line of the source: the one rounded further takes the nearest whole step that turns as the exact pair does + if determinant(columns) <= 0.0 { + let [across, down] = columns; + let across_further = squared_distance(across, exact[0]) >= squared_distance(down, exact[1]); + columns = if across_further { + turning_step(exact[0], |step| [step, down]).map_or(columns, |step| [step, down]) + } else { + turning_step(exact[1], |step| [across, step]).map_or(columns, |step| [across, step]) + }; + } + } + + let [flip_x, flip_y] = self.flip.sides(); + if flip_x { + columns[0] = columns[0].map(|v| -v); + } + if flip_y { + columns[1] = columns[1].map(|v| -v); + } + + let offset = self.offset.map(|along| finite(along, 0.0).clamp(-Self::MAX_OFFSET, Self::MAX_OFFSET)); + + // About the tile's centre: the centre reads the centre moved by the offset + let shift = [0, 1].map(|axis| 0.5 + offset[axis] - 0.5 * (columns[0][axis] + columns[1][axis])); + (columns, shift) + } + + /// Whether it changes nothing (a turn a hair short of a whole one included) + pub fn is_identity(&self) -> bool { + let (columns, shift) = self.affine(); + let steps = [columns[0][0] - 1.0, columns[0][1], columns[1][0], columns[1][1] - 1.0]; + steps.iter().chain(&shift).all(|along| along.abs() < IDENTITY_TOLERANCE) + } +} + +/// How the second column turns from the first: positive anticlockwise, as every exact turn and scale does, 0 when they lie on one line +fn determinant([across, down]: [[f32; 2]; 2]) -> f32 { + across[0] * down[1] - across[1] * down[0] +} + +fn squared_distance(a: [f32; 2], b: [f32; 2]) -> f32 { + (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) +} + +/// The whole step nearest `exact` (a corner of the cell it lies in) whose columns from `pair` turn as an exact pair does; a corner usually does; otherwise the rounded pair stays +fn turning_step(exact: [f32; 2], pair: impl Fn([f32; 2]) -> [[f32; 2]; 2]) -> Option<[f32; 2]> { + let [x, y] = exact.map(f32::floor); + [[x, y], [x + 1.0, y], [x, y + 1.0], [x + 1.0, y + 1.0]] + .into_iter() + .filter(|corner| determinant(pair(*corner)) > 0.0) + .min_by(|a, b| squared_distance(*a, exact).total_cmp(&squared_distance(*b, exact))) +} + +#[cfg(test)] +mod tests { + use super::*; + + impl TileTransform { + /// Where the texel at `uv` reads from in its tile (0..1), or None where the content does not repeat and no longer reaches (the renderer's read, without its bilinear corners) + fn source(&self, [u, v]: [f32; 2]) -> Option<[f32; 2]> { + let (columns, shift) = self.affine(); + let at = [0, 1].map(|axis| columns[0][axis] * u + columns[1][axis] * v + shift[axis]); + match self.repeat { + RepeatMode::HorizontallyAndVertically => Some(at.map(|along| along.rem_euclid(1.0))), + RepeatMode::None => at.iter().all(|along| (0.0..=1.0).contains(along)).then_some(at), + } + } + } + + fn near(a: [f32; 2], b: [f32; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4 + } + + #[test] + fn the_library_transform_reads_each_texel_from_itself() { + let transform = TileTransform::LIBRARY; + assert!(transform.is_identity()); + assert!(near(transform.source([0.3, 0.7]).unwrap_or_default(), [0.3, 0.7])); + } + + #[test] + fn scaling_offset_and_flip_move_the_reads_about_the_centre() { + let mut transform = TileTransform { scaling: [2.0, 2.0], ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.5, 0.5]), "the centre stays"); + assert!(near(transform.source([0.75, 0.5]).unwrap_or_default(), [0.0, 0.5]), "twice the content: a quarter tile reads half a tile on"); + transform.repeat = RepeatMode::None; + assert_eq!(transform.source([0.9, 0.5]), None, "past the content reads nothing without repeat"); + transform = TileTransform { offset: [0.25, 0.0], ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.75, 0.5])); + assert!(near(transform.source([0.9, 0.5]).unwrap_or_default(), [0.15, 0.5]), "the read wraps round the tile"); + transform = TileTransform { flip: FlipMode::Horizontally, ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.8, 0.3])); + transform.flip = FlipMode::Vertically; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.2, 0.7])); + } + + #[test] + fn a_tile_safe_turn_moves_whole_tiles_per_edge() { + let transform = TileTransform { scaling: [2.0, 2.0], rotation: 30.0, ..TileTransform::LIBRARY }; + let (columns, _) = transform.affine(); + assert_eq!(columns, [[2.0, 1.0], [-1.0, 2.0]], "the turn snaps to whole steps, about 26.6°"); + + // A small turn of the plain tile snaps back to no turn, never to nothing + let small = TileTransform { rotation: 10.0, ..TileTransform::LIBRARY }; + assert_eq!(small.affine().0, [[1.0, 0.0], [0.0, 1.0]]); + let tiny = TileTransform { scaling: [0.1, 0.1], rotation: 45.0, ..TileTransform::LIBRARY }; + assert!(tiny.affine().0.iter().all(|column| column != &[0.0, 0.0])); + + // Unsafe, the turn is exact + let free = TileTransform { tile_safe: false, ..transform }; + assert!((free.affine().0[0][1] - 2.0 * 30f32.to_radians().sin()).abs() < 1e-5); + + // A square turn keeps its scaling + let square = TileTransform { scaling: [1.5, 1.5], rotation: 90.0, ..TileTransform::LIBRARY }; + assert!((square.affine().0[1][0] + 1.5).abs() < 1e-5); + + // A turn just short of a whole one is square too (a tiny negative turn is stored that way) + let nearly_whole = TileTransform { scaling: [1.5, 1.5], rotation: 359.99995, ..TileTransform::LIBRARY }; + assert!((nearly_whole.affine().0[0][0] - 1.5).abs() < 1e-5, "{:?}", nearly_whole.affine().0); + } + + #[test] + fn a_tile_safe_turn_never_rounds_both_steps_onto_one_line() { + // Narrow and tall, turned half a quarter: both steps round straight down, so one moves off that line + let narrow = TileTransform { scaling: [0.1, 2.0], rotation: 45.0, ..TileTransform::LIBRARY }; + + let (columns, _) = narrow.affine(); + + assert!(determinant(columns) > 0.0, "the source is read in two directions: {columns:?}"); + } + + #[test] + fn a_turn_a_hair_short_of_a_whole_one_changes_nothing() { + for tile_safe in [true, false] { + let transform = TileTransform { rotation: 359.99998, tile_safe, ..TileTransform::LIBRARY }; + assert!(transform.is_identity(), "tile safe {tile_safe}: {:?}", transform.affine()); + } + assert!(!TileTransform { rotation: 359.9, tile_safe: false, ..TileTransform::LIBRARY }.is_identity()); + } + + #[test] + fn hostile_values_stay_in_the_tile() { + let transform = TileTransform { scaling: [f32::NAN, f32::INFINITY], offset: [f32::NAN, -1e30], rotation: f32::INFINITY, ..TileTransform::LIBRARY }; + let [u, v] = transform.source([0.9, 0.9]).unwrap_or_default(); + assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)); + } +} diff --git a/crates/core/src/tile_transform/flip_mode.rs b/crates/core/src/tile_transform/flip_mode.rs new file mode 100644 index 00000000..fc008c48 --- /dev/null +++ b/crates/core/src/tile_transform/flip_mode.rs @@ -0,0 +1,49 @@ +use serde::{Deserialize, Serialize}; + +/// Which way the Transform filter turns its result over +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FlipMode { + #[default] + None, + /// Left and right swap + Horizontally, + /// Top and bottom swap + Vertically, + HorizontallyAndVertically, +} + +impl FlipMode { + /// Every mode, in the order a list shows them + pub const ALL: [FlipMode; 4] = [FlipMode::None, FlipMode::Horizontally, FlipMode::Vertically, FlipMode::HorizontallyAndVertically]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + FlipMode::None => "None", + FlipMode::Horizontally => "Horizontally", + FlipMode::Vertically => "Vertically", + FlipMode::HorizontallyAndVertically => "Horizontally & Vertically", + } + } + + /// The id `effect.set {flipMode}` takes + pub fn id(self) -> &'static str { + match self { + FlipMode::None => "none", + FlipMode::Horizontally => "horizontally", + FlipMode::Vertically => "vertically", + FlipMode::HorizontallyAndVertically => "horizontallyAndVertically", + } + } + + /// Whether it swaps across (left and right) and down (top and bottom) + pub fn sides(self) -> [bool; 2] { + match self { + FlipMode::None => [false, false], + FlipMode::Horizontally => [true, false], + FlipMode::Vertically => [false, true], + FlipMode::HorizontallyAndVertically => [true, true], + } + } +} diff --git a/crates/core/src/tile_transform/repeat_mode.rs b/crates/core/src/tile_transform/repeat_mode.rs new file mode 100644 index 00000000..adc7be88 --- /dev/null +++ b/crates/core/src/tile_transform/repeat_mode.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +/// Whether a moved texture repeats across its UV tile or leaves empty where it no longer reaches +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum RepeatMode { + /// Past the tile's edge reads empty + None, + /// The tile repeats both ways, so the result stays seamless + #[default] + HorizontallyAndVertically, +} + +impl RepeatMode { + /// Every mode, in the order a list shows them + pub const ALL: [RepeatMode; 2] = [RepeatMode::None, RepeatMode::HorizontallyAndVertically]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + RepeatMode::None => "None", + RepeatMode::HorizontallyAndVertically => "Horizontally & Vertically", + } + } + + /// The id `effect.set {repeatMode}` takes + pub fn id(self) -> &'static str { + match self { + RepeatMode::None => "none", + RepeatMode::HorizontallyAndVertically => "horizontallyAndVertically", + } + } +} diff --git a/crates/core/src/validation_mode.rs b/crates/core/src/validation_mode.rs new file mode 100644 index 00000000..b46ac99a --- /dev/null +++ b/crates/core/src/validation_mode.rs @@ -0,0 +1,46 @@ +//! Which texels PBR Validate checks + +use serde::{Deserialize, Serialize}; + +/// PBR Validate's Validation Mode: the non-metal base colors, the metal ones, or both +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ValidationMode { + Albedo, + Metal, + #[default] + Combined, +} + +impl ValidationMode { + /// Every mode, in the order a switch shows them + pub const ALL: [ValidationMode; 3] = [ValidationMode::Albedo, ValidationMode::Metal, ValidationMode::Combined]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + ValidationMode::Albedo => "Albedo", + ValidationMode::Metal => "Metal", + ValidationMode::Combined => "Combined", + } + } + + /// The id `effect.set {validationMode}` takes + pub fn id(self) -> &'static str { + match self { + ValidationMode::Albedo => "albedo", + ValidationMode::Metal => "metal", + ValidationMode::Combined => "combined", + } + } + + /// Whether non-metal base colors are checked + pub fn checks_albedo(self) -> bool { + self != ValidationMode::Metal + } + + /// Whether metal base colors are checked + pub fn checks_metal(self) -> bool { + self != ValidationMode::Albedo + } +} diff --git a/crates/core/src/warp_blending.rs b/crates/core/src/warp_blending.rs new file mode 100644 index 00000000..f5e2d0bd --- /dev/null +++ b/crates/core/src/warp_blending.rs @@ -0,0 +1,42 @@ +//! How a Multi Directional Warp combines its directions + +use serde::{Deserialize, Serialize}; + +/// How the reads of a Multi Directional Warp's directions combine +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WarpBlending { + #[default] + Average, + /// The largest of them, per component + Max, + /// The smallest of them, per component + Min, + /// One move after the other, each from where the last one landed + Chain, +} + +impl WarpBlending { + /// Every choice, in the order a panel lists them + pub const ALL: [WarpBlending; 4] = [WarpBlending::Average, WarpBlending::Max, WarpBlending::Min, WarpBlending::Chain]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + WarpBlending::Average => "Average", + WarpBlending::Max => "Max", + WarpBlending::Min => "Min", + WarpBlending::Chain => "Chain", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + WarpBlending::Average => "average", + WarpBlending::Max => "max", + WarpBlending::Min => "min", + WarpBlending::Chain => "chain", + } + } +} diff --git a/crates/core/src/warp_mode.rs b/crates/core/src/warp_mode.rs new file mode 100644 index 00000000..95fe042b --- /dev/null +++ b/crates/core/src/warp_mode.rs @@ -0,0 +1,39 @@ +//! How a Warp moves the texels it reads + +use serde::{Deserialize, Serialize}; + +/// Which way a Warp moves texels: along its source's slope, along one direction, or along several +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WarpMode { + /// Along the source's slope, each texel its own way + #[default] + Warp, + /// Along the Angle, forwards or backwards by the source + Directional, + /// Along Directions spread evenly from the Angle, blended + MultiDirectional, +} + +impl WarpMode { + /// Every choice, in the order a panel lists them + pub const ALL: [WarpMode; 3] = [WarpMode::Warp, WarpMode::Directional, WarpMode::MultiDirectional]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + WarpMode::Warp => "Warp", + WarpMode::Directional => "Directional Warp", + WarpMode::MultiDirectional => "Multi Directional Warp", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + WarpMode::Warp => "warp", + WarpMode::Directional => "directional", + WarpMode::MultiDirectional => "multiDirectional", + } + } +} diff --git a/crates/core/src/warp_source_mode.rs b/crates/core/src/warp_source_mode.rs new file mode 100644 index 00000000..8452f627 --- /dev/null +++ b/crates/core/src/warp_source_mode.rs @@ -0,0 +1,39 @@ +//! What drives a Warp + +use serde::{Deserialize, Serialize}; + +/// The values a Warp's moves follow +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WarpSourceMode { + /// Fractal noise of the Warp's seed + #[default] + DefaultNoise, + /// The values the Warp filters (their luminance) + PreviousInput, + /// An image input (until one is linked: flat, so nothing moves) + CustomNoise, +} + +impl WarpSourceMode { + /// Every choice, in the order a panel lists them + pub const ALL: [WarpSourceMode; 3] = [WarpSourceMode::DefaultNoise, WarpSourceMode::PreviousInput, WarpSourceMode::CustomNoise]; + + /// The name a panel shows + pub fn label(self) -> &'static str { + match self { + WarpSourceMode::DefaultNoise => "Default Noise", + WarpSourceMode::PreviousInput => "Previous Input", + WarpSourceMode::CustomNoise => "Custom Noise", + } + } + + /// The id `effect.set` takes + pub fn id(self) -> &'static str { + match self { + WarpSourceMode::DefaultNoise => "defaultNoise", + WarpSourceMode::PreviousInput => "previousInput", + WarpSourceMode::CustomNoise => "customNoise", + } + } +} diff --git a/crates/engine/src/filter_about.rs b/crates/engine/src/filter_about.rs new file mode 100644 index 00000000..b27bcc26 --- /dev/null +++ b/crates/engine/src/filter_about.rs @@ -0,0 +1,85 @@ +//! What each library filter does, in one sentence, and the words it is found by: the Attributes of its properties + +/// A library filter's description and tags +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FilterAbout { + pub description: &'static str, + pub tags: &'static [&'static str], +} + +const fn about(description: &'static str, tags: &'static [&'static str]) -> FilterAbout { + FilterAbout { description, tags } +} + +/// One entry per library filter id, found by its id +const ABOUT: &[(&str, FilterAbout)] = &[ + ("hsl", about("Shifts the hue and changes the saturation and lightness of the colors.", &["color", "hue", "saturation", "lightness"])), + ("levels", about("Remaps the values between new black and white points, with a midtone gamma.", &["levels", "contrast", "remap"])), + ("contrastLuminosity", about("Raises or lowers the contrast and the overall brightness.", &["contrast", "brightness"])), + ("colorBalance", about("Tints the shadows, midtones and highlights each towards a color.", &["color", "tint", "balance"])), + ( + "colorCorrect", + about("Corrects the contrast, luminosity and saturation of the shadows, midtones and highlights.", &["color", "correction", "saturation"]), + ), + ("gradientMap", about("Replaces each value by the color at its place on a gradient.", &["gradient", "color", "remap"])), + ("gradientCurve", about("Bends the values through a curve preset.", &["gradient", "curve", "remap"])), + ("gradientDynamic", about("Reads the colors along a gradient source at each value's position.", &["gradient", "color", "dynamic"])), + ("posterize", about("Rounds the values to a few steps.", &["steps", "quantize", "flat"])), + ("clamp", about("Keeps the values between a minimum and a maximum.", &["clamp", "range", "limit"])), + ("smoothstep", about("Eases the values between a minimum and a maximum from black to white.", &["smoothstep", "range", "ease"])), + ("heightAdjust", about("Flips, scales and raises heights around mid gray.", &["height", "offset", "multiply"])), + ("histogramScan", about("Turns the values into a sharp or soft cut at a chosen position.", &["histogram", "contrast", "cut"])), + ("histogramRange", about("Squeezes the values into a narrower range around a position.", &["histogram", "range"])), + ("histogramShift", about("Slides the values along and wraps them around.", &["histogram", "shift", "wrap"])), + ("invert", about("Turns dark into light and light into dark.", &["invert", "negative"])), + ("threshold", about("Makes every value white past the threshold and black below it.", &["threshold", "black and white", "cut"])), + ("grayscale", about("Turns the colors into grays.", &["grayscale", "desaturate"])), + ("edgeDetect", about("Draws lines where the values change sharply.", &["edges", "outline", "lines"])), + ("normalInvert", about("Flips the green component of a normal map.", &["normal", "invert", "green"])), + ("bakedLighting", about("Paints sun, sky and light shading into the base color from the baked mesh maps.", &["lighting", "stylized", "shading"])), + ("bakedLightingEnvironment", about("Lights the base color with the viewport environment.", &["lighting", "environment", "shading"])), + ("replaceColor", about("Swaps one color for another, keeping the shading.", &["color", "replace", "swap"])), + ("blur", about("Softens the input: each texel spreads into its neighbours.", &["blur", "soften"])), + ("blurDirectional", about("Smears the input along one direction.", &["blur", "motion", "direction"])), + ("slopeBlur", about("Smears the values downhill along a noise height field.", &["blur", "slope", "flow"])), + ("sharpen", about("Makes the details crisper.", &["sharpen", "detail"])), + ("highPass", about("Keeps the fine details and drops the broad shapes.", &["detail", "high pass", "frequency"])), + ("bevel", about("Slopes the shapes down to their edge, or raises a slope around them.", &["bevel", "edge", "slope"])), + ("bevelSmooth", about("Draws a smooth ramp from the edge of the shapes.", &["bevel", "edge", "ramp"])), + ("directionalDistance", about("Draws a trail fading away from the shapes towards an angle.", &["distance", "trail", "leak"])), + ("glow", about("Lays a soft halo of color around the shapes.", &["glow", "halo", "light"])), + ("dropShadow", about("Lays a blurred, offset shadow of the shapes under them.", &["shadow", "drop shadow"])), + ("maskOutline", about("Draws a band along the edge of the shapes.", &["outline", "edge", "stroke"])), + ("warp", about("Moves the texels by a noise or another source.", &["warp", "distort", "noise"])), + ("mosaic", about("Breaks the input into square pixels, a set number across the UV tile.", &["pixelate", "mosaic", "cells"])), + ("fxaa", about("Smooths stair-stepped edges by blending across them.", &["anti-aliasing", "edges", "smooth"])), + ("anisotropicKuwahara", about("Smooths the input into painterly strokes that follow its direction.", &["painterly", "smooth", "stylize"])), + ("pbrValidate", about("Shows in red the base colors outside the physically plausible ranges.", &["pbr", "validate", "albedo", "metal"])), + ("colorMatch", about("Moves the colors so a source color, the texture's mean by default, lands on a target color.", &["color", "match", "recolor"])), + ("heightToNormal", about("Turns the layer's height into its normal.", &["height", "normal", "convert"])), + ("mirror", about("Copies one side of each UV tile over the other.", &["mirror", "symmetry", "flip"])), + ("transform", about("Scales, turns, moves and flips the content of each UV tile.", &["transform", "scale", "rotate", "offset", "flip"])), + ("matFinishGrind", about("Gives the material a ground finish: fine brushed lines in its roughness.", &["material", "metal", "scratches"])), + ("matFinishRaw", about("Gives the material a raw finish: uneven, cloudy roughness.", &["material", "raw", "rough"])), + ("matFinishSanded", about("Gives the material a sanded finish: a fine, even grain in its roughness.", &["material", "sanded", "rough"])), + ("matFinishHammered", about("Gives the material a hammered finish: round dents in its roughness.", &["material", "metal", "hammered"])), +]; + +/// The description and tags of library filter `id` (its exact id) +pub fn of(id: &str) -> Option { + ABOUT.iter().find(|(entry, _)| *entry == id).map(|(_, about)| *about) +} + +#[cfg(test)] +mod tests { + use super::of; + use crate::filter_lib::FILTERS; + + #[test] + fn every_library_filter_is_described_and_tagged() { + for def in FILTERS { + let about = of(def.id).unwrap_or_else(|| panic!("{} has no description", def.id)); + assert!(about.description.ends_with('.') && !about.tags.is_empty(), "{}", def.id); + } + } +} diff --git a/crates/engine/src/folder_cmds.rs b/crates/engine/src/folder_cmds.rs index dbf9f8f7..5b22cf50 100644 --- a/crates/engine/src/folder_cmds.rs +++ b/crates/engine/src/folder_cmds.rs @@ -217,6 +217,8 @@ fn layer_seeds(layer: &mut Layer) -> Vec<&mut u32> { EffectKind::Material(fill) => seeds.extend(fill.sources.values_mut().filter_map(source_seed)), EffectKind::Generator(generator) => seeds.push(&mut generator.seed), EffectKind::Filter(Filter::Warp { seed, .. } | Filter::SlopeBlur { seed, .. } | Filter::DirectionalWarp { seed, .. }) => seeds.push(seed), + EffectKind::Filter(Filter::SourceWarp(warp)) => seeds.push(&mut warp.seed), + EffectKind::Filter(Filter::SourceSlopeBlur(slope)) => seeds.push(&mut slope.seed), _ => {} } } @@ -236,6 +238,10 @@ fn seed_count(layer: &Layer) -> usize { EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })), EffectKind::Material(fill) => fill_seeds(fill), EffectKind::Generator(_) | EffectKind::Filter(Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. }) => 1, + EffectKind::Generator(_) + | EffectKind::Filter( + Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. } | Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_), + ) => 1, _ => 0, }) .sum(); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 87ccb68e..09cdaecb 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -74,6 +74,12 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { effect.channel_blends.iter().map(|(channel, blend)| (channel.id().to_string(), json!({ "blend": blend.mode.label(), "opacity": blend.opacity }))); out["channelBlends"] = Value::Object(channels.collect()); } + if !effect.off_channels.is_empty() { + out["offChannels"] = json!(effect.off_channels.iter().map(|channel| channel.id()).collect::>()); + } + if !effect.inputs.is_empty() { + out["inputs"] = Value::Object(effect.inputs.iter().map(|(id, source)| (id.clone(), source_json(source))).collect()); + } 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::(); @@ -119,8 +125,8 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { 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), + Filter::Hsl { hue, saturation, lightness, .. } => out["hsl"] = json!([hue, saturation, lightness]), + Filter::Blur { radius, .. } => out["radius"] = json!(radius), _ => {} } } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 1a36ef38..61d2611e 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -5,6 +5,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, + Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, ImageInput, Layer, LayerId, LayerKind, + NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; use texturecraft_paint::alphas::{self, LibraryAlpha}; @@ -122,6 +124,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)} | {effect: filter effect id, input: image input id (distanceMap, customNoise), value?|procedural?|image?|alpha?|anchor? as a mask fill's source, or clear: true (back to its default gray)}", has_layer, fill_set ), @@ -566,11 +569,13 @@ fn mask_source_mut(s: &mut Session, effect: LayerId) -> Result<&mut Source> { } fn fill_set(session: &mut Session, params: &Value) -> Result { + if let Some(input) = strp(params, "input") { + return input_set(session, params, input); + } let target = fill_target(session, params, FILL_SET)?; if let FillTarget::Mask(effect) = target { return mask_fill_set(session, params, effect); } - let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off @@ -683,6 +688,43 @@ fn mask_fill_set(s: &mut Session, p: &Value, effect: LayerId) -> Result { Ok(Value::Null) } +/// `layer.fill.set {effect, input}`: the source of a filter effect's image input `id`, or its default gray back (`clear`) +fn input_set(s: &mut Session, p: &Value, id: &str) -> Result { + let effect = u64p(p, "effect").map(LayerId).ok_or_else(|| bad(FILL_SET, "`input` goes with a filter `effect`"))?; + let found = s.doc.project.effect(effect).map(|(_, found)| found).ok_or_else(|| bad(FILL_SET, format!("no effect {}", effect.0)))?; + let EffectKind::Filter(filter) = &found.kind else { return Err(bad(FILL_SET, format!("{} is not a filter effect", effect.0))) }; + let input = ImageInput::named(filter, id).ok_or_else(|| bad(FILL_SET, format!("the {} filter has no image input `{id}`", filter.label())))?; + refuse_gray_keys(p, "an image input")?; + + let (source, library_alpha) = if p.get("clear").and_then(Value::as_bool) == Some(true) { + (None, None) + } else { + let (source, alpha) = gray_source(s, p, effect, found.input(&input))?; + (Some(source), alpha) + }; + + // Its default gray is not stored, so a project that never set the input saves as before + let stored = source.filter(|source| *source != input.default_source()); + + // Setting what the input already reads adds no undo step + if found.inputs.get(input.id) == stored.as_ref() && library_alpha_present(s, library_alpha) { + return Ok(Value::Null); + } + + s.edit("Set image input", |s| { + if let Some(alpha) = library_alpha { + s.add_library_alpha(alpha)?; + } + let found = s.doc.project.effect_mut(effect).ok_or_else(|| bad(FILL_SET, "the effect is gone"))?; + match stored { + Some(source) => found.inputs.insert(input.id.to_string(), source), + None => found.inputs.remove(input.id), + }; + Ok(()) + })?; + Ok(Value::Null) +} + /// Refuses the [`GRAY_REFUSED_KEYS`] for `subject`, a fill with one grayscale source fn refuse_gray_keys(p: &Value, subject: &str) -> Result<()> { if GRAY_REFUSED_KEYS.iter().any(|key| p.get(key).is_some()) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 53c87e71..23c6b489 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -24,6 +24,7 @@ pub mod fill_hit_test; pub mod fill_material_cmds; pub mod fill_mode; pub mod fill_reset_cmds; +pub mod filter_about; pub mod filter_lib; pub mod folder_cmds; mod frame_target; @@ -73,10 +74,12 @@ mod session_log; pub mod set_cmds; pub mod smart_masks; mod solo; +mod stylized_lighting_params; pub mod swatch_cmds; pub mod template_cmds; pub mod text_cmds; pub mod thumbs; +mod tile_transform_params; mod tool_availability; pub mod tool_cmds; pub mod tool_settings; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 93c25a02..899f71cb 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -12,6 +12,9 @@ use crate::mask_owner::MaskOwner; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; +/// The `filter` id of a filter effect with no filter picked +pub const EMPTY_FILTER: &str = "none"; + pub fn specs() -> Vec { vec![ cmd!("mask.add.white", "Add white mask", ["Layers", "Mask"], None, "{layer?}", has_layer, |s, p| add_mask(s, p, MaskBackground::White)), @@ -68,7 +71,7 @@ pub fn specs() -> Vec { "Add filter", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", + "{layer?, target?: mask|content, name?, filter?: any id or label from filter.list (warpDirectional adds Warp in its Directional mode) or \"none\" for an empty filter that changes nothing, level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], positions?: [0..1, ...], quantity?: 2..10, grayscaleMode?: desaturation|luma|average|max|min, blur?, balance?, invert?, linear?, debug?, preset?: round|pinch|stairs|easeOut|ease|easeIn|peakOut|peak|peakIn|bump|doubleBump|triangular, orientation?: horizontal|vertical, color?, levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", has_layer, add_filter ), @@ -96,6 +99,7 @@ pub fn specs() -> Vec { [], None, "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -293,6 +297,14 @@ fn push_effect_in( if let Some(name) = name_param(p) { effect.name = name.to_string(); } + + // A filter that changes only some channels (lighting, validation) starts with the other channels' pills off + if content + && let EffectKind::Filter(filter) = &effect.kind + && let Some(on) = filter.starts_on() + { + effect.off_channels = Channel::ALL.into_iter().filter(|channel| !on.contains(channel)).collect(); + } if !content { layer.mask.get_or_insert_with(|| Mask::new(background)).effects.push(effect); } else if layer.is_group() { @@ -586,7 +598,9 @@ fn add_levels(s: &mut Session, p: &Value) -> Result { fn add_filter(s: &mut Session, p: &Value) -> Result { let id = strp(p, "filter").unwrap_or("invert"); - let kind = crate::filter_lib::build(id, p)?; + + // An empty filter changes nothing until one is picked into it + let kind = if id == EMPTY_FILTER { EffectKind::Filter(Filter::Empty) } else { crate::filter_lib::build(id, p)? }; // Library filters are named after their shelf entry (material finishes are fill effects) let mut p = p.clone(); @@ -718,6 +732,11 @@ fn set(session: &mut Session, params: &Value) -> Result { return Err(bad(CMD, "a mask's levels remap its one value: leave out `affects`")); } + let switched = switched_channels(params)?; + if !switched.is_empty() && on_mask { + return Err(bad(CMD, "a mask effect has one value: leave out `channels`")); + } + // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one let anchor = match session.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { @@ -755,9 +774,15 @@ fn set(session: &mut Session, params: &Value) -> Result { _ => None, }; - // Naming the filter the effect already is edits its parameters like a plain effect.set + // Naming the filter the effect already is edits its parameters like a plain effect.set (Directional Warp's former id also sets its mode); a warp saved before the warp modes has no mode to set, so another mode replaces it as a swap does + let changes_saved_warp_mode = |filter: &str| matches!(session.doc.project.effect(effect), Some((_, Effect { kind: EffectKind::Filter(saved), .. })) if crate::filter_lib::changes_saved_warp_mode(filter, params, saved)); let swapped = match strp(params, "filter") { - Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None, + Some(EMPTY_FILTER) => Some(emptied_filter(session, effect)?), + Some(filter) + if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) && !changes_saved_warp_mode(filter) => + { + None + } Some(filter) => Some(swapped_filter(session, effect, filter, params)?), None => None, }; @@ -769,7 +794,7 @@ fn set(session: &mut Session, params: &Value) -> Result { let edited = session.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 == old.label() || Some(edited.name.as_str()) == old.former_label()) { edited.name = label.to_string(); } @@ -779,6 +804,13 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(visible) = boolp(params, "visible") { edited.visible = visible; } + for (channel, on) in &switched { + if *on { + edited.off_channels.remove(channel); + } else { + edited.off_channels.insert(*channel); + } + } crate::effect_blending_cmds::set_blending(edited, channel, blend, f32p(params, "opacity")); if let Some(name) = name_param(params) { edited.name = name.to_string(); @@ -813,7 +845,7 @@ fn set(session: &mut Session, params: &Value) -> Result { // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} - EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, + EffectKind::Filter(filter) => crate::filter_lib::apply_named(strp(params, "filter"), params, filter, CMD)?, EffectKind::Fill { source, projection, .. } => { // `uniform` picks the source, so it outranks settings that would edit the current pattern let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none()); @@ -883,6 +915,30 @@ fn fill_pattern(command: &str, params: &Value, current: &Source) -> Result Result> { + const CMD: &str = "effect.set"; + let Some(given) = params.get("channels") else { return Ok(Vec::new()) }; + let given = given.as_object().ok_or_else(|| bad(CMD, "`channels` must be an object of channel ids to true (on) or false (off)"))?; + given + .iter() + .map(|(id, on)| { + let channel = Channel::parse(id).ok_or_else(|| bad(CMD, format!("unknown channel `{id}`")))?; + let on = on.as_bool().ok_or_else(|| bad(CMD, format!("`channels.{id}` must be true or false")))?; + Ok((channel, on)) + }) + .collect() +} + +/// An empty filter and its label, to replace filter effect `effect`'s +fn emptied_filter(s: &Session, effect: LayerId) -> Result<(EffectKind, &'static str)> { + match s.doc.project.effect(effect) { + Some((_, Effect { kind: EffectKind::Filter(_), .. })) => Ok((EffectKind::Filter(Filter::Empty), Filter::Empty.label())), + Some((_, other)) => Err(bad("effect.set", format!("`filter` changes filter effects only, not {}", other.kind.name().to_ascii_lowercase()))), + None => Err(bad("effect.set", format!("no effect {}", effect.0))), + } +} + /// 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 { @@ -900,10 +956,9 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<( } let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?; - let mut kind = crate::filter_lib::build(def.id, &Value::Null)?; - let EffectKind::Filter(filter) = &mut kind else { + 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)); @@ -911,7 +966,8 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<( return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); } - crate::filter_lib::apply(p, filter, CMD)?; + // Built as effect.add.filter builds it, from the id given, so a former id such as `warpDirectional` sets the same mode it adds with + let kind = crate::filter_lib::build_for(CMD, id, p)?; Ok((kind, def.label)) } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index e3638c2f..4a27474f 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -51,12 +51,10 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, out.extend(link.outputs.values().cloned()); } } - for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { - out.extend(effect.kind.images_read().map(str::to_string)); + out.extend(effect.images_read().map(str::to_string)); out.extend(crate::path_tool::path_images(&effect.kind)); } - for child in layer.children() { images_used(project, *child, out, depth + 1); } diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 15d8c072..a0e6d366 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -2,7 +2,10 @@ use rayon::prelude::*; use texturecraft_compose::pattern::{Coords, procedural}; -use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, SIZE_REFERENCE_RES, Source, TextureSet, + TileTransform, +}; use texturecraft_geom::glam::{Vec2, Vec3}; use crate::materials::{Builder, build}; @@ -88,16 +91,16 @@ pub fn material(id: &str, size: usize) -> Option>> { /// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K). fn magnified(f: Filter, k: f32) -> Filter { match f { - Filter::Blur { radius } => Filter::Blur { radius: radius * k }, + Filter::Blur { radius, wrap } => Filter::Blur { radius: radius * k, wrap }, Filter::DirectionalBlur { radius, angle } => Filter::DirectionalBlur { radius: radius * k, angle }, - Filter::SlopeBlur { radius, scale, seed } => Filter::SlopeBlur { radius: radius * k, scale, seed }, - Filter::Warp { intensity, scale, seed } => Filter::Warp { intensity: intensity * k, scale, seed }, - Filter::HighPass { radius } => Filter::HighPass { radius: radius * k }, + Filter::SlopeBlur { radius, scale, seed, divider } => Filter::SlopeBlur { radius: radius * k, scale, seed, divider }, + Filter::Warp { intensity, scale, seed, divider } => Filter::Warp { intensity: intensity * k, scale, seed, divider }, + Filter::HighPass { radius, space, alpha } => Filter::HighPass { radius: radius * k, space, alpha }, Filter::EdgeDetect { width } => Filter::EdgeDetect { width: width * k }, - Filter::Bevel { width } => Filter::Bevel { width: width * k }, - Filter::Mosaic { size } => Filter::Mosaic { size: size * k }, + Filter::Bevel { width, wrap } => Filter::Bevel { width: width * k, wrap }, + Filter::Mosaic { size, alpha } => Filter::Mosaic { size: size * k, alpha }, Filter::Glow { radius, amount } => Filter::Glow { radius: radius * k, amount }, - Filter::DirectionalWarp { intensity, angle, scale, seed } => Filter::DirectionalWarp { intensity: intensity * k, angle, scale, seed }, + Filter::DirectionalWarp { intensity, angle, scale, seed, divider } => Filter::DirectionalWarp { intensity: intensity * k, angle, scale, seed, divider }, f => f, } } @@ -108,9 +111,16 @@ fn magnified(f: Filter, k: f32) -> Filter { pub fn filter(id: &str, size: usize) -> Option>> { let res = u32::try_from(size).ok()?.max(1); let kind = match crate::filter_lib::build(id, &serde_json::Value::Null).ok()? { - EffectKind::Filter(f) => EffectKind::Filter(magnified(f, 2048.0 / res as f32)), + // Transform changes nothing as the library adds it: its picture shows it scaled and turned + EffectKind::Filter(Filter::Transform(transform)) => { + EffectKind::Filter(Filter::Transform(TileTransform { scaling: [2.0, 2.0], rotation: 30.0, ..transform })) + } + EffectKind::Filter(f) => EffectKind::Filter(magnified(f, SIZE_REFERENCE_RES / res as f32)), k => k, }; + + // The filters that shape a mask's edge read where values cross 0.5: they get black and white shapes, where the clouds would leave them black + let shapes = matches!(kind, EffectKind::Filter(Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))); let mesh = texturecraft_geom::primitives::plane(2.0, 2); let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res); let mut p = Project::new("preview", ""); @@ -118,7 +128,12 @@ pub fn filter(id: &str, size: usize) -> Option>> { let procedural = |kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high, ramp: Vec::new() }; let mut fill = Fill::default(); - fill.sources.insert(Channel::BaseColor, procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1])); + let base = if shapes { + procedural(ProceduralKind::Checker, 3.0, [0.0; 3], [1.0; 3]) + } else { + procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1]) + }; + fill.sources.insert(Channel::BaseColor, base); fill.sources.insert(Channel::Roughness, procedural(ProceduralKind::Checker, 4.0, [0.25; 3], [0.7; 3])); fill.sources.insert(Channel::Height, procedural(ProceduralKind::Cells, 3.0, [-0.12; 3], [0.12; 3])); let mut layer = Layer::new(p.alloc_id(), "sample", LayerKind::Fill(fill), &CHANNELS); @@ -192,4 +207,18 @@ mod tests { let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); assert!(plain != warped, "the warp shows in its preview"); } + + #[test] + fn the_edge_shaping_filters_show_their_shapes_not_black() { + let size = 32; + // A neutral filter shows the checker as it is; an edge filter must change it + let checker = filter("levels", size).unwrap(); + for id in ["bevelSmooth", "directionalDistance"] { + let pixels = filter(id, size).unwrap(); + assert!(pixels != checker, "{id}: the preview shows the unchanged checker"); + let lit: Vec = pixels.into_iter().flatten().map(|sample| sample.base.iter().sum::() / 3.0).collect(); + let bright = lit.iter().filter(|value| **value > 0.25).count(); + assert!(bright * 5 > lit.len(), "{id}: {bright} of {} texels lit", lit.len()); + } + } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index fbb0b9f3..2f5ad634 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -757,41 +757,38 @@ impl Session { (Some(previous), Some(current)) => !Arc::ptr_eq(previous, current), (previous, current) => previous.is_some() != current.is_some(), }; - if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(resource_changed)) { + if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(|name| resource_changed(&name))) { self.path_cache = None; } // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); - if removed_or_replaced_resource { - for cache in &mut self.caches { - cache.invalidate_all(); - } - - return; - } - let added_resource_names: BTreeSet<&str> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); - let is_added = |name: &str| added_resource_names.contains(name); let uses_added_resource = |texture_set_index: usize| { - use texturecraft_core::{EffectKind, Fill}; - - let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); - let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); - let project = &self.doc.project; - !added_resource_names.is_empty() - && project.texture_sets.get(texture_set_index).is_some_and(|set| { - project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { - matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) - || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| { effect.kind.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill)) - }) - }) + let uses_added_resource = |texture_set_index: usize| { + use texturecraft_core::{EffectKind, Fill}; + + let is_added = |name: &str| added_resource_names.contains(name); + let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); + let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); + let project = &self.doc.project; + !added_resource_names.is_empty() + && project.texture_sets.get(texture_set_index).is_some_and(|set| { + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) + || layer + .mask + .iter() + .flat_map(|mask| &mask.effects) + .chain(&layer.content_effects) + .any(|effect| effect.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill))) }) - }; + }) + }; let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default()); let stack_key = |document: &Document, texture_set_index: usize| { let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default(); diff --git a/crates/engine/src/tile_transform_params.rs b/crates/engine/src/tile_transform_params.rs new file mode 100644 index 00000000..86a0f807 --- /dev/null +++ b/crates/engine/src/tile_transform_params.rs @@ -0,0 +1,52 @@ +//! `effect.set` on a Transform filter: repeatMode, flipMode, scaling, offset, tileSafeRotation and rotation + +use serde_json::Value; +use texturecraft_core::{FlipMode, RepeatMode, TileTransform}; + +use crate::Result; +use crate::commands::{bad, boolp, f32p, strp}; +use crate::layer_cmds::FULL_TURN_DEGREES; + +/// Set the Transform settings given in `p`; a value of the wrong kind is refused and changes nothing +pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Result<()> { + let mut edited = *transform; + if p.get("repeatMode").is_some() { + let id = strp(p, "repeatMode").unwrap_or_default(); + edited.repeat = + RepeatMode::ALL.into_iter().find(|mode| mode.id() == id).ok_or_else(|| bad(cmd, "`repeatMode` must be none or horizontallyAndVertically"))?; + } + if p.get("flipMode").is_some() { + let id = strp(p, "flipMode").unwrap_or_default(); + edited.flip = FlipMode::ALL + .into_iter() + .find(|mode| mode.id() == id) + .ok_or_else(|| bad(cmd, "`flipMode` must be none, horizontally, vertically or horizontallyAndVertically"))?; + } + let (low, high) = TileTransform::SCALING; + if let Some(scaling) = pair(p, "scaling", cmd)? { + edited.scaling = scaling.map(|scale| scale.clamp(low, high)); + } + if let Some(offset) = pair(p, "offset", cmd)? { + edited.offset = offset.map(|along| along.clamp(-TileTransform::MAX_OFFSET, TileTransform::MAX_OFFSET)); + } + if p.get("tileSafeRotation").is_some() { + edited.tile_safe = boolp(p, "tileSafeRotation").ok_or_else(|| bad(cmd, "`tileSafeRotation` must be true or false"))?; + } + if p.get("rotation").is_some() { + let degrees = f32p(p, "rotation").ok_or_else(|| bad(cmd, "`rotation` must be a number of degrees"))?; + edited.rotation = degrees.rem_euclid(FULL_TURN_DEGREES); + } + *transform = edited; + Ok(()) +} + +/// `[x, y]` (or one number for both) under `key`, if given; anything else is refused +fn pair(p: &Value, key: &str, cmd: &str) -> Result> { + let Some(value) = p.get(key) else { return Ok(None) }; + let number = |item: &Value| item.as_f64().map(|value| value as f32).filter(|value| value.is_finite()); + let parsed = match value { + Value::Array(items) if items.len() == 2 => items.first().and_then(number).zip(items.get(1).and_then(number)).map(|(x, y)| [x, y]), + other => number(other).map(|both| [both, both]), + }; + parsed.map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y] or one number"))) +} diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 6d77ebf5..e02220c9 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use texturecraft_core::project::ENVIRONMENTS; -use texturecraft_core::{BakedMap, Channel, EnvAlignment, ShadowMode, ToneMapping}; +use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping}; use texturecraft_geom::glam::Vec3; use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p}; @@ -301,6 +301,7 @@ fn display(s: &mut Session, p: &Value) -> Result { } let scatter_color = color_param("display.set", p, "scatterColor")?; + let (environment_before, rotation_before) = (s.doc.project.display.environment.clone(), s.doc.project.display.env_rotation); let settings = &mut s.doc.project.display; if let Some(picked) = environment { settings.environment = picked; @@ -368,10 +369,27 @@ fn display(s: &mut Session, p: &Value) -> Result { if f32p(p, "fov").is_some() { s.camera.fov = s.doc.project.display.fov; } + + // Baked Lighting Environment lights with the viewport environment: the layers it lights composite again when that turns or changes + let display = &s.doc.project.display; + if (display.environment.as_str(), display.env_rotation) != (environment_before.as_str(), rotation_before) && lit_by_environment(&s.doc.project) { + for cache in &mut s.caches { + cache.invalidate_all(); + } + } s.revision = s.revision.wrapping_add(1); Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null)) } +/// Whether a layer's content has a Baked Lighting Environment +fn lit_by_environment(project: &Project) -> bool { + project + .layers + .values() + .flat_map(|layer| layer.content_effects.iter()) + .any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. }))) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index 8274f5d8..f1414b05 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -33,54 +33,39 @@ fn id(reply: Value, key: &str) -> u64 { fn content_effects_commands_inspect_and_round_trip() { let mut s = session(); let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer"); - let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "hue": 1.0 / 3.0})).unwrap(), "effect"); - + let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "mode": "regular", "hue": 1.0 / 3.0})).unwrap(), "effect"); assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor)); assert!(s.doc.project.layer(LayerId(layer)).unwrap().mask.is_none(), "content effects don't create a mask"); assert_eq!(s.target, StackTarget::Effect(LayerId(hsl))); - // Mask-only effects refuse the content, unknown targets are errors + // Mask-only effects refuse the content, unknown targets are errors. assert!(execute(&mut s, "effect.add.generator", &json!({"target": "content"})).is_err()); assert!(execute(&mut s, "effect.add.filter", &json!({"target": "nope"})).is_err()); - execute(&mut s, "effect.set", &json!({"effect": hsl, "hue": 0.0, "lightness": -1.0})).unwrap(); - assert!(close(center(&mut s, Channel::BaseColor), [0.0; 3])); - execute(&mut s, "effect.set", &json!({"effect": hsl, "visible": false})).unwrap(); - // A content fill effect, edited through layer.fill.set + // A content fill effect, edited through layer.fill.set. let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect"); - assert!(close(center(&mut s, Channel::Roughness), [0.7; 3])); assert!(close(center(&mut s, Channel::BaseColor), [1.0, 0.0, 0.0]), "channels without a source stay"); - execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "value": 0.9})).unwrap(); - assert!(close(center(&mut s, Channel::Roughness), [0.9; 3])); - execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "enabled": false})).unwrap(); - assert!(close(center(&mut s, Channel::Roughness), [0.2; 3])); assert!(execute(&mut s, "layer.fill.set", &json!({"effect": hsl, "channel": "roughness", "value": 0.5})).is_err(), "not a fill effect"); - // Inspect shows the content stack; the project survives a save/load round trip + // Inspect shows the content stack; the project survives a save/load round trip. let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); let kinds: Vec<&str> = row["contentEffects"].as_array().unwrap().iter().map(|effect| effect["kind"].as_str().unwrap()).collect(); - assert_eq!(kinds, ["HSL Perceptive", "Fill"], "{row}"); - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.doc.project, s.doc.project); execute(&mut s, "layer.select", &json!({"layer": layer, "target": fill})).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": fill})).unwrap(); - assert_eq!(s.target, StackTarget::Content); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert_eq!(s.doc.project.layer(LayerId(layer)).unwrap().content_effects.len(), 2); } diff --git a/crates/engine/tests/it/filter_card.rs b/crates/engine/tests/it/filter_card.rs new file mode 100644 index 00000000..ee9c25af --- /dev/null +++ b/crates/engine/tests/it/filter_card.rs @@ -0,0 +1,140 @@ +//! The Filter effect card: an empty filter, its content channels switched on and off, Intensity's divider, Restore defaults and the Attributes it lists + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, Filter, LayerId, SourceSlopeBlur, SourceWarp}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, center, facing_session as session, filter_of, set}; + +fn assert_close(actual: [f32; 3], expected: [f32; 3], what: &str) { + assert!((0..3).all(|i| (actual[i] - expected[i]).abs() < 4e-3), "{what}: {actual:?}, expected {expected:?}"); +} + +/// A fill layer of base color 0.2 and roughness 0.3 under content filter `params`: (layer, effect) +fn filtered_layer(s: &mut Session, params: Value) -> (u64, LayerId) { + let layer = execute(s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.3})).unwrap()["layer"].as_u64().unwrap(); + (layer, add_filter(s, params)) +} + +/// An empty filter changes nothing and is named for it; picking a filter names it after the filter, × empties it again +#[test] +fn an_empty_filter_renders_nothing_until_one_is_picked() { + let mut s = session(); + let (_, effect) = filtered_layer(&mut s, json!({"filter": "none"})); + + assert_eq!(filter_of(&s, effect), Filter::Empty); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Filter (empty)"); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "an empty filter leaves the color"); + + set(&mut s, effect, json!({"filter": "invert"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Invert"); + assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the picked filter works"); + + set(&mut s, effect, json!({"filter": "none"})); + assert_eq!(filter_of(&s, effect), Filter::Empty); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "emptied again"); +} + +/// A content filter switched off for a channel leaves that channel; inspect lists it; masks refuse `channels` +#[test] +fn a_content_filter_leaves_the_channels_switched_off() { + let mut s = session(); + let (layer, effect) = filtered_layer(&mut s, json!({"filter": "invert"})); + + assert_close(center(&mut s, Channel::Roughness), [0.7; 3], "every channel at first"); + + set(&mut s, effect, json!({"channels": {"roughness": false}})); + assert_close(center(&mut s, Channel::Roughness), [0.3; 3], "roughness switched off"); + assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the color still inverted"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); + let filter_row = row["contentEffects"].as_array().unwrap().iter().find(|filter_row| filter_row["id"] == effect.0).unwrap(); + assert_eq!(filter_row["offChannels"], json!(["roughness"])); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.7; 3], "one undo step"); + + set(&mut s, effect, json!({"channels": {"roughness": false}})); + set(&mut s, effect, json!({"channels": {"roughness": true}})); + assert!(s.doc.project.effect(effect).unwrap().1.off_channels.is_empty()); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"nope": false}})).is_err()); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"roughness": 1}})).is_err()); + + let masked = execute(&mut s, "effect.add.filter", &json!({"filter": "invert", "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + + assert!(execute(&mut s, "effect.set", &json!({"effect": masked, "channels": {"roughness": false}})).is_err()); +} + +/// Intensity ÷ Divider: warp 0.5 ÷ 10 renders as warp 0.05; only 1, 10, 100 and 1000 are taken; a divider of 1 is not saved +#[test] +fn the_divider_divides_the_intensity() { + let warp = |intensity: f32, divider: u16| { + let mut s = session(); + execute(&mut s, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "checker", "scale": 8.0})).unwrap(); + let params = json!({"filter": "warp", "target": "content", "intensity": intensity, "seed": 5}); + let effect = execute(&mut s, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": effect, "divider": divider})).unwrap(); + s.update(); + (0..SIZE).step_by(7).map(|x| s.caches[0].composite.value(Channel::BaseColor, x, SIZE / 2)[0]).collect::>() + }; + let divided = warp(0.5, 10); + assert_eq!(divided, warp(0.05, 1), "0.5 ÷ 10 = 0.05"); + assert_ne!(divided, warp(0.5, 1), "the divider changes the warp"); + + let mut s = session(); + let (_, effect) = filtered_layer(&mut s, json!({"filter": "slopeBlur"})); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "divider": 7})).is_err()); + + set(&mut s, effect, json!({"divider": 100})); + assert!(matches!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur { divider: 100, .. }))); + + let saved = serde_json::to_value(Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }).unwrap(); + assert_eq!(saved, json!({"Warp": {"intensity": 1.0, "scale": 2.0, "seed": 3}}), "saved as before dividers"); + + let loaded: Filter = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded, Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }); +} + +/// Restore defaults puts the parameters back in one undo step, keeping the name and switched-off channels; none at defaults +#[test] +fn restore_defaults_puts_the_filters_parameters_back() { + let mut s = session(); + let (_, effect) = filtered_layer(&mut s, json!({"filter": "warp", "name": "Wobble"})); + let defaults = filter_of(&s, effect); + let steps = s.history_labels().len(); + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": false})); + assert_eq!(s.history_labels().len(), steps, "no step at defaults"); + + set(&mut s, effect, json!({"intensity": 0.5, "seed": 9, "divider": 100, "channels": {"height": false}})); + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": true})); + assert_eq!(filter_of(&s, effect), defaults); + + let restored = s.doc.project.effect(effect).unwrap().1.clone(); + assert_eq!(restored.name, "Wobble"); + assert!(restored.off_channels.contains(&Channel::Height)); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(matches!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp { divider: 100, seed: 9, .. })), "one undo step"); + + let empty = filtered_layer(&mut s, json!({"filter": "none"})).1; + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": empty.0})).unwrap(), json!({"changed": false})); + + let fill = execute(&mut s, "effect.add.fill", &json!({"target": "content"})).unwrap()["effect"].as_u64().unwrap(); + assert!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": fill})).is_err()); +} + +#[test] +fn filter_list_describes_and_tags_every_filter() { + let mut s = session(); + let listed = execute(&mut s, "filter.list", &Value::Null).unwrap(); + for def in listed.as_array().unwrap() { + assert!(def["description"].as_str().is_some_and(|text| !text.is_empty()), "{def}"); + assert!(def["tags"].as_array().is_some_and(|tags| !tags.is_empty()), "{def}"); + } + let blur = listed.as_array().unwrap().iter().find(|def| def["id"] == "blur").unwrap(); + assert_eq!(blur["tags"], json!(["blur", "soften"])); +} diff --git a/crates/engine/tests/it/filter_colour.rs b/crates/engine/tests/it/filter_colour.rs new file mode 100644 index 00000000..f0bc3561 --- /dev/null +++ b/crates/engine/tests/it/filter_colour.rs @@ -0,0 +1,100 @@ +//! The colour filters (Color Balance, Color Correct, HSL Perceptive, Contrast Luminosity) and the shared edge wrap of Blur and Bevel + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Bevel, Channel, Filter}; +use texturecraft_engine::execute; + +use crate::filter_support::{center, facing_session as session, filter_of, filtered, set}; + +fn distance(a: [f32; 3], b: [f32; 3]) -> f32 { + (0..3).map(|i| (a[i] - b[i]).abs()).fold(0.0, f32::max) +} + +/// Color Correct: neutral by default, then each tone's contrast, luminosity and saturation; one undo step per edit +#[test] +fn color_correct_changes_nothing_until_its_tones_move() { + let mut s = session(); + let color = [0.6, 0.3, 0.2]; + let effect = filtered(&mut s, color, json!({"filter": "colorCorrect"})); + let neutral = filter_of(&s, effect); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Color Correct"); + assert!(distance(center(&mut s, Channel::BaseColor), color) < 4e-3, "the defaults change nothing"); + + set(&mut s, effect, json!({"shadows": [0.0, 0.0, 0.0], "midtones": [0.0, 0.0, 0.0], "highlights": [0.0, 0.0, 0.0]})); + let gray = center(&mut s, Channel::BaseColor); + assert!((gray[0] - gray[1]).abs() < 4e-3 && (gray[1] - gray[2]).abs() < 4e-3, "saturation 0 everywhere is gray: {gray:?}"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(filter_of(&s, effect), neutral, "one undo step takes back all three tones"); + + set(&mut s, effect, json!({"midtones": [0.0, 0.3, 0.5], "shadows": [0.0, 0.3, 0.5], "highlights": [0.0, 0.3, 0.5]})); + let lighter = center(&mut s, Channel::BaseColor); + assert!((0..3).all(|i| lighter[i] > color[i] + 0.1), "luminosity lifts every tone: {lighter:?}"); + + let roughness = center(&mut s, Channel::Roughness); + assert!(roughness[0] > 0.4, "scalars take contrast and luminosity: {roughness:?}"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "midtones": "x"})).is_err()); + + let Filter::ColorCorrect { midtones, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(midtones, [0.0, 0.3, 0.5], "a refused edit changes nothing"); + + set(&mut s, effect, json!({"midtones": [5.0, -5.0, 5.0]})); + let Filter::ColorCorrect { midtones, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(midtones, [1.0, -1.0, 1.0], "clamped to the ranges"); +} + +/// HSL Perceptive: a new filter is Perceptive, projects saved before stay Regular; a perceptive hue turn keeps lightness better +#[test] +fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { + let mut s = session(); + let yellow = [0.8, 0.7, 0.05]; + let effect = filtered(&mut s, yellow, json!({"filter": "hsl", "hue": 0.5})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: true, .. }), "new filters are perceptive"); + + let perceptive = center(&mut s, Channel::BaseColor); + set(&mut s, effect, json!({"mode": "regular"})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: false, .. })); + + let regular = center(&mut s, Channel::BaseColor); + // Rec. 709 luminance weights + let relative_luminance = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; + let drift = |color: [f32; 3]| (relative_luminance(color) - relative_luminance(yellow)).abs(); + assert!(drift(perceptive) < drift(regular), "perceptive {perceptive:?} regular {regular:?}"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "vivid"})).is_err()); + + // Saved before the mode: Regular, and saved again without the field + let old: Filter = serde_json::from_value(json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})).unwrap(); + assert_eq!(old, Filter::Hsl { hue: 0.5, saturation: 0.0, lightness: 0.0, perceptive: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})); +} + +/// Contrast Luminosity starts neutral (contrast 0) like the other colour filters +#[test] +fn contrast_luminosity_starts_neutral() { + let mut s = session(); + let effect = filtered(&mut s, [0.2; 3], json!({"filter": "contrastLuminosity"})); + assert_eq!(filter_of(&s, effect), Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.0 }); + assert!(distance(center(&mut s, Channel::BaseColor), [0.2; 3]) < 4e-3); +} + +/// Blur and Bevel take the shared edge wrap: effect.set {wrap}, saved only when on, old projects load with it off +#[test] +fn blur_and_bevel_take_the_edge_wrap() { + let mut s = session(); + let blur = filtered(&mut s, [0.2; 3], json!({"filter": "blur"})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: false, .. })); + + set(&mut s, blur, json!({"wrap": true})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: true, .. })); + + assert!(execute(&mut s, "effect.set", &json!({"effect": blur.0, "wrap": "yes"})).is_err()); + + let bevel = filtered(&mut s, [0.2; 3], json!({"filter": "bevel", "wrap": true})); + assert!(matches!(filter_of(&s, bevel), Filter::DistanceBevel(Bevel { wrap: true, .. }))); + + let old: Filter = serde_json::from_value(json!({"Blur": {"radius": 4.0}})).unwrap(); + assert_eq!(old, Filter::Blur { radius: 4.0, wrap: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Blur": {"radius": 4.0}}), "off is not saved"); +} diff --git a/crates/engine/tests/it/filter_gradient.rs b/crates/engine/tests/it/filter_gradient.rs new file mode 100644 index 00000000..738c5390 --- /dev/null +++ b/crates/engine/tests/it/filter_gradient.rs @@ -0,0 +1,168 @@ +//! The gradient filters: Gradient (positions, quantity, input transformation, linear blending, debug), Gradient Curve and Gradient Dynamic + +use serde_json::json; +use texturecraft_engine::core::{Channel, EffectKind, Filter, GrayscaleMode, layer::gradient}; +use texturecraft_engine::execute; +use texturecraft_engine::filter_lib::{LIBRARY_GRADIENT_CURVE, LIBRARY_GRADIENT_DYNAMIC, MID_GRAY}; + +use crate::filter_support::{add_filter, center, center_uv, facing_session as session, filter_of, filtered, refused, set}; + +fn near(a: f32, b: f32) -> bool { + (a - b).abs() < 6e-3 +} + +/// Projects saved before read a gradient as evenly spaced colors from the texel's luma, blended in linear, and save it as before +#[test] +fn a_gradient_saved_before_reads_and_saves_as_before() { + let saved = json!({"GradientMap": {"colors": [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]}}); + let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]])); + assert_eq!(serde_json::to_value(&filter).unwrap(), saved, "nothing new is saved"); + + let Filter::GradientMap { colors, input, .. } = &filter else { panic!() }; + assert_eq!(input.mode, GrayscaleMode::Luma); + + for t in [0.0, 0.2, 0.37, 0.5, 0.81, 1.0] { + assert_eq!(filter.ramp_at(t), gradient(colors, t), "bit for bit as before at {t}"); + } +} + +/// The library's Gradient: black, mid gray and white at 0, 0.5 and 1; places, quantity, invert, balance and linear blending move what a texel reads +#[test] +fn gradient_places_quantity_and_input_transformation() { + let mut s = session(); + let effect = filtered(&mut s, [0.25; 3], json!({"filter": "gradientMap"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient"); + + let Filter::GradientMap { quantity, input, linear, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!((quantity, input.mode, linear), (Some(3), GrayscaleMode::Average, true)); + + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY / 2.0), "halfway from black to mid gray"); + + set(&mut s, effect, json!({"positions": [0.0, 0.25, 1.0]})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY), "mid gray moved to 0.25"); + + set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.5 / 0.75)), "inverted, it reads 0.75"); + + set(&mut s, effect, json!({"invert": false, "balance": 0.75})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.25 / 0.75)), "balance 0.75 lifts it to 0.5"); + + set(&mut s, effect, json!({"balance": 0.5, "positions": [0.0, 0.5, 1.0], "linear": false})); + let srgb = center(&mut s, Channel::BaseColor)[0]; + assert!(near(srgb, 0.0508), "blended in sRGB, halfway from black to mid gray is sRGB 0.25: {srgb}"); + + set(&mut s, effect, json!({"quantity": 4})); + assert_eq!(filter_of(&s, effect).ramp_colors().len(), 4); + + refused( + &mut s, + effect, + &[ + json!({"quantity": 11}), + json!({"quantity": 1}), + json!({"grayscaleMode": "x"}), + json!({"positions": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]}), + json!({"debug": 3}), + ], + ); + + set(&mut s, effect, json!({"grayscaleMode": "max"})); + let Filter::GradientMap { input, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(input.mode, GrayscaleMode::Max); +} + +/// A new gradient given its colors alone ramps evenly through every one of them +#[test] +fn a_gradient_given_colors_alone_ramps_evenly_through_all_of_them() { + let mut s = session(); + + let two = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap", "colors": [[0, 0, 0], [1, 1, 1]]})); + let mid = center(&mut s, Channel::BaseColor)[0]; + assert!(near(mid, 0.5), "black to white reads mid gray halfway: {mid}"); + + execute(&mut s, "effect.remove", &json!({"effect": two.0})).unwrap(); + let five = add_filter(&mut s, json!({"filter": "gradientMap", "colors": [[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75], [1, 1, 1]]})); + assert_eq!(filter_of(&s, five).ramp_colors().len(), 5, "every color is used"); +} + +/// Display Gradient (Debug) shows the ramp left to right across the texture +#[test] +fn display_gradient_shows_the_ramp_across_the_texture() { + let mut s = session(); + let effect = filtered(&mut s, [0.9; 3], json!({"filter": "gradientMap", "debug": true})); + let (value, uv) = (center(&mut s, Channel::BaseColor), center_uv(&mut s)); + let ramp = filter_of(&s, effect).ramp_at(uv.x).unwrap(); + assert!((0..3).all(|k| (value[k] - ramp[k]).abs() < 0.03), "{value:?} vs {ramp:?} at u {}", uv.x); +} + +/// An old gradient that gains a quantity keeps its colors' places and adds the new one at 1 +#[test] +fn a_saved_gradient_keeps_its_places_when_it_gains_a_color() { + let mut s = session(); + let effect = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap"})); + if let Some(found) = s.doc.project.effect_mut(effect) { + found.kind = EffectKind::Filter(Filter::even_gradient(vec![[0.0; 3], [1.0, 0.0, 0.0], [1.0; 3]])); + } + set(&mut s, effect, json!({"quantity": 4})); + let Filter::GradientMap { colors, positions, quantity, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!((positions, quantity), (vec![0.0, 0.5, 1.0, 1.0], Some(4))); + assert_eq!(colors.last(), Some(&[1.0; 3]), "the new color starts as the last one"); +} + +/// A color added at 1 starts as the ramp's color there: its rightmost stop's, not the last one listed +#[test] +fn an_added_color_keeps_the_ramps_end() { + let mut s = session(); + let effect = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap", "colors": [[1, 1, 1], [0, 0, 0]]})); + set(&mut s, effect, json!({"positions": [0.8, 0.2]})); + let before = filter_of(&s, effect).ramp_at(0.9); + + set(&mut s, effect, json!({"quantity": 3})); + + assert_eq!(before, Some([1.0; 3]), "white past its stop at 0.8"); + assert_eq!(filter_of(&s, effect).ramp_at(0.9), before, "the added color at 1 keeps the end white"); +} + +/// Gradient Curve: values remapped through the preset after balance, contrast and invert +#[test] +fn gradient_curve_remaps_through_its_preset() { + let mut s = session(); + let effect = filtered(&mut s, [0.25; 3], json!({"filter": "gradientCurve"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient Curve"); + assert_eq!(filter_of(&s, effect), LIBRARY_GRADIENT_CURVE, "the workflow's defaults"); + + let round = (1.0f32 - 0.75 * 0.75).sqrt(); + assert!(near(center(&mut s, Channel::BaseColor)[0], round), "Round at 0.25"); + + set(&mut s, effect, json!({"preset": "easeIn"})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.0625), "Ease In at 0.25"); + + set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.5625), "Ease In at 0.75"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "preset": "spiral"})).is_err()); + + let Filter::GradientCurve { preset, .. } = filter_of(&s, effect) else { panic!() }; + assert_eq!(preset.id(), "easeIn", "a refused preset changes nothing"); +} + +/// Gradient Dynamic with a uniform Gradient Source: every texel reads that color (scalars its gray) +#[test] +fn gradient_dynamic_reads_its_uniform_source() { + let mut s = session(); + let effect = filtered(&mut s, [0.9, 0.1, 0.1], json!({"filter": "gradientDynamic", "color": [0.2, 0.4, 0.6]})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient Dynamic"); + + let Filter::GradientDynamic { vertical, position, .. } = LIBRARY_GRADIENT_DYNAMIC else { panic!() }; + assert_eq!(filter_of(&s, effect), Filter::GradientDynamic { vertical, position, color: [0.2, 0.4, 0.6] }, "the workflow's defaults, the color given"); + + let color = center(&mut s, Channel::BaseColor); + assert!(near(color[0], 0.2) && near(color[1], 0.4) && near(color[2], 0.6), "{color:?}"); + + set(&mut s, effect, json!({"orientation": "vertical", "position": 0.7})); + let Filter::GradientDynamic { vertical, position, .. } = filter_of(&s, effect) else { panic!() }; + assert!(vertical && position == 0.7); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "orientation": "diagonal"})).is_err()); +} diff --git a/crates/engine/tests/it/filter_inputs.rs b/crates/engine/tests/it/filter_inputs.rs new file mode 100644 index 00000000..423eab27 --- /dev/null +++ b/crates/engine/tests/it/filter_inputs.rs @@ -0,0 +1,109 @@ +//! Filter image inputs: Bevel Smooth's and Directional Distance's Distance Map and Warp's Custom Noise read a source set on the effect + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Effect, LayerId, Source}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_shape::shape_edge; +use crate::filter_support::{SIZE, add_filter, roughness, session, set}; + +/// `layer.fill.set` on image input `params` of `effect`: its result, the error as text +fn input(s: &mut Session, effect: LayerId, params: Value) -> Result { + let mut params = params; + params["effect"] = json!(effect.0); + execute(s, "layer.fill.set", ¶ms).map_err(|error| error.to_string()) +} + +/// The image inputs `effect` holds, by input id +fn inputs(s: &Session, effect: LayerId) -> Vec<(String, Source)> { + let (_, found) = s.doc.project.effect(effect).unwrap(); + found.inputs.iter().map(|(id, source)| (id.clone(), source.clone())).collect() +} + +/// Bevel Smooth's Distance Map scales its distance texel by texel: a gray, an anchor's gray, back to white; its default is not stored; one undo step +#[test] +fn a_distance_map_scales_the_bevel_smooth_distance() { + let mut s = session(); + + // A layer below records a roughness of 0.5 at an anchor point + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.5})).unwrap(); + let anchor = LayerId(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap()["effect"].as_u64().unwrap()); + let (at, _, _) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "bevelSmooth"})); + + set(&mut s, effect, json!({"smoothing": 0.0})); + let full = roughness(&mut s, at(4)); + assert!(full > 0.0 && full < 1.0, "on the ramp: {full}"); + + input(&mut s, effect, json!({"input": "distanceMap", "value": 0.5})).unwrap(); + let half = roughness(&mut s, at(4)); + assert!(half < full - 0.05, "half the distance fades sooner: {half} vs {full}"); + assert_eq!(inputs(&s, effect), vec![("distanceMap".to_string(), Source::Uniform([0.5; 3]))]); + + let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"inputs\":{\"distanceMap\""), "inspect shows the input"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(inputs(&s, effect).is_empty(), "one undo step"); + assert_eq!(roughness(&mut s, at(4)), full); + + input(&mut s, effect, json!({"input": "distanceMap", "anchor": anchor.0, "anchorChannel": "roughness"})).unwrap(); + assert!((roughness(&mut s, at(4)) - half).abs() < 1e-3, "the anchor's 0.5 reads as the uniform 0.5"); + + input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty() && roughness(&mut s, at(4)) == full, "cleared: white, as before"); + + let steps = s.history_labels().len(); + input(&mut s, effect, json!({"input": "distanceMap", "value": 1.0})).unwrap(); + input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty(), "the default gray is not stored"); + assert_eq!(s.history_labels().len(), steps, "setting what the input already reads adds no undo step"); + + for bad in [json!({"input": "nope", "value": 0.5}), json!({"input": "distanceMap", "channel": "roughness", "value": 0.5}), json!({"input": "distanceMap"})] + { + assert!(input(&mut s, effect, bad.clone()).is_err(), "{bad}"); + } + assert!(input(&mut s, anchor, json!({"input": "distanceMap", "value": 0.5})).is_err(), "not a filter"); +} + +/// Directional Distance: a black Distance Map leaves no trail +#[test] +fn a_black_distance_map_leaves_no_trail() { + let mut s = session(); + let (at, _, outward) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "directionalDistance"})); + + set(&mut s, effect, json!({"angle": if outward > 0 { 0.0 } else { 180.0 }, "distance": 0.05})); + assert!(roughness(&mut s, at(1)) > 0.0, "a trail"); + + input(&mut s, effect, json!({"input": "distanceMap", "value": 0.0})).unwrap(); + assert_eq!((roughness(&mut s, at(1)), roughness(&mut s, at(-2))), (0.0, 1.0), "no trail, the shapes stay"); +} + +/// Warp's Custom Noise moves texels by its source; projects saved before image inputs load with none and save without them +#[test] +fn a_custom_noise_moves_the_warp() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + let row = SIZE / 2; + let before: Vec = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect(); + let moved = |s: &mut Session| (0..SIZE).map(|x| (roughness(s, (x, row)) - before[x as usize]).abs()).fold(0.0f32, f32::max); + + let effect = add_filter(&mut s, json!({"filter": "warp"})); + set(&mut s, effect, json!({"intensity": 0.05, "divider": 1, "warpMode": "directional", "sourceMode": "customNoise"})); + assert!(moved(&mut s) < 2e-3, "its default mid gray moves nothing"); + + input(&mut s, effect, json!({"input": "customNoise", "procedural": "gradient"})).unwrap(); + assert!(moved(&mut s) > 0.01, "a source moves texels: {}", moved(&mut s)); + + set(&mut s, effect, json!({"sourceMode": "defaultNoise"})); + assert_eq!(inputs(&s, effect).len(), 1, "kept while another source mode is on"); + + let (_, found) = s.doc.project.effect(effect).unwrap(); + let saved = serde_json::to_value(Effect { inputs: Default::default(), ..found.clone() }).unwrap(); + assert!(saved.get("inputs").is_none(), "no inputs, no key: saves as before"); + + let loaded: Effect = serde_json::from_value(saved).unwrap(); + assert!(loaded.inputs.is_empty(), "an effect saved before loads with none"); +} diff --git a/crates/engine/tests/it/filter_light.rs b/crates/engine/tests/it/filter_light.rs new file mode 100644 index 00000000..5fccb750 --- /dev/null +++ b/crates/engine/tests/it/filter_light.rs @@ -0,0 +1,204 @@ +//! The light filters: Glow, Drop Shadow, Baked Lighting Stylized and Baked Lighting Environment + +use serde_json::json; +use texturecraft_engine::core::{Channel, DirectionalLight, EffectKind, Filter, LayerId, LightingOutput}; +use texturecraft_engine::filter_lib::{LIBRARY_DROP_SHADOW, LIBRARY_ENVIRONMENT_LIGHTING, LIBRARY_GLOW, library_baked_lighting}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, refused, set}; + +/// A plane, so every texel faces the same way +fn session() -> Session { + Session::new_project("t", primitives::plane(2.0, 2), "builtin:plane", None, SIZE).unwrap() +} + +/// A fill layer with library filter `id` in its mask: the effect +fn masked(s: &mut Session, id: &str) -> LayerId { + execute(s, "layer.add.fill", &json!({})).unwrap(); + execute(s, "mask.add.black", &json!({})).unwrap(); + LayerId(execute(s, "effect.add.filter", &json!({"filter": id, "target": "mask"})).unwrap()["effect"].as_u64().unwrap()) +} + +/// Projects saved before keep their additive glow, read and saved as they were; a new Glow is the halo, named the same +#[test] +fn a_glow_saved_before_stays_additive_and_a_new_glow_is_the_halo() { + let saved = json!({"Glow": {"radius": 16.0, "amount": 1.0}}); + let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::Glow { radius: 16.0, amount: 1.0 }); + assert_eq!(serde_json::to_value(&filter).unwrap(), saved); + + let mut s = session(); + let effect = masked(&mut s, "glow"); + assert_eq!(filter_of(&s, effect), LIBRARY_GLOW, "the workflow's defaults"); + assert_eq!(filter_of(&s, effect).label(), "Glow"); + assert_eq!(filter.label(), "Glow"); +} + +/// Glow's Used on a Mask, Mode, Width (inner glow below 0), Spread, Opacity and Color set and clamp; bad values are refused +#[test] +fn glow_settings_set_clamp_and_refuse() { + let mut s = session(); + let effect = masked(&mut s, "glow"); + + set(&mut s, effect, json!({"usedOnMask": true, "mode": "precise", "width": -3.0, "spread": 0.4, "opacity": 0.6, "color": [0.2, 0.4, 0.6]})); + let glow = Filter::HaloGlow { on_mask: true, precise: true, width: -1.0, spread: 0.4, opacity: 0.6, color: [0.2, 0.4, 0.6] }; + assert_eq!(filter_of(&s, effect), glow); + + refused(&mut s, effect, &[json!({"mode": "hard"}), json!({"usedOnMask": 1}), json!({"color": "red"})]); + + assert_eq!(filter_of(&s, effect), glow); + + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); + assert_eq!(filter_of(&s, effect), LIBRARY_GLOW); +} + +/// Drop Shadow: the workflow's defaults, then Angle wrapping, Distance both ways, Size, Spread, Opacity and Color +#[test] +fn drop_shadow_defaults_and_settings() { + let mut s = session(); + let effect = masked(&mut s, "Drop Shadow"); + assert_eq!(filter_of(&s, effect), LIBRARY_DROP_SHADOW, "the workflow's defaults"); + + set(&mut s, effect, json!({"angle": 450.0, "distance": -0.9, "size": 2.0, "spread": 0.3, "opacity": 0.25, "color": "#ffffff"})); + assert_eq!(filter_of(&s, effect), Filter::DropShadow { angle: 90.0, distance: -0.5, size: 1.0, spread: 0.3, opacity: 0.25, color: [1.0; 3] }); + + refused(&mut s, effect, &[json!({"color": [1.0]})]); + + let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "dropShadow" && f["mask"] == true)); +} + +/// A content fill layer with library filter `id` on its content: the effect +fn on_content(s: &mut Session, id: &str) -> LayerId { + execute(s, "layer.add.fill", &json!({})).unwrap(); + add_filter(s, json!({"filter": id})) +} + +/// Projects saved before keep their Baked Lighting, read and saved as they were and named Baked Lighting Stylized; a new one takes the workflow's defaults +#[test] +fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { + let saved = json!({"BakedLighting": {"azimuth": 45.0, "elevation": 45.0, "light": 0.75, "ambient": 0.5, "occlusion": 1.0}}); + let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert!(filter.stylized_lighting().is_none(), "lights as before"); + assert_eq!(serde_json::to_value(&filter).unwrap(), saved); + assert_eq!(filter.label(), "Baked Lighting Stylized"); + assert_eq!(filter.former_label(), Some("Baked Lighting")); + + let mut s = session(); + let effect = on_content(&mut s, "Baked Lighting"); + let made = filter_of(&s, effect); + assert_eq!(made, library_baked_lighting(), "the workflow's sun, sky and lights"); + + let (stylized, _) = made.stylized_lighting().unwrap(); + assert_eq!( + (stylized.output, stylized.mesh_only, stylized.dielectric_reflectance, stylized.cavity_smoothness), + (LightingOutput::DiffuseSpecular, false, 0.04, 0.25) + ); + assert_eq!((stylized.lights[0].azimuth, stylized.lights[1].azimuth, stylized.lights[0].intensity), (90.0, 180.0, 0.0)); + + let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLighting" && f["mask"] == false && f["label"] == "Baked Lighting Stylized")); +} + +/// The stylized settings set and clamp; one set on a Baked Lighting saved before gives it the rest lit as it was; bad choices are refused +#[test] +fn stylized_lighting_settings_set_clamp_and_refuse() { + let mut s = session(); + let effect = on_content(&mut s, "bakedLighting"); + let old = Filter::BakedLighting { azimuth: 45.0, elevation: 45.0, light: 0.8, ambient: 0.4, occlusion: 1.0, stylized: None }; + s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old); + + set( + &mut s, + effect, + json!({ + "skyColor": [0.1, 0.2, 0.3], "light1": {"azimuth": 450.0, "elevation": -30.0, "intensity": 5.0, "color": "#ff0000"}, + "diffuseCavity": 0.5, "cavitySmoothness": 9.0, "dielectricReflectance": 1.0, "heightToNormal": 2.0, + "input": "specularGlossiness", "output": "specular", "normalDetails": "meshHeightNormal" + }), + ); + let filter = filter_of(&s, effect); + let (stylized, light) = filter.stylized_lighting().unwrap(); + assert_eq!((light.sun.intensity, light.sky_intensity, stylized.sun_color), (0.8, 0.4, [1.0; 3]), "the rest as it lit"); + + assert_eq!(stylized.sky_color, [0.1, 0.2, 0.3]); + assert_eq!(stylized.lights[0], DirectionalLight { azimuth: 90.0, elevation: 330.0, intensity: 2.0, color: [1.0, 0.0, 0.0] }); + assert_eq!((stylized.diffuse_cavity, stylized.cavity_smoothness, stylized.dielectric_reflectance, stylized.height_to_normal), (0.5, 4.0, 0.16, 2.0)); + assert!(stylized.specular_glossiness && !stylized.mesh_only && stylized.output == LightingOutput::Specular); + + refused( + &mut s, + effect, + &[json!({"output": "both"}), json!({"input": 1}), json!({"normalDetails": "height"}), json!({"light2": 3}), json!({"groundColor": "dirt"})], + ); + assert_eq!(filter_of(&s, effect), filter, "refusals change nothing"); + + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); + assert_eq!(filter_of(&s, effect).stylized_lighting().unwrap().0.output, LightingOutput::DiffuseSpecular); +} + +/// Baked Lighting Environment: the workflow's defaults, only the Color pill lit, rotations wrapping and the rest clamped, Restore defaults +#[test] +fn environment_lighting_defaults_and_settings() { + let mut s = session(); + let effect = on_content(&mut s, "bakedLightingEnvironment"); + let made = filter_of(&s, effect); + assert_eq!(made, LIBRARY_ENVIRONMENT_LIGHTING, "the workflow's defaults"); + assert_eq!((made.label(), s.doc.project.effect(effect).unwrap().1.name.as_str()), ("Baked Lighting Environment", "Baked Lighting Environment")); + + let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness) && off.contains(&Channel::Height), "only the Color pill is lit: {off:?}"); + + let stylized = on_content(&mut s, "bakedLighting"); + assert!(s.doc.project.effect(stylized).unwrap().1.off_channels.contains(&Channel::Metallic), "Baked Lighting Stylized lights the Color pill only too"); + + let blur = on_content(&mut s, "blur"); + assert!(s.doc.project.effect(blur).unwrap().1.off_channels.is_empty(), "other filters work on every channel"); + + set( + &mut s, + effect, + json!({"horizontalRotation": 370.0, "verticalRotation": -90.0, "exposure": 9.0, "heightIntensity": -1.0, "ambientOcclusion": 0.5, "specularOcclusion": 2.0}), + ); + assert_eq!( + filter_of(&s, effect), + Filter::EnvironmentLighting { + horizontal: 10.0, + vertical: 270.0, + exposure: 5.0, + height_intensity: 0.0, + ambient_occlusion: 0.5, + specular_occlusion: 1.0 + } + ); + + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); + assert_eq!(filter_of(&s, effect), made); + + let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLightingEnvironment" && f["mask"] == false)); +} + +/// Baked Lighting Environment lights the base color with the viewport environment: another environment relights it, Exposure brightens it +#[test] +fn environment_lighting_follows_the_viewport_environment() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap(); + let center = |s: &mut Session| { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, SIZE / 2, SIZE / 2) + }; + let unlit = center(&mut s); + + let effect = add_filter(&mut s, json!({"filter": "bakedLightingEnvironment"})); + let studio = center(&mut s); + assert_ne!(studio, unlit, "the studio lights the base color"); + + execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap(); + let night = center(&mut s); + assert!(night[0] < studio[0] * 0.5, "the night lights it less: {night:?} vs {studio:?}"); + + set(&mut s, effect, json!({"exposure": 3.0})); + assert!(center(&mut s)[0] > night[0], "exposure brightens it"); +} diff --git a/crates/engine/tests/it/filter_shape.rs b/crates/engine/tests/it/filter_shape.rs new file mode 100644 index 00000000..73dc6521 --- /dev/null +++ b/crates/engine/tests/it/filter_shape.rs @@ -0,0 +1,364 @@ +//! The shape filters: Threshold's modes, Mirror, Mask Outline, Bevel, Bevel Smooth, Directional Distance, Warp's modes and Blur Slope's source + +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + Bevel, BevelBlur, BevelCorner, BevelDirection, BevelSmooth, DirectionalDistance, EffectKind, Filter, MaskOutline, Mirror, MirrorCorner, MirrorMode, + OutlinePosition, SlopeBlending, SourceSlopeBlur, SourceWarp, ThresholdMode, WarpBlending, WarpMode, WarpSource, WarpSourceMode, +}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, refused, roughness, session, set}; + +/// Threshold: a new one is Greater than 0.01; each mode compares its way; one saved before keeps Greater or equal +#[test] +fn threshold_modes_compare_their_way() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + let effect = add_filter(&mut s, json!({"filter": "threshold"})); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }, "the library defaults"); + + let texel = (SIZE / 4, SIZE / 2); + assert_eq!(roughness(&mut s, texel), 1.0); + + set(&mut s, effect, json!({"level": 0.25})); + assert_eq!(roughness(&mut s, texel), 0.0, "a value at the level is not greater"); + + for (mode, white) in [("greaterOrEqual", 1.0), ("lower", 0.0), ("lowerOrEqual", 1.0)] { + set(&mut s, effect, json!({"mode": mode})); + assert_eq!(roughness(&mut s, texel), white, "{mode}"); + } + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "sideways"})).is_err()); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.25, mode: ThresholdMode::LowerOrEqual }, "a refused mode changes nothing"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }); +} + +/// Mirror: the left half of each UV tile copied onto the right (inverted the other way, or a corner onto the rest), its axis white in Display Debug +#[test] +fn mirror_copies_one_side_over_the_other() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + let row = SIZE / 2; + let (left, right) = ((20, row), (SIZE - 1 - 20, row)); + let (left_before, right_before) = (roughness(&mut s, left), roughness(&mut s, right)); + assert!((left_before - right_before).abs() > 0.05, "the gradient differs across: {left_before} {right_before}"); + + let effect = add_filter(&mut s, json!({"filter": "mirror"})); + assert_eq!(filter_of(&s, effect), Filter::Mirror(Mirror::LIBRARY)); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mirror"); + assert!((roughness(&mut s, left) - left_before).abs() < 2e-3, "the left side stays"); + assert!((roughness(&mut s, right) - left_before).abs() < 2e-3, "the right side reads the left"); + + set(&mut s, effect, json!({"invertAxisX": true})); + assert!((roughness(&mut s, left) - right_before).abs() < 2e-3, "inverted, the left side reads the right"); + + set(&mut s, effect, json!({"mode": "corner", "cornerType": "topRight"})); + assert!((roughness(&mut s, (20, 20)) - roughness(&mut s, (SIZE - 1 - 20, 20))).abs() < 2e-3, "a corner mirrors across too"); + + let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() }; + assert_eq!((mirror.mode, mirror.corner), (MirrorMode::Corner, MirrorCorner::TopRight)); + + set(&mut s, effect, json!({"mode": "axisX", "displayDebug": true})); + assert_eq!(roughness(&mut s, (SIZE / 2, row)), 1.0, "Display Debug draws the axis white"); + + refused(&mut s, effect, &[json!({"mode": "diagonal"}), json!({"cornerType": "middle"}), json!({"invertAxisY": "yes"})]); + + set(&mut s, effect, json!({"axisYOffset": 3.0})); + let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() }; + assert_eq!(mirror.offset, [0.5, 1.0], "offsets clamp to the tile"); +} + +/// Mask Outline: a band along the edge where the gradient crosses its Threshold, outside, inside or on both sides, on black or over the values +#[test] +fn mask_outline_draws_a_band_along_the_threshold_edge() { + let mut s = session(); + let (at, values, _) = shape_edge(&mut s); + + let effect = add_filter(&mut s, json!({"filter": "maskOutline"})); + assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mask Outline"); + + set(&mut s, effect, json!({"threshold": 0.5, "width": 0.03})); + assert_eq!(roughness(&mut s, at(2)), 1.0, "outside, next to the edge"); + assert_eq!(roughness(&mut s, at(8)), 0.0, "past the band"); + assert_eq!(roughness(&mut s, at(-2)), 0.0, "inside the shapes"); + + set(&mut s, effect, json!({"maskPosition": "inside"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 0.0), "inside"); + + set(&mut s, effect, json!({"maskPosition": "both"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 1.0), "both sides"); + + set(&mut s, effect, json!({"startFromBlack": false})); + let far = at(8); + assert!((roughness(&mut s, far) - values[far.0 as usize]).abs() < 2e-3, "over the values"); + + set(&mut s, effect, json!({"startFromBlack": true, "maskPosition": "outside", "blur": 1.0})); + let (near, further) = (roughness(&mut s, at(1)), roughness(&mut s, at(2))); + assert!(near > further && further > 0.0 && near < 1.0, "a blurred band fades out: {near} {further}"); + + refused(&mut s, effect, &[json!({"maskPosition": "around"}), json!({"startFromBlack": 1})]); + + set(&mut s, effect, json!({"width": 4.0, "curveShape": -3.0})); + let Filter::MaskOutline(outline) = filter_of(&s, effect) else { panic!() }; + assert_eq!((outline.position, outline.width, outline.curve), (OutlinePosition::Outside, 1.0, -1.0), "values clamp"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY)); +} + +/// A fill whose roughness is a repeating gradient: the middle row's values +fn gradient_row(s: &mut Session) -> Vec { + execute(s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + middle_row(s) +} + +/// The composited roughness along the middle row +fn middle_row(s: &mut Session) -> Vec { + (0..SIZE).map(|x| roughness(s, (x, SIZE / 2))).collect() +} + +/// A roughness gradient crossing 0.5 away from the tile's sides along the middle row: texel `steps` outward of the shapes' first texel at its edge (inward below 0), the values before any filter, and the outward direction along x +pub(crate) fn shape_edge(s: &mut Session) -> (impl Fn(i64) -> (u32, u32) + use<>, Vec, i64) { + let row = SIZE / 2; + let values = gradient_row(s); + let edge = (SIZE / 4..SIZE * 3 / 4).find(|x| (values[*x as usize] >= 0.5) != (values[*x as usize - 1] >= 0.5)).unwrap(); + let (inner, outward): (u32, i64) = if values[edge as usize] >= 0.5 { (edge, -1) } else { (edge - 1, 1) }; + (move |steps: i64| ((inner as i64 + steps * outward) as u32, row), values, outward) +} + +/// Bevel: a negative Distance slopes the shapes down to their edge, a positive one rises around them; Smoothing, Corner Type, Blur Mode and Wrap set; one saved before keeps its width bevel +#[test] +fn bevel_slopes_inwards_or_outwards() { + let mut s = session(); + let (at, values, _) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "bevel"})); + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Bevel"); + + let value = |at: (u32, u32)| values[at.0 as usize]; + + // Inwards over a tenth of the tile (12.8 texels here) + let (edge, outside) = (roughness(&mut s, at(0)), roughness(&mut s, at(3))); + assert!(edge < value(at(0)) * 0.2, "down at the edge: {edge} vs {}", value(at(0))); + assert!((outside - value(at(3))).abs() < 2e-3, "outside untouched"); + + set(&mut s, effect, json!({"distance": 0.1})); + let (near, further) = (roughness(&mut s, at(1)), roughness(&mut s, at(6))); + assert!(near > 0.8 && further > value(at(6)) && near > further, "rises around the shapes: {near} {further}"); + assert!((roughness(&mut s, at(-2)) - value(at(-2))).abs() < 2e-3, "inside untouched"); + + set(&mut s, effect, json!({"smoothing": 2.0, "blurMode": "uniform"})); + let smoothed = roughness(&mut s, at(1)); + assert!((smoothed - near).abs() > 1e-3, "smoothing blurs the slope: {smoothed} vs {near}"); + + set(&mut s, effect, json!({"cornerType": "angular", "wrap": true})); + refused(&mut s, effect, &[json!({"cornerType": "square"}), json!({"blurMode": "even"}), json!({"wrap": 1})]); + + set(&mut s, effect, json!({"distance": -3.0, "smoothing": 9.0})); + let expected = Bevel { wrap: true, distance: -1.0, corner: BevelCorner::Angular, smoothing: 5.0, blur: BevelBlur::Uniform }; + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(expected), "values clamp"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY)); + + let old: Filter = serde_json::from_value(json!({"Bevel": {"width": 16.0}})).unwrap(); + assert_eq!(old, Filter::Bevel { width: 16.0, wrap: false }, "a bevel saved before keeps its width"); +} + +/// Bevel Smooth: a ramp from the edge outwards (shapes white), inwards (around them black) or across it (mid gray on it) +#[test] +fn bevel_smooth_ramps_from_the_edge() { + let mut s = session(); + let (at, _, _) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "bevelSmooth"})); + assert_eq!(filter_of(&s, effect), Filter::BevelSmooth(BevelSmooth::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Bevel Smooth"); + + set(&mut s, effect, json!({"smoothing": 0.0})); + + let (inside, near, further) = (roughness(&mut s, at(-3)), roughness(&mut s, at(1)), roughness(&mut s, at(6))); + assert_eq!(inside, 1.0, "out: the shapes stay white"); + assert!(near > further && further > 0.0 && near < 1.0, "fades outwards: {near} {further}"); + + set(&mut s, effect, json!({"direction": "in"})); + let (outside, inner) = (roughness(&mut s, at(3)), roughness(&mut s, at(-3))); + assert!(outside == 0.0 && inner > 0.0 && inner < 1.0, "in: rises inwards: {outside} {inner}"); + + set(&mut s, effect, json!({"direction": "inOut"})); + let (edge_in, edge_out) = (roughness(&mut s, at(0)), roughness(&mut s, at(1))); + assert!(edge_in > 0.5 && edge_out < 0.5 && edge_in - edge_out < 0.2, "across: mid gray at the edge: {edge_in} {edge_out}"); + + set(&mut s, effect, json!({"curveOffset": 0.5})); + assert!(roughness(&mut s, at(0)) > edge_in, "the offset raises the ramp"); + + refused(&mut s, effect, &[json!({"direction": "up"}), json!({"wrap": "yes"})]); + + set(&mut s, effect, json!({"distance": 2.0, "smoothing": 20.0, "maskThreshold": -1.0, "distanceMapMultiplier": 4.0, "curveShape": 5.0})); + let Filter::BevelSmooth(smooth) = filter_of(&s, effect) else { panic!() }; + assert_eq!( + (smooth.direction, smooth.distance, smooth.smoothing, smooth.threshold, smooth.multiplier, smooth.curve_shape), + (BevelDirection::InOut, 0.3, 10.0, 0.0, 1.0, 1.0), + "values clamp" + ); +} + +/// Directional Distance: a trail fading away from the shapes towards its Angle, none against it +#[test] +fn directional_distance_trails_one_way() { + let mut s = session(); + let (at, _, outward) = shape_edge(&mut s); + let effect = add_filter(&mut s, json!({"filter": "directionalDistance"})); + assert_eq!(filter_of(&s, effect), Filter::DirectionalDistance(DirectionalDistance::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Directional Distance"); + + // Along the row, away from the shapes + let away = if outward > 0 { 0.0 } else { 180.0 }; + set(&mut s, effect, json!({"angle": away, "distance": 0.05})); + let (inside, near, further) = (roughness(&mut s, at(-2)), roughness(&mut s, at(1)), roughness(&mut s, at(4))); + assert_eq!(inside, 1.0, "the shapes are white"); + assert!(near > further && further > 0.0, "fades away from them: {near} {further}"); + + set(&mut s, effect, json!({"contrast": 0.5})); + assert_eq!(roughness(&mut s, at(1)), 1.0, "contrast hardens the near trail"); + + set(&mut s, effect, json!({"angle": away + 180.0, "contrast": 0.0})); + assert!(roughness(&mut s, at(1)) < near, "against the angle the edge gets less trail"); + + set(&mut s, effect, json!({"distance": 1.0, "angle": -90.0, "contrast": 3.0, "distanceMapMultiplier": -1.0})); + let expected = DirectionalDistance { distance: 0.3, angle: 270.0, contrast: 1.0, multiplier: 0.0 }; + assert_eq!(filter_of(&s, effect), Filter::DirectionalDistance(expected), "values clamp, the angle wraps"); +} + +/// Texels either side of a texel that must all rise (or fall) for the warp and slope tests to read it as on a slope +const SLOPE_WINDOW: usize = 8; + +/// Warp: library defaults, the former Directional Warp id, Previous Input moving texels by their values, blended directions, old saves +#[test] +fn warp_modes_move_texels_their_way() { + let mut s = session(); + let before = gradient_row(&mut s); + let after = middle_row; + let moved = |values: &[f32]| values.iter().zip(&before).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + + let effect = add_filter(&mut s, json!({"filter": "warp"})); + assert_eq!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Warp"); + + set(&mut s, effect, json!({"intensity": 0.05, "divider": 1})); + let warped = after(&mut s); + assert!(moved(&warped) > 0.01 && warped.iter().all(|v| v.is_finite()), "the noise moves texels: {}", moved(&warped)); + + set(&mut s, effect, json!({"intensity": 0.0})); + assert!(moved(&after(&mut s)) < 2e-3, "no intensity, no move"); + + // Along the gradient where it rises: a texel above mid gray reads further up it, so it gets lighter + let rising = |x: usize| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k]); + let falling = |x: usize| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] < before[k]); + let light = |x: &usize| (0.6..0.85).contains(&before[*x]); + let (texel, angle) = match (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| light(x) && rising(*x)) { + Some(x) => (x, 0.0), + None => ((SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| light(x) && falling(*x)).unwrap(), 180.0), + }; + set(&mut s, effect, json!({"intensity": 0.05, "warpMode": "directional", "angle": angle, "sourceMode": "previousInput"})); + let directional = after(&mut s); + assert!(directional[texel] > before[texel] + 0.01, "{} -> {}", before[texel], directional[texel]); + + set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing moves"); + + set(&mut s, effect, json!({"warpMode": "multiDirectional", "sourceMode": "defaultNoise", "directions": 2, "blendingMode": "max"})); + let max = after(&mut s); + set(&mut s, effect, json!({"blendingMode": "min"})); + let min = after(&mut s); + set(&mut s, effect, json!({"blendingMode": "average"})); + let average = after(&mut s); + assert!(max.iter().zip(&min).all(|(max, min)| max + 1e-4 >= *min) && max.iter().zip(&min).any(|(max, min)| max - min > 0.01), "Max over Min"); + assert!(average.iter().zip(max.iter().zip(&min)).all(|(average, (max, min))| *average <= max + 2e-3 && *average >= min - 2e-3), "the average between"); + + set(&mut s, effect, json!({"blendingMode": "chain", "directions": 4})); + assert!(after(&mut s).iter().all(|v| v.is_finite())); + + refused(&mut s, effect, &[json!({"warpMode": "spiral"}), json!({"directions": 3}), json!({"blendingMode": "sum"}), json!({"sourceMode": "image"})]); + + set(&mut s, effect, json!({"intensity": 5.0, "angle": -90.0, "sourceTiling": 99.0, "sourceBlur": -1.0, "seed": 7})); + let Filter::SourceWarp(warp) = filter_of(&s, effect) else { panic!() }; + assert_eq!((warp.intensity, warp.angle, warp.source.tiling, warp.source.blur, warp.seed), (1.0, 270.0, 16.0, 0.0, 7), "values clamp, the angle wraps"); + assert_eq!((warp.mode, warp.blending, warp.directions), (WarpMode::MultiDirectional, WarpBlending::Chain, 4)); + + let former = add_filter(&mut s, json!({"filter": "warpDirectional"})); + let directional = SourceWarp { mode: WarpMode::Directional, ..SourceWarp::LIBRARY }; + assert_eq!(filter_of(&s, former), Filter::SourceWarp(directional), "the former id adds a Directional Warp"); + + // Saved before the modes: loads as it was, and Restore defaults gives the warp of its mode + let saved = json!({"DirectionalWarp": {"intensity": 8.0, "angle": 30.0, "scale": 4.0, "seed": 3}}); + let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::DirectionalWarp { intensity: 8.0, angle: 30.0, scale: 4.0, seed: 3, divider: 1 }); + assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); + + s.doc.project.effect_mut(former).unwrap().kind = EffectKind::Filter(old); + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": former.0})).unwrap(); + assert_eq!(filter_of(&s, former), Filter::SourceWarp(directional)); +} + +/// Blur Slope: library defaults, Min under Blur under Max, reading downhill of its Previous Input, Quality, one undo, old saves +#[test] +fn slope_blur_reads_downhill_of_its_source() { + let mut s = session(); + let before = gradient_row(&mut s); + let after = middle_row; + let moved = |values: &[f32]| values.iter().zip(&before).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + + let effect = add_filter(&mut s, json!({"filter": "slopeBlur"})); + assert_eq!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY), "the library defaults"); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Blur Slope"); + + set(&mut s, effect, json!({"intensity": 0.05, "divider": 1})); + let blur = after(&mut s); + assert!(moved(&blur) > 0.005 && blur.iter().all(|v| v.is_finite()), "the noise's slope smears: {}", moved(&blur)); + + set(&mut s, effect, json!({"blendingMode": "min"})); + let min = after(&mut s); + set(&mut s, effect, json!({"blendingMode": "max"})); + let max = after(&mut s); + assert!(max.iter().zip(&min).all(|(max, min)| max + 1e-4 >= *min) && max.iter().zip(&min).any(|(max, min)| max - min > 0.01), "Max over Min"); + assert!(blur.iter().zip(max.iter().zip(&min)).all(|(blur, (max, min))| *blur <= max + 2e-3 && *blur >= min - 2e-3), "Blur between"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + let Filter::SourceSlopeBlur(slope) = filter_of(&s, effect) else { panic!() }; + assert_eq!(slope.blending, SlopeBlending::Min, "one undo step"); + + // Read downhill of the gradient itself: every texel where it rises reads darker values + set(&mut s, effect, json!({"blendingMode": "blur", "sourceMode": "previousInput"})); + let downhill = after(&mut s); + let rising = (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k] + 1e-4)).unwrap(); + assert!(downhill[rising] < before[rising] - 0.005, "{} -> {}", before[rising], downhill[rising]); + + set(&mut s, effect, json!({"quality": 0.0})); + let coarse = after(&mut s); + assert!(coarse.iter().all(|v| v.is_finite()) && coarse != downhill, "fewer reads, another smear"); + + set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing smears"); + + refused(&mut s, effect, &[json!({"blendingMode": "average"}), json!({"sourceMode": "image"}), json!({"divider": 7})]); + + set(&mut s, effect, json!({"intensity": 5.0, "quality": -1.0, "sourceTiling": 99.0, "sourceBlur": 2.0, "sourceBalance": 0.25, "seed": 7})); + let Filter::SourceSlopeBlur(slope) = filter_of(&s, effect) else { panic!() }; + let source = WarpSource { mode: WarpSourceMode::CustomNoise, blur: 1.0, balance: 0.25, contrast: 0.0, tiling: 16.0 }; + assert_eq!((slope.intensity, slope.quality, slope.source, slope.seed), (1.0, 0.0, source, 7), "values clamp"); + + // Saved before its source settings: loads and saves as it was, and Restore defaults gives today's Blur Slope + let saved = json!({"SlopeBlur": {"radius": 16.0, "scale": 4.0, "seed": 1}}); + let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1, divider: 1 }); + assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); + + s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old); + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY)); +} diff --git a/crates/engine/tests/it/filter_simple.rs b/crates/engine/tests/it/filter_simple.rs new file mode 100644 index 00000000..8b6bdaaa --- /dev/null +++ b/crates/engine/tests/it/filter_simple.rs @@ -0,0 +1,319 @@ +//! The simple adjustment filters, the blurs, Highpass and Grayscale Conversion + +use serde_json::json; +use texturecraft_engine::core::{Channel, ConversionMode, EffectKind, Filter, GrayscaleConversion, HighpassSpace, lum}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, filter_of, roughness, session, set}; + +/// A session with one roughness `value` fill +fn fill(value: f32) -> Session { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": value})).unwrap(); + s +} + +const TEXEL: (u32, u32) = (SIZE / 4, SIZE / 2); + +fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 2e-3 +} + +/// The library defaults leave the values as they are (Posterize steps them, Invert inverts) +#[test] +fn new_simple_filters_start_where_the_reference_does() { + let cases = [ + ("clamp", Filter::Clamp { min: 0.0, max: 1.0 }), + ("smoothstep", Filter::Smoothstep { min: 0.0, max: 1.0 }), + ("heightAdjust", Filter::HeightAdjust { invert: false, offset: 0.0, multiply: 1.0 }), + ("histogramScan", Filter::HistogramScan { position: 0.5, contrast: 0.0, invert_position: false }), + ("histogramShift", Filter::HistogramShift { offset: 0.0 }), + ("posterize", Filter::Posterize { levels: 8.0, alpha: false }), + ("invert", Filter::Invert), + ]; + for (id, defaults) in cases { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": id})); + assert_eq!(filter_of(&s, effect), defaults, "{id}"); + } + let mut s = fill(0.25); + add_filter(&mut s, json!({"filter": "clamp"})); + add_filter(&mut s, json!({"filter": "heightAdjust"})); + add_filter(&mut s, json!({"filter": "histogramScan"})); + add_filter(&mut s, json!({"filter": "histogramShift"})); + assert!(close(roughness(&mut s, TEXEL), 0.25), "Clamp, Height Adjust, Histogram Scan and Shift at their defaults change nothing"); +} + +/// Smoothstep eases between its bounds; Clamp keeps within them +#[test] +fn smoothstep_eases_between_minimum_and_maximum() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "smoothstep"})); + assert!(close(roughness(&mut s, TEXEL), 0.15625), "0.25 eased: 3t² − 2t³"); + + set(&mut s, effect, json!({"min": 0.25, "max": 0.75})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "at the minimum"); + + set(&mut s, effect, json!({"min": 0.0, "max": 0.2})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "past the maximum"); + + set(&mut s, effect, json!({"min": 0.25, "max": 0.25})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "equal bounds are a step, the bound itself white"); +} + +/// Invert's switch turns it off and on in one undo step each; restore defaults turns it back on +#[test] +fn invert_switches_off_and_on() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "invert"})); + assert!(close(roughness(&mut s, TEXEL), 0.75)); + + set(&mut s, effect, json!({"invert": false})); + assert_eq!(filter_of(&s, effect), Filter::InvertOff); + assert!(close(roughness(&mut s, TEXEL), 0.25), "off changes nothing"); + assert_eq!(filter_of(&s, effect).label(), "Invert", "still named Invert"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "invert": "yes"})).is_err()); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert, "one undo step"); + + set(&mut s, effect, json!({"invert": false})); + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert); + + // An old project's Invert still reads as before + let old: Filter = serde_json::from_value(json!("Invert")).unwrap(); + assert_eq!(old, Filter::Invert); +} + +/// Height Adjust flips, scales and raises around mid gray +#[test] +fn height_adjust_flips_scales_and_raises() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "heightAdjust"})); + + set(&mut s, effect, json!({"multiply": 2.0})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "(0.25 − 0.5) × 2 + 0.5"); + + set(&mut s, effect, json!({"invert": true, "offset": 0.1})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "flipped to 0.75, (0.75 − 0.5) × 2 + 0.5 + 0.1 clamped"); + + set(&mut s, effect, json!({"multiply": 1.0, "offset": -0.2})); + assert!(close(roughness(&mut s, TEXEL), 0.55)); + + set(&mut s, effect, json!({"multiply": 50.0})); + assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: true, offset: -0.2, multiply: 10.0 }, "Multiply caps at 10"); +} + +/// Height Adjust's Offset reaches -10..10 as the reference's does +#[test] +fn height_adjust_offset_reaches_ten_either_way() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "heightAdjust"})); + + set(&mut s, effect, json!({"offset": 5.0})); + let kept = filter_of(&s, effect); + set(&mut s, effect, json!({"offset": -50.0})); + + assert_eq!(kept, Filter::HeightAdjust { invert: false, offset: 5.0, multiply: 1.0 }, "an offset of 5 is kept"); + assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: false, offset: -10.0, multiply: 1.0 }, "Offset stops at -10"); +} + +/// Histogram Scan's Invert Position reads the position from the other end; old saves have none +#[test] +fn histogram_scan_inverts_its_position() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "histogramScan"})); + + set(&mut s, effect, json!({"position": 0.2, "contrast": 1.0})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "0.25 is above 0.2"); + + set(&mut s, effect, json!({"invertPosition": true})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "0.25 is below 1 − 0.2"); + + let old: Filter = serde_json::from_value(json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}})).unwrap(); + assert_eq!(old, Filter::HistogramScan { position: 0.5, contrast: 0.5, invert_position: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}}), "saved as before"); +} + +/// Histogram Shift's Position: 1 shifts nothing, lower shifts back by 1 − position; offsets saved before read as themselves +#[test] +fn histogram_shift_takes_a_position() { + let mut s = fill(0.25); + let effect = add_filter(&mut s, json!({"filter": "histogramShift"})); + + set(&mut s, effect, json!({"position": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::HistogramShift { offset: -0.5 }); + assert!(close(roughness(&mut s, TEXEL), 0.75), "0.25 − 0.5 wraps to 0.75"); + + assert_eq!(Filter::shift_position(-0.5), 0.5); + assert_eq!(Filter::shift_position(0.25), 0.25, "an old positive offset shows as itself"); + assert_eq!(Filter::shift_position(0.0), 1.0); +} + +/// Posterize steps to its Colors Amount and takes Apply to Alpha; old saves read without it and save as before +#[test] +fn posterize_takes_apply_to_alpha() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "posterize"})); + + set(&mut s, effect, json!({"levels": 2, "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::Posterize { levels: 2.0, alpha: true }); + assert!(close(roughness(&mut s, TEXEL), 0.0)); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": 1})).is_err()); + + let old: Filter = serde_json::from_value(json!({"Posterize": {"levels": 4.0}})).unwrap(); + assert_eq!(old, Filter::Posterize { levels: 4.0, alpha: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Posterize": {"levels": 4.0}}), "saved as before"); +} + +/// Pixelate takes Pixels Amount (cells across the UV tile) and Apply To Alpha; Mosaics saved before load and save as before +#[test] +fn pixelate_takes_pixels_amount_and_apply_to_alpha() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "pixelate"})); + assert_eq!(filter_of(&s, effect), Filter::Mosaic { size: 64.0, alpha: true }, "32 pixels across, coverage stepped"); + + set(&mut s, effect, json!({"pixelsAmount": 7.6, "applyToAlpha": false})); + let Filter::Mosaic { size, alpha } = filter_of(&s, effect) else { panic!() }; + assert!(close(Filter::pixels_amount(size), 8.0) && !alpha, "a whole Pixels Amount: {size}"); + assert!(close(roughness(&mut s, TEXEL), 0.3), "a uniform fill stays"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "no"})).is_err()); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Pixelate"), "named after the reference workflow"); + + let old: Filter = serde_json::from_value(json!({"Mosaic": {"size": 32.0}})).unwrap(); + assert_eq!(old, Filter::Mosaic { size: 32.0, alpha: true }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Mosaic": {"size": 32.0}}), "saved as before"); +} + +/// FXAA (Anti-aliasing) takes Affect Alpha Channel (off for a new one) and leaves flat values as they are +#[test] +fn fxaa_takes_affect_alpha_channel() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "FXAA (Anti-aliasing)"})); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }); + + set(&mut s, effect, json!({"affectAlphaChannel": true})); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: true }); + assert!(close(roughness(&mut s, TEXEL), 0.3), "nothing to smooth on a flat fill"); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "affectAlphaChannel": 2})).is_err()); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }, "one undo step"); +} + +/// Blur and Blur Directional take Intensity in the reference workflow's unit (16 texels at 2K each); radius still works +#[test] +fn blurs_take_intensity() { + let mut s = fill(0.3); + let blur = add_filter(&mut s, json!({"filter": "blur"})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 4.8, wrap: false }, "a new Blur starts at Blur Intensity 0.30"); + + set(&mut s, blur, json!({"intensity": 2.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 32.0, wrap: false }); + + set(&mut s, blur, json!({"intensity": 1000.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 256.0, wrap: false }, "capped as radius is"); + + let directional = add_filter(&mut s, json!({"filter": "blurDirectional"})); + + set(&mut s, directional, json!({"intensity": 0.5, "angle": 90})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 8.0, angle: 90.0 }); + + set(&mut s, directional, json!({"radius": 4.0})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 4.0, angle: 90.0 }, "radius in texels at 2K still sets it"); +} + +/// Highpass takes Radius in Blur Intensity's unit (a new one 3), Color Space and Apply To Alpha; a Highpass saved before loads and saves as before +#[test] +fn highpass_takes_radius_color_space_and_apply_to_alpha() { + let mut s = fill(0.3); + let effect = add_filter(&mut s, json!({"filter": "Highpass"})); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false }); + assert!(close(roughness(&mut s, TEXEL), 0.5), "a flat fill has no detail: mid gray"); + + set(&mut s, effect, json!({"intensity": 0.5, "colorSpace": "srgbFromAcescg", "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 8.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "colorSpace": "rec2020"})).is_err()); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "yes"})).is_err()); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false }, "one undo step"); + + let old: Filter = serde_json::from_value(json!({"HighPass": {"radius": 8.0}})).unwrap(); + assert_eq!(old, Filter::HighPass { radius: 8.0, space: HighpassSpace::Working, alpha: false }); + assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HighPass": {"radius": 8.0}}), "saved as before"); +} + +/// The composited base color at the test texel +fn base_color(s: &mut Session) -> [f32; 3] { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, TEXEL.0, TEXEL.1) +} + +/// A new Grayscale Conversion weighs a third of each component; a Grayscale saved before keeps its luminance, also after its first edit +#[test] +fn grayscale_conversion_takes_its_settings_and_keeps_saved_grayscales() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap(); + let effect = add_filter(&mut s, json!({"filter": "Grayscale Conversion"})); + assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::LIBRARY)); + + s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(Filter::Grayscale); + let saved = base_color(&mut s); + assert!(saved.iter().all(|v| close(*v, saved[0])) && close(saved[0], lum([0.8, 0.2, 0.1])), "{saved:?}"); + + set(&mut s, effect, json!({"balance": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::of_luminance()), "the luminance weights"); + assert!(close(base_color(&mut s)[0], saved[0]), "looks the same after its first edit"); + + set(&mut s, effect, json!({"red": 1.0, "green": 0.0, "blue": 0.0, "invert": true})); + assert!(close(base_color(&mut s)[0], 1.0 - 0.8), "Red only, inverted"); + + set(&mut s, effect, json!({"mode": "min", "invert": false})); + assert!(close(base_color(&mut s)[0], 0.1), "the darkest component"); + + set(&mut s, effect, json!({"channelInput": "customInput", "mode": "max"})); + assert!(close(base_color(&mut s)[0], 0.5), "the Custom Input reads mid gray until set"); + + let Filter::GrayscaleConversion(conversion) = filter_of(&s, effect) else { panic!("converted") }; + assert!(conversion.custom_input && conversion.mode == ConversionMode::Max); + + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channelInput": "image"})).is_err()); + assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "luma"})).is_err(), "Luma is the gradients' mode"); + + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Grayscale Conversion")); + assert_eq!(serde_json::to_value(Filter::Grayscale).unwrap(), json!("Grayscale"), "saved as before"); +} + +/// Grayscale Conversion turns only colors gray: a signed height keeps its sign and a normal map is left alone +#[test] +fn grayscale_conversion_keeps_heights_signed_and_normals_as_they_are() { + let mut s = session(); + let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "height", "value": -0.6})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap(); + s.update(); + let height_before = s.caches[0].composite.value(Channel::Height, TEXEL.0, TEXEL.1)[0]; + let normal_before = s.caches[0].composite.value(Channel::Normal, TEXEL.0, TEXEL.1); + + add_filter(&mut s, json!({"filter": "grayscale"})); + s.update(); + let height = s.caches[0].composite.value(Channel::Height, TEXEL.0, TEXEL.1)[0]; + let normal = s.caches[0].composite.value(Channel::Normal, TEXEL.0, TEXEL.1); + + assert!(height_before < -0.5, "the fill's height is negative: {height_before}"); + assert!((height - height_before).abs() < 0.02, "a signed height keeps its sign: {height} from {height_before}"); + assert!(normal.iter().zip(normal_before).all(|(after, before)| close(*after, before)), "the normal is untouched: {normal:?}"); + + let gray = base_color(&mut s); + assert!(close(gray[0], gray[2]), "the color turns gray: {gray:?}"); +} diff --git a/crates/engine/tests/it/filter_swap.rs b/crates/engine/tests/it/filter_swap.rs index 0bfa03f4..c8502ad8 100644 --- a/crates/engine/tests/it/filter_swap.rs +++ b/crates/engine/tests/it/filter_swap.rs @@ -1,10 +1,12 @@ //! 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::core::{BlendMode, Effect, EffectKind, Filter, LayerId, WarpMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, StackTarget, execute}; +use crate::filter_support::set; + /// 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() @@ -35,12 +37,12 @@ fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() { 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(); + set(&mut s, swapped, json!({"blend": "Multiply", "opacity": 0.4, "visible": false})); - execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap(); + set(&mut s, swapped, json!({"filter": "blur", "radius": 5.0})); let blur = effect(&s, swapped); - assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind); + 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]); @@ -51,21 +53,114 @@ 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(); + set(&mut s, id, json!({"filter": "threshold"})); assert_eq!(effect(&s, id).name, "Flip"); } +#[test] +fn swapping_to_the_former_directional_warp_id_sets_directional_mode() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + set(&mut s, id, json!({"filter": "warpDirectional"})); + + let swapped = effect(&s, id).kind; + assert!(matches!(swapped, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional), "{swapped:?}"); +} + +#[test] +fn naming_the_former_directional_warp_id_on_a_warp_sets_directional_mode() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "warp", "target": "content", "seed": 7})); + + set(&mut s, id, json!({"filter": "warpDirectional"})); + + let edited = effect(&s, id).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional && warp.seed == 7), "{edited:?}"); +} + +#[test] +fn a_warp_mode_given_with_the_former_directional_warp_id_wins() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "warp", "target": "content"})); + + set(&mut s, id, json!({"filter": "warpDirectional", "warpMode": "warp"})); + + let edited = effect(&s, id).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Warp), "{edited:?}"); +} + +/// A content warp effect saved before the warp modes, as `filter` +fn saved_warp(s: &mut Session, filter: Filter) -> LayerId { + let id = add(s, "effect.add.filter", json!({"filter": "warp", "target": "content"})); + s.doc.project.effect_mut(id).unwrap().kind = EffectKind::Filter(filter); + id +} + +#[test] +fn asking_a_saved_warp_for_another_mode_replaces_it_with_a_warp_in_that_mode() { + let mut s = session(); + let warp = saved_warp(&mut s, Filter::Warp { intensity: 8.0, scale: 4.0, seed: 1, divider: 1 }); + let directional = saved_warp(&mut s, Filter::DirectionalWarp { intensity: 8.0, angle: 0.0, scale: 4.0, seed: 1, divider: 1 }); + + set(&mut s, warp, json!({"filter": "warpDirectional", "angle": 90.0})); + set(&mut s, directional, json!({"filter": "warp", "warpMode": "multiDirectional"})); + + let edited = effect(&s, warp).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional && warp.angle == 90.0), "{edited:?}"); + let edited = effect(&s, directional).kind; + assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::MultiDirectional), "{edited:?}"); +} + +#[test] +fn editing_a_saved_warp_in_its_own_mode_keeps_it() { + let mut s = session(); + let warp = saved_warp(&mut s, Filter::Warp { intensity: 8.0, scale: 4.0, seed: 1, divider: 1 }); + let directional = saved_warp(&mut s, Filter::DirectionalWarp { intensity: 8.0, angle: 0.0, scale: 4.0, seed: 1, divider: 1 }); + + set(&mut s, warp, json!({"filter": "warp", "warpMode": "warp", "seed": 3})); + set(&mut s, directional, json!({"filter": "warpDirectional", "angle": 45.0})); + + assert_eq!(effect(&s, warp).kind, EffectKind::Filter(Filter::Warp { intensity: 8.0, scale: 4.0, seed: 3, divider: 1 })); + assert_eq!(effect(&s, directional).kind, EffectKind::Filter(Filter::DirectionalWarp { intensity: 8.0, angle: 45.0, scale: 4.0, seed: 1, divider: 1 })); +} + +#[test] +fn swapping_to_a_gradient_given_colors_ramps_evenly_through_them() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + set(&mut s, id, json!({"filter": "gradientMap", "colors": [[0, 0, 0], [1, 1, 1]]})); + + let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") }; + let halfway = gradient.ramp_at(0.5).unwrap(); + assert!((halfway[0] - 0.5).abs() < 1e-3, "black to white is mid gray halfway: {halfway:?}"); +} + +/// A swap to a gradient given five colors and their places ramps through all five, not the library's three +#[test] +fn swapping_to_a_gradient_given_colors_and_places_uses_every_color() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let colors = [[0.0; 3], [0.25; 3], [0.5; 3], [0.75; 3], [1.0; 3]]; + + set(&mut s, id, json!({"filter": "gradientMap", "colors": colors, "positions": [0.0, 0.1, 0.2, 0.3, 1.0]})); + + let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") }; + assert_eq!(gradient.ramp_colors(), colors); +} + #[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(); + set(&mut s, id, json!({"filter": "sharpen"})); 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!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level, .. }) if level == 0.3), "{:?}", restored.kind); assert_eq!(restored.name, "Threshold"); } @@ -74,7 +169,7 @@ 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(); + let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "normalInvert"})).unwrap_err(); assert!(err.to_string().contains("not on masks"), "{err}"); assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); @@ -86,9 +181,9 @@ fn a_mask_filter_swaps_in_place_on_the_mask() { 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(); + set(&mut s, swapped, json!({"blend": "Multiply", "opacity": 0.4})); - execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap(); + set(&mut s, swapped, json!({"filter": "blur"})); let blur = effect(&s, swapped); assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind); @@ -103,11 +198,11 @@ 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(); + set(&mut s, id, json!({"filter": "blur", "radius": 9.0})); + set(&mut s, id, json!({"filter": "blur"})); 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); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius, .. }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind); } #[test] @@ -115,7 +210,7 @@ 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(); + set(&mut s, id, json!({"filter": "threshold", "name": "Edges"})); let swapped = effect(&s, id); assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind); @@ -126,11 +221,11 @@ fn a_name_given_with_the_swap_wins() { 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(); + set(&mut s, id, json!({"blend": "Multiply", "opacity": 0.4, "name": "Flip"})); let before = effect(&s, id); for refused in [ - json!({"effect": id.0, "filter": "grayscale"}), + json!({"effect": id.0, "filter": "normalInvert"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"}), json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}), @@ -153,6 +248,7 @@ fn only_filter_effects_swap_and_only_to_filters() { 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))); } @@ -170,3 +266,31 @@ fn invalid_swap_parameters_report_effect_set_and_preserve_history() { assert_eq!(effect(&s, id), before); assert_eq!(s.history_labels(), history); } + +#[test] +fn a_mask_takes_grayscale_conversion() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + + set(&mut s, id, json!({"filter": "grayscale"})); + + let swapped = effect(&s, id); + assert!(matches!(swapped.kind, EffectKind::Filter(Filter::GrayscaleConversion(_))), "{:?}", swapped.kind); + assert_eq!(swapped.name, "Grayscale Conversion"); +} + +#[test] +fn filters_carry_the_workflows_names_and_former_names_still_follow_a_swap() { + let mut s = session(); + let slope = add(&mut s, "effect.add.filter", json!({"filter": "slopeBlur", "target": "content"})); + assert_eq!(effect(&s, slope).name, "Blur Slope"); + let names: Vec = execute(&mut s, "filter.list", &Value::Null).unwrap().as_array().unwrap().iter().map(|def| def["label"].clone()).collect(); + for name in ["Contrast Luminosity", "Blur Slope", "Highpass", "Grayscale Conversion"] { + assert!(names.contains(&json!(name)), "{name} in {names:?}"); + } + + // A project saved before the rename holds the former name: a swap still renames it, and the former name still finds the filter + let old = add(&mut s, "effect.add.filter", json!({"filter": "Slope Blur", "target": "content", "name": "Slope Blur"})); + set(&mut s, old, json!({"filter": "blur"})); + assert_eq!(effect(&s, old).name, "Blur"); +} diff --git a/crates/engine/tests/it/filter_transform.rs b/crates/engine/tests/it/filter_transform.rs new file mode 100644 index 00000000..704c2c87 --- /dev/null +++ b/crates/engine/tests/it/filter_transform.rs @@ -0,0 +1,78 @@ +//! The Transform filter: each UV tile's content scaled, turned, moved and flipped, repeating round the tile or empty past it + +use serde_json::json; +use texturecraft_engine::core::{EffectKind, Filter, FlipMode, LayerId, RepeatMode, TileTransform}; +use texturecraft_engine::{Session, execute}; + +use crate::filter_support::{SIZE, add_filter, refused, roughness, session, set}; + +fn transform_of(s: &Session, effect: LayerId) -> TileTransform { + match &s.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Filter(Filter::Transform(transform)) => *transform, + other => panic!("not a transform: {other:?}"), + } +} + +/// A new Transform changes nothing; Offset moves the content round the tile, Repeat mode None leaves empty past it, Flip mode turns it over +#[test] +fn transform_moves_scales_and_flips_each_tile() { + let mut s = session(); + let row = SIZE / 2; + let empty = roughness(&mut s, (8, row)); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); + let before: Vec = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect(); + let was = |x: u32| before[(x % SIZE) as usize]; + + let effect = add_filter(&mut s, json!({"filter": "transform"})); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Transform"); + + for x in [20, 64, 100] { + assert!((roughness(&mut s, (x, row)) - was(x)).abs() < 1e-4, "a new Transform changes nothing at {x}"); + } + + // A quarter tile on: each texel reads 32 texels further right, the last ones round from the left + set(&mut s, effect, json!({"offset": [0.25, 0.0]})); + for x in [20, 50, 110] { + assert!((roughness(&mut s, (x, row)) - was(x + SIZE / 4)).abs() < 2e-3, "offset at {x}"); + } + + set(&mut s, effect, json!({"offset": 0.0, "flipMode": "horizontally"})); + assert!((roughness(&mut s, (20, row)) - was(SIZE - 1 - 20)).abs() < 2e-3, "flipped, the left reads the right"); + + // Twice across about the centre: the centre stays; without repeat the edges read empty (the layer's content is clear there) + set(&mut s, effect, json!({"flipMode": "none", "scaling": [2.0, 2.0], "repeatMode": "none"})); + assert!((roughness(&mut s, (SIZE / 2, row)) - was(SIZE / 2)).abs() < 2e-2, "the centre stays"); + assert!((roughness(&mut s, (8, row)) - empty).abs() < 1e-4, "past the content reads empty"); + + // Repeating, texel 8 reads 2 · 8.5 / 128 − 0.5 of a tile on: between texels 80 and 81 + set(&mut s, effect, json!({"repeatMode": "horizontallyAndVertically"})); + assert!((roughness(&mut s, (8, row)) - (was(80) + was(81)) / 2.0).abs() < 2e-3, "the tile comes round again"); + + let edited = transform_of(&s, effect); + assert_eq!((edited.repeat, edited.flip, edited.scaling), (RepeatMode::HorizontallyAndVertically, FlipMode::None, [2.0, 2.0])); + + set(&mut s, effect, json!({"rotation": -30.0, "tileSafeRotation": false})); + let turned = transform_of(&s, effect); + assert_eq!((turned.rotation, turned.tile_safe), (330.0, false), "a turn reads 0..360"); + + refused( + &mut s, + effect, + &[ + json!({"repeatMode": "sideways"}), + json!({"flipMode": "diagonal"}), + json!({"scaling": [1.0]}), + json!({"offset": "far"}), + json!({"tileSafeRotation": 1}), + ], + ); + assert_eq!(transform_of(&s, effect), turned, "a refused value changes nothing"); + + set(&mut s, effect, json!({"scaling": [1e9, -5.0]})); + assert_eq!(transform_of(&s, effect).scaling, [TileTransform::SCALING.1, TileTransform::SCALING.0], "scaling clamps"); + + execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); +} diff --git a/crates/engine/tests/it/folder_contents.rs b/crates/engine/tests/it/folder_contents.rs index 11ca86e9..b517deea 100644 --- a/crates/engine/tests/it/folder_contents.rs +++ b/crates/engine/tests/it/folder_contents.rs @@ -139,6 +139,7 @@ fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) { }; let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind { EffectKind::Filter(Filter::Warp { seed, .. }) => Some(seed), + EffectKind::Filter(Filter::SourceWarp(warp)) => Some(warp.seed), _ => None, }); (pattern(Channel::BaseColor), pattern(Channel::Roughness), warp.unwrap()) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f45226e8..c38e850b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -21,8 +21,17 @@ mod fill_patterns; mod fill_projections; mod fill_sampling; mod fill_whole_material; +mod filter_card; +mod filter_colour; +mod filter_gradient; +mod filter_inputs; +mod filter_light; +mod filter_shape; +mod filter_simple; +mod filter_stylize; mod filter_support; mod filter_swap; +mod filter_transform; mod filters; mod folder_contents; mod frame_selection; diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 26fcb753..d423c852 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -63,7 +63,6 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { "matFinishGrind", "highPass", "edgeDetect", - "warpDirectional", "grayscale", "normalInvert", "bevel", @@ -80,47 +79,36 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); - assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); - execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it + // A gradient map recolors the content; effect.set edits it and inspect shows it. let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); - execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); - assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); - let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); - assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); - execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped + // Posterize on the mask; its steps are clamped. let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); - assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); - assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0)); - - // Material finishes fill the content's roughness and height + assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels, .. }) if levels == 64.0)); + // Material finishes fill the content's roughness and height. let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); - assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - - // A directional blur, slope blur and warp composite without trouble on a sphere + // A directional blur, slope blur and warp composite without trouble on a sphere. for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), - ("slopeBlur", json!({"radius": 30})), + ("slopeBlur", json!({"intensity": 0.5, "divider": 1})), ("warp", json!({"intensity": 50})), ("warpDirectional", json!({"intensity": 50, "angle": 30})), ("highPass", json!({"radius": 20})), diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index 8889b7ae..5cb945c0 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,4 +1,5 @@ //! The images a project reads beyond fill sources: a colour selection's ID map, the mask brush and its paths +//! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, LayerId}; @@ -27,11 +28,23 @@ fn selecting_layer(session: &mut Session, id_map: &str) -> LayerId { layer } +/// [`selecting_layer`] with a Bevel Smooth that reads `input` as its Distance Map +fn layer_reading(session: &mut Session, id_map: &str, input: &str) -> LayerId { + let layer = selecting_layer(session, id_map); + let filter = execute(session, "effect.add.filter", &json!({"filter": "bevelSmooth", "target": "content"})).unwrap()["effect"].as_u64().unwrap(); + execute(session, "layer.fill.set", &json!({"effect": filter, "input": "distanceMap", "image": input})).unwrap(); + layer +} + #[test] fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_path_read() { +fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mask_brush_and_a_path_read() { let mut session = session(); let [id_map, path, brush, unused] = ["id.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); let layer = selecting_layer(&mut session, &id_map); + let [id_map, input, path, brush, unused] = + ["id.png", "input.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); + let layer = layer_reading(&mut session, &id_map, &input); // A path on the mask is painted with one image, then the brush moves on to another execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); @@ -46,15 +59,19 @@ fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_p #[test] fn a_smart_material_carries_the_image_its_selection_reads() { +fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() { let mut session = session(); let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); let layer = selecting_layer(&mut session, &id_map); + let input = session.import_resource_bytes("input.png", white_png()).unwrap(); + let layer = layer_reading(&mut session, &id_map, &input); let bytes = session.smart_material_bytes(layer, "Parts").unwrap(); let mut other = self::session(); other.add_smart_material_bytes(&bytes).unwrap(); assert!(other.doc.resources.contains_key(&id_map), "the ID map comes along"); + assert!(other.doc.resources.contains_key(&input), "the filter input comes along"); } #[test] diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index b5ae16f0..2802448b 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -268,6 +268,8 @@ fn panic_hunt() { s.update(); } } + + hunt_filters(&hostile); } /// A 4 × 4 gray PNG, the image the hunted decals project @@ -278,8 +280,10 @@ fn gray_png() -> Vec { } /// Frame edits and frame and Fill section resets on the fills they act on (a planar, a warp and a decal mask) meet hostile values without panicking; a refused edit changes nothing and adds no undo step +/// Frame edits, frame and Fill section resets and Transform filter settings on the fills they act on (a planar, a warp, a decal mask and a Transform filter) meet hostile values without panicking; a refused edit changes nothing and adds no undo step #[test] fn panic_hunt_frames() { +fn panic_hunt_frames_and_transforms() { let mut s = session(); let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); let planar = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); @@ -288,6 +292,7 @@ fn panic_hunt_frames() { execute(&mut s, "layer.fill.projection", &json!({"layer": warp, "projection": "warp"})).unwrap(); let decal = execute(&mut s, "layer.add.decal", &json!({"image": image, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap(); let mask_effect = decal["maskEffect"].as_u64().unwrap(); + let transform = execute(&mut s, "effect.add.filter", &json!({"filter": "transform", "target": "content"})).unwrap()["effect"].as_u64().unwrap(); s.update(); let hostile_values = @@ -310,6 +315,15 @@ fn panic_hunt_frames() { s.update(); } } + + let transform_keys = ["repeatMode", "flipMode", "scaling", "offset", "rotation", "tileSafeRotation"]; + for key in transform_keys { + for value in &hostile_values { + let mut params = json!({"effect": transform}); + params[key] = value.clone(); + hunt_refused_changes_nothing(&mut s, "effect.set", ¶ms); + } + } } /// Run `command` with `params` and render; refused, it must leave the project and the undo history as they were @@ -321,6 +335,166 @@ fn hunt_refused_changes_nothing(s: &mut Session, command: &str, params: &Value) s.update(); } +/// The number parameters library filters read, all set at once to one hostile value +const FILTER_NUMBER_KEYS: &[&str] = &[ + "radius", + "intensity", + "amount", + "level", + "hue", + "saturation", + "lightness", + "contrast", + "luminosity", + "levels", + "min", + "max", + "position", + "range", + "offset", + "multiply", + "scale", + "angle", + "width", + "distance", + "smoothing", + "size", + "spread", + "opacity", + "blur", + "balance", + "quality", + "sourceBlur", + "sourceBalance", + "sourceContrast", + "sourceTiling", + "tolerance", + "softness", + "light", + "ambient", + "occlusion", + "azimuth", + "elevation", + "horizontalRotation", + "verticalRotation", + "exposure", + "heightIntensity", + "ambientOcclusion", + "specularOcclusion", + "pixelsAmount", + "curveOffset", + "curveShape", + "maskThreshold", + "distanceMapMultiplier", + "threshold", + "axisXOffset", + "axisYOffset", + "surfaceSize", + "heightDepth", + "normalIntensity", + "chroma", + "luma", + "red", + "green", + "blue", + "alpha", + "tensorSmoothness", + "anisotropy", + "sharpness", + "smoothness", + "rotation", + "scaling", + "diffuseCavity", + "specularAo", + "specularCavity", + "cavitySmoothness", + "edgesIntensity", + "edgesSmoothness", + "dielectricReflectance", + "heightToNormal", +]; + +/// The objects library filters read numbers from (Baked Lighting Stylized's two lights) +const FILTER_LIGHT_KEYS: &[&str] = &["light1", "light2"]; + +/// Every filter number parameter set to `number`, with seeds, switches and choices at their ends +fn filter_extreme(number: f64) -> Value { + let mut params = json!({"seed": u64::MAX, "wrap": true, "applyToAlpha": true, "invert": true, "directions": 4, "divider": 1000}); + for key in FILTER_NUMBER_KEYS { + params[*key] = json!(number); + } + for key in FILTER_LIGHT_KEYS { + params[*key] = json!({"azimuth": number, "elevation": number, "intensity": number}); + } + params +} + +/// Every library filter added on the content and on a mask with `hostile` and extreme parameters, edited to extremes, and rendered; then swapped to the same way +fn hunt_filters(hostile: &[Value]) { + let extremes: Vec = [3.0e38, -3.0e38, 0.0].into_iter().map(filter_extreme).collect(); + + for def in texturecraft_engine::filter_lib::FILTERS { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap(); + for target in ["content", "mask"] { + if target == "mask" { + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + } + + for given in hostile.iter().chain(&extremes) { + let mut params = if given.is_object() { given.clone() } else { json!({}) }; + params["filter"] = json!(def.id); + params["target"] = json!(target); + let added = execute(&mut s, "effect.add.filter", ¶ms).ok().and_then(|reply| reply["effect"].as_u64()); + s.update(); + + // Extreme values are clamped, not refused, so every filter meets them on the content + if target == "content" && extremes.contains(given) { + assert!(added.is_some(), "{} takes extreme values: {params}", def.id); + } + if let Some(effect) = added { + for edit in &extremes { + let mut edit = edit.clone(); + edit["effect"] = json!(effect); + // Each accepted value reaches the compositor before the next edit replaces it + if execute(&mut s, "effect.set", &edit).is_ok() { + s.update(); + } + } + } + } + } + } + + hunt_filter_swaps(hostile, &extremes); +} + +/// An empty filter effect on the content and on a mask swapped through `effect.set` to every library filter with each of `hostile` and `extremes`, and rendered +fn hunt_filter_swaps(hostile: &[Value], extremes: &[Value]) { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap(); + for target in ["content", "mask"] { + if target == "mask" { + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + } + let added = execute(&mut s, "effect.add.filter", &json!({"filter": "none", "target": target})).unwrap(); + let effect = added["effect"].as_u64().unwrap(); + + for def in texturecraft_engine::filter_lib::FILTERS { + for given in hostile.iter().chain(extremes) { + let mut params = if given.is_object() { given.clone() } else { json!({}) }; + params["effect"] = json!(effect); + params["filter"] = json!(def.id); + + // Emptied first, so each swap builds the filter anew rather than editing it in place + execute(&mut s, "effect.set", &json!({"effect": effect, "filter": "none"})).unwrap(); + let _ = execute(&mut s, "effect.set", ¶ms); + s.update(); + } + } + } +} + /// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ /// between the two, so every command that takes a colour says which form is which. #[test] diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index 11635fcc..57e5f87e 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -8,6 +8,7 @@ use std::f32::consts::{PI, TAU}; use rayon::prelude::*; +use texturecraft_compose::environment_sky; use texturecraft_geom::glam::{Vec2, Vec3}; /// An equirect HDR image (linear RGB). @@ -18,86 +19,9 @@ pub struct EnvImage { pub data: Vec<[f32; 3]>, } +pub use texturecraft_compose::environment_sky::{dir_of, radiance, sh_basis, uv_of}; pub use texturecraft_core::project::ENVIRONMENTS; -pub fn dir_of(u: f32, v: f32) -> Vec3 { - let (theta, phi) = (v * PI, u * TAU); - Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin()) -} - -pub fn uv_of(d: Vec3) -> Vec2 { - let phi = d.z.atan2(d.x); - Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI) -} - -/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees). -struct SoftBox { - az: f32, - el: f32, - hw: f32, - hh: f32, - color: Vec3, -} - -impl SoftBox { - fn eval(&self, d: Vec3) -> Vec3 { - let el = d.y.clamp(-1.0, 1.0).asin().to_degrees(); - let az = d.z.atan2(d.x).to_degrees(); - let daz = ((az - self.az + 540.0).rem_euclid(360.0)) - 180.0; - let (x, y) = (daz.abs() / self.hw, (el - self.el).abs() / self.hh); - let e = |t: f32| 1.0 - smooth((t - 0.8) / 0.4); - self.color * e(x) * e(y) - } -} - -fn smooth(t: f32) -> f32 { - let t = t.clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 { - if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(0.6)) } else { horizon.lerp(ground, (-d.y).powf(0.25)) } -} - -fn radiance(name: &str, d: Vec3) -> Vec3 { - match name { - "Studio Contrast" => { - let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01)); - base + SoftBox { az: 35.0, el: 30.0, hw: 22.0, hh: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d) - + SoftBox { az: -150.0, el: 40.0, hw: 6.0, hh: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d) - } - "Overcast" => { - let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15)); - base + SoftBox { az: 60.0, el: 55.0, hw: 40.0, hh: 25.0, color: Vec3::splat(0.6) }.eval(d) - } - "Sunset" => { - let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); - let sun_dir = dir_of(0.12, 0.47); - let sun = smooth((d.dot(sun_dir) - 0.9985) / 0.0012) * 120.0; - base + Vec3::new(1.0, 0.6, 0.3) * sun - } - "Warehouse" => { - let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06)); - for k in 0..6 { - c += SoftBox { az: -150.0 + k as f32 * 60.0, el: 50.0, hw: 6.0, hh: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d); - } - c + SoftBox { az: 90.0, el: 5.0, hw: 30.0, hh: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d) - } - "Night" => { - let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005)); - base + SoftBox { az: 20.0, el: 15.0, hw: 10.0, hh: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d) - + SoftBox { az: -110.0, el: 10.0, hw: 12.0, hh: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d) - } - // "Studio Soft" (default) - _ => { - let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07)); - base + SoftBox { az: 40.0, el: 35.0, hw: 28.0, hh: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d) - + SoftBox { az: -125.0, el: 20.0, hw: 35.0, hh: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d) - + SoftBox { az: 175.0, el: 55.0, hw: 8.0, hh: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d) - } - } -} - /// Render a built-in environment (unknown names give the default studio). pub fn environment(name: &str, width: u32) -> EnvImage { let w = width.clamp(16, 4096); @@ -132,16 +56,8 @@ impl EnvImage { /// Box-downsample by 2. pub fn half(&self) -> EnvImage { - let (w, h) = ((self.width / 2).max(1), (self.height / 2).max(1)); - let mut data = vec![[0.0f32; 3]; (w * h) as usize]; - data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| { - for (x, px) in row.iter_mut().enumerate() { - let (sx, sy) = (x as i64 * 2, y as i64 * 2); - let s = (self.get(sx, sy) + self.get(sx + 1, sy) + self.get(sx, sy + 1) + self.get(sx + 1, sy + 1)) * 0.25; - *px = s.to_array(); - } - }); - EnvImage { width: w, height: h, data } + let (width, height, data) = environment_sky::half(self.width, self.height, |x, y| self.get(x as i64, y as i64)); + EnvImage { width, height, data: data.iter().map(Vec3::to_array).collect() } } /// An imported equirect image (`rgba` row-major, top row first, sRGB-encoded when `srgb`) as @@ -149,23 +65,12 @@ impl EnvImage { /// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the /// pixel count does not match the size. pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option { - Self::from_pixels(width, height, rgba, srgb) - } - - /// An imported linear RGB equirect image, with the same validation and size limits as [Self::from_rgba]. - pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option { - Self::from_pixels(width, height, rgb, false) - } - - fn from_pixels(width: u32, height: u32, pixels: &[[f32; COMPONENTS]], srgb: bool) -> Option { - if width == 0 || height == 0 || pixels.len() as u64 != width as u64 * height as u64 { + if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 { return None; } - let lin = |v: f32| { - let v = if v.is_finite() { v.clamp(0.0, 65_000.0) } else { 0.0 }; - if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v } - }; let data = pixels.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect(); + let linear = |v: f32| environment_sky::environment_linear(v, srgb); + let data = rgba.par_iter().map(|p| [linear(p[0]), linear(p[1]), linear(p[2])]).collect(); let mut img = EnvImage { width, height, data }; while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH { img = img.half(); @@ -247,48 +152,9 @@ pub fn prefilter(env: &EnvImage, levels: u32) -> Vec { out } -/// Diffuse irradiance as 9 SH coefficients (already convolved with the cosine lobe and divided -/// by π, so `Σ c·Y(n)` times albedo is the diffuse radiance). +/// Diffuse irradiance as 9 SH coefficients, convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance pub fn sh9(env: &EnvImage) -> [[f32; 3]; 9] { - let mut src = env.clone(); - while src.width > 128 { - src = src.half(); - } - let (w, h) = (src.width, src.height); - let mut c = [Vec3::ZERO; 9]; - for y in 0..h { - let theta = PI * (y as f32 + 0.5) / h as f32; - let dw = (TAU / w as f32) * (PI / h as f32) * theta.sin(); - for x in 0..w { - let d = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32); - // No firefly clamp: the projection integrates, so a bright sun lights diffuse fully. - let l = src.get(x as i64, y as i64) * dw; - for (k, ylm) in sh_basis(d).iter().enumerate() { - c[k] += l * *ylm; - } - } - } - let a = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0]; - let mut out = [[0.0; 3]; 9]; - for k in 0..9 { - out[k] = (c[k] * a[k] / PI).to_array(); - } - out -} - -pub fn sh_basis(d: Vec3) -> [f32; 9] { - let (x, y, z) = (d.x, d.y, d.z); - [ - 0.282_095, - 0.488_603 * y, - 0.488_603 * z, - 0.488_603 * x, - 1.092_548 * x * y, - 1.092_548 * y * z, - 0.315_392 * (3.0 * z * z - 1.0), - 1.092_548 * x * z, - 0.546_274 * (x * x - y * y), - ] + environment_sky::sh9_averaged(env.width, env.height, |x, y| env.get(x as i64, y as i64)) } #[cfg(test)] diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 5e0561af..481cb6d4 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -1319,7 +1319,7 @@ impl Renderer { let img = match imported { Some(img) => img, None if !self.env_is_imported && self.env_name == name => return, - None => ibl::environment(name, 512), + None => ibl::environment(name, texturecraft_compose::environment_sky::VIEWPORT_WIDTH), }; let levels = ibl::prefilter(&img, ENV_LEVELS); diff --git a/crates/ui-egui/src/anchor_properties.rs b/crates/ui-egui/src/anchor_properties.rs index 360bef5b..e3fb0313 100644 --- a/crates/ui-egui/src/anchor_properties.rs +++ b/crates/ui-egui/src/anchor_properties.rs @@ -78,3 +78,25 @@ fn reader_glyph(kind: &EffectKind) -> &'static str { EffectKind::Fill { .. } | EffectKind::Material(_) => ic::PAINT_BUCKET, } } + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::execute; + + use super::*; + + #[test] + fn a_reference_shows_the_icon_of_what_reads_the_anchor() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"roughness": 0.5})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &Value::Null).unwrap()["effect"].as_u64().unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let filter = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "bevelSmooth"})).unwrap()["effect"].clone(); + execute(&mut session, "layer.fill.set", &json!({"effect": filter, "input": "distanceMap", "anchor": anchor})).unwrap(); + + let glyphs: Vec<&str> = references(&session.doc.project, LayerId(anchor)).iter().map(|reference| reference.glyph).collect(); + assert_eq!(glyphs, [ic::FUNNEL], "a filter reading the anchor shows the filter icon, not a fill's"); + } +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 0dc5bc7f..5248b0fb 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -7,8 +7,8 @@ use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, + BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, }; -use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -24,11 +24,6 @@ use crate::theme::{Tokens, caption}; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; -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), @@ -3029,28 +3024,6 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option { picked } -/// Swatches for gradient map stops (dark to light) with Add color and Remove last; true when -/// they changed. -fn gradient_stops(ui: &mut Ui, salt: &str, stops: &mut Vec<[f32; 3]>) -> bool { - let mut changed = false; - ui.horizontal_wrapped(|ui| { - for (i, stop) in stops.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("{salt}_{i}"), stop, FILTER_SWATCH_WIDTH); - } - }); - ui.horizontal(|ui| { - 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(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - stops.pop(); - changed = true; - } - }); - changed -} - /// The properties of effect `effect_id` of `layer`: each kind's own settings. fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { let tokens = Tokens::get(ui.ctx()); @@ -3166,6 +3139,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe } }), EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), + EffectKind::Filter(filter) => crate::filter_properties::filter_properties(app, ui, effect_id, filter), EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { let settings = crate::compare_settings::CompareSettings { @@ -3182,85 +3156,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe } } -/// 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, value: Value, merge: bool| { - let mut params = json!({ "effect": id, "merge": merge }); - params[key] = value; - app.run("effect.set", params); - }; - 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 value, min, max) in scalar_params(filter) { - let decimals = if matches!(key, "seed" | "levels") { - 0 - } else if max - min > 10.0 { - 1 - } else { - 2 - }; - if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) { - set(app, key, json!(value), merge); - } - } - - 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 balance = *rgb; - let mut edit = None; - 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!(balance), merge); - } - } - } - Filter::ReplaceColor { from, to, .. } => { - for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { - let mut color = *rgb; - ui.horizontal(|ui| { - 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(FILTER_HINT_SIZE).color(tk.text_dim)); - } - Filter::GradientMap { colors } => { - let mut stops = colors.clone(); - if gradient_stops(ui, &format!("gradient_{id}"), &mut stops) { - 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(FILTER_HINT_SIZE).color(tk.text_dim)); - } - Filter::Warp { .. } - | Filter::DirectionalBlur { .. } - | Filter::SlopeBlur { .. } - | Filter::DirectionalWarp { .. } - | Filter::HighPass { .. } - | Filter::EdgeDetect { .. } - | 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(FILTER_HINT_SIZE).color(tk.text_dim)); - } - _ => {} - } -} - #[cfg(test)] mod layer_layout_tests { use super::*; diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 7efd7a14..24a62cd4 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -428,6 +428,7 @@ fn procedural_rows( // A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes let gray = matches!(slot_of, SourceSlot::Grayscale); + let gray = matches!(slot_of, SourceSlot::Grayscale | SourceSlot::Input(_)); if gray { edit = edit.or(balance_and_seed(sheet, &mut edited)); } diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 5a9fa0d7..2f7d7358 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -370,6 +370,41 @@ mod tests { use super::*; + /// A repeating map far denser than the tiles drawn (Scaling 64 turned 45°) still fills the whole window, its far corner too + #[test] + fn a_dense_repeating_preview_leaves_no_bare_field() { + use texturecraft_engine::core::TileTransform; + + let tokens = Tokens::for_brightness(crate::theme::Brightness::MediumDark); + let transform = TileTransform { scaling: [64.0, 64.0], rotation: 45.0, ..TileTransform::LIBRARY }; + let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| lattice_preview(ui.painter(), rect, transform.affine(), true, &tokens)); + + // Whether a filled shape other than the bare field covers `point` + let covered = |point: Pos2| { + output.shapes.iter().any(|clipped| match &clipped.shape { + Shape::Rect(shape) => shape.fill != tokens.field && shape.fill != Color32::TRANSPARENT && shape.rect.contains(point), + Shape::Path(path) if path.fill != Color32::TRANSPARENT => { + let corners = &path.points; + let side = |index: usize| { + let (from, to) = (corners[index], corners[(index + 1) % corners.len()]); + (to - from).x * (point - from).y - (to - from).y * (point - from).x + }; + let sides: Vec = (0..corners.len()).map(side).collect(); + sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) + } + _ => false, + }) + }; + for corner in [pos2(1.0, 1.0), pos2(99.0, 1.0), pos2(1.0, 99.0), pos2(99.0, 99.0)] { + assert!(covered(corner), "the preview fills {corner:?}"); + } + + // No renderer takes the uploads here + output.drop_without_applying_deltas(); + } + /// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another #[test] fn the_ring_spaces_its_copies_as_the_engine_does() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2e663682..d1d19dc1 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -249,6 +249,10 @@ mod tests { keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label)); for filter in FILTERS { keys.extend([filter.label, filter.group]); + if let Some(about) = filter.about() { + keys.push(about.description); + keys.extend(about.tags); + } if let Ok(EffectKind::Filter(effect)) = build(filter.id, &serde_json::Value::Null) { keys.push(effect.label()); keys.extend(scalar_params(&effect).into_iter().map(|parameter| parameter.1)); diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index b8274f79..922eacd2 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -91,6 +91,8 @@ const BLACK_SWATCH: u8 = 10; /// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it pub(crate) const NEW_FILTER: &str = "hsl"; +/// The filter Add filter adds: an empty one, which changes nothing until its slot's picker swaps a filter into it +pub(crate) const NEW_FILTER: &str = texturecraft_engine::mask_cmds::EMPTY_FILTER; /// The Layers panel's top row and what its menus open pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a3671aee..11cbf1f2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -38,7 +38,9 @@ mod fill_material_panel; mod fill_panel; mod fill_pictures; mod fill_symmetry_panel; +mod filter_properties; mod filter_slot; +mod filter_transform_rows; mod folder_properties; pub mod fonts; mod frame_gizmo; diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs index b34aa1d1..5b7e4a11 100644 --- a/crates/ui-egui/src/material_orb.rs +++ b/crates/ui-egui/src/material_orb.rs @@ -5,6 +5,7 @@ use egui::{Color32, ColorImage, Painter, Rect, pos2}; use rayon::prelude::*; use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{Channel, DIELECTRIC_REFLECTANCE}; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::texel::linear_to_srgb; @@ -125,6 +126,7 @@ fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f for (channel, value) in out.iter_mut().enumerate() { let base = sample.base[channel].clamp(0.0, 1.0); let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * metallic; + let f0 = DIELECTRIC_REFLECTANCE + (base - DIELECTRIC_REFLECTANCE) * metallic; let specular = f0 * scale + bias; *value = diffuse_light[channel] * base * (1.0 - metallic) * (1.0 - specular) + specular_light[channel] * specular + sample.emissive[channel].max(0.0); } diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs index b9239dc0..d120ce3f 100644 --- a/crates/ui-egui/src/property_sheet/color_bar.rs +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -86,6 +86,17 @@ fn open_picker(ctx: &egui::Context, state_id: Id, state: &mut PickerState, linea } impl PropertySheet<'_> { + /// Opens the picker of the colour bar `bar` (its [`ColorPick::id`]) on `linear` from the next frame, as a click on the bar does + pub(crate) fn open_color_picker(&self, bar: Id, linear: [f32; 3]) { + let ctx = self.ui.ctx(); + let state_id = bar.with("picker"); + let mut state = picker_state(ctx, state_id); + if !state.open { + open_picker(ctx, &mut state, linear); + ctx.data_mut(|data| data.insert_temp(state_id, state)); + } + } + /// A uniform colour (linear): a bar across the card that opens the picker (with the project's `swatches`), and the eyedropper; `eyedropping` is the bar whose pick waits for its click pub(crate) fn color_bar(&mut self, label: &str, linear: [f32; 3], eyedropping: Option, swatches: &[[f32; 3]]) -> ColorPick { let center_y = self.take(super::ROW_HEIGHT).center().y; diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index b4eb8182..30b16b1c 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -20,6 +20,26 @@ pub(super) const CARD_BLEED: f32 = 6.0; /// Corner radius of a card pub(super) const CARD_RADIUS: u8 = 6; +/// From a card's top to its name's centre +const CARD_NAME_CENTER: f32 = CARD_PADDING + 6.0; + +/// Air above a sub-group's name inside a held card, and the name row under it +const INNER_CAPTION_AIR: f32 = 6.0; +const INNER_CAPTION_ROW: f32 = 22.0; + +/// From an inner caption's row top to its name's centre +const INNER_CAPTION_CENTER: f32 = 10.0; + +/// Air between an inner caption's name and its hairline, and from the hairline's end to the right edge +const INNER_RULE_AIR: f32 = 8.0; +const INNER_RULE_END: f32 = 16.0; + +/// Air above the folded row that ends a held card +const CLOSING_FOLD_AIR: f32 = 2.0; + +/// The room a rule under a card's slot takes: the hairline 1 px down, then air (the next row starts 6 under the slot) +const SLOT_RULE_ROOM: f32 = 6.0; + /// From the right edge to the centre of a band's reset button const BAND_RESET_INSET: f32 = 26.0; @@ -33,6 +53,9 @@ const BAND_PICTURE_AIR: f32 = 8.0; /// A band's reset button click square const BAND_RESET_TARGET: f32 = 20.0; +/// How far above and below a foldable card's name a click folds it +const CARD_HIT_HALF_HEIGHT: f32 = 12.0; + /// How far a title's text reaches below its centre const TITLE_HALF_LINE: f32 = 7.0; @@ -117,6 +140,53 @@ impl PropertySheet<'_> { BandResponse { open, reset: reset_clicked } } + /// A folded group inside a card: bold name, its value (dim) and a caret; returns whether it is open + pub(crate) fn card(&mut self, title: &str, foldable: Option) -> bool { + if self.held && self.card.is_some() { + return self.inner_caption(title, foldable); + } + + self.open_card(); + let id = self.named_id("card", title); + self.scope = id; + let rect = self.take(CARD_NAME_CENTER + ROW_HEIGHT / 2.0); + let center_y = rect.top() + CARD_NAME_CENTER; + let open = foldable.is_none_or(|default_open| { + let hit = Rect::from_x_y_ranges(self.left..=self.right, (center_y - CARD_HIT_HALF_HEIGHT)..=(center_y + CARD_HIT_HALF_HEIGHT)); + self.fold_toggle(id, hit, title, default_open) + }); + + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + if foldable.is_some() { + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + } + self.drawn(center_y + TITLE_HALF_LINE); + open + } + + /// A sub-group inside the held card: its bold name on a hairline (no card in a card), a caret when it folds + fn inner_caption(&mut self, title: &str, foldable: Option) -> bool { + self.space(INNER_CAPTION_AIR); + let id = self.named_id("caption", title); + let rect = self.take(INNER_CAPTION_ROW); + let center_y = rect.top() + INNER_CAPTION_CENTER; + let open = foldable.is_none_or(|default_open| self.fold_toggle(id, Rect::from_x_y_ranges(self.left..=self.right, rect.y_range()), title, default_open)); + + let tokens = self.tokens; + let painter = self.ui.painter(); + let name = painter.text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + let rule_end = self.right - INNER_RULE_END; + if name.right() + INNER_RULE_AIR < rule_end { + painter.line_segment([pos2(name.right() + INNER_RULE_AIR, center_y), pos2(rule_end, center_y)], Stroke::new(1.0, tokens.separator)); + } + if foldable.is_some() { + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + } + self.drawn(center_y + TITLE_HALF_LINE); + open + } + /// A group's fold state kept under `id`, flipped by a click on `hit` (answering as `title`); returns whether it is open fn fold_toggle(&mut self, id: egui::Id, hit: Rect, title: &str, default_open: bool) -> bool { let mut open = self.ui.data(|data| data.get_temp::(id)).unwrap_or(default_open); @@ -134,12 +204,25 @@ impl PropertySheet<'_> { Rect::from_min_max(pos2(self.left - CARD_BLEED, rect.top()), pos2(self.right + CARD_BLEED, rect.bottom())) } + /// Keeps the card open now open through what follows: groups inside it become inner captions, and slots and cards join it, until [`Self::release_card`] + pub(crate) fn hold_card(&mut self) { + self.held = self.card.is_some(); + } + /// Ends [`Self::hold_card`] and closes the held card pub(crate) fn release_card(&mut self) { self.held = false; self.close_card(); } + /// A hairline across the open card under its slot row, then air before its settings + pub(crate) fn slot_rule(&mut self) { + let rect = self.take(SLOT_RULE_ROOM); + let y = rect.top() + 1.0; + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.drawn(y); + } + /// Starts a card with no name row: a slot card, whose slot is its top row; inside a held card it joins that card pub(crate) fn open_card(&mut self) { if self.held && self.card.is_some() { @@ -178,6 +261,12 @@ impl PropertySheet<'_> { open } + /// The folded row that ends a held card (its Attributes), [`CLOSING_FOLD_AIR`] under the rows before it; returns whether it is open + pub(crate) fn closing_fold(&mut self, title: &str) -> bool { + self.space(CLOSING_FOLD_AIR); + self.fold(title, None, false) + } + /// Ends the open card (not a held one: [`Self::release_card`] ends that): its face reaches [`CARD_PADDING`] below what its rows painted pub(crate) fn close_card(&mut self) { if self.held { diff --git a/crates/ui-egui/src/property_sheet/marker_drag.rs b/crates/ui-egui/src/property_sheet/marker_drag.rs new file mode 100644 index 00000000..8faaa6dc --- /dev/null +++ b/crates/ui-egui/src/property_sheet/marker_drag.rs @@ -0,0 +1,8 @@ +//! Where a gradient's dragged marker moved + +/// A marker that was dragged: which color, its new place and whether it continues the drag's undo step +pub(crate) struct MarkerDrag { + pub(crate) index: usize, + pub(crate) position: f32, + pub(crate) merge: bool, +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index fe8a47dd..fdef2d7b 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -2,6 +2,7 @@ mod action_row; mod action_row_response; +mod attribute_rows; mod axis_rows; mod band_response; mod button_icon; @@ -12,11 +13,13 @@ mod compare_row; mod compare_row_response; mod eye_toggle; mod factor_slider; +mod gradient_rows; mod group; mod hold_pad; mod id_color_row; mod id_color_row_response; mod info_icon; +mod marker_drag; mod material_rows; mod name_field; mod number_field; diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index f517175d..f44b8045 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -170,6 +170,9 @@ impl PropertySheet<'_> { let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; let (label, stack) = match lead { RowLead::Label { text, stack } => (text, stack), + let (label, stack, text_color) = match lead { + RowLead::Label { text, stack } => (text, stack, self.tokens.text), + RowLead::Tinted { text, color } => (text, false, color), RowLead::Loose(text) if shift + self.text_width(text, font.clone()) <= self.column() - self.left - LOOSE_LABEL_AIR => { self.paint_info(center_y); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); @@ -195,10 +198,10 @@ impl PropertySheet<'_> { self.seen.label_width = self.seen.label_width.max(width); } - let text = self.tokens.text; if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { self.paint_info(center_y); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); return self.column(); } diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs index 36d82d8a..84fc568d 100644 --- a/crates/ui-egui/src/property_sheet/row_lead.rs +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -14,6 +14,9 @@ pub(crate) enum RowLead<'a> { /// A setting of the row above, dim, its label on the label column like its parent's Child(&'a str), + + /// A label beside the controls column in a color of its own (Color Balance's color names) + Tinted { text: &'a str, color: egui::Color32 }, } impl<'a> RowLead<'a> { @@ -26,6 +29,7 @@ impl<'a> RowLead<'a> { pub(crate) fn text(self) -> &'a str { match self { RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) => text, + RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) | RowLead::Tinted { text, .. } => text, } } } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 14b8d740..aa8dde9c 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -1,11 +1,14 @@ use std::ops::RangeInclusive; use egui::{Align2, Id, Rect, Sense, Stroke, WidgetInfo, pos2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Rect, Response, Sense, Stroke, StrokeKind, WidgetInfo, pos2}; +use egui_phosphor::regular as ic; use super::number_field::shown_number; use super::track::Track; use super::value_text::ValueText; use super::{PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, TEXT_SIZE}; +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; /// Radius of a slider's knob @@ -29,6 +32,22 @@ const DIAL_ZERO_DEGREES: f32 = 90.0; /// Air between the dial and the value, and between the track's end and the dial const DIAL_AIR: f32 = 6.0; +/// Air between a tinted slider's track end and its right-hand color name +const TINT_WORD_AIR: f32 = 8.0; + +/// Half the height of Intensity's divider chip +const CHIP_HALF_HEIGHT: f32 = 10.0; + +/// The chip's room around its number: the caret and the air on both sides +const CHIP_PADDING: f32 = 24.0; + +/// Air between the chip and the value, beyond the panel's value column +const CHIP_TO_VALUE: f32 = 18.0; + +/// Where a slider's unit chip draws its caret and its text, from the chip's right end +const CHIP_CARET_INSET: f32 = 9.0; +const CHIP_TEXT_INSET: f32 = 18.0; + impl PropertySheet<'_> { /// A bounded number; `Some(merge)` when `value` changed, `merge` true for a drag's later steps pub(crate) fn slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { @@ -65,6 +84,22 @@ impl PropertySheet<'_> { Self::apply_typed(value, typed, dragged) } + /// A −1..1 balance between two tinted color names, left as the label and right after the track (`rights`: the group's right names) + pub(crate) fn tinted_slider(&mut self, left: (&str, Color32), right: (&str, Color32), rights: &[&str], value: &mut f32) -> Option { + let tokens = self.tokens; + let readable = |tint: Color32| crate::theme::legible_tint(tint, tokens.row, tokens.text); + let (control, center_y) = self.row_with(RowLead::Tinted { text: left.0, color: readable(left.1) }); + let id = self.next_id(); + let widest = rights.iter().map(|name| self.text_width(name, FontId::proportional(TEXT_SIZE))).fold(0.0, f32::max); + let word_x = self.track_end() - widest; + let track = Track { start: control.left() + KNOB_RADIUS, end: word_x - TINT_WORD_AIR, center_y, zero: Some(0.0), ramp: false }; + let range = -1.0..=1.0; + let dragged = self.track(id, left.0, &track, value, &range); + self.ui.painter().text(pos2(word_x, center_y), Align2::LEFT_CENTER, right.0, FontId::proportional(TEXT_SIZE), readable(right.1)); + let typed = self.value_field(id, left.0, center_y, *value, &range, 2, ""); + Self::apply_typed(value, typed, dragged) + } + /// An angle in degrees: the track, then a small dial just before the value pub(crate) fn angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { self.angle_led(RowLead::label(label), degrees, range) @@ -107,6 +142,40 @@ impl PropertySheet<'_> { Self::apply_typed(degrees, typed, dragged) } + /// A slider with a small dropdown chip before its value (Intensity's divider); returns the edit and the chip + pub(crate) fn slider_with_chip( + &mut self, + label: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + chip: &str, + widest_chip: &str, + ) -> (Option, Response) { + let (control, center_y) = self.row(label); + let id = self.next_id(); + let chip_end = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - CHIP_TO_VALUE; + let chip_width = self.text_width(widest_chip, FontId::proportional(TEXT_SIZE)) + CHIP_PADDING; + let chip_rect = Rect::from_min_max(pos2(chip_end - chip_width, center_y - CHIP_HALF_HEIGHT), pos2(chip_end, center_y + CHIP_HALF_HEIGHT)); + let chip_response = self.ui.interact(chip_rect, id.with("chip"), Sense::click()); + chip_response.widget_info(|| WidgetInfo::labeled(egui::Role::ComboBox, true, chip)); + + let tokens = self.tokens; + let open = egui::Popup::is_id_open(self.ui.ctx(), egui::Popup::default_response_id(&chip_response)); + let painter = self.ui.painter(); + painter.rect_filled(chip_rect, CornerRadius::same(CONTROL_RADIUS), if chip_response.hovered() { tokens.row_hover } else { tokens.button }); + if open { + painter.rect_stroke(chip_rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } + painter.text(pos2(chip_end - CHIP_CARET_INSET, center_y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(ICON_SIZE), tokens.text); + painter.text(pos2(chip_end - CHIP_TEXT_INSET, center_y), Align2::RIGHT_CENTER, chip, semibold(SMALL_TEXT_SIZE), tokens.text); + + let track = Track { start: control.left() + KNOB_RADIUS, end: chip_rect.left() - DIAL_AIR - KNOB_RADIUS, center_y, zero: None, ramp: false }; + let dragged = self.track(id, label, &track, value, &range); + let typed = self.value_field(id, label, center_y, *value, &range, decimals, ""); + (Self::apply_typed(value, typed, dragged), chip_response) + } + /// A typed value wins over a drag in the same frame and starts its own undo step pub(super) fn apply_typed(value: &mut f32, typed: Option, dragged: Option) -> Option { match typed { diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 3c144770..edee6c7a 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -75,6 +75,13 @@ impl PropertySheet<'_> { self.slot_row(thumbnail, name, source, on, clear, reset.then_some(true)) } + /// [`Self::slot`] whose ⟲ always shows beside the ×, faint and inert while what it restores is at its defaults (`changed` false) + pub(crate) fn slot_restorable(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, changed: bool) -> SlotResponse { + self.open_card(); + self.space(SLOT_CARD_TOP); + self.slot_row(thumbnail, name, source, None, true, Some(changed)) + } + /// [`Self::slot`]'s row inside the card open now (an input a mode adds, under that mode), not a card of its own pub(crate) fn slot_in_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, clear: bool) -> SlotResponse { self.slot_row(thumbnail, name, source, None, clear, None) diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 98b278e1..f0316e7d 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,6 +1,7 @@ -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; +use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; /// Draws a picture row's picture into its square @@ -93,6 +94,16 @@ impl PropertySheet<'_> { self.segments(control, options, selected, runs, None) } + /// [`Self::switch`] with its label always above it, the switch across the whole panel (long choices in a set of such switches); returns the picked index + pub(crate) fn stacked_switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { + if !self.switch_fits(options, self.left) { + return self.switch_dropdown(label, options, selected); + } + + let (control, _) = self.row_with(RowLead::Label { text: label, stack: true }); + self.segments(control, options, selected, untinted, None) + } + /// Whether every option's word fits its share of a switch from `left` to the panel's right edge fn switch_fits(&self, options: &[&str], left: f32) -> bool { let segment = (self.right - left) / options.len().max(1) as f32; diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index fc155266..adaeb900 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -99,7 +99,7 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { } } - if sheet.fold("Edges", None, true) { + if sheet.card("Edges", Some(true)) { sheet.toggle("Wrap", &mut state.wrap); sheet.toggle("Shape Crop", &mut state.crop); sheet.info(DEPTH_CULLING_TIP); @@ -115,6 +115,11 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { { *on = !*on; } + let (_, chip) = sheet.slider_with_chip("Intensity", &mut state.intensity, 0.0..=1.0, 2, &format!("÷{}", state.divider), "÷1000"); + let dividers = ["1", "10", "100", "1000"]; + if let Some(picked) = sheet.hanging_list(&chip, state.divider, ÷rs, &|divider: &str| format!("÷{divider}"), None).0 { + state.divider = picked; + } let band = sheet.band("Parameters", true, None, Some("3")); if band.open { sheet.caption("Offset"); @@ -325,6 +330,7 @@ fn card_under_caption(ui: &mut egui::Ui, state: &mut (bool, std::cell::Cell)) { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "ramp", |sheet| { + if let Some(drag) = sheet.gradient_ramp(&[[1.0, 0.0, 0.0]], &[state.0], &|_| [0.5; 3]) { + state.0 = drag.position; + state.1.push(drag.merge); + } + }); +} + +/// A marker pressed past the ramp's end changes nothing at first; its first move inward still starts its own undo step +#[test] +fn a_gradient_marker_pressed_past_the_ramps_end_starts_an_undo_step_with_its_first_change() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui_state(one_marker_ramp, (1.0, Vec::new())); + harness.run_steps(2); + let marker = harness.get_by_label("Color 1").rect(); + let past_end = marker.right_center() - egui::vec2(1.0, 0.0); + harness.drag_at(past_end); + harness.run(); + harness.hover_at(past_end + egui::vec2(20.0, 0.0)); + harness.run(); + harness.hover_at(past_end - egui::vec2(40.0, 0.0)); + harness.run(); + harness.hover_at(past_end - egui::vec2(60.0, 0.0)); + harness.run(); + harness.drop_at(past_end - egui::vec2(60.0, 0.0)); + harness.run(); + + let merges = &harness.state().1; + assert!(merges.len() >= 2, "the drag changes the value more than once: {merges:?}"); + assert_eq!(merges.first(), Some(&false), "the first real change starts an undo step: {merges:?}"); + assert!(merges.iter().skip(1).all(|merge| *merge), "later changes continue it: {merges:?}"); +} + #[test] fn the_label_column_fits_the_widest_short_label_and_long_labels_stack() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs index 4f81abb1..8fc9ebc0 100644 --- a/crates/ui-egui/src/property_sheet/tests/gallery.rs +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -20,6 +20,8 @@ pub(super) struct Gallery { pub(super) channel_on: bool, pub(super) channels: [bool; 5], pub(super) channel_value: f32, + pub(super) intensity: f32, + pub(super) divider: &'static str, pub(super) seed: u32, pub(super) randomized: u32, pub(super) long_choice: usize, @@ -44,6 +46,8 @@ impl Default for Gallery { channel_on: true, channels: [true, true, true, false, true], channel_value: 0.8, + intensity: 0.5, + divider: "1", seed: 1234, randomized: 0, long_choice: 0, diff --git a/crates/ui-egui/src/source_slot.rs b/crates/ui-egui/src/source_slot.rs index 454ff93b..e7474eec 100644 --- a/crates/ui-egui/src/source_slot.rs +++ b/crates/ui-egui/src/source_slot.rs @@ -1,7 +1,9 @@ //! What a source slot card edits: one channel of a fill's material, or a mask fill's one grayscale source +//! What a source slot card edits: one channel of a fill's material, a mask fill's one grayscale source, or a filter's image input use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, ChannelKind}; +use texturecraft_engine::core::{Channel, ChannelKind, ImageInput}; use crate::i18n::tr; @@ -11,6 +13,8 @@ pub(crate) enum SourceSlot { Channel(Channel), /// A mask fill's source, read as gray 0..1 Grayscale, + /// A filter's image input, read as gray 0..1 + Input(ImageInput), } impl SourceSlot { @@ -19,6 +23,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => tr(channel.label()), SourceSlot::Grayscale => tr("Grayscale"), + SourceSlot::Input(input) => tr(input.label), } } @@ -27,6 +32,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => channel.kind(), SourceSlot::Grayscale => ChannelKind::Scalar, + SourceSlot::Grayscale | SourceSlot::Input(_) => ChannelKind::Scalar, } } @@ -35,6 +41,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => channel.default_value(), SourceSlot::Grayscale => [1.0; 3], + SourceSlot::Input(input) => [input.default; 3], } } @@ -56,6 +63,7 @@ impl SourceSlot { match self { SourceSlot::Grayscale => ([0.0; 3], [1.0; 3]), + SourceSlot::Grayscale | SourceSlot::Input(_) => ([0.0; 3], [1.0; 3]), SourceSlot::Channel(Channel::BaseColor) => BASE_COLOR_ENDS, SourceSlot::Channel(Channel::Height) => HEIGHT_ENDS, SourceSlot::Channel(_) => CHANNEL_ENDS, @@ -67,6 +75,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => json!({"channel": channel.id()}), SourceSlot::Grayscale => json!({}), + SourceSlot::Input(input) => json!({"input": input.id}), } } @@ -75,6 +84,7 @@ impl SourceSlot { match self { SourceSlot::Channel(channel) => channel.id(), SourceSlot::Grayscale => "grayscale", + SourceSlot::Input(input) => input.id, } } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 05b2eb8f..33f94c62 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -397,12 +397,45 @@ pub const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; /// The axes' letters, as the Axis switches and the 3D fields' tags show them pub const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; +/// Cyan, magenta and yellow: the opposites of [`AXIS_COLORS`] at the same brightness (Color Balance's color names) +pub const OPPOSITE_COLORS: [Color32; 3] = [Color32::from_rgb(0x52, 0xb8, 0xc4), Color32::from_rgb(0xc4, 0x6a, 0xc8), Color32::from_rgb(0xd2, 0xb8, 0x52)]; + /// `from` moved `amount` of the way to `to` in gamma space, opaque pub(crate) fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount).round().clamp(0.0, 255.0) as u8; Color32::from_rgb(mix(from.r(), to.r()), mix(from.g(), to.g()), mix(from.b(), to.b())) } +/// Least contrast a tinted color name keeps against its background (the WCAG ratio for normal text: the names are regular 12 pt lettering) +const TINT_MIN_CONTRAST: f32 = 4.5; + +/// How finely [`legible_tint`] walks from the tint to the text colour: a tenth of the way at a time keeps as much of the tint as reads +const TINT_STEPS: u8 = 10; + +/// `tint` moved toward `text` just enough to read on `background` (Color Balance's yellow and cyan names on a light card); a tint that already reads stays as it is +pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color32 { + (0..=TINT_STEPS) + .map(|step| tint.lerp_to_gamma(text, f32::from(step) / f32::from(TINT_STEPS))) + .find(|color| contrast_ratio(*color, background) >= TINT_MIN_CONTRAST) + .unwrap_or(text) +} + +/// WCAG's flare term, added to both luminances so black still has a ratio +const WCAG_FLARE: f32 = 0.05; + +/// The WCAG contrast ratio of two opaque colors (1..21) +fn contrast_ratio(a: Color32, b: Color32) -> f32 { + let luminance = |color: Color32| { + let linear = egui::Rgba::from(color); + + // Rec. 709 luminance + 0.2126 * linear.r() + 0.7152 * linear.g() + 0.0722 * linear.b() + }; + let (first, second) = (luminance(a), luminance(b)); + let (high, low) = (first.max(second), first.min(second)); + (high + WCAG_FLARE) / (low + WCAG_FLARE) +} + /// A section caption inside a panel: semibold in the strong colour, as written (no capitals). pub fn caption(text: &str) -> egui::RichText { egui::RichText::new(text).font(semibold(12.5)).strong() @@ -412,6 +445,23 @@ pub fn caption(text: &str) -> egui::RichText { mod tests { use super::*; + #[test] + fn tint_names_reach_normal_text_contrast_and_a_tint_that_already_reads_stays_as_it_is() { + for theme in [Brightness::Light, Brightness::MediumLight, Brightness::MediumDark, Brightness::Dark] { + let tokens = Tokens::for_brightness(theme); + for tint in OPPOSITE_COLORS.into_iter().chain(AXIS_COLORS) { + let shown = legible_tint(tint, tokens.row, tokens.text); + assert!(contrast_ratio(shown, tokens.row) >= TINT_MIN_CONTRAST, "{theme:?} {tint:?} -> {shown:?}"); + if contrast_ratio(tint, tokens.row) >= TINT_MIN_CONTRAST { + assert_eq!(shown, tint, "{theme:?}: a tint that already reads stays as it is"); + } + } + } + + let light = Tokens::for_brightness(Brightness::Light); + assert_ne!(legible_tint(OPPOSITE_COLORS[2], light.row, light.text), OPPOSITE_COLORS[2], "yellow darkens on a light card"); + } + #[test] fn settings_round_trip_and_unknown_values_load_the_defaults() { for b in Brightness::ALL { @@ -429,18 +479,7 @@ mod tests { #[test] fn every_brightness_and_accent_reads() { - // Relative luminance (WCAG) and contrast ratio. - let lum = |c: Color32| { - let ch = |v: u8| { - let v = f32::from(v) / 255.0; - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } - }; - 0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b()) - }; - let contrast = |a: Color32, b: Color32| { - let (x, y) = (lum(a), lum(b)); - (x.max(y) + 0.05) / (x.min(y) + 0.05) - }; + let contrast = contrast_ratio; for b in Brightness::ALL { for a in Accent::ALL { let t = Tokens::for_brightness(b).with_accent(a); diff --git a/crates/ui-egui/tests/it/filter_colour.rs b/crates/ui-egui/tests/it/filter_colour.rs new file mode 100644 index 00000000..92d57879 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_colour.rs @@ -0,0 +1,85 @@ +//! The colour filters in Properties: HSL Perceptive's Mode switch and centred sliders, the tone cards of Color Balance and +//! Color Correct, and Blur's Wrap toggle + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, filter_of, topmost}; +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::Filter; + +#[test] +fn hsl_mode_switches_and_its_sliders_sit_at_the_middle() { + let (mut harness, effect) = app_with("hsl", "content", WINDOW_HEIGHT); + for label in ["Hue", "Saturation", "Lightness"] { + let value = harness.get_by_role_and_label(Role::Slider, label).accesskit_node().numeric_value(); + assert_eq!(value, Some(0.5), "{label} unchanged reads 0.50"); + } + + let regular = harness.get_by_role_and_label(Role::RadioButton, "Regular").rect(); + click_at(&mut harness, regular.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::Hsl { perceptive: false, .. }), "{:?}", filter_of(&harness, effect)); + + // A click at the right end of Saturation doubles it (stored 1) + let track = harness.get_by_role_and_label(Role::Slider, "Saturation").rect(); + click_at(&mut harness, along(track, 1.0)); + + assert!(matches!(filter_of(&harness, effect), Filter::Hsl { saturation, .. } if saturation > 0.95), "{:?}", filter_of(&harness, effect)); +} + +/// A stored hue past half a turn (0.75, the same hue as -0.25) shows wrapped round on the centred Hue slider, not pinned at its right end +#[test] +fn hsl_hue_past_half_a_turn_shows_wrapped_round() { + let (mut harness, effect) = app_with("hsl", "content", WINDOW_HEIGHT); + harness.state_mut().run("effect.set", serde_json::json!({"effect": effect.0, "hue": 0.75})); + harness.run_steps(2); + + let shown = harness.get_by_role_and_label(Role::Slider, "Hue").accesskit_node().numeric_value().unwrap(); + + assert!((shown - 0.25).abs() < 1e-3, "a quarter turn back shows a quarter left of the middle: {shown}"); +} + +/// Color Balance's tone cards fold one at a time, and a row edits only its own card's tone +#[test] +fn color_balance_tone_cards_fold_and_edit_their_own_tone() { + let (mut harness, effect) = app_with("colorBalance", "content", WINDOW_HEIGHT); + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, "Cyan").count(), 3, "a Cyan row per tone"); + + let midtones = harness.get_by_role_and_label(Role::Button, "Midtones").rect(); + click_at(&mut harness, midtones.center()); + + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, "Cyan").count(), 2, "Midtones folds"); + + // Highlights comes first: its Yellow row's left end pushes the highlights to yellow + let track = topmost(&harness, Role::Slider, "Yellow"); + click_at(&mut harness, along(track, 0.0)); + + let Filter::ColorBalance { highlights, shadows, midtones } = filter_of(&harness, effect) else { panic!() }; + assert!(highlights[2] < -0.9 && shadows == [0.0; 3] && midtones == [0.0; 3], "{highlights:?} {midtones:?} {shadows:?}"); +} + +/// Color Correct's Midtones card sits between its header and the Highlights card's, and its Saturation row edits the midtones only +#[test] +fn color_correct_midtones_card_edits_its_own_tone() { + let (mut harness, effect) = app_with("colorCorrect", "content", WINDOW_HEIGHT); + let midtones = harness.get_by_role_and_label(Role::Button, "Midtones").rect(); + let highlights = harness.get_by_role_and_label(Role::Button, "Highlights").rect(); + let track = harness + .get_all_by_role_and_label(Role::Slider, "Saturation") + .map(|node| node.rect()) + .find(|rect| rect.top() > midtones.bottom() && rect.bottom() < highlights.top()) + .unwrap(); + click_at(&mut harness, along(track, 0.0)); + + let Filter::ColorCorrect { shadows, midtones, .. } = filter_of(&harness, effect) else { panic!() }; + assert!(midtones[2] < 0.05 && shadows[2] == 0.5, "the Midtones card's Saturation: {midtones:?} {shadows:?}"); +} + +#[test] +fn blur_wrap_switches_the_edge_wrap() { + let (mut harness, effect) = app_with("blur", "content", WINDOW_HEIGHT); + let wrap = harness.get_by_role_and_label(Role::CheckBox, "Blur Wrap").rect(); + + click_at(&mut harness, wrap.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::Blur { wrap: true, .. })); +} diff --git a/crates/ui-egui/tests/it/filter_light.rs b/crates/ui-egui/tests/it/filter_light.rs new file mode 100644 index 00000000..d93268ba --- /dev/null +++ b/crates/ui-egui/tests/it/filter_light.rs @@ -0,0 +1,118 @@ +//! The light and shadow filters in Properties: Glow's Used on a Mask, Mode and signed Width, Drop Shadow's Angle and Distance, the Baked Lighting cards and rows (the Sun's angle names) + +use crate::filter_support::{TALL_WINDOW_HEIGHT, WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, topmost, undo, undo_depth}; +use egui::accesskit::Role; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{Filter, LightingOutput}; + +/// Clicks on Used on a Mask, Precise and the left end of Width turn the glow into a precise inner glow laid as white on the mask +#[test] +fn glow_rows_set_used_on_a_mask_precise_and_an_inner_width() { + let (mut harness, effect) = app_with("glow", "mask", WINDOW_HEIGHT); + + let toggle = harness.get_by_role_and_label(Role::CheckBox, "Used on a Mask").rect(); + click_at(&mut harness, toggle.center()); + let precise = harness.get_by_role_and_label(Role::RadioButton, "Precise").rect(); + click_at(&mut harness, precise.center()); + let width = harness.get_by_role_and_label(Role::Slider, "Width").rect(); + click_at(&mut harness, along(width, 0.0)); + + let Filter::HaloGlow { on_mask, precise, width, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(on_mask && precise, "{on_mask} {precise}"); + assert!(width < -0.9, "inner glow: {width}"); +} + +/// Drop Shadow's Distance reaches both ways and its Angle row carries a dial +#[test] +fn drop_shadow_distance_goes_both_ways() { + let (mut harness, effect) = app_with("dropShadow", "mask", WINDOW_HEIGHT); + let distance = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + + click_at(&mut harness, along(distance, 0.0)); + + let Filter::DropShadow { distance, angle, .. } = filter_of(&harness, effect) else { panic!() }; + assert!(distance < -0.45, "towards the light: {distance}"); + assert_eq!(angle, 90.0); + + // The dial sits between the Angle track and its value, so the track ends short of Distance's + let angle_track = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + let distance_track = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + assert!(angle_track.right() < distance_track.right() - DIAL_ROOM, "{angle_track:?} {distance_track:?}"); +} + +/// How much shorter than a plain slider's track an angle row's track is at least: room for its dial +const DIAL_ROOM: f32 = 10.0; + +/// Drop Shadow's Angle dial row: a drag turns it in one undo step, undo turns it back +#[test] +fn drop_shadow_angle_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("dropShadow", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + let angle = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + + drag(&mut harness, along(angle, 0.5), along(angle, 0.0)); + + let Filter::DropShadow { angle, .. } = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(angle < 0.5, "turned to 0: {angle}"); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + assert!(matches!(filter_of(&harness, effect), Filter::DropShadow { angle, .. } if angle == 90.0), "{:?}", filter_of(&harness, effect)); +} + +/// The Sun card's angles read Sun Horizontal Angle and Sun Vertical Angle; Light 1 and 2 keep Horizontal Angle and Vertical Angle +#[test] +fn baked_lighting_stylized_sun_angles_take_the_sun_names() { + let (harness, _) = app_with("bakedLighting", "content", TALL_WINDOW_HEIGHT); + + for label in ["Sun Horizontal Angle", "Sun Vertical Angle"] { + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, label).count(), 1, "{label}"); + } + for label in ["Horizontal Angle", "Vertical Angle"] { + assert_eq!(harness.query_all_by_role_and_label(Role::Slider, label).count(), 2, "{label}: Light 1 and 2"); + } +} + +/// Baked Lighting Stylized's cards edit their own settings: Sun Intensity's right end, Light 1's Intensity and Output's Specular only +#[test] +fn baked_lighting_stylized_cards_set_the_sun_a_light_and_the_output() { + let (mut harness, effect) = app_with("bakedLighting", "content", TALL_WINDOW_HEIGHT); + + let sun = harness.get_by_role_and_label(Role::Slider, "Sun Intensity").rect(); + click_at(&mut harness, along(sun, 1.0)); + + // Light 1's card comes before Light 2's + let light_1 = topmost(&harness, Role::Slider, "Intensity"); + click_at(&mut harness, along(light_1, 1.0)); + let output = harness.get_by_role_and_label(Role::ComboBox, "Diffuse + Specular").rect(); + click_at(&mut harness, output.center()); + let specular = harness.get_by_label("Specular only").rect(); + click_at(&mut harness, specular.center()); + + let filter = filter_of(&harness, effect); + let (stylized, light) = filter.stylized_lighting().unwrap(); + assert!(light.sun.intensity > 9.5, "{}", light.sun.intensity); + assert!(stylized.lights[0].intensity > 1.9 && stylized.lights[1].intensity == 0.0, "{:?}", stylized.lights); + assert_eq!(stylized.output, LightingOutput::Specular); +} + +/// Baked Lighting Environment's rows: Horizontal Rotation with its dial, a signed Exposure, and the stacked Specular Occlusion Intensity under its label +#[test] +fn baked_lighting_environment_rows_set_rotation_exposure_and_occlusion() { + let (mut harness, effect) = app_with("bakedLightingEnvironment", "content", TALL_WINDOW_HEIGHT); + + let rotation = harness.get_by_role_and_label(Role::Slider, "Horizontal Rotation").rect(); + click_at(&mut harness, rotation.center()); + let exposure = harness.get_by_role_and_label(Role::Slider, "Exposure").rect(); + click_at(&mut harness, along(exposure, 0.0)); + let specular = harness.get_by_role_and_label(Role::Slider, "Specular Occlusion Intensity").rect(); + click_at(&mut harness, along(specular, 1.0)); + + let Filter::EnvironmentLighting { horizontal, exposure, specular_occlusion, ambient_occlusion, .. } = filter_of(&harness, effect) else { + panic!("{:?}", filter_of(&harness, effect)) + }; + + assert!((150.0..210.0).contains(&horizontal), "half way round: {horizontal}"); + assert!(exposure < -4.5, "darker: {exposure}"); + assert!(specular_occlusion > 0.95 && ambient_occlusion == 1.0, "{specular_occlusion} {ambient_occlusion}"); +} diff --git a/crates/ui-egui/tests/it/filter_shape.rs b/crates/ui-egui/tests/it/filter_shape.rs new file mode 100644 index 00000000..50358d2b --- /dev/null +++ b/crates/ui-egui/tests/it/filter_shape.rs @@ -0,0 +1,307 @@ +//! The shape filters in Properties: Threshold's Mode switch, Mirror's mode-dependent rows, Mask Outline's, Bevel's, Bevel Smooth's, Directional Distance's, Warp's (its Directional mode and Angle) and Blur Slope's rows (its ÷ chip, Seed and Source Parameters' Blur) + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, lowest, pick, topmost, undo, undo_depth}; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::{ + BevelBlur, BevelCorner, BevelDirection, EffectKind, Filter, MirrorCorner, MirrorMode, OutlinePosition, SlopeBlending, ThresholdMode, WarpBlending, + WarpMode, WarpSourceMode, +}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Threshold's slider is named Threshold and its ≤ segment sets Lower or equal +#[test] +fn threshold_mode_switch_sets_the_comparison() { + let (mut harness, effect) = app_with("threshold", "mask", WINDOW_HEIGHT); + + let level = harness.get_by_role_and_label(Role::Slider, "Threshold").rect(); + click_at(&mut harness, along(level, 1.0)); + let lower = harness.get_by_role_and_label(Role::RadioButton, "≤").rect(); + click_at(&mut harness, lower.center()); + + let Filter::Threshold { level, mode } = filter_of(&harness, effect) else { panic!() }; + assert!(level > 0.95, "{level}"); + assert_eq!(mode, ThresholdMode::LowerOrEqual); +} + +/// Mirror shows Axis X Offset and Invert Axis X, swaps them for Axis Y's, and a corner mirror shows only its Corner Type +#[test] +fn mirror_rows_follow_the_mode() { + let (mut harness, effect) = app_with("mirror", "mask", WINDOW_HEIGHT); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert Axis X").rect(); + + click_at(&mut harness, invert.center()); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!(mirror.invert, [true, false]); + + let mode = harness.get_by_role_and_label(Role::ComboBox, "Mirror Axis X").rect(); + click_at(&mut harness, mode.center()); + let axis_y = harness.get_by_label("Mirror Axis Y").rect(); + click_at(&mut harness, axis_y.center()); + + assert!(harness.query_by_label("Axis Y Offset").is_some() && harness.query_by_label("Axis X Offset").is_none()); + + let mode = harness.get_by_role_and_label(Role::ComboBox, "Mirror Axis Y").rect(); + click_at(&mut harness, mode.center()); + let corner = harness.get_by_label("Mirror Corner").rect(); + click_at(&mut harness, corner.center()); + let corner_type = harness.get_by_role_and_label(Role::ComboBox, "Top Left").rect(); + click_at(&mut harness, corner_type.center()); + let bottom_right = harness.get_by_label("Bottom Right").rect(); + click_at(&mut harness, bottom_right.center()); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((mirror.mode, mirror.corner), (MirrorMode::Corner, MirrorCorner::BottomRight)); + assert!(harness.query_by_label("Axis Y Offset").is_none()); +} + +/// Mirror's mode list pick is one undo step, and undo puts Axis X back +#[test] +fn mirror_mode_pick_is_one_undo_step() { + let (mut harness, effect) = app_with("mirror", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + + pick(&mut harness, "Mirror Axis X", "Mirror Axis Y"); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!(mirror.mode, MirrorMode::AxisY); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the pick"); + + undo(&mut harness); + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!() }; + assert_eq!(mirror.mode, MirrorMode::AxisX); +} + +/// Mask Outline's Both segment, Start From Black toggle, Width and the signed Curve Shape each set their own setting +#[test] +fn mask_outline_rows_set_the_band() { + let (mut harness, effect) = app_with("maskOutline", "mask", WINDOW_HEIGHT); + + pick(&mut harness, "Outside", "Both"); + let from_black = harness.get_by_role_and_label(Role::CheckBox, "Start From Black").rect(); + click_at(&mut harness, from_black.center()); + let width = harness.get_by_role_and_label(Role::Slider, "Width").rect(); + click_at(&mut harness, along(width, 1.0)); + let curve = harness.get_by_role_and_label(Role::Slider, "Curve Shape").rect(); + click_at(&mut harness, along(curve, 0.0)); + + let Filter::MaskOutline(outline) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((outline.position, outline.from_black), (OutlinePosition::Both, false)); + assert!(outline.width > 0.95 && outline.curve < -0.95, "{outline:?}"); + assert_eq!((outline.threshold, outline.blur), (1.0, 0.0), "the others stay"); +} + +/// Bevel's Bevel Wrap, signed Distance, Corner Type, Smoothing and Blur Mode each set their own setting +#[test] +fn bevel_rows_set_the_slope() { + let (mut harness, effect) = app_with("bevel", "mask", WINDOW_HEIGHT); + + let wrap = harness.get_by_role_and_label(Role::CheckBox, "Bevel Wrap").rect(); + click_at(&mut harness, wrap.center()); + let distance = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + click_at(&mut harness, along(distance, 1.0)); + pick(&mut harness, "Round", "Angular"); + let smoothing = harness.get_by_role_and_label(Role::Slider, "Smoothing").rect(); + click_at(&mut harness, along(smoothing, 1.0)); + pick(&mut harness, "Non-Uniform", "Uniform"); + + let Filter::DistanceBevel(bevel) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((bevel.wrap, bevel.corner, bevel.blur), (true, BevelCorner::Angular, BevelBlur::Uniform)); + assert!(bevel.distance > 0.95 && bevel.smoothing > 4.9, "{bevel:?}"); +} + +/// Bevel's Distance drag is one undo step, and undo puts the distance back +#[test] +fn bevel_distance_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("bevel", "mask", WINDOW_HEIGHT); + let Filter::DistanceBevel(before) = filter_of(&harness, effect) else { panic!() }; + let depth = undo_depth(&harness); + let distance = harness.get_by_role_and_label(Role::Slider, "Distance").rect(); + + drag(&mut harness, along(distance, 0.5), along(distance, 1.0)); + + let Filter::DistanceBevel(bevel) = filter_of(&harness, effect) else { panic!() }; + assert!(bevel.distance > 0.95, "{bevel:?}"); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::DistanceBevel(before)); +} + +/// Bevel Smooth's Direction, Curve Offset and Bevel Wrap set their own setting +#[test] +fn bevel_smooth_rows() { + let (mut harness, effect) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); + + pick(&mut harness, "Out", "In/Out"); + let offset = harness.get_by_role_and_label(Role::Slider, "Curve Offset").rect(); + click_at(&mut harness, along(offset, 0.0)); + let wrap = harness.get_by_role_and_label(Role::CheckBox, "Bevel Wrap").rect(); + click_at(&mut harness, wrap.center()); + + let Filter::BevelSmooth(smooth) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((smooth.direction, smooth.wrap), (BevelDirection::InOut, true)); + assert!(smooth.curve_offset < -0.95 && smooth.distance == 0.1, "{smooth:?}"); +} + +/// Directional Distance's Angle row turns its trail and leaves the distance alone +#[test] +fn directional_distance_angle_row() { + let (mut harness, effect) = app_with("directionalDistance", "mask", WINDOW_HEIGHT); + let angle = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + + click_at(&mut harness, along(angle, 0.0)); + + let Filter::DirectionalDistance(trail) = filter_of(&harness, effect) else { panic!() }; + assert!(trail.angle < 5.0 && trail.distance == 0.1, "{trail:?}"); +} + +/// Warp shows the Angle only in the directional modes; Directions, Blending Mode, Source Mode, Source Tiling and Intensity set their own setting +#[test] +fn warp_rows_follow_the_mode() { + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_label("Angle").is_none() && harness.query_by_label("Source Parameters").is_some()); + + // The filter card is named Warp too: the Warp Mode list is the lower one + let mode = lowest(&harness, Role::ComboBox, "Warp"); + click_at(&mut harness, mode.center()); + let multi = harness.get_by_label("Multi Directional Warp").rect(); + click_at(&mut harness, multi.center()); + + assert!(harness.query_by_role_and_label(Role::Slider, "Angle").is_some(), "a directional mode turns by its Angle"); + + let two = harness.get_by_role_and_label(Role::RadioButton, "2").rect(); + click_at(&mut harness, two.center()); + pick(&mut harness, "Average", "Chain"); + pick(&mut harness, "Default Noise", "Previous Input"); + let tiling = harness.get_by_role_and_label(Role::Slider, "Source Tiling").rect(); + click_at(&mut harness, along(tiling, 1.0)); + let intensity = harness.get_by_role_and_label(Role::Slider, "Intensity").rect(); + click_at(&mut harness, along(intensity, 1.0)); + + let Filter::SourceWarp(warp) = filter_of(&harness, effect) else { panic!() }; + assert_eq!( + (warp.mode, warp.directions, warp.blending, warp.source.mode), + (WarpMode::MultiDirectional, 2, WarpBlending::Chain, WarpSourceMode::PreviousInput) + ); + assert!(warp.source.tiling > 15.9 && warp.intensity > 0.95, "{warp:?}"); + assert_eq!((warp.seed, warp.divider, warp.source.balance), (0, 10, 0.5), "the others stay"); +} + +/// Blur Slope shows the reference's rows in order (no Slope scale); Blending Mode, Source Type and Quality set their own setting +#[test] +fn slope_blur_rows_set_the_smear() { + let (mut harness, effect) = app_with("slopeBlur", "mask", WINDOW_HEIGHT); + assert!(harness.query_by_label("Slope scale").is_none()); + let top = |harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str| harness.get_by_role_and_label(role, label).rect().top(); + let order = [ + top(&harness, Role::Slider, "Intensity"), + top(&harness, Role::ComboBox, "Blur"), + top(&harness, Role::Slider, "Quality"), + harness.get_by_label("Source Parameters").rect().top(), + top(&harness, Role::ComboBox, "Default Noise"), + top(&harness, Role::Slider, "Blur"), + top(&harness, Role::Slider, "Position"), + top(&harness, Role::Slider, "Contrast"), + top(&harness, Role::Slider, "Source Tiling"), + ]; + assert!(order.windows(2).all(|pair| pair[0] < pair[1]), "{order:?}"); + + pick(&mut harness, "Blur", "Max"); + pick(&mut harness, "Default Noise", "Custom Noise"); + let quality = harness.get_by_role_and_label(Role::Slider, "Quality").rect(); + click_at(&mut harness, along(quality, 0.0)); + + let Filter::SourceSlopeBlur(slope) = filter_of(&harness, effect) else { panic!() }; + assert_eq!((slope.blending, slope.source.mode), (SlopeBlending::Max, WarpSourceMode::CustomNoise)); + assert!(slope.quality < 0.05, "{slope:?}"); + assert_eq!((slope.seed, slope.divider, slope.source.balance), (0, 10, 0.5), "the others stay"); + + // Source Type's list reads Custom Noise too: the input's slot is the lower, between it and Blur + let source_type = topmost(&harness, Role::ComboBox, "Custom Noise"); + let slot = lowest(&harness, Role::ComboBox, "Custom Noise"); + let blur = harness.get_by_role_and_label(Role::Slider, "Blur").rect(); + assert!(source_type.bottom() <= slot.top() && slot.bottom() <= blur.top(), "the Custom Noise input under Source Type: {source_type:?} {slot:?} {blur:?}"); +} + +/// Warp's Directional Warp (a list pick) shows its Angle, whose track turns it; the list pick is one undo step +#[test] +fn warp_directional_mode_and_its_angle() { + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + + // The filter card is named Warp too: the Warp Mode list is the lower one + let mode = lowest(&harness, Role::ComboBox, "Warp"); + click_at(&mut harness, mode.center()); + let directional = harness.get_by_label("Directional Warp").rect(); + click_at(&mut harness, directional.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::SourceWarp(warp) if warp.mode == WarpMode::Directional)); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the pick"); + + let angle = harness.get_by_role_and_label(Role::Slider, "Angle").rect(); + click_at(&mut harness, along(angle, 0.5)); + + let Filter::SourceWarp(warp) = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!((warp.angle - 180.0).abs() < 0.5, "half way round: {}", warp.angle); + + undo(&mut harness); + undo(&mut harness); + + assert!(matches!(filter_of(&harness, effect), Filter::SourceWarp(warp) if warp.mode == WarpMode::Warp), "{:?}", filter_of(&harness, effect)); +} + +/// A legacy Warp's seed past 2^24 opens in the Seed field exactly as stored (it read through an f32, one less) +#[test] +fn legacy_warp_seed_past_two_to_the_24_opens_as_stored() { + const LARGE_SEED: u32 = 16_777_217; + let (mut harness, effect) = app_with("warp", "mask", WINDOW_HEIGHT); + let project = &mut harness.state_mut().session.doc.project; + project.effect_mut(effect).unwrap().kind = EffectKind::Filter(Filter::Warp { intensity: 8.0, scale: 4.0, seed: LARGE_SEED, divider: 1 }); + harness.run_steps(2); + + let field = harness.get_by_role_and_label(Role::Label, "Seed value").rect(); + click_at(&mut harness, field.center()); + + let typed = harness.get_all_by_role(Role::TextInput).filter(|node| node.rect().intersects(field)).find_map(|node| node.accesskit_node().value()); + assert_eq!(typed, Some(LARGE_SEED.to_string())); +} + +/// Blur Slope's ÷ chip picks the divider, the dice picks a new Seed, and Source Parameters' Blur shows 0..20 over the stored 0..1 +#[test] +fn slope_blur_divider_seed_and_source_blur() { + let (mut harness, effect) = app_with("slopeBlur", "mask", WINDOW_HEIGHT); + + let chip = harness.get_by_role_and_label(Role::ComboBox, "÷10").rect(); + click_at(&mut harness, chip.center()); + let thousand = harness.get_by_role_and_label(Role::ListBoxOption, "÷1000").rect(); + click_at(&mut harness, thousand.center()); + let dice = harness.get_by_role_and_label(Role::Button, "Random").rect(); + click_at(&mut harness, dice.center()); + let blur = harness.get_by_role_and_label(Role::Slider, "Blur").rect(); + click_at(&mut harness, along(blur, 0.5)); + + let Filter::SourceSlopeBlur(slope) = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert_eq!(slope.divider, 1000); + assert_ne!(slope.seed, 0, "a new seed"); + assert!((slope.source.blur - 0.5).abs() < 0.01, "stored on 0..1: {}", slope.source.blur); + let shown = harness.get_by_role_and_label(Role::Slider, "Blur").accesskit_node().numeric_value().unwrap(); + assert!((shown - 10.0).abs() < 0.2, "shown on 0..20: {shown}"); +} + +/// Mirror's Display Debug switch and its axis offset track set their own setting +#[test] +fn mirror_debug_and_offset() { + let (mut harness, effect) = app_with("mirror", "mask", WINDOW_HEIGHT); + + let debug = harness.get_by_role_and_label(Role::CheckBox, "Display Debug").rect(); + click_at(&mut harness, debug.center()); + let offset = harness.get_by_role_and_label(Role::Slider, "Axis X Offset").rect(); + click_at(&mut harness, along(offset, 1.0)); + + let Filter::Mirror(mirror) = filter_of(&harness, effect) else { panic!("{:?}", filter_of(&harness, effect)) }; + assert!(mirror.debug); + assert_eq!(mirror.offset, [1.0, 0.5], "Axis X's offset only"); +} diff --git a/crates/ui-egui/tests/it/filter_simple.rs b/crates/ui-egui/tests/it/filter_simple.rs new file mode 100644 index 00000000..52e04446 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_simple.rs @@ -0,0 +1,240 @@ +//! The simple adjustment filters in Properties: Invert's switch, Height Adjust's Invert above its sliders, Histogram Scan's +//! Invert Position and Posterize's Apply to Alpha under theirs, Pixelate and FXAA (Anti-aliasing)'s switches, and the reference's names on +//! Clamp, Smoothstep, Histogram Shift, Sharpen, Blur and Blur Directional; Highpass's and Grayscale Conversion's rows; the simple sliders +//! (Contrast Luminosity, Clamp, Smoothstep, Sharpen, Histogram Range, Edge Detect, Replace Color) setting their own setting, a drag as one undo step + +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::{ConversionMode, Filter, HighpassSpace}; + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, lowest, pick, undo, undo_depth}; + +/// Invert's only row is its switch: a click turns it off, another back on +#[test] +fn invert_switch_turns_it_off_and_on() { + let (mut harness, effect) = app_with("invert", "mask", WINDOW_HEIGHT); + let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + + click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::InvertOff); + + let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::Invert); +} + +/// Height Adjust: Invert above Offset and Multiply; the switch flips it and Multiply's track sets it +#[test] +fn height_adjust_rows() { + let (mut harness, effect) = app_with("heightAdjust", "mask", WINDOW_HEIGHT); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + let offset = harness.get_by_role_and_label(Role::Slider, "Offset").rect(); + let multiply = harness.get_by_role_and_label(Role::Slider, "Multiply").rect(); + assert!(invert.center().y < offset.center().y && offset.center().y < multiply.center().y, "Invert, Offset, Multiply"); + + click_at(&mut harness, invert.center()); + click_at(&mut harness, along(multiply, 1.0)); + + let Filter::HeightAdjust { invert, offset, multiply } = filter_of(&harness, effect) else { panic!() }; + assert!(invert && offset == 0.0 && multiply > 9.5, "{invert} {offset} {multiply}"); +} + +/// Histogram Scan's Invert Position sits under Position and Contrast +#[test] +fn histogram_scan_switch_under_its_sliders() { + let (mut harness, effect) = app_with("histogramScan", "mask", WINDOW_HEIGHT); + let contrast = harness.get_by_role_and_label(Role::Slider, "Contrast").rect(); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert Position").rect(); + assert!(invert.center().y > contrast.center().y); + + click_at(&mut harness, invert.center()); + + assert!(matches!(filter_of(&harness, effect), Filter::HistogramScan { invert_position: true, .. })); +} + +/// Posterize's Apply to Alpha sits under Colors Amount +#[test] +fn posterize_switch_under_its_slider() { + let (mut harness, effect) = app_with("posterize", "mask", WINDOW_HEIGHT); + let amount = harness.get_by_role_and_label(Role::Slider, "Colors Amount").rect(); + let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply to Alpha").rect(); + assert!(alpha.center().y > amount.center().y); + + click_at(&mut harness, alpha.center()); + + assert_eq!(filter_of(&harness, effect), Filter::Posterize { levels: 8.0, alpha: true }); +} + +/// Clamp's Min and Max, Smoothstep's Minimum and Maximum and Sharpen Intensity +#[test] +fn reference_names_on_the_sliders() { + for (filter, labels) in [("clamp", &["Min", "Max"][..]), ("smoothstep", &["Minimum", "Maximum"]), ("sharpen", &["Sharpen Intensity"])] { + let (harness, _) = app_with(filter, "mask", WINDOW_HEIGHT); + for label in labels { + assert!(harness.query_by_role_and_label(Role::Slider, label).is_some(), "{filter}: {label}"); + } + } +} + +/// Histogram Shift's Position: a click on its middle shifts by a half turn back +#[test] +fn histogram_shift_position_middle_is_a_half_turn_back() { + let (mut harness, effect) = app_with("histogramShift", "mask", WINDOW_HEIGHT); + let position = harness.get_by_role_and_label(Role::Slider, "Position").rect(); + + click_at(&mut harness, position.center()); + + let Filter::HistogramShift { offset } = filter_of(&harness, effect) else { panic!() }; + assert!((offset + 0.5).abs() < 0.05, "the middle is a half turn back: {offset}"); +} + +/// The setting slider case `label` of a filter sets, read back from the filter +type ReadSetting = fn(&Filter) -> Option; + +/// One slider per case, clicked at `share` of its track: (library filter, slider, share, the setting it sets, the value expected) +const SLIDER_CASES: [(&str, &str, f32, ReadSetting, f32); 12] = [ + ("contrastLuminosity", "Contrast", 1.0, |filter| if let Filter::ContrastLuminosity { contrast, .. } = filter { Some(*contrast) } else { None }, 1.0), + ("contrastLuminosity", "Luminosity", 0.0, |filter| if let Filter::ContrastLuminosity { luminosity, .. } = filter { Some(*luminosity) } else { None }, -1.0), + ("clamp", "Min", 0.5, |filter| if let Filter::Clamp { min, .. } = filter { Some(*min) } else { None }, 0.5), + ("clamp", "Max", 0.5, |filter| if let Filter::Clamp { max, .. } = filter { Some(*max) } else { None }, 0.5), + ("smoothstep", "Minimum", 0.5, |filter| if let Filter::Smoothstep { min, .. } = filter { Some(*min) } else { None }, 0.5), + ("smoothstep", "Maximum", 0.5, |filter| if let Filter::Smoothstep { max, .. } = filter { Some(*max) } else { None }, 0.5), + ("sharpen", "Sharpen Intensity", 1.0, |filter| if let Filter::Sharpen { amount } = filter { Some(*amount) } else { None }, 4.0), + ("histogramRange", "Range", 1.0, |filter| if let Filter::HistogramRange { range, .. } = filter { Some(*range) } else { None }, 1.0), + ("histogramRange", "Position", 0.0, |filter| if let Filter::HistogramRange { position, .. } = filter { Some(*position) } else { None }, 0.0), + ("edgeDetect", "Width", 0.5, |filter| if let Filter::EdgeDetect { width } = filter { Some(*width) } else { None }, 32.0), + ("replaceColor", "Tolerance", 1.0, |filter| if let Filter::ReplaceColor { tolerance, .. } = filter { Some(*tolerance) } else { None }, 1.0), + ("replaceColor", "Softness", 1.0, |filter| if let Filter::ReplaceColor { softness, .. } = filter { Some(*softness) } else { None }, 1.0), +]; + +/// How near a clicked slider's setting must land to the value expected +const SLIDER_TOLERANCE: f32 = 0.01; + +/// Each simple filter's sliders set their own setting through the pointer +#[test] +fn simple_sliders_set_their_own_setting() { + for (filter, label, share, read, expected) in SLIDER_CASES { + let (mut harness, effect) = app_with(filter, "content", WINDOW_HEIGHT); + let before = filter_of(&harness, effect); + let track = harness.get_by_role_and_label(Role::Slider, label).rect(); + + click_at(&mut harness, along(track, share)); + + let after = filter_of(&harness, effect); + let value = read(&after).unwrap(); + assert!((value - expected).abs() < SLIDER_TOLERANCE, "{filter} {label}: {value}, expected {expected}"); + assert_ne!(read(&before), read(&after), "{filter} {label} changed"); + } +} + +/// A slider drag is one undo step, and undo puts the value back +#[test] +fn a_slider_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("sharpen", "content", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + let track = harness.get_by_role_and_label(Role::Slider, "Sharpen Intensity").rect(); + + drag(&mut harness, along(track, 0.5), along(track, 1.0)); + + assert!(matches!(filter_of(&harness, effect), Filter::Sharpen { amount } if amount > 3.9), "{:?}", filter_of(&harness, effect)); + assert_eq!(undo_depth(&harness), depth + 1); + + undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Sharpen { amount: 1.0 }); +} + +/// Pixelate: Pixels Amount (32) with Apply To Alpha under it +#[test] +fn pixelate_rows() { + let (mut harness, effect) = app_with("pixelate", "mask", WINDOW_HEIGHT); + let amount = harness.get_by_role_and_label(Role::Slider, "Pixels Amount"); + assert_eq!(amount.accesskit_node().numeric_value().map(f64::round), Some(32.0)); + let amount = amount.rect(); + let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); + assert!(alpha.center().y > amount.center().y); + + click_at(&mut harness, alpha.center()); + assert!(matches!(filter_of(&harness, effect), Filter::Mosaic { alpha: false, .. })); + + click_at(&mut harness, along(amount, 1.0)); + let Filter::Mosaic { size, .. } = filter_of(&harness, effect) else { panic!() }; + assert!((Filter::pixels_amount(size) - 128.0).abs() < 0.5, "the right end is 128 across: {size}"); +} + +/// FXAA (Anti-aliasing): only its Affect Alpha Channel switch +#[test] +fn fxaa_rows() { + let (mut harness, effect) = app_with("fxaa", "mask", WINDOW_HEIGHT); + let affect = harness.get_by_role_and_label(Role::CheckBox, "Affect Alpha Channel").rect(); + + click_at(&mut harness, affect.center()); + + assert_eq!(filter_of(&harness, effect), Filter::Fxaa { alpha: true }); +} + +/// Blur's Blur Intensity takes the reference's name and starts at 0.30 +#[test] +fn blur_intensity_takes_the_reference_name() { + let (harness, _) = app_with("blur", "mask", WINDOW_HEIGHT); + let intensity = harness.get_by_role_and_label(Role::Slider, "Blur Intensity"); + assert_eq!(intensity.accesskit_node().numeric_value().map(|value| (value * 100.0).round()), Some(30.0)); +} + +/// Blur Directional's Intensity and Angle take the reference's names, and Intensity's right end is the widest blur +#[test] +fn blur_directional_rows_take_the_reference_names() { + let (mut harness, effect) = app_with("blurDirectional", "mask", WINDOW_HEIGHT); + let intensity = harness.get_by_role_and_label(Role::Slider, "Intensity").rect(); + assert!(harness.query_by_role_and_label(Role::Slider, "Angle").is_some()); + + click_at(&mut harness, along(intensity, 1.0)); + + assert!(matches!(filter_of(&harness, effect), Filter::DirectionalBlur { radius, .. } if radius > 250.0)); +} + +/// Highpass: Color Space, Radius and Apply To Alpha, each setting its own value +#[test] +fn highpass_rows() { + let (mut harness, effect) = app_with("highPass", "mask", WINDOW_HEIGHT); + let radius = harness.get_by_role_and_label(Role::Slider, "Radius"); + assert_eq!(radius.accesskit_node().numeric_value().map(|value| (value * 100.0).round()), Some(300.0)); + let radius = radius.rect(); + let space = harness.get_by_role_and_label(Role::ComboBox, "Working space / Mask").rect(); + let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); + assert!(space.center().y < radius.center().y && radius.center().y < alpha.center().y, "the reference's order"); + + pick(&mut harness, "Working space / Mask", "sRGB (from ACEScg)"); + click_at(&mut harness, alpha.center()); + assert_eq!(filter_of(&harness, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); + + click_at(&mut harness, along(radius, 1.0)); + assert!(matches!(filter_of(&harness, effect), Filter::HighPass { radius, .. } if radius > 250.0), "Radius 16 = 256 texels at 2K"); +} + +/// Grayscale Conversion: Channel Input (Custom Input shows its slot right under it), Invert, Balance, Contrast, Mode and the weights in Channels Weights only +#[test] +fn grayscale_conversion_rows() { + let (mut harness, effect) = app_with("grayscale", "mask", WINDOW_HEIGHT); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect().center().y; + let sliders = ["Balance", "Contrast", "Red", "Green", "Blue", "Alpha"].map(|label| harness.get_by_role_and_label(Role::Slider, label).rect().center().y); + let rows: Vec = std::iter::once(invert).chain(sliders).collect(); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Input").is_none(), "no slot for the current channel"); + + pick(&mut harness, "Current Channel", "Custom Input"); + + let Filter::GrayscaleConversion(conversion) = filter_of(&harness, effect) else { panic!() }; + assert!(conversion.custom_input); + + // The lowest: Channel Input shows the same name where its words don't fit a switch + let slot = lowest(&harness, Role::ComboBox, "Custom Input"); + let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); + assert!(slot.center().y < invert.center().y, "its slot right under Channel Input"); + + click_at(&mut harness, invert.center()); + pick(&mut harness, "Channels Weights", "Max"); + + let Filter::GrayscaleConversion(conversion) = filter_of(&harness, effect) else { panic!() }; + assert!(conversion.invert && conversion.mode == ConversionMode::Max); + assert!(harness.query_by_label("Red").is_none(), "no weights outside Channels Weights"); +} diff --git a/crates/ui-egui/tests/it/filter_stylize.rs b/crates/ui-egui/tests/it/filter_stylize.rs new file mode 100644 index 00000000..b285db69 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_stylize.rs @@ -0,0 +1,178 @@ +//! Anisotropic Kuwahara's, PBR Validate (Metallic Roughness)'s, Height To Normal's and Color Match's rows in Properties + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{ + AnisotropicKuwahara, ColorMatch, Filter, HeightToNormal, LayerId, PbrValidate, SourceColorMode, TargetColorMode, ValidationMode, +}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::{TALL_WINDOW_HEIGHT, WINDOW_HEIGHT, along, app_with, click_at, filter_of, lowest, pick, undo_depth}; + +/// Anisotropic Kuwahara: Extract Direction (its Custom Input slot right under it), then Radius … Anisotropy and the Anisotropy Angle dial, in the reference's order +#[test] +fn anisotropic_kuwahara_rows() { + let (mut harness, effect) = app_with("anisotropicKuwahara", "mask", WINDOW_HEIGHT); + let rows = ["Radius", "Smoothness", "Sharpness", "Tensor Smoothness", "Anisotropy", "Anisotropy Angle"] + .map(|label| harness.get_by_role_and_label(Role::Slider, label).rect().center().y); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Input").is_none(), "no slot for the current channel"); + + pick(&mut harness, "Current Channel", "Custom Input"); + + let Filter::AnisotropicKuwahara(kuwahara) = filter_of(&harness, effect) else { panic!("still Kuwahara") }; + assert!(kuwahara.custom_input); + let slot = lowest(&harness, Role::ComboBox, "Custom Input"); + let radius = harness.get_by_role_and_label(Role::Slider, "Radius").rect(); + assert!(slot.center().y < radius.center().y, "its slot right under Extract Direction"); + + // A click at the left end of Sharpness's track reaches its least value, the library's + let sharpness = harness.get_by_role_and_label(Role::Slider, "Sharpness").rect(); + click_at(&mut harness, along(sharpness, 0.0)); + + let Filter::AnisotropicKuwahara(kuwahara) = filter_of(&harness, effect) else { panic!("still Kuwahara") }; + assert!((kuwahara.sharpness - AnisotropicKuwahara::LIBRARY.sharpness).abs() < 0.02, "{}", kuwahara.sharpness); +} + +/// The height of the label line a stacked setting shows above its control (the panel style's stack rhythm) +const STACK_LABEL_LINE: f32 = 18.0; + +/// PBR Validate: three switches, each label above its switch across the panel; each click sets its own setting +#[test] +fn pbr_validate_rows() { + let (mut harness, effect) = app_with("pbrValidate", "content", TALL_WINDOW_HEIGHT); + let firsts = ["Albedo", "50 sRGB", "70-100% Reflective"].map(|option| harness.get_by_role_and_label(Role::RadioButton, option).rect()); + for pair in firsts.windows(2) { + assert!((pair[0].left() - pair[1].left()).abs() < 1.0, "every switch starts at the panel's edge: {pair:?}"); + assert!(pair[1].top() - pair[0].bottom() >= STACK_LABEL_LINE, "a label line between the switches: {pair:?}"); + } + let last = harness.get_by_role_and_label(Role::RadioButton, "60-100% Reflective").rect(); + let combined = harness.get_by_role_and_label(Role::RadioButton, "Combined").rect(); + assert!((last.right() - combined.right()).abs() < 1.0, "all as wide: {last:?} {combined:?}"); + + for option in ["Albedo", "50 sRGB", "70-100% Reflective"] { + let segment = harness.get_by_role_and_label(Role::RadioButton, option).rect(); + click_at(&mut harness, segment.center()); + } + + assert_eq!(filter_of(&harness, effect), Filter::PbrValidate(PbrValidate { mode: ValidationMode::Albedo, albedo_dark: 50, metal_low: 70 })); +} + +/// Where along Surface Size's track the click lands: away from the default and between whole centimetres, so rounding shows +const OFF_DEFAULT_SHARE: f32 = 0.37; + +/// A click on Surface Size that rounds to the centimetres it holds changes nothing, so it adds no undo step +#[test] +fn height_to_normal_click_rounding_to_the_stored_size_adds_no_step() { + let (mut harness, effect) = app_with("heightToNormal", "mask", WINDOW_HEIGHT); + let size = harness.get_by_role_and_label(Role::Slider, "Surface Size (cm)").rect(); + click_at(&mut harness, along(size, OFF_DEFAULT_SHARE)); + let (depth, after_first) = (undo_depth(&harness), filter_of(&harness, effect)); + + click_at(&mut harness, along(size, OFF_DEFAULT_SHARE)); + + assert_eq!(filter_of(&harness, effect), after_first); + assert_eq!(undo_depth(&harness), depth, "the same whole centimetres again: no new step"); +} + +/// Height To Normal: its two switches, then whole Surface Size (cm) and Height Depth (cm), or Normal Intensity without world units +#[test] +fn height_to_normal_rows() { + let (mut harness, effect) = app_with("heightToNormal", "mask", WINDOW_HEIGHT); + let rows = [ + (Role::CheckBox, "Overwrite Existing Normal"), + (Role::CheckBox, "Use World Units"), + (Role::Slider, "Surface Size (cm)"), + (Role::Slider, "Height Depth (cm)"), + ] + .map(|(role, label)| harness.get_by_role_and_label(role, label).rect().center().y); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + + // A click on Surface Size's track sets whole centimetres + let size = harness.get_by_role_and_label(Role::Slider, "Surface Size (cm)").rect(); + click_at(&mut harness, along(size, OFF_DEFAULT_SHARE)); + + let Filter::HeightToNormal(filter) = filter_of(&harness, effect) else { panic!("still Height To Normal") }; + assert!(filter.surface_size != 300.0 && filter.surface_size.fract() == 0.0, "{}", filter.surface_size); + assert!(harness.query_by_role_and_label(Role::Slider, "Normal Intensity").is_none()); + + let overwrite = harness.get_by_role_and_label(Role::CheckBox, "Overwrite Existing Normal").rect(); + click_at(&mut harness, overwrite.center()); + let world = harness.get_by_role_and_label(Role::CheckBox, "Use World Units").rect(); + click_at(&mut harness, world.center()); + + let Filter::HeightToNormal(filter) = filter_of(&harness, effect) else { panic!("still Height To Normal") }; + assert_eq!((filter.overwrite, filter.world_units, filter.intensity), (false, false, HeightToNormal::LIBRARY.intensity)); + assert!(harness.query_by_role_and_label(Role::Slider, "Surface Size (cm)").is_none()); + + // A click at the left end of Normal Intensity's track reaches 0 + let intensity = harness.get_by_role_and_label(Role::Slider, "Normal Intensity").rect(); + click_at(&mut harness, along(intensity, 0.0)); + + let Filter::HeightToNormal(filter) = filter_of(&harness, effect) else { panic!("still Height To Normal") }; + assert!(filter.intensity < 0.5, "{}", filter.intensity); +} + +/// The Color Match settings effect `effect` holds now +fn color_match_of(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> ColorMatch { + let Filter::ColorMatch(matcher) = filter_of(harness, effect) else { panic!("still Color Match") }; + matcher +} + +/// Color Match: Source Color Mode (a list: its three words don't fit a switch), Target Color Mode (a switch, a list where its words don't fit), Target Color, Custom Color Variation and its Color Variation card; each mode's color or image slot right under it, clicked through the pointer +#[test] +fn color_match_rows() { + let (mut harness, effect) = app_with("colorMatch", "content", TALL_WINDOW_HEIGHT); + + // Target Color Mode's control: its switch's segment, or its list where the words don't fit + let target_mode = |harness: &Harness<'_, TextureCraftApp>, shown: &str| { + harness + .query_all_by(|node| matches!(node.role(), Role::RadioButton | Role::ComboBox) && node.label().as_deref() == Some(shown)) + .map(|node| node.rect()) + .min_by(|a, b| a.top().total_cmp(&b.top())) + .unwrap() + }; + let rows = [ + harness.get_by_role_and_label(Role::ComboBox, "Average").rect(), + target_mode(&harness, "Parameter"), + harness.get_by_role_and_label(Role::Button, "Target Color").rect(), + harness.get_by_role_and_label(Role::CheckBox, "Custom Color Variation").rect(), + harness.get_by_role_and_label(Role::Slider, "Hue").rect(), + harness.get_by_role_and_label(Role::Slider, "Chroma").rect(), + harness.get_by_role_and_label(Role::Slider, "Luma").rect(), + ] + .map(|rect| rect.center().y); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); + assert!(harness.query_by_role_and_label(Role::Button, "Source Color").is_none(), "Average shows no Source Color"); + + pick(&mut harness, "Parameter", "Image Input"); + + assert_eq!(color_match_of(&harness, effect).target_mode, TargetColorMode::ImageInput); + assert!(harness.query_by_role_and_label(Role::Button, "Target Color").is_none(), "the Image Input slot replaces Target Color"); + let shown = harness.query_all_by_label("Image Input").count(); + assert!(shown >= 2, "the mode and its slot: {shown}"); + + // The source list's own Parameter row (not a control showing Parameter) + let list = harness.get_by_role_and_label(Role::ComboBox, "Average").rect(); + click_at(&mut harness, list.center()); + let row = harness + .query_all_by(|node| !matches!(node.role(), Role::RadioButton | Role::ComboBox) && node.label().as_deref() == Some("Parameter")) + .map(|node| node.rect()) + .find(|rect| rect.top() >= list.bottom() - 1.0) + .unwrap(); + click_at(&mut harness, row.center()); + + assert_eq!(color_match_of(&harness, effect).source_mode, SourceColorMode::Parameter); + let source = harness.get_by_role_and_label(Role::Button, "Source Color").rect(); + assert!(source.center().y < target_mode(&harness, "Image Input").center().y, "Source Color right under its mode"); + + let luma = harness.get_by_role_and_label(Role::Slider, "Luma").rect(); + click_at(&mut harness, along(luma, 1.0)); + assert!(color_match_of(&harness, effect).luma > 0.95, "{}", color_match_of(&harness, effect).luma); + + let custom = harness.get_by_role_and_label(Role::CheckBox, "Custom Color Variation").rect(); + click_at(&mut harness, custom.center()); + assert!(!color_match_of(&harness, effect).custom_variation); + assert!(harness.query_by_role_and_label(Role::Slider, "Hue").is_none(), "the Color Variation card goes with its switch"); +} diff --git a/crates/ui-egui/tests/it/filter_transform.rs b/crates/ui-egui/tests/it/filter_transform.rs new file mode 100644 index 00000000..38af6e79 --- /dev/null +++ b/crates/ui-egui/tests/it/filter_transform.rs @@ -0,0 +1,86 @@ +//! The Transform filter in Properties: Scaling and Offset beside its preview, Tile Safe Rotation, Rotation, Repeat mode and Flip mode + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{Filter, FlipMode, RepeatMode, TileTransform}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::{WINDOW_HEIGHT, along, app_with, click_at, drag, filter_of, undo, undo_depth}; + +/// Every row sets its own setting through the pointer, in the reference's order +#[test] +fn transform_rows_set_the_transform() { + let (mut harness, effect) = app_with("transform", "mask", WINDOW_HEIGHT); + let transform = |harness: &Harness<'_, TextureCraftApp>| match filter_of(harness, effect) { + Filter::Transform(transform) => transform, + other => panic!("not a transform: {other:?}"), + }; + assert_eq!(transform(&harness), TileTransform::LIBRARY); + + let top = |harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str| harness.get_by_role_and_label(role, label).rect().top(); + let order = [ + top(&harness, Role::Slider, "Scaling"), + top(&harness, Role::Slider, "Offset"), + top(&harness, Role::CheckBox, "Tile Safe Rotation"), + top(&harness, Role::Slider, "Rotation"), + top(&harness, Role::ComboBox, "Horizontally & Vertically"), + top(&harness, Role::ComboBox, "None"), + ]; + assert!(order.windows(2).all(|pair| pair[0] < pair[1]), "Scaling, Offset, Tile Safe Rotation, Rotation, Repeat mode, Flip mode: {order:?}"); + + // Linked, the Scaling track sets both directions + let scaling = harness.get_by_role_and_label(Role::Slider, "Scaling").rect(); + click_at(&mut harness, along(scaling, 1.0)); + + let scaled = transform(&harness).scaling; + assert!(scaled[0] > 4.5 && scaled[0] == scaled[1], "{scaled:?}"); + + let offset = harness.get_by_role_and_label(Role::Slider, "Offset").rect(); + click_at(&mut harness, along(offset, 1.0)); + + let moved = transform(&harness).offset; + assert!(moved[0] > 0.95 && moved[1] == 0.0, "the first Offset slider moves across: {moved:?}"); + + let tile_safe = harness.get_by_role_and_label(Role::CheckBox, "Tile Safe Rotation").rect(); + click_at(&mut harness, tile_safe.center()); + + assert!(!transform(&harness).tile_safe); + + let rotation = harness.get_by_role_and_label(Role::Slider, "Rotation").rect(); + click_at(&mut harness, rotation.center()); + + let degrees = transform(&harness).rotation; + assert!((150.0..210.0).contains(°rees), "{degrees}"); + + let flip = harness.get_by_role_and_label(Role::ComboBox, "None").rect(); + click_at(&mut harness, flip.center()); + let vertically = harness.get_by_label("Vertically").rect(); + click_at(&mut harness, vertically.center()); + + assert_eq!(transform(&harness).flip, FlipMode::Vertically); + + let repeat = harness.get_by_role_and_label(Role::ComboBox, "Horizontally & Vertically").rect(); + click_at(&mut harness, repeat.center()); + let none = harness.get_by_label("None").rect(); + click_at(&mut harness, none.center()); + + assert_eq!(transform(&harness).repeat, RepeatMode::None); +} + +/// A Rotation drag is one undo step, and undo turns the tile back +#[test] +fn rotation_drag_is_one_undo_step() { + let (mut harness, effect) = app_with("transform", "mask", WINDOW_HEIGHT); + let depth = undo_depth(&harness); + let rotation = harness.get_by_role_and_label(Role::Slider, "Rotation").rect(); + + drag(&mut harness, along(rotation, 0.0), along(rotation, 0.5)); + + let Filter::Transform(turned) = filter_of(&harness, effect) else { panic!() }; + assert!((150.0..210.0).contains(&turned.rotation), "{turned:?}"); + assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); + + undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Transform(TileTransform::LIBRARY)); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3e9a0d64..6cf3242b 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -33,7 +33,6 @@ mod fill_projection_rows; mod fill_support; mod fill_symmetry_rows; mod filter_picker; -mod filter_support; mod folder_properties; mod frame_selection; mod generator_panel; @@ -66,6 +65,7 @@ mod pen_pressure; mod polygon_fill; mod popup_press_close; mod project_config; +mod properties_lists; mod properties_min_width; mod properties_popup; mod properties_scroll; @@ -101,6 +101,16 @@ mod view2d_tiles; mod view_mode_picker; mod window_menu_684; +mod filter_card; +mod filter_colour; +mod filter_gradient; +mod filter_inputs; +mod filter_light; +mod filter_shape; +mod filter_simple; +mod filter_stylize; +mod filter_support; +mod filter_transform; mod stencil; mod symmetry; mod symmetry_2d; diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs new file mode 100644 index 00000000..ef3bcb47 --- /dev/null +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -0,0 +1,265 @@ +//! Every list in each Properties screen, through real pointer input: a click opens it; with it open the view still zooms on the wheel, pans on a middle drag and orbits on an Alt drag; Escape, a click outside and a stroke on the model close it + +use egui::accesskit::Role; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Vec2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::fill_support::{click_node, fill_app}; +use crate::filter_support::click_at; +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, WHEEL_NOTCH}; + +/// Moves of a drag in the view, each a few points, so it is a drag well before its release +const DRAG_MOVES: usize = 6; + +/// A drag in the view: long enough to move the camera, short enough to stay in the view +const GESTURE: Vec2 = vec2(-60.0, 40.0); + +/// Where in the view the gestures start, as a share of its width from its left edge +const GESTURE_SHARE: f32 = 0.3; + +/// Escapes between lists, so one that stays open can't leave its popup over the next +const ESCAPES_TO_CLEAR: usize = 2; + +/// The Properties screen a `setup` leaves selected in the sample session +fn screen(setup: impl FnOnce(&mut Session)) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + setup(&mut session); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_accessibility_check(false).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(STARTUP_FRAMES); + harness +} + +/// A new fill layer with a white mask, `command` adding an effect with `params` to its `target` stack, and that effect selected +fn with_effect(session: &mut Session, target: &str, command: &str, params: Value) { + let layer = execute(session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(session, "mask.add.white", &json!({"layer": layer})).unwrap(); + let mut params = params; + params["layer"] = json!(layer); + params["target"] = json!(target); + let effect = execute(session, command, ¶ms).unwrap()["effect"].as_u64().unwrap(); + execute(session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(LayerId(effect)); +} + +/// The screens with lists in Properties, each named for the failure messages +fn screens() -> Vec<(&'static str, Harness<'static, TextureCraftApp>)> { + vec![ + ("paint tool", screen(|_| {})), + ( + "fill layer", + screen(|session| { + execute(session, "layer.add.fill", &json!({})).unwrap(); + }), + ), + ( + "folder", + screen(|session| { + let folder = execute(session, "layer.add.group", &json!({})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": folder, "target": "content"})).unwrap(); + }), + ), + ("mask fill", screen(|session| with_effect(session, "mask", "effect.add.fill", json!({})))), + ("mask paint", screen(|session| with_effect(session, "mask", "effect.add.paint", json!({})))), + ("colour selection", screen(|session| with_effect(session, "mask", "effect.add.colorSelection", json!({})))), + ("compare mask", screen(|session| with_effect(session, "mask", "effect.add.compare", json!({})))), + ("levels", screen(|session| with_effect(session, "content", "effect.add.levels", json!({})))), + ("generator", screen(|session| with_effect(session, "mask", "effect.add.generator", json!({"generator": "curvature"})))), + ("blur filter", screen(|session| with_effect(session, "content", "effect.add.filter", json!({"filter": "blur"})))), + ("gradient filter", screen(|session| with_effect(session, "content", "effect.add.filter", json!({"filter": "gradient"})))), + ("warp filter", screen(|session| with_effect(session, "mask", "effect.add.filter", json!({"filter": "warp"})))), + ] +} + +/// The lists right of the view (the docked panels), top to bottom, each as its rect and what it shows +fn lists(harness: &Harness<'_, TextureCraftApp>) -> Vec<(Rect, String)> { + let view = harness.state().viewport_rect; + let window = Rect::from_min_size(Pos2::ZERO, PROPERTIES_WINDOW); + let mut lists: Vec<(Rect, String)> = harness + .query_all_by_role(Role::ComboBox) + .filter(|node| node.rect().left() >= view.right() && window.contains_rect(node.rect())) + .map(|node| (node.rect(), format!("{:?} = {:?}", node.accesskit_node().label(), node.value()))) + .collect(); + lists.sort_by(|(a, _), (b, _)| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left()))); + lists +} + +/// A `button` press at `from` dragged by `by` in small moves, then released, with `modifiers` held +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, by: Vec2, button: PointerButton, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + harness.run_steps(DRAG_STEP_FRAMES); + for step in 1..=DRAG_MOVES { + harness.hover_at(from + by * (step as f32 / DRAG_MOVES as f32)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(SETTLE_FRAMES); +} + +/// One wheel notch at `at` +fn wheel(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, WHEEL_NOTCH), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + harness.run_steps(REDRAW_FRAMES); +} + +/// Whether one wheel notch at `at` zooms the camera +fn zooms(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) -> bool { + let distance = harness.state().session.camera.distance; + wheel(harness, at); + harness.state().session.camera.distance != distance +} + +/// Whether a middle drag from `from` pans the camera +fn pans(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2) -> bool { + let target = harness.state().session.camera.target; + drag(harness, from, GESTURE, PointerButton::Middle, Modifiers::NONE); + harness.state().session.camera.target != target +} + +/// Whether an Alt drag from `from` orbits the camera +fn orbits(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2) -> bool { + let yaw = harness.state().session.camera.yaw; + drag(harness, from, GESTURE, PointerButton::Primary, Modifiers::ALT); + harness.state().session.camera.yaw != yaw +} + +/// Where the gestures start in the view: clear of the lists, which open beside Properties +fn gesture_start(harness: &Harness<'_, TextureCraftApp>) -> Pos2 { + let view = harness.state().viewport_rect; + view.left_center() + vec2(view.width() * GESTURE_SHARE, 0.0) +} + +fn is_open(harness: &Harness<'_, TextureCraftApp>) -> bool { + egui::Popup::is_any_open(&harness.ctx) +} + +/// Opens the list at `button` with a click; false when it did not open +fn open(harness: &mut Harness<'_, TextureCraftApp>, button: Rect) -> bool { + click_at(harness, button.center()); + harness.run_steps(SETTLE_FRAMES); + is_open(harness) +} + +/// What goes wrong with the list at `button`, each a line naming it +fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &str) -> Vec { + let mut problems = Vec::new(); + let gesture_start = gesture_start(harness); + if !open(harness, button) { + return vec![format!("{name}: a click does not open it")]; + } + + if !zooms(harness, gesture_start) { + problems.push(format!("{name}: the wheel over the view does not zoom while it is open")); + } + + // Each gesture starts with the list open, whatever the one before did to it + if !is_open(harness) && !open(harness, button) { + return [problems, vec![format!("{name}: it does not open again after the wheel")]].concat(); + } + if !pans(harness, gesture_start) { + problems.push(format!("{name}: a middle drag in the view does not pan while it is open")); + } + + // A middle drag may close it, as a click outside does; the orbit is checked with it open again + if !is_open(harness) && !open(harness, button) { + return [problems, vec![format!("{name}: a second click does not open it")]].concat(); + } + if !orbits(harness, gesture_start) { + problems.push(format!("{name}: an Alt drag in the view does not orbit while it is open")); + } + + if !is_open(harness) && !open(harness, button) { + return [problems, vec![format!("{name}: it does not open again")]].concat(); + } + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + if is_open(harness) { + problems.push(format!("{name}: Escape does not close it")); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + } + + if open(harness, button) { + click_at(harness, gesture_start); + if is_open(harness) { + problems.push(format!("{name}: a click in the view does not close it")); + } + } + + if !is_open(harness) && open(harness, button) { + drag(harness, gesture_start, GESTURE, PointerButton::Primary, Modifiers::NONE); + if is_open(harness) { + problems.push(format!("{name}: a stroke on the model does not close it")); + } + } + problems +} + +#[test] +fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_a_stroke_outside() { + let mut problems = Vec::new(); + for (screen, mut harness) in screens() { + let count = lists(&harness).len(); + assert!(count > 0, "{screen}: lists show"); + for index in 0..count { + // Looked up again each time: a closed list or a stroke may move the rows below + let Some((button, shown)) = lists(&harness).get(index).cloned() else { + problems.push(format!("{screen}: list {index} of {count} is gone")); + continue; + }; + + problems.extend(check_list(&mut harness, button, &format!("{screen}: {shown}"))); + for _ in 0..ESCAPES_TO_CLEAR { + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + } + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); +} + +#[test] +fn the_colour_picker_window_and_the_symmetry_settings_leave_the_view_its_wheel_middle_drag_and_alt_orbit() { + let (mut harness, _) = fill_app(json!({"color": [0.2, 0.2, 0.2]}), None, Some("Material"), PROPERTIES_WINDOW); + click_node(&mut harness, Role::Button, "Base color"); + let start = gesture_start(&harness); + let picker_open = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(); + assert!(picker_open(&harness), "the colour bar opens its picker"); + assert!(zooms(&mut harness, start), "the wheel over the view zooms with the picker open"); + assert!(pans(&mut harness, start), "a middle drag pans with the picker open"); + assert!(orbits(&mut harness, start), "an Alt drag orbits with the picker open"); + assert!(picker_open(&harness), "the picker stays open through the camera moves, as a window beside the panel"); + + let mut harness = screen(|_| {}); + + // The paint controls overflow the bar at this width; its arrow brings the Symmetry buttons into view + harness.get_by_label("Scroll right").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(SETTLE_FRAMES); + let settings_open = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_label("Radial symmetry").is_some(); + assert!(settings_open(&harness), "the settings open"); + let start = gesture_start(&harness); + assert!(zooms(&mut harness, start), "the wheel over the view zooms with the symmetry settings open"); + assert!(settings_open(&harness), "the wheel leaves the settings open"); + assert!(pans(&mut harness, start), "a middle drag pans with the symmetry settings open"); + assert!(orbits(&mut harness, start), "an Alt drag orbits with the symmetry settings open"); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 9d45eed0..f733e8a7 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -2208,6 +2208,68 @@ fn layer_toolbar_snapshots() { } } +/// Screen 12: the Filter effect: empty, Blur on a mask, Slope Blur on the content (pills, Seed, Intensity's chip), its Divider list open, Restore defaults hovered +#[test] +#[ignore] +fn filter_card_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let add = |session: &mut texturecraft_engine::Session, params: serde_json::Value| { + LayerId(execute(session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let empty = add(&mut session, json!({"layer": layer, "target": "content", "filter": "none"})); + let blur = add(&mut session, json!({"layer": layer, "target": "mask", "filter": "blur"})); + let slope = add(&mut session, json!({"layer": layer, "target": "content", "filter": "slopeBlur", "seed": 12})); + execute(&mut session, "effect.set", &json!({"effect": slope.0, "divider": 10, "channels": {"metallic": false, "normal": false}})).unwrap(); + let invert = add(&mut session, json!({"layer": layer, "target": "content", "filter": "invert"})); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(empty); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + + // Add filter opens the picker; a filter selected from its row does not + save(&mut harness, &output_dir, "filter-empty"); + harness.state_mut().session.target = StackTarget::Effect(blur); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-blur-mask"); + harness.state_mut().session.target = StackTarget::Effect(invert); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-invert-content"); + harness.state_mut().session.target = StackTarget::Effect(slope); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-slope"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-slope-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + harness.get_by_role_and_label(egui::Role::ComboBox, "Blur").click(); + harness.run_steps(3); + let option = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Max").rect().center(); + harness.hover_at(option); + save(&mut harness, &output_dir, "filter-slope-blending-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + let reset = harness.get_by_role_and_label(egui::Role::Button, "Restore defaults").rect().center(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "filter-reset-hovered"); + harness.get_by_role_and_label(egui::Role::ComboBox, "÷10").click(); + harness.run_steps(3); + let option = harness.get_by_role_and_label(egui::Role::ListBoxOption, "÷100").rect().center(); + harness.hover_at(option); + save(&mut harness, &output_dir, "filter-divider-open"); +} + #[test] #[ignore = "writes the material picker (Material mode) to TC_UI_SNAPSHOTS; run with --ignored"] /// A whole-material fill's card opens the material picker: grouped under its categories, Copper chosen and Brass hovered, then a search @@ -2250,6 +2312,585 @@ fn material_picker_snapshots() { } } +#[test] +#[ignore = "writes the colour filters (screen 18) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 18: Color Balance, Color Correct, HSL Perceptive and Contrast Luminosity with the mock's values, one knob hovered +fn colour_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let mut add = |params: serde_json::Value| { + let mut params = params; + params["layer"] = layer.clone(); + params["target"] = json!("content"); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let effects = [ + ("colour-balance", add(json!({"filter": "colorBalance", "highlights": [0.0, 0.0, -0.2], "midtones": [0.25, 0.0, 0.0], "shadows": [0.0, -0.1, 0.0]}))), + ("colour-correct", add(json!({"filter": "colorCorrect", "shadows": [0.0, 0.1, 0.5], "midtones": [0.2, 0.0, 0.6], "highlights": [0.0, -0.1, 0.5]}))), + ("hsl", add(json!({"filter": "hsl", "hue": 0.12, "saturation": 0.0, "lightness": -0.1}))), + ("contrast-luminosity", add(json!({"filter": "contrastLuminosity", "contrast": 0.3}))), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(4); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(effects[2].1); + harness.run_steps(4); + let hue = harness.get_by_role_and_label(egui::Role::Slider, "Hue").rect(); + harness.hover_at(egui::pos2(hue.left() + hue.width() * 0.62, hue.center().y)); + save(&mut harness, &output_dir, "filter-hsl-hovered"); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-colour-balance-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the gradient filters (screen 19) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 19: Gradient, Gradient Curve (and its Preset list open, Bump hovered) and Gradient Dynamic +fn gradient_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |params: serde_json::Value| { + let mut params = params; + params["layer"] = layer.clone(); + params["target"] = json!("mask"); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let stops = json!([[0.009, 0.008, 0.013], [0.55, 0.105, 0.021], [0.87, 0.67, 0.35]]); + let effects = [ + ("gradient", add(json!({"filter": "gradientMap", "colors": stops, "positions": [0.0, 0.45, 1.0]}))), + ("gradient-curve", add(json!({"filter": "gradientCurve"}))), + ("gradient-dynamic", add(json!({"filter": "gradientDynamic", "color": [0.578, 0.578, 0.578]}))), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(4); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(effects[1].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Round").click(); + harness.run_steps(3); + let bump = harness.get_by_label("Bump").rect(); + harness.hover_at(bump.center()); + save(&mut harness, &output_dir, "filter-gradient-curve-presets"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + let marker = harness.get_all_by_role_and_label(egui::Role::Slider, "Color 2").next().unwrap().rect(); + harness.hover_at(marker.center()); + save(&mut harness, &output_dir, "filter-gradient-marker-hovered"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-gradient-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the light and shadow filters (screen 20) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 20: Glow (and its Width hovered) and Drop Shadow +fn light_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let effects = [("glow", add("glow")), ("drop-shadow", add("dropShadow"))]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let distance = harness.get_by_role_and_label(egui::Role::Slider, "Distance").rect(); + harness.hover_at(distance.center()); + save(&mut harness, &output_dir, "filter-drop-shadow-hovered"); + harness.get_by_role_and_label(egui::Role::Button, "Color").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-drop-shadow-color-picker"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-glow-{theme}")); + } + } + + // Baked Lighting Stylized on content, in a window tall enough for all its cards, then its Output list open + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let params = json!({"layer": layer.clone(), "target": "content", "filter": "bakedLighting"}); + let lighting = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + let params = json!({"layer": layer.clone(), "target": "content", "filter": "bakedLightingEnvironment"}); + let environment = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(lighting); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2600.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(8); + save(&mut harness, &output_dir, "filter-baked-lighting-stylized"); + let output = harness.get_by_role_and_label(egui::Role::ComboBox, "Diffuse + Specular").rect(); + harness.hover_at(output.center()); + harness.get_by_role_and_label(egui::Role::ComboBox, "Diffuse + Specular").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-baked-lighting-stylized-output-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-baked-lighting-stylized-{theme}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + + // Baked Lighting Environment, then hovering its stacked Specular Occlusion Intensity + harness.state_mut().session.target = StackTarget::Effect(environment); + harness.run_steps(8); + save(&mut harness, &output_dir, "filter-baked-lighting-environment"); + let specular = harness.get_by_role_and_label(egui::Role::Slider, "Specular Occlusion Intensity").rect(); + harness.hover_at(specular.center()); + save(&mut harness, &output_dir, "filter-baked-lighting-environment-hovered"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("filter-baked-lighting-environment-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the shape filters (screen 21) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 21: Mirror in each mode (its Mode list open), Mask Outline, Threshold (its Mode hovered) +fn shape_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str, settings: serde_json::Value| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + let effect = execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap(); + let mut settings = settings; + settings["effect"] = json!(effect); + execute(&mut session, "effect.set", &settings).unwrap(); + LayerId(effect) + }; + let effects = [ + ("mirror-axis-x", add("mirror", json!({}))), + ("mirror-axis-y", add("mirror", json!({"mode": "axisY"}))), + ("mirror-corner", add("mirror", json!({"mode": "corner"}))), + ("mask-outline", add("maskOutline", json!({}))), + ("bevel", add("bevel", json!({}))), + ("bevel-smooth", add("bevelSmooth", json!({}))), + ("directional-distance", add("directionalDistance", json!({}))), + ("threshold", add("threshold", json!({}))), + ("warp", add("warp", json!({}))), + ("warp-directional", add("warp", json!({"warpMode": "directional"}))), + ("warp-multi-directional", add("warp", json!({"warpMode": "multiDirectional"}))), + ("transform", add("transform", json!({"scaling": [2.0, 2.0], "offset": [0.25, 0.0], "rotation": 30.0}))), + ("transform-plain", add("transform", json!({"repeatMode": "none", "scaling": [1.5, 1.5], "tileSafeRotation": false, "rotation": 20.0}))), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let shown = |name: &str| effects.iter().find(|(shown, _)| *shown == name).map(|(_, effect)| *effect).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("threshold")); + harness.run_steps(4); + let mode = harness.get_by_role_and_label(egui::Role::RadioButton, "≥").rect(); + harness.hover_at(mode.center()); + save(&mut harness, &output_dir, "filter-threshold-hovered"); + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Mirror Axis X").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-mirror-mode-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + // Warp's mode list (under the filter card, also named Warp) and Multi Directional Warp's Blending Mode list, open + harness.state_mut().session.target = StackTarget::Effect(shown("warp")); + harness.run_steps(4); + let lists = harness.query_all_by_role_and_label(egui::Role::ComboBox, "Warp"); + lists.max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-warp-mode-list"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(shown("warp-multi-directional")); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Average").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-warp-blending-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + // Transform's Flip mode and Repeat mode lists, open with a choice hovered + harness.state_mut().session.target = StackTarget::Effect(shown("transform")); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "None").click(); + harness.run_steps(4); + harness.hover_at(harness.get_by_label("Vertically").rect().center()); + harness.run_steps(2); + save(&mut harness, &output_dir, "filter-transform-flip-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Horizontally & Vertically").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-transform-repeat-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + for name in ["mirror-axis-x", "mask-outline", "bevel", "bevel-smooth", "warp-multi-directional", "transform"] { + harness.state_mut().session.target = StackTarget::Effect(shown(name)); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}-{theme}")); + } + } + } +} + +#[test] +#[ignore = "writes the simple filters (screen 23) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 23: Clamp, Smoothstep, Invert, Height Adjust, Histogram Scan, Histogram Shift, Sharpen and Posterize, one hovered switch +fn simple_filter_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let effects = [ + "clamp", + "smoothstep", + "invert", + "heightAdjust", + "histogramScan", + "histogramShift", + "sharpen", + "posterize", + "pixelate", + "fxaa", + "blur", + "blurDirectional", + "highPass", + "grayscale", + "anisotropicKuwahara", + ] + .map(|id| (id, add(id))); + + // PBR Validate goes on the layer content (its Color and Metal pills) + let params = json!({"layer": layer.clone(), "target": "content", "filter": "pbrValidate"}); + let pbr = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + + // Height To Normal too (its Normal pill), once with world units and once without + let params = json!({"layer": layer.clone(), "target": "content", "filter": "heightToNormal"}); + let normals = [(); 2].map(|_| LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap())); + execute(&mut session, "effect.set", &json!({"effect": normals[1].0, "useWorldUnits": false})).unwrap(); + + // Color Match too (its Color pill): a new one, and one reading its Input and Image Input + let params = json!({"layer": layer.clone(), "target": "content", "filter": "colorMatch"}); + let matches = [(); 2].map(|_| LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap())); + execute(&mut session, "effect.set", &json!({"effect": matches[1].0, "sourceColorMode": "input", "targetColorMode": "imageInput"})).unwrap(); + + // Replace Color too (its two colour bars) + let params = json!({"layer": layer.clone(), "target": "content", "filter": "replaceColor"}); + let replace = LayerId(execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let shown = |name: &str| effects.iter().find(|(shown, _)| *shown == name).map(|(_, effect)| *effect).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("posterize")); + harness.run_steps(4); + let alpha = harness.get_by_role_and_label(egui::Role::CheckBox, "Apply to Alpha").rect(); + harness.hover_at(alpha.center()); + save(&mut harness, &output_dir, "filter-posterize-hovered"); + harness.state_mut().session.target = StackTarget::Effect(shown("highPass")); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Working space / Mask").click(); + harness.run_steps(2); + harness.get_by_label("sRGB (from ACEScg)").hover(); + save(&mut harness, &output_dir, "filter-highPass-open"); + harness.key_press(egui::Key::Escape); + let custom = json!({"effect": shown("grayscale").0, "channelInput": "customInput"}); + execute(&mut harness.state_mut().session, "effect.set", &custom).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("grayscale")); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-grayscale-custom"); + let custom = json!({"effect": shown("anisotropicKuwahara").0, "extractDirection": "customInput"}); + execute(&mut harness.state_mut().session, "effect.set", &custom).unwrap(); + harness.state_mut().session.target = StackTarget::Effect(shown("anisotropicKuwahara")); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-anisotropicKuwahara-custom"); + harness.state_mut().session.target = StackTarget::Effect(pbr); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-pbrValidate"); + let metal = harness.get_by_role_and_label(egui::Role::RadioButton, "70-100% Reflective").rect(); + harness.hover_at(metal.center()); + save(&mut harness, &output_dir, "filter-pbrValidate-hovered"); + for (effect, name) in normals.into_iter().zip(["heightToNormal", "heightToNormal-intensity"]) { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + let world = harness.get_by_role_and_label(egui::Role::CheckBox, "Use World Units").rect(); + harness.hover_at(world.center()); + save(&mut harness, &output_dir, "filter-heightToNormal-hovered"); + for (effect, name) in matches.into_iter().zip(["colorMatch", "colorMatch-inputs"]) { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(matches[0]); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Average").click(); + harness.run_steps(2); + harness.get_by_label("Input").hover(); + save(&mut harness, &output_dir, "filter-colorMatch-open"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.state_mut().session.target = StackTarget::Effect(replace); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-replaceColor"); + harness.get_by_role_and_label(egui::Role::Button, "Replacement color").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "filter-replaceColor-picker"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + for name in ["heightAdjust", "histogramScan", "pixelate", "blurDirectional", "highPass", "grayscale", "anisotropicKuwahara"] { + harness.state_mut().session.target = StackTarget::Effect(shown(name)); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}-{theme}")); + } + harness.state_mut().session.target = StackTarget::Effect(pbr); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-pbrValidate-{theme}")); + harness.state_mut().session.target = StackTarget::Effect(normals[0]); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-heightToNormal-{theme}")); + harness.state_mut().session.target = StackTarget::Effect(matches[0]); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-colorMatch-{theme}")); + } + } +} + +#[test] +#[ignore = "writes the filter image inputs (screen 22) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 22: Bevel Smooth's Distance Map uniform, read from an anchor point and its picker open; Warp's Custom Noise from a pattern +fn image_input_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"name": "Cavity Dirt mask"})).unwrap()["effect"].clone(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": layer.clone()})).unwrap(); + let mut add = |filter: &str, settings: serde_json::Value, input: serde_json::Value| { + let params = json!({"layer": layer.clone(), "target": "mask", "filter": filter}); + let effect = execute(&mut session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap(); + let mut settings = settings; + settings["effect"] = json!(effect); + execute(&mut session, "effect.set", &settings).unwrap(); + if !input.is_null() { + let mut input = input; + input["effect"] = json!(effect); + execute(&mut session, "layer.fill.set", &input).unwrap(); + } + LayerId(effect) + }; + let effects = [ + ("bevel-smooth-uniform", add("bevelSmooth", json!({}), serde_json::Value::Null)), + ("bevel-smooth-anchor", add("bevelSmooth", json!({}), json!({"input": "distanceMap", "anchor": anchor}))), + ("warp-custom-noise", add("warp", json!({"sourceMode": "customNoise"}), json!({"input": "customNoise", "procedural": "clouds"}))), + ("blur-changed", add("blur", json!({"radius": 12.0, "wrap": true}), serde_json::Value::Null)), + ]; + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(effects[0].1); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}")); + } + harness.state_mut().session.target = StackTarget::Effect(effects[0].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::ComboBox, "Distance Map").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-distance-map-picker"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + // Blur with Attributes open, then its Parameters reset hovered (Restore defaults named over it) + harness.state_mut().session.target = StackTarget::Effect(effects[3].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "filter-attributes-open"); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(4); + let reset = harness.get_by_role_and_label(egui::Role::Button, "Restore defaults").rect().center(); + harness.set_render_cursor(false); + harness.hover_at(reset); + harness.run_steps(60); + save(&mut harness, &output_dir, "filter-restore-defaults-hover"); + harness.set_render_cursor(true); + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(4); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.state_mut().session.target = StackTarget::Effect(effects[3].1); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-attributes-open-{theme}")); + harness.get_by_role_and_label(egui::Role::Button, "Attributes").click(); + harness.run_steps(4); + for (name, effect) in effects { + harness.state_mut().session.target = StackTarget::Effect(effect); + harness.run_steps(6); + save(&mut harness, &output_dir, &format!("filter-{name}-{theme}")); + } + } + } +} + +#[test] +#[ignore = "writes the filter picker states (screen 13) to TC_UI_SNAPSHOTS; run with --ignored"] +/// Screen 13: the filter picker opened from an empty card, swapping (current outlined), searching, and in a mask +fn filter_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::core::LayerId; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let add = |session: &mut texturecraft_engine::Session, params: serde_json::Value| { + LayerId(execute(session, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) + }; + let empty = add(&mut session, json!({"layer": layer, "target": "content", "filter": "none"})); + let slope = add(&mut session, json!({"layer": layer, "target": "content", "filter": "slopeBlur"})); + execute(&mut session, "effect.set", &json!({"effect": slope.0, "channels": {"metallic": false, "normal": false}})).unwrap(); + let masked = add(&mut session, json!({"layer": layer, "target": "mask", "filter": "none"})); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Effect(empty); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + let open = |harness: &mut Harness<'_, TextureCraftApp>, card: &str, hover: &str| { + harness.get_by_role_and_label(egui::Role::ComboBox, card).click(); + settle_thumbnails(harness); + let tile = harness.get_by_role_and_label(egui::Role::ListBoxOption, hover).rect().center(); + harness.hover_at(tile); + }; + open(&mut harness, "Filter", "Blur"); + save(&mut harness, &output_dir, "filter-picker-new"); + harness.event(egui::Event::Text("blur".into())); + harness.hover_at(egui::pos2(1.0, 1.0)); + save(&mut harness, &output_dir, "filter-picker-search"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(slope); + harness.run_steps(4); + open(&mut harness, "Blur Slope", "Clamp"); + save(&mut harness, &output_dir, "filter-picker-swapping"); + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = StackTarget::Effect(masked); + harness.run_steps(4); + open(&mut harness, "Filter", "Bevel"); + save(&mut harness, &output_dir, "filter-picker-mask"); +} + /// The Properties panel at its minimum width (the right column dragged as narrow as it goes), on the Fill tab's widest row (3D projection settings) and on a filter #[test] #[ignore] @@ -2280,6 +2921,7 @@ fn properties_min_width_snapshot() { } harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "hsl"})).unwrap(); + execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "colorMatch"})).unwrap(); save(&mut harness, &output_dir, "properties-min-width-filter"); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9b88b0f8..bc2cc695 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -589,13 +589,16 @@ with `material.apply` instead. The fill remembers the material (`Fill.material`, - `effect.blending.modeToEveryChannel`, `opacityToEveryChannel` and `bothToEveryChannel {effect?, channel?}` give every channel of a content effect one channel's blend mode, opacity or both; `effect.blending.copy` and `effect.blending.paste {effect?}` carry every channel's blending between effects (a mask effect takes - the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending. + the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending and + `effect.set {effect, channels: {roughness: false}}` switches a content effect's channels on or off. - `mask.add.bitmap {layer?, image | alpha, projection?}` adds a mask fill reading an image's gray; `effect.set {effect, idMap: image resource | null}` gives a colour selection its own ID map in place of the baked one; `tool.material {maskImage: image resource | null}` paints an image's gray into masks. - `effect.add.colorSelection {layer?, color?, tolerance?}` and `mask.add.heightCombination {layer?}` add a colour selection or a compare mask (this layer's height against the layers below) to a layer's mask, making the mask first when it has none; both return `{effect}`. +- `effect.filter.restoreDefaults {effect?}` puts a filter's parameters back to its defaults (name, + channels and blending stay) and returns `{changed}`. - `layer.fill.resetProjection {layer? | effect?}` puts the Fill section back to a new fill's (same projection kind; a placed frame, the symmetry and the sources stay); `layer.fill.resetFrame` puts a warp's frame back around the mesh with its corners unpulled. Each is one undo step, or none when From 616601d4a99998bb788885f9ac75666a6a6294f9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:49 +0000 Subject: [PATCH 040/153] Temporary: filter effects keep main's filter panel until part 5, and effects read their blend through main's lookups --- crates/compose/src/eval.rs | 20 ++++---- crates/compose/src/lib.rs | 1 - crates/compose/tests/cache_and_instances.rs | 7 ++- crates/core/src/layer.rs | 8 +++- crates/core/src/project.rs | 1 + crates/engine/src/fill_material_cmds.rs | 2 - crates/engine/src/fill_reset_cmds.rs | 1 - crates/engine/src/filter_lib.rs | 2 +- crates/engine/src/folder_cmds.rs | 1 + crates/engine/src/layer_cmds.rs | 5 +- crates/engine/src/mask_cmds.rs | 3 +- crates/engine/src/materials.rs | 1 - crates/engine/src/session.rs | 3 ++ crates/engine/src/warp_cmds.rs | 1 - crates/engine/tests/it/fill_projections.rs | 1 - crates/engine/tests/it/filter_support.rs | 2 +- crates/engine/tests/it/folder_contents.rs | 1 + crates/engine/tests/it/resources_used.rs | 6 +++ crates/engine/tests/session.rs | 2 +- crates/render/src/ibl.rs | 2 +- crates/ui-egui/src/dock.rs | 48 +------------------ crates/ui-egui/src/fill_material_panel.rs | 10 +--- crates/ui-egui/src/filter_slot.rs | 8 ---- crates/ui-egui/src/layer_toolbar.rs | 2 + crates/ui-egui/src/material_orb.rs | 8 ++-- crates/ui-egui/src/orb_environment.rs | 2 - crates/ui-egui/src/property_sheet/row.rs | 6 +-- crates/ui-egui/src/property_sheet/slot.rs | 9 ---- crates/ui-egui/src/property_sheet/tests.rs | 2 +- crates/ui-egui/src/round_gizmo.rs | 1 - crates/ui-egui/src/slot_thumbnail.rs | 1 - crates/ui-egui/src/source_slot.rs | 7 ++- crates/ui-egui/tests/it/empty_start.rs | 2 - crates/ui-egui/tests/it/fill_channel_image.rs | 6 --- crates/ui-egui/tests/it/filter_picker.rs | 4 +- .../ui-egui/tests/it/tile_generator_panel.rs | 1 - crates/ui-egui/tests/ui_snapshots.rs | 2 +- 37 files changed, 56 insertions(+), 133 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52305968..85827ada 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -11,9 +11,9 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, ShapeCrop, Source, - TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, + Filtering, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, + ShapeCrop, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -752,7 +752,7 @@ fn filter_region( }; let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); - let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let opacity = filter_effect.map(|effect| effect.blend_of(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); // Generator stages keep their ramp beside the mask stack below @@ -1155,7 +1155,6 @@ 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: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { fn effect_plans<'a>( inp: &Inputs<'a>, effects: &'a [Effect], @@ -1182,6 +1181,7 @@ fn effect_plans<'a>( } _ => (None, false), }; + let blend = effect.blend_of(channel); EffectPlan { id: effect.id, kind: offset_effect(&effect.kind, around), @@ -1242,7 +1242,6 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann img.resampled_tile(w, h, tx, ty, &empty).map(Cow::Owned) } -fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { /// The plan of layer `id`'s `mask` for tile (tx, ty), its fills under the Scale and Rotation `around` of the folders holding the layer fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>, around: ContentsOffset) -> Option> { if !mask.enabled { @@ -1375,7 +1374,6 @@ fn plan_content<'a>( LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => { let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); - Content::Fill { fill: Box::new(Cow::Borrowed(f)), depth, covers_all } Content::Fill { fill: Box::new(offset_fill(f, around)), depth, covers_all } } LayerKind::Group { children, contents, .. } => { @@ -1512,7 +1510,7 @@ impl<'t> Tape<'t> { impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), tape: Tape::Off, copy: None } + Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, tape: Tape::Off, copy: None } } /// Run `f` with `tape` as this texel's tape. @@ -2400,7 +2398,6 @@ impl<'a, 'b> Texel<'a, 'b> { } None => (value, coverage), }, - EffectKind::Levels(levels) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), EffectKind::Levels(levels) => match Channel::ALL.get(chan_plan.ch) { Some(&channel) if levels.remaps(channel) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), _ => (value, coverage), @@ -3265,14 +3262,12 @@ pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option< } let reads_stack = found.kind.reads_stack(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); - let probe = evaluation_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); let empty = || [EffectHistogram::new(bins, false), EffectHistogram::new(bins, false)]; let [left_counts, right_counts] = tiles .par_iter() .map(|&(tx, ty)| { - own = evaluation_fields(&cut_inp, &channels, &[(tx, ty)]); let mut own = None; let fields = histogram_tile_fields(shared.as_ref(), &mut own, &cut_inp, &channels, (tx, ty)); let mut sides = empty(); @@ -3387,7 +3382,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti #[cfg(test)] mod tests { use super::*; - use texturecraft_core::{ChannelBlend, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; + use texturecraft_core::{ChannelBlend, CompareOp, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; use texturecraft_geom::primitives; struct Fixture { @@ -4442,6 +4437,7 @@ soft {soft:?}" }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(f.project.alloc_id(), compare)); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0 }))); f.project.layer_mut(top).unwrap().mask = Some(mask); let color = run(&f, None).value(Channel::BaseColor, 30, 30); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index c40ce2f7..c4fb958c 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -45,7 +45,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use effect_histogram::EffectHistogram; pub use eval::{ - BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 57cb0a1c..3b69ec6a 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -8,8 +8,8 @@ use texturecraft_compose::{ BelowCache, Composite, Inputs, MaskGray, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, }; use texturecraft_core::{ - BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, - Procedural, ProceduralKind, Project, Projection, Source, TextureSet, + BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, + LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use texturecraft_texel::{TILE, TileImage, to_u16}; @@ -954,6 +954,7 @@ fn flat_image(value: f32) -> std::sync::Arc { } #[test] +fn id_map_image_changes_invalidate_stack_key() { let mut fixture = fixture(); heavy_stack(&mut fixture); let bottom_layer = fixture.project.texture_sets[0].stack[0]; @@ -967,5 +968,7 @@ fn flat_image(value: f32) -> std::sync::Arc { images.insert("id".into(), flat_image(0.1)); let original = stack_key(&fixture, &images); + images.insert("id".into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache"); } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 56520585..0f4fc5ab 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, DepthCulling, Projector, ShapeCrop, lum}; +use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, CompareSource, ContentsOffset, DepthCulling, Projector, RandomizedSeed, ShapeCrop, lum}; mod curvature_detail; mod curvature_mode; @@ -1176,6 +1176,7 @@ pub enum Filter { }, } +/// Whether a switch is on, its default where it defaults to on (not saved then) fn is_true(on: &bool) -> bool { *on } @@ -1645,6 +1646,7 @@ impl Layer { LayerKind::Fill(fill) => fill.sources.values().any(|source| source.reads_anchor(None)), _ => false, }; + fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.kind.reads(None)) } /// Whether the layer's result depends on the stack below it: it reads an anchor point, or its mask compares channels of the stack @@ -1669,6 +1671,7 @@ pub struct Effect { impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { // Generators and fills that build a mask usually add on top of the background + Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0, channel_blends: BTreeMap::new() } } /// How the effect blends on `channel` of its layer's content, or on its mask (`None`) @@ -1713,9 +1716,12 @@ mod tests { } #[test] + fn a_colour_selection_id_map_is_reported_as_used() { let mut selection = crate::ColorSelection::new(Vec::new(), 0.0); selection.id_map = Some("id.png".into()); + let effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); + assert_eq!(effect.kind.images_read().collect::>(), vec!["id.png"]); } #[test] diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 794a5915..79d6c0d5 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -652,6 +652,7 @@ impl Project { out.push((layer.id, None)); } let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()); + out.extend(effects.filter(|e| e.kind.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); } out } diff --git a/crates/engine/src/fill_material_cmds.rs b/crates/engine/src/fill_material_cmds.rs index c4141934..2b82e437 100644 --- a/crates/engine/src/fill_material_cmds.rs +++ b/crates/engine/src/fill_material_cmds.rs @@ -45,7 +45,6 @@ fn set_material(s: &mut Session, p: &Value) -> Result { match target { // A fill effect changes a channel while it has a source: its channels stay on, at their defaults FillTarget::Effect(_) => edited.sources.iter_mut().for_each(|(channel, source)| *source = Source::uniform_of(*channel)), - FillTarget::Layer(_) => edited.sources.clear(), FillTarget::Layer(_) | FillTarget::Mask(_) => edited.sources.clear(), } Ok(()) @@ -126,7 +125,6 @@ fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMat fn target_set(s: &Session, target: FillTarget) -> Result { let owner = match target { FillTarget::Layer(id) => id, - FillTarget::Effect(id) => s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?, FillTarget::Effect(id) | FillTarget::Mask(id) => { s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))? } diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index 5c1d4c6d..236cd79a 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -13,7 +13,6 @@ pub fn specs() -> Vec { "Reset fill settings", [], None, - "{layer? | effect?: content fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", "{layer? | effect?: content or mask fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", has_layer, reset_projection diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 2430b0dd..c424f839 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -131,7 +131,7 @@ pub fn build(id: &str, p: &Value) -> Result { "bakedLighting" => Filter::BakedLighting { azimuth: 45.0, elevation: 45.0, light: 0.8, ambient: 0.4, occlusion: 1.0 }, "levels" => { let mut l = Levels::default(); - crate::mask_cmds::levels_from(p, &mut l); + crate::mask_cmds::levels_from(cmd, p, &mut l)?; return Ok(EffectKind::Levels(l)); } finish => return mat_finish(finish).map(EffectKind::Material).ok_or_else(|| bad(cmd, format!("unknown filter `{id}`"))), diff --git a/crates/engine/src/folder_cmds.rs b/crates/engine/src/folder_cmds.rs index 599f2c5e..ab811c86 100644 --- a/crates/engine/src/folder_cmds.rs +++ b/crates/engine/src/folder_cmds.rs @@ -224,6 +224,7 @@ fn seed_count(layer: &Layer) -> usize { .map(|effect| match &effect.kind { EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })), EffectKind::Material(fill) => fill_seeds(fill), + EffectKind::Generator(_) | EffectKind::Filter(Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. }) => 1, _ => 0, }) .sum(); diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index dbdac206..6dec1d24 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -6,7 +6,6 @@ use texturecraft_core::{ Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; -use texturecraft_paint::alphas; use texturecraft_paint::alphas::{self, LibraryAlpha}; use crate::commands::{ @@ -122,7 +121,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -131,7 +130,6 @@ pub fn specs() -> Vec { "Set fill projection", [], None, - "{layer? | effect?: content fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", "{layer? | effect?: content or mask fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", has_layer, fill_projection @@ -524,7 +522,6 @@ pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result match s.doc.project.effect(effect).map(|(_, found)| &found.kind) { Some(EffectKind::Material(_)) => Ok(FillTarget::Effect(effect)), - _ => Err(bad(cmd, format!("{} is not a content fill effect", effect.0))), Some(EffectKind::Fill { .. }) => Ok(FillTarget::Mask(effect)), _ => Err(bad(cmd, format!("{} is not a fill effect", effect.0))), }, diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 44a81ea7..74b1dfda 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,7 +2,6 @@ use serde_json::{Value, json}; use texturecraft_core::{ - MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, }; @@ -96,7 +95,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; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b] linear, ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 64d8d752..2ef21bda 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -841,7 +841,6 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { crate::layer_cmds::insert_selected(s, layer)? } else { let folder_id = s.doc.project.alloc_id(); - let mut folder = Layer::new(folder_id, material.label, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); let mut folder = Layer::new(folder_id, material.label, LayerKind::folder(), &channels); for blend in folder.channels.values_mut() { *blend = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 1a51a38a..75d0da63 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -775,6 +775,8 @@ impl Session { let added_resource_names: BTreeSet<&str> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); let is_added = |name: &str| added_resource_names.contains(name); + let uses_added_resource = + |texture_set_index: usize| { use texturecraft_core::{EffectKind, Fill}; let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); @@ -785,6 +787,7 @@ impl Session { project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| { + effect.kind.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill)) }) }) }) diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 11b4ceaa..1669c2e0 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -17,7 +17,6 @@ pub fn specs() -> Vec { "Reset frame", [], None, - "{layer? | effect?: content fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", "{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", has_layer, reset_frame diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 3c7e6267..a69d3317 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -514,7 +514,6 @@ fn an_axis_planar_reading_a_pattern_is_not_placed() { let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); let effect = added["effect"].as_u64().unwrap(); - execute(&mut s, "effect.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); execute(&mut s, "layer.fill.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); } diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index 020b202f..df495231 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -1,4 +1,4 @@ -//! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite +//! What the filter tests share: their sessions and reading the composite use texturecraft_engine::Session; use texturecraft_engine::core::Channel; diff --git a/crates/engine/tests/it/folder_contents.rs b/crates/engine/tests/it/folder_contents.rs index 0ad960ef..eb676eba 100644 --- a/crates/engine/tests/it/folder_contents.rs +++ b/crates/engine/tests/it/folder_contents.rs @@ -123,6 +123,7 @@ fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) { other => panic!("not a pattern: {other:?}"), }; let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind { + EffectKind::Filter(Filter::Warp { seed, .. }) => Some(seed), _ => None, }); (pattern(Channel::BaseColor), pattern(Channel::Roughness), warp.unwrap()) diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index 9d57d1d6..9540e368 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,3 +1,4 @@ +//! The images a project reads beyond fill sources: a colour selection's ID map, the mask brush and its paths use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, LayerId}; @@ -27,7 +28,10 @@ fn selecting_layer(session: &mut Session, id_map: &str) -> LayerId { } #[test] +fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_path_read() { let mut session = session(); + let [id_map, path, brush, unused] = ["id.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); + let layer = selecting_layer(&mut session, &id_map); // A path on the mask is painted with one image, then the brush moves on to another execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); @@ -41,8 +45,10 @@ fn selecting_layer(session: &mut Session, id_map: &str) -> LayerId { } #[test] +fn a_smart_material_carries_the_image_its_selection_reads() { let mut session = session(); let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); + let layer = selecting_layer(&mut session, &id_map); let bytes = session.smart_material_bytes(layer, "Parts").unwrap(); let mut other = self::session(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index be7a504a..23efa4d4 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -279,7 +279,7 @@ fn gray_png() -> Vec { /// Frame edits and frame and Fill section resets on the fills they act on (a planar, a warp and a decal mask) meet hostile values without panicking; a refused edit changes nothing and adds no undo step #[test] -fn panic_hunt_frames_and_transforms() { +fn panic_hunt_frames() { let mut s = session(); let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); let planar = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index 5c6b59db..e8a44942 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -156,7 +156,7 @@ impl EnvImage { let v = if v.is_finite() { v.clamp(0.0, 65_000.0) } else { 0.0 }; if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v } }; - let data = rgba.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect(); + let data = pixels.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect(); let mut img = EnvImage { width, height, data }; while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH { img = img.half(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 15e59218..e38c7749 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::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Source, + BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; @@ -19,7 +19,6 @@ use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_s use crate::past_end::PastEnd; use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; -use crate::source_choice::SourceChoice; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; @@ -1841,7 +1840,6 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: }); } -/// The tabs over the panel when it shows a fill layer's sections, which they jump between /// The tabs over the panel when it shows a fill layer's or a mask fill effect's sections, which they jump between pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 3]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { @@ -1899,9 +1897,6 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { } } (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), - (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { - (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => legacy_body(ui, |ui| instance_properties(app, ui, layer)), - (Some(layer), StackTarget::Mask) => legacy_body(ui, |ui| { (Some(layer), StackTarget::Content) if layer.is_group() => crate::folder_properties::folder_properties(app, ui, layer.id), (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => crate::instance_properties::instance_properties(app, ui, layer), (Some(layer), StackTarget::Mask) => { @@ -2003,8 +1998,6 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); 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(PREVIEW_STROKE_MIN_ALPHA))))); - let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); // A mask stroke shows the gray it lays down and no material let gray = match (content, &app.session.tool.mask_image) { @@ -3067,53 +3060,20 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe // Property sheets keep the panel's own edges; only the rows not yet laid out by one get the legacy margin match &effect.kind { EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), - EffectKind::Levels(levels) => legacy_body(ui, |ui| crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels)), EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); - let name = match source { - Source::Anchor { anchor, channel, .. } => { - let owner = project.effect(*anchor).and_then(|(owner, _)| project.layers.get(&owner)); - let read = if anchor_in_mask(app, *anchor) { "Mask" } else { channel.label() }; - format!("{} · {}", owner.map_or_else(|| tr("missing").to_string(), |layer| layer.name.clone()), tr(read)) let current = match source { Source::Anchor { anchor, channel, .. } => anchor_label(app, *anchor, *channel), Source::Uniform(_) => tr("Uniform value").to_string(), Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), - Source::Image { name, .. } => name.clone(), Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]), }; - // Main's Grayscale slot on the new picker: patterns, images and a uniform value, or the anchor points below - let (rect, source_response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::filter_slot::SLOT_HEIGHT), Sense::click()); - source_response.widget_info(|| egui::WidgetInfo { - current_text_value: Some(name.clone()), - ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, tr("Grayscale")) - let (ctx, popup) = (ui.ctx().clone(), ui.make_persistent_id(("fill_source_picker", id))); - if source_response.clicked() { - crate::resource_picker::toggle(&ctx, popup); - let highlighted = source_response.hovered() || egui::Popup::is_id_open(&ctx, popup); - crate::filter_slot::paint(ui, rect, (highlighted, source_response.has_focus()), None, (tr("Grayscale"), &name)); - let current = crate::fill_material_panel::source_choice(source); - let images = app.session.images.clone(); - let picked = crate::resource_picker::show(&source_response, popup, &mut app.thumbs, Some(¤t), current != SourceChoice::Uniform, |thumbs| { - let mut tabs = crate::fill_material_panel::source_tabs(thumbs, &ctx, &images, &anchors, Color32::from_gray(204)); - tabs.iter_mut().for_each(|tab| tab.groups.retain(|group| group.header != Some(tr("Alphas")))); - tabs - let anchor_channel = if let Source::Anchor { channel, .. } = source { *channel } else { Channel::Height }; - let params = match picked.filter(|choice| *choice != current) { - Some(SourceChoice::Procedural(kind)) => Some(json!({"effect": id, "procedural": kind.label()})), - Some(SourceChoice::Image(image)) => Some(json!({"effect": id, "image": image})), - Some(SourceChoice::Uniform) => Some(json!({"effect": id, "uniform": 1.0})), - Some(SourceChoice::Anchor(anchor)) => Some(json!({"effect": id, "anchor": anchor.0, "anchorChannel": anchor_channel.id()})), - Some(SourceChoice::Import) => { - None let source_response = combo(ui, tr("Source"), current, |ui| { if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { app.run("effect.set", json!({"effect": id, "value": 1.0})); } - Some(SourceChoice::Alpha(_)) | None => None, - if let Some(params) = params { if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) { app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); } @@ -3167,7 +3127,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe crate::fill_panel::fill_sheet(app, sheet, fill, &json!({"effect": id}), &enabled, layer.id); }); } - EffectKind::Anchor => legacy_body(ui, |ui| { EffectKind::Anchor => crate::anchor_properties::anchor_properties(app, ui, effect_id, &effect.name), EffectKind::Paint => legacy_body(ui, |ui| { let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { @@ -3206,8 +3165,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe } }), EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), - EffectKind::ColorSelection { colors, tolerance } => { - legacy_body(ui, |ui| crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance)) EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { let settings = crate::compare_settings::CompareSettings { @@ -3221,9 +3178,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe }; crate::compare_properties::compare_properties(app, ui, layer, effect_id, settings); } - other => legacy_body(ui, |ui| { - ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); - }), } } diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 4d4db43e..7efd7a14 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -178,7 +178,6 @@ pub(crate) fn source_line(app: &TextureCraftApp, source: &Source) -> String { } } -/// One source's card (a channel's): its slot (the row opens the source picker), then the source's own settings; `in_card`: only its slot row, inside the card open now /// One source's card (a channel's, a mask fill's grayscale or a filter's image input): its slot (the row opens the source picker), then the source's own settings; `in_card`: only its slot row, inside the card open now pub(crate) fn source_card( app: &mut TextureCraftApp, @@ -302,7 +301,6 @@ fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSl } /// The picker's choice `source` is: a library alpha's image is its alpha -pub(crate) fn source_choice(source: &Source) -> SourceChoice { fn source_choice(source: &Source) -> SourceChoice { match source { Source::Uniform(_) => SourceChoice::Uniform, @@ -313,13 +311,6 @@ fn source_choice(source: &Source) -> SourceChoice { } /// The source picker's tabs: Resources (Procedurals, Textures with Import... first, Alphas in their shelf groups, Uniform) and the stack's Anchor points -pub(crate) fn source_tabs( - thumbs: &mut Thumbs, - ctx: &egui::Context, - images: &ImageStore, - anchors: &[(LayerId, String)], - uniform: Color32, -) -> Vec> { fn source_tabs(thumbs: &mut Thumbs, ctx: &egui::Context, images: &ImageStore, anchors: &[(LayerId, String)], uniform: Color32) -> Vec> { let procedurals = ProceduralKind::ALL.into_iter().map(|kind| tile(SourceChoice::Procedural(kind), tr(kind.label()), None, TilePicture::Procedural(kind))).collect(); @@ -436,6 +427,7 @@ fn procedural_rows( let mut edit = scale_and_contrast(sheet, &mut edited); // A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes + let gray = matches!(slot_of, SourceSlot::Grayscale); if gray { edit = edit.or(balance_and_seed(sheet, &mut edited)); } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 1fa4929f..de81ca34 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -53,14 +53,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: paint(ui, rect, (highlighted, response.has_focus()), thumbnail.as_ref().map(egui::TextureHandle::id), (tr("Filter"), name)); let tabs = |thumbs: &mut Thumbs| { - let mut groups: Vec> = Vec::new(); - for def in filter_effects().iter().filter(|def| def.mask || !on_mask) { - let item = - ResourcePickerItem { id: def.id, label: tr(def.label).to_owned(), caption: None, picture: TilePicture::Texture(thumbs.filter(&ctx, def.id)) }; - match groups.last_mut() { - Some(group) if group.header == Some(tr(def.group)) => group.items.push(item), - _ => groups.push(PickerGroup { header: Some(tr(def.group)), items: vec![item] }), - vec![PickerTab { icon: ic::FUNNEL, name: tr("Filter"), groups }] let mut items: Vec> = filter_effects() .iter() .filter(|def| def.mask || !on_mask) diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 05ad4070..b8274f79 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -89,6 +89,8 @@ const SHADOW_OFFSET: [i8; 2] = [3, 4]; const WHITE_SWATCH: u8 = 235; const BLACK_SWATCH: u8 = 10; +/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it +pub(crate) const NEW_FILTER: &str = "hsl"; /// The Layers panel's top row and what its menus open pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs index b41cbabf..b34aa1d1 100644 --- a/crates/ui-egui/src/material_orb.rs +++ b/crates/ui-egui/src/material_orb.rs @@ -14,15 +14,15 @@ use crate::orb_previews::{OrbJob, OrbPreviews}; use crate::preview_image::aces; use crate::theme::Tokens; -/// The reflectance of non-metals at normal incidence -const DIELECTRIC_REFLECTANCE: f32 = 0.04; - /// Largest orb rendered, in physical pixels const MAX_SIDE_PX: usize = 512; /// The sphere's radius in halves of the square const SPHERE_RADIUS: f32 = 0.84; +/// Reflectance of a non-metal seen face on +const DIELECTRIC_F0: f32 = 0.04; + /// The lowest roughness shaded (a perfect mirror aliases at orb sizes) const MIN_ROUGHNESS: f32 = 0.03; @@ -124,7 +124,7 @@ fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f let mut out = [0.0; 3]; for (channel, value) in out.iter_mut().enumerate() { let base = sample.base[channel].clamp(0.0, 1.0); - let f0 = DIELECTRIC_REFLECTANCE + (base - DIELECTRIC_REFLECTANCE) * metallic; + let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * metallic; let specular = f0 * scale + bias; *value = diffuse_light[channel] * base * (1.0 - metallic) * (1.0 - specular) + specular_light[channel] * specular + sample.emissive[channel].max(0.0); } diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index 0e05486f..432e1857 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -33,8 +33,6 @@ impl OrbEnvironment { fn from_hdr(bytes: &[u8]) -> Option { let decoded = image::load_from_memory_with_format(bytes, image::ImageFormat::Hdr).inspect_err(|e| log::warn!("the orb studio did not load: {e}")).ok()?; - let rgba: Vec<[f32; 4]> = pixels.iter().map(|&[red, green, blue]| [red, green, blue, 1.0]).collect(); - let env = EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false)?; let rgb = decoded.to_rgb32f(); let rgba: Vec<[f32; 4]> = rgb.pixels().map(|pixel| [pixel[0], pixel[1], pixel[2], 1.0]).collect(); EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false).map(|env| OrbEnvironment::of(&env)) diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index be6936e2..f517175d 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -168,8 +168,8 @@ impl PropertySheet<'_> { let center_y = self.cursor_y() + ROW_HEIGHT / 2.0; let shift = self.lead_shift(); let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; - let (label, stack, text_color) = match lead { - RowLead::Label { text, stack } => (text, stack, self.tokens.text), + let (label, stack) = match lead { + RowLead::Label { text, stack } => (text, stack), RowLead::Loose(text) if shift + self.text_width(text, font.clone()) <= self.column() - self.left - LOOSE_LABEL_AIR => { self.paint_info(center_y); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, text, font, self.tokens.text); @@ -198,7 +198,7 @@ impl PropertySheet<'_> { let text = self.tokens.text; if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { self.paint_info(center_y); - self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); + self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text); return self.column(); } diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 468e42a1..3c144770 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -275,18 +275,9 @@ impl PropertySheet<'_> { dice_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::i18n::tr("Random"))); if dice_response.clicked() { - *seed = next_seed(*seed); *seed = texturecraft_engine::folder_cmds::next_seed(*seed); changed = true; } changed } } - -/// A new seed that looks random but follows from the old one (SplitMix32's mixing step), so tests and replays get the same sequence -pub(crate) fn next_seed(seed: u32) -> u32 { - let mut z = seed.wrapping_add(0x9e37_79b9); - z = (z ^ (z >> 16)).wrapping_mul(0x85eb_ca6b); - z = (z ^ (z >> 13)).wrapping_mul(0xc2b2_ae35); - z ^ (z >> 16) -} diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 67c55f5e..91478700 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -4,7 +4,6 @@ use egui_kittest::kittest::Queryable as _; use egui_phosphor::regular as ic; use super::number_field::shown_number; -use super::slot::next_seed; use super::{NumberField, PropertySheet}; use crate::theme::{Accent, Brightness, Tokens}; use texturecraft_engine::folder_cmds::next_seed; @@ -264,6 +263,7 @@ fn card_under_caption(ui: &mut egui::Ui, state: &mut (bool, std::cell::Cell) -> RoundGizmo { diff --git a/crates/ui-egui/src/slot_thumbnail.rs b/crates/ui-egui/src/slot_thumbnail.rs index 16cebc02..ab657a0e 100644 --- a/crates/ui-egui/src/slot_thumbnail.rs +++ b/crates/ui-egui/src/slot_thumbnail.rs @@ -1,6 +1,5 @@ //! The picture a slot card shows of a fill channel's source -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, TextureHandle, TextureId, pos2}; use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Stroke, StrokeKind, TextureHandle, TextureId, pos2}; use egui_phosphor::regular as ic; use texturecraft_engine::compose::ThumbTarget; diff --git a/crates/ui-egui/src/source_slot.rs b/crates/ui-egui/src/source_slot.rs index 4f353f73..454ff93b 100644 --- a/crates/ui-egui/src/source_slot.rs +++ b/crates/ui-egui/src/source_slot.rs @@ -1,4 +1,4 @@ -//! What a source slot card edits: one channel of a fill's material +//! What a source slot card edits: one channel of a fill's material, or a mask fill's one grayscale source use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, ChannelKind}; @@ -26,10 +26,10 @@ impl SourceSlot { pub(crate) fn kind(self) -> ChannelKind { match self { SourceSlot::Channel(channel) => channel.kind(), + SourceSlot::Grayscale => ChannelKind::Scalar, } } - /// The value Uniform and the slot's × give it /// The value Uniform and the slot's × give it: a new mask fill's white for a grayscale pub(crate) fn default_value(self) -> [f32; 3] { match self { @@ -43,7 +43,6 @@ impl SourceSlot { if self.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 } } - /// A procedural's two ends when it is picked: a softer part of the channel's range /// A procedural's two ends when it is picked: a gray fill spans the whole range, a channel a softer part of it pub(crate) fn procedural_ends(self) -> ([f32; 3], [f32; 3]) { /// Base color stays off pure black and white, which read as unlit or blown out @@ -56,13 +55,13 @@ impl SourceSlot { const CHANNEL_ENDS: ([f32; 3], [f32; 3]) = ([0.2; 3], [0.8; 3]); match self { + SourceSlot::Grayscale => ([0.0; 3], [1.0; 3]), SourceSlot::Channel(Channel::BaseColor) => BASE_COLOR_ENDS, SourceSlot::Channel(Channel::Height) => HEIGHT_ENDS, SourceSlot::Channel(_) => CHANNEL_ENDS, } } - /// The fill command's fields naming the slot /// The fill command's fields naming the slot (a grayscale has no channel) pub(crate) fn fields(self) -> Value { match self { diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index a52a385b..caefbdd4 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -105,8 +105,6 @@ fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { assert!(!has_camera_picker(&empty), "no camera picker"); - // The picker shows "Material" right of the tool shelf and the Assets panel and left of the right column: one per view in the split layout - let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && (300.0..1200.0).contains(x)).count(); // The picker shows "Material" right of the tool shelf and the Assets panel: one per view in the split layout let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && *x > 400.0).count(); diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index 6863656e..d926b906 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -6,7 +6,6 @@ use serde_json::json; use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; use texturecraft_ui_egui::TextureCraftApp; -use crate::fill_support::click_node; use crate::fill_support::{click_label, click_node}; /// Opens the Roughness slot's source picker on the Material tab and types `search` into its search field, which has the focus @@ -127,13 +126,11 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - // The search field has the focus: it brings the tile into the grid's view // The mask fill's Grayscale slot opens the source picker; its search finds the image click_node(&mut harness, egui::Role::ComboBox, "Grayscale"); harness.run_steps(2); harness.event(egui::Event::Text("mask".into())); harness.run_steps(2); - harness.get_by_role_and_label(egui::Role::ListBoxOption, &image_name).click(); click_node(&mut harness, egui::Role::ListBoxOption, &image_name); harness.run_steps(3); @@ -148,9 +145,6 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { projection: Projection::Triplanar { .. }, .. })); - // The search field has the focus: it brings the tile into the grid's view - harness.event(egui::Event::Text("uniform".into())); - harness.get_by_role_and_label(egui::Role::ListBoxOption, "Uniform value").click(); // The slot's × puts the mask fill back to a uniform value click_node(&mut harness, egui::Role::Button, "Clear"); harness.run_steps(3); diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 2efe721f..dfb895a8 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -68,10 +68,10 @@ fn escape_closes_the_picker_without_changes() { /// Opens the wand's Add effect menu and clicks Filter fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { - harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + harness.get_by_role_and_label(Role::Button, "Add effect").click(); harness.run_steps(3); - harness.get_by_label("Add filter").click(); + harness.get_by_role_and_label(Role::Button, "Filter").click(); harness.run_steps(3); } diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 48b3be42..96ec383c 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -118,7 +118,6 @@ fn the_anchor_points_tab_picks_an_anchor() { harness.get_by_label("Anchor points").click(); harness.run_steps(3); - harness.get_by_role_and_label(Role::ListBoxOption, &label).click(); // An anchor tile is labelled with the anchor's name; its layer is named only where two anchors share a name harness.get_by_role_and_label(Role::ListBoxOption, "Height").click(); harness.run_steps(3); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index c451ea98..a6c18764 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -2278,7 +2278,7 @@ fn properties_min_width_snapshot() { save(&mut harness, &output_dir, &format!("properties-min-width-planar-{name}")); } harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "colorMatch"})).unwrap(); + execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "hsl"})).unwrap(); save(&mut harness, &output_dir, "properties-min-width-filter"); } From 7d8cbb658a681625702f1495d554053fbe3d5a39 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 041/153] Filters: the stand-ins parts 2-4 kept for the filter panel and the effect blend lookups go --- crates/compose/src/eval.rs | 10 ---------- crates/compose/tests/cache_and_instances.rs | 6 ------ crates/core/src/layer.rs | 7 ------- crates/core/src/lib.rs | 2 -- crates/core/src/project.rs | 1 - crates/engine/src/filter_lib.rs | 1 - crates/engine/src/folder_cmds.rs | 1 - crates/engine/src/layer_cmds.rs | 3 --- crates/engine/src/mask_cmds.rs | 1 - crates/engine/src/session.rs | 3 --- crates/engine/tests/it/filter_support.rs | 3 --- crates/engine/tests/it/folder_contents.rs | 1 - crates/engine/tests/it/resources_used.rs | 6 ------ crates/engine/tests/session.rs | 2 -- crates/render/src/ibl.rs | 1 - crates/ui-egui/src/dock.rs | 2 -- crates/ui-egui/src/fill_material_panel.rs | 1 - crates/ui-egui/src/filter_slot.rs | 1 - crates/ui-egui/src/layer_toolbar.rs | 2 -- crates/ui-egui/src/material_orb.rs | 5 ----- crates/ui-egui/src/property_sheet/row.rs | 3 --- crates/ui-egui/src/property_sheet/row_lead.rs | 1 - crates/ui-egui/src/property_sheet/slider.rs | 2 -- crates/ui-egui/src/property_sheet/switch_control.rs | 1 - crates/ui-egui/src/property_sheet/tests.rs | 1 - crates/ui-egui/src/source_slot.rs | 4 ---- crates/ui-egui/tests/it/filter_picker.rs | 2 -- crates/ui-egui/tests/ui_snapshots.rs | 1 - 28 files changed, 74 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ffe4a3d3..6e7fb298 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -11,9 +11,6 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, - Filtering, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Sampling, - ShapeCrop, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, Project, Projection, @@ -1316,7 +1313,6 @@ fn field( for (((&filter, &margin), &wrap), &own_wrap) in filters.iter().zip(&margins).zip(&wrapping).zip(&own_wraps) { let region = region_around(inp, tiles, margin, wrap)?; let start = previous.as_ref().map(|(index, field)| (*index, field)); - let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, region, start)?; let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, own_wrap, region, start)?; // Preserve only stages with anchors before the next filter overwrites their value @@ -1437,7 +1433,6 @@ fn filter_region( }; let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); - let opacity = filter_effect.map(|effect| effect.blend_of(channel).opacity.clamp(0.0, 1.0)).unwrap_or(1.0); let filter = filter_effect.and_then(|effect| match &effect.kind { EffectKind::Filter(filter) => Some(filter), _ => None, @@ -2171,7 +2166,6 @@ fn effect_plans<'a>( } _ => (None, false), }; - let blend = effect.blend_of(channel); let environment = match &effect.kind { EffectKind::Filter(Filter::EnvironmentLighting { .. }) => Some(EnvironmentSh::of(&inp.project.display, inp.images)), _ => None, @@ -2554,7 +2548,6 @@ type ChannelContents = [Option<([f32; 3], f32)>; NCH]; impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, tape: Tape::Off, copy: None } Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, lit: None, tape: Tape::Off, copy: None } } @@ -3547,7 +3540,6 @@ impl<'a, 'b> Texel<'a, 'b> { EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); - (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) let lit = match &effect.stylized { Some(stylized) => { let nrm = self.lit_normal(stylized.relief()); @@ -4606,7 +4598,6 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti #[cfg(test)] mod tests { use super::*; - use texturecraft_core::{ChannelBlend, CompareOp, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; use texturecraft_core::{ ChannelBlend, CompareOp, Effect, Layer, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, TextureSet, }; @@ -5930,7 +5921,6 @@ soft {soft:?}" }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(f.project.alloc_id(), compare)); - mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0 }))); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 2.0, wrap: true }))); f.project.layer_mut(top).unwrap().mask = Some(mask); diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index dea9f8d6..423b6975 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -10,7 +10,6 @@ use texturecraft_compose::{ use texturecraft_core::project::ENV_RESOURCE_PREFIX; use texturecraft_core::{ BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, - HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, GrayscaleConversion, HeightMask, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, }; @@ -673,7 +672,6 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { // Changing the hot mask must invalidate the retained fields let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap(); - blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false }); let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); @@ -961,7 +959,6 @@ fn flat_image(value: f32) -> std::sync::Arc { } #[test] -fn id_map_image_changes_invalidate_stack_key() { fn filter_input_and_id_map_image_changes_invalidate_stack_key() { let mut fixture = fixture(); heavy_stack(&mut fixture); @@ -980,7 +977,6 @@ fn filter_input_and_id_map_image_changes_invalidate_stack_key() { images.insert("input".into(), flat_image(0.1)); images.insert("id".into(), flat_image(0.1)); - images.insert("id".into(), flat_image(0.9)); for name in ["input", "id"] { let original = stack_key(&fixture, &images); images.insert(name.into(), flat_image(0.9)); @@ -988,7 +984,6 @@ fn filter_input_and_id_map_image_changes_invalidate_stack_key() { } } - assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache"); #[test] fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { let mut fixture = fixture(); @@ -1027,7 +1022,6 @@ enum BlurOn { fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option, blur_on: BlurOn) -> (LayerId, LayerId) { let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); - let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0 })); let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false })); match blur_on { BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur), diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index aee8f43d..1ff4e0fc 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,7 +4,6 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, CompareSource, ContentsOffset, DepthCulling, Projector, RandomizedSeed, ShapeCrop, lum}; use crate::curve_preset::CurvePreset; use crate::gradient_input::{GradientInput, ramp, shape_gray}; use crate::{ @@ -1321,7 +1320,6 @@ fn unit_divider() -> u16 { 1 } -/// Whether a switch is on, its default where it defaults to on (not saved then) /// Serde default of a switch that was on in projects saved before it existed fn yes() -> bool { true @@ -2057,7 +2055,6 @@ impl Layer { LayerKind::Fill(fill) => fill.sources.values().any(|source| source.reads_anchor(None)), _ => false, }; - fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.kind.reads(None)) fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.reads(None)) } @@ -2089,7 +2086,6 @@ pub struct Effect { impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { // Generators and fills that build a mask usually add on top of the background - Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0, channel_blends: BTreeMap::new() } Effect { id, name: kind.name().to_string(), @@ -2169,15 +2165,12 @@ mod tests { } #[test] - fn a_colour_selection_id_map_is_reported_as_used() { fn a_colour_selection_id_map_and_a_filter_image_input_are_reported_as_used() { let mut selection = crate::ColorSelection::new(Vec::new(), 0.0); selection.id_map = Some("id.png".into()); - let effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); let mut effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection)); effect.inputs.insert("mask".into(), Source::image("input.png")); - assert_eq!(effect.kind.images_read().collect::>(), vec!["id.png"]); assert_eq!(effect.images_read().collect::>(), vec!["id.png", "input.png"]); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ea2c1805..b05c708b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,8 +111,6 @@ pub use image_input::ImageInput; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, - OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator, - TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, posterize, diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 97d35be8..7dfcefca 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -652,7 +652,6 @@ impl Project { out.push((layer.id, None)); } let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()); - out.extend(effects.filter(|e| e.kind.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); out.extend(effects.filter(|e| e.reads(Some(anchor))).map(|e| (layer.id, Some(e.id)))); } out diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index b4a72c26..2cab1ad0 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -342,7 +342,6 @@ pub(crate) fn build_for(cmd: &str, id: &str, p: &Value) -> Result { "bakedLighting" => library_baked_lighting(), "bakedLightingEnvironment" => LIBRARY_ENVIRONMENT_LIGHTING, "levels" => { - crate::mask_cmds::levels_from(cmd, p, &mut l)?; let mut levels = Levels::default(); crate::mask_cmds::levels_from(cmd, p, &mut levels)?; return Ok(EffectKind::Levels(levels)); diff --git a/crates/engine/src/folder_cmds.rs b/crates/engine/src/folder_cmds.rs index 5b22cf50..4b0ce043 100644 --- a/crates/engine/src/folder_cmds.rs +++ b/crates/engine/src/folder_cmds.rs @@ -237,7 +237,6 @@ fn seed_count(layer: &Layer) -> usize { .map(|effect| match &effect.kind { EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })), EffectKind::Material(fill) => fill_seeds(fill), - EffectKind::Generator(_) | EffectKind::Filter(Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. }) => 1, EffectKind::Generator(_) | EffectKind::Filter( Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. } | Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_), diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 61d2611e..1de76b29 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -3,8 +3,6 @@ use serde_json::{Value, json}; use texturecraft_core::{ - Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat, - Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, ImageInput, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; @@ -123,7 +121,6 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", "{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)} | {effect: filter effect id, input: image input id (distanceMap, customNoise), value?|procedural?|image?|alpha?|anchor? as a mask fill's source, or clear: true (back to its default gray)}", has_layer, fill_set diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 899f71cb..403459b5 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -98,7 +98,6 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 2f5ad634..241b5717 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -766,9 +766,6 @@ impl Session { previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); let added_resource_names: BTreeSet<&str> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); - let uses_added_resource = - |texture_set_index: usize| { - effect.kind.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill)) let uses_added_resource = |texture_set_index: usize| { use texturecraft_core::{EffectKind, Fill}; diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index e37b8e79..16e2e0a0 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -1,8 +1,5 @@ -//! What the filter tests share: their sessions and reading the composite //! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite -use texturecraft_engine::Session; -use texturecraft_engine::core::Channel; use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId}; use texturecraft_engine::geom::glam::Vec2; diff --git a/crates/engine/tests/it/folder_contents.rs b/crates/engine/tests/it/folder_contents.rs index b517deea..f9c7d961 100644 --- a/crates/engine/tests/it/folder_contents.rs +++ b/crates/engine/tests/it/folder_contents.rs @@ -138,7 +138,6 @@ fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) { other => panic!("not a pattern: {other:?}"), }; let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind { - EffectKind::Filter(Filter::Warp { seed, .. }) => Some(seed), EffectKind::Filter(Filter::SourceWarp(warp)) => Some(warp.seed), _ => None, }); diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index 5cb945c0..bd89ee77 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,4 +1,3 @@ -//! The images a project reads beyond fill sources: a colour selection's ID map, the mask brush and its paths //! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths use serde_json::{Value, json}; @@ -37,11 +36,8 @@ fn layer_reading(session: &mut Session, id_map: &str, input: &str) -> LayerId { } #[test] -fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_path_read() { fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mask_brush_and_a_path_read() { let mut session = session(); - let [id_map, path, brush, unused] = ["id.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); - let layer = selecting_layer(&mut session, &id_map); let [id_map, input, path, brush, unused] = ["id.png", "input.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap()); let layer = layer_reading(&mut session, &id_map, &input); @@ -58,11 +54,9 @@ fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mas } #[test] -fn a_smart_material_carries_the_image_its_selection_reads() { fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() { let mut session = session(); let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); - let layer = selecting_layer(&mut session, &id_map); let input = session.import_resource_bytes("input.png", white_png()).unwrap(); let layer = layer_reading(&mut session, &id_map, &input); let bytes = session.smart_material_bytes(layer, "Parts").unwrap(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 2802448b..62d4f7cd 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -279,10 +279,8 @@ fn gray_png() -> Vec { out } -/// Frame edits and frame and Fill section resets on the fills they act on (a planar, a warp and a decal mask) meet hostile values without panicking; a refused edit changes nothing and adds no undo step /// Frame edits, frame and Fill section resets and Transform filter settings on the fills they act on (a planar, a warp, a decal mask and a Transform filter) meet hostile values without panicking; a refused edit changes nothing and adds no undo step #[test] -fn panic_hunt_frames() { fn panic_hunt_frames_and_transforms() { let mut s = session(); let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index 57e5f87e..43c8f56c 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -68,7 +68,6 @@ impl EnvImage { if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 { return None; } - let data = pixels.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect(); let linear = |v: f32| environment_sky::environment_linear(v, srgb); let data = rgba.par_iter().map(|p| [linear(p[0]), linear(p[1]), linear(p[2])]).collect(); let mut img = EnvImage { width, height, data }; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5248b0fb..89a6f43a 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,7 +6,6 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source, }; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; @@ -3138,7 +3137,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe tool_properties(app, ui); } }), - EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), EffectKind::Filter(filter) => crate::filter_properties::filter_properties(app, ui, effect_id, filter), EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 24a62cd4..f99000c2 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -427,7 +427,6 @@ fn procedural_rows( let mut edit = scale_and_contrast(sheet, &mut edited); // A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes - let gray = matches!(slot_of, SourceSlot::Grayscale); let gray = matches!(slot_of, SourceSlot::Grayscale | SourceSlot::Input(_)); if gray { edit = edit.or(balance_and_seed(sheet, &mut edited)); diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index daa99d27..8f4ea87e 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -40,7 +40,6 @@ pub(crate) fn picker(app: &mut TextureCraftApp, pick: &egui::Response, effect: u items.sort_by_cached_key(|item| item.label.to_lowercase()); vec![PickerTab { icon: ic::FUNNEL, name: tr("Filters"), groups: vec![PickerGroup { header: None, items }] }] }; - let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); let picked = resource_picker::show(pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); if let Some(id) = picked.filter(|id| Some(*id) != current) { app.run("effect.set", json!({"effect": effect, "filter": id})); diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 922eacd2..31716da3 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -89,8 +89,6 @@ const SHADOW_OFFSET: [i8; 2] = [3, 4]; const WHITE_SWATCH: u8 = 235; const BLACK_SWATCH: u8 = 10; -/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it -pub(crate) const NEW_FILTER: &str = "hsl"; /// The filter Add filter adds: an empty one, which changes nothing until its slot's picker swaps a filter into it pub(crate) const NEW_FILTER: &str = texturecraft_engine::mask_cmds::EMPTY_FILTER; diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs index 5b7e4a11..3e19aadd 100644 --- a/crates/ui-egui/src/material_orb.rs +++ b/crates/ui-egui/src/material_orb.rs @@ -4,7 +4,6 @@ use egui::{Color32, ColorImage, Painter, Rect, pos2}; use rayon::prelude::*; -use texturecraft_engine::core::Channel; use texturecraft_engine::core::{Channel, DIELECTRIC_REFLECTANCE}; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::texel::linear_to_srgb; @@ -21,9 +20,6 @@ const MAX_SIDE_PX: usize = 512; /// The sphere's radius in halves of the square const SPHERE_RADIUS: f32 = 0.84; -/// Reflectance of a non-metal seen face on -const DIELECTRIC_F0: f32 = 0.04; - /// The lowest roughness shaded (a perfect mirror aliases at orb sizes) const MIN_ROUGHNESS: f32 = 0.03; @@ -125,7 +121,6 @@ fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f let mut out = [0.0; 3]; for (channel, value) in out.iter_mut().enumerate() { let base = sample.base[channel].clamp(0.0, 1.0); - let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * metallic; let f0 = DIELECTRIC_REFLECTANCE + (base - DIELECTRIC_REFLECTANCE) * metallic; let specular = f0 * scale + bias; *value = diffuse_light[channel] * base * (1.0 - metallic) * (1.0 - specular) + specular_light[channel] * specular + sample.emissive[channel].max(0.0); diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index f44b8045..ca9af0e1 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -168,8 +168,6 @@ impl PropertySheet<'_> { let center_y = self.cursor_y() + ROW_HEIGHT / 2.0; let shift = self.lead_shift(); let label_x = self.left + shift + ROW_PICTURE_SIZE + ROW_PICTURE_AIR; - let (label, stack) = match lead { - RowLead::Label { text, stack } => (text, stack), let (label, stack, text_color) = match lead { RowLead::Label { text, stack } => (text, stack, self.tokens.text), RowLead::Tinted { text, color } => (text, false, color), @@ -200,7 +198,6 @@ impl PropertySheet<'_> { if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { self.paint_info(center_y); - self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); return self.column(); } diff --git a/crates/ui-egui/src/property_sheet/row_lead.rs b/crates/ui-egui/src/property_sheet/row_lead.rs index 84fc568d..4cfaaa77 100644 --- a/crates/ui-egui/src/property_sheet/row_lead.rs +++ b/crates/ui-egui/src/property_sheet/row_lead.rs @@ -28,7 +28,6 @@ impl<'a> RowLead<'a> { /// The row's name, as assistive tech reads it pub(crate) fn text(self) -> &'a str { match self { - RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) => text, RowLead::Label { text, .. } | RowLead::Loose(text) | RowLead::Picture { text, .. } | RowLead::Child(text) | RowLead::Tinted { text, .. } => text, } } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index aa8dde9c..a94831bc 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -1,13 +1,11 @@ use std::ops::RangeInclusive; -use egui::{Align2, Id, Rect, Sense, Stroke, WidgetInfo, pos2}; use egui::{Align2, Color32, CornerRadius, FontId, Id, Rect, Response, Sense, Stroke, StrokeKind, WidgetInfo, pos2}; use egui_phosphor::regular as ic; use super::number_field::shown_number; use super::track::Track; use super::value_text::ValueText; -use super::{PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, TEXT_SIZE}; use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, ROW_HIT_HALF_HEIGHT, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index f0316e7d..f975c19d 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,6 +1,5 @@ use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; -use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE}; use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index adaeb900..a8727f95 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -329,7 +329,6 @@ fn card_under_caption(ui: &mut egui::Ui, state: &mut (bool, std::cell::Cell ChannelKind { match self { SourceSlot::Channel(channel) => channel.kind(), - SourceSlot::Grayscale => ChannelKind::Scalar, SourceSlot::Grayscale | SourceSlot::Input(_) => ChannelKind::Scalar, } } @@ -62,7 +59,6 @@ impl SourceSlot { const CHANNEL_ENDS: ([f32; 3], [f32; 3]) = ([0.2; 3], [0.8; 3]); match self { - SourceSlot::Grayscale => ([0.0; 3], [1.0; 3]), SourceSlot::Grayscale | SourceSlot::Input(_) => ([0.0; 3], [1.0; 3]), SourceSlot::Channel(Channel::BaseColor) => BASE_COLOR_ENDS, SourceSlot::Channel(Channel::Height) => HEIGHT_ENDS, diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 2dcee134..69244a47 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -56,11 +56,9 @@ fn escape_closes_the_picker_without_changes() { /// Opens the wand's Add effect menu and clicks Filter fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { - harness.get_by_role_and_label(Role::Button, "Add effect").click(); let at = harness.get_by_role_and_label(Role::Button, "Add effect").rect().center(); click_at(harness, at); - harness.get_by_role_and_label(Role::Button, "Filter").click(); let at = harness.get_by_role_and_label(Role::Button, "Filter").rect().center(); click_at(harness, at); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index f733e8a7..abe99bf3 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -2920,7 +2920,6 @@ fn properties_min_width_snapshot() { save(&mut harness, &output_dir, &format!("properties-min-width-planar-{name}")); } harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "hsl"})).unwrap(); execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "colorMatch"})).unwrap(); save(&mut harness, &output_dir, "properties-min-width-filter"); } From 71e35ae35c67cf248876cf70c178d32b5f30f64a Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:29:49 +0000 Subject: [PATCH 042/153] Effects, masks and folders: review repairs from #698 Chasse's repairs to this part's code, carried over from the #698 head (5644b7d3). --- crates/compose/src/below.rs | 1 + crates/compose/src/eval.rs | 62 ++++++++++----- crates/compose/src/lib.rs | 4 +- crates/compose/tests/cache_and_instances.rs | 3 + crates/core/src/color_selection.rs | 11 ++- crates/core/src/contents_offset.rs | 10 +++ crates/core/src/layer.rs | 17 ++++ crates/core/src/project.rs | 17 +++- crates/engine/src/add_mask_cmds.rs | 2 + crates/engine/src/color_selection_cmds.rs | 2 + crates/engine/src/folder_cmds.rs | 31 +++++--- crates/engine/src/layer_cmds.rs | 1 + crates/engine/src/layer_cmds/fill_target.rs | 9 +++ crates/engine/src/layer_selection.rs | 1 + crates/engine/src/mask_cmds.rs | 1 + crates/engine/src/painting.rs | 6 +- crates/engine/src/path_tool.rs | 15 +++- crates/engine/src/session.rs | 2 +- crates/engine/tests/it/add_mask_items.rs | 14 ++++ crates/engine/tests/it/color_selection.rs | 24 ++++++ crates/engine/tests/it/compare_mask.rs | 14 ++++ crates/engine/tests/it/content_effects.rs | 79 ++++++++++++++++--- crates/engine/tests/it/effect_blending.rs | 15 ++++ crates/engine/tests/it/fill_projections.rs | 1 + crates/engine/tests/it/folder_contents.rs | 23 ++++++ crates/engine/tests/it/mask_fill_source.rs | 18 +++++ crates/engine/tests/it/mask_paint_image.rs | 5 ++ crates/engine/tests/it/painter_gaps.rs | 1 + crates/engine/tests/it/resources_used.rs | 3 + crates/engine/tests/session.rs | 4 +- crates/paint/src/commit.rs | 70 ++++++++++------ crates/render/src/ibl.rs | 11 ++- crates/ui-egui/src/anchor_properties.rs | 20 +++-- crates/ui-egui/src/compare_properties.rs | 3 +- crates/ui-egui/src/dock.rs | 1 + crates/ui-egui/src/folder_properties.rs | 3 + crates/ui-egui/src/gpu.rs | 74 ++++++++++++++++- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/move_on_model.rs | 1 + crates/ui-egui/src/orb_environment.rs | 10 ++- .../ui-egui/src/property_sheet/action_row.rs | 3 + .../src/property_sheet/id_color_row.rs | 17 ++-- crates/ui-egui/src/property_sheet/tests.rs | 61 ++++++++++++++ crates/ui-egui/src/round_gizmo.rs | 2 + crates/ui-egui/src/thumbs.rs | 50 ++++++++++++ crates/ui-egui/src/viewport.rs | 3 + crates/ui-egui/tests/it/anchor_point.rs | 8 ++ .../tests/it/color_selection_editor.rs | 24 ++++++ crates/ui-egui/tests/it/compare_mask_rows.rs | 5 ++ crates/ui-egui/tests/it/effect_rows.rs | 16 ++++ crates/ui-egui/tests/it/effect_sliders.rs | 16 ++++ crates/ui-egui/tests/it/fill_channel_image.rs | 3 + crates/ui-egui/tests/it/folder_properties.rs | 5 ++ .../ui-egui/tests/it/instance_properties.rs | 3 + crates/ui-egui/tests/it/layer_toolbar.rs | 13 +++ crates/ui-egui/tests/it/levels_editor.rs | 13 +++ crates/ui-egui/tests/it/mask_fill_rows.rs | 10 +++ .../ui-egui/tests/it/mask_paint_grayscale.rs | 7 ++ crates/ui-egui/tests/it/popup_press_close.rs | 1 + crates/ui-egui/tests/it/rename_anchor.rs | 7 ++ crates/ui-egui/tests/it/source_picker.rs | 1 + .../ui-egui/tests/it/tile_generator_panel.rs | 3 + crates/ui-egui/tests/ui_snapshots.rs | 1 + 63 files changed, 766 insertions(+), 97 deletions(-) create mode 100644 crates/engine/src/layer_cmds/fill_target.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 993c4e9a..05d1cafc 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -204,6 +204,7 @@ impl StackKey { if !same_shape || (left_image.width(), left_image.height()) != size { return None; } + if left_image.same_tiles(right_image) { continue; } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 85827ada..f8fad747 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -363,7 +363,7 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator 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)), - // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them + // Use reference-resolution reach so all callers classify the same filters as stages EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) } @@ -611,7 +611,7 @@ fn stroke_at(preview: Option<&[u16]>, o: usize) -> f32 { } /// The full stack of tile (tx, ty) in `channels` and the channels the layer's mask compares, when the layer reads the stack below it (else empty) -fn anchor_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { +fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; if !reads_stack(inp.project, id) { return Vec::new(); @@ -1106,7 +1106,7 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], til } /// Layer `id`'s filtered `mask` field put into `fields` (nothing without a mask or a field) -fn insert_mask_field(inp: &Inputs, channels: &[Channel], fields: &mut Fields, id: LayerId, mask: Option<&Mask>, tiles: &[(u32, u32)]) { +fn insert_mask_field(inp: &EvaluationInputs, channels: &[Channel], fields: &mut Fields, id: LayerId, mask: Option<&Mask>, tiles: &[(u32, u32)]) { if let Some(mask) = mask && let Some(filtered) = field(inp, channels, fields, id, Job::Mask(mask), tiles) { @@ -1156,7 +1156,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>, + inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, @@ -1243,7 +1243,15 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann } /// The plan of layer `id`'s `mask` for tile (tx, ty), its fills under the Scale and Rotation `around` of the folders holding the layer -fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>, around: ContentsOffset) -> Option> { +fn mask_plan<'a>( + inp: &EvaluationInputs<'a>, + id: LayerId, + mask: &'a Mask, + tx: u32, + ty: u32, + fields: Option<&'a Fields>, + around: ContentsOffset, +) -> Option> { if !mask.enabled { return None; } @@ -1268,7 +1276,7 @@ fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32 } /// The plans of sibling layers `list` (under the Scale and Rotation of the folders holding them) -fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { +fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { let around = list.first().map_or(ContentsOffset::NONE, |id| inp.project.contents_around(*id)); plan_in(inp, list, channels, tx, ty, depth, fields, around) } @@ -1276,7 +1284,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t /// [`plan`] of sibling layers held by folders whose Scale and Rotation make `around` #[allow(clippy::too_many_arguments)] fn plan_in<'a>( - inp: &Inputs<'a>, + inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, @@ -1288,13 +1296,14 @@ fn plan_in<'a>( if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, around)).collect() } /// The plan of layer `id` at `depth` (None where it draws nothing), its fills under the Scale and Rotation `around` of the folders holding it; a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( - inp: &Inputs<'a>, + inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, @@ -1342,7 +1351,7 @@ fn plan_node<'a>( /// The content of `layer` (layer `id`'s own, or its instance source's; None for an unfollowed instance) and its plan per drawn channel of `channels`, its fills under the Scale and Rotation `around` of the folders holding `id`; a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_content<'a>( - inp: &Inputs<'a>, + inp: &EvaluationInputs<'a>, id: LayerId, layer: &'a Layer, channels: &[Channel], @@ -2139,6 +2148,7 @@ impl<'a, 'b> Texel<'a, 'b> { self.below = Some(*acc); return true; } + if node.mask.as_ref().is_some_and(|mask| mask.layer.is_some()) { self.below = Some(*acc); } @@ -3151,6 +3161,8 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let bins = bins.max(1); let (cut, in_mask) = cut_below(inp.project, owner, effect)?; let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; + let projectors = ProjectorDepthCache::default(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); let channels = cut.texture_set(inp.ts).map(|set| set.channel_list()).unwrap_or_default(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); @@ -3204,23 +3216,33 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u } /// The neighbourhood fields every sampled tile of a histogram shares; None with only local neighbourhood filters below, where each tile builds its own -fn shared_histogram_fields(inp: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Option { - // A field covers the bounding box of the tiles it is built for, the whole set for a scattered sample - let probe = neighbourhood_fields(inp, channels, tiles.get(..1).unwrap_or_default()); - if probe.is_empty() { +fn shared_histogram_fields(inp: &EvaluationInputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Option { + let probe = evaluation_fields(inp, channels, tiles.get(..1).unwrap_or_default()); + let covers_set = |field: &Field| field.x0 == 0 && field.y0 == 0 && field.w == inp.gbuf.width && field.h == inp.gbuf.height; + + // When every field covers the set, their inputs already span the sample + if probe.values().all(covers_set) { return Some(probe); } - // A stage reading the whole set builds it for every tile: once for the whole sample instead - let whole_set = probe.values().any(|field| field.w >= inp.gbuf.width && field.h >= inp.gbuf.height); - whole_set.then(|| neighbourhood_fields(inp, channels, tiles)) + // Mixed fields need the sample's bounds to cover every dependency + let whole_set = probe.values().any(covers_set); + drop(probe); + + whole_set.then(|| evaluation_fields(inp, channels, tiles)) } /// The fields histogram tile `tile` reads: the `shared` ones, else its own built into `own` -fn histogram_tile_fields<'f>(shared: Option<&'f Fields>, own: &'f mut Option, inp: &Inputs, channels: &[Channel], tile: (u32, u32)) -> &'f Fields { +fn histogram_tile_fields<'f>( + shared: Option<&'f Fields>, + own: &'f mut Option, + inp: &EvaluationInputs, + channels: &[Channel], + tile: (u32, u32), +) -> &'f Fields { match shared { Some(fields) => fields, - None => own.insert(neighbourhood_fields(inp, channels, &[tile])), + None => own.insert(evaluation_fields(inp, channels, &[tile])), } } @@ -3256,6 +3278,8 @@ pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option< } let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; + let projectors = ProjectorDepthCache::default(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); let mut channels = set.channel_list(); if !channels.contains(&channel) { channels.push(channel); @@ -4471,6 +4495,7 @@ soft {soft:?}" f.project.layer_mut(top).unwrap().mask = Some(mask); let color = run(&f, None).value(Channel::BaseColor, 30, 30); + assert!(close(color, [0.5; 3]), "the layer under shows: {color:?}"); } @@ -4772,6 +4797,7 @@ soft {soft:?}" // The folder's mask ends at 0 (its black child hides), the reader above shows at 0.4 over the 0.5 base let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index c4fb958c..c0369fd2 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -46,10 +46,12 @@ pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use effect_histogram::EffectHistogram; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, - covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, + composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, + stack_reads_neighbours, }; pub use mask_gray::MaskGray; pub use pattern_context::PatternContext; +pub use projector_depth_cache::ProjectorDepthCache; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 3b69ec6a..fd6332ad 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -906,14 +906,17 @@ fn generator_input_image_changes_invalidate_stack_key() { let original = key(&images); images.insert("unrelated".into(), image(0.5)); + assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged"); let old_image = Arc::downgrade(&images["used"]); images.insert("used".into(), image(0.9)); + assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels"); assert!(key(&images) != original, "replacing a generator input must invalidate the cache"); images.remove("used"); + assert!(key(&images) != original, "removing a generator input must invalidate the cache"); } diff --git a/crates/core/src/color_selection.rs b/crates/core/src/color_selection.rs index df2390a4..45416298 100644 --- a/crates/core/src/color_selection.rs +++ b/crates/core/src/color_selection.rs @@ -42,10 +42,14 @@ impl ColorSelection { /// How much ID color `id` is selected, 0..1 (none: no ID map there) pub fn amount(&self, id: Option<[f32; 3]>) -> f32 { let Some(id) = id else { return 0.0 }; + if self.tolerance.is_nan() || self.hardness.is_nan() { + return 0.0; + } + let distance = self .colors .iter() - // A NaN component matches nothing (f32::max would drop it), as the old strict comparison did + // Carry NaN through the component maximum so a malformed color cannot match .map(|picked| { picked .iter() @@ -63,10 +67,8 @@ impl ColorSelection { return 1.0; } - // A NaN tolerance or hardness (only a hand-edited file holds one) selects nothing, as a NaN component does let width = 1.0 - self.hardness.clamp(0.0, 1.0); - let ramp = if width <= 0.0 { 0.0 } else { (1.0 - past / width).clamp(0.0, 1.0) }; - if ramp.is_nan() { 0.0 } else { ramp } + if width <= 0.0 { 0.0 } else { (1.0 - past / width).clamp(0.0, 1.0) } } /// The gray this selection gives ID color `id` and how much of it covers the mask below (a transparent background covers only the selection) @@ -114,6 +116,7 @@ mod tests { nan_hardness.hardness = f32::NAN; for selection in [nan_tolerance, nan_hardness] { + assert_eq!(selection.amount(Some([1.0, 0.0, 0.0])), 0.0, "an exact match still needs valid settings"); assert_eq!(selection.amount(Some([0.8, 0.0, 0.0])), 0.0); } } diff --git a/crates/core/src/contents_offset.rs b/crates/core/src/contents_offset.rs index 033071b0..564b0917 100644 --- a/crates/core/src/contents_offset.rs +++ b/crates/core/src/contents_offset.rs @@ -38,8 +38,10 @@ impl ContentsOffset { pub fn new(scale: f32, rotation: f32) -> ContentsOffset { let (low, high) = ContentsOffset::SCALE_RANGE; let scale = if scale.is_finite() { scale.clamp(low, high) } else { 1.0 }; + let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE; let rotation = if rotation.is_finite() { (rotation - turn_start).rem_euclid(turn_end - turn_start) + turn_start } else { 0.0 }; + ContentsOffset { scale, rotation } } @@ -53,6 +55,7 @@ impl ContentsOffset { // A loaded offset never went through `new` let offset = ContentsOffset::new(self.scale, self.rotation); let mut out = projection.clone(); + match &mut out { Projection::Uv { scale, rotation, .. } => { *scale = scale.map(|s| s * offset.scale); @@ -68,6 +71,7 @@ impl ContentsOffset { uv.rotation += offset.rotation; } } + out } } @@ -81,7 +85,9 @@ mod tests { fn an_offset_multiplies_the_tiling_and_adds_to_the_angle_of_every_projection() { let offset = ContentsOffset::new(1.5, 30.0); let uv = offset.apply(&Projection::Uv { scale: [2.0, 4.0], rotation: 10.0, offset: [0.25, 0.0] }); + assert_eq!(uv, Projection::Uv { scale: [3.0, 6.0], rotation: 40.0, offset: [0.25, 0.0] }); + let spherical = Projection::Spherical { scale: 1.0, uv: UvTransform { tiling: [2.0, 1.0], rotation: -5.0, offset: [0.0; 2] }, @@ -89,6 +95,7 @@ mod tests { projector: Default::default(), }; let Projection::Spherical { scale, uv, .. } = offset.apply(&spherical) else { panic!("expected a spherical projection") }; + assert_eq!((scale, uv.tiling, uv.rotation), (1.0, [3.0, 1.5], 25.0)); assert_eq!(offset.apply(&Projection::UvTile), Projection::UvTile); assert_eq!(ContentsOffset::NONE.apply(&spherical), spherical); @@ -97,6 +104,7 @@ mod tests { #[test] fn nested_offsets_combine_and_hostile_values_are_kept_in_range() { let both = ContentsOffset::new(2.0, 170.0).then(ContentsOffset::new(1.5, 20.0)); + assert_eq!((both.scale, both.rotation), (3.0, -170.0)); assert_eq!(ContentsOffset::new(f32::NAN, f32::INFINITY), ContentsOffset::NONE); assert_eq!(ContentsOffset::new(1e9, 190.0), ContentsOffset { scale: 100.0, rotation: -170.0 }); @@ -107,10 +115,12 @@ mod tests { #[test] fn deep_nesting_and_loaded_offsets_keep_the_scale_in_range() { let deep = (0..17).fold(ContentsOffset::NONE, |around, _| around.then(ContentsOffset::new(100.0, 0.0))); + assert_eq!(deep.scale, ContentsOffset::SCALE_RANGE.1); let loaded: ContentsOffset = serde_json::from_str(r#"{"scale":0,"rotation":0}"#).unwrap(); let tiled = loaded.apply(&Projection::Uv { scale: [2.0, 2.0], rotation: 0.0, offset: [0.0; 2] }); + assert_eq!(tiled, Projection::Uv { scale: [0.02, 0.02], rotation: 0.0, offset: [0.0; 2] }, "a loaded Scale of 0 is kept at the smallest"); } } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 0f4fc5ab..9d318149 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1834,6 +1834,7 @@ mod tests { assert!((open.apply(0.0) + 0.5).abs() < 1e-6, "0.2 below the black handle is half a range below black"); assert!((open.apply(0.8) - 1.5).abs() < 1e-6); assert!((open.apply(0.4) - clamped.apply(0.4)).abs() < 1e-6, "between the handles both remap alike"); + let bent = Levels { gamma: 2.0, ..open }; assert!((bent.apply(0.0) + 0.5).abs() < 1e-6, "gamma bends only the part between the handles"); } @@ -1872,15 +1873,21 @@ mod tests { fn levels_saved_before_the_channel_and_clamp_load_as_they_rendered() { let saved = serde_json::json!({"in_low": 0.2, "in_high": 0.6, "gamma": 1.0, "out_low": 0.0, "out_high": 1.0}); let loaded: Levels = serde_json::from_value(saved.clone()).unwrap(); + assert!(loaded.clamp, "they stopped at the output ends"); assert_eq!(loaded.affects, None, "they remapped every channel"); assert!(Channel::ALL.iter().all(|&channel| loaded.remaps(channel))); + let saved_again = serde_json::to_value(loaded).unwrap(); + assert!(saved_again.get("affects").is_none(), "no channel is saved, as before: {saved_again}"); assert!(saved_again.get("clamp").is_none(), "a clamped level is saved as before: {saved_again}"); assert_eq!(serde_json::from_value::(saved_again).unwrap(), loaded); + let unclamped = serde_json::to_value(Levels { clamp: false, ..loaded }).unwrap(); + assert_eq!(serde_json::from_value::(unclamped).unwrap(), Levels { clamp: false, ..loaded }, "an unclamped level keeps its choice"); + let base = Levels { affects: Some(Channel::BaseColor), ..loaded }; assert!(base.remaps(Channel::BaseColor) && !base.remaps(Channel::Roughness)); } @@ -1974,14 +1981,18 @@ mod tests { assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false)); assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); + let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); assert!(!fill_layer.reads_anchor()); + let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }; fill_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })], ..Mask::new(MaskBackground::Black) }); + assert!(fill_layer.reads_anchor()); + let reader = fill_layer.mask.as_ref().map(|mask| &mask.effects[0].kind); assert!(reader.is_some_and(|reader| reader.reads(Some(LayerId(9))) && reader.reads(None) && !reader.reads(Some(LayerId(8))))); @@ -1989,9 +2000,12 @@ mod tests { let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); + assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9))) && !EffectKind::Generator(generator.clone()).reads(Some(LayerId(8)))); + generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); + assert!(generator_layer.reads_anchor()); } @@ -2002,7 +2016,9 @@ mod tests { let EffectKind::Compare { left, right, channel, hardness, .. } = kind else { panic!("{kind:?}") }; assert_eq!((left, right, channel, hardness), (CompareSource::ThisMask, CompareSource::Constant, Channel::Height, 1.0)); assert_eq!(serde_json::to_string(&kind).unwrap(), saved, "an unedited compare saves only its op, value and tolerance"); + let round_trip: EffectKind = serde_json::from_str(&serde_json::to_string(&kind).unwrap()).unwrap(); + assert_eq!(round_trip, kind); } @@ -2015,6 +2031,7 @@ mod tests { assert_eq!(CompareOp::LesserThan.mask(left, right, 0.1, 1.0), step(left < right)); assert_eq!(CompareOp::WithinTolerance.mask(left, right, 0.05, 1.0), step((left - right).abs() <= 0.05)); } + assert!((CompareOp::GreaterThan.mask(0.55, 0.5, 0.1, 0.9) - 0.5).abs() < 1e-5, "halfway up a 0.1 ramp"); assert_eq!(CompareOp::GreaterThan.mask(0.45, 0.5, 0.1, 0.0), 0.0, "below the edge stays 0 however soft"); assert_eq!(CompareOp::GreaterThan.mask(0.6, 0.5, 0.1, f32::NAN), 1.0, "a NaN hardness compares hard"); diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 79d6c0d5..b182682d 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -801,17 +801,23 @@ mod tests { let gid = p.alloc_id(); let g = Layer::new(gid, "g", LayerKind::folder(), &Channel::DEFAULT_SET); p.insert_layer(0, g, Some(a), false).unwrap(); + assert_eq!(p.texture_sets[0].stack, vec![a, gid, b]); + p.move_above(b, Some(gid), true).unwrap(); + assert_eq!(p.texture_sets[0].stack, vec![a, gid]); assert_eq!(p.layer(gid).unwrap().children(), &[b]); assert_eq!(p.locate(b), Some((0, Some(gid), 0))); assert!(p.move_above(gid, Some(b), true).is_err(), "a group cannot go inside itself"); + p.validate().unwrap(); let removed = p.remove_layer(gid).unwrap(); + assert_eq!(removed, vec![gid, b]); assert_eq!(p.texture_sets[0].stack, vec![a]); assert!(p.layer(b).is_err()); + p.validate().unwrap(); } @@ -875,12 +881,14 @@ mod tests { p.insert_layer(0, top, Some(id), false).unwrap(); let json = serde_json::to_string(&p).unwrap(); let back: Project = serde_json::from_str(&json).unwrap(); + assert_eq!(back, p); assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id)); // The mask fill of the layer above reads it let top = back.layers.values().find(|l| l.name == "y").unwrap(); let reader = top.mask.as_ref().unwrap().effects[0].id; + assert_eq!(back.anchor_readers(anchor), vec![(top.id, Some(reader))]); assert!(back.anchor_readers(LayerId(999)).is_empty()); @@ -902,15 +910,18 @@ mod tests { let a = p.insert_layer(0, a, None, false).unwrap(); let inst = Layer::new(p.alloc_id(), "a", LayerKind::Instance { source: a }, &[]); let inst = p.insert_layer(1, inst, None, false).unwrap(); + assert_eq!(p.content_layer(inst).map(|l| l.id), Some(a)); assert_eq!(p.sets_drawing(a), vec![0, 1]); assert_eq!(p.sets_drawing(inst), vec![1]); + p.validate().unwrap(); - // A folder holding an instance of itself draws itself. + // A folder holding an instance of itself draws itself let gid = p.alloc_id(); p.insert_layer(1, Layer::new(gid, "g", LayerKind::folder(), &[]), None, false).unwrap(); let loop_id = p.alloc_id(); p.insert_layer(1, Layer::new(loop_id, "g", LayerKind::Instance { source: gid }, &[]), Some(gid), true).unwrap(); + assert_eq!(p.instance_cycle(), Some(loop_id)); assert!(p.validate().is_err()); assert!(p.content_layer(LayerId(999)).is_none()); @@ -930,6 +941,7 @@ mod tests { let a = p.insert_layer(0, a, Some(inner), true).unwrap(); let top = paint(&mut p, "top"); let top = p.insert_layer(0, top, None, false).unwrap(); + assert_eq!(p.contents_around(a), ContentsOffset { scale: 3.0, rotation: 20.0 }); assert_eq!(p.contents_around(inner), ContentsOffset::new(2.0, 30.0)); assert_eq!( @@ -939,9 +951,12 @@ mod tests { // A folder saved before folders had an offset has none, and one without an offset saves as before let old: LayerKind = serde_json::from_str(r#"{"Group":{"children":[],"collapsed":true}}"#).unwrap(); + assert_eq!(old, LayerKind::Group { children: vec![], collapsed: true, contents: ContentsOffset::NONE, randomized: Vec::new() }); assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"Group":{"children":[],"collapsed":true}}"#); + let saved = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&saved).unwrap().contents_around(a), p.contents_around(a)); } diff --git a/crates/engine/src/add_mask_cmds.rs b/crates/engine/src/add_mask_cmds.rs index ee2e8404..be508092 100644 --- a/crates/engine/src/add_mask_cmds.rs +++ b/crates/engine/src/add_mask_cmds.rs @@ -58,8 +58,10 @@ fn add_bitmap(s: &mut Session, p: &Value) -> Result { } (None, None) => return Err(bad(CMD, "`image` or `alpha` is required")), }; + let projection = crate::layer_cmds::projection_from(p, CMD, None, || crate::warp_cmds::fitted_frame(&s.mesh))?; let kind = EffectKind::Fill { source: Source::Image { name, normal_format: Default::default() }, projection, sampling: Sampling::default() }; let add_library = |s: &mut Session| library.map_or(Ok(()), |alpha| s.add_library_alpha(alpha).map(|_| ())); + push_own_mask_effect(s, p, kind, "Add bitmap mask", add_library) } diff --git a/crates/engine/src/color_selection_cmds.rs b/crates/engine/src/color_selection_cmds.rs index 7e7e53be..80f14713 100644 --- a/crates/engine/src/color_selection_cmds.rs +++ b/crates/engine/src/color_selection_cmds.rs @@ -138,6 +138,7 @@ fn id_color_at(session: &Session, params: &Value, owner: LayerId, id_map: Option if material != set.material { return Err(bad(CMD, "that surface belongs to another texture set")); } + uv } }; @@ -148,6 +149,7 @@ fn id_color_at(session: &Session, params: &Value, owner: LayerId, id_map: Option if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) { return Err(bad(CMD, "that point is outside the texture set's UV space")); } + let (x, y) = (texel[0] as u32, texel[1] as u32); let color = match (image, baked) { (Some(image), _) => { diff --git a/crates/engine/src/folder_cmds.rs b/crates/engine/src/folder_cmds.rs index ab811c86..dbf9f8f7 100644 --- a/crates/engine/src/folder_cmds.rs +++ b/crates/engine/src/folder_cmds.rs @@ -104,21 +104,31 @@ fn reset_contents(s: &mut Session, p: &Value) -> Result { return Ok(Value::Null); } - let mut descended = Vec::new(); - descendants(&s.doc.project, id, 0, &mut descended); - let inside: HashSet = descended.into_iter().collect(); + let mut inside = Vec::new(); + descendants(&s.doc.project, id, 0, &mut inside); + let inside: HashSet = inside.into_iter().collect(); + s.edit("Reset folder contents", |s| { let contents = contents_mut(&mut s.doc.project, id).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", id.0)))?; *contents = ContentsOffset::NONE; - let randomized = randomized_mut(&mut s.doc.project, id).map(std::mem::take).unwrap_or_default(); - for record in randomized.iter().filter(|record| inside.contains(&record.layer)) { - let Some(layer) = s.doc.project.layers.get_mut(&record.layer) else { continue }; - // Only a seed still at the value Randomize seeds gave it goes back: one changed since keeps the artist's pick - if let Some(seed) = layer_seeds(layer).into_iter().nth(record.index as usize).filter(|seed| **seed == record.after) { - *seed = record.before; + let randomized = randomized_mut(&mut s.doc.project, id).map(std::mem::take).unwrap_or_default(); + let mut records_by_layer = HashMap::>::new(); + for record in randomized.iter().filter(|record| inside.contains(&record.layer)) { + records_by_layer.entry(record.layer).or_default().push(record); + } + + for (layer_id, records) in records_by_layer { + let Some(layer) = s.doc.project.layers.get_mut(&layer_id) else { continue }; + let mut seeds = layer_seeds(layer); + for record in records { + // Preserve seeds edited since randomization + if let Some(seed) = seeds.get_mut(record.index as usize).filter(|seed| ***seed == record.after) { + **seed = record.before; + } } } + Ok(()) })?; Ok(Value::Null) @@ -186,7 +196,8 @@ fn descendants(project: &Project, id: LayerId, depth: usize, out: &mut Vec Result<(&mut _ => Err(EngineError::Other("not a mask fill effect".into())), }; } + let fill = fill_mut(s, target)?; Ok((&mut fill.projection, &mut fill.sampling)) } diff --git a/crates/engine/src/layer_cmds/fill_target.rs b/crates/engine/src/layer_cmds/fill_target.rs new file mode 100644 index 00000000..c95d8ffb --- /dev/null +++ b/crates/engine/src/layer_cmds/fill_target.rs @@ -0,0 +1,9 @@ +use texturecraft_core::LayerId; + +/// Which fill `layer.fill.*` edits: a fill layer's (`layer`), a content fill effect's (`effect`) or a mask fill effect's (`effect`: one grayscale source, no channels or material) +#[derive(Clone, Copy)] +pub(crate) enum FillTarget { + Layer(LayerId), + Effect(LayerId), + Mask(LayerId), +} diff --git a/crates/engine/src/layer_selection.rs b/crates/engine/src/layer_selection.rs index e766fe0e..fe78e4a6 100644 --- a/crates/engine/src/layer_selection.rs +++ b/crates/engine/src/layer_selection.rs @@ -104,6 +104,7 @@ fn push_rows(project: &Project, list: &[LayerId], expanded_only: bool, depth: us for id in list.iter().rev() { let Some(layer) = project.layers.get(id) else { continue }; + rows.push(*id); if let LayerKind::Group { children, collapsed, .. } = &layer.kind && !(expanded_only && *collapsed) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 74b1dfda..93c25a02 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -574,6 +574,7 @@ fn levels_target(levels: &mut Levels, content: bool) -> Result<()> { } else if levels.affects.is_some() { return Err(bad("effect.add", "a mask's levels remap its one value: leave out `affects`")); } + Ok(()) } diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index e6e253da..e288b098 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -560,10 +560,11 @@ impl Session { let Some(mut st) = self.stroke.take() else { return Ok(()) }; let size = (st.canvas.alpha.width(), st.canvas.alpha.height()); if st.canvas.dirty.is_empty() { - // Nothing painted: drop any mask effect the stroke created. + // Nothing painted: drop any mask effect the stroke created self.doc = st.before; return Ok(()); } + let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone()); let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut st.staging); @@ -588,8 +589,7 @@ impl Session { self.redo.clear(); self.modified = true; self.revision = self.revision.wrapping_add(1); - // The live preview already shows the committed result: the stroke's tiles recomposite - // from the committed pixels at low priority, without holding up this frame. + // Recompute committed tiles at low priority because the live preview already shows them self.mark_settle(st.ts, st.target, st.canvas.dirty.iter().copied()); Ok(()) } diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 19157759..b3916b46 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -156,7 +156,7 @@ impl PathState { #[derive(Clone)] pub(crate) struct PathCache { pub(crate) eid: LayerId, - // A change to the mask images `below` paints with drops the cache (Session::invalidate_changed) + // Session::invalidate_changed discards the prefix when an image it reads changes key: (u64, Option<(u32, u32)>), below: Vec, mask: Option, @@ -165,8 +165,9 @@ pub(crate) struct PathCache { impl PathCache { /// The image resources the cached paths painted their mask with - pub(crate) fn images(&self) -> impl Iterator + '_ { - self.below.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image) + pub(crate) fn images(&self) -> impl Iterator + '_ { + // Only successfully painted paths enter the prefix + self.below.iter().filter_map(|shape| shape.paint.get("mask_image")?.as_str()) } } @@ -837,7 +838,7 @@ impl Session { let from = if back { &self.path_steps.0 } else { &self.path_steps.1 }; let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) }; - // Returning false here would let undo/redo consume document history instead. + // Keep undo and redo within the active path history if self.quick_mask.editing { return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into())); } @@ -1216,12 +1217,17 @@ mod tests { for v in [0.4, 0.45] { execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); } + assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1)); + let r = s.render_paths(eid, 1).unwrap(); + assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}"); + let cached = pixels(&s, eid); s.path_cache = None; s.render_paths(eid, 0).unwrap(); + assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); @@ -1255,6 +1261,7 @@ mod tests { let eid = LayerId(eid); execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.6], [0.9, 0.6]]})).unwrap(); + assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1), "the bottom path is cached"); execute(&mut s, "resource.remove", &json!({"name": image})).unwrap(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 75d0da63..fbb0b9f3 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -757,7 +757,7 @@ impl Session { (Some(previous), Some(current)) => !Arc::ptr_eq(previous, current), (previous, current) => previous.is_some() != current.is_some(), }; - if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(|name| resource_changed(&name))) { + if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(resource_changed)) { self.path_cache = None; } diff --git a/crates/engine/tests/it/add_mask_items.rs b/crates/engine/tests/it/add_mask_items.rs index ec0e6e53..1b93b325 100644 --- a/crates/engine/tests/it/add_mask_items.rs +++ b/crates/engine/tests/it/add_mask_items.rs @@ -25,8 +25,10 @@ fn gray_png() -> Vec { fn added(s: &mut Session, command: &str, params: Value) -> (LayerId, EffectKind) { let steps = s.history_labels().len(); let effect = LayerId(execute(s, command, ¶ms).unwrap()["effect"].as_u64().unwrap()); + assert_eq!(s.history_labels().len(), steps + 1, "{command} is one undo step"); assert_eq!(s.target, StackTarget::Effect(effect), "{command} selects the effect it adds"); + let kind = s.doc.project.effect(effect).unwrap().1.kind.clone(); (effect, kind) } @@ -36,19 +38,25 @@ fn a_bitmap_mask_is_a_black_mask_with_a_fill_reading_the_picked_alpha() { let (mut s, layer) = fill(); let name = resource_name(alphas::find("scratches").unwrap()); let (_, kind) = added(&mut s, "mask.add.bitmap", json!({"layer": layer.0, "alpha": "scratches"})); + assert!(matches!(kind, EffectKind::Fill { source: Source::Image { name: ref read, .. }, .. } if *read == name), "{kind:?}"); + let mask = s.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert_eq!(mask.background, MaskBackground::Black); assert!(s.doc.resources.contains_key(&name)); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.is_none(), "one undo takes the mask back"); assert!(!s.doc.resources.contains_key(&name), "and the alpha's picture with it"); // Without a picture there is nothing to add assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0})).is_err()); assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0, "image": "missing.png"})).is_err()); + let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); + assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0, "image": image, "alpha": "scratches"})).is_err(), "one picture, not two"); assert!(s.doc.project.layer(layer).unwrap().mask.is_none()); } @@ -57,6 +65,7 @@ fn a_bitmap_mask_is_a_black_mask_with_a_fill_reading_the_picked_alpha() { fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_below() { let (mut s, layer) = fill(); let (_, kind) = added(&mut s, "mask.add.heightCombination", json!({"layer": layer.0})); + match kind { EffectKind::Compare { left, right, channel, hardness, .. } => { assert_eq!((left, right, channel, hardness), (CompareSource::ThisLayer, CompareSource::LayersBelow, Channel::Height, 0.9)); @@ -70,13 +79,16 @@ fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_b fn color_selections_go_in_the_mask_and_are_selected() { let (mut s, layer) = fill(); let (first, kind) = added(&mut s, "mask.add.colorSelection", json!({"layer": layer.0})); + assert!(matches!(kind, EffectKind::ColorSelection(_))); assert_eq!(s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().background, MaskBackground::Black, "as colour selection masks were"); // Add effect's item adds another to the same mask, whatever target it is given let (second, kind) = added(&mut s, "effect.add.colorSelection", json!({"layer": layer.0, "target": "content"})); assert!(matches!(kind, EffectKind::ColorSelection(_))); + let mask: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask, vec![first, second]); assert!(s.doc.project.layer(layer).unwrap().content_effects.is_empty()); } @@ -102,7 +114,9 @@ fn add_mask_on_an_instance_starts_its_own_mask() { let (effect, _) = added(&mut s, command, params); assert_eq!(s.doc.project.layer(source).unwrap().mask, before, "{command} left the source's mask as it was"); + let own = s.doc.project.layer(instance).unwrap().mask.as_ref().map(|mask| mask.effects.iter().map(|effect| effect.id).collect::>()); + assert_eq!(own, Some(vec![effect]), "{command} started the instance's own mask"); } } diff --git a/crates/engine/tests/it/color_selection.rs b/crates/engine/tests/it/color_selection.rs index 97039c9e..25d62f1a 100644 --- a/crates/engine/tests/it/color_selection.rs +++ b/crates/engine/tests/it/color_selection.rs @@ -92,11 +92,15 @@ fn a_uv_pick_adds_the_color_there_or_replaces_one() { assert_close(picked, stored(TOP_LEFT_ID)); let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap(); + assert_eq!(replaced["index"], json!(0)); + let picked = colors(&session, effect); assert_eq!(picked.len(), 2); + assert_close(picked[0], stored(BOTTOM_ID)); execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step"); } @@ -107,11 +111,13 @@ fn the_colors_param_replaces_the_list_in_one_undo_step() { let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)]; execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap(); + assert_eq!(colors(&session, effect), edited.to_vec()); let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") }; assert!(matches!(&found.kind, EffectKind::ColorSelection(selection) if selection.tolerance == 0.2)); execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect), vec![NO_PART]); } @@ -124,8 +130,11 @@ fn bad_colors_are_refused_and_change_nothing() { for colors_param in &refused { assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}"); } + assert_eq!(colors(&session, effect), vec![NO_PART]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap(); + assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1"); } @@ -315,10 +324,12 @@ fn a_new_color_selection_selects_nothing_until_a_color_is_picked() { execute(&mut session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap(); let added = execute(&mut session, "mask.add.colorSelection", &Value::Null).unwrap(); let effect = LayerId(added["effect"].as_u64().unwrap()); + assert_eq!(colors(&session, effect), Vec::<[f32; 3]>::new()); execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1.0, 0.0, 0.0]]})).unwrap(); execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": []})).unwrap(); + assert_eq!(colors(&session, effect), Vec::<[f32; 3]>::new(), "the last color can be removed"); } @@ -342,6 +353,7 @@ fn an_image_resource_can_be_the_id_map_without_a_mesh_map() { assert_eq!(execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string().matches(&format!("\"idMap\":\"{image}\"")).count(), 1); execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": null})).unwrap(); + assert_eq!(session.mask_at(layer, &[top_right]).unwrap(), vec![0.0], "back on the missing mesh map"); } @@ -355,20 +367,28 @@ fn output_hardness_and_background_shape_the_mask_in_one_undo_step_each() { assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![1.0, 0.0], "selected part, background"); execute(&mut session, "effect.set", &json!({"effect": effect.0, "output": 0.5, "background": "white"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 1.0]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "gray"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 0.5]); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 1.0], "one undo step"); // A transparent background leaves the mask below it: the black mask background here execute(&mut session, "effect.set", &json!({"effect": effect.0, "output": 1.0, "background": "transparent"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![1.0, 0.0]); // The bottom part is far from the picked color: a soft edge reaches it only when wide enough execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "black", "tolerance": 0.0, "hardness": 0.0})).unwrap(); let soft = session.mask_at(layer, &texels).unwrap(); + assert_eq!(soft[0], 1.0); + let far = (200.0f32 - 10.0) / 255.0; assert!((soft[1] - (1.0 - far)).abs() < 1e-2, "{soft:?}"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "purple"})).is_err()); @@ -387,9 +407,13 @@ fn the_id_mask_view_shows_the_chosen_image_where_the_mask_reads_it() { let image = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": image})).unwrap(); + assert_eq!(session.id_mask_image(effect).map(|(texture_set, _)| texture_set), Some(0)); + let rgba = session.id_mask_view_rgba(effect, 16).unwrap(); + assert_eq!(rgba.len(), 16 * 16 * 4); + let pixel = |x: usize, y: usize| -> [u8; 3] { let start = (y * 16 + x) * 4; [rgba[start], rgba[start + 1], rgba[start + 2]] diff --git a/crates/engine/tests/it/compare_mask.rs b/crates/engine/tests/it/compare_mask.rs index fd00fa03..8a0e3224 100644 --- a/crates/engine/tests/it/compare_mask.rs +++ b/crates/engine/tests/it/compare_mask.rs @@ -60,11 +60,13 @@ fn this_layer_is_compared_with_the_layers_below() { assert_eq!(base_color(&mut session), LAYER_COLOR, "the layer shows where its mask compares true"); execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "lesser"})).unwrap(); + assert!(close(mask(&mut session, top), 0.0)); assert_eq!(base_color(&mut session), BELOW_COLOR, "the layer is hidden where the comparison fails"); // Changing the layers below changes the mask above them (no stale cached stack) execute(&mut session, "layer.fill.set", &json!({"layer": bottom.0, "channel": "roughness", "value": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "0.6 < 0.9 holds: {}", mask(&mut session, top)); assert_eq!(base_color(&mut session), LAYER_COLOR); } @@ -78,9 +80,11 @@ fn hardness_ramps_the_mask_past_the_edge() { assert!(close(mask(&mut session, top), 0.3), "{}", mask(&mut session, top)); execute(&mut session, "effect.set", &json!({"effect": compare.0, "hardness": 1.0})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "a hard step: {}", mask(&mut session, top)); execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "within", "tolerance": 0.02, "hardness": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 0.9), "0.01 past the tolerance of 0.1's ramp: {}", mask(&mut session, top)); } @@ -89,8 +93,11 @@ fn a_constant_side_and_the_mask_so_far() { let mut session = session(); let (_, top, compare) = two_layers(&mut session, 0.2, 0.6); execute(&mut session, "effect.set", &json!({"effect": compare.0, "right": "constant", "value": 0.7, "hardness": 1.0})).unwrap(); + assert!(close(mask(&mut session, top), 0.0), "0.6 > 0.7 fails"); + execute(&mut session, "effect.set", &json!({"effect": compare.0, "left": "thisMask", "value": 0.5})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "a white mask (1) > 0.5 holds"); let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); @@ -104,10 +111,15 @@ fn compare_parameters_are_one_undo_step_and_refuse_unknown_values() { let mut session = session(); let (_, top, compare) = two_layers(&mut session, 0.2, 0.6); execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "lesser", "right": "constant", "value": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "0.6 < 0.9"); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "back to 0.6 > layers below 0.2"); + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"op\":\"greater\"") && inspected.contains("\"right\":\"layersBelow\""), "one undo step restores both"); assert!(execute(&mut session, "effect.set", &json!({"effect": compare.0, "left": "elsewhere"})).is_err()); @@ -122,9 +134,11 @@ fn the_histogram_counts_what_each_side_reads() { let histogram = execute(&mut session, "effect.histogram", &json!({"effect": compare.0, "bins": 10})).unwrap(); let busiest = |side: &str| { let counts: Vec = histogram["compare"][side].as_array().unwrap().iter().map(|count| count.as_u64().unwrap()).collect(); + assert!(counts.iter().sum::() > 0, "{side} counts texels"); counts.iter().enumerate().max_by_key(|(_, count)| **count).map(|(bucket, _)| bucket).unwrap() }; + assert_eq!(busiest("left"), 6, "this layer's roughness 0.65"); assert_eq!(busiest("right"), 2, "the layers below's roughness 0.25"); } diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index 525296b3..8274f5d8 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -119,18 +119,24 @@ fn anchor_points_in_masks_record_the_mask_for_layers_above() { execute(&mut s, "effect.add.fill", &json!({"value": 0.4})).unwrap(); let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"target": "mask", "name": "Wear"})).unwrap(), "effect"); let layer = s.doc.project.layer(LayerId(low)).unwrap(); + assert!(layer.mask.as_ref().unwrap().effects.iter().any(|effect| effect.id.0 == anchor), "in the mask"); assert!(layer.content_effects.is_empty(), "not on the content"); // Without a target (or with no params at all) it still goes on the content, as before let content = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|effect| effect.id.0 == content)); + let bare = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|effect| effect.id.0 == bare)); // Folders take anchors in their masks only let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + assert!(execute(&mut s, "effect.add.anchor", &json!({"layer": folder})).is_err(), "folder content"); + execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap(); execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); @@ -202,12 +208,16 @@ fn mask_anchor_points_feed_layers_above_and_folders_take_them() { // No target (or null params) still goes on the content, named after the layer let content = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|effect| effect.id.0 == content)); assert_eq!(s.doc.project.effect(LayerId(content)).unwrap().1.name, name); + execute(&mut s, "effect.add.fill", &json!({"layer": low, "target": "mask", "value": 0.4})).unwrap(); let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low, "target": "mask"})).unwrap(), "effect"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.effect(LayerId(anchor)).is_none() && s.doc.project.layer(LayerId(low)).unwrap().mask.is_some(), "one undo step"); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); let mask = s.doc.project.layer(LayerId(low)).unwrap().mask.clone().unwrap(); let added = mask.effects.iter().find(|effect| effect.id.0 == anchor); @@ -220,21 +230,30 @@ fn mask_anchor_points_feed_layers_above_and_folders_take_them() { let reader = id(execute(&mut s, "effect.add.fill", &json!({"anchor": anchor, "anchorChannel": "baseColor"})).unwrap(), "effect"); let anchored = center(&mut s, Channel::BaseColor); execute(&mut s, "effect.set", &json!({"effect": reader, "value": 0.4})).unwrap(); + assert!(close(anchored, center(&mut s, Channel::BaseColor)), "{anchored:?}"); + execute(&mut s, "effect.set", &json!({"effect": reader, "anchor": anchor, "anchorChannel": "roughness"})).unwrap(); + assert!(close(anchored, center(&mut s, Channel::BaseColor)), "every channel reads the gray"); // Inspect lists what reads an anchor point let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(&format!("\"references\":[{{\"effect\":{reader},\"layer\":{top}}}]")), "{inspect}"); // Folders take mask anchor points, not content ones let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + assert!(execute(&mut s, "effect.add.anchor", &json!({"layer": folder})).is_err(), "a folder has no content stack"); + let folder_anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap(), "effect"); let folder_mask = s.doc.project.layer(LayerId(folder)).unwrap().mask.clone().unwrap(); + assert!(folder_mask.effects.iter().any(|effect| effect.id.0 == folder_anchor)); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); } @@ -264,36 +283,51 @@ fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.2})).unwrap(), "effect"); let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|effect| effect.id.0).collect::>(); + assert!(close(center(&mut s, Channel::Roughness), [0.2; 3]), "the fill covers the paint"); - // To the bottom, the paint shows again; an index past the end means the top. + + // To the bottom, the paint shows again; an index past the end means the top execute(&mut s, "effect.move", &json!({"effect": fill, "index": 0})).unwrap(); + assert_eq!(order(&s), [fill, paint]); assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); + execute(&mut s, "effect.move", &json!({"effect": fill, "index": 99})).unwrap(); + assert_eq!(order(&s), [paint, fill]); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(order(&s), [fill, paint]); assert!(execute(&mut s, "effect.move", &json!({"effect": fill})).is_err(), "index is required"); assert!(execute(&mut s, "effect.move", &json!({"effect": 999_999, "index": 0})).is_err()); - // A duplicate sits just above its original with the painted pixels, and takes the selection. + + // A duplicate sits just above its original with the painted pixels, and takes the selection execute(&mut s, "layer.select", &json!({"layer": layer, "target": paint})).unwrap(); let copy = id(execute(&mut s, "effect.duplicate", &json!({"effect": paint})).unwrap(), "effect"); + assert_eq!(order(&s), [fill, paint, copy]); assert_eq!(s.target, StackTarget::Effect(LayerId(copy))); assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy")); - // Undoing it leaves no missing effect selected, but the stack it was in. + + // Undoing it leaves no missing effect selected, but the stack it was in execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.target, StackTarget::Content); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes"); assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err()); - // Mask effects move within the mask. + + // Mask effects move within the mask execute(&mut s, "mask.add.black", &Value::Null).unwrap(); let a = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(), "effect"); let b = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); execute(&mut s, "effect.move", &json!({"effect": b, "index": 0})).unwrap(); let mask: Vec = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id.0).collect(); + assert_eq!(mask, [b, a]); } @@ -305,40 +339,54 @@ fn effects_copy_and_paste_between_layers_and_stacks() { execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + assert_eq!(execute(&mut s, "effect.copy", &Value::Null).unwrap(), json!({"copied": paint}), "the selected effect"); assert!(execute(&mut s, "layer.paste", &Value::Null).is_err(), "the clipboard holds an effect, not a layer"); - // Onto the content of a fill above that covers the first: its strokes come along. + + // Onto the content of a fill above that covers the first: its strokes come along let high = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); let pasted = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); + assert_eq!(s.target, StackTarget::Effect(LayerId(pasted))); assert!(s.doc.pixels.layer(LayerId(pasted), Channel::Roughness).is_some()); + execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); - // Above the selected effect. + + // Above the selected effect let inv = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); execute(&mut s, "effect.copy", &json!({"effect": inv})).unwrap(); execute(&mut s, "layer.select", &json!({"layer": high, "target": pasted})).unwrap(); let again = id(execute(&mut s, "effect.paste", &Value::Null).unwrap(), "effect"); let order: Vec = s.doc.project.layer(LayerId(high)).unwrap().content_effects.iter().map(|effect| effect.id.0).collect(); + assert_eq!(order, [pasted, again, inv]); - // A generator goes on a mask (made for it) even with the content selected; asking for the - // content is an error. Cut removes the original. + + // A generator needs a mask even when content is selected execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); let generator = id(execute(&mut s, "effect.add.generator", &Value::Null).unwrap(), "effect"); execute(&mut s, "effect.cut", &json!({"effect": generator})).unwrap(); + assert!(s.doc.project.effect(LayerId(generator)).is_none()); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &json!({"target": "content"})).is_err()); + execute(&mut s, "effect.paste", &Value::Null).unwrap(); let mask = &s.doc.project.layer(LayerId(low)).unwrap().mask; + assert!(mask.as_ref().is_some_and(|mask| mask.effects.iter().any(|effect| matches!(effect.kind, EffectKind::Generator(_))))); - // A fill reading an anchor point needs one below its new layer. + + // A fill reading an anchor point needs one below its new layer execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); execute(&mut s, "layer.select", &json!({"layer": high})).unwrap(); let reader = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "anchor": anchor})).unwrap(), "effect"); execute(&mut s, "effect.copy", &json!({"effect": reader})).unwrap(); execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &Value::Null).is_err(), "the anchor is on the layer itself"); } @@ -459,10 +507,12 @@ fn mask_fill_can_use_an_image_source() { // Adding a fill selects the imported image let fill = id(execute(&mut session, "effect.add.fill", &json!({"target": "mask", "image": brick})).unwrap(), "effect"); + assert!(matches!(fill_source(&session, fill), Source::Image { name, .. } if *name == brick), "{:?}", fill_source(&session, fill)); // Editing a fill selects a different image execute(&mut session, "effect.set", &json!({"effect": fill, "image": wood})).unwrap(); + assert!(matches!(fill_source(&session, fill), Source::Image { name, .. } if *name == wood), "{:?}", fill_source(&session, fill)); // Projection edits preserve the image source @@ -485,6 +535,7 @@ fn mask_fill_can_use_an_image_source() { // The Source menu's Uniform value action replaces an image source execute(&mut session, "effect.set", &json!({"effect": fill, "value": 0.25})).unwrap(); + assert!(matches!(fill_source(&session, fill), Source::Uniform(v) if (v[0] - 0.25).abs() < 1e-6), "{:?}", fill_source(&session, fill)); } @@ -495,11 +546,13 @@ fn content_levels_remap_the_channel_they_affect() { let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.8, 0.8], "roughness": 0.8})).unwrap(), "layer"); let levels_effect = id(execute(&mut s, "effect.add.levels", &json!({"target": "content", "outHigh": 0.5})).unwrap(), "effect"); let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"affects\":\"baseColor\""), "{inspected}"); assert!(close(center(&mut s, Channel::BaseColor), [0.4; 3]), "{:?}", center(&mut s, Channel::BaseColor)); assert!((center(&mut s, Channel::Roughness)[0] - 0.8).abs() < 1e-3, "roughness is not what it remaps"); execute(&mut s, "effect.set", &json!({"effect": levels_effect, "affects": "roughness"})).unwrap(); + assert!((center(&mut s, Channel::BaseColor)[0] - 0.8).abs() < 1e-3); assert!((center(&mut s, Channel::Roughness)[0] - 0.4).abs() < 1e-3); assert!(execute(&mut s, "effect.set", &json!({"effect": levels_effect, "affects": "normal"})).is_err(), "levels pass normal maps through"); @@ -512,19 +565,26 @@ fn content_levels_remap_the_channel_they_affect() { for visible in [false, true] { execute(&mut s, "effect.set", &json!({"effect": levels_effect, "visible": visible})).unwrap(); } + assert!((center(&mut s, Channel::BaseColor)[0] - 0.4).abs() < 1e-3); assert!((center(&mut s, Channel::Roughness)[0] - 0.4).abs() < 1e-3); // Past the white input handle: on, it stops at the output end; off, it carries on execute(&mut s, "effect.set", &json!({"effect": levels_effect, "affects": "baseColor", "inHigh": 0.6, "outHigh": 0.6, "clamp": true})).unwrap(); + assert!((center(&mut s, Channel::BaseColor)[0] - 0.6).abs() < 1e-3, "{:?}", center(&mut s, Channel::BaseColor)); + execute(&mut s, "effect.set", &json!({"effect": levels_effect, "clamp": false})).unwrap(); + assert!((center(&mut s, Channel::BaseColor)[0] - 0.8).abs() < 1e-3, "0.8 is a third past 0.6: {:?}", center(&mut s, Channel::BaseColor)); // A mask's levels remap its one value execute(&mut s, "mask.add.black", &json!({"layer": layer})).unwrap(); + assert!(execute(&mut s, "effect.add.levels", &json!({"target": "mask", "affects": "roughness"})).is_err()); + let mask_levels = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": mask_levels, "affects": "roughness"})).is_err()); } @@ -542,6 +602,7 @@ fn a_color_histogram_has_its_components_and_luminance() { let components: Vec> = histogram["components"].as_array().unwrap().iter().map(counts).collect(); let [red, green, blue] = &components[..] else { panic!("three components: {components:?}") }; let texels = red.last().copied().unwrap(); + assert!(texels > 0); assert_eq!([red, green, blue], [&vec![0, 0, 0, texels], &vec![texels, 0, 0, 0], &vec![texels, 0, 0, 0]]); assert_eq!(counts(&histogram["luminance"]), vec![0, texels, 0, 0], "red's luminance is 0.3"); diff --git a/crates/engine/tests/it/effect_blending.rs b/crates/engine/tests/it/effect_blending.rs index f90bd380..b2d2e2be 100644 --- a/crates/engine/tests/it/effect_blending.rs +++ b/crates/engine/tests/it/effect_blending.rs @@ -70,13 +70,17 @@ fn a_content_effect_blends_each_channel_on_its_own() { execute(&mut s, "effect.set", &json!({"effect": effect, "opacity": 1.0, "blend": "Normal"})).unwrap(); assert_close(center(&mut s, Channel::Roughness), [0.8; 3], "every channel back to normal at 100%"); assert_close(center(&mut s, Channel::BaseColor), [0.5; 3], "every channel back to normal at 100%"); + assert!(channel_blends(&mut s, layer, effect).is_null(), "no channel blends apart any more"); // Saved per channel, loaded as saved; an effect saved before has none execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply"})).unwrap(); let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); + let effect = s.doc.project.effect(LayerId(effect)).unwrap().1; + assert_eq!(effect.blend_of(Some(Channel::BaseColor)), effect.blend_of(None), "unset channels share the effect's blending"); } @@ -100,11 +104,13 @@ fn one_channels_blending_goes_to_every_channel_in_one_undo_step() { execute(&mut s, "effect.blending.bothToEveryChannel", &json!({"channel": "roughness"})).unwrap(); assert_close(center(&mut s, Channel::BaseColor), [0.5, 0.0, 0.0], "base color multiplies at full opacity"); + assert!(channel_blends(&mut s, layer, effect).is_null(), "every channel blends alike"); // Nothing left to change: no empty undo step let steps = s.history_labels().len(); execute(&mut s, "effect.blending.bothToEveryChannel", &json!({"channel": "roughness"})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "every channel already blends alike"); } @@ -114,29 +120,38 @@ fn channel_blending_copies_and_pastes_between_effects() { let mut s = session(); let (layer, effect) = layer_with_content_fill(&mut s); execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply", "opacity": 0.5})).unwrap(); + assert!(execute(&mut s, "effect.blending.paste", &json!({"effect": effect})).is_err(), "nothing copied yet"); + execute(&mut s, "effect.blending.copy", &json!({"effect": effect})).unwrap(); let other = id(execute(&mut s, "effect.add.fill", &json!({"layer": layer, "target": "content", "roughness": 0.8})).unwrap(), "effect"); execute(&mut s, "effect.blending.paste", &json!({"effect": other})).unwrap(); let pasted = s.doc.project.effect(LayerId(other)).unwrap().1; + assert_eq!(pasted.blend_of(Some(Channel::Roughness)), s.doc.project.effect(LayerId(effect)).unwrap().1.blend_of(Some(Channel::Roughness))); assert_eq!(pasted.blend_of(Some(Channel::BaseColor)), pasted.blend_of(None)); + let steps = s.history_labels().len(); execute(&mut s, "effect.blending.paste", &json!({"effect": other})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "pasting the blending it already has adds no undo step"); // A mask effect has one channel: it takes the shared blending and refuses a channel of its own execute(&mut s, "mask.add.white", &json!({"layer": layer})).unwrap(); let masked = id(execute(&mut s, "effect.add.fill", &json!({"layer": layer})).unwrap(), "effect"); execute(&mut s, "effect.blending.paste", &json!({"effect": masked})).unwrap(); + assert!(s.doc.project.effect(LayerId(masked)).unwrap().1.channel_blends.is_empty()); assert!(execute(&mut s, "effect.set", &json!({"effect": masked, "channel": "roughness", "opacity": 0.5})).is_err()); assert!(execute(&mut s, "effect.blending.modeToEveryChannel", &json!({"effect": masked})).is_err()); // Levels and anchor points have no blending let levels = id(execute(&mut s, "effect.add.levels", &json!({"layer": layer, "target": "content"})).unwrap(), "effect"); + assert!(execute(&mut s, "effect.blending.copy", &json!({"effect": levels})).is_err()); + execute(&mut s, "layer.select", &json!({"layer": layer, "target": levels})).unwrap(); + assert!((texturecraft_engine::commands::find("effect.blending.paste").unwrap().enabled)(&s).is_err(), "greyed for levels"); } diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index a69d3317..9bafe467 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -515,6 +515,7 @@ fn an_axis_planar_reading_a_pattern_is_not_placed() { let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); let effect = added["effect"].as_u64().unwrap(); execute(&mut s, "layer.fill.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); + assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); } diff --git a/crates/engine/tests/it/folder_contents.rs b/crates/engine/tests/it/folder_contents.rs index eb676eba..11ca86e9 100644 --- a/crates/engine/tests/it/folder_contents.rs +++ b/crates/engine/tests/it/folder_contents.rs @@ -51,35 +51,47 @@ fn a_folders_scale_and_rotation_lay_on_its_fills_without_changing_them_and_reset let steps = s.history_labels().len(); let set = execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 1.5, "rotation": 30.0})).unwrap(); + assert_eq!(set, json!({"scale": 1.5, "rotation": 30.0})); assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); assert_eq!(s.doc.project.contents_around(fill), ContentsOffset::new(1.5, 30.0)); assert_eq!(projection(&s, fill), own, "the fill keeps its own values"); + s.update(); let turned = base_colors(&s); assert_ne!(turned, before, "the fill renders scaled and turned"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""contents":{"rotation":30.0,"scale":1.5}"#), "{inspect}"); // A drag continues its step; one value given keeps the other execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "rotation": 400.0, "merge": true})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1); assert_eq!(s.doc.project.contents_offset(folder), ContentsOffset::new(1.5, 40.0)); // The values it already has add no step let unchanged = execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 1.5, "rotation": 40.0})).unwrap(); + assert_eq!(unchanged, json!({"scale": 1.5, "rotation": 40.0})); assert_eq!(s.history_labels().len(), steps + 1, "no step for the same values"); execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap(); + assert!(s.doc.project.contents_offset(folder).is_none()); + s.update(); + assert_eq!(base_colors(&s), before, "reset gives every fill its own back"); + let steps = s.history_labels().len(); execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "nothing to drop, no step"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.contents_offset(folder), ContentsOffset::new(1.5, 40.0)); // Only folders take an offset, and it needs a value @@ -98,13 +110,16 @@ fn randomize_seeds_gives_every_pattern_inside_a_new_seed_in_one_undo_step() { let steps = s.history_labels().len(); let out = execute(&mut s, "folder.randomizeSeeds", &json!({"layer": outer.0})).unwrap(); + assert_eq!(out["seeds"], 3); assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + let after = fill_seeds(&s, fill); assert!(after.0 != before.0 && after.2 != before.2, "{before:?} -> {after:?}"); assert_eq!(after.0, after.1, "channels on one seed stay on one seed"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill_seeds(&s, fill), before, "one undo takes every seed back"); // A folder with nothing seeded inside adds no step @@ -146,18 +161,23 @@ fn the_contents_reset_puts_back_the_seeds_randomize_seeds_changed_in_one_undo_st // Old projects: the record is saved with the folder and read back let saved = serde_json::to_value(&s.doc.project).unwrap(); + assert!(saved.to_string().contains("randomized"), "the folder keeps its seeds from before in the project"); let steps = s.history_labels().len(); execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); assert_eq!(fill_seeds(&s, fill), before, "every seed is back"); assert!(s.doc.project.contents_offset(folder).is_none(), "the Scale is dropped too"); assert!(!texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "nothing left to reset"); + s.update(); + assert_eq!(base_colors(&s), pictured, "the fill looks as it did before Randomize seeds"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(fill_seeds(&s, fill), randomized, "one undo brings the random seeds and the Scale back"); assert_eq!(s.doc.project.contents_offset(folder).scale, 2.0); @@ -173,8 +193,11 @@ fn the_contents_reset_puts_back_the_seeds_randomize_seeds_changed_in_one_undo_st fn a_folder_saved_without_randomized_seeds_opens_and_saves_unchanged() { let (s, folder, _) = folder_with_fill(); let saved = serde_json::to_value(&s.doc.project.layers[&folder]).unwrap(); + assert!(saved.to_string().contains("\"children\"") && !saved.to_string().contains("randomized"), "nothing new is written: {saved}"); + let read: texturecraft_engine::core::Layer = serde_json::from_value(saved.clone()).unwrap(); + assert!(matches!(&read.kind, LayerKind::Group { randomized, .. } if randomized.is_empty())); assert_eq!(serde_json::to_value(&read).unwrap(), saved); } diff --git a/crates/engine/tests/it/mask_fill_source.rs b/crates/engine/tests/it/mask_fill_source.rs index 71ad1384..e5e9a1c4 100644 --- a/crates/engine/tests/it/mask_fill_source.rs +++ b/crates/engine/tests/it/mask_fill_source.rs @@ -48,6 +48,7 @@ fn a_mask_fill_takes_a_procedural_an_image_an_alpha_or_a_value_as_its_one_graysc execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": kind.label(), "scale": 4.0})).unwrap(); let Source::Procedural { pattern, low, high, .. } = source(&s, effect) else { panic!("not a procedural: {:?}", source(&s, effect)) }; assert_eq!((pattern.kind, pattern.scale, low, high), (kind, 4.0, [0.0; 3], [1.0; 3])); + let line = mask_line(&s, layer); assert!(line.iter().any(|value| (value - line[0]).abs() > 1e-3), "the mask follows the pattern: {line:?}"); @@ -58,20 +59,26 @@ fn a_mask_fill_takes_a_procedural_an_image_an_alpha_or_a_value_as_its_one_graysc let scratches = alphas::find("scratches").unwrap(); execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "alpha": "scratches"})).unwrap(); + assert_eq!(source(&s, effect), Source::image(resource_name(scratches))); assert!(s.doc.resources.contains_key(&resource_name(scratches))); execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 0.25})).unwrap(); + assert_eq!(source(&s, effect), Source::Uniform([0.25; 3])); assert!(mask_line(&s, layer).iter().all(|value| (value - 0.25).abs() < 1e-3)); + execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 7.0})).unwrap(); + assert_eq!(source(&s, effect), Source::Uniform([1.0; 3]), "a mask value stays in 0..1"); let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("projectionSettings"), "inspect shows the mask fill's projection"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(source(&s, effect), Source::image(resource_name(scratches)), "each pick is one undo step"); } @@ -87,6 +94,7 @@ fn a_mask_fill_has_no_channels_or_material() { ] { assert!(execute(&mut s, "layer.fill.set", &refused).is_err(), "{refused}"); } + assert!(execute(&mut s, "layer.fill.material", &json!({"effect": effect.0, "material": null})).is_err()); assert_eq!(source(&s, effect), before); } @@ -95,11 +103,15 @@ fn a_mask_fill_has_no_channels_or_material() { fn a_mask_fill_is_projected_and_reset_like_any_fill() { let (mut s, _, effect) = mask_fill(); execute(&mut s, "layer.fill.projection", &json!({"effect": effect.0, "projection": "planar", "scale": 2.0, "symmetry": true})).unwrap(); + assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 2.0)); + let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("projectionSettings"), "inspect shows the mask fill's projection"); execute(&mut s, "layer.fill.resetProjection", &json!({"effect": effect.0})).unwrap(); + assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 1.0), "the reset keeps the projection, at its defaults"); match &s.doc.project.effect(effect).unwrap().1.kind { EffectKind::Fill { sampling, .. } => assert!(sampling.symmetry.on, "the reset keeps the Symmetry section"), @@ -107,6 +119,7 @@ fn a_mask_fill_is_projected_and_reset_like_any_fill() { } execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 2.0), "the reset is one undo step"); } @@ -126,19 +139,23 @@ fn a_procedural_source_is_made_at_its_resolution() { // A quarter of the texture set's size: the pattern is made at 128 × 128 and smoothed back up execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolutionFactor": -2})).unwrap(); + assert_eq!(resolution(&s, effect).factor, -2); + let coarse = mask_line(&s, layer); assert!(coarse.iter().zip(&every_texel).any(|(sampled, exact)| (sampled - exact).abs() > 1e-3), "{coarse:?} vs {every_texel:?}"); assert!(execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string().contains("\"resolution\""), "inspect shows it"); // Another parameter keeps it; a bad size is refused and changes nothing execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "contrast": 1.0})).unwrap(); + assert_eq!(resolution(&s, effect).factor, -2); assert!(execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolution": "big"})).is_err()); assert_eq!(resolution(&s, effect).factor, -2); // The default size again: every texel, as before execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolution": "auto", "resolutionFactor": 0})).unwrap(); + assert!(resolution(&s, effect).is_default()); assert_eq!(mask_line(&s, layer), every_texel); } @@ -147,6 +164,7 @@ fn a_procedural_source_is_made_at_its_resolution() { fn a_pattern_saved_before_resolutions_existed_reads_and_saves_unchanged() { let old = r#"{"kind":"Clouds","scale":4.0,"seed":1,"contrast":1.0,"balance":0.0,"invert":false}"#; let pattern: Procedural = serde_json::from_str(old).unwrap(); + assert_eq!(pattern, Procedural::new(ProceduralKind::Clouds)); assert_eq!(serde_json::to_string(&pattern).unwrap(), old, "no resolution, no new field in the file"); } diff --git a/crates/engine/tests/it/mask_paint_image.rs b/crates/engine/tests/it/mask_paint_image.rs index 61f16f29..97248d47 100644 --- a/crates/engine/tests/it/mask_paint_image.rs +++ b/crates/engine/tests/it/mask_paint_image.rs @@ -38,6 +38,7 @@ fn a_mask_stroke_paints_the_tools_image_gray_and_null_goes_back_to_the_value() { let (mut session, layer) = masked_layer(); let image = session.import_resource_bytes("halves.png", halves_png()).unwrap(); let set = execute(&mut session, "tool.material", &json!({"maskImage": image})).unwrap(); + assert_eq!(set["maskImage"], json!(image)); assert!(execute(&mut session, "tool.material", &json!({"maskImage": "missing.png"})).is_err(), "an unknown image is refused"); assert!(execute(&mut session, "tool.material", &json!({"maskImage": 3})).is_err()); @@ -48,8 +49,11 @@ fn a_mask_stroke_paints_the_tools_image_gray_and_null_goes_back_to_the_value() { // Back to one value: the next stroke paints white on the left too let set = execute(&mut session, "tool.material", &json!({"maskImage": null})).unwrap(); + assert_eq!(set["maskImage"], Value::Null); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.1, 0.5], [0.9, 0.5]]})).unwrap(); + assert!(mask_at(&session, layer, 0.25, 0.5) > 0.95); } @@ -114,6 +118,7 @@ fn a_mask_stroke_paints_the_image_it_began_with_when_the_resource_is_replaced_mi session.end_stroke().unwrap(); assert_eq!(replaced, image, "the white picture took the black one's name"); + let (left, right) = (mask_at(&session, layer, 0.25, 0.5), mask_at(&session, layer, 0.75, 0.5)); assert!(left < 0.05 && right < 0.05, "the whole stroke is black: left {left}, right {right}"); } diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index c22a0d42..26fcb753 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -133,6 +133,7 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); execute(&mut s, "effect.add.filter", &p).unwrap(); } + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite())); } diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index 9540e368..8889b7ae 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -62,8 +62,11 @@ fn importing_the_id_map_a_selection_reads_again_redraws_its_mask() { let mut session = session(); let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); selecting_layer(&mut session, &id_map); + assert!(red_in_the_view(&mut session), "white is selected"); + execute(&mut session, "resource.remove", &json!({"name": id_map})).unwrap(); + assert!(!red_in_the_view(&mut session), "no ID map, nothing selected"); let imported = session.import_resource_bytes("id.png", white_png()).unwrap(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 23efa4d4..b5ae16f0 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -257,10 +257,10 @@ fn panic_hunt() { if spec.id == "project.sample" { continue; // slow (bakes); covered elsewhere } + for p in &hostile { let mut s = session(); - // Match the 256px fixture: otherwise empty/irrelevant bake.run params perform - // repeated 2048px default bakes. Keep every input, ray count and fresh session. + // Match the 256px fixture so empty bake options cannot launch a 2048px bake for texture_set in &mut s.doc.project.texture_sets { texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256; } diff --git a/crates/paint/src/commit.rs b/crates/paint/src/commit.rs index e7df85cf..74742f5e 100644 --- a/crates/paint/src/commit.rs +++ b/crates/paint/src/commit.rs @@ -4,10 +4,10 @@ //! the stroke is drawn, so the commit itself is quick even at 8K. use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use rayon::prelude::*; -use texturecraft_compose::{MaskGray, PixelStore}; +use texturecraft_compose::{ImageRes, MaskGray, PixelStore}; use texturecraft_core::{Channel, ChannelKind, LayerId}; use texturecraft_texel::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed}; @@ -36,8 +36,8 @@ fn over(img: &mut TileImage, b: &Blend, src: &CommitSource, mut staged: Option = src.tiles.iter().map(|&t| (t, staged.as_mut().and_then(|s| s.take(image, src.alpha, &key, &empty, t)))).collect(); let updated: Vec<((u32, u32), Vec)> = tiles @@ -47,9 +47,11 @@ fn over(img: &mut TileImage, b: &Blend, src: &CommitSource, mut staged: Option return None, Some(Some(t)) => Some(t), @@ -74,6 +76,8 @@ fn blend_tile(dst: &mut [u16], components: usize, stroke_alpha: &[u16], (tx, ty) // The last component is the coverage, the ones before it the value let value_count = components.saturating_sub(1); let opacity = source.opacity.clamp(0.0, 1.0); + let gray_source = if source.erase || carried.is_some() { None } else { blend.gray }; + for i in 0..TILE_AREA { let mut weight = from_u16(stroke_alpha.get(i).copied().unwrap_or(0)) * opacity; if weight <= 0.0 { @@ -96,7 +100,7 @@ fn blend_tile(dst: &mut [u16], components: usize, stroke_alpha: &[u16], (tx, ty) } let Some((coverage_slot, values)) = dst.get_mut(i * components..(i + 1) * components).and_then(<[u16]>::split_last_mut) else { continue }; - let gray = blend.gray.map(|gray| gray.at(x, y, (source.alpha.width(), source.alpha.height()))); + let gray = gray_source.map(|gray| gray.at(x, y, (source.alpha.width(), source.alpha.height()))); let coverage = from_u16(*coverage_slot); for (component, slot) in values.iter_mut().enumerate() { let previous = dec(blend.kind, *slot); @@ -135,18 +139,32 @@ fn fill_from(dst: &mut Vec, from: Option<&[u16]>, empty: &[u16]) { } /// What a pre-blended tile was blended with, besides the stroke alpha. -#[derive(Clone, Debug, PartialEq)] +#[derive(Debug)] struct BlendKey { value: Vec, - image: Option, + image: Option<(Weak, (u32, u32))>, opacity: f32, erase: bool, } impl BlendKey { - fn new(b: &Blend, src: &CommitSource) -> BlendKey { - let image = b.gray.and_then(MaskGray::image_name).map(str::to_owned); - BlendKey { value: b.value.to_vec(), image, opacity: src.opacity, erase: src.erase } + fn new(blend: &Blend, source: &CommitSource) -> Self { + let image = match blend.gray { + Some(MaskGray::Image { image, .. }) if !source.erase => Some((Arc::downgrade(image), (source.alpha.width(), source.alpha.height()))), + _ => None, + }; + Self { value: blend.value.to_vec(), image, opacity: source.opacity, erase: source.erase } + } +} + +impl PartialEq for BlendKey { + fn eq(&self, other: &Self) -> bool { + let same_image = match (&self.image, &other.image) { + (Some((image, size)), Some((other_image, other_size))) => Weak::ptr_eq(image, other_image) && size == other_size, + (None, None) => true, + _ => false, + }; + same_image && self.value == other.value && self.opacity == other.opacity && self.erase == other.erase } } @@ -183,23 +201,25 @@ impl StagedImage { if !same(e.from.as_ref(), current) || e.data.len() != TILE_AREA * image.comps() { return None; } + if e.alpha.is_some() && self.key.as_ref() == Some(key) && same(e.alpha.as_ref(), alpha.tile_handle(t.0, t.1)) { return Some((e.data, true)); } + if e.alpha.is_some() { - // Blended with an older stroke alpha: back to the layer tile. + // Discard blends for superseded stroke alpha fill_from(&mut e.data, e.from.as_deref().map(Vec::as_slice), empty); } Some((e.data, false)) } /// Prepare the tiles `src.tiles` of `img` (re-blending those staged before): a copy of the - /// image tile, blended with the stroke when it has no per-texel source or carried values - /// (those blend at the commit). + /// image tile, blended with the stroke when it has no stencil or carried values + /// (those blend at the commit) fn stage(&mut self, img: Option<&TileImage>, comps: usize, b: &Blend, src: &CommitSource) { let key = BlendKey::new(b, src); if self.key.as_ref() != Some(&key) { - // The stroke's settings changed: earlier blends are void. + // A changed dependency invalidates the staged blend self.tiles.clear(); self.key = Some(key); } @@ -210,10 +230,12 @@ impl StagedImage { .into_par_iter() .filter_map(|((tx, ty), old)| { let from = img.and_then(|i| i.tile_handle(tx, ty)); - // Erasing never allocates a tile. + + // Erasing can only change an existing tile if from.is_none() && src.erase { return None; } + let mut data = old.map(|o| o.data).unwrap_or_default(); fill_from(&mut data, from.map(|f| f.as_slice()), &empty); let alpha = src.alpha.tile_handle(tx, ty).filter(|_| blend).cloned(); @@ -394,6 +416,7 @@ mod tests { commit_mask(&mut px, LayerId(9), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); let before = px.clone(); commit_mask(&mut px, LayerId(9), (64, 64), &MaskGray::Value(0.0), src(&a, &tiles, 1.0, true), &mut Staging::default()); + assert_eq!(from_u16(before.masks[&LayerId(9)].get(5, 5)[1]), 1.0); assert_eq!(px.masks[&LayerId(9)].get(5, 5)[1], 0); } @@ -439,9 +462,7 @@ mod tests { commit_layer(&mut base, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default()); commit_mask(&mut base, LayerId(2), (64, 64), &MaskGray::Value(0.5), src(&a, &tiles, 1.0, false), &mut Staging::default()); let carried: BTreeMap = vals.keys().map(|c| (*c, a.clone())).collect(); - // Staged when the stroke started, then again after the alpha changed (pre-blended - // tiles re-blend), and staged once more with its last alpha change left out (that - // tile blends at the commit): the commit matches an unstaged one. + // The final unstaged alpha change still belongs in the commit for (erase, carry, stage_last) in [(false, false, true), (true, false, true), (false, false, false), (false, true, true)] { let mut a = a.clone(); let mut staged = base.clone(); @@ -462,10 +483,10 @@ mod tests { commit_mask(&mut plain, LayerId(2), (64, 64), &MaskGray::Value(1.0), source(&a, &tiles, c, erase), &mut Staging::default()); commit_layer(&mut staged, LayerId(1), (64, 64), &vals, source(&a, &tiles, c, erase), &mut staging); commit_mask(&mut staged, LayerId(2), (64, 64), &MaskGray::Value(1.0), source(&a, &tiles, c, erase), &mut staging); + assert_eq!((&staged.layers, &staged.masks), (&plain.layers, &plain.masks), "erase {erase}, carried {carry}, staged last {stage_last}"); } - // Tiles staged before the layer changed or with another value are stale: the commit - // reads the current tile. + // The commit must read the current tile when its staged values are stale let mut px = base.clone(); let mut staging = Staging::default(); staging.stage_layer(&px, LayerId(1), &vals, &src(&a, &tiles, 1.0, false)); @@ -476,6 +497,7 @@ mod tests { commit_mask(&mut expected, LayerId(2), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); commit_layer(&mut px, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut staging); commit_mask(&mut px, LayerId(2), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut staging); + assert_eq!((&px.layers, &px.masks), (&expected.layers, &expected.masks)); } @@ -495,14 +517,18 @@ mod tests { let mut plain = PixelStore::default(); commit_mask(&mut plain, LayerId(4), (64, 64), &image("scratches", 0.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); + assert!(gray_at(&plain, 16) < 0.05 && gray_at(&plain, 48) > 0.95, "left {} right {}", gray_at(&plain, 16), gray_at(&plain, 48)); - // Staged with another image first: the commit blends the image it is given + // A resource replaced under the same name must invalidate its staged blend let mut staged = PixelStore::default(); let mut staging = Staging::default(); + let previous_image = image("scratches", 0.5); staging.stage_mask(&staged, LayerId(4), &image("other", 0.5), &src(&a, &tiles, 1.0, false)); - staging.stage_mask(&staged, LayerId(4), &image("scratches", 0.0), &src(&a, &tiles, 1.0, false)); + staging.stage_mask(&staged, LayerId(4), &previous_image, &src(&a, &tiles, 1.0, false)); + commit_mask(&mut staged, LayerId(4), (64, 64), &image("scratches", 0.0), src(&a, &tiles, 1.0, false), &mut staging); + assert_eq!(staged.masks, plain.masks); } } diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index e8a44942..11635fcc 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -149,7 +149,16 @@ impl EnvImage { /// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the /// pixel count does not match the size. pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option { - if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 { + Self::from_pixels(width, height, rgba, srgb) + } + + /// An imported linear RGB equirect image, with the same validation and size limits as [Self::from_rgba]. + pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option { + Self::from_pixels(width, height, rgb, false) + } + + fn from_pixels(width: u32, height: u32, pixels: &[[f32; COMPONENTS]], srgb: bool) -> Option { + if width == 0 || height == 0 || pixels.len() as u64 != width as u64 * height as u64 { return None; } let lin = |v: f32| { diff --git a/crates/ui-egui/src/anchor_properties.rs b/crates/ui-egui/src/anchor_properties.rs index 98ecd292..360bef5b 100644 --- a/crates/ui-egui/src/anchor_properties.rs +++ b/crates/ui-egui/src/anchor_properties.rs @@ -13,6 +13,7 @@ use crate::reference::Reference; /// The properties of anchor point `anchor` named `name`; renaming goes through `effect.set`, a reference's click through `layer.select` pub(crate) fn anchor_properties(app: &mut TextureCraftApp, ui: &mut Ui, anchor: LayerId, name: &str) { let references = references(&app.session.doc.project, anchor); + PropertySheet::show(ui, ("anchor_sheet", anchor.0), |sheet| { sheet.section(tr("Anchor point"), false); if let Some(renamed) = sheet.name_field(tr("Anchor point name"), name) { @@ -44,13 +45,18 @@ fn references(project: &Project, anchor: LayerId) -> Vec { let (kind, glyph) = match effect { None if matches!(layer.kind, LayerKind::Fill(_)) => (n_("Fill"), ic::PAINT_BUCKET), None => return None, - Some(effect) => { - let in_content = layer.content_effects.iter().any(|content_effect| content_effect.id == effect); - match project.effect(effect).map(|(_, found)| &found.kind) { - Some(EffectKind::Fill { .. } | EffectKind::Material(_)) if in_content => (n_("Fill"), ic::PAINT_BUCKET), - Some(EffectKind::Fill { .. }) => (n_("Mask fill"), ic::PAINT_BUCKET), - Some(other) => (other.name(), reader_glyph(other)), - None => return None, + Some(effect_id) => { + let in_mask = layer.mask.iter().flat_map(|mask| &mask.effects).find(|effect| effect.id == effect_id); + let (found, in_content) = if let Some(mask_effect) = in_mask { + (mask_effect, false) + } else { + (layer.content_effects.iter().find(|effect| effect.id == effect_id)?, true) + }; + + match &found.kind { + EffectKind::Fill { .. } | EffectKind::Material(_) if in_content => (n_("Fill"), ic::PAINT_BUCKET), + EffectKind::Fill { .. } => (n_("Mask fill"), ic::PAINT_BUCKET), + other => (other.name(), reader_glyph(other)), } } }; diff --git a/crates/ui-egui/src/compare_properties.rs b/crates/ui-egui/src/compare_properties.rs index 74e7029c..c92d7351 100644 --- a/crates/ui-egui/src/compare_properties.rs +++ b/crates/ui-egui/src/compare_properties.rs @@ -84,10 +84,9 @@ pub(crate) fn compare_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: } if sheet.band(tr("Source histograms"), true, None, None).open { - let histograms = histogram_counts(app, sheet.ui, effect_id); - // A constant has no spread: it shows as a line at its value in its side's colour let constants = [left, right].map(|side| (side == CompareSource::Constant).then_some(constant)); + let histograms = if constants.contains(&None) { histogram_counts(app, sheet.ui, effect_id) } else { None }; sheet.embed(|ui| source_histograms(ui, histograms.as_deref(), constants)); } }); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e38c7749..0dc5bc7f 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2835,6 +2835,7 @@ fn mask_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, e else { return; }; + PropertySheet::show(ui, ("mask_fill_sheet", effect_id.0), |sheet| { crate::mask_fill_panel::mask_fill_sheet(app, sheet, effect_id, source, projection, sampling, layer.id); }); diff --git a/crates/ui-egui/src/folder_properties.rs b/crates/ui-egui/src/folder_properties.rs index b205fc0e..bc2ddae6 100644 --- a/crates/ui-egui/src/folder_properties.rs +++ b/crates/ui-egui/src/folder_properties.rs @@ -28,16 +28,19 @@ pub(crate) fn folder_properties(app: &mut TextureCraftApp, ui: &mut Ui, folder: if sheet.section_reset(tr("Contents"), changed) { app.run("folder.contents.reset", json!({"layer": folder.0})); } + let (low, high) = ContentsOffset::SCALE_RANGE; let mut scale = offset.scale; if let Some(merge) = sheet.factor_slider(tr("Scale"), &mut scale, SCALE_DOUBLINGS, low..=high) { app.run("folder.contents.set", json!({"layer": folder.0, "scale": scale, "merge": merge})); } + let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE; let mut rotation = offset.rotation; if let Some(merge) = sheet.relative_angle(tr("Rotation"), &mut rotation, turn_start..=turn_end) { app.run("folder.contents.set", json!({"layer": folder.0, "rotation": rotation, "merge": merge})); } + if sheet.button(ic::DICE_FIVE, tr("Randomize seeds")).clicked() { app.run("folder.randomizeSeeds", json!({"layer": folder.0})); } diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index dce44a17..8195344c 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -102,6 +102,8 @@ pub struct GpuLink { aux: BTreeMap, /// Image identity without holding its decoded pixels alive. aux_image: Option>, + /// Weak identity of the last uploaded ID mask image. + aux_id_mask: Option>, /// The display kinds sent to the GPU per set: kinds the set has no channels for are not /// converted, unless an earlier upload gave them content that must be overwritten. Only the /// renderer recreating a set's textures ([`GpuState::recreated`]) replaces its entry with @@ -165,6 +167,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { env: Default::default(), aux: BTreeMap::new(), aux_image: None, + aux_id_mask: None, sent: HashMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, @@ -211,6 +214,7 @@ impl GpuLink { out.mesh = Some((session.mesh.clone(), session.mesh_id)); self.mesh_id = session.mesh_id; self.aux.clear(); + self.aux_id_mask = None; } let sets: Vec = session.doc.project.texture_sets.iter().map(|texture_set| (texture_set.size(), texture_set.material)).collect(); @@ -287,6 +291,10 @@ impl GpuLink { self.aux.retain(|_, (view, _)| view != "image"); } + if self.aux_id_mask.as_ref().is_some_and(|image| image.strong_count() == 0) { + self.aux_id_mask = None; + } + match aux_map { Some(AuxView::MeshMap(map)) => self.sync_mesh_maps(session, map, None, &mut out), Some(AuxView::IdMask(effect)) => { @@ -397,16 +405,24 @@ impl GpuLink { /// Queues the image color selection `effect` reads as its ID mask on its texture set; the texture set it shows on, None when it reads the ID mesh map fn sync_id_mask(&mut self, session: &Session, effect: LayerId, out: &mut SceneSync) -> Option { - let (texture_set, image) = session.id_mask_image(effect)?; + let Some((texture_set, image)) = session.id_mask_image(effect) else { + self.aux_id_mask = None; + return None; + }; + let cache = session.caches.get(texture_set)?; let resolution = texturecraft_render::aux_size(cache.size); let key = (format!("idMask{}:{resolution}", effect.0), Arc::as_ptr(image) as u64); - if self.aux.get(&texture_set) != Some(&key) + let same_image = self.aux_id_mask.as_ref().is_some_and(|previous| std::ptr::eq(previous.as_ptr(), Arc::as_ptr(image))); + if (!same_image || self.aux.get(&texture_set) != Some(&key)) && let Some(rgba) = session.id_mask_view_rgba(effect, resolution) { out.aux.push((texture_set, resolution, rgba)); self.aux.insert(texture_set, key); + // A weak owner keeps the address unique without retaining the decoded pixels + self.aux_id_mask = Some(Arc::downgrade(image)); } + Some(texture_set) } } @@ -575,6 +591,7 @@ mod tests { env: Default::default(), aux: BTreeMap::new(), aux_image: None, + aux_id_mask: None, sent: HashMap::new(), adapter: String::new(), composite_total: 0, @@ -643,13 +660,17 @@ mod tests { let out = gpu.sync(&mut s, Some(AuxView::Image), None, 0, 0.0); assert_eq!(out.image_aux.len(), 1, "equal resolutions share a single pixel buffer"); + let (targets, bytes) = out.image_aux.values().next().unwrap(); + assert!(targets.len() > 1); assert_eq!(targets.len(), s.caches.len()); assert!(bytes.as_chunks::<4>().0.iter().all(|pixel| *pixel == [9, 9, 9, 255])); + drop(out); let out = gpu.sync(&mut s, Some(AuxView::Image), None, 0, 0.0); assert!(out.image_aux.is_empty(), "nothing is sent again while the view stays"); + drop(out); // The renderer recreates a resized set's textures blank, in the same frame as this sync @@ -663,6 +684,7 @@ mod tests { // Switching images leaves the previous decoded image owned only by the session let original = Arc::downgrade(s.images.get(&name).unwrap()); execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); + assert!(original.upgrade().is_none(), "even a pending upload does not hold the decoded source"); assert!(gpu.sync(&mut s, None, None, 0, 0.0).image_aux.is_empty()); assert!(gpu.aux_image.is_none()); @@ -675,6 +697,54 @@ mod tests { assert!(updated.image_aux.values().all(|(_, pixels)| pixels.as_chunks::<4>().0.iter().all(|pixel| *pixel == [255, 0, 0, 255]))); } + #[test] + fn the_id_mask_view_uploads_reimported_pixels_even_if_the_address_was_reused() { + let mut gpu = link(); + let mut session = session(false); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let selection = execute(&mut session, "effect.add.colorSelection", &json!({})).unwrap(); + let effect = LayerId(selection["effect"].as_u64().unwrap()); + let resource = "selection.png"; + let image = |color| Arc::new(ImageRes::new(1, 1, vec![color], false)); + session.images.insert(resource.into(), image([1.0, 0.0, 0.0, 1.0])); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": resource})).unwrap(); + + let first = gpu.sync(&mut session, Some(AuxView::IdMask(effect)), None, 0, 0.0); + + assert!(first.aux[0].2.as_chunks::<4>().0.iter().all(|pixel| *pixel == [255, 0, 0, 255])); + + let (set, original) = session.id_mask_image(effect).unwrap(); + let retired = Arc::downgrade(original); + drop(session.images.remove(resource)); + + assert!(retired.upgrade().is_none(), "upload ownership must drop independently of decoded source pixels"); + + let replacement = image([0.0, 0.0, 1.0, 1.0]); + // Simulate an allocator returning the previous address for the new image + gpu.aux.get_mut(&set).unwrap().1 = Arc::as_ptr(&replacement) as u64; + session.images.insert(resource.into(), replacement); + + let updated = gpu.sync(&mut session, Some(AuxView::IdMask(effect)), None, 0, 0.0); + + assert_eq!(updated.aux.len(), 1, "replacement pixels must be sent even when the raw address key matches"); + assert!(updated.aux[0].2.as_chunks::<4>().0.iter().all(|pixel| *pixel == [0, 0, 255, 255])); + assert!(gpu.sync(&mut session, Some(AuxView::IdMask(effect)), None, 0, 0.0).aux.is_empty()); + + gpu.sync(&mut session, None, None, 0, 0.0); + + assert!(gpu.sync(&mut session, Some(AuxView::IdMask(effect)), None, 0, 0.0).aux.is_empty(), "an unchanged pick reuses the existing upload"); + + let (_, active) = session.id_mask_image(effect).unwrap(); + let active = Arc::downgrade(active); + drop(session.images.remove(resource)); + + assert!(active.upgrade().is_none(), "only the resource store owns the decoded pixels"); + + gpu.sync(&mut session, None, None, 0, 0.0); + + assert!(gpu.aux_id_mask.is_none(), "the upload identity expires with the removed image"); + } + fn kinds(out: &SceneSync) -> BTreeSet { out.tiles.iter().filter(|t| t.0 == 0).map(|t| t.1).collect() } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index db514466..a3671aee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1074,7 +1074,7 @@ impl eframe::App for TextureCraftApp { self.poll_link_cooks(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_link_imports(ctx); - self.thumbs.sync_images(&self.session.images, self.session.revision); + self.thumbs.sync_project_previews(&self.session); // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true); diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs index b42bdbfb..84602e32 100644 --- a/crates/ui-egui/src/move_on_model.rs +++ b/crates/ui-egui/src/move_on_model.rs @@ -368,6 +368,7 @@ mod tests { let mut pointer = press_the_button(&mut harness); assert_eq!(harness.state().moving_on_model, Some(MoveOnModel { layer, effect: Some(LayerId(effect)) }), "a press starts the hold"); + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); let_go(&mut harness, &mut pointer); diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index 432e1857..d74186f0 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -33,9 +33,13 @@ impl OrbEnvironment { fn from_hdr(bytes: &[u8]) -> Option { let decoded = image::load_from_memory_with_format(bytes, image::ImageFormat::Hdr).inspect_err(|e| log::warn!("the orb studio did not load: {e}")).ok()?; - let rgb = decoded.to_rgb32f(); - let rgba: Vec<[f32; 4]> = rgb.pixels().map(|pixel| [pixel[0], pixel[1], pixel[2], 1.0]).collect(); - EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false).map(|env| OrbEnvironment::of(&env)) + + let rgb = decoded.into_rgb32f(); + let (pixels, _) = rgb.as_raw().as_chunks::<3>(); + let env = EnvImage::from_linear_rgb(rgb.width(), rgb.height(), pixels)?; + drop(rgb); + + Some(OrbEnvironment::of(&env)) } /// The built-in procedural studio, should the bundled one ever fail to decode diff --git a/crates/ui-egui/src/property_sheet/action_row.rs b/crates/ui-egui/src/property_sheet/action_row.rs index 8eaf51cd..4f26126f 100644 --- a/crates/ui-egui/src/property_sheet/action_row.rs +++ b/crates/ui-egui/src/property_sheet/action_row.rs @@ -43,6 +43,7 @@ impl PropertySheet<'_> { let painter = self.ui.painter(); painter.rect(button, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); painter.text(button.center(), Align2::CENTER_CENTER, *word, font.clone(), if *enabled { tokens.text } else { tokens.text_dim }); + self.paint_control_focus(&response); x = button.right() + BUTTON_GAP; } @@ -54,9 +55,11 @@ impl PropertySheet<'_> { if response.clicked() { *on = !*on; } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, toggle_label)); self.ui.painter().text(pos2(label_end, center_y), Align2::RIGHT_CENTER, toggle_label, font, tokens.text); self.pill(pill, *on, true); + self.paint_control_focus(&response); ActionRowResponse { clicked, toggled: response.clicked() } } } diff --git a/crates/ui-egui/src/property_sheet/id_color_row.rs b/crates/ui-egui/src/property_sheet/id_color_row.rs index 17095786..5017212f 100644 --- a/crates/ui-egui/src/property_sheet/id_color_row.rs +++ b/crates/ui-egui/src/property_sheet/id_color_row.rs @@ -1,4 +1,4 @@ -//! One ID color of a color selection: its swatch (the eyedropper that picks it again), its R G B, and a × while hovered +//! One ID color of a color selection: its swatch, its RGB values, and a Remove button use egui::{Align2, Color32, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, pos2, vec2}; use egui_phosphor::regular as ic; @@ -63,6 +63,7 @@ impl PropertySheet<'_> { let color = Color32::from_rgb(red, green, blue); let painter = self.ui.painter().clone(); painter.rect_filled(swatch, CornerRadius::same(SWATCH_RADIUS), color); + if enabled && (hovered || repicking) { // Rec. 709 luminance let luminance = (0.2126 * f32::from(red) + 0.7152 * f32::from(green) + 0.0722 * f32::from(blue)) / 255.0; @@ -77,14 +78,14 @@ impl PropertySheet<'_> { painter.text(pos2(x + LETTER_TO_VALUE, center_y), Align2::LEFT_CENTER, value.to_string(), FontId::proportional(TEXT_SIZE), tokens.text); } - // The × answers only while the row is hovered, so it never takes a click meant for the row under a moving pointer + // Keep Remove in the focus order even while the pointer is outside the row let remove = Rect::from_center_size(pos2(self.right - REMOVE_INSET, center_y), vec2(GLYPH_TARGET, GLYPH_TARGET)); let remove_id = self.next_id(); let remove_tip = crate::i18n::tr("Remove"); - let remove_response = self.ui.interact(remove, remove_id, if hovered { Sense::click() } else { Sense::hover() }); - remove_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, hovered, format!("{remove_tip} {}", readout()))); + let remove_response = self.ui.interact(remove, remove_id, Sense::click()); + remove_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{remove_tip} {}", readout()))); let remove_response = self.tip(remove_response, remove_tip); - if hovered { + if hovered || remove_response.has_focus() { painter.text( remove.center(), Align2::CENTER_CENTER, @@ -93,7 +94,11 @@ impl PropertySheet<'_> { if remove_response.hovered() { tokens.text } else { tokens.text_dim }, ); } + + self.paint_control_focus(&swatch_response); + self.paint_control_focus(&remove_response); self.drawn(swatch.bottom()); - IdColorRowResponse { repick: swatch_response.clicked(), remove: hovered && remove_response.clicked() } + + IdColorRowResponse { repick: swatch_response.clicked(), remove: remove_response.clicked() } } } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 91478700..fc155266 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -162,6 +162,67 @@ fn toggles_switches_and_pills_change_their_state() { assert_eq!(harness.state().channels, [true, true, true, true, true]); } +#[test] +fn keyboard_focus_is_visible_on_switches_toggles_and_channel_pills() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for brightness in [Brightness::MediumDark, Brightness::Light] { + let mut harness = builder(brightness).build_ui(|ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "keyboard", |sheet| { + sheet.switch("Scale", &["Tiling", "Physical size"], 0); + sheet.toggle("Shape Crop", &mut false); + sheet.channel_pills(&["Normal"], &[true]); + }); + }); + harness.run_steps(3); + + for label in ["Tiling", "Physical size", "Shape Crop", "Normal"] { + harness.key_press(egui::Key::Tab); + harness.run_steps(2); + + let node = harness.get_by_label(label); + assert!(node.is_focused(), "{label} receives keyboard focus"); + + let rect = node.rect(); + assert!( + harness.output().shapes.iter().any(|clipped| { + matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.stroke.width > 1.0 && shape.rect.center().distance(rect.center()) < 1.0) + }), + "{label} paints a visible focus outline" + ); + } + } +} + +#[test] +fn keyboard_can_remove_an_id_color_without_hovering_the_row() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui_state( + |ui, removed| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "keyboard", |sheet| { + if !*removed { + *removed = sheet.id_color_row([10, 20, 30], false, true).remove; + } + }); + }, + false, + ); + harness.run_steps(3); + + for label in ["Pick color R 10 G 20 B 30", "Remove R 10 G 20 B 30"] { + harness.key_press(egui::Key::Tab); + harness.run_steps(2); + + assert!(harness.get_by_label(label).is_focused(), "{label} receives keyboard focus"); + } + harness.key_press(egui::Key::Space); + harness.run_steps(2); + + assert!(*harness.state(), "Space activates the focused Remove button"); + assert!(harness.query_by_label("Remove R 10 G 20 B 30").is_none()); +} + /// A toggle's pill starts on the controls column, where a dropdown's button starts (it sat 3 px in) #[test] fn a_toggles_pill_starts_where_a_dropdown_starts() { diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index 26d86bf8..a52838f4 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -719,6 +719,7 @@ pub(crate) mod tests { let from = on_the_model_off_the_handles(&harness); drag(&mut harness, from, from + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(effect_projection(&harness, effect), before, "{kind}: a drag off the handles leaves the projection alone"); assert_eq!(harness.state().session.history_labels().len(), steps, "{kind}: and adds no undo step"); @@ -727,6 +728,7 @@ pub(crate) mod tests { None => crate::frame_gizmo::FrameGizmo::of(harness.state(), rect).unwrap_or_else(|| panic!("{kind}: a gizmo shows")).center, }; drag(&mut harness, center, center + vec2(0.0, -30.0), Modifiers::NONE); + assert_ne!(effect_projection(&harness, effect), before, "{kind}: the centre square moves it"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "{kind}: one step, no stroke"); } diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index b85e073a..08bec6bf 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -7,6 +7,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; +use texturecraft_engine::Session; use texturecraft_engine::compose::{ImageRes, ImageStore}; use texturecraft_engine::core::{BakedMap, ProceduralKind}; use texturecraft_engine::paint::presets::BrushPreset; @@ -50,6 +51,7 @@ pub struct Thumbs { saved_files_epoch: u64, images: HashMap, TextureHandle)>, images_revision: Option, + preview_session: Option<(u64, u64)>, /// Each texture set's ID mesh map preview, with the map it shows (a rebake's new map replaces it) id_maps: HashMap>, TextureHandle)>, /// (frame, thumbnails rendered in it) @@ -143,6 +145,27 @@ impl Thumbs { }); } + /// Keep project previews only while they refer to current resources or bake maps. + pub(crate) fn sync_project_previews(&mut self, session: &Session) { + let current = (session.project_id, session.revision); + let previous = self.preview_session.replace(current); + if previous == Some(current) { + return; + } + + // Two projects can have the same revision + if previous.is_none_or(|(project, _)| project != session.project_id) { + self.images_revision = None; + self.id_maps.clear(); + } + + self.sync_images(&session.images, session.revision); + self.id_maps.retain(|&set, (shown, _)| { + set < session.doc.project.texture_sets.len() + && session.baked(set).and_then(|baked| baked.maps.get(&BakedMap::Id)).is_some_and(|map| std::ptr::eq(shown.as_ptr(), Arc::as_ptr(map))) + }); + } + /// 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(); @@ -661,4 +684,31 @@ mod tests { assert_eq!(shared, first, "the same map keeps its cached preview"); assert_ne!(rebaked, first, "a new map of the same texture set, even of equal texels, gets a new preview"); } + + #[test] + fn dropped_bakes_and_replaced_projects_release_their_id_preview_textures() { + use texturecraft_engine::geom::primitives; + + let ctx = egui::Context::default(); + let mut thumbs = Thumbs::default(); + let mut project = Session::new_project("A", primitives::material_ball(), "builtin:materialBall", None, 128).unwrap(); + project.doc.baked.insert(0, id_map()); + project.doc.baked.insert(1, id_map()); + thumbs.sync_project_previews(&project); + let first = thumbs.id_mesh_map(&ctx, 0, project.baked(0).unwrap()).unwrap().id(); + let second = thumbs.id_mesh_map(&ctx, 1, project.baked(1).unwrap()).unwrap().id(); + + let _undo_map = project.doc.baked.remove(&0).unwrap(); + project.revision += 1; + thumbs.sync_project_previews(&project); + + assert!(ctx.tex_manager().read().meta(first).is_none(), "an undo-owned map does not need a preview"); + assert!(ctx.tex_manager().read().meta(second).is_some(), "a live bake keeps its texture"); + + let mut replacement = Session::new_project("B", primitives::plane(2.0, 2), "builtin:plane", None, 128).unwrap(); + replacement.revision = project.revision; + thumbs.sync_project_previews(&replacement); + + assert!(ctx.tex_manager().read().meta(second).is_none(), "a different project with the same revision releases the old texture"); + } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 47b7ab56..a2a018c1 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2644,8 +2644,11 @@ mod tests { harness.run_steps(2); crate::id_color_pick::IdColorPick::start(harness.state_mut(), effect, None); + assert_eq!(aux_view(harness.state()), Some(crate::gpu::AuxView::IdMask(effect)), "the pick's own ID mask"); + crate::id_color_pick::IdColorPick::end(harness.state_mut()); + assert_eq!(aux_view(harness.state()), None, "the earlier view"); } diff --git a/crates/ui-egui/tests/it/anchor_point.rs b/crates/ui-egui/tests/it/anchor_point.rs index 2e7d7f3a..6fcce487 100644 --- a/crates/ui-egui/tests/it/anchor_point.rs +++ b/crates/ui-egui/tests/it/anchor_point.rs @@ -46,17 +46,22 @@ fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { fn the_name_field_renames_on_enter_in_one_undo_step_and_escape_keeps_it() { let (mut harness, anchor, _, _) = anchor_harness(); assert_eq!(anchor_name(&harness, anchor), "Cavity Dirt mask", "a mask anchor point is named after its layer"); + let steps = harness.state().session.history_labels().len(); type_name(&mut harness, "Edges"); + assert_eq!(anchor_name(&harness, anchor), "Cavity Dirt mask", "nothing changes while typing"); + harness.key_press(Key::Enter); harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); type_name(&mut harness, "Never applied"); harness.key_press(Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges", "Escape keeps the name"); } @@ -64,8 +69,10 @@ fn the_name_field_renames_on_enter_in_one_undo_step_and_escape_keeps_it() { fn a_click_on_a_reference_selects_what_reads_the_anchor_point() { let (mut harness, _, top, reader) = anchor_harness(); assert!(harness.state().session.selected_layer() != Some(top)); + harness.get_by_role_and_label(Role::Button, "Rust Mask fill").click(); harness.run_steps(REDRAW_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(top)); assert_eq!(harness.state().session.target, StackTarget::Effect(reader)); } @@ -98,6 +105,7 @@ fn a_name_typed_then_left_with_shift_tab_is_kept() { // The focus moves back to a control drawn before the field: the field never sees itself focused again harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab); harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges", "the typed name is kept"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "in one undo step"); } diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 8a946e94..b3d5274d 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -110,12 +110,14 @@ fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { let (mut harness, effect) = app_with_color_selection(true); harness.get_by_label(PICK_COLOR).click(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_id_color.is_some_and(|pick| pick.effect == effect && pick.index.is_none())); assert_eq!(harness.state().session.view, ViewMode::MeshMap(BakedMap::Id)); let center = harness.state().viewport_rect.center(); harness.event(Event::PointerMoved(center)); harness.run_steps(2); + assert!(eyedropper_at(&harness, center), "the pointer is an eyedropper"); click_at(&mut harness, center); @@ -134,6 +136,7 @@ fn without_an_id_map_picking_is_off() { harness.run_steps(SETTLE_FRAMES); let repick = row_button(&harness, FIRST, "Pick color"); click_at(&mut harness, repick); + assert!(harness.state().picking_id_color.is_none()); assert_eq!(colors(&harness, effect).len(), 3); } @@ -148,6 +151,7 @@ fn removing_a_row_cancels_a_pending_replacement() { let (mut harness, effect) = app_with_color_selection(true); let repick = row_button(&harness, SECOND, "Pick color"); click_at(&mut harness, repick); + assert_eq!(harness.state().picking_id_color.unwrap().index, Some(1)); let remove = row_button(&harness, FIRST, "Remove"); @@ -185,9 +189,11 @@ fn escape_cancels_id_picking_with_a_hidden_rail_popup() { harness.get_by_role_and_label(egui::Role::Button, "Close"); harness.key_press(egui::Key::Tab); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.hide_ui); assert!(harness.query_by_role_and_label(egui::Role::Button, "Close").is_none()); assert!(harness.state().picking_id_color.is_some()); + let history = harness.state().session.history_labels(); harness.key_press(egui::Key::Escape); @@ -212,9 +218,12 @@ fn picking_from_the_popup_closes_it_before_the_viewport_click() { click_at(&mut harness, pick); assert!(harness.state().picking_id_color.is_some()); + let center = harness.state().viewport_rect.center(); assert!(popup.contains(center), "pick a point the popup would otherwise cover"); + click_at(&mut harness, center); + assert_eq!(colors(&harness, effect).len(), 4, "the next viewport click must pick, even under the former popup"); assert_eq!(harness.state().properties_popup, None); } @@ -236,7 +245,9 @@ fn a_2d_pick_replaces_the_chosen_row_and_undo_restores_it() { assert_eq!(colors(&harness, effect), vec![FIRST, ID_PART.map(|channel| channel as f32 / 255.0), THIRD]); assert_eq!(harness.state().session.view, ViewMode::Material); assert!(!harness.state().session.stroke_active()); + harness.state_mut().session.undo().unwrap(); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); } @@ -264,6 +275,7 @@ fn removing_an_image_during_id_picking_falls_back_to_material() { execute(session, "viewport.view", &json!({"mode": "image", "image": name})).unwrap(); harness.get_by_label(PICK_COLOR).click(); harness.run_steps(3); + assert_eq!(harness.state().session.view, ViewMode::MeshMap(BakedMap::Id)); assert!(harness.state().picking_id_color.is_some()); @@ -317,6 +329,7 @@ fn color_selection_snapshots_and_quick_mask_pick() { click_at(&mut harness, center); assert!(harness.state().session.quick_mask.editing, "picking preserves quick-mask editing"); + save(&mut harness, "color-selection-quick-mask-restored"); execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); @@ -350,11 +363,13 @@ fn the_background_list_and_the_output_invert_edit_one_undo_step_each() { harness.run_steps(SETTLE_FRAMES); harness.get_by_role_and_label(Role::ListBoxOption, "White").click(); harness.run_steps(REDRAW_FRAMES); + assert_eq!(selection(&harness, effect).background, SelectionBackground::White); assert_eq!(harness.state().session.history_labels().len(), steps + 1); let invert = harness.get_by_role_and_label(Role::Button, "Invert").rect().center(); click_at(&mut harness, invert); + assert_eq!(selection(&harness, effect).output, 0.0); assert_eq!(harness.state().session.history_labels().len(), steps + 2); } @@ -367,6 +382,7 @@ fn the_background_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click harness.run_steps(SETTLE_FRAMES); harness.get_by_role_and_label(Role::ComboBox, "Black").rect() }); + assert_eq!(selection(&harness, effect).background, SelectionBackground::Black, "nothing changed"); } @@ -381,10 +397,12 @@ fn the_id_mask_slot_picks_a_texture_and_its_x_goes_back_to_the_mesh_map() { harness.run_steps(SETTLE_FRAMES); harness.get_by_role_and_label(Role::ListBoxOption, &texture).click(); harness.run_steps(REDRAW_FRAMES); + assert_eq!(selection(&harness, effect).id_map.as_deref(), Some(texture.as_str())); let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect().center(); click_at(&mut harness, clear); + assert_eq!(selection(&harness, effect).id_map, None); assert!(harness.query_by_role_and_label(Role::Button, "Clear").is_none(), "the mesh map has no ×"); } @@ -400,10 +418,12 @@ fn reading_the_mesh_map_shows_no_tile_as_the_current_id_mask() { let texture = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.run_steps(STARTUP_FRAMES); + assert_eq!(selection(&harness, effect).id_map, None, "the selection reads the ID mesh map"); harness.get_by_role_and_label(Role::ComboBox, "ID Mask").click(); harness.run_steps(SETTLE_FRAMES); + assert!(!tile_is_current(&harness, "Import..."), "Import... is an action, not the map read"); assert!(!tile_is_current(&harness, &texture)); @@ -411,6 +431,7 @@ fn reading_the_mesh_map_shows_no_tile_as_the_current_id_mask() { harness.run_steps(REDRAW_FRAMES); harness.get_by_role_and_label(Role::ComboBox, "ID Mask").click(); harness.run_steps(SETTLE_FRAMES); + assert!(tile_is_current(&harness, &texture), "a chosen texture is the current tile"); assert!(!tile_is_current(&harness, "Import...")); } @@ -455,6 +476,7 @@ fn a_hand_picked_id_mask_picks_without_a_bake() { harness.get_by_label(PICK_COLOR).click(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_id_color.is_some_and(|pick| pick.effect == effect), "Pick color starts picking with no bake"); let center = harness.state().viewport_rect.center(); @@ -475,10 +497,12 @@ fn clearing_the_only_id_mask_ends_a_waiting_pick() { harness.run_steps(STARTUP_FRAMES); harness.get_by_label(PICK_COLOR).click(); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().picking_id_color.is_some(), "the pick waits"); let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect().center(); click_at(&mut harness, clear); + assert_eq!(selection(&harness, effect).id_map, None); assert!(harness.state().picking_id_color.is_none(), "with no ID map left the pick ends"); assert_eq!(harness.state().session.view, ViewMode::Material, "and the earlier view comes back"); diff --git a/crates/ui-egui/tests/it/compare_mask_rows.rs b/crates/ui-egui/tests/it/compare_mask_rows.rs index daf7af52..3bfc94ca 100644 --- a/crates/ui-egui/tests/it/compare_mask_rows.rs +++ b/crates/ui-egui/tests/it/compare_mask_rows.rs @@ -56,19 +56,23 @@ fn the_rows_show_and_edit_the_comparison_one_undo_step_each() { let steps = undo_steps(&harness); pick_source(&mut harness, "Layers below", "Constant"); + assert_eq!(compare(&harness, effect).2, CompareSource::Constant); assert_eq!(undo_steps(&harness), steps + 1, "one undo step"); assert!(has_slider(&harness, "Constant"), "a constant side shows its value"); pick_source(&mut harness, "This layer", "This mask"); + assert_eq!(compare(&harness, effect).0, CompareSource::ThisMask); harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("≈")).click(); harness.run_steps(REDRAW_FRAMES); + assert_eq!(compare(&harness, effect).1, CompareOp::WithinTolerance); assert!(has_slider(&harness, "Tolerance"), "within tolerance shows its tolerance"); pick_source(&mut harness, "Height", "Roughness"); + assert_eq!(compare(&harness, effect).3, Channel::Roughness); assert_eq!(undo_steps(&harness), steps + 4); } @@ -81,5 +85,6 @@ fn a_source_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click_outsi harness.run_steps(SETTLE_FRAMES); harness.get_by_role_and_label(Role::ComboBox, "Layers below").rect() }); + assert_eq!(compare(&harness, effect).2, CompareSource::LayersBelow, "nothing changed"); } diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index ba6c7372..8c792de8 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -45,14 +45,17 @@ fn dragging_an_effect_row_reorders_its_stack() { // Rows show C, B, A; dropping A above C moves it to the top drag(&mut harness, "Effect A", "Effect C", false); + assert_eq!(order(&harness), [b, c, a]); // Dropping A below B returns it to the bottom drag(&mut harness, "Effect A", "Effect B", true); + assert_eq!(order(&harness), [a, b, c]); // Dropping C above A places it between A and B drag(&mut harness, "Effect C", "Effect A", false); + assert_eq!(order(&harness), [a, c, b]); } @@ -66,7 +69,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect, effect_of(&harness).id.0); + harness.state_mut().ui.layer_material_view = false; harness.run_steps(2); @@ -80,7 +85,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.run_steps(2); harness.get_by_label("Multiply").click(); harness.run_steps(3); + assert_eq!(base_color_blend(&effect_of(&harness)).mode, texturecraft_engine::core::BlendMode::Multiply, "the row sets the displayed channel's"); + let roughness = effect_of(&harness).blend_of(Some(texturecraft_engine::core::Channel::Roughness)).mode; assert_eq!(roughness, texturecraft_engine::core::BlendMode::Normal, "the other channels keep theirs"); @@ -116,7 +123,9 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { harness.run_steps(2); harness.hover_at(opacity_at + egui::vec2(8.0, 8.0)); harness.run_steps(2); + assert_eq!(base_color_blend(&effect_of(&harness)).opacity, 1.0, "the drag started without changing the opacity"); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); harness.run_steps(2); harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); @@ -124,7 +133,9 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { let opacity = base_color_blend(&effect_of(&harness)).opacity; assert!(opacity < 0.9, "the drag lowered the opacity: {opacity}"); assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(base_color_blend(&effect_of(&harness)).opacity, 1.0); assert_eq!(base_color_blend(&effect_of(&harness)).mode, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); } @@ -142,6 +153,7 @@ fn an_effect_rows_blending_options_reach_every_channel() { let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect_of(&harness).blend_of(Some(Channel::Roughness)).mode, BlendMode::Normal); let open_blending_options = |harness: &mut Harness<'_, TextureCraftApp>| { @@ -151,8 +163,10 @@ fn an_effect_rows_blending_options_reach_every_channel() { harness.run_steps(3); }; open_blending_options(&mut harness); + assert!(harness.get_by_label("Use this blend mode on every channel").accesskit_node().is_disabled(), "the Material view shows no channel to lend"); assert!(harness.get_by_label("Paste channel blending").accesskit_node().is_disabled(), "nothing is copied yet"); + harness.key_press(egui::Key::Escape); harness.run_steps(3); @@ -162,11 +176,13 @@ fn an_effect_rows_blending_options_reach_every_channel() { open_blending_options(&mut harness); harness.get_by_label("Use this blend mode on every channel").click(); harness.run_steps(3); + assert_eq!(effect_of(&harness).blend_of(Some(Channel::Roughness)).mode, BlendMode::Multiply); open_blending_options(&mut harness); harness.get_by_label("Copy channel blending").click(); harness.run_steps(3); open_blending_options(&mut harness); + assert!(!harness.get_by_label("Paste channel blending").accesskit_node().is_disabled(), "a copy can be pasted"); } diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index a2b4e0de..cf141d3b 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -43,6 +43,7 @@ fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { fn dragging_a_slider_applies_it() { let (mut harness, effect) = selected_generator(); assert_eq!(balance(&harness, effect), 0.5); + let track_rect = track(&harness, "Global balance"); harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); harness.run_steps(2); @@ -50,6 +51,7 @@ fn dragging_a_slider_applies_it() { harness.run_steps(2); harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); } @@ -71,11 +73,14 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { for x in [60.0, 160.0] { harness.hover_at(point_at(x)); harness.run_steps(2); + assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); + last = level(&harness); } harness.drop_at(point_at(160.0)); harness.run_steps(3); + assert_eq!(level(&harness), last); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } @@ -88,6 +93,7 @@ fn clicking_a_slider_track_applies_it() { harness.drag_at(at); harness.drop_at(at); harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); } @@ -118,6 +124,7 @@ fn a_value_typed_in_the_number_field_applies() { type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); harness.key_press(egui::Key::Enter); harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.25); assert_eq!(harness.state().session.history_labels().len(), steps + 1); } @@ -137,11 +144,13 @@ fn a_track_drag_drops_text_typed_in_the_number_field() { harness.run_steps(2); let dragged = balance(&harness, effect); assert!(dragged < 0.25, "the drag applies: {dragged}"); + // Leave whatever has focus: a click on empty space harness.drag_at(egui::pos2(5.0, 1390.0)); harness.drop_at(egui::pos2(5.0, 1390.0)); harness.key_press(egui::Key::Enter); harness.run_steps(3); + assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); } @@ -156,16 +165,23 @@ fn leaving_the_number_field_unchanged_keeps_the_value() { type_balance(&mut harness, &[], ""); harness.key_press(egui::Key::Enter); harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333, "left without typing"); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); + assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); assert!(number_field(&harness, "Global balance").is_focused()); + harness.key_press(egui::Key::Escape); harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333); + // Typing the value it already has is no edit either type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); harness.key_press(egui::Key::Enter); harness.run_steps(3); + assert_eq!(harness.state().session.history_labels().len(), steps); } diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index d926b906..f369d475 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -135,6 +135,7 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; + assert!(matches!(effect, EffectKind::Fill { source: Source::Image { name, .. }, .. } if name == &image_name)); click_node(&mut harness, egui::Role::ComboBox, "UV projection"); @@ -143,6 +144,7 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; + assert!(matches!(effect, EffectKind::Fill { projection: Projection::Triplanar { .. }, .. })); // The slot's × puts the mask fill back to a uniform value @@ -150,6 +152,7 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; + assert!(matches!(effect, EffectKind::Fill { source: Source::Uniform(_), .. })); } diff --git a/crates/ui-egui/tests/it/folder_properties.rs b/crates/ui-egui/tests/it/folder_properties.rs index 721a5dfd..c92c429c 100644 --- a/crates/ui-egui/tests/it/folder_properties.rs +++ b/crates/ui-egui/tests/it/folder_properties.rs @@ -60,6 +60,7 @@ fn scale_and_rotation_drags_are_one_undo_step_each_and_the_reset_drops_them() { let scaled = offset(&harness, folder); assert!((scaled.scale - 4.0).abs() < SCALE_TOLERANCE, "the right end is x4: {scaled:?}"); assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); + drag(&mut harness, "Rotation", 0.75); let turned = offset(&harness, folder); assert!((turned.rotation - 90.0).abs() < ROTATION_TOLERANCE_DEGREES && turned.scale == scaled.scale, "{turned:?}"); @@ -69,6 +70,7 @@ fn scale_and_rotation_drags_are_one_undo_step_each_and_the_reset_drops_them() { harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults").click(); harness.run_steps(SETTLE_FRAMES); + assert!(offset(&harness, folder).is_none(), "the reset drops the offset"); assert_eq!(harness.state().session.history_labels().len(), steps + 3); } @@ -86,14 +88,17 @@ fn randomize_seeds_is_one_undo_step_the_contents_reset_puts_them_back_and_an_emp let steps = harness.state().session.history_labels().len(); harness.get_by_role_and_label(Role::Button, "Randomize seeds").click(); harness.run_steps(SETTLE_FRAMES); + assert_ne!(seed(&harness), 7); assert_eq!(harness.state().session.history_labels().len(), steps + 1); // The Contents reset lights up and puts the seed back, in one undo step let reset = harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults"); assert!(!reset.accesskit_node().is_disabled(), "randomized seeds light the reset"); + reset.click(); harness.run_steps(SETTLE_FRAMES); + assert_eq!(seed(&harness), 7, "the seed from before Randomize seeds"); assert_eq!(harness.state().session.history_labels().len(), steps + 2); assert!(harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults").accesskit_node().is_disabled(), "nothing left to reset"); diff --git a/crates/ui-egui/tests/it/instance_properties.rs b/crates/ui-egui/tests/it/instance_properties.rs index 15ece0a7..d54463ee 100644 --- a/crates/ui-egui/tests/it/instance_properties.rs +++ b/crates/ui-egui/tests/it/instance_properties.rs @@ -40,9 +40,11 @@ fn set_name(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> String { fn the_source_card_names_the_source_and_its_texture_set_and_a_click_selects_it() { let (mut harness, instance, source) = instance_harness(false); assert_eq!(harness.state().session.selected_layer(), Some(instance)); + let card = format!("Steel {}", set_name(&harness, source)); harness.get_by_role_and_label(Role::Button, &card).click(); harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(source), "the click goes to the source"); } @@ -60,6 +62,7 @@ fn a_source_that_is_gone_shows_a_missing_layer_that_takes_no_click() { harness.run_steps(1); harness.drop_at(at); harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(instance)); assert_eq!(harness.state().session.history_labels().len(), steps, "the click ran nothing"); } diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs index 004be414..9466a76f 100644 --- a/crates/ui-egui/tests/it/layer_toolbar.rs +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -49,10 +49,13 @@ fn add_effect_greys_mask_only_effects_on_the_content_and_adds_them_in_the_mask() let steps = harness.state().session.history_labels().len(); for item in ["Compare mask", "Color selection", "Generator"] { pick(&mut harness, "Add effect", item); + assert_eq!(harness.state().session.history_labels().len(), steps, "{item} is greyed on the layer content, not sent to the mask"); + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); } + assert!(harness.state().session.doc.project.layer(layer).unwrap().mask.is_none()); harness.state_mut().run("mask.add.white", json!({"layer": layer.0})); @@ -60,8 +63,10 @@ fn add_effect_greys_mask_only_effects_on_the_content_and_adds_them_in_the_mask() pick(&mut harness, "Add effect", "Color selection"); let kinds = mask_kinds(&harness, layer); assert!(matches!(kinds.as_slice(), [EffectKind::ColorSelection(_)]), "{kinds:?}"); + let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap(); let added = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::ColorSelection(_))).unwrap().id; + assert_eq!(harness.state().session.target, StackTarget::Effect(added), "the new colour selection is selected"); } @@ -74,6 +79,7 @@ fn add_mask_adds_a_height_combination_and_greys_once_the_layer_has_a_mask() { let steps = harness.state().session.history_labels().len(); pick(&mut harness, "Add mask", "White"); + assert_eq!(harness.state().session.history_labels().len(), steps, "a layer with a mask adds to it through Add effect"); } @@ -81,10 +87,13 @@ fn add_mask_adds_a_height_combination_and_greys_once_the_layer_has_a_mask() { fn bitmap_opens_the_texture_picker_and_adds_the_mask_only_once_one_is_picked() { let (mut harness, layer) = app(); pick(&mut harness, "Add mask", "Bitmap"); + assert!(egui::Popup::is_any_open(&harness.ctx), "Bitmap opens the texture picker"); assert!(harness.state().session.doc.project.layer(layer).unwrap().mask.is_none(), "no mask until a texture is picked"); + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(!egui::Popup::is_any_open(&harness.ctx)); assert!(harness.state().session.doc.project.layer(layer).unwrap().mask.is_none(), "Escape adds nothing"); @@ -136,6 +145,7 @@ fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() { for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add folder", "Remove layer"] { let button = harness.query_all_by_label_contains(label).find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect(); + assert!(button.left() >= left && button.right() <= left + width, "{label} at {button:?} stays inside the panel"); } @@ -143,9 +153,12 @@ fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() { let before = layers(&harness); let folder = harness.get_by_role_and_label(Role::Button, "Add folder").rect(); click_at(&mut harness, folder.center()); + assert_eq!(layers(&harness), before + 1, "Add folder answers a click"); + let remove = harness.query_all_by_label_contains("Remove layer").find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect(); click_at(&mut harness, remove.center()); + assert_eq!(layers(&harness), before, "and Remove does"); } diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs index d117abc8..d962f022 100644 --- a/crates/ui-egui/tests/it/levels_editor.rs +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -157,6 +157,7 @@ fn output_handles_keep_their_side_once_inverted() { fn reset_and_invert_are_one_undo_step_each() { let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); assert!(button(&harness, "Reset").accesskit_node().is_disabled(), "nothing to reset at the defaults"); + set_levels(&mut harness, effect, json!({"inLow": 0.1, "inHigh": 0.9, "gamma": 2.0, "outLow": 0.2, "outHigh": 0.7})); let steps = undo_steps(&harness); @@ -181,6 +182,7 @@ fn auto_fits_the_input_range_to_the_histogram() { let holds = |count: &u32| f64::from(*count) > f64::from(total) * AUTO_MIN_SHARE; let low = counts.iter().position(holds).unwrap() as f32 / HISTOGRAM_BUCKETS as f32; let high = (counts.iter().rposition(holds).unwrap() + 1) as f32 / HISTOGRAM_BUCKETS as f32; + assert!(low > 0.0 || high < 1.0, "the clouds don't fill the whole range: {low}..{high}"); button(&harness, "Auto").click(); @@ -246,11 +248,13 @@ fn exact_entry_opens_on_a_double_click_and_closes_with_typing() { assert_eq!(open_fields(&harness), 0, "no number fields until a handle asks for them"); type_value(&mut harness, "Output low", ""); + assert!(harness.query_all(by().role(Role::TextInput)).any(|node| node.is_focused()), "the number field has focus"); assert_eq!(open_fields(&harness), HANDLE_LABELS.len()); harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert_eq!(open_fields(&harness), 0, "Escape closes the fields"); assert_eq!(buttons(&harness), before, "the buttons go back where they were"); } @@ -479,6 +483,7 @@ fn a_content_levels_picks_the_channel_it_affects() { assert_eq!(levels(&harness, effect).affects, Some(Channel::BaseColor)); assert!(painted_text(&harness, "LEVELS - BASE COLOR"), "the caption names the channel"); assert!(harness.query_by_label("Blending").is_none(), "levels have no blending"); + for view in ["Colors", "RGB", "R", "G", "B", "Lum"] { assert!(harness.query_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some(view)).is_some(), "{view} on the display switch"); } @@ -487,6 +492,7 @@ fn a_content_levels_picks_the_channel_it_affects() { let steps = undo_steps(&harness); harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("R")).click(); harness.run_steps(SETTLE_FRAMES); + assert_eq!(undo_steps(&harness), steps); assert!( harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("R")).accesskit_node().toggled() @@ -495,14 +501,18 @@ fn a_content_levels_picks_the_channel_it_affects() { ); assert_eq!(affects_list(&harness).and_then(|list| list.accesskit_node().label()).as_deref(), Some("Base color")); + affects_list(&harness).unwrap().click(); harness.run_steps(SETTLE_FRAMES); + assert!( harness.query_by(|node| node.role() == Role::ListBoxOption && node.label().as_deref() == Some("Normal")).is_none(), "levels pass normal maps through" ); + harness.get_by(|node| node.role() == Role::ListBoxOption && node.label().as_deref() == Some("Roughness")).click(); harness.run_steps(REDRAW_FRAMES); + assert_eq!(levels(&harness, effect).affects, Some(Channel::Roughness)); assert_eq!(undo_steps(&harness), steps + 1); assert!(painted_text(&harness, "LEVELS - ROUGHNESS")); @@ -515,9 +525,11 @@ fn clamp_is_one_undo_step() { assert!(painted_text(&harness, "LEVELS - MASK")); assert!(affects_list(&harness).is_none() && !painted_text(&harness, "Affects"), "a mask has no channel to pick"); assert!(!levels(&harness, effect).clamp, "new levels carry on past their handles"); + let steps = undo_steps(&harness); harness.get_by_role_and_label(Role::CheckBox, "Clamp").click(); harness.run_steps(SETTLE_FRAMES); + assert!(levels(&harness, effect).clamp); assert_eq!(undo_steps(&harness), steps + 1); } @@ -532,5 +544,6 @@ fn the_affects_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click_ou harness.run_steps(SETTLE_FRAMES); button }); + assert_eq!(levels(&harness, effect).affects, Some(Channel::BaseColor), "nothing changed"); } diff --git a/crates/ui-egui/tests/it/mask_fill_rows.rs b/crates/ui-egui/tests/it/mask_fill_rows.rs index 041a2bb9..471d4e2c 100644 --- a/crates/ui-egui/tests/it/mask_fill_rows.rs +++ b/crates/ui-egui/tests/it/mask_fill_rows.rs @@ -59,16 +59,20 @@ fn a_mask_fill_has_fill_symmetry_and_grayscale_tabs_and_its_slot_picks_the_sourc for tab in ["Fill", "Symmetry", "Grayscale"] { assert!(harness.query_by_role_and_label(Role::Tab, tab).is_some(), "the {tab} tab"); } + assert!(harness.query_by_role_and_label(Role::Tab, "Material").is_none(), "a mask fill has no material"); assert!(harness.query_by_label("Move on model").is_some(), "the Fill section's projection rows"); click(&mut harness, Role::ComboBox, "Grayscale"); + assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "the slot opens the source picker"); + click(&mut harness, Role::ListBoxOption, "Clouds"); let (Source::Procedural { pattern, low, high, .. }, _) = mask_fill(&harness, effect) else { panic!("a procedural") }; assert_eq!((pattern.kind, low, high), (ProceduralKind::Clouds, [0.0; 3], [1.0; 3]), "a gray pattern spans black to white"); assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); assert!(harness.query_by_label("Scale").is_some(), "the pattern's own rows follow the slot"); + for shown in ["Contrast", "Balance", "Random"] { assert!(harness.query_by_label(shown).is_some(), "a grayscale's {shown} (Seed's dice) shows with Scale, Attributes folded"); } @@ -83,13 +87,17 @@ fn a_mask_fill_has_fill_symmetry_and_grayscale_tabs_and_its_slot_picks_the_sourc assert!(harness.query_by_role_and_label(Role::Label, caption).is_some(), "one list holds the {caption} sizes under their caption"); } click(&mut harness, Role::ListBoxOption, "1024 × 1024"); + assert_eq!(resolution(&harness), (ResolutionMode::Custom, 1024, 0)); + click_below(&mut harness, Role::ComboBox, "1024 × 1024"); click(&mut harness, Role::ListBoxOption, "×4 · 1024"); + assert_eq!(resolution(&harness), (ResolutionMode::Auto, 1024, 2), "1024 is the texture set's ×4"); // The slot's × puts the mask fill back to white click(&mut harness, Role::Button, "Clear"); + assert_eq!(mask_fill(&harness, effect).0, Source::Uniform([1.0; 3])); } @@ -117,12 +125,14 @@ fn a_mask_fills_projection_moves_on_the_model_and_resets_with_its_section() { let button = harness.get_by_role_and_label(Role::Button, "Move on model").rect().center(); let mut held = None; mouse_drag_watching(&mut harness, button, button + MOVE_DRAG, |harness| held = held.or(harness.state().moving_on_model)); + assert_eq!(held, Some(MoveOnModel { layer, effect: Some(effect) })); assert_eq!(harness.state().moving_on_model, None, "letting go ends it"); let Projection::Uv { offset, .. } = mask_fill(&harness, effect).1 else { panic!("still UV") }; assert!(offset[0] != 0.0 && offset[1] == 0.0, "a drag across slides the image across: {offset:?}"); click(&mut harness, Role::Button, "Fill: Reset to defaults"); + assert_eq!(mask_fill(&harness, effect).1, Projection::default(), "the Fill section's reset reaches the mask fill"); } diff --git a/crates/ui-egui/tests/it/mask_paint_grayscale.rs b/crates/ui-egui/tests/it/mask_paint_grayscale.rs index e2e28236..fd65cd03 100644 --- a/crates/ui-egui/tests/it/mask_paint_grayscale.rs +++ b/crates/ui-egui/tests/it/mask_paint_grayscale.rs @@ -45,6 +45,7 @@ fn the_grayscale_slot_paints_one_gray_its_ramp_drags_and_inverts() { assert!(harness.query_by_role_and_label(Role::ComboBox, "Grayscale").is_some(), "the Grayscale slot card"); click(&mut harness, Role::Button, "Invert"); + assert_eq!(harness.state().session.tool.mask_value, 0.0, "white inverts to black"); // A real drag along the ramp to its right end @@ -58,6 +59,7 @@ fn the_grayscale_slot_paints_one_gray_its_ramp_drags_and_inverts() { } harness.drop_at(at(1.0)); harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().session.tool.mask_value > 0.95, "dragged to {}", harness.state().session.tool.mask_value); } @@ -65,18 +67,23 @@ fn the_grayscale_slot_paints_one_gray_its_ramp_drags_and_inverts() { fn the_slot_picks_an_image_to_paint_and_clear_goes_back_to_the_gray() { let (mut harness, image) = folder_mask_harness(); click(&mut harness, Role::ComboBox, "Grayscale"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Import...").is_some(), "Textures starts with Import..."); + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Import...").is_none(), "Escape closes the picker"); assert_eq!(harness.state().session.tool.mask_image, None); click(&mut harness, Role::ComboBox, "Grayscale"); click(&mut harness, Role::ListBoxOption, &image); + assert_eq!(harness.state().session.tool.mask_image.as_deref(), Some(image.as_str())); assert!(harness.query_by_role_and_label(Role::Slider, "Grayscale").is_none(), "an image has no ramp"); click(&mut harness, Role::Button, "Clear"); + assert_eq!(harness.state().session.tool.mask_image, None); assert!(harness.query_by_role_and_label(Role::Slider, "Grayscale").is_some(), "the ramp is back"); } diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index b909b013..91d09606 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -130,6 +130,7 @@ fn a_stroke_on_the_model_closes_the_add_effect_menu() { let mut harness = app(&MemoryStorage::default()); harness.get_by_role_and_label(Role::Button, "Add effect").click(); harness.run_steps(SETTLE_FRAMES); + assert!(egui::Popup::is_any_open(&harness.ctx), "the menu opens"); stroke_on_model(&mut harness, Modifiers::NONE); diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index e98d2e6c..9c29a765 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -192,6 +192,7 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { // Add effect adds to the mask, since the mask's fill is the selected target of the Low layer assert!(matches!(h.state().session.target, StackTarget::Effect(_))); + add_effect(&mut h, "Anchor point"); let anchor = mask_anchor_of(&h, low).expect("the anchor point is in the mask of Low"); assert!(h.state().session.doc.project.layer(LayerId(low)).unwrap().content_effects.is_empty(), "the anchor point is not on the layer content"); @@ -200,6 +201,7 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { let high = high_layer(&mut h.state_mut().session); h.run_steps(3); add_effect(&mut h, "Fill"); + assert!(matches!(reader_source(&h, high), Source::Uniform(_)), "a new fill starts as a uniform value"); // The Anchor points tab lists the mask anchor of the layer below @@ -229,6 +231,7 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { let ref_anchor = id(&texturecraft_engine::execute(&mut reference, "effect.add.anchor", &json!({"target": "mask"})).unwrap(), "effect"); high_layer(&mut reference); texturecraft_engine::execute(&mut reference, "effect.add.fill", &json!({"anchor": ref_anchor})).unwrap(); + assert!(close(base_color(&mut h.state_mut().session), base_color(&mut reference))); // Save and reopen keep the link and the result @@ -253,12 +256,16 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { .id .0; h.state_mut().run("effect.set", json!({"effect": fill, "value": 1.0})); + assert!(matches!(reader_source(&h, high), Source::Uniform(_))); + h.state_mut().session.modified = false; reopen(&mut h, &file); + assert_eq!(mask_anchor_of(&h, low), Some(anchor), "the anchor point is still in the mask"); let Source::Anchor { anchor: read, .. } = reader_source(&h, high) else { panic!("the reopened fill reads an anchor") }; assert_eq!(read.0, anchor, "the reopened fill still reads that anchor"); assert!(close(base_color(&mut h.state_mut().session), [expected; 3]), "{:?}", base_color(&mut h.state_mut().session)); + std::fs::remove_dir_all(file.parent().unwrap()).unwrap(); } diff --git a/crates/ui-egui/tests/it/source_picker.rs b/crates/ui-egui/tests/it/source_picker.rs index f40afea9..378b1a87 100644 --- a/crates/ui-egui/tests/it/source_picker.rs +++ b/crates/ui-egui/tests/it/source_picker.rs @@ -155,6 +155,7 @@ fn the_anchor_points_tab_lists_mask_anchor_points_by_name() { click_widget(&mut harness, Role::Tab, "Anchor points"); let anchor = harness.get_all_by_role(Role::ListBoxOption).find_map(|node| node.accesskit_node().label().filter(|label| label.starts_with("Dirt mask"))); click_tile(&mut harness, &anchor.expect("the mask anchor point below is offered under its own name")); + assert!(matches!(source(&harness, reader, Channel::Roughness), Source::Anchor { .. })); } diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 96ec383c..ebe3746b 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -121,6 +121,7 @@ fn the_anchor_points_tab_picks_an_anchor() { // An anchor tile is labelled with the anchor's name; its layer is named only where two anchors share a name harness.get_by_role_and_label(Role::ListBoxOption, "Height").click(); harness.run_steps(3); + assert!(source(&harness, effect).anchor().is_some()); } @@ -155,6 +156,7 @@ fn an_amount_drag_is_one_undo_step_and_restore_defaults_puts_the_tiles_back() { drag_slider(&mut harness, "X amount"); let tile = pattern(&harness, effect).tile.unwrap(); + assert!(tile.amount[0] > TileGenerator::default().amount[0], "the drag adds columns: {:?}", tile.amount); assert_eq!(harness.state().session.history_labels().len(), history + 1, "one drag is one undo step"); @@ -162,6 +164,7 @@ fn an_amount_drag_is_one_undo_step_and_restore_defaults_puts_the_tiles_back() { harness.run_steps(SCROLL_FRAMES); lowest(&harness, "Restore defaults").click(); harness.run_steps(3); + assert_eq!(*pattern(&harness, effect).tile.unwrap(), TileGenerator::default()); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index a6c18764..9d45eed0 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -841,6 +841,7 @@ fn mask_fill_image_snapshot() { let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; assert_eq!(*source, Source::image(name)); assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); + save(&mut harness, &output_dir, "mask-fill-image-selected"); } From a99c37392c42e7ade7ade629556064812f2956b5 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 043/153] Filters: review repairs from #698 Chasse's repairs to this part's code, carried over from the #698 head (5644b7d3). --- crates/compose/src/below.rs | 2 + crates/compose/src/environment_sh.rs | 38 ++- crates/compose/src/environment_sky.rs | 35 +- crates/compose/src/eval.rs | 305 +++++++++++++----- crates/compose/src/eval/evaluation_inputs.rs | 45 +++ crates/compose/src/lib.rs | 1 + crates/compose/src/shape_distance.rs | 90 +++--- crates/compose/src/soft_box.rs | 13 +- crates/compose/tests/cache_and_instances.rs | 3 + crates/core/src/color_match.rs | 46 ++- crates/core/src/curve_preset.rs | 2 + crates/core/src/gradient_input.rs | 47 ++- crates/core/src/grayscale_conversion.rs | 3 + crates/core/src/image_input.rs | 1 + crates/core/src/layer.rs | 32 +- crates/core/src/lib.rs | 4 + crates/core/src/mask_outline.rs | 2 + crates/core/src/mirror.rs | 5 + crates/core/src/prepared_color_match.rs | 35 ++ crates/core/src/prepared_gradient.rs | 35 ++ crates/core/src/source_warp.rs | 6 + crates/core/src/stylized_lighting.rs | 3 + crates/core/src/stylized_shading.rs | 34 +- crates/core/src/threshold_mode.rs | 3 + crates/core/src/tile_transform.rs | 10 + crates/engine/src/layer_cmds.rs | 2 + crates/engine/src/mask_cmds.rs | 4 +- crates/engine/src/material_lib.rs | 2 + crates/engine/src/preview.rs | 12 +- crates/engine/src/session.rs | 26 +- crates/engine/src/tile_transform_params.rs | 5 + crates/engine/tests/it/content_effects.rs | 21 +- crates/engine/tests/it/filter_card.rs | 15 + crates/engine/tests/it/filter_colour.rs | 13 + crates/engine/tests/it/filter_gradient.rs | 8 + crates/engine/tests/it/filter_inputs.rs | 13 + crates/engine/tests/it/filter_light.rs | 42 +++ crates/engine/tests/it/filter_shape.rs | 24 ++ crates/engine/tests/it/filter_simple.rs | 34 ++ crates/engine/tests/it/filter_stylize.rs | 16 + crates/engine/tests/it/filter_support.rs | 3 + crates/engine/tests/it/filter_swap.rs | 8 + crates/engine/tests/it/filter_transform.rs | 11 + crates/engine/tests/it/painter_gaps.rs | 19 +- crates/render/src/ibl.rs | 34 +- .../ui-egui/src/property_sheet/color_bar.rs | 4 +- .../src/property_sheet/switch_control.rs | 2 +- crates/ui-egui/tests/it/filter_card.rs | 3 + crates/ui-egui/tests/it/filter_gradient.rs | 3 + crates/ui-egui/tests/it/filter_inputs.rs | 5 + crates/ui-egui/tests/it/filter_light.rs | 2 + crates/ui-egui/tests/it/filter_picker.rs | 8 + crates/ui-egui/tests/it/filter_shape.rs | 5 + crates/ui-egui/tests/it/filter_simple.rs | 10 + crates/ui-egui/tests/it/filter_stylize.rs | 5 + crates/ui-egui/tests/it/filter_transform.rs | 1 + crates/ui-egui/tests/it/properties_lists.rs | 6 + 57 files changed, 937 insertions(+), 229 deletions(-) create mode 100644 crates/compose/src/eval/evaluation_inputs.rs create mode 100644 crates/core/src/prepared_color_match.rs create mode 100644 crates/core/src/prepared_gradient.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 4d8f01c1..cfb5edb2 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -206,9 +206,11 @@ impl StackKey { { return None; } + if self.pixels.len() != other.pixels.len() { return None; } + let size = self.set.size(); let mut changed = BTreeSet::new(); for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { diff --git a/crates/compose/src/environment_sh.rs b/crates/compose/src/environment_sh.rs index 30a2d847..390928bf 100644 --- a/crates/compose/src/environment_sh.rs +++ b/crates/compose/src/environment_sh.rs @@ -1,6 +1,6 @@ //! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, Weak}; use texturecraft_core::project::DisplaySettings; use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3}; @@ -16,33 +16,33 @@ pub struct EnvironmentSh { rotation: f32, } -/// The environment the last coefficients were worked out for: a built-in by name, or an imported image (held, so it is not a different image at the same address) -type CacheEntry = (String, Option>, Arc<[[f32; 3]; 9]>); +/// The last coefficients, keyed by a built-in name or the identity of an imported image +type CacheEntry = (String, Option>, [[f32; 3]; 9]); static CACHE: Mutex> = Mutex::new(None); impl EnvironmentSh { /// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh { - let image = display.environment_resource().and_then(|name| images.get(name)).cloned(); + let image = display.environment_resource().and_then(|name| images.get(name)); let same = |entry: &CacheEntry| match (&entry.1, &image) { - (Some(held), Some(image)) => Arc::ptr_eq(held, image), + (Some(identity), Some(image)) => std::ptr::eq(identity.as_ptr(), Arc::as_ptr(image)), (None, None) => entry.0 == display.environment, _ => false, }; let rotation = display.env_rotation.to_radians(); - let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2.clone()); + let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2); if let Some(coefficients) = cached { - return EnvironmentSh { coefficients: *coefficients, rotation }; + return EnvironmentSh { coefficients, rotation }; } - // Worked out with the cache unlocked: the averaging runs on the thread pool, where a worker holding the lock could take another tile's task that waits for it - let coefficients = match &image { + // Average outside the lock so a Rayon worker can take another tile that needs the cache + let coefficients = match image { Some(image) => image_sh(image), None => built_in_sh(&display.environment), }; - *CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image, Arc::new(coefficients))); + *CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image.map(Arc::downgrade), coefficients)); EnvironmentSh { coefficients, rotation } } @@ -113,6 +113,24 @@ mod tests { assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment"); } + #[test] + fn replacing_an_imported_environment_releases_its_image() { + let display = DisplaySettings { environment: "resource:lighting".into(), ..DisplaySettings::default() }; + + for color in [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]] { + let image = Arc::new(ImageRes::new(32, 16, vec![color; 32 * 16], false)); + let image_identity = Arc::downgrade(&image); + let images = ImageStore::from([("lighting".into(), image)]); + + let lighting = EnvironmentSh::of(&display, &images); + drop(images); + let irradiance = lighting.irradiance(Vec3::Y, 0.0, 0.0); + + assert!(irradiance.distance(Vec3::new(color[0], color[1], color[2])) < 0.02); + assert!(image_identity.upgrade().is_none(), "lighting should release the decoded image with its store"); + } + } + /// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock #[test] fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() { diff --git a/crates/compose/src/environment_sky.rs b/crates/compose/src/environment_sky.rs index 0c37ccd2..ec911b88 100644 --- a/crates/compose/src/environment_sky.rs +++ b/crates/compose/src/environment_sky.rs @@ -59,41 +59,44 @@ const SUN_RADIANCE: f32 = 120.0; /// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio) pub fn radiance(name: &str, d: Vec3) -> Vec3 { + if name == "Sunset" { + let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); + let sun_dir = dir_of(0.12, 0.47); + let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE; + return base + Vec3::new(1.0, 0.6, 0.3) * sun; + } + + let (azimuth, elevation) = SoftBox::angles(d); match name { "Studio Contrast" => { let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01)); - base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d) - + SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d) + base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(azimuth, elevation) + + SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(azimuth, elevation) } "Overcast" => { let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15)); - base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(d) - } - "Sunset" => { - let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05)); - let sun_dir = dir_of(0.12, 0.47); - let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE; - base + Vec3::new(1.0, 0.6, 0.3) * sun + base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(azimuth, elevation) } "Warehouse" => { let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06)); for k in 0..6 { - c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d); + c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) } + .eval(azimuth, elevation); } - c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d) + c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(azimuth, elevation) } "Night" => { let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005)); - base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d) - + SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d) + base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(azimuth, elevation) + + SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(azimuth, elevation) } // "Studio Soft" (default) _ => { let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07)); - base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d) - + SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d) - + SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d) + base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(azimuth, elevation) + + SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(azimuth, elevation) + + SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(azimuth, elevation) } } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6e7fb298..7b0ef05b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -13,14 +13,15 @@ use rayon::prelude::*; use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, Project, Projection, - RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, - TileTransform, blend1, blend3, lum, mix3, per_unit, posterize, + HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, + PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, + TargetColorMode, TextureSet, TileGrid, TileTransform, blend1, blend3, lum, mix3, per_unit, posterize, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::effect_histogram::EffectHistogram; @@ -38,6 +39,7 @@ use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use evaluation_inputs::EvaluationInputs; const NCH: usize = Channel::ALL.len(); @@ -276,6 +278,24 @@ struct EffectPlan<'a> { stylized: Option, /// The source a point filter's image input reads (Grayscale Conversion's Custom Input) input: Option, + /// Custom stops shared across tile plans and channels + gradient: Option>, +} + +impl EffectPlan<'_> { + fn point(&self, filter: &Filter, kind: ChannelKind, value: [f32; 3]) -> Option<[f32; 3]> { + match &self.gradient { + Some(gradient) => gradient.point(kind, value), + None => filter.point(kind, value), + } + } + + fn ramp_at(&self, filter: &Filter, position: f32) -> Option<[f32; 3]> { + match &self.gradient { + Some(gradient) => gradient.at(position), + None => filter.ramp_at(position), + } + } } struct MaskPlan<'a> { @@ -424,7 +444,7 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator Some((index, texels(*radius), Op::Glow(*amount))), EffectKind::Filter(Filter::Mosaic { size, alpha }) => Some((index, texels(*size), Op::Mosaic { alpha: *alpha })), EffectKind::Filter(Filter::Fxaa { alpha }) => Some((index, FXAA_SEARCH as f32 + 1.0, Op::Fxaa { alpha: *alpha })), - // The ellipse reaches up to twice the radius along a clear direction, and the direction is read around its reach + // Both the direction search and the ellipse can reach twice the radius EffectKind::Filter(Filter::AnisotropicKuwahara(kuwahara)) if kuwahara.radius > 0.0 => { Some((index, texels(kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS)) * (2.0 + kuwahara.tensor_reach()) + 1.0, Op::Kuwahara(*kuwahara))) } @@ -435,7 +455,7 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator { Some((index, if matcher.source_mode == SourceColorMode::Average { WHOLE_SET } else { 1.0 }, Op::ColorMatch(*matcher))) } - // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them + // Use reference-resolution reach so all callers classify the same filters as stages EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) } @@ -714,28 +734,43 @@ fn gather( data } -/// The linear colors `source` gives over texel region `(x0, y0, w, h)` (its tiles `tiles`), row by row -fn input_colors(inp: &Inputs, source: &Source, tiles: &[(u32, u32)], (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec<[f32; 3]> { - let parts: Vec> = tiles - .par_iter() - .map(|&(tx, ty)| { - let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); - tile_texels(inp.gbuf, tx, ty) - .map(|(x, y, offset)| { - let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); - (x, y, texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color)) - }) - .collect() - }) - .collect(); - let mut colors = vec![[0.0f32; 3]; (w * h) as usize]; - for &(x, y, color) in parts.iter().flatten() { - if let (Some(dx), Some(dy)) = (x.checked_sub(x0), y.checked_sub(y0)) - && let Some(slot) = colors.get_mut((dy * w + dx) as usize) - { - *slot = color; - } +/// The linear colors a filter input gives over the tile-aligned texel region, row by row +fn input_colors( + inputs: &EvaluationInputs, + source: &Source, + (layer, channels, below): (LayerId, &[Channel], &Fields), + (left, top, width, height): (u32, u32, u32, u32), +) -> Vec<[f32; 3]> { + if width == 0 || height == 0 { + return Vec::new(); } + + let mut colors = vec![[0.0; 3]; (width * height) as usize]; + let horizontal_tiles = left / TILE..(left + width).div_ceil(TILE); + colors.par_chunks_mut((TILE * width) as usize).enumerate().for_each(|(band, colors)| { + let tile_y = top / TILE + band as u32; + let band_top = tile_y * TILE; + for tile_x in horizontal_tiles.clone() { + let anchors = if matches!(source, Source::Anchor { .. }) { anchor_plan(inputs, layer, channels, tile_x, tile_y, Some(below)) } else { Vec::new() }; + let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); + + for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) { + if x < left || x - left >= width { + continue; + } + + let index = ((y - band_top) * width + (x - left)) as usize; + let Some(pixel) = colors.get_mut(index) else { continue }; + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchors.is_empty() { + texel.anchors_below(&anchors, layer); + } + + *pixel = texel.source(source, &Projection::default(), Sampling::default(), ChannelKind::Color); + } + } + }); + colors } @@ -748,48 +783,65 @@ fn color_match(data: &mut [f32], comps: usize, matcher: &ColorMatch, (sources, t return; } - // The mean of the covered colors (premultiplied, so a texel counts by its coverage) - let (sum, covered) = data - .par_chunks(4) - .fold( - || ([0.0f64; 3], 0.0f64), - |(mut sum, mut covered), px| { - if let [r, g, b, a] = *px - && a > 0.0 - && a.is_finite() - { - for (slot, v) in sum.iter_mut().zip([r, g, b]) { - *slot += f64::from(v); - } - covered += f64::from(a); - } - (sum, covered) - }, - ) - .reduce(|| ([0.0; 3], 0.0), |(a, ca), (b, cb)| ([a[0] + b[0], a[1] + b[1], a[2] + b[2]], ca + cb)); - let mean = if covered > 0.0 { sum.map(|v| (v / covered) as f32) } else { matcher.target_color }; - data.par_chunks_mut(4).enumerate().for_each(|(i, px)| { - let [r, g, b, a] = *px else { return }; - if a <= 0.0 || !a.is_finite() { + let source_color = if matcher.source_mode == SourceColorMode::Average { mean_region_color(data, matcher.target_color) } else { matcher.source_color }; + let source_pixels = if matcher.source_mode == SourceColorMode::Input { sources.as_deref() } else { None }; + let target_pixels = if matcher.target_mode == TargetColorMode::ImageInput { targets.as_deref() } else { None }; + + if source_pixels.is_none() && target_pixels.is_none() { + let prepared = PreparedColorMatch::new(*matcher, source_color, matcher.target_color); + match_pixels(data, opacity, |_, color| prepared.apply(color)); + } else { + match_pixels(data, opacity, |index, color| { + let source = source_pixels.and_then(|pixels| pixels.get(index)).copied().unwrap_or(source_color); + let target = target_pixels.and_then(|pixels| pixels.get(index)).copied().unwrap_or(matcher.target_color); + matcher.apply(color, source, target) + }); + } +} + +fn match_pixels(data: &mut [f32], opacity: f32, remap: impl Fn(usize, [f32; 3]) -> [f32; 3] + Sync) { + data.par_chunks_mut(4).enumerate().for_each(|(index, pixel)| { + let [red, green, blue, alpha] = *pixel else { return }; + if alpha <= 0.0 || !alpha.is_finite() { return; } - let source = match matcher.source_mode { - SourceColorMode::Average => mean, - SourceColorMode::Parameter => matcher.source_color, - SourceColorMode::Input => sources.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.source_color), - }; - let target = match matcher.target_mode { - TargetColorMode::Parameter => matcher.target_color, - TargetColorMode::ImageInput => targets.as_ref().and_then(|colors| colors.get(i)).copied().unwrap_or(matcher.target_color), - }; - let moved = matcher.apply([r, g, b].map(|v| v / a), source, target); - for (slot, v) in px.iter_mut().zip(moved) { - *slot += (v * a - *slot) * opacity; + let moved = remap(index, [red, green, blue].map(|component| component / alpha)); + for (slot, value) in pixel.iter_mut().zip(moved) { + *slot += (value * alpha - *slot) * opacity; } }); } +/// The mean of a premultiplied color region, or the fallback when no texel is covered +fn mean_region_color(data: &[f32], fallback: [f32; 3]) -> [f32; 3] { + // Premultiplication weights the color by coverage + let (color_sum, coverage_sum) = data + .par_chunks(4) + .fold( + || ([0.0f64; 3], 0.0f64), + |(mut colors, mut coverage), pixel| { + if let [red, green, blue, alpha] = *pixel + && alpha > 0.0 + && alpha.is_finite() + { + for (sum, component) in colors.iter_mut().zip([red, green, blue]) { + *sum += f64::from(component); + } + coverage += f64::from(alpha); + } + + (colors, coverage) + }, + ) + .reduce( + || ([0.0; 3], 0.0), + |(left, left_coverage), (right, right_coverage)| ([left[0] + right[0], left[1] + right[1], left[2] + right[2]], left_coverage + right_coverage), + ); + + if coverage_sum > 0.0 { color_sum.map(|component| (component / coverage_sum) as f32) } else { fallback } +} + /// Height To Normal at texel `(x, y)` into `acc`: the 3×3 Sobel normal of the heights `height` reads, laid over normal `center` unless it overwrites it fn height_to_normal_texel( filter: &HeightToNormal, @@ -906,7 +958,7 @@ fn kuwahara_texel( let falloff = (-KUWAHARA_FALLOFF * distance).exp(); let heading = v.atan2(u); for (k, (sum, square)) in sums.iter_mut().zip(&mut squares).enumerate() { - // The middle texel belongs to every sector; the others to the sectors they face, fading towards their sides + // The center contributes to every sector while other weights taper at sector boundaries let facing = (heading - k as f32 * std::f32::consts::TAU / AnisotropicKuwahara::SECTORS as f32).cos(); let weight = if distance <= 0.0 { falloff @@ -915,6 +967,7 @@ fn kuwahara_texel( } else { continue; }; + for (slot, value) in sum.iter_mut().zip(&px) { *slot += weight * value; } @@ -924,7 +977,7 @@ fn kuwahara_texel( } } - // Calmer sectors weigh more, sharper the higher the Sharpness (in logs, so the powers can't overflow) + // Weight low-variance sectors more and use logarithms to avoid overflow let sharpness = kuwahara.sharpness_exponent(); let logs: [Option; AnisotropicKuwahara::SECTORS] = std::array::from_fn(|sector| { let (sum, square) = (sums.get(sector)?, squares.get(sector)?); @@ -1226,7 +1279,7 @@ fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel] } /// [`anchor_plan`], or the plain set stack when `lit` (a layer lit by its material reads the stack below it too) -fn below_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], (tx, ty): (u32, u32), fields: Option<&'a Fields>, lit: bool) -> Vec> { +fn below_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], (tx, ty): (u32, u32), fields: Option<&'a Fields>, lit: bool) -> Vec> { let anchors = anchor_plan(inp, id, channels, tx, ty, fields); if !anchors.is_empty() || !lit { return anchors; @@ -1301,7 +1354,7 @@ fn field( margins[index] += margins[index + 1]; } - // A wrapping filter reads across the set's edges, so it and every filter under it cover the whole set along an axis it crosses + // A wrapped dependency expands all lower stages across any crossed axis let own_wraps: Vec = filters.iter().map(|filter| wraps(effects, filter.0)).collect(); let mut wrapping = own_wraps.clone(); for index in (0..wrapping.len().saturating_sub(1)).rev() { @@ -1459,7 +1512,14 @@ fn filter_region( }; // The gray the filter's image input reads (its first; the filters that read one have one) - let input = filter_effect.zip(filter).and_then(|(effect, filter)| ImageInput::of(filter).first().map(|input| effect.input(input))); + let input = filter_effect.zip(filter).and_then(|(effect, filter)| { + // Color Match reads each input as linear color separately + if matches!(filter, Filter::ColorMatch(_)) { + return None; + } + + ImageInput::of(filter).first().map(|input| effect.input(input)) + }); let lit_prefix = channel == Some(Channel::BaseColor) && effects.iter().filter(|effect| effect.visible).take(index).any(|effect| lights_material(&effect.kind)); @@ -1569,8 +1629,9 @@ fn filter_region( // Color Match's Input and Image Input colors over the region, when its modes read them let match_inputs = match (op, filter_effect) { (Op::ColorMatch(matcher), Some(effect)) if opacity > 0.0 => { - let read = - |on: bool, input: ImageInput| on.then(|| input_colors(inputs, &effect.input(&input), ®ion_tiles, (region_x, region_y, width, height))); + let read = |on: bool, input: ImageInput| { + on.then(|| input_colors(inputs, &effect.input(&input), (id, channels, below), (region_x, region_y, width, height))) + }; [ read(matcher.source_mode == SourceColorMode::Input, ImageInput::SOURCE_INPUT), read(matcher.target_mode == TargetColorMode::ImageInput, ImageInput::TARGET_INPUT), @@ -1585,7 +1646,7 @@ fn filter_region( _ => 0.5, }; - // A Highpass in sRGB filters its colors encoded (decoded again below); one with Apply To Alpha keeps the colors on the new coverage + // Filter High Pass in its working space and preserve color when only coverage changes let (space, highpass_alpha) = match (op, job) { (Op::HighPass { space, alpha }, Job::Content(channel)) if components == 4 => { (if channel.kind() == ChannelKind::Color { space } else { HighpassSpace::Working }, alpha) @@ -1595,7 +1656,7 @@ fn filter_region( let covered = highpass_alpha.then(|| stack_values.clone()); recode(&mut stack_values, components, |rgb| space.encode(rgb)); - // A wrapped axis pads by the reach up to one period (past it the far side repeats), so a set pads to 3x its size at most + // Pad by at most one sampling period on either side because farther reads repeat let pad_x = if wrap && region_x == 0 && width == inputs.gbuf.width { reach.min(width) } else { 0 }; let pad_y = if wrap && region_y == 0 && height == inputs.gbuf.height { reach.min(height) } else { 0 }; @@ -1690,7 +1751,7 @@ fn filter_region( && let Some(filter) = filter { let kind = channel.map_or(ChannelKind::Scalar, Channel::kind); - map_blurred(&mut filtered_values, &stack_values, components, filter, kind, opacity); + map_blurred(&mut filtered_values, &stack_values, components, filter, inputs.gradient(filter).as_deref(), kind, opacity); } if pad == (0, 0) { filtered_values } else { unpad(&filtered_values, components, unpadded, pad) } }; @@ -1993,17 +2054,22 @@ fn mask_outline(data: &mut [f32], cover: &[f32], comps: usize, (width, height, r } /// Run point filter `filter` on blurred texels `data` (premultiplied content or masks) and mix the result over the unblurred `orig` by `opacity` -fn map_blurred(data: &mut [f32], orig: &[f32], comps: usize, filter: &Filter, kind: ChannelKind, opacity: f32) { +fn map_blurred(data: &mut [f32], orig: &[f32], comps: usize, filter: &Filter, gradient: Option<&PreparedGradient>, kind: ChannelKind, opacity: f32) { + let point = |value| match gradient { + Some(gradient) => gradient.point(kind, value), + None => filter.point(kind, value), + }; let straight = |value: f32, cover: f32| if cover > MIN_ALPHA { value / cover } else { 0.0 }; + data.par_chunks_mut(comps).zip(orig.par_chunks(comps)).for_each(|(pixel, original)| match (pixel, original) { ([value], [before]) => { - let mapped = filter.point(kind, [*value; 3]).map_or(*value, |gray| gray[0]); + let mapped = point([*value; 3]).map_or(*value, |gray| gray[0]); *value = before + (mapped - before) * opacity; } ([r, g, b, cover], [r0, g0, b0, cover0]) => { let before = [straight(*r0, *cover0), straight(*g0, *cover0), straight(*b0, *cover0)]; let blurred = [straight(*r, *cover), straight(*g, *cover), straight(*b, *cover)]; - let mixed = mix3(before, filter.point(kind, blurred).unwrap_or(before), opacity); + let mixed = mix3(before, point(blurred).unwrap_or(before), opacity); [*r, *g, *b, *cover] = [mixed[0] * cover0, mixed[1] * cover0, mixed[2] * cover0, *cover0]; } _ => {} @@ -2192,6 +2258,10 @@ fn effect_plans<'a>( EffectKind::Filter(filter) if !filter.is_neighbourhood() => ImageInput::of(filter).first().map(|input| effect.input(input)), _ => None, }, + gradient: match &effect.kind { + EffectKind::Filter(filter) => inp.gradient(filter), + _ => None, + }, } }) .collect() @@ -3154,7 +3224,7 @@ impl<'a, 'b> Texel<'a, 'b> { } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { - let ramp = filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map_or(value, lum); + let ramp = effect.ramp_at(filter, self.coords().uv.x.rem_euclid(1.0)).map_or(value, lum); value += (ramp - value) * opacity; } EffectKind::Filter(Filter::GrayscaleConversion(conversion)) => { @@ -3166,7 +3236,7 @@ impl<'a, 'b> Texel<'a, 'b> { } 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]); + let filtered = effect.point(filter, ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); value += (filtered - value) * opacity; } EffectKind::ColorSelection(selection) => { @@ -3582,8 +3652,9 @@ impl<'a, 'b> Texel<'a, 'b> { }, // A gradient's debug view shows its ramp left to right across each UV tile EffectKind::Filter(filter @ Filter::GradientMap { debug: true, .. }) => { - let ramp = - filter.ramp_at(self.coords().uv.x.rem_euclid(1.0)).map(|color| if chan_plan.kind == ChannelKind::Color { color } else { [lum(color); 3] }); + let ramp = effect + .ramp_at(filter, self.coords().uv.x.rem_euclid(1.0)) + .map(|color| if chan_plan.kind == ChannelKind::Color { color } else { [lum(color); 3] }); (ramp.map_or(value, |ramp| mix3(value, ramp, opacity)), coverage) } @@ -3603,7 +3674,7 @@ impl<'a, 'b> Texel<'a, 'b> { } // Neighbourhood filters come precomputed through `ChanPlan::start` - EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), + EffectKind::Filter(filter) => (effect.point(filter, chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), // Anchors are recorded by `eval`; mask-only effects leave content as it is EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection(_) | EffectKind::Compare { .. } => { (value, coverage) @@ -5066,6 +5137,7 @@ mod tests { 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, wrap: false }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 }] { @@ -5342,14 +5414,20 @@ mod tests { let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0; 3], 1.0); assert!(!stack_reads_neighbours(&f.project, 0)); + let mut mask = Mask::new(MaskBackground::White); let eid = f.project.alloc_id(); mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(stack_reads_neighbours(&f.project, 0)); + f.project.layer_mut(id).unwrap().mask = None; + assert!(!stack_reads_neighbours(&f.project, 0)); + content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0, alpha: true })); + assert!(stack_reads_neighbours(&f.project, 0)); } @@ -5456,7 +5534,9 @@ soft {soft:?}" f.pixels.layer_mut(id, Channel::BaseColor, (64, 64)).set(3, 3, &[to_u16(0.5), 0, 0, to_u16(0.5)]); let posterize = content_fx(&mut f, id, EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: false })); assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [0.75, 0.25, 0.25]), "the coverage stays as it is"); + f.project.effect_mut(posterize).unwrap().kind = EffectKind::Filter(Filter::Posterize { levels: 2.0, alpha: true }); + assert!(close(run(&f, None).value(Channel::BaseColor, 3, 3), [1.0, 0.0, 0.0]), "half coverage rounds up to whole"); } @@ -5485,6 +5565,7 @@ soft {soft:?}" let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 1, 1), [0.625, 0.375, 0.375]), "the cell's coverage: {:?}", out.value(Channel::BaseColor, 1, 1)); assert!(close(out.value(Channel::BaseColor, 2, 2), [0.625, 0.375, 0.375]), "spread over the cell"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Mosaic { size: 128.0, alpha: false }); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 1, 1), [1.0, 0.0, 0.0]), "the texel keeps its whole coverage"); @@ -5501,6 +5582,7 @@ soft {soft:?}" let mut f = fixture(); let id = painted(&mut f, |x, y| Some((if stairs(x, y) { [1.0; 3] } else { [0.0; 3] }, 1.0))); assert_eq!(mids(&run(&f, None)), 0); + content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); let out = run(&f, None); assert!(mids(&out) > 16, "{} texels blended", mids(&out)); @@ -5511,8 +5593,11 @@ soft {soft:?}" let id = painted(&mut f, |x, y| stairs(x, y).then_some(([1.0; 3], 1.0))); let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Fxaa { alpha: false })); let plain = |out: &Composite| (0..64 * 64).all(|i| [0.5, 1.0].iter().any(|v| (out.value(Channel::BaseColor, i % 64, i / 64)[0] - v).abs() < 2e-4)); + assert!(plain(&run(&f, None)), "each texel keeps its coverage"); + f.project.effect_mut(fx).unwrap().kind = EffectKind::Filter(Filter::Fxaa { alpha: true }); + assert!(!plain(&run(&f, None)), "the coverage is smoothed"); } @@ -5523,6 +5608,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::White); mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Hsl { hue: 0.3, saturation: 1.0, lightness: -0.5, perceptive: false }))); f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.75; 3])); } @@ -5572,11 +5658,13 @@ soft {soft:?}" // The checker tiles: its period P repeats across the whole row let hard = row(None); let period = (1..64).find(|&p| (0..64 - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= 32, "{hard:?}"); // Wrapped, the blur at the texture's edge sees the far side, so the result keeps tiling; clipped, the edge differs let wrapped = row(Some(true)); assert!((0..64 - period).all(|x| (wrapped[x] - wrapped[x + period]).abs() < 0.02), "{wrapped:?}"); + let clipped = row(Some(false)); assert!((clipped[0] - clipped[period]).abs() > 0.05, "{clipped:?}"); assert!((12..52).all(|x| (clipped[x] - wrapped[x]).abs() < 0.02), "away from the edges, wrap changes nothing"); @@ -5600,6 +5688,7 @@ soft {soft:?}" }; let hard = composite(None, &all_tiles(WIDTH, HEIGHT)); let period = (1..WIDTH as usize).find(|&p| (0..WIDTH as usize - p).all(|x| (hard[x] - hard[x + p]).abs() < 1e-3)).unwrap(); + assert!(period <= WIDTH as usize / 2, "the checker tiles across the set: {hard:?}"); let wrapping = [ @@ -5627,6 +5716,7 @@ soft {soft:?}" }; let mut gradient = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); let hard = row(Some(gradient.clone())); + assert!(hard.iter().zip(row(None)).all(|(a, b)| (a - b).abs() < 1e-3), "a black to white ramp keeps a scalar as it is"); // Blurred first, then looked up: the same as a blur of that size @@ -5646,6 +5736,7 @@ soft {soft:?}" let below = fill_layer(&mut f.project, [0.0; 3], 0.0); let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); assert_ne!(below, id); + let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0, space: HighpassSpace::SrgbFromLinear, alpha: false })); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 30, 30), [texturecraft_texel::srgb_to_linear(0.5); 3]), "{:?}", out.value(Channel::BaseColor, 30, 30)); @@ -5699,12 +5790,15 @@ soft {soft:?}" let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 })); let out = run(&f, None); let vals: Vec = (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| out.value(Channel::Roughness, x, y)[0]).collect(); + assert!(vals.iter().all(|v| (0.0..=1.0).contains(v))); assert!(vals.iter().filter(|v| **v > 0.5).count() > 64 && vals.iter().filter(|v| **v < 0.01).count() > 64, "{vals:?}"); + f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != edges); content_fx(&mut f, id, EffectKind::Filter(Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3, divider: 1 })); let warped = run(&f, None); let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2)); + assert!(differs, "the warp moves the checker"); // Point filters @@ -5751,6 +5845,7 @@ soft {soft:?}" let glow = Filter::HaloGlow { on_mask: true, precise: false, width: 1.0, spread: 0.0, opacity: 1.0, color: [1.0; 3] }; let glowing = row_of(Some(glow)); assert!(glowing.iter().zip(&plain).all(|(g, p)| *g >= p - 1e-4), "a glow only adds"); + let lit = (0..64 * 64).filter(|&i| dark(plain[i]) && glowing[i] > low + 0.1 * (high - low)).count(); assert!(lit > 64, "{lit} dark texels lit"); @@ -5758,6 +5853,7 @@ soft {soft:?}" let shadow = Filter::DropShadow { angle: 90.0, distance: 0.1, size: 0.0, spread: 0.0, opacity: 0.5, color: [0.0; 3] }; let shadowed = row_of(Some(shadow)); assert!(shadowed.iter().zip(&plain).all(|(s, p)| *s >= p - 1e-4), "a shadow only goes under the shapes"); + let reach = 6; let at = |x: usize, y: usize| plain[y * 64 + x]; let (mut below, mut above) = (Vec::new(), Vec::new()); @@ -5771,7 +5867,9 @@ soft {soft:?}" } } } + assert!(!below.is_empty() && !above.is_empty()); + let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; assert!(mean(&below) > 0.2 * (high - low), "under: {below:?}"); assert!(mean(&above) < 0.05 * (high - low), "above: {above:?}"); @@ -5836,8 +5934,10 @@ soft {soft:?}" // Facing the light adds illumination; facing away keeps ambient only let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 }); assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}"); + let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 }); assert!(close(away, [0.2; 3]), "{away:?}"); + let f = Filter::BakedLighting { azimuth: 0.0, elevation: 0.0, light: 0.0, ambient: 1.0, occlusion: 0.5, stylized: None }; assert_eq!(f.baked_light([0.0, 1.0, 0.0], 0.2), Some(0.6), "half the occlusion"); assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); @@ -5886,9 +5986,44 @@ soft {soft:?}" // The roughness below (0.8) passes the first compare everywhere: the mask so far is white let white = *mask_so_far.last().unwrap(); + assert!(white > 0 && mask_so_far.iter().sum::() == white, "{mask_so_far:?}"); } + #[test] + fn color_match_reads_the_anchor_in_either_image_input() { + let mut fixture = fixture(); + let original_color = [0.6, 0.19, 0.09]; + let target_color = [0.1, 0.3, 0.8]; + let lower = fill_layer(&mut fixture.project, original_color, 0.5); + let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); + let upper = fill_layer(&mut fixture.project, original_color, 0.5); + let source = Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }; + + let matcher = ColorMatch { source_mode: SourceColorMode::Input, target_color, custom_variation: false, ..ColorMatch::LIBRARY }; + let effect_id = content_fx(&mut fixture, upper, EffectKind::Filter(Filter::ColorMatch(matcher))); + let effect = fixture.project.effect_mut(effect_id).unwrap(); + effect.inputs.insert(ImageInput::SOURCE_INPUT.id.to_owned(), source.clone()); + + let from_anchor = run(&fixture, None).value(Channel::BaseColor, 30, 30); + + assert!(close(from_anchor, target_color), "{from_anchor:?}"); + + let effect = fixture.project.effect_mut(effect_id).unwrap(); + effect.kind = EffectKind::Filter(Filter::ColorMatch(ColorMatch { + source_mode: SourceColorMode::Parameter, + source_color: original_color, + target_mode: TargetColorMode::ImageInput, + ..matcher + })); + effect.inputs.clear(); + effect.inputs.insert(ImageInput::TARGET_INPUT.id.to_owned(), source); + + let to_anchor = run(&fixture, None).value(Channel::BaseColor, 30, 30); + + assert!(close(to_anchor, original_color), "{to_anchor:?}"); + } + #[test] fn a_histogram_shares_one_field_of_a_stage_reading_the_whole_set() { let mut f = fixture(); @@ -5899,7 +6034,10 @@ soft {soft:?}" let inp = inputs(&f, &images, None); let channels = f.project.texture_set(0).unwrap().channel_list(); - let shared = shared_histogram_fields(&inp, &channels, &all_tiles(64, 64)); + let projectors = ProjectorDepthCache::default(); + let inputs = EvaluationInputs::new(&inp, &projectors); + + let shared = shared_histogram_fields(&inputs, &channels, &all_tiles(64, 64)); assert!(shared.is_some_and(|fields| fields.contains_key(&FieldKey::Content(id, Channel::BaseColor))), "every sampled tile reads one field"); } @@ -6026,15 +6164,18 @@ soft {soft:?}" let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })); f.project.layer_mut(top).unwrap().mask = Some(mask.clone()); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // The field pre-pass reads anchors under blur, preserving flat height mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); f.project.layer_mut(top).unwrap().mask = Some(mask); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); // An anchor above its reader is not evaluated yet, so it reads the channel default f.project.move_layer(low, 1).unwrap(); + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } @@ -6070,11 +6211,13 @@ soft {soft:?}" mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false }))); fixture.project.layer_mut(low).unwrap().mask = Some(mask.clone()); let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.4; 3]), "{color:?}"); // An empty paint layer still records its mask anchor for the layer above fixture.project.layer_mut(low).unwrap().kind = LayerKind::Paint; let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); } @@ -6097,6 +6240,7 @@ soft {soft:?}" let reader = anchor_reader(&mut fixture, anchor); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let expected = assert_sparse_mask_matches_image(&fixture, reader, &texels).unwrap(); + assert!(expected.iter().any(|value| *value > 0.1 && *value < 0.9), "the anchor records a softened checker"); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 128.0, wrap: false }))); @@ -6153,6 +6297,7 @@ soft {soft:?}" // A dim gray is valid for a dielectric only: the layer's metal makes it red in the filter's prepass and in the flattened layer assert!(close(blurred, PbrValidate::INVALID), "{blurred:?}"); + let (_, _, data) = flat.iter().find(|(channel, tile, _)| *channel == Channel::BaseColor && *tile == (0, 0)).unwrap(); let texel = (30 * TILE as usize + 30) * 4; let flattened: [f32; 3] = std::array::from_fn(|i| from_u16(data[texel + i])); diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs new file mode 100644 index 00000000..a895001a --- /dev/null +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -0,0 +1,45 @@ +use std::collections::HashMap; +use std::ops::Deref; +use std::sync::{Arc, Mutex, PoisonError}; + +use texturecraft_core::{Filter, PreparedGradient}; + +use super::Inputs; +use crate::ProjectorDepthCache; + +pub(super) struct EvaluationInputs<'a> { + inputs: &'a Inputs<'a>, + pub(super) projectors: &'a ProjectorDepthCache, + gradients: Mutex>>, +} + +impl<'a> EvaluationInputs<'a> { + pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self { + Self { inputs, projectors, gradients: Mutex::default() } + } + + pub(super) fn gradient(&self, filter: &'a Filter) -> Option> { + if !matches!(filter, Filter::GradientMap { linear: false, .. }) { + return None; + } + + // The borrowed project keeps filter addresses stable for this evaluation + let key = std::ptr::from_ref(filter) as usize; + let mut gradients = self.gradients.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(prepared) = gradients.get(&key) { + return Some(Arc::clone(prepared)); + } + + let prepared = Arc::new(PreparedGradient::of(filter)?); + gradients.insert(key, Arc::clone(&prepared)); + Some(prepared) + } +} + +impl<'a> Deref for EvaluationInputs<'a> { + type Target = Inputs<'a>; + + fn deref(&self) -> &Self::Target { + self.inputs + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 65cf4271..852127e0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -33,6 +33,7 @@ pub mod pattern; mod pattern_context; pub mod projector_cover; pub mod projector_depth; +mod projector_depth_cache; pub mod projector_view; mod shape_distance; mod slope_texel; diff --git a/crates/compose/src/shape_distance.rs b/crates/compose/src/shape_distance.rs index 0f3df3a7..60fd130c 100644 --- a/crates/compose/src/shape_distance.rs +++ b/crates/compose/src/shape_distance.rs @@ -37,9 +37,8 @@ pub(crate) fn distance_filter( [value] => *value, _ => 0.0, }; - let values: Vec = data.par_chunks(components).map(value).collect(); let shapes = |inside: &(dyn Fn(f32) -> bool + Sync)| -> Vec { - values.par_iter().zip(cover.par_iter()).map(|(value, covered)| *covered > 0.0 && inside(*value)).collect() + data.par_chunks(components).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && inside(value(pixel))).collect() }; let smoothed = |field: &mut [f32], texels: f32| { let radius = texels.round() as usize; @@ -55,15 +54,22 @@ pub(crate) fn distance_filter( let edge = edge_distances(&inside, (width, height), bevel.corner == BevelCorner::Angular); let reach = bevel.reach(tile_resolution); let mut slope: Vec = inside.par_iter().zip(edge.par_iter()).map(|(inside, edge)| bevel.slope(*inside, *edge, reach)).collect(); - let mut blurred = slope.clone(); - smoothed(&mut blurred, bevel.smoothing_texels(tile_resolution)); - slope.par_iter_mut().zip(blurred.par_iter()).for_each(|(sharp, blurred)| { - *sharp = match bevel.blur { - BevelBlur::Uniform => *blurred, - // Sharp at the slope's foot, as blurred as Uniform at its top - BevelBlur::NonUniform => *sharp + (blurred - *sharp) * *sharp, - }; - }); + drop(edge); + + let smoothing_radius = bevel.smoothing_texels(tile_resolution).round() as usize; + if smoothing_radius > 0 { + match bevel.blur { + BevelBlur::Uniform => blur(&mut slope, width, height, smoothing_radius), + BevelBlur::NonUniform => { + let mut blurred = slope.clone(); + blur(&mut blurred, width, height, smoothing_radius); + + // Keep the foot sharp and blur the top at full strength + slope.par_iter_mut().zip(blurred).for_each(|(sharp, blurred)| *sharp += (blurred - *sharp) * *sharp); + } + } + } + let bevel = *bevel; (inside, Box::new(move |texel, inside, value| bevel.apply(inside, value, slope.get(texel).copied().unwrap_or(1.0)))) } @@ -77,6 +83,7 @@ pub(crate) fn distance_filter( .enumerate() .map(|(texel, (inside, edge))| smooth.value(curve, *inside, *edge, reach * map(texel))) .collect(); + drop(edge); smoothed(&mut ramp, smooth.smoothing_texels(tile_resolution)); (inside, Box::new(move |texel, _, value| ramp.get(texel).copied().unwrap_or(value))) } @@ -116,34 +123,42 @@ pub(crate) fn distance_filter( /// Every texel's distance (texels) to the edge between it and the nearest texel on the other side of the shapes `inside`: straight-line, or the larger axis distance when `angular` fn edge_distances(inside: &[bool], (width, height): (usize, usize), angular: bool) -> Vec { - let outside: Vec = inside.iter().map(|inside| !inside).collect(); - let (to_inside, to_outside) = if angular { - (chessboard_distances(inside, (width, height)), chessboard_distances(&outside, (width, height))) - } else { - (straight_distances(inside, (width, height)), straight_distances(&outside, (width, height))) - }; - inside - .par_iter() - .zip(to_inside.par_iter().zip(to_outside.par_iter())) - .map(|(inside, (to_inside, to_outside))| (if *inside { *to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0)) - .collect() + let distances = if angular { chessboard_distances } else { straight_distances }; + let mut to_inside = distances(inside, (width, height), true); + let to_outside = distances(inside, (width, height), false); + + to_inside + .par_iter_mut() + .zip(to_outside) + .zip(inside) + .for_each(|((to_inside, to_outside), inside)| *to_inside = (if *inside { to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0)); + + to_inside } -/// Every texel's straight-line distance (texels) to the nearest texel where `feature` holds; farther than the region when none does -fn straight_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { - // Squared distances, separable: along the rows, then along the columns of those +/// Each texel's straight-line distance to the nearest texel on the requested side. +fn straight_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec { + // Start beyond the region so a line without a feature stays out of reach let far = ((width + height) as f32).powi(2); - let mut rows: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + let mut rows: Vec = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect(); rows.par_chunks_mut(width.max(1)).for_each_init(DistanceEnvelope::default, |envelope, row| envelope.lower(row)); + let mut columns: Vec = (0..width * height).map(|at| rows.get((at % height.max(1)) * width + at / height.max(1)).copied().unwrap_or(far)).collect(); columns.par_chunks_mut(height.max(1)).for_each_init(DistanceEnvelope::default, |envelope, column| envelope.lower(column)); - (0..width * height).map(|at| columns.get((at % width.max(1)) * height + at / width.max(1)).copied().unwrap_or(far).sqrt()).collect() + + // Reuse the row buffer for the final distances in row-major order + rows.resize(width * height, far); + for (index, distance) in rows.iter_mut().enumerate() { + *distance = columns.get((index % width.max(1)) * height + index / width.max(1)).copied().unwrap_or(far).sqrt(); + } + + rows } -/// Every texel's distance (texels, the larger of across and down) to the nearest texel where `feature` holds; farther than the region when none does -fn chessboard_distances(feature: &[bool], (width, height): (usize, usize)) -> Vec { +/// Each texel's distance to the nearest texel on the requested side, measured along the larger axis. +fn chessboard_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec { let far = (width + height) as f32; - let mut distances: Vec = feature.iter().map(|feature| if *feature { 0.0 } else { far }).collect(); + let mut distances: Vec = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect(); // One pass down from the texels above and left, one up from those below and right let step = |distances: &mut [f32], (x, y): (usize, usize), neighbours: [(isize, isize); 4]| { @@ -210,6 +225,7 @@ fn trail_steps((width, height): (usize, usize), direction: [f32; 2], reach: f32) if steps.last().is_some_and(|(last_across, last_down, _)| (*last_across, *last_down) == (across, down)) { continue; } + steps.push((across, down, if reach > 0.0 { back / reach } else { 0.0 })); } steps @@ -289,12 +305,12 @@ mod tests { // One feature texel in the middle of a 5 × 5 region let mut feature = vec![false; 25]; feature[12] = true; - let straight = straight_distances(&feature, (5, 5)); - let chessboard = chessboard_distances(&feature, (5, 5)); + let straight = straight_distances(&feature, (5, 5), true); + let chessboard = chessboard_distances(&feature, (5, 5), true); assert_eq!((straight[12], straight[13], chessboard[13]), (0.0, 1.0, 1.0)); assert!((straight[0] - 8f32.sqrt()).abs() < 1e-5, "{}", straight[0]); assert_eq!(chessboard[0], 2.0, "a corner is as far as its larger axis"); - let none = straight_distances(&[false; 4], (2, 2)); + let none = straight_distances(&[false; 4], (2, 2), true); assert!(none.iter().all(|distance| *distance >= 4.0), "no feature is beyond the region"); } @@ -304,8 +320,8 @@ mod tests { let (width, height) = (7, 3); let mut feature = vec![false; width * height]; feature[1] = true; - let straight = straight_distances(&feature, (width, height)); - let chessboard = chessboard_distances(&feature, (width, height)); + let straight = straight_distances(&feature, (width, height), true); + let chessboard = chessboard_distances(&feature, (width, height), true); let at = |x: usize, y: usize| y * width + x; assert_eq!((straight[at(1, 0)], straight[at(6, 0)], straight[at(1, 2)]), (0.0, 5.0, 2.0)); @@ -360,8 +376,8 @@ mod tests { #[test] fn shared_trail_steps_find_what_each_texel_walking_its_own_finds() { - // About one texel in fifty a shape, in a region whose rows end part way through a word - // Small enough that the walk's float sums round as exactly as the shared steps (thousands of texels across, a near tie can round a texel over) + // Sparse rows end partway through a word + // Keep the region small enough to avoid rounding nearly tied rays into different texels let (width, height) = (150, 97); let mut seed = 12345u32; let inside: Vec = (0..width * height) diff --git a/crates/compose/src/soft_box.rs b/crates/compose/src/soft_box.rs index b1fba4f7..7145148b 100644 --- a/crates/compose/src/soft_box.rs +++ b/crates/compose/src/soft_box.rs @@ -16,11 +16,16 @@ const EDGE_FADE_START: f32 = 0.8; const EDGE_FADE_WIDTH: f32 = 0.4; impl SoftBox { - /// The light the box sends along direction `d` - pub fn eval(&self, d: Vec3) -> Vec3 { - let elevation = d.y.clamp(-1.0, 1.0).asin().to_degrees(); - let azimuth = d.z.atan2(d.x).to_degrees(); + /// Convert the sampled direction to degrees once for all the lights + pub fn angles(direction: Vec3) -> (f32, f32) { + let elevation = direction.y.clamp(-1.0, 1.0).asin().to_degrees(); + let azimuth = direction.z.atan2(direction.x).to_degrees(); + (azimuth, elevation) + } + + /// The light the box sends along the sampled azimuth and elevation + pub fn eval(&self, azimuth: f32, elevation: f32) -> Vec3 { // The azimuth difference wrapped to -180..180 degrees let azimuth_step = ((azimuth - self.azimuth + 540.0).rem_euclid(360.0)) - 180.0; let (x, y) = (azimuth_step.abs() / self.half_width, (elevation - self.elevation).abs() / self.half_height); diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 423b6975..014e9ec5 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -980,6 +980,7 @@ fn filter_input_and_id_map_image_changes_invalidate_stack_key() { for name in ["input", "id"] { let original = stack_key(&fixture, &images); images.insert(name.into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != original, "replacing the {name} image must invalidate the cache"); } } @@ -995,6 +996,7 @@ fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { let unlit = stack_key(&fixture, &images); fixture.project.display.env_rotation += 90.0; + assert_eq!(stack_key(&fixture, &images), unlit, "without Baked Lighting Environment the turn changes nothing"); let lighting = @@ -1008,6 +1010,7 @@ fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() { assert_eq!(lit.changed_tiles(&turned), None, "and recomposites every tile"); images.insert("sky".into(), flat_image(0.9)); + assert!(stack_key(&fixture, &images) != turned, "replacing the environment image invalidates the cache"); } diff --git a/crates/core/src/color_match.rs b/crates/core/src/color_match.rs index c945bf72..8b25ee85 100644 --- a/crates/core/src/color_match.rs +++ b/crates/core/src/color_match.rs @@ -51,28 +51,44 @@ impl ColorMatch { /// Linear `color` moved by the step from `source` to `target`; without Custom Color Variation it keeps all of its difference from the source, with it at most Hue, Chroma and Luma of it (all 0: the target color itself). Hostile values give the color back pub fn apply(&self, color: [f32; 3], source: [f32; 3], target: [f32; 3]) -> [f32; 3] { - let [lightness, a, b] = oklab::from_linear(color.map(|v| v.max(0.0))); - let [source_lightness, source_a, source_b] = oklab::from_linear(source.map(|v| v.max(0.0))); - let [target_lightness, target_a, target_b] = oklab::from_linear(target.map(|v| v.max(0.0))); + let lab = |color: [f32; 3]| oklab::from_linear(color.map(|component| component.max(0.0))); + let [lightness, a, b] = lab(color); + let [source_lightness, source_a, source_b] = lab(source); + let [target_lightness, target_a, target_b] = lab(target); let moved = if self.custom_variation { - let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; - let keep = |difference: f32, max: f32| difference.clamp(-max, max); - let (chroma, hue) = (a.hypot(b), b.atan2(a)); - let (source_chroma, source_hue) = (source_a.hypot(source_b), source_b.atan2(source_a)); - let (target_chroma, target_hue) = (target_a.hypot(target_b), target_b.atan2(target_a)); - let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; - let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA)); - let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0); - let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians()); - [out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()] + self.move_polar(polar([lightness, a, b]), polar([source_lightness, source_a, source_b]), polar([target_lightness, target_a, target_b])) } else { [target_lightness + lightness - source_lightness, target_a + a - source_a, target_b + b - source_b] }; - let out = oklab::to_linear(moved); - if out.iter().all(|v| v.is_finite()) { out.map(|v| v.clamp(0.0, 1.0)) } else { color } + matched_linear(color, moved) } + + #[inline] + pub(super) fn move_polar( + &self, + [lightness, chroma, hue]: [f32; 3], + [source_lightness, source_chroma, source_hue]: [f32; 3], + [target_lightness, target_chroma, target_hue]: [f32; 3], + ) -> [f32; 3] { + let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 }; + let keep = |difference: f32, max: f32| difference.clamp(-max, max); + let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI; + let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA)); + let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0); + let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians()); + [out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()] + } +} + +pub(super) fn polar([lightness, a, b]: [f32; 3]) -> [f32; 3] { + [lightness, a.hypot(b), b.atan2(a)] +} + +pub(super) fn matched_linear(original: [f32; 3], lab: [f32; 3]) -> [f32; 3] { + let out = oklab::to_linear(lab); + if out.iter().all(|value| value.is_finite()) { out.map(|value| value.clamp(0.0, 1.0)) } else { original } } #[cfg(test)] diff --git a/crates/core/src/curve_preset.rs b/crates/core/src/curve_preset.rs index 97d843c4..fe586794 100644 --- a/crates/core/src/curve_preset.rs +++ b/crates/core/src/curve_preset.rs @@ -124,6 +124,7 @@ mod tests { fn every_preset_stays_in_range_and_reads_a_non_finite_t_as_0() { for preset in CurvePreset::ALL { let values: Vec = (0..=SAMPLES).map(|i| preset.at(i as f32 / SAMPLES as f32)).collect(); + assert!(values.iter().all(|value| (0.0..=1.0).contains(value)), "{}", preset.id()); assert_eq!(preset.at(f32::NAN), preset.at(0.0), "{}", preset.id()); assert_eq!(preset.at(f32::INFINITY), preset.at(0.0), "{}", preset.id()); @@ -134,6 +135,7 @@ mod tests { fn stairs_has_four_levels_and_triangular_two_teeth() { let mut levels: Vec = (0..=SAMPLES).map(|i| CurvePreset::Stairs.at(i as f32 / SAMPLES as f32)).collect(); levels.dedup(); + assert_eq!(levels, [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); let triangular = |t: f32| CurvePreset::Triangular.at(t); diff --git a/crates/core/src/gradient_input.rs b/crates/core/src/gradient_input.rs index 12f99b20..042b59dd 100644 --- a/crates/core/src/gradient_input.rs +++ b/crates/core/src/gradient_input.rs @@ -2,8 +2,8 @@ use serde::{Deserialize, Serialize}; -use crate::finite_unit; use crate::grayscale_mode::GrayscaleMode; +use crate::{ChannelKind, finite_unit, lum, per_unit}; /// Full contrast stays a finite step instead of a division by zero const MIN_STEEPNESS: f32 = 1e-3; @@ -44,13 +44,23 @@ impl GradientInput { /// The ramp position of gray `x` pub fn shape(&self, x: f32) -> f32 { - // Left as it is, the gray reaches the ramp bit for bit as projects saved before read it (the ramp clamps it) + // Preserve the exact input when the transformation is neutral if self.balance == NEUTRAL_BALANCE && self.contrast == 0.0 && !self.invert { return x; } shape_gray(x, self.balance, self.contrast, self.invert) } + + /// Apply a gradient to a channel using its ramp sampler + pub fn map(&self, kind: ChannelKind, value: [f32; 3], sample: impl Fn(f32) -> Option<[f32; 3]>) -> Option<[f32; 3]> { + if kind == ChannelKind::Color { + return sample(self.shape(self.mode.gray(value))); + } + + // Preserve the signed-channel mapping and leave normals alone + Some(per_unit(kind, value, |gray| sample(self.shape(gray)).map_or(gray, lum))) + } } /// Gray `x` balanced (0.5 keeps it), contrasted around mid gray (0 keeps it, 1 is a step at 0.5) and maybe inverted, in 0..1 @@ -64,17 +74,21 @@ pub fn shape_gray(x: f32, balance: f32, contrast: f32, invert: bool) -> f32 { /// A ramp stop's place and color type Stop = (f32, [f32; 3]); +pub(crate) fn ramp_stops<'a>(colors: &'a [[f32; 3]], positions: &'a [f32]) -> impl ExactSizeIterator + 'a { + let last = colors.len().saturating_sub(1); + colors.iter().copied().enumerate().map(move |(index, color)| { + let even_position = || if last == 0 { 0.0 } else { index as f32 / last as f32 }; + let position = positions.get(index).copied().filter(|position| position.is_finite()).unwrap_or_else(even_position); + (position.clamp(0.0, 1.0), color) + }) +} + /// The color at `t` on a ramp of `colors` placed at `positions` (each 0..1, evenly spaced where missing), blended in linear or sRGB pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Option<[f32; 3]> { - let last = colors.len().checked_sub(1)?; - let even = |index: usize| if last == 0 { 0.0 } else { index as f32 / last as f32 }; - let stops = colors - .iter() - .enumerate() - .map(|(index, color)| (positions.get(index).copied().filter(|p| p.is_finite()).unwrap_or_else(|| even(index)).clamp(0.0, 1.0), *color)); + let stops = ramp_stops(colors, positions); let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - // The stops each side of `t` without sorting them, per texel: the last placed at or before it and the first placed after it + // Keep the last stop at or before the sample and the first stop after it let (mut before, mut after): (Option, Option) = (None, None); for (position, color) in stops { if position <= t { @@ -91,15 +105,14 @@ pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Opt (None, None) => return None, }; + let encode = |color: [f32; 3]| if linear { color } else { color.map(linear_to_srgb) }; + Some(interpolate((before_place, encode(before_color)), (after_place, encode(after_color)), linear, t)) +} + +pub(crate) fn interpolate((before_place, before_color): Stop, (after_place, after_color): Stop, linear: bool, t: f32) -> [f32; 3] { let share = if after_place > before_place { ((t - before_place) / (after_place - before_place)).clamp(0.0, 1.0) } else { 0.0 }; - Some(if linear { - std::array::from_fn(|k| before_color[k] + (after_color[k] - before_color[k]) * share) - } else { - std::array::from_fn(|k| { - let (before, after) = (linear_to_srgb(before_color[k]), linear_to_srgb(after_color[k])); - srgb_to_linear(before + (after - before) * share) - }) - }) + let color = std::array::from_fn(|component| before_color[component] + (after_color[component] - before_color[component]) * share); + if linear { color } else { color.map(srgb_to_linear) } } // A copy of texturecraft_texel's: texel and core are both layer 0, so core cannot use it diff --git a/crates/core/src/grayscale_conversion.rs b/crates/core/src/grayscale_conversion.rs index 3f186a7d..126b9b3b 100644 --- a/crates/core/src/grayscale_conversion.rs +++ b/crates/core/src/grayscale_conversion.rs @@ -69,10 +69,13 @@ mod tests { fn weights_balance_contrast_and_invert_shape_the_gray() { let only_red = GrayscaleConversion { weights: [1.0, 0.0, 0.0, 0.0], ..GrayscaleConversion::LIBRARY }; assert!((only_red.gray([0.6, 1.0, 1.0], 1.0) - 0.6).abs() < 1e-6); + let alpha = GrayscaleConversion { weights: [0.0, 0.0, 0.0, 1.0], ..GrayscaleConversion::LIBRARY }; assert!((alpha.gray([1.0; 3], 0.25) - 0.25).abs() < 1e-6, "Alpha weighs the coverage"); + let inverted = GrayscaleConversion { invert: true, mode: ConversionMode::Max, ..GrayscaleConversion::LIBRARY }; assert!((inverted.gray([0.2, 0.7, 0.1], 1.0) - 0.3).abs() < 1e-6); + let contrasted = GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..GrayscaleConversion::LIBRARY }; assert_eq!(contrasted.gray([0.6; 3], 1.0), 1.0); } diff --git a/crates/core/src/image_input.rs b/crates/core/src/image_input.rs index d935074f..751911c3 100644 --- a/crates/core/src/image_input.rs +++ b/crates/core/src/image_input.rs @@ -78,6 +78,7 @@ mod tests { fn a_warp_has_its_custom_noise_only_in_that_source_mode() { let warp = SourceWarp::LIBRARY; assert!(ImageInput::of(&Filter::SourceWarp(warp)).is_empty()); + let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, ..warp.source }, ..warp }; assert_eq!(ImageInput::of(&Filter::SourceWarp(custom)), vec![ImageInput::CUSTOM_NOISE]); assert_eq!(ImageInput::named(&Filter::SourceWarp(warp), "customNoise"), Some(ImageInput::CUSTOM_NOISE), "kept while the mode is off"); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1ff4e0fc..c819446b 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -8,39 +8,49 @@ use crate::curve_preset::CurvePreset; use crate::gradient_input::{GradientInput, ramp, shape_gray}; use crate::{ AnisotropicKuwahara, Backface, BakedMap, Bevel, BevelSmooth, BlendMode, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, DepthCulling, - DirectionalDistance, DirectionalLight, FillSymmetry, GrayscaleConversion, HeightToNormal, HighpassSpace, MaskOutline, Mirror, PbrValidate, Projector, - RandomizedSeed, ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, + DirectionalDistance, DirectionalLight, GrayscaleConversion, HeightToNormal, HighpassSpace, MaskOutline, Mirror, PbrValidate, Projector, RandomizedSeed, + ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, }; mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; +mod filtering; mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; +mod sampling; +mod scale_mode; mod tile_blending; mod tile_generator; mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_transform; +mod uv_wrap; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; +pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; +pub use sampling::Sampling; +pub use scale_mode::ScaleMode; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_transform::UvTransform; +pub use uv_wrap::UvWrap; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -1425,6 +1435,7 @@ pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [ if s <= 0.0 { return [l; 3]; } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; let p = 2.0 * l - q; [hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)] @@ -1621,11 +1632,7 @@ impl Filter { _ => per_unit(kind, v, |x| finite_unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)), } } - Filter::GradientMap { input, .. } => match kind { - ChannelKind::Color => self.ramp_at(input.shape(input.mode.gray(v)))?, - // A height reads the ramp at its 0..1 place, as projects saved before did - _ => per_unit(kind, v, |x| self.ramp_at(input.shape(x)).map_or(x, lum)), - }, + Filter::GradientMap { input, .. } => input.map(kind, v, |position| self.ramp_at(position))?, Filter::GradientCurve { preset, invert, balance, contrast } => per_unit(kind, v, |x| preset.at(shape_gray(x, *balance, *contrast, *invert))), Filter::GradientDynamic { color, .. } => match kind { ChannelKind::Color => color.map(finite_unit), @@ -2366,6 +2373,7 @@ mod tests { let x = step as f32 / 1000.0; let color = [x, 0.5 * x, 1.0 - x]; assert_eq!(gm.point(ChannelKind::Color, color), gradient(&colors, lum(color)), "color {color:?}"); + let height = 2.0 * x - 1.0; let saved_before = per_unit(ChannelKind::Signed, [height; 3], |t| gradient(&colors, t).map_or(t, lum)); assert_eq!(gm.point(ChannelKind::Signed, [height; 3]), Some(saved_before), "height {height}"); @@ -2379,29 +2387,39 @@ mod tests { let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 }; assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0])); assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3])); + let gm = Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]); assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0])); assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0])); assert_eq!(Filter::even_gradient(vec![]).point(c, [0.3; 3]), None, "an empty gradient changes nothing"); + let gray_ramp = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]); assert!(close(gray_ramp.point(ChannelKind::Signed, [-0.6; 3]).unwrap(), [-0.6; 3]), "a height reads the ramp at its 0..1 place"); assert!(close(Filter::Posterize { levels: 2.0, alpha: false }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); + let scan = |position, contrast| Filter::HistogramScan { position, contrast, invert_position: false }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); + let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); + let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); + assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); + let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0])); + for f in [ Filter::Blur { radius: 1.0, wrap: false }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0, divider: 1 }, diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b05c708b..88ee96d1 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -45,6 +45,8 @@ pub mod mirror_mode; pub mod oklab; pub mod outline_position; pub mod pbr_validate; +mod prepared_color_match; +mod prepared_gradient; pub mod project; pub mod projector; pub mod ramp_curve; @@ -122,6 +124,8 @@ pub use mirror_corner::MirrorCorner; pub use mirror_mode::MirrorMode; pub use outline_position::OutlinePosition; pub use pbr_validate::PbrValidate; +pub use prepared_color_match::PreparedColorMatch; +pub use prepared_gradient::PreparedGradient; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, diff --git a/crates/core/src/mask_outline.rs b/crates/core/src/mask_outline.rs index cbd17456..de70f808 100644 --- a/crates/core/src/mask_outline.rs +++ b/crates/core/src/mask_outline.rs @@ -72,8 +72,10 @@ mod tests { assert_eq!(band(outline, false, 0.3), 1.0, "a hard band outside"); assert_eq!(band(outline, true, 0.3), 0.0, "nothing inside an outside band"); assert_eq!(band(outline, false, 0.0), 0.0, "nothing past its reach"); + let inside = MaskOutline { position: OutlinePosition::Inside, ..outline }; assert_eq!((band(inside, true, 0.3), band(inside, false, 0.3)), (1.0, 0.0)); + let both = MaskOutline { position: OutlinePosition::Both, ..outline }; assert_eq!((band(both, true, 0.3), band(both, false, 0.3)), (1.0, 1.0)); assert_eq!(outline.apply(0.4, 0.0), 0.0, "from black"); diff --git a/crates/core/src/mirror.rs b/crates/core/src/mirror.rs index 44831b81..9a2bd491 100644 --- a/crates/core/src/mirror.rs +++ b/crates/core/src/mirror.rs @@ -73,18 +73,23 @@ mod tests { let mut mirror = Mirror::LIBRARY; assert_eq!(mirror.source([0.25, 0.4]), [0.25, 0.4], "the left side stays"); assert_eq!(mirror.source([0.75, 0.4]), [0.25, 0.4], "the right side reads the left"); + mirror.invert[0] = true; + assert_eq!(mirror.source([0.25, 0.4]), [0.75, 0.4], "inverted, the left side reads the right"); mirror.offset[0] = 0.25; mirror.invert[0] = false; + assert_eq!(mirror.source([0.75, 0.0]), [0.25, 0.0], "a copy past the left edge folds back at it"); mirror.mode = MirrorMode::AxisY; + assert_eq!(mirror.source([0.9, 0.75]), [0.9, 0.25], "Axis Y reads the top for the bottom"); mirror.mode = MirrorMode::Corner; mirror.corner = MirrorCorner::BottomRight; + assert_eq!(mirror.source([0.25, 0.25]), [0.75, 0.75], "every quarter reads the kept one"); assert_eq!(mirror.source([0.75, 0.75]), [0.75, 0.75]); assert!(mirror.on_axis([0.5, 0.1], 0.01) && mirror.on_axis([0.1, 0.5], 0.01) && !mirror.on_axis([0.1, 0.1], 0.01)); diff --git a/crates/core/src/prepared_color_match.rs b/crates/core/src/prepared_color_match.rs new file mode 100644 index 00000000..0c97fa57 --- /dev/null +++ b/crates/core/src/prepared_color_match.rs @@ -0,0 +1,35 @@ +//! Reusable OKLab references for moving a region of colors + +use crate::color_match::{matched_linear, polar}; +use crate::{ColorMatch, oklab}; + +/// The settings and converted references for a region with constant source and target colors +#[derive(Clone, Copy, Debug)] +pub struct PreparedColorMatch { + settings: ColorMatch, + source: [f32; 3], + target: [f32; 3], +} + +impl PreparedColorMatch { + /// Prepare the fixed reference pair once for the region + pub fn new(settings: ColorMatch, source: [f32; 3], target: [f32; 3]) -> Self { + let reference = |color: [f32; 3]| { + let lab = oklab::from_linear(color.map(|component| component.max(0.0))); + if settings.custom_variation { polar(lab) } else { lab } + }; + Self { settings, source: reference(source), target: reference(target) } + } + + /// Move a texel using the prepared reference pair + pub fn apply(&self, color: [f32; 3]) -> [f32; 3] { + let lab = oklab::from_linear(color.map(|component| component.max(0.0))); + let moved = if self.settings.custom_variation { + self.settings.move_polar(polar(lab), self.source, self.target) + } else { + std::array::from_fn(|index| self.target[index] + lab[index] - self.source[index]) + }; + + matched_linear(color, moved) + } +} diff --git a/crates/core/src/prepared_gradient.rs b/crates/core/src/prepared_gradient.rs new file mode 100644 index 00000000..4e5fa307 --- /dev/null +++ b/crates/core/src/prepared_gradient.rs @@ -0,0 +1,35 @@ +use crate::gradient_input::{interpolate, linear_to_srgb, ramp_stops}; +use crate::{ChannelKind, Filter, GradientInput}; + +/// An sRGB gradient prepared for repeated sampling +pub struct PreparedGradient { + stops: Vec<(f32, [f32; 3])>, + input: GradientInput, +} + +impl PreparedGradient { + /// Prepare an sRGB ramp by converting its endpoints once + pub fn of(filter: &Filter) -> Option { + let Filter::GradientMap { positions, linear: false, input, .. } = filter else { return None }; + + let mut stops: Vec<_> = ramp_stops(filter.ramp_colors(), positions).map(|(position, color)| (position, color.map(linear_to_srgb))).collect(); + + // Stable order preserves which stop wins at shared positions + stops.sort_by(|left, right| left.0.total_cmp(&right.0)); + Some(Self { stops, input: *input }) + } + + /// Sample the prepared ramp at a normalized position + pub fn at(&self, position: f32) -> Option<[f32; 3]> { + let position = if position.is_finite() { position.clamp(0.0, 1.0) } else { 0.0 }; + let split = self.stops.partition_point(|stop| stop.0 <= position); + let before = split.checked_sub(1).and_then(|index| self.stops.get(index)).copied(); + let after = self.stops.get(split).copied(); + Some(interpolate(before.or(after)?, after.or(before)?, false, position)) + } + + /// Apply the prepared gradient to one value + pub fn point(&self, kind: ChannelKind, value: [f32; 3]) -> Option<[f32; 3]> { + self.input.map(kind, value, |position| self.at(position)) + } +} diff --git a/crates/core/src/source_warp.rs b/crates/core/src/source_warp.rs index 4891f752..f4b5b76a 100644 --- a/crates/core/src/source_warp.rs +++ b/crates/core/src/source_warp.rs @@ -109,12 +109,16 @@ mod tests { let warp = SourceWarp::LIBRARY; assert!((warp.move_texels(2048) - 20.48).abs() < 1e-3, "0.1 ÷ 10 of the tile"); assert_eq!(warp.angles().count(), 0); + let directional = SourceWarp { mode: WarpMode::Directional, angle: 30.0, ..warp }; assert_eq!(directional.angles().collect::>(), vec![30.0]); + let multi = SourceWarp { mode: WarpMode::MultiDirectional, angle: 10.0, ..warp }; assert_eq!(multi.angles().collect::>(), vec![10.0, 100.0, 190.0, 280.0]); + let chained = SourceWarp { blending: WarpBlending::Chain, ..multi }; assert!((chained.reach(2048) - 4.0 * 20.48).abs() < 1e-3, "four moves one after the other"); + let input = SourceWarp { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..warp }; assert!((input.reach(2048) - (20.48 + 8.0)).abs() < 1e-3, "plus where it measures the slope"); assert_eq!((SourceWarp::amount(0.0), SourceWarp::amount(0.5), SourceWarp::amount(1.0)), (-1.0, 0.0, 1.0)); @@ -125,8 +129,10 @@ mod tests { let warp = SourceWarp::LIBRARY; let gentle = warp.slope_move([0.01, 0.0], 2048); assert!(gentle[0] > 0.0 && gentle[0] < warp.move_texels(2048), "{gentle:?}"); + let steep = warp.slope_move([1.0, 1.0], 2048); assert!((steep[0].hypot(steep[1]) - warp.move_texels(2048)).abs() < 1e-3, "a cliff moves the whole way, no further: {steep:?}"); + let hostile = SourceWarp { intensity: f32::NAN, angle: f32::INFINITY, directions: 9, divider: 0, mode: WarpMode::MultiDirectional, ..warp }; assert_eq!((hostile.move_texels(2048), hostile.angles().collect::>()), (0.0, vec![0.0])); assert_eq!(hostile.slope_move([f32::NAN, 1.0], 2048)[0], 0.0); diff --git a/crates/core/src/stylized_lighting.rs b/crates/core/src/stylized_lighting.rs index 3c5289d8..3aa0801b 100644 --- a/crates/core/src/stylized_lighting.rs +++ b/crates/core/src/stylized_lighting.rs @@ -136,6 +136,7 @@ mod tests { let smooth = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)); let rough = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.9)); assert!(smooth[0] > rough[0] + 0.1 && rough[0] > 0.0, "{smooth:?} {rough:?}"); + let diffuse = StylizedLighting { output: LightingOutput::Diffuse, ..StylizedLighting::library() }; assert_eq!(diffuse.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)), [0.0; 3]); } @@ -148,9 +149,11 @@ mod tests { let cavities = StylizedLighting { diffuse_cavity: 1.0, ..StylizedLighting::PLAIN }; assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat: no cavity"); assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity"); + let sun = light(90.0, 1.0, 0.0); assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat in the sun: no cavity"); assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity in the sun"); + let edges = StylizedLighting { edges_intensity: 1.0, ..StylizedLighting::PLAIN }; assert_eq!(edges.shading(sky).shade(gray, UP, [1.0, 0.9], &material(0.5)), [1.0; 3], "a sharp edge"); } diff --git a/crates/core/src/stylized_shading.rs b/crates/core/src/stylized_shading.rs index 57d4d5ca..24bcdda8 100644 --- a/crates/core/src/stylized_shading.rs +++ b/crates/core/src/stylized_shading.rs @@ -101,6 +101,8 @@ impl StylizedShading { let kept = if self.output.specular() { 1.0 - metal } else { 1.0 }; (finite_unit(channel(Channel::Roughness)[0]), f0, albedo.map(|x| x * kept)) }; + let compute_diffuse = self.output.diffuse(); + let compute_specular = self.output.specular(); let roughness = roughness.max(MIN_ROUGHNESS); let sky = self.ambient(normal); @@ -109,7 +111,7 @@ impl StylizedShading { let diffuse_cavity = 1.0 - cavity * self.diffuse_cavity; let specular_cavity = 1.0 - cavity * self.specular_cavity; - let mut diffuse = sky.map(|sky_light| sky_light * self.sky_intensity * diffuse_ao * diffuse_cavity); + let mut diffuse = if compute_diffuse { sky.map(|sky_light| sky_light * self.sky_intensity * diffuse_ao * diffuse_cavity) } else { [0.0; 3] }; let mut specular = [0.0f32; 3]; for &(direction, intensity, color) in &self.lights { let facing = dot(normal, direction); @@ -117,21 +119,29 @@ impl StylizedShading { continue; } - let half = normalize([normal[0] + direction[0], normal[1] + direction[1], normal[2] + direction[2]]); - let normal_dot_half = dot(normal, half).max(0.0); - let highlight = ggx(normal_dot_half, roughness) / COOK_TORRANCE_DENOMINATOR * facing * specular_cavity; - for (((diffuse, specular), color), f0) in diffuse.iter_mut().zip(&mut specular).zip(color).zip(f0) { - *diffuse += color * intensity * facing * diffuse_cavity; - *specular += color * intensity * highlight * schlick(f0, normal_dot_half); + if compute_diffuse { + for (diffuse, color) in diffuse.iter_mut().zip(color) { + *diffuse += color * intensity * facing * diffuse_cavity; + } + } + if compute_specular { + let half = normalize([normal[0] + direction[0], normal[1] + direction[1], normal[2] + direction[2]]); + let normal_dot_half = dot(normal, half).max(0.0); + let highlight = ggx(normal_dot_half, roughness) / COOK_TORRANCE_DENOMINATOR * facing * specular_cavity; + for ((specular, color), f0) in specular.iter_mut().zip(color).zip(f0) { + *specular += color * intensity * highlight * schlick(f0, normal_dot_half); + } } } - for ((specular, f0), sky_light) in specular.iter_mut().zip(f0).zip(sky) { - *specular += f0 * sky_light * self.sky_intensity * specular_ao * specular_cavity; + if compute_specular { + for ((specular, f0), sky_light) in specular.iter_mut().zip(f0).zip(sky) { + *specular += f0 * sky_light * self.sky_intensity * specular_ao * specular_cavity; + } } - std::array::from_fn(|k| { - let lit = if self.output.diffuse() { diffuse_albedo[k] * diffuse[k] } else { 0.0 }; - let shine = if self.output.specular() { specular[k] } else { 0.0 }; + std::array::from_fn(|channel| { + let lit = if compute_diffuse { diffuse_albedo[channel] * diffuse[channel] } else { 0.0 }; + let shine = specular[channel]; let shaded = finite_unit(lit + shine); finite_unit(shaded + (1.0 - shaded) * edge * self.edges_intensity) }) diff --git a/crates/core/src/threshold_mode.rs b/crates/core/src/threshold_mode.rs index 3dc3b05b..953b649d 100644 --- a/crates/core/src/threshold_mode.rs +++ b/crates/core/src/threshold_mode.rs @@ -73,6 +73,7 @@ mod tests { fn a_threshold_saved_before_the_modes_reads_and_saves_as_before() { let saved = r#"{"Threshold":{"level":0.5}}"#; let filter: Filter = serde_json::from_str(saved).unwrap(); + assert_eq!(filter, Filter::Threshold { level: 0.5, mode: ThresholdMode::GreaterOrEqual }); assert_eq!(serde_json::to_string(&filter).unwrap(), saved); assert_eq!(filter.point(ChannelKind::Scalar, [0.5; 3]), Some([1.0; 3]), "a value at the level turns white as before"); @@ -84,7 +85,9 @@ mod tests { assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Greater, value)), [Some(0.0), Some(0.0), Some(1.0)]); assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Lower, value)), [Some(1.0), Some(0.0), Some(0.0)]); assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::LowerOrEqual, value)), [Some(1.0), Some(1.0), Some(0.0)]); + let saved = serde_json::to_string(&Filter::Threshold { level: 0.01, mode: ThresholdMode::LowerOrEqual }).unwrap(); + assert!(saved.contains(r#""mode":"lowerOrEqual""#), "{saved}"); } } diff --git a/crates/core/src/tile_transform.rs b/crates/core/src/tile_transform.rs index a834f7c8..2807b801 100644 --- a/crates/core/src/tile_transform.rs +++ b/crates/core/src/tile_transform.rs @@ -161,14 +161,22 @@ mod tests { let mut transform = TileTransform { scaling: [2.0, 2.0], ..TileTransform::LIBRARY }; assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.5, 0.5]), "the centre stays"); assert!(near(transform.source([0.75, 0.5]).unwrap_or_default(), [0.0, 0.5]), "twice the content: a quarter tile reads half a tile on"); + transform.repeat = RepeatMode::None; + assert_eq!(transform.source([0.9, 0.5]), None, "past the content reads nothing without repeat"); + transform = TileTransform { offset: [0.25, 0.0], ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.75, 0.5])); assert!(near(transform.source([0.9, 0.5]).unwrap_or_default(), [0.15, 0.5]), "the read wraps round the tile"); + transform = TileTransform { flip: FlipMode::Horizontally, ..TileTransform::LIBRARY }; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.8, 0.3])); + transform.flip = FlipMode::Vertically; + assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.2, 0.7])); } @@ -181,6 +189,7 @@ mod tests { // A small turn of the plain tile snaps back to no turn, never to nothing let small = TileTransform { rotation: 10.0, ..TileTransform::LIBRARY }; assert_eq!(small.affine().0, [[1.0, 0.0], [0.0, 1.0]]); + let tiny = TileTransform { scaling: [0.1, 0.1], rotation: 45.0, ..TileTransform::LIBRARY }; assert!(tiny.affine().0.iter().all(|column| column != &[0.0, 0.0])); @@ -213,6 +222,7 @@ mod tests { let transform = TileTransform { rotation: 359.99998, tile_safe, ..TileTransform::LIBRARY }; assert!(transform.is_identity(), "tile safe {tile_safe}: {:?}", transform.affine()); } + assert!(!TileTransform { rotation: 359.9, tile_safe: false, ..TileTransform::LIBRARY }.is_identity()); } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 1de76b29..bea50e17 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -569,10 +569,12 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { if let Some(input) = strp(params, "input") { return input_set(session, params, input); } + let target = fill_target(session, params, FILL_SET)?; if let FillTarget::Mask(effect) = target { return mask_fill_set(session, params, effect); } + let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 403459b5..4264b338 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -773,7 +773,7 @@ fn set(session: &mut Session, params: &Value) -> Result { _ => None, }; - // Naming the filter the effect already is edits its parameters like a plain effect.set (Directional Warp's former id also sets its mode); a warp saved before the warp modes has no mode to set, so another mode replaces it as a swap does + // Update matching filter variants in place and rebuild when the legacy filter lacks the requested mode let changes_saved_warp_mode = |filter: &str| matches!(session.doc.project.effect(effect), Some((_, Effect { kind: EffectKind::Filter(saved), .. })) if crate::filter_lib::changes_saved_warp_mode(filter, params, saved)); let swapped = match strp(params, "filter") { Some(EMPTY_FILTER) => Some(emptied_filter(session, effect)?), @@ -965,7 +965,7 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<( return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); } - // Built as effect.add.filter builds it, from the id given, so a former id such as `warpDirectional` sets the same mode it adds with + // Resolve legacy IDs the same way as effect.add.filter to preserve their modes let kind = crate::filter_lib::build_for(CMD, id, p)?; Ok((kind, def.label)) } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 4a27474f..678d7bb7 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -51,10 +51,12 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, out.extend(link.outputs.values().cloned()); } } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.images_read().map(str::to_string)); out.extend(crate::path_tool::path_images(&effect.kind)); } + for child in layer.children() { images_used(project, *child, out, depth + 1); } diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index a0e6d366..c44dce36 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -121,6 +121,10 @@ pub fn filter(id: &str, size: usize) -> Option>> { // The filters that shape a mask's edge read where values cross 0.5: they get black and white shapes, where the clouds would leave them black let shapes = matches!(kind, EffectKind::Filter(Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))); + render_filter_preview(kind, size, res, shapes) +} + +fn render_filter_preview(kind: EffectKind, size: usize, res: u32, shapes: bool) -> Option>> { let mesh = texturecraft_geom::primitives::plane(2.0, 2); let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res); let mut p = Project::new("preview", ""); @@ -210,9 +214,11 @@ mod tests { #[test] fn the_edge_shaping_filters_show_their_shapes_not_black() { - let size = 32; - // A neutral filter shows the checker as it is; an edge filter must change it - let checker = filter("levels", size).unwrap(); + const SIDE_PX: u32 = 32; + let size = SIDE_PX as usize; + + // Use the same checker input with an inactive filter + let checker = render_filter_preview(EffectKind::Filter(Filter::InvertOff), size, SIDE_PX, true).unwrap(); for id in ["bevelSmooth", "directionalDistance"] { let pixels = filter(id, size).unwrap(); assert!(pixels != checker, "{id}: the preview shows the unchanged checker"); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 241b5717..4fd5983e 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -757,19 +757,28 @@ impl Session { (Some(previous), Some(current)) => !Arc::ptr_eq(previous, current), (previous, current) => previous.is_some() != current.is_some(), }; - if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(|name| resource_changed(&name))) { + if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(resource_changed)) { self.path_cache = None; } // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); + if removed_or_replaced_resource { + for cache in &mut self.caches { + cache.invalidate_all(); + } + + return; + } + let added_resource_names: BTreeSet<&str> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); + let is_added = |name: &str| added_resource_names.contains(name); + let added_environment = self.doc.project.display.environment_resource().is_some_and(is_added); let uses_added_resource = |texture_set_index: usize| { - use texturecraft_core::{EffectKind, Fill}; + use texturecraft_core::{EffectKind, Fill, Filter}; - let is_added = |name: &str| added_resource_names.contains(name); let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); let project = &self.doc.project; @@ -777,12 +786,11 @@ impl Session { && project.texture_sets.get(texture_set_index).is_some_and(|set| { project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) - || layer - .mask - .iter() - .flat_map(|mask| &mask.effects) - .chain(&layer.content_effects) - .any(|effect| effect.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill))) + || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| { + effect.images_read().any(is_added) + || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill)) + || (added_environment && matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. }))) + }) }) }) }; diff --git a/crates/engine/src/tile_transform_params.rs b/crates/engine/src/tile_transform_params.rs index 86a0f807..bde8fdf4 100644 --- a/crates/engine/src/tile_transform_params.rs +++ b/crates/engine/src/tile_transform_params.rs @@ -10,6 +10,7 @@ use crate::layer_cmds::FULL_TURN_DEGREES; /// Set the Transform settings given in `p`; a value of the wrong kind is refused and changes nothing pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Result<()> { let mut edited = *transform; + if p.get("repeatMode").is_some() { let id = strp(p, "repeatMode").unwrap_or_default(); edited.repeat = @@ -22,6 +23,7 @@ pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Resu .find(|mode| mode.id() == id) .ok_or_else(|| bad(cmd, "`flipMode` must be none, horizontally, vertically or horizontallyAndVertically"))?; } + let (low, high) = TileTransform::SCALING; if let Some(scaling) = pair(p, "scaling", cmd)? { edited.scaling = scaling.map(|scale| scale.clamp(low, high)); @@ -29,6 +31,7 @@ pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Resu if let Some(offset) = pair(p, "offset", cmd)? { edited.offset = offset.map(|along| along.clamp(-TileTransform::MAX_OFFSET, TileTransform::MAX_OFFSET)); } + if p.get("tileSafeRotation").is_some() { edited.tile_safe = boolp(p, "tileSafeRotation").ok_or_else(|| bad(cmd, "`tileSafeRotation` must be true or false"))?; } @@ -36,6 +39,7 @@ pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Resu let degrees = f32p(p, "rotation").ok_or_else(|| bad(cmd, "`rotation` must be a number of degrees"))?; edited.rotation = degrees.rem_euclid(FULL_TURN_DEGREES); } + *transform = edited; Ok(()) } @@ -48,5 +52,6 @@ fn pair(p: &Value, key: &str, cmd: &str) -> Result> { Value::Array(items) if items.len() == 2 => items.first().and_then(number).zip(items.get(1).and_then(number)).map(|(x, y)| [x, y]), other => number(other).map(|both| [both, both]), }; + parsed.map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y] or one number"))) } diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index f1414b05..d9fbed69 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -34,38 +34,53 @@ fn content_effects_commands_inspect_and_round_trip() { let mut s = session(); let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer"); let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "mode": "regular", "hue": 1.0 / 3.0})).unwrap(), "effect"); + assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor)); assert!(s.doc.project.layer(LayerId(layer)).unwrap().mask.is_none(), "content effects don't create a mask"); assert_eq!(s.target, StackTarget::Effect(LayerId(hsl))); - // Mask-only effects refuse the content, unknown targets are errors. + // Mask-only effects refuse the content, unknown targets are errors assert!(execute(&mut s, "effect.add.generator", &json!({"target": "content"})).is_err()); assert!(execute(&mut s, "effect.add.filter", &json!({"target": "nope"})).is_err()); + execute(&mut s, "effect.set", &json!({"effect": hsl, "hue": 0.0, "lightness": -1.0})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), [0.0; 3])); + execute(&mut s, "effect.set", &json!({"effect": hsl, "visible": false})).unwrap(); - // A content fill effect, edited through layer.fill.set. + // A content fill effect, edited through layer.fill.set let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect"); + assert!(close(center(&mut s, Channel::Roughness), [0.7; 3])); assert!(close(center(&mut s, Channel::BaseColor), [1.0, 0.0, 0.0]), "channels without a source stay"); + execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "value": 0.9})).unwrap(); + assert!(close(center(&mut s, Channel::Roughness), [0.9; 3])); + execute(&mut s, "layer.fill.set", &json!({"effect": fill, "channel": "roughness", "enabled": false})).unwrap(); + assert!(close(center(&mut s, Channel::Roughness), [0.2; 3])); assert!(execute(&mut s, "layer.fill.set", &json!({"effect": hsl, "channel": "roughness", "value": 0.5})).is_err(), "not a fill effect"); - // Inspect shows the content stack; the project survives a save/load round trip. + // Inspect shows the content stack; the project survives a save/load round trip let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); let kinds: Vec<&str> = row["contentEffects"].as_array().unwrap().iter().map(|effect| effect["kind"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["HSL Perceptive", "Fill"], "{row}"); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); execute(&mut s, "layer.select", &json!({"layer": layer, "target": fill})).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": fill})).unwrap(); + assert_eq!(s.target, StackTarget::Content); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layer(LayerId(layer)).unwrap().content_effects.len(), 2); } diff --git a/crates/engine/tests/it/filter_card.rs b/crates/engine/tests/it/filter_card.rs index ee9c25af..51c88f67 100644 --- a/crates/engine/tests/it/filter_card.rs +++ b/crates/engine/tests/it/filter_card.rs @@ -24,14 +24,19 @@ fn an_empty_filter_renders_nothing_until_one_is_picked() { assert_eq!(filter_of(&s, effect), Filter::Empty); assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Filter (empty)"); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "an empty filter leaves the color"); set(&mut s, effect, json!({"filter": "invert"})); + assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Invert"); + assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the picked filter works"); set(&mut s, effect, json!({"filter": "none"})); + assert_eq!(filter_of(&s, effect), Filter::Empty); + assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "emptied again"); } @@ -50,6 +55,7 @@ fn a_content_filter_leaves_the_channels_switched_off() { let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); let filter_row = row["contentEffects"].as_array().unwrap().iter().find(|filter_row| filter_row["id"] == effect.0).unwrap(); + assert_eq!(filter_row["offChannels"], json!(["roughness"])); execute(&mut s, "edit.undo", &Value::Null).unwrap(); @@ -57,6 +63,7 @@ fn a_content_filter_leaves_the_channels_switched_off() { set(&mut s, effect, json!({"channels": {"roughness": false}})); set(&mut s, effect, json!({"channels": {"roughness": true}})); + assert!(s.doc.project.effect(effect).unwrap().1.off_channels.is_empty()); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"nope": false}})).is_err()); @@ -90,12 +97,15 @@ fn the_divider_divides_the_intensity() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "divider": 7})).is_err()); set(&mut s, effect, json!({"divider": 100})); + assert!(matches!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur { divider: 100, .. }))); let saved = serde_json::to_value(Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }).unwrap(); + assert_eq!(saved, json!({"Warp": {"intensity": 1.0, "scale": 2.0, "seed": 3}}), "saved as before dividers"); let loaded: Filter = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded, Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }); } @@ -110,20 +120,24 @@ fn restore_defaults_puts_the_filters_parameters_back() { assert_eq!(s.history_labels().len(), steps, "no step at defaults"); set(&mut s, effect, json!({"intensity": 0.5, "seed": 9, "divider": 100, "channels": {"height": false}})); + assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": true})); assert_eq!(filter_of(&s, effect), defaults); let restored = s.doc.project.effect(effect).unwrap().1.clone(); + assert_eq!(restored.name, "Wobble"); assert!(restored.off_channels.contains(&Channel::Height)); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(matches!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp { divider: 100, seed: 9, .. })), "one undo step"); let empty = filtered_layer(&mut s, json!({"filter": "none"})).1; assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": empty.0})).unwrap(), json!({"changed": false})); let fill = execute(&mut s, "effect.add.fill", &json!({"target": "content"})).unwrap()["effect"].as_u64().unwrap(); + assert!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": fill})).is_err()); } @@ -136,5 +150,6 @@ fn filter_list_describes_and_tags_every_filter() { assert!(def["tags"].as_array().is_some_and(|tags| !tags.is_empty()), "{def}"); } let blur = listed.as_array().unwrap().iter().find(|def| def["id"] == "blur").unwrap(); + assert_eq!(blur["tags"], json!(["blur", "soften"])); } diff --git a/crates/engine/tests/it/filter_colour.rs b/crates/engine/tests/it/filter_colour.rs index f0bc3561..6106ba99 100644 --- a/crates/engine/tests/it/filter_colour.rs +++ b/crates/engine/tests/it/filter_colour.rs @@ -16,18 +16,22 @@ fn color_correct_changes_nothing_until_its_tones_move() { let mut s = session(); let color = [0.6, 0.3, 0.2]; let effect = filtered(&mut s, color, json!({"filter": "colorCorrect"})); + let neutral = filter_of(&s, effect); assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Color Correct"); assert!(distance(center(&mut s, Channel::BaseColor), color) < 4e-3, "the defaults change nothing"); set(&mut s, effect, json!({"shadows": [0.0, 0.0, 0.0], "midtones": [0.0, 0.0, 0.0], "highlights": [0.0, 0.0, 0.0]})); + let gray = center(&mut s, Channel::BaseColor); assert!((gray[0] - gray[1]).abs() < 4e-3 && (gray[1] - gray[2]).abs() < 4e-3, "saturation 0 everywhere is gray: {gray:?}"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(filter_of(&s, effect), neutral, "one undo step takes back all three tones"); set(&mut s, effect, json!({"midtones": [0.0, 0.3, 0.5], "shadows": [0.0, 0.3, 0.5], "highlights": [0.0, 0.3, 0.5]})); + let lighter = center(&mut s, Channel::BaseColor); assert!((0..3).all(|i| lighter[i] > color[i] + 0.1), "luminosity lifts every tone: {lighter:?}"); @@ -50,13 +54,16 @@ fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { let mut s = session(); let yellow = [0.8, 0.7, 0.05]; let effect = filtered(&mut s, yellow, json!({"filter": "hsl", "hue": 0.5})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: true, .. }), "new filters are perceptive"); let perceptive = center(&mut s, Channel::BaseColor); set(&mut s, effect, json!({"mode": "regular"})); + assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: false, .. })); let regular = center(&mut s, Channel::BaseColor); + // Rec. 709 luminance weights let relative_luminance = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; let drift = |color: [f32; 3]| (relative_luminance(color) - relative_luminance(yellow)).abs(); @@ -66,6 +73,7 @@ fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { // Saved before the mode: Regular, and saved again without the field let old: Filter = serde_json::from_value(json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})).unwrap(); + assert_eq!(old, Filter::Hsl { hue: 0.5, saturation: 0.0, lightness: 0.0, perceptive: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})); } @@ -75,6 +83,7 @@ fn hsl_perceptive_turns_the_hue_at_the_same_lightness() { fn contrast_luminosity_starts_neutral() { let mut s = session(); let effect = filtered(&mut s, [0.2; 3], json!({"filter": "contrastLuminosity"})); + assert_eq!(filter_of(&s, effect), Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.0 }); assert!(distance(center(&mut s, Channel::BaseColor), [0.2; 3]) < 4e-3); } @@ -84,17 +93,21 @@ fn contrast_luminosity_starts_neutral() { fn blur_and_bevel_take_the_edge_wrap() { let mut s = session(); let blur = filtered(&mut s, [0.2; 3], json!({"filter": "blur"})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: false, .. })); set(&mut s, blur, json!({"wrap": true})); + assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: true, .. })); assert!(execute(&mut s, "effect.set", &json!({"effect": blur.0, "wrap": "yes"})).is_err()); let bevel = filtered(&mut s, [0.2; 3], json!({"filter": "bevel", "wrap": true})); + assert!(matches!(filter_of(&s, bevel), Filter::DistanceBevel(Bevel { wrap: true, .. }))); let old: Filter = serde_json::from_value(json!({"Blur": {"radius": 4.0}})).unwrap(); + assert_eq!(old, Filter::Blur { radius: 4.0, wrap: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Blur": {"radius": 4.0}}), "off is not saved"); } diff --git a/crates/engine/tests/it/filter_gradient.rs b/crates/engine/tests/it/filter_gradient.rs index 738c5390..d73e2913 100644 --- a/crates/engine/tests/it/filter_gradient.rs +++ b/crates/engine/tests/it/filter_gradient.rs @@ -16,6 +16,7 @@ fn near(a: f32, b: f32) -> bool { fn a_gradient_saved_before_reads_and_saves_as_before() { let saved = json!({"GradientMap": {"colors": [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]}}); let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]])); assert_eq!(serde_json::to_value(&filter).unwrap(), saved, "nothing new is saved"); @@ -40,12 +41,15 @@ fn gradient_places_quantity_and_input_transformation() { assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY / 2.0), "halfway from black to mid gray"); set(&mut s, effect, json!({"positions": [0.0, 0.25, 1.0]})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY), "mid gray moved to 0.25"); set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.5 / 0.75)), "inverted, it reads 0.75"); set(&mut s, effect, json!({"invert": false, "balance": 0.75})); + assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.25 / 0.75)), "balance 0.75 lifts it to 0.5"); set(&mut s, effect, json!({"balance": 0.5, "positions": [0.0, 0.5, 1.0], "linear": false})); @@ -53,6 +57,7 @@ fn gradient_places_quantity_and_input_transformation() { assert!(near(srgb, 0.0508), "blended in sRGB, halfway from black to mid gray is sRGB 0.25: {srgb}"); set(&mut s, effect, json!({"quantity": 4})); + assert_eq!(filter_of(&s, effect).ramp_colors().len(), 4); refused( @@ -93,6 +98,7 @@ fn display_gradient_shows_the_ramp_across_the_texture() { let effect = filtered(&mut s, [0.9; 3], json!({"filter": "gradientMap", "debug": true})); let (value, uv) = (center(&mut s, Channel::BaseColor), center_uv(&mut s)); let ramp = filter_of(&s, effect).ramp_at(uv.x).unwrap(); + assert!((0..3).all(|k| (value[k] - ramp[k]).abs() < 0.03), "{value:?} vs {ramp:?} at u {}", uv.x); } @@ -136,9 +142,11 @@ fn gradient_curve_remaps_through_its_preset() { assert!(near(center(&mut s, Channel::BaseColor)[0], round), "Round at 0.25"); set(&mut s, effect, json!({"preset": "easeIn"})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.0625), "Ease In at 0.25"); set(&mut s, effect, json!({"invert": true})); + assert!(near(center(&mut s, Channel::BaseColor)[0], 0.5625), "Ease In at 0.75"); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "preset": "spiral"})).is_err()); diff --git a/crates/engine/tests/it/filter_inputs.rs b/crates/engine/tests/it/filter_inputs.rs index 423eab27..23611860 100644 --- a/crates/engine/tests/it/filter_inputs.rs +++ b/crates/engine/tests/it/filter_inputs.rs @@ -41,21 +41,26 @@ fn a_distance_map_scales_the_bevel_smooth_distance() { assert_eq!(inputs(&s, effect), vec![("distanceMap".to_string(), Source::Uniform([0.5; 3]))]); let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"inputs\":{\"distanceMap\""), "inspect shows the input"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(inputs(&s, effect).is_empty(), "one undo step"); assert_eq!(roughness(&mut s, at(4)), full); input(&mut s, effect, json!({"input": "distanceMap", "anchor": anchor.0, "anchorChannel": "roughness"})).unwrap(); + assert!((roughness(&mut s, at(4)) - half).abs() < 1e-3, "the anchor's 0.5 reads as the uniform 0.5"); input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty() && roughness(&mut s, at(4)) == full, "cleared: white, as before"); let steps = s.history_labels().len(); input(&mut s, effect, json!({"input": "distanceMap", "value": 1.0})).unwrap(); input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap(); + assert!(inputs(&s, effect).is_empty(), "the default gray is not stored"); assert_eq!(s.history_labels().len(), steps, "setting what the input already reads adds no undo step"); @@ -63,6 +68,7 @@ fn a_distance_map_scales_the_bevel_smooth_distance() { { assert!(input(&mut s, effect, bad.clone()).is_err(), "{bad}"); } + assert!(input(&mut s, anchor, json!({"input": "distanceMap", "value": 0.5})).is_err(), "not a filter"); } @@ -74,9 +80,11 @@ fn a_black_distance_map_leaves_no_trail() { let effect = add_filter(&mut s, json!({"filter": "directionalDistance"})); set(&mut s, effect, json!({"angle": if outward > 0 { 0.0 } else { 180.0 }, "distance": 0.05})); + assert!(roughness(&mut s, at(1)) > 0.0, "a trail"); input(&mut s, effect, json!({"input": "distanceMap", "value": 0.0})).unwrap(); + assert_eq!((roughness(&mut s, at(1)), roughness(&mut s, at(-2))), (0.0, 1.0), "no trail, the shapes stay"); } @@ -92,18 +100,23 @@ fn a_custom_noise_moves_the_warp() { let effect = add_filter(&mut s, json!({"filter": "warp"})); set(&mut s, effect, json!({"intensity": 0.05, "divider": 1, "warpMode": "directional", "sourceMode": "customNoise"})); + assert!(moved(&mut s) < 2e-3, "its default mid gray moves nothing"); input(&mut s, effect, json!({"input": "customNoise", "procedural": "gradient"})).unwrap(); + assert!(moved(&mut s) > 0.01, "a source moves texels: {}", moved(&mut s)); set(&mut s, effect, json!({"sourceMode": "defaultNoise"})); + assert_eq!(inputs(&s, effect).len(), 1, "kept while another source mode is on"); let (_, found) = s.doc.project.effect(effect).unwrap(); let saved = serde_json::to_value(Effect { inputs: Default::default(), ..found.clone() }).unwrap(); + assert!(saved.get("inputs").is_none(), "no inputs, no key: saves as before"); let loaded: Effect = serde_json::from_value(saved).unwrap(); + assert!(loaded.inputs.is_empty(), "an effect saved before loads with none"); } diff --git a/crates/engine/tests/it/filter_light.rs b/crates/engine/tests/it/filter_light.rs index 5fccb750..770d57e3 100644 --- a/crates/engine/tests/it/filter_light.rs +++ b/crates/engine/tests/it/filter_light.rs @@ -25,6 +25,7 @@ fn masked(s: &mut Session, id: &str) -> LayerId { fn a_glow_saved_before_stays_additive_and_a_new_glow_is_the_halo() { let saved = json!({"Glow": {"radius": 16.0, "amount": 1.0}}); let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(filter, Filter::Glow { radius: 16.0, amount: 1.0 }); assert_eq!(serde_json::to_value(&filter).unwrap(), saved); @@ -61,11 +62,13 @@ fn drop_shadow_defaults_and_settings() { assert_eq!(filter_of(&s, effect), LIBRARY_DROP_SHADOW, "the workflow's defaults"); set(&mut s, effect, json!({"angle": 450.0, "distance": -0.9, "size": 2.0, "spread": 0.3, "opacity": 0.25, "color": "#ffffff"})); + assert_eq!(filter_of(&s, effect), Filter::DropShadow { angle: 90.0, distance: -0.5, size: 1.0, spread: 0.3, opacity: 0.25, color: [1.0; 3] }); refused(&mut s, effect, &[json!({"color": [1.0]})]); let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "dropShadow" && f["mask"] == true)); } @@ -80,6 +83,7 @@ fn on_content(s: &mut Session, id: &str) -> LayerId { fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { let saved = json!({"BakedLighting": {"azimuth": 45.0, "elevation": 45.0, "light": 0.75, "ambient": 0.5, "occlusion": 1.0}}); let filter: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert!(filter.stylized_lighting().is_none(), "lights as before"); assert_eq!(serde_json::to_value(&filter).unwrap(), saved); assert_eq!(filter.label(), "Baked Lighting Stylized"); @@ -91,6 +95,7 @@ fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { assert_eq!(made, library_baked_lighting(), "the workflow's sun, sky and lights"); let (stylized, _) = made.stylized_lighting().unwrap(); + assert_eq!( (stylized.output, stylized.mesh_only, stylized.dielectric_reflectance, stylized.cavity_smoothness), (LightingOutput::DiffuseSpecular, false, 0.04, 0.25) @@ -98,6 +103,7 @@ fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() { assert_eq!((stylized.lights[0].azimuth, stylized.lights[1].azimuth, stylized.lights[0].intensity), (90.0, 180.0, 0.0)); let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLighting" && f["mask"] == false && f["label"] == "Baked Lighting Stylized")); } @@ -120,6 +126,7 @@ fn stylized_lighting_settings_set_clamp_and_refuse() { ); let filter = filter_of(&s, effect); let (stylized, light) = filter.stylized_lighting().unwrap(); + assert_eq!((light.sun.intensity, light.sky_intensity, stylized.sun_color), (0.8, 0.4, [1.0; 3]), "the rest as it lit"); assert_eq!(stylized.sky_color, [0.1, 0.2, 0.3]); @@ -132,6 +139,7 @@ fn stylized_lighting_settings_set_clamp_and_refuse() { effect, &[json!({"output": "both"}), json!({"input": 1}), json!({"normalDetails": "height"}), json!({"light2": 3}), json!({"groundColor": "dirt"})], ); + assert_eq!(filter_of(&s, effect), filter, "refusals change nothing"); assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true)); @@ -148,6 +156,7 @@ fn environment_lighting_defaults_and_settings() { assert_eq!((made.label(), s.doc.project.effect(effect).unwrap().1.name.as_str()), ("Baked Lighting Environment", "Baked Lighting Environment")); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness) && off.contains(&Channel::Height), "only the Color pill is lit: {off:?}"); let stylized = on_content(&mut s, "bakedLighting"); @@ -161,6 +170,7 @@ fn environment_lighting_defaults_and_settings() { effect, json!({"horizontalRotation": 370.0, "verticalRotation": -90.0, "exposure": 9.0, "heightIntensity": -1.0, "ambientOcclusion": 0.5, "specularOcclusion": 2.0}), ); + assert_eq!( filter_of(&s, effect), Filter::EnvironmentLighting { @@ -177,6 +187,7 @@ fn environment_lighting_defaults_and_settings() { assert_eq!(filter_of(&s, effect), made); let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); + assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLightingEnvironment" && f["mask"] == false)); } @@ -200,5 +211,36 @@ fn environment_lighting_follows_the_viewport_environment() { assert!(night[0] < studio[0] * 0.5, "the night lights it less: {night:?} vs {studio:?}"); set(&mut s, effect, json!({"exposure": 3.0})); + assert!(center(&mut s)[0] > night[0], "exposure brightens it"); } + +#[test] +fn reimporting_the_selected_environment_relights_the_composite() { + let mut session = session(); + let image_bytes = |rgb: [u8; 3]| { + let image = image::RgbImage::from_pixel(8, 4, image::Rgb(rgb)); + let mut bytes = std::io::Cursor::new(Vec::new()); + image.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); + bytes.into_inner() + }; + let sample = |session: &mut Session| { + session.update(); + session.caches[0].composite.value(Channel::BaseColor, SIZE / 2, SIZE / 2) + }; + execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap(); + add_filter(&mut session, json!({"filter": "bakedLightingEnvironment"})); + let name = session.import_resource_bytes("lighting.png", image_bytes([255, 0, 0])).unwrap(); + execute(&mut session, "display.set", &json!({"environment": format!("resource:{name}")})).unwrap(); + let red = sample(&mut session); + assert!(red[0] > red[1], "the selected resource lights the base color"); + + execute(&mut session, "resource.remove", &json!({"name": name})).unwrap(); + let fallback = sample(&mut session); + let replacement = session.import_resource_bytes("lighting.png", image_bytes([0, 255, 0])).unwrap(); + let green = sample(&mut session); + + assert_eq!(replacement, name); + assert_ne!(fallback, red); + assert!(green[1] > green[0] && green != fallback, "reimporting the referenced image relights the material: {green:?}"); +} diff --git a/crates/engine/tests/it/filter_shape.rs b/crates/engine/tests/it/filter_shape.rs index 73dc6521..5ffd623c 100644 --- a/crates/engine/tests/it/filter_shape.rs +++ b/crates/engine/tests/it/filter_shape.rs @@ -21,10 +21,12 @@ fn threshold_modes_compare_their_way() { assert_eq!(roughness(&mut s, texel), 1.0); set(&mut s, effect, json!({"level": 0.25})); + assert_eq!(roughness(&mut s, texel), 0.0, "a value at the level is not greater"); for (mode, white) in [("greaterOrEqual", 1.0), ("lower", 0.0), ("lowerOrEqual", 1.0)] { set(&mut s, effect, json!({"mode": mode})); + assert_eq!(roughness(&mut s, texel), white, "{mode}"); } @@ -32,6 +34,7 @@ fn threshold_modes_compare_their_way() { assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.25, mode: ThresholdMode::LowerOrEqual }, "a refused mode changes nothing"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }); } @@ -53,15 +56,18 @@ fn mirror_copies_one_side_over_the_other() { assert!((roughness(&mut s, right) - left_before).abs() < 2e-3, "the right side reads the left"); set(&mut s, effect, json!({"invertAxisX": true})); + assert!((roughness(&mut s, left) - right_before).abs() < 2e-3, "inverted, the left side reads the right"); set(&mut s, effect, json!({"mode": "corner", "cornerType": "topRight"})); + assert!((roughness(&mut s, (20, 20)) - roughness(&mut s, (SIZE - 1 - 20, 20))).abs() < 2e-3, "a corner mirrors across too"); let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() }; assert_eq!((mirror.mode, mirror.corner), (MirrorMode::Corner, MirrorCorner::TopRight)); set(&mut s, effect, json!({"mode": "axisX", "displayDebug": true})); + assert_eq!(roughness(&mut s, (SIZE / 2, row)), 1.0, "Display Debug draws the axis white"); refused(&mut s, effect, &[json!({"mode": "diagonal"}), json!({"cornerType": "middle"}), json!({"invertAxisY": "yes"})]); @@ -82,14 +88,17 @@ fn mask_outline_draws_a_band_along_the_threshold_edge() { assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mask Outline"); set(&mut s, effect, json!({"threshold": 0.5, "width": 0.03})); + assert_eq!(roughness(&mut s, at(2)), 1.0, "outside, next to the edge"); assert_eq!(roughness(&mut s, at(8)), 0.0, "past the band"); assert_eq!(roughness(&mut s, at(-2)), 0.0, "inside the shapes"); set(&mut s, effect, json!({"maskPosition": "inside"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 0.0), "inside"); set(&mut s, effect, json!({"maskPosition": "both"})); + assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 1.0), "both sides"); set(&mut s, effect, json!({"startFromBlack": false})); @@ -107,6 +116,7 @@ fn mask_outline_draws_a_band_along_the_threshold_edge() { assert_eq!((outline.position, outline.width, outline.curve), (OutlinePosition::Outside, 1.0, -1.0), "values clamp"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY)); } @@ -164,9 +174,11 @@ fn bevel_slopes_inwards_or_outwards() { assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(expected), "values clamp"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY)); let old: Filter = serde_json::from_value(json!({"Bevel": {"width": 16.0}})).unwrap(); + assert_eq!(old, Filter::Bevel { width: 16.0, wrap: false }, "a bevel saved before keeps its width"); } @@ -194,6 +206,7 @@ fn bevel_smooth_ramps_from_the_edge() { assert!(edge_in > 0.5 && edge_out < 0.5 && edge_in - edge_out < 0.2, "across: mid gray at the edge: {edge_in} {edge_out}"); set(&mut s, effect, json!({"curveOffset": 0.5})); + assert!(roughness(&mut s, at(0)) > edge_in, "the offset raises the ramp"); refused(&mut s, effect, &[json!({"direction": "up"}), json!({"wrap": "yes"})]); @@ -224,9 +237,11 @@ fn directional_distance_trails_one_way() { assert!(near > further && further > 0.0, "fades away from them: {near} {further}"); set(&mut s, effect, json!({"contrast": 0.5})); + assert_eq!(roughness(&mut s, at(1)), 1.0, "contrast hardens the near trail"); set(&mut s, effect, json!({"angle": away + 180.0, "contrast": 0.0})); + assert!(roughness(&mut s, at(1)) < near, "against the angle the edge gets less trail"); set(&mut s, effect, json!({"distance": 1.0, "angle": -90.0, "contrast": 3.0, "distanceMapMultiplier": -1.0})); @@ -254,6 +269,7 @@ fn warp_modes_move_texels_their_way() { assert!(moved(&warped) > 0.01 && warped.iter().all(|v| v.is_finite()), "the noise moves texels: {}", moved(&warped)); set(&mut s, effect, json!({"intensity": 0.0})); + assert!(moved(&after(&mut s)) < 2e-3, "no intensity, no move"); // Along the gradient where it rises: a texel above mid gray reads further up it, so it gets lighter @@ -269,6 +285,7 @@ fn warp_modes_move_texels_their_way() { assert!(directional[texel] > before[texel] + 0.01, "{} -> {}", before[texel], directional[texel]); set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing moves"); set(&mut s, effect, json!({"warpMode": "multiDirectional", "sourceMode": "defaultNoise", "directions": 2, "blendingMode": "max"})); @@ -281,6 +298,7 @@ fn warp_modes_move_texels_their_way() { assert!(average.iter().zip(max.iter().zip(&min)).all(|(average, (max, min))| *average <= max + 2e-3 && *average >= min - 2e-3), "the average between"); set(&mut s, effect, json!({"blendingMode": "chain", "directions": 4})); + assert!(after(&mut s).iter().all(|v| v.is_finite())); refused(&mut s, effect, &[json!({"warpMode": "spiral"}), json!({"directions": 3}), json!({"blendingMode": "sum"}), json!({"sourceMode": "image"})]); @@ -297,11 +315,13 @@ fn warp_modes_move_texels_their_way() { // Saved before the modes: loads as it was, and Restore defaults gives the warp of its mode let saved = json!({"DirectionalWarp": {"intensity": 8.0, "angle": 30.0, "scale": 4.0, "seed": 3}}); let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::DirectionalWarp { intensity: 8.0, angle: 30.0, scale: 4.0, seed: 3, divider: 1 }); assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); s.doc.project.effect_mut(former).unwrap().kind = EffectKind::Filter(old); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": former.0})).unwrap(); + assert_eq!(filter_of(&s, former), Filter::SourceWarp(directional)); } @@ -336,6 +356,7 @@ fn slope_blur_reads_downhill_of_its_source() { set(&mut s, effect, json!({"blendingMode": "blur", "sourceMode": "previousInput"})); let downhill = after(&mut s); let rising = (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k] + 1e-4)).unwrap(); + assert!(downhill[rising] < before[rising] - 0.005, "{} -> {}", before[rising], downhill[rising]); set(&mut s, effect, json!({"quality": 0.0})); @@ -343,6 +364,7 @@ fn slope_blur_reads_downhill_of_its_source() { assert!(coarse.iter().all(|v| v.is_finite()) && coarse != downhill, "fewer reads, another smear"); set(&mut s, effect, json!({"sourceMode": "customNoise"})); + assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing smears"); refused(&mut s, effect, &[json!({"blendingMode": "average"}), json!({"sourceMode": "image"}), json!({"divider": 7})]); @@ -355,10 +377,12 @@ fn slope_blur_reads_downhill_of_its_source() { // Saved before its source settings: loads and saves as it was, and Restore defaults gives today's Blur Slope let saved = json!({"SlopeBlur": {"radius": 16.0, "scale": 4.0, "seed": 1}}); let old: Filter = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(old, Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1, divider: 1 }); assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before"); s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY)); } diff --git a/crates/engine/tests/it/filter_simple.rs b/crates/engine/tests/it/filter_simple.rs index 8b6bdaaa..225e6911 100644 --- a/crates/engine/tests/it/filter_simple.rs +++ b/crates/engine/tests/it/filter_simple.rs @@ -41,6 +41,7 @@ fn new_simple_filters_start_where_the_reference_does() { add_filter(&mut s, json!({"filter": "heightAdjust"})); add_filter(&mut s, json!({"filter": "histogramScan"})); add_filter(&mut s, json!({"filter": "histogramShift"})); + assert!(close(roughness(&mut s, TEXEL), 0.25), "Clamp, Height Adjust, Histogram Scan and Shift at their defaults change nothing"); } @@ -52,12 +53,15 @@ fn smoothstep_eases_between_minimum_and_maximum() { assert!(close(roughness(&mut s, TEXEL), 0.15625), "0.25 eased: 3t² − 2t³"); set(&mut s, effect, json!({"min": 0.25, "max": 0.75})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "at the minimum"); set(&mut s, effect, json!({"min": 0.0, "max": 0.2})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "past the maximum"); set(&mut s, effect, json!({"min": 0.25, "max": 0.25})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "equal bounds are a step, the bound itself white"); } @@ -69,6 +73,7 @@ fn invert_switches_off_and_on() { assert!(close(roughness(&mut s, TEXEL), 0.75)); set(&mut s, effect, json!({"invert": false})); + assert_eq!(filter_of(&s, effect), Filter::InvertOff); assert!(close(roughness(&mut s, TEXEL), 0.25), "off changes nothing"); assert_eq!(filter_of(&s, effect).label(), "Invert", "still named Invert"); @@ -76,14 +81,17 @@ fn invert_switches_off_and_on() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "invert": "yes"})).is_err()); execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert, "one undo step"); set(&mut s, effect, json!({"invert": false})); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Invert); // An old project's Invert still reads as before let old: Filter = serde_json::from_value(json!("Invert")).unwrap(); + assert_eq!(old, Filter::Invert); } @@ -94,15 +102,19 @@ fn height_adjust_flips_scales_and_raises() { let effect = add_filter(&mut s, json!({"filter": "heightAdjust"})); set(&mut s, effect, json!({"multiply": 2.0})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "(0.25 − 0.5) × 2 + 0.5"); set(&mut s, effect, json!({"invert": true, "offset": 0.1})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "flipped to 0.75, (0.75 − 0.5) × 2 + 0.5 + 0.1 clamped"); set(&mut s, effect, json!({"multiply": 1.0, "offset": -0.2})); + assert!(close(roughness(&mut s, TEXEL), 0.55)); set(&mut s, effect, json!({"multiply": 50.0})); + assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: true, offset: -0.2, multiply: 10.0 }, "Multiply caps at 10"); } @@ -127,12 +139,15 @@ fn histogram_scan_inverts_its_position() { let effect = add_filter(&mut s, json!({"filter": "histogramScan"})); set(&mut s, effect, json!({"position": 0.2, "contrast": 1.0})); + assert!(close(roughness(&mut s, TEXEL), 1.0), "0.25 is above 0.2"); set(&mut s, effect, json!({"invertPosition": true})); + assert!(close(roughness(&mut s, TEXEL), 0.0), "0.25 is below 1 − 0.2"); let old: Filter = serde_json::from_value(json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}})).unwrap(); + assert_eq!(old, Filter::HistogramScan { position: 0.5, contrast: 0.5, invert_position: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}}), "saved as before"); } @@ -144,6 +159,7 @@ fn histogram_shift_takes_a_position() { let effect = add_filter(&mut s, json!({"filter": "histogramShift"})); set(&mut s, effect, json!({"position": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::HistogramShift { offset: -0.5 }); assert!(close(roughness(&mut s, TEXEL), 0.75), "0.25 − 0.5 wraps to 0.75"); @@ -159,12 +175,14 @@ fn posterize_takes_apply_to_alpha() { let effect = add_filter(&mut s, json!({"filter": "posterize"})); set(&mut s, effect, json!({"levels": 2, "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::Posterize { levels: 2.0, alpha: true }); assert!(close(roughness(&mut s, TEXEL), 0.0)); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": 1})).is_err()); let old: Filter = serde_json::from_value(json!({"Posterize": {"levels": 4.0}})).unwrap(); + assert_eq!(old, Filter::Posterize { levels: 4.0, alpha: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Posterize": {"levels": 4.0}}), "saved as before"); } @@ -184,9 +202,11 @@ fn pixelate_takes_pixels_amount_and_apply_to_alpha() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "no"})).is_err()); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Pixelate"), "named after the reference workflow"); let old: Filter = serde_json::from_value(json!({"Mosaic": {"size": 32.0}})).unwrap(); + assert_eq!(old, Filter::Mosaic { size: 32.0, alpha: true }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Mosaic": {"size": 32.0}}), "saved as before"); } @@ -199,12 +219,14 @@ fn fxaa_takes_affect_alpha_channel() { assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }); set(&mut s, effect, json!({"affectAlphaChannel": true})); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: true }); assert!(close(roughness(&mut s, TEXEL), 0.3), "nothing to smooth on a flat fill"); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "affectAlphaChannel": 2})).is_err()); execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }, "one undo step"); } @@ -216,17 +238,21 @@ fn blurs_take_intensity() { assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 4.8, wrap: false }, "a new Blur starts at Blur Intensity 0.30"); set(&mut s, blur, json!({"intensity": 2.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 32.0, wrap: false }); set(&mut s, blur, json!({"intensity": 1000.0})); + assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 256.0, wrap: false }, "capped as radius is"); let directional = add_filter(&mut s, json!({"filter": "blurDirectional"})); set(&mut s, directional, json!({"intensity": 0.5, "angle": 90})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 8.0, angle: 90.0 }); set(&mut s, directional, json!({"radius": 4.0})); + assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 4.0, angle: 90.0 }, "radius in texels at 2K still sets it"); } @@ -239,15 +265,18 @@ fn highpass_takes_radius_color_space_and_apply_to_alpha() { assert!(close(roughness(&mut s, TEXEL), 0.5), "a flat fill has no detail: mid gray"); set(&mut s, effect, json!({"intensity": 0.5, "colorSpace": "srgbFromAcescg", "applyToAlpha": true})); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 8.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "colorSpace": "rec2020"})).is_err()); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "yes"})).is_err()); execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false }, "one undo step"); let old: Filter = serde_json::from_value(json!({"HighPass": {"radius": 8.0}})).unwrap(); + assert_eq!(old, Filter::HighPass { radius: 8.0, space: HighpassSpace::Working, alpha: false }); assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HighPass": {"radius": 8.0}}), "saved as before"); } @@ -271,16 +300,20 @@ fn grayscale_conversion_takes_its_settings_and_keeps_saved_grayscales() { assert!(saved.iter().all(|v| close(*v, saved[0])) && close(saved[0], lum([0.8, 0.2, 0.1])), "{saved:?}"); set(&mut s, effect, json!({"balance": 0.5})); + assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::of_luminance()), "the luminance weights"); assert!(close(base_color(&mut s)[0], saved[0]), "looks the same after its first edit"); set(&mut s, effect, json!({"red": 1.0, "green": 0.0, "blue": 0.0, "invert": true})); + assert!(close(base_color(&mut s)[0], 1.0 - 0.8), "Red only, inverted"); set(&mut s, effect, json!({"mode": "min", "invert": false})); + assert!(close(base_color(&mut s)[0], 0.1), "the darkest component"); set(&mut s, effect, json!({"channelInput": "customInput", "mode": "max"})); + assert!(close(base_color(&mut s)[0], 0.5), "the Custom Input reads mid gray until set"); let Filter::GrayscaleConversion(conversion) = filter_of(&s, effect) else { panic!("converted") }; @@ -290,6 +323,7 @@ fn grayscale_conversion_takes_its_settings_and_keeps_saved_grayscales() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "luma"})).is_err(), "Luma is the gradients' mode"); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Grayscale Conversion")); assert_eq!(serde_json::to_value(Filter::Grayscale).unwrap(), json!("Grayscale"), "saved as before"); } diff --git a/crates/engine/tests/it/filter_stylize.rs b/crates/engine/tests/it/filter_stylize.rs index 13b28c90..512a405c 100644 --- a/crates/engine/tests/it/filter_stylize.rs +++ b/crates/engine/tests/it/filter_stylize.rs @@ -59,6 +59,7 @@ fn anisotropic_kuwahara_takes_its_settings_and_smooths() { assert_eq!(undone, AnisotropicKuwahara { radius: AnisotropicKuwahara::MAX_RADIUS, ..AnisotropicKuwahara::LIBRARY }, "one undo step"); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Anisotropic Kuwahara")); } @@ -75,6 +76,7 @@ fn pbr_validate_marks_implausible_base_colors() { assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate::LIBRARY)); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Metallic) && off.contains(&Channel::Roughness), "{off:?}"); assert_eq!(base_color(&mut s, texel), PbrValidate::INVALID, "too dark"); assert_eq!(s.caches[0].composite.value(Channel::Metallic, texel.0, texel.1)[0], 0.0, "the metal is left as it is"); @@ -84,6 +86,7 @@ fn pbr_validate_marks_implausible_base_colors() { assert!((shown[0] - dark).abs() < 1e-3, "Metal leaves non-metal colors unchecked: {shown:?}"); set(&mut s, effect, json!({"validationMode": "albedo", "albedoDarkRangeThreshold": 50, "metalReflectanceRange": 70})); + assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate { mode: ValidationMode::Albedo, albedo_dark: 50, metal_low: 70 })); assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "albedoDarkRangeThreshold": 40})).is_err()); @@ -109,6 +112,7 @@ fn height_to_normal_turns_the_height_into_the_normal() { let bumps = json!({"layer": fill, "channel": "height", "procedural": "Clouds", "scale": 16, "low": [-0.05, -0.05, -0.05], "high": [0.05, 0.05, 0.05]}); execute(&mut s, "layer.fill.set", &bumps).unwrap(); let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect(); + assert!(tilt(&mut s, &texels) < 1e-3, "a fill's own normal is flat"); let color = base_color(&mut s, texels[0]); @@ -117,6 +121,7 @@ fn height_to_normal_turns_the_height_into_the_normal() { assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(HeightToNormal::LIBRARY)); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::Normal) && off.contains(&Channel::BaseColor) && off.contains(&Channel::Height), "{off:?}"); let made = tilt(&mut s, &texels); @@ -124,15 +129,19 @@ fn height_to_normal_turns_the_height_into_the_normal() { assert_eq!(base_color(&mut s, texels[0]), color, "the base color is left as it is"); set(&mut s, effect, json!({"heightDepth": 64.0})); + assert!(tilt(&mut s, &texels) > made * 1.5, "deeper heights tilt more"); set(&mut s, effect, json!({"useWorldUnits": false, "normalIntensity": 0.0})); + assert!(tilt(&mut s, &texels) < 1e-3, "no intensity: flat"); execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap(); + assert!(tilt(&mut s, &texels) < 1e-3, "Overwrite Existing Normal replaces the fill's normal"); set(&mut s, effect, json!({"overwriteExistingNormal": false})); + assert!((normal(&mut s, texels[0])[0] - 0.7).abs() < 0.02, "laid over the fill's normal: {:?}", normal(&mut s, texels[0])); let all = json!({"overwriteExistingNormal": true, "useWorldUnits": true, "surfaceSize": 0.0, "heightDepth": 500.0, @@ -154,6 +163,7 @@ fn height_to_normal_turns_the_height_into_the_normal() { assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "useWorldUnits": "yes"})).is_err()); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Height To Normal")); } @@ -167,15 +177,18 @@ fn color_match_moves_the_colors_to_the_target() { let texels: Vec<(u32, u32)> = (0..24).map(|k| (SIZE / 4 + k * 2, SIZE / 2)).collect(); let before: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); let spread = |colors: &[[f32; 3]]| colors.iter().map(|c| c[0]).fold(f32::MIN, f32::max) - colors.iter().map(|c| c[0]).fold(f32::MAX, f32::min); + assert!(spread(&before) > 0.05, "the clouds vary: {before:?}"); let effect = add_filter(&mut s, json!({"filter": "Color Match"})); assert_eq!(filter_of(&s, effect), Filter::ColorMatch(ColorMatch::LIBRARY)); let off = &s.doc.project.effect(effect).unwrap().1.off_channels; + assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness), "{off:?}"); let new: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&new) > 0.02, "a new Color Match keeps the pattern: {new:?}"); let redness = new.iter().map(|c| c[0] - c[2]).sum::() / new.len() as f32; @@ -192,6 +205,7 @@ fn color_match_moves_the_colors_to_the_target() { // Without Custom Color Variation the texels keep their differences from the mean, now around the target set(&mut s, effect, json!({"customColorVariation": false})); let kept: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect(); + assert!(spread(&kept) > 0.02, "variation kept: {kept:?}"); let redness = kept.iter().map(|c| c[0] - c[2]).sum::() / kept.len() as f32; @@ -200,6 +214,7 @@ fn color_match_moves_the_colors_to_the_target() { let brighter = |colors: &[[f32; 3]], a: usize, b: usize| colors[a][0] + colors[a][1] > colors[b][0] + colors[b][1]; let (lightest, darkest) = (0..texels.len()).fold((0, 0), |(hi, lo), k| (if before[k][0] > before[hi][0] { k } else { hi }, if before[k][0] < before[lo][0] { k } else { lo })); + assert!(brighter(&kept, lightest, darkest), "the lightest red stays the lightest"); // Source Color Parameter: the texels of that color land on the target @@ -238,5 +253,6 @@ fn color_match_moves_the_colors_to_the_target() { &[json!({"sourceColorMode": "median"}), json!({"targetColorMode": "input"}), json!({"customColorVariation": 1}), json!({"targetColor": "red"})], ); let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("Color Match")); } diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs index 16e2e0a0..796396c2 100644 --- a/crates/engine/tests/it/filter_support.rs +++ b/crates/engine/tests/it/filter_support.rs @@ -57,6 +57,7 @@ pub(crate) fn roughness(s: &mut Session, (x, y): (u32, u32)) -> f32 { pub(crate) fn add_filter(s: &mut Session, params: Value) -> LayerId { let mut params = params; params["target"] = json!("content"); + LayerId(execute(s, "effect.add.filter", ¶ms).unwrap()["effect"].as_u64().unwrap()) } @@ -78,6 +79,7 @@ pub(crate) fn filter_of(s: &Session, effect: LayerId) -> Filter { pub(crate) fn set(s: &mut Session, effect: LayerId, params: Value) { let mut params = params; params["effect"] = json!(effect.0); + execute(s, "effect.set", ¶ms).unwrap(); } @@ -86,6 +88,7 @@ pub(crate) fn refused(s: &mut Session, effect: LayerId, bad: &[Value]) { for bad in bad { let mut params = bad.clone(); params["effect"] = json!(effect.0); + assert!(execute(s, "effect.set", ¶ms).is_err(), "{bad}"); } } diff --git a/crates/engine/tests/it/filter_swap.rs b/crates/engine/tests/it/filter_swap.rs index c8502ad8..5c41ea01 100644 --- a/crates/engine/tests/it/filter_swap.rs +++ b/crates/engine/tests/it/filter_swap.rs @@ -109,6 +109,7 @@ fn asking_a_saved_warp_for_another_mode_replaces_it_with_a_warp_in_that_mode() { let edited = effect(&s, warp).kind; assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional && warp.angle == 90.0), "{edited:?}"); + let edited = effect(&s, directional).kind; assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::MultiDirectional), "{edited:?}"); } @@ -135,6 +136,7 @@ fn swapping_to_a_gradient_given_colors_ramps_evenly_through_them() { let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") }; let halfway = gradient.ramp_at(0.5).unwrap(); + assert!((halfway[0] - 0.5).abs() < 1e-3, "black to white is mid gray halfway: {halfway:?}"); } @@ -188,8 +190,10 @@ fn a_mask_filter_swaps_in_place_on_the_mask() { 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]); } @@ -234,8 +238,10 @@ fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { } 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"); } @@ -284,6 +290,7 @@ fn filters_carry_the_workflows_names_and_former_names_still_follow_a_swap() { let mut s = session(); let slope = add(&mut s, "effect.add.filter", json!({"filter": "slopeBlur", "target": "content"})); assert_eq!(effect(&s, slope).name, "Blur Slope"); + let names: Vec = execute(&mut s, "filter.list", &Value::Null).unwrap().as_array().unwrap().iter().map(|def| def["label"].clone()).collect(); for name in ["Contrast Luminosity", "Blur Slope", "Highpass", "Grayscale Conversion"] { assert!(names.contains(&json!(name)), "{name} in {names:?}"); @@ -292,5 +299,6 @@ fn filters_carry_the_workflows_names_and_former_names_still_follow_a_swap() { // A project saved before the rename holds the former name: a swap still renames it, and the former name still finds the filter let old = add(&mut s, "effect.add.filter", json!({"filter": "Slope Blur", "target": "content", "name": "Slope Blur"})); set(&mut s, old, json!({"filter": "blur"})); + assert_eq!(effect(&s, old).name, "Blur"); } diff --git a/crates/engine/tests/it/filter_transform.rs b/crates/engine/tests/it/filter_transform.rs index 704c2c87..d5e7b9a6 100644 --- a/crates/engine/tests/it/filter_transform.rs +++ b/crates/engine/tests/it/filter_transform.rs @@ -19,12 +19,14 @@ fn transform_moves_scales_and_flips_each_tile() { let mut s = session(); let row = SIZE / 2; let empty = roughness(&mut s, (8, row)); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap(); execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap(); let before: Vec = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect(); let was = |x: u32| before[(x % SIZE) as usize]; let effect = add_filter(&mut s, json!({"filter": "transform"})); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Transform"); @@ -34,26 +36,32 @@ fn transform_moves_scales_and_flips_each_tile() { // A quarter tile on: each texel reads 32 texels further right, the last ones round from the left set(&mut s, effect, json!({"offset": [0.25, 0.0]})); + for x in [20, 50, 110] { assert!((roughness(&mut s, (x, row)) - was(x + SIZE / 4)).abs() < 2e-3, "offset at {x}"); } set(&mut s, effect, json!({"offset": 0.0, "flipMode": "horizontally"})); + assert!((roughness(&mut s, (20, row)) - was(SIZE - 1 - 20)).abs() < 2e-3, "flipped, the left reads the right"); // Twice across about the centre: the centre stays; without repeat the edges read empty (the layer's content is clear there) set(&mut s, effect, json!({"flipMode": "none", "scaling": [2.0, 2.0], "repeatMode": "none"})); + assert!((roughness(&mut s, (SIZE / 2, row)) - was(SIZE / 2)).abs() < 2e-2, "the centre stays"); assert!((roughness(&mut s, (8, row)) - empty).abs() < 1e-4, "past the content reads empty"); // Repeating, texel 8 reads 2 · 8.5 / 128 − 0.5 of a tile on: between texels 80 and 81 set(&mut s, effect, json!({"repeatMode": "horizontallyAndVertically"})); + assert!((roughness(&mut s, (8, row)) - (was(80) + was(81)) / 2.0).abs() < 2e-3, "the tile comes round again"); let edited = transform_of(&s, effect); + assert_eq!((edited.repeat, edited.flip, edited.scaling), (RepeatMode::HorizontallyAndVertically, FlipMode::None, [2.0, 2.0])); set(&mut s, effect, json!({"rotation": -30.0, "tileSafeRotation": false})); + let turned = transform_of(&s, effect); assert_eq!((turned.rotation, turned.tile_safe), (330.0, false), "a turn reads 0..360"); @@ -68,11 +76,14 @@ fn transform_moves_scales_and_flips_each_tile() { json!({"tileSafeRotation": 1}), ], ); + assert_eq!(transform_of(&s, effect), turned, "a refused value changes nothing"); set(&mut s, effect, json!({"scaling": [1e9, -5.0]})); + assert_eq!(transform_of(&s, effect).scaling, [TileTransform::SCALING.1, TileTransform::SCALING.0], "scaling clamps"); execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(); + assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY); } diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index d423c852..e1e27297 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -79,33 +79,44 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); + assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); + execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it. + // A gradient map recolors the content; effect.set edits it and inspect shows it let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); + execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); + assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); + execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped. + // Posterize on the mask; its steps are clamped let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels, .. }) if levels == 64.0)); - // Material finishes fill the content's roughness and height. + + // Material finishes fill the content's roughness and height let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); + assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - // A directional blur, slope blur and warp composite without trouble on a sphere. + + // A directional blur, slope blur and warp composite without trouble on a sphere for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"intensity": 0.5, "divider": 1})), diff --git a/crates/render/src/ibl.rs b/crates/render/src/ibl.rs index 43c8f56c..ccab5dba 100644 --- a/crates/render/src/ibl.rs +++ b/crates/render/src/ibl.rs @@ -56,8 +56,12 @@ impl EnvImage { /// Box-downsample by 2. pub fn half(&self) -> EnvImage { - let (width, height, data) = environment_sky::half(self.width, self.height, |x, y| self.get(x as i64, y as i64)); - EnvImage { width, height, data: data.iter().map(Vec3::to_array).collect() } + Self::half_from(self.width, self.height, |x, y| self.get(i64::from(x), i64::from(y))) + } + + fn half_from(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> Self { + let (width, height, data) = environment_sky::half(width, height, texel); + Self { width, height, data: data.into_iter().map(|rgb| rgb.to_array()).collect() } } /// An imported equirect image (`rgba` row-major, top row first, sRGB-encoded when `srgb`) as @@ -65,16 +69,32 @@ impl EnvImage { /// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the /// pixel count does not match the size. pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option { - if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 { + Self::from_pixels(width, height, rgba, srgb) + } + + /// An imported linear RGB equirect image, with the same validation and size limits as [Self::from_rgba]. + pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option { + Self::from_pixels(width, height, rgb, false) + } + + fn from_pixels(width: u32, height: u32, pixels: &[[f32; COMPONENTS]], srgb: bool) -> Option { + if width == 0 || height == 0 || pixels.len() as u64 != width as u64 * height as u64 { return None; } - let linear = |v: f32| environment_sky::environment_linear(v, srgb); - let data = rgba.par_iter().map(|p| [linear(p[0]), linear(p[1]), linear(p[2])]).collect(); - let mut img = EnvImage { width, height, data }; + + let linear_rgb = |pixel: &[f32; COMPONENTS]| std::array::from_fn(|component| environment_sky::environment_linear(pixel[component], srgb)); + let mut img = if width > MAX_IMPORT_WIDTH || height > MAX_IMPORT_WIDTH { + // Linearize only the texels that contribute to the first reduced level + Self::half_from(width, height, |x, y| Vec3::from(linear_rgb(&pixels[y as usize * width as usize + x as usize]))) + } else { + Self { width, height, data: pixels.par_iter().map(linear_rgb).collect() } + }; + while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH { img = img.half(); } - // The mip chain needs at least 4×2 texels at its last level. + + // The mip chain needs at least 4×2 texels at its last level if img.width < 128 || img.height < 64 { let (w, h) = (img.width.max(128), img.height.max(64)); let data = (0..w * h).map(|i| img.sample(dir_of(((i % w) as f32 + 0.5) / w as f32, ((i / w) as f32 + 0.5) / h as f32)).to_array()).collect(); diff --git a/crates/ui-egui/src/property_sheet/color_bar.rs b/crates/ui-egui/src/property_sheet/color_bar.rs index d120ce3f..f2322fa4 100644 --- a/crates/ui-egui/src/property_sheet/color_bar.rs +++ b/crates/ui-egui/src/property_sheet/color_bar.rs @@ -92,8 +92,8 @@ impl PropertySheet<'_> { let state_id = bar.with("picker"); let mut state = picker_state(ctx, state_id); if !state.open { - open_picker(ctx, &mut state, linear); - ctx.data_mut(|data| data.insert_temp(state_id, state)); + open_picker(ctx, state_id, &mut state, linear); + ctx.memory_mut(|memory| memory.caches.cache::().set(state_id, state)); } } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index f975c19d..6fd7b040 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -1,4 +1,4 @@ -use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, RowLead, SMALL_TEXT_SIZE, TEXT_SIZE}; use crate::theme::semibold; diff --git a/crates/ui-egui/tests/it/filter_card.rs b/crates/ui-egui/tests/it/filter_card.rs index 6c78e409..30834e46 100644 --- a/crates/ui-egui/tests/it/filter_card.rs +++ b/crates/ui-egui/tests/it/filter_card.rs @@ -17,6 +17,7 @@ fn a_pill_switches_its_channel_and_the_chip_picks_the_divider() { let chip = harness.get_by_role_and_label(Role::ComboBox, "÷10").rect(); click_at(&mut harness, chip.center()); + assert!(egui::Popup::is_any_open(&harness.ctx), "the chip opens its list"); let hundred = harness.get_by_role_and_label(Role::ListBoxOption, "÷100").rect(); @@ -33,6 +34,7 @@ fn restore_defaults_and_clear_on_the_card() { let restore = harness.get_by_role_and_label(Role::Button, "Restore defaults"); assert!(restore.accesskit_node().is_disabled(), "inert at the defaults"); + let restore = restore.rect(); let clear = harness.get_by_role_and_label(Role::Button, "Clear").rect(); assert!((restore.center().y - clear.center().y).abs() < 0.5 && restore.right() < clear.left(), "⟲ beside × on the card"); @@ -68,6 +70,7 @@ fn the_filter_card_holds_its_parameters() { // A row inside the card keeps the card's bleed on both sides; a band would span the panel assert_eq!(attributes.left(), card.left() + CARD_BLEED, "{attributes:?} {card:?}"); assert_eq!(sub_group.left(), attributes.left(), "a sub-group is a caption in the card, not a card of its own"); + for slider in harness.query_all_by_role(Role::Slider) { assert!(slider.rect().bottom() <= attributes.top(), "Attributes is the card's last row: {:?}", slider.rect()); } diff --git a/crates/ui-egui/tests/it/filter_gradient.rs b/crates/ui-egui/tests/it/filter_gradient.rs index 9a485c56..fe9e1bde 100644 --- a/crates/ui-egui/tests/it/filter_gradient.rs +++ b/crates/ui-egui/tests/it/filter_gradient.rs @@ -18,6 +18,7 @@ fn a_gradient_marker_drags_its_color_along_the_ramp() { let Filter::GradientMap { positions, .. } = filter_of(&harness, effect) else { panic!() }; let moved = positions.get(1).copied().unwrap(); + assert!(moved > 0.6, "dragged right: {positions:?}"); undo(&mut harness); @@ -48,7 +49,9 @@ fn a_color_quantity_drag_is_its_own_undo_step() { let (mut harness, effect) = app_with("gradientMap", "content", WINDOW_HEIGHT); let linear = harness.get_by_role_and_label(Role::CheckBox, "Blend Color in Linear").rect(); click_at(&mut harness, linear.center()); + assert!(matches!(filter_of(&harness, effect), Filter::GradientMap { linear: false, .. })); + let depth = undo_depth(&harness); // From 2.6 colors to 3.2 (both round to the 3 it has), then to 4.2 diff --git a/crates/ui-egui/tests/it/filter_inputs.rs b/crates/ui-egui/tests/it/filter_inputs.rs index b3ff2d4f..4d1500ed 100644 --- a/crates/ui-egui/tests/it/filter_inputs.rs +++ b/crates/ui-egui/tests/it/filter_inputs.rs @@ -27,7 +27,9 @@ fn the_distance_map_slot_picks_its_source() { assert!(lowest(&harness, Role::ComboBox, "Distance Map").top() > topmost(&harness, Role::Button, "Attributes").bottom(), "after the filter card"); click(&mut harness, Role::ComboBox, "Distance Map"); + assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "the slot opens the source picker"); + click(&mut harness, Role::ListBoxOption, "Clouds"); let Some(Source::Procedural { pattern, low, high, .. }) = input(&harness, effect, "distanceMap") else { panic!("a procedural") }; @@ -36,6 +38,7 @@ fn the_distance_map_slot_picks_its_source() { // The filter card has its own ×: the slot's is the lower one click(&mut harness, Role::Button, "Clear"); + assert_eq!(input(&harness, effect, "distanceMap"), None, "back to its default white"); let ramp = harness.get_by_role_and_label(Role::Slider, "Distance Map").rect(); @@ -79,6 +82,7 @@ fn the_attributes_row_opens_on_a_click() { let (mut harness, _) = app_with("bevelSmooth", "mask", WINDOW_HEIGHT); let category = "Category: Filter"; assert!(harness.query_by_label(category).is_none(), "closed by default"); + let band = topmost(&harness, Role::Button, "Attributes"); assert!(band.bottom() < lowest(&harness, Role::ComboBox, "Distance Map").top(), "above the input's card"); @@ -109,6 +113,7 @@ fn the_sheet_keeps_its_layout_when_the_scroll_bar_comes_in() { for frame in 0..3 { harness.run_steps(1); + assert_eq!(layout(&harness), first, "frame {frame}"); } } diff --git a/crates/ui-egui/tests/it/filter_light.rs b/crates/ui-egui/tests/it/filter_light.rs index d93268ba..40e8190c 100644 --- a/crates/ui-egui/tests/it/filter_light.rs +++ b/crates/ui-egui/tests/it/filter_light.rs @@ -57,6 +57,7 @@ fn drop_shadow_angle_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); undo(&mut harness); + assert!(matches!(filter_of(&harness, effect), Filter::DropShadow { angle, .. } if angle == 90.0), "{:?}", filter_of(&harness, effect)); } @@ -91,6 +92,7 @@ fn baked_lighting_stylized_cards_set_the_sun_a_light_and_the_output() { let filter = filter_of(&harness, effect); let (stylized, light) = filter.stylized_lighting().unwrap(); + assert!(light.sun.intensity > 9.5, "{}", light.sun.intensity); assert!(stylized.lights[0].intensity > 1.9 && stylized.lights[1].intensity == 0.0, "{:?}", stylized.lights); assert_eq!(stylized.output, LightingOutput::Specular); diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 69244a47..53808c42 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -30,6 +30,7 @@ fn picking_from_the_slot_swaps_the_filter() { // 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"); let at = harness.get_by_label("Sharpen").rect().center(); @@ -78,6 +79,7 @@ fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { harness.run_steps(3); let at = harness.get_by_label("Sharpen").rect().center(); click_at(&mut harness, at); + assert!(matches!(filter_of(&harness, added), Filter::Sharpen { .. }), "{:?}", filter_of(&harness, added)); } @@ -85,6 +87,7 @@ fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { fn escape_after_add_filter_keeps_the_empty_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); @@ -95,6 +98,7 @@ fn escape_after_add_filter_keeps_the_empty_filter() { assert!(matches!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); harness.state_mut().run("edit.undo", Value::Null); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the empty filter"); } @@ -111,6 +115,7 @@ fn add_filter_on_a_mask_adds_it_to_the_mask() { 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!(filter_of(&harness, added), Filter::Empty), "{:?}", filter_of(&harness, added)); assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open"); @@ -123,6 +128,7 @@ fn add_filter_reopens_closed_properties_to_show_its_picker() { let (mut harness, _) = app_with_invert(); harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); harness.run_steps(3); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Invert").is_none()); add_filter_from_the_wand(&mut harness); @@ -138,6 +144,7 @@ fn keyboard_opens_the_slot_and_outside_click_closes_it() { harness.get_by_role_and_label(Role::ComboBox, "Invert").focus(); harness.key_press(key); harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx)); let position = harness.state().viewport_rect.center(); @@ -147,6 +154,7 @@ fn keyboard_opens_the_slot_and_outside_click_closes_it() { harness.run_steps(1); } harness.run_steps(3); + assert!(!egui::Popup::is_any_open(&harness.ctx)); assert!(matches!(filter_of(&harness, effect), Filter::Invert)); } diff --git a/crates/ui-egui/tests/it/filter_shape.rs b/crates/ui-egui/tests/it/filter_shape.rs index 50358d2b..3a2b5229 100644 --- a/crates/ui-egui/tests/it/filter_shape.rs +++ b/crates/ui-egui/tests/it/filter_shape.rs @@ -127,6 +127,7 @@ fn bevel_distance_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::DistanceBevel(before)); } @@ -195,6 +196,7 @@ fn warp_rows_follow_the_mode() { fn slope_blur_rows_set_the_smear() { let (mut harness, effect) = app_with("slopeBlur", "mask", WINDOW_HEIGHT); assert!(harness.query_by_label("Slope scale").is_none()); + let top = |harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str| harness.get_by_role_and_label(role, label).rect().top(); let order = [ top(&harness, Role::Slider, "Intensity"), @@ -266,6 +268,7 @@ fn legacy_warp_seed_past_two_to_the_24_opens_as_stored() { click_at(&mut harness, field.center()); let typed = harness.get_all_by_role(Role::TextInput).filter(|node| node.rect().intersects(field)).find_map(|node| node.accesskit_node().value()); + assert_eq!(typed, Some(LARGE_SEED.to_string())); } @@ -287,7 +290,9 @@ fn slope_blur_divider_seed_and_source_blur() { assert_eq!(slope.divider, 1000); assert_ne!(slope.seed, 0, "a new seed"); assert!((slope.source.blur - 0.5).abs() < 0.01, "stored on 0..1: {}", slope.source.blur); + let shown = harness.get_by_role_and_label(Role::Slider, "Blur").accesskit_node().numeric_value().unwrap(); + assert!((shown - 10.0).abs() < 0.2, "shown on 0..20: {shown}"); } diff --git a/crates/ui-egui/tests/it/filter_simple.rs b/crates/ui-egui/tests/it/filter_simple.rs index 52e04446..9157f62d 100644 --- a/crates/ui-egui/tests/it/filter_simple.rs +++ b/crates/ui-egui/tests/it/filter_simple.rs @@ -16,10 +16,12 @@ fn invert_switch_turns_it_off_and_on() { let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::InvertOff); let switch = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect(); click_at(&mut harness, switch.center()); + assert_eq!(filter_of(&harness, effect), Filter::Invert); } @@ -122,6 +124,7 @@ fn simple_sliders_set_their_own_setting() { let after = filter_of(&harness, effect); let value = read(&after).unwrap(); + assert!((value - expected).abs() < SLIDER_TOLERANCE, "{filter} {label}: {value}, expected {expected}"); assert_ne!(read(&before), read(&after), "{filter} {label} changed"); } @@ -140,6 +143,7 @@ fn a_slider_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1); undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Sharpen { amount: 1.0 }); } @@ -149,11 +153,13 @@ fn pixelate_rows() { let (mut harness, effect) = app_with("pixelate", "mask", WINDOW_HEIGHT); let amount = harness.get_by_role_and_label(Role::Slider, "Pixels Amount"); assert_eq!(amount.accesskit_node().numeric_value().map(f64::round), Some(32.0)); + let amount = amount.rect(); let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); assert!(alpha.center().y > amount.center().y); click_at(&mut harness, alpha.center()); + assert!(matches!(filter_of(&harness, effect), Filter::Mosaic { alpha: false, .. })); click_at(&mut harness, along(amount, 1.0)); @@ -198,6 +204,7 @@ fn highpass_rows() { let (mut harness, effect) = app_with("highPass", "mask", WINDOW_HEIGHT); let radius = harness.get_by_role_and_label(Role::Slider, "Radius"); assert_eq!(radius.accesskit_node().numeric_value().map(|value| (value * 100.0).round()), Some(300.0)); + let radius = radius.rect(); let space = harness.get_by_role_and_label(Role::ComboBox, "Working space / Mask").rect(); let alpha = harness.get_by_role_and_label(Role::CheckBox, "Apply To Alpha").rect(); @@ -205,9 +212,11 @@ fn highpass_rows() { pick(&mut harness, "Working space / Mask", "sRGB (from ACEScg)"); click_at(&mut harness, alpha.center()); + assert_eq!(filter_of(&harness, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::SrgbFromAcescg, alpha: true }); click_at(&mut harness, along(radius, 1.0)); + assert!(matches!(filter_of(&harness, effect), Filter::HighPass { radius, .. } if radius > 250.0), "Radius 16 = 256 texels at 2K"); } @@ -218,6 +227,7 @@ fn grayscale_conversion_rows() { let invert = harness.get_by_role_and_label(Role::CheckBox, "Invert").rect().center().y; let sliders = ["Balance", "Contrast", "Red", "Green", "Blue", "Alpha"].map(|label| harness.get_by_role_and_label(Role::Slider, label).rect().center().y); let rows: Vec = std::iter::once(invert).chain(sliders).collect(); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1]), "the reference's order: {rows:?}"); assert!(harness.query_by_role_and_label(Role::ComboBox, "Custom Input").is_none(), "no slot for the current channel"); diff --git a/crates/ui-egui/tests/it/filter_stylize.rs b/crates/ui-egui/tests/it/filter_stylize.rs index b285db69..936f4735 100644 --- a/crates/ui-egui/tests/it/filter_stylize.rs +++ b/crates/ui-egui/tests/it/filter_stylize.rs @@ -23,6 +23,7 @@ fn anisotropic_kuwahara_rows() { let Filter::AnisotropicKuwahara(kuwahara) = filter_of(&harness, effect) else { panic!("still Kuwahara") }; assert!(kuwahara.custom_input); + let slot = lowest(&harness, Role::ComboBox, "Custom Input"); let radius = harness.get_by_role_and_label(Role::Slider, "Radius").rect(); assert!(slot.center().y < radius.center().y, "its slot right under Extract Direction"); @@ -150,6 +151,7 @@ fn color_match_rows() { assert_eq!(color_match_of(&harness, effect).target_mode, TargetColorMode::ImageInput); assert!(harness.query_by_role_and_label(Role::Button, "Target Color").is_none(), "the Image Input slot replaces Target Color"); + let shown = harness.query_all_by_label("Image Input").count(); assert!(shown >= 2, "the mode and its slot: {shown}"); @@ -164,15 +166,18 @@ fn color_match_rows() { click_at(&mut harness, row.center()); assert_eq!(color_match_of(&harness, effect).source_mode, SourceColorMode::Parameter); + let source = harness.get_by_role_and_label(Role::Button, "Source Color").rect(); assert!(source.center().y < target_mode(&harness, "Image Input").center().y, "Source Color right under its mode"); let luma = harness.get_by_role_and_label(Role::Slider, "Luma").rect(); click_at(&mut harness, along(luma, 1.0)); + assert!(color_match_of(&harness, effect).luma > 0.95, "{}", color_match_of(&harness, effect).luma); let custom = harness.get_by_role_and_label(Role::CheckBox, "Custom Color Variation").rect(); click_at(&mut harness, custom.center()); + assert!(!color_match_of(&harness, effect).custom_variation); assert!(harness.query_by_role_and_label(Role::Slider, "Hue").is_none(), "the Color Variation card goes with its switch"); } diff --git a/crates/ui-egui/tests/it/filter_transform.rs b/crates/ui-egui/tests/it/filter_transform.rs index 38af6e79..4f526a30 100644 --- a/crates/ui-egui/tests/it/filter_transform.rs +++ b/crates/ui-egui/tests/it/filter_transform.rs @@ -82,5 +82,6 @@ fn rotation_drag_is_one_undo_step() { assert_eq!(undo_depth(&harness), depth + 1, "one undo step for the drag"); undo(&mut harness); + assert_eq!(filter_of(&harness, effect), Filter::Transform(TileTransform::LIBRARY)); } diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs index ef3bcb47..e5aef5c7 100644 --- a/crates/ui-egui/tests/it/properties_lists.rs +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -174,6 +174,7 @@ fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &s if !is_open(harness) && !open(harness, button) { return [problems, vec![format!("{name}: it does not open again after the wheel")]].concat(); } + if !pans(harness, gesture_start) { problems.push(format!("{name}: a middle drag in the view does not pan while it is open")); } @@ -182,6 +183,7 @@ fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &s if !is_open(harness) && !open(harness, button) { return [problems, vec![format!("{name}: a second click does not open it")]].concat(); } + if !orbits(harness, gesture_start) { problems.push(format!("{name}: an Alt drag in the view does not orbit while it is open")); } @@ -189,6 +191,7 @@ fn check_list(harness: &mut Harness<'_, TextureCraftApp>, button: Rect, name: &s if !is_open(harness) && !open(harness, button) { return [problems, vec![format!("{name}: it does not open again")]].concat(); } + harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); if is_open(harness) { @@ -219,6 +222,7 @@ fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_ for (screen, mut harness) in screens() { let count = lists(&harness).len(); assert!(count > 0, "{screen}: lists show"); + for index in 0..count { // Looked up again each time: a closed list or a stroke may move the rows below let Some((button, shown)) = lists(&harness).get(index).cloned() else { @@ -233,6 +237,7 @@ fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_ } } } + assert!(problems.is_empty(), "{}", problems.join("\n")); } @@ -257,6 +262,7 @@ fn the_colour_picker_window_and_the_symmetry_settings_leave_the_view_its_wheel_m harness.run_steps(SETTLE_FRAMES); let settings_open = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_label("Radial symmetry").is_some(); assert!(settings_open(&harness), "the settings open"); + let start = gesture_start(&harness); assert!(zooms(&mut harness, start), "the wheel over the view zooms with the symmetry settings open"); assert!(settings_open(&harness), "the wheel leaves the settings open"); From 8c521dbf560c25a405b3128411dadf99fa21920b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:32:12 +0000 Subject: [PATCH 044/153] Instanced folders: a neighbourhood filter under an offset folder reads its content in the instance's space Reported by skylartaylor on #698: a Blur on a layer inside an instanced folder under a scaled or rotated folder read its content in the source's un-offset space. Neighbourhood fields are built and looked up per layer and folder offset, for content and mask fields and on the cached-layer path. --- crates/compose/src/eval.rs | 126 ++++++++++++++------ crates/compose/tests/cache_and_instances.rs | 81 ++++++++++++- 2 files changed, 167 insertions(+), 40 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index f8fad747..d0cdb0f2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -296,10 +296,23 @@ impl Field { } } +/// A layer's mask or content channel field, filtered under the folders' Scale and Rotation (as bits) its traversal lays on its fills #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum FieldKey { - Mask(LayerId), - Content(LayerId, Channel), + Mask(LayerId, [u32; 2]), + Content(LayerId, Channel, [u32; 2]), +} + +impl FieldKey { + /// The key of layer `id`'s mask field under the folders' offset `around` + pub fn mask(id: LayerId, around: ContentsOffset) -> FieldKey { + FieldKey::Mask(id, [around.scale.to_bits(), around.rotation.to_bits()]) + } + + /// The key of layer `id`'s `channel` content field under the folders' offset `around` + pub fn content(id: LayerId, channel: Channel, around: ContentsOffset) -> FieldKey { + FieldKey::Content(id, channel, [around.scale.to_bits(), around.rotation.to_bits()]) + } } pub type Fields = HashMap; @@ -646,14 +659,14 @@ fn layer_mask(p: &Project, id: LayerId) -> Option<&Mask> { /// Layers of `list` in drawing order (bottom → top, folder and instanced folder contents after /// their folder). -fn draw_order(p: &Project, list: &[LayerId], depth: usize, out: &mut Vec) { +fn draw_order(p: &Project, list: &[LayerId], depth: usize, around: ContentsOffset, out: &mut Vec<(LayerId, ContentsOffset)>) { if depth > texturecraft_core::project::MAX_DEPTH { return; } for id in list { - out.push(*id); + out.push((*id, around)); if let Some(l) = p.content_layer(*id) { - draw_order(p, l.children(), depth + 1, out); + draw_order(p, l.children(), depth + 1, around.then(p.contents_offset(l.id)), out); } } } @@ -666,7 +679,14 @@ enum Job<'a> { } /// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`. -fn field(inp: &EvaluationInputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { +fn field( + inp: &EvaluationInputs, + channels: &[Channel], + below: &Fields, + (id, around): (LayerId, ContentsOffset), + job: Job, + tiles: &[(u32, u32)], +) -> Option { let effects = match job { Job::Mask(mask) => &mask.effects, Job::Content(_) => &inp.project.content_layer(id)?.content_effects, @@ -685,7 +705,7 @@ fn field(inp: &EvaluationInputs, channels: &[Channel], below: &Fields, id: Layer 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)?; + let filtered = filter_region(inp, channels, below, (id, around), job, effects, filter, region, start)?; // Preserve only stages with anchors before the next filter overwrites their value if let Some((previous_index, previous_field)) = previous.take() @@ -739,7 +759,7 @@ fn filter_region( inputs: &EvaluationInputs, channels: &[Channel], below: &Fields, - id: LayerId, + (id, around): (LayerId, ContentsOffset), job: Job, effects: &[Effect], (index, radius, op): (usize, f32, Op), @@ -781,7 +801,7 @@ fn filter_region( match job { Job::Mask(layer_mask) => { // The layer's own filtered content, for a compare of it (this mask's field is not built yet) - let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), inputs.project.contents_around(id)) else { + let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), around) else { return Vec::new(); }; @@ -791,7 +811,7 @@ fn filter_region( mask = Some(mask_stack); } Job::Content(channel) => { - nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below)); + nodes = plan_in(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below), around); if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { channel_plan.effects.truncate(index); channel_plan.start = start; @@ -1064,11 +1084,11 @@ pub fn neighbourhood_fields(inputs: &Inputs, channels: &[Channel], tiles: &[(u32 fn evaluation_fields(inp: &EvaluationInputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields { let stack = inp.project.texture_set(inp.ts).map(|s| s.stack.as_slice()).unwrap_or_default(); - fields_of(inp, channels, stack, tiles) + fields_of(inp, channels, (stack, ContentsOffset::NONE), tiles) } -/// [`neighbourhood_fields`] of the layers drawn by `list` only. -fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields { +/// [`neighbourhood_fields`] of the layers drawn by `list` only, held by folders whose Scale and Rotation make `around` +fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[LayerId], ContentsOffset), tiles: &[(u32, u32)]) -> Fields { let mut out = Fields::new(); if tiles.is_empty() || inp.gbuf.width == 0 { return out; @@ -1076,29 +1096,30 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], til let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp.project, list, 0, &mut order); - prepare_curvature_sizes(inp, &order); + draw_order(inp.project, list, 0, around, &mut order); + let ids: Vec = order.iter().map(|(id, _)| *id).collect(); + prepare_curvature_sizes(inp, &ids); - for id in order { + for (id, around) in order { let Some(layer) = inp.project.content_layer(id) else { continue }; let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); // A mask comparing the layer's own content reads it filtered, so its field comes after the content's let compares_content = mask.is_some_and(|mask| mask.effects.iter().any(|effect| effect.visible && compares_this_layer(&effect.kind))); if !compares_content { - insert_mask_field(inp, channels, &mut out, id, mask, tiles); + insert_mask_field(inp, channels, &mut out, (id, around), mask, tiles); } if !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some() { 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); + if let Some(filtered) = field(inp, channels, &out, (id, around), Job::Content(*channel), tiles) { + out.insert(FieldKey::content(id, *channel, around), filtered); } } } if compares_content { - insert_mask_field(inp, channels, &mut out, id, mask, tiles); + insert_mask_field(inp, channels, &mut out, (id, around), mask, tiles); } } @@ -1106,11 +1127,18 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], til } /// Layer `id`'s filtered `mask` field put into `fields` (nothing without a mask or a field) -fn insert_mask_field(inp: &EvaluationInputs, channels: &[Channel], fields: &mut Fields, id: LayerId, mask: Option<&Mask>, tiles: &[(u32, u32)]) { +fn insert_mask_field( + inp: &EvaluationInputs, + channels: &[Channel], + fields: &mut Fields, + (id, around): (LayerId, ContentsOffset), + mask: Option<&Mask>, + tiles: &[(u32, u32)], +) { if let Some(mask) = mask - && let Some(filtered) = field(inp, channels, fields, id, Job::Mask(mask), tiles) + && let Some(filtered) = field(inp, channels, fields, (id, around), Job::Mask(mask), tiles) { - fields.insert(FieldKey::Mask(id), filtered); + fields.insert(FieldKey::mask(id, around), filtered); } } @@ -1258,7 +1286,7 @@ fn mask_plan<'a>( let background = if mask.background == MaskBackground::White { 1.0 } else { 0.0 }; let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, around); - let filtered = fields.and_then(|fields| fields.get(&FieldKey::Mask(id))); + let filtered = fields.and_then(|fields| fields.get(&FieldKey::mask(id, around))); for effect in &mut effects { effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(id, _)| *id == effect.id).map(|(_, field)| field)); } @@ -1375,7 +1403,7 @@ fn plan_content<'a>( let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), around) } else { Vec::new() }; - let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c)))); + let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::content(id, *c, around)))); Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start }) }) .collect::>(); @@ -1418,11 +1446,25 @@ fn plan_levels<'a>(inp: &EvaluationInputs<'a>, levels: &[Level], channels: &[Cha let last = levels.len().saturating_sub(1); levels .iter() + .zip(level_offsets(inp.project, levels)) .enumerate() - .map(|(d, l)| LevelPlan { - below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, inp.project.contents_around(l.at)), - above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), + .map(|(d, (l, around))| LevelPlan { + below: if warm { Vec::new() } else { plan_in(inp, &l.below, channels, tx, ty, d, Some(fields), around) }, + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, around), + above: plan_in(inp, &l.above, channels, tx, ty, d, Some(fields), around), + }) + .collect() +} + +/// The Scale and Rotation the folders (instanced ones included) above each level of the path to the hot layer lay on its fills +fn level_offsets(p: &Project, levels: &[Level]) -> Vec { + let mut around = ContentsOffset::NONE; + levels + .iter() + .map(|level| { + let held = around; + around = around.then(p.content_layer(level.at).map_or(ContentsOffset::NONE, |layer| p.contents_offset(layer.id))); + held }) .collect() } @@ -2546,7 +2588,7 @@ fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles // Filter the current and following tiles as one run let planned_tiles: Vec<(u32, u32)> = block.iter().chain(&ahead).copied().collect(); let uncached_planned_tiles: Vec<(u32, u32)> = planned_tiles.iter().copied().filter(uncached).collect(); - let fields = Arc::new(block_fields(inp, &channels, &set.stack, hot, &uncached_planned_tiles, &planned_tiles)); + let fields = Arc::new(block_fields(inp, &channels, &set.stack, split.as_deref(), &uncached_planned_tiles, &planned_tiles)); let hot_tiles: std::collections::BTreeSet<(u32, u32)> = planned_tiles.iter().copied().collect(); let stack_tiles = if hot.is_some() && uncached_planned_tiles.len() < planned_tiles.len() { uncached_planned_tiles.into_iter().collect() @@ -2558,7 +2600,7 @@ fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles } fields } - _ => Arc::new(block_fields(inp, &channels, &set.stack, hot, &fresh, block)), + _ => Arc::new(block_fields(inp, &channels, &set.stack, split.as_deref(), &fresh, block)), }; let quota = match below.as_deref() { @@ -2589,8 +2631,8 @@ fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { let working_width = inp.gbuf.width; let mut order = Vec::new(); - draw_order(inp.project, stack, 0, &mut order); - order.into_iter().any(|id| { + draw_order(inp.project, stack, 0, ContentsOffset::NONE, &mut order); + order.into_iter().any(|(id, _)| { let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some()) }) @@ -2598,14 +2640,22 @@ fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool { /// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`), /// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`. -fn block_fields(inp: &EvaluationInputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields { +fn block_fields( + inp: &EvaluationInputs, + channels: &[Channel], + stack: &[LayerId], + split: Option<&[Level]>, + fresh: &[(u32, u32)], + tiles: &[(u32, u32)], +) -> Fields { + let hot = split.and_then(|levels| levels.last().zip(level_offsets(inp.project, levels).last().copied())); match hot { - Some(hot) if fresh.len() < tiles.len() => { - let mut fields = fields_of(inp, channels, stack, fresh); - fields.extend(fields_of(inp, channels, &[hot.at], tiles)); + Some((hot, around)) if fresh.len() < tiles.len() => { + let mut fields = fields_of(inp, channels, (stack, ContentsOffset::NONE), fresh); + fields.extend(fields_of(inp, channels, (&[hot.at], around), tiles)); fields } - _ => fields_of(inp, channels, stack, tiles), + _ => fields_of(inp, channels, (stack, ContentsOffset::NONE), tiles), } } diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index fd6332ad..29fd7115 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -8,8 +8,8 @@ use texturecraft_compose::{ BelowCache, Composite, Inputs, MaskGray, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, }; use texturecraft_core::{ - BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, - LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, + BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, + HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; use texturecraft_texel::{TILE, TileImage, to_u16}; @@ -975,3 +975,80 @@ fn id_map_image_changes_invalidate_stack_key() { assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache"); } + +/// Where a blur lies on the layer inside the instanced folder +#[derive(Clone, Copy, Debug)] +enum BlurOn { + Content, + Mask, +} + +/// A folder of set `ts` holding a Clouds fill whose content or mask is blurred by 8; returns the folder and the fill +fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option, blur_on: BlurOn) -> (LayerId, LayerId) { + let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); + let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None); + let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0 })); + match blur_on { + BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur), + BlurOn::Mask => { + let mut mask = Mask::new(MaskBackground::Black); + let checker = procedural(ProceduralKind::Checker, 0.0, 1.0); + mask.effects.push(effect(f, EffectKind::Fill { source: checker, projection: Projection::default(), sampling: Default::default() })); + mask.effects.push(blur); + f.project.layer_mut(clouds).unwrap().mask = Some(mask); + } + } + (held, clouds) +} + +/// A top-level folder of set 0 laying Scale 2 and Rotation 25 on the fills inside it +fn offset_folder(f: &mut Fixture) -> LayerId { + let contents = ContentsOffset::new(2.0, 25.0); + put(f, 0, None, LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, None) +} + +#[test] +fn a_neighbourhood_filter_in_an_instanced_folder_under_an_offset_folder_reads_its_content_in_the_instances_space() { + let mut mismatches = Vec::new(); + for blur_on in [BlurOn::Content, BlurOn::Mask] { + let mut instanced = fixture(); + let (source, _) = folder_of_blurred_clouds(&mut instanced, 1, None, blur_on); + let outer = offset_folder(&mut instanced); + put(&mut instanced, 0, Some(outer), LayerKind::Instance { source }, None); + + let mut copied = fixture(); + let outer = offset_folder(&mut copied); + folder_of_blurred_clouds(&mut copied, 0, Some(outer), blur_on); + + let (instanced, copied) = (reference(&instanced, 0), reference(&copied, 0)); + let texels = (0..RES).flat_map(|y| (0..RES).map(move |x| (x, y))); + let differences: Vec = texels + .map(|(x, y)| { + let (a, b) = (instanced.value(Channel::BaseColor, x, y), copied.value(Channel::BaseColor, x, y)); + a.iter().zip(&b).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max) + }) + .filter(|difference| *difference > 1e-5) + .collect(); + let largest = differences.iter().copied().fold(0.0, f32::max); + + if !differences.is_empty() { + mismatches.push(format!("{blur_on:?} blur: the instance differs from the copy by up to {largest} on {} texels", differences.len())); + } + } + + assert!(mismatches.is_empty(), "{}", mismatches.join("; ")); +} + +#[test] +fn a_hot_layer_with_a_neighbourhood_filter_in_an_instanced_folder_under_an_offset_folder_composites_exactly_cached() { + for blur_on in [BlurOn::Content, BlurOn::Mask] { + let mut instanced = fixture(); + let (source, clouds) = folder_of_blurred_clouds(&mut instanced, 1, None, blur_on); + let outer = offset_folder(&mut instanced); + put(&mut instanced, 0, Some(outer), LayerKind::Instance { source }, None); + + let cache = check_cached(&instanced, 0, clouds); + + assert!(!cache.is_empty(), "{blur_on:?} blur: the hot layer is cached through its instance"); + } +} From a9928aacf3ef2cbd28b19516a203d556fef4a836 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:30:01 +0000 Subject: [PATCH 045/153] Instanced folders: a filter's lit layer and height read the instance's space too The filter stack's own plans (the lit base colour below a filter and the heights it reads) take the traversal's folder offset, as the neighbourhood fields do since part 4. --- crates/compose/src/eval.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 7b0ef05b..b53c134f 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1532,10 +1532,11 @@ fn filter_region( .par_iter() .map(|&(tile_x, tile_y)| { // A base colour lit by its material below the filter lights it as the full render does - let lit_layer = if lit_prefix { plan(inputs, &[id], channels, tile_x, tile_y, 0, Some(below)).into_iter().find(|node| node.lights) } else { None }; + let lit_layer = + if lit_prefix { plan_in(inputs, &[id], channels, tile_x, tile_y, 0, Some(below), around).into_iter().find(|node| node.lights) } else { None }; let anchor_nodes = below_plan(inputs, id, channels, (tile_x, tile_y), Some(below), lit_layer.is_some()); let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); - let height_nodes = if heights { plan(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below)) } else { Vec::new() }; + let height_nodes = if heights { plan_in(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below), around) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); let mut generator_sizes = None; @@ -6039,7 +6040,10 @@ soft {soft:?}" let shared = shared_histogram_fields(&inputs, &channels, &all_tiles(64, 64)); - assert!(shared.is_some_and(|fields| fields.contains_key(&FieldKey::Content(id, Channel::BaseColor))), "every sampled tile reads one field"); + assert!( + shared.is_some_and(|fields| fields.contains_key(&FieldKey::content(id, Channel::BaseColor, ContentsOffset::NONE))), + "every sampled tile reads one field" + ); } #[test] From a90313c888a4c5e92602c754ef98e5eb62155c10 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sun, 22 Nov 2026 06:06:10 -0500 Subject: [PATCH 046/153] Clear texture updates in the headless Properties scroll test --- crates/ui-egui/src/property_sheet/properties_scroll.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/property_sheet/properties_scroll.rs b/crates/ui-egui/src/property_sheet/properties_scroll.rs index 294d52f5..4c3a5be7 100644 --- a/crates/ui-egui/src/property_sheet/properties_scroll.rs +++ b/crates/ui-egui/src/property_sheet/properties_scroll.rs @@ -116,12 +116,15 @@ mod tests { let context = egui::Context::default(); for (selection, expected_offset) in [(content, 42.0), (effect, 68.0), (content, 42.0)] { - let _ = context.run_ui(egui::RawInput::default(), |ui| { + let mut frame = context.run_ui(egui::RawInput::default(), |ui| { let area = scroll.prepare(ScrollArea::vertical().max_height(80.0), ui.scope_id(), selection); let output = area.show(ui, |ui| ui.add_space(256.0)); assert_eq!(output.state.clamped_offset().y, expected_offset); }); + + // This headless test has no renderer to apply texture updates + frame.textures_delta.clear(); } execute(&mut session, "effect.remove", &json!({"effect": effect_id.0})).unwrap(); From 6782dc90767ce7cb321c93b7d24a9fe1e5b5993d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 13:11:48 +0100 Subject: [PATCH 047/153] Layers: open context menus from material and mask thumbnails --- crates/ui-egui/src/dock.rs | 135 ++++++++++++++++-------- crates/ui-egui/tests/it/layers_panel.rs | 54 ++++++++++ 2 files changed, 147 insertions(+), 42 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 7f8cebfe..1659b998 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -175,7 +175,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| { let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); match &selected { - Some(layer) => effect_menu(app, ui, layer), + Some(layer) => effect_menu(app, ui, layer, false), None => { ui.label(RichText::new(tr("Select a layer")).color(tokens.text_dim)); } @@ -292,9 +292,9 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "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); +/// The content thumbnail targets content directly. The row and toolbar follow the selection. +fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, content_thumbnail: bool) { + let content = content_thumbnail || (!layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app)); let target = if content { "content" } else { "mask" }; ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); @@ -309,6 +309,9 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { (tr("Add anchor point"), "effect.add.anchor", json!({"target": target})), ]; for (label, command, params) in items { + if content_thumbnail && matches!(command, "effect.add.generator" | "effect.add.compare") { + continue; + } if !ui.button(label).clicked() { continue; } @@ -657,12 +660,14 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { content_glyph(&painter, &tokens, thumbnail, layer); } + let content_label = tr("Select the layer content"); + let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(content_label); painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); - let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); if content_response.clicked() { let modifiers = ui.input(|input| input.modifiers); click_layer(app, modifiers, layer.id.0, Some("content")); } + thumbnail_context_menu(ui, &content_response, content_label, &layer.name, content_target, |ui| layer_context_menu(app, ui, layer, true)); x = thumbnail.right() + THUMBNAIL_SPACING; // An instance draws its source's content, blending and (unless it has its own) mask @@ -696,9 +701,8 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize if !mask.enabled { painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } - let mask_response = ui - .interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()) - .on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)")); + let mask_label = tr("Select the mask (Alt+click: show it in the viewport)"); + let mask_response = ui.interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()).on_hover_text(mask_label); if mask_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); if ui.input(|input| input.modifiers.alt) { @@ -707,6 +711,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize app.run("viewport.view", view); } } + thumbnail_context_menu(ui, &mask_response, mask_label, &layer.name, mask_target, |ui| mask_management_menu(app, ui, layer, true)); if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { painter.rect_stroke( mask_rect.expand(HIGHLIGHT_OUTSET), @@ -878,7 +883,25 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {} } - row.context_menu(|ui| layer_context_menu(app, ui, layer)); + row.context_menu(|ui| layer_context_menu(app, ui, layer, false)); +} + +/// Expose the thumbnail as a focusable control and use the same popup for pointer and keyboard. +fn thumbnail_context_menu(ui: &Ui, response: &egui::Response, label: &str, layer_name: &str, selected: bool, contents: impl FnOnce(&mut Ui)) { + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, format!("{label} ({layer_name})"))); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu)); + let mut popup = egui::Popup::context_menu(response).anchor(response); + let return_focus = popup.is_open() && ui.input(|input| input.key_pressed(egui::Key::Escape)); + if response.has_focus() { + ui.painter().rect_stroke(response.rect.shrink(1.0), THUMBNAIL_ROUNDING, ui.visuals().widgets.active.fg_stroke, egui::StrokeKind::Inside); + if ui.input_mut(|input| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu)) { + popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); + } + } + popup.show(contents); + if return_focus { + response.request_focus(); + } } /// `params` of a shelf material dropped on the row of `layer`: inside a folder when dropped on its middle, else directly below the row @@ -1379,14 +1402,14 @@ fn blending_options_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) }); } -fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { +fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, content_thumbnail: bool) { let tk = Tokens::get(ui.ctx()); ui.set_min_width(230.0); let lid = layer.id.0; let keymap = app.ui.keymap.clone(); - // On one of several selected layers, remove, duplicate and group act on all of them - let several = selection_with(app, layer.id); + // The row menu can act on several selected layers. A thumbnail identifies one layer. + let several = if content_thumbnail { None } else { selection_with(app, layer.id) }; let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, p: Value, enabled: bool| { let mut b = egui::Button::new(label); if let Some(sc) = crate::keymap::shortcut_of(&keymap, id) { @@ -1405,29 +1428,12 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } }; - // An instance edits its source mask until it gets its own - let project = &app.session.doc.project; - let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.is_some()); - - // A switched-off mask has no values to export - let mask_on = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.as_ref().is_some_and(|m| m.enabled)); run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": lid}), layer.mask.is_none()); run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": lid}), layer.mask.is_none()); run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": lid}), true); - ui.separator(); - run(app, ui, tr("Toggle mask"), "mask.toggle", json!({"layer": lid}), has_mask); - run(app, ui, tr("Invert mask background"), "mask.invertBackground", json!({"layer": lid}), has_mask); - run(app, ui, tr("Invert mask"), "mask.invert", json!({"layer": lid}), has_mask); - run(app, ui, tr("Clear mask"), "mask.clear", json!({"layer": lid}), has_mask); - run(app, ui, tr("Remove mask"), "mask.remove", json!({"layer": lid}), has_mask); - #[cfg(not(target_arch = "wasm32"))] - if ui.add_enabled(mask_on, egui::Button::new(tr("Export mask to file..."))).clicked() { - export_mask_file(app, layer); - ui.close(); - } - if ui.add_enabled(mask_on, egui::Button::new(tr("Copy mask to clipboard"))).clicked() { - copy_mask(app, ui.ctx(), layer.id); - ui.close(); + if !content_thumbnail { + ui.separator(); + mask_management_menu(app, ui, layer, false); } geometry_mask_menu(app, ui, layer); ui.separator(); @@ -1444,19 +1450,20 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } ui.close(); } - #[cfg(not(target_arch = "wasm32"))] - if ui.add_enabled(has_mask, egui::Button::new(tr("Create smart mask"))).clicked() { - app.run("layer.select", json!({"layer": lid})); - crate::smart_mask_menu::save(app, layer, &crate::library_dir()); - ui.close(); - } ui.separator(); run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true); run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true); let paste_layer = crate::menus::enabled(app, "layer.paste"); - let paste_effect = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); run(app, ui, tr("Paste layer(s)"), "layer.paste", json!({}), paste_layer); - run(app, ui, tr("Paste effect"), "effect.paste", json!({}), paste_effect); + let has_content_stack = app.session.doc.project.content_layer(layer.id).is_some_and(|owner| !owner.is_group()); + let (params, paste_effect) = if content_thumbnail { + let compatible = + app.session.clipboard.as_ref().and_then(|(doc, id)| doc.project.effect(*id)).is_some_and(|(_, effect)| effect.kind.content_only() != Some(false)); + (json!({"layer": lid, "target": "content"}), has_content_stack && compatible) + } else { + (json!({}), texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some()) + }; + run(app, ui, tr("Paste effect"), "effect.paste", params, paste_effect); let paste_instance = crate::menus::enabled(app, "layer.pasteInstance"); run(app, ui, tr("Paste as instance"), "layer.pasteInstance", json!({}), paste_instance); run(app, ui, tr("Duplicate layer(s)"), "layer.duplicate", json!({"layer": lid}), true); @@ -1481,8 +1488,52 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } } }); - ui.separator(); - effect_menu(app, ui, layer); + if !content_thumbnail || has_content_stack { + ui.separator(); + effect_menu(app, ui, layer, content_thumbnail); + } +} + +/// Mask management is available from the row and directly from the mask thumbnail. +fn mask_management_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, mask_thumbnail: bool) { + // An instance inherits its source mask until it has its own. + let project = &app.session.doc.project; + let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()); + let (has_mask, mask_on) = (mask.is_some(), mask.is_some_and(|mask| mask.enabled)); + let lid = layer.id.0; + let target = if mask_thumbnail { "mask" } else { "content" }; + for (label, command) in [ + (tr("Toggle mask"), "mask.toggle"), + (tr("Invert mask background"), "mask.invertBackground"), + (tr("Invert mask"), "mask.invert"), + (tr("Clear mask"), "mask.clear"), + (tr("Remove mask"), "mask.remove"), + ] { + let mut button = egui::Button::new(label).selected(command == "mask.toggle" && mask_on); + if let Some(shortcut) = crate::keymap::shortcut_of(&app.ui.keymap, command) { + button = button.shortcut_text(shortcut); + } + if ui.add_enabled(has_mask, button).clicked() { + app.run("layer.select", json!({"layer": lid, "target": target})); + app.run(command, json!({"layer": lid})); + ui.close(); + } + } + #[cfg(not(target_arch = "wasm32"))] + if ui.add_enabled(has_mask, egui::Button::new(tr("Create smart mask"))).clicked() { + app.run("layer.select", json!({"layer": lid, "target": target})); + crate::smart_mask_menu::save(app, layer, &crate::library_dir()); + ui.close(); + } + #[cfg(not(target_arch = "wasm32"))] + if ui.add_enabled(mask_on, egui::Button::new(tr("Export mask to file..."))).clicked() { + export_mask_file(app, layer); + ui.close(); + } + if ui.add_enabled(mask_on, egui::Button::new(tr("Copy mask to clipboard"))).clicked() { + copy_mask(app, ui.ctx(), layer.id); + ui.close(); + } } // --------------------------------------------------------------------------------------------- diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 0a88c260..7033bb86 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -318,6 +318,60 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { h.run_steps(3); } +#[test] +fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() { + let (mut h, clicked) = harness(); + let selected = { + let session = &mut h.state_mut().session; + let layer = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Another fill"})).unwrap(), "layer")); + execute(session, "mask.add.white", &Value::Null).unwrap(); + layer + }; + h.run_steps(3); + assert_eq!(h.state().session.selected_layer(), Some(selected)); + + let at = thumb(&h, "Masked fill", true); + right_click(&mut h, at); + assert!(h.query_by_label("Flatten layer").is_none()); + h.get_by_label("Toggle mask").click(); + h.run_steps(3); + let project = &h.state().session.doc.project; + assert!(!project.layers[&clicked].mask.as_ref().unwrap().enabled); + assert!(project.layers[&selected].mask.as_ref().unwrap().enabled); + assert_eq!(h.state().session.target, StackTarget::Mask); + + // The same layer's mask is still selected when its material menu opens. + let at = thumb(&h, "Masked fill", false); + right_click(&mut h, at); + assert!(h.query_by_label("Toggle mask").is_none()); + assert!(h.query_by_label("Add generator").is_none()); + h.get_by_label("Add levels").click(); + h.run_steps(3); + let layer = &h.state().session.doc.project.layers[&clicked]; + assert_eq!(layer.content_effects.len(), 2); + assert_eq!(layer.mask.as_ref().unwrap().effects.len(), 1); +} + +#[test] +fn focused_mask_thumbnail_opens_and_dismisses_its_menu_from_the_keyboard() { + let (mut h, _) = harness(); + let thumbnail = "Select the mask (Alt+click: show it in the viewport) (Masked fill)"; + h.get_by_label(thumbnail).focus(); + h.run_steps(3); + assert!(h.get_by_label(thumbnail).is_focused()); + + h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + h.run_steps(3); + assert!(h.query_by_label("Toggle mask").is_some()); + h.key_press(egui::Key::ArrowDown); + h.run_steps(3); + assert!(h.get_by_label("Toggle mask").is_focused()); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.query_by_label("Toggle mask").is_none()); + assert!(h.get_by_label(thumbnail).is_focused()); +} + /// Click the eye of the top-level row `name` with `modifiers` held (the eye sits in the first 20 points after the 7-point edge). fn click_eye(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: egui::Modifiers) { let row = h.get_by_label(name).rect(); From 30d7ee51c4470544bc7aa56a85f68dc7960a8eab Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 23 Nov 2026 03:56:43 -0500 Subject: [PATCH 048/153] Remove redundant tests and fix unused build warnings --- Cargo.lock | 1 - Cargo.toml | 4 - apps/texturecraft-cli/tests/cli.rs | 11 --- apps/texturecraft-web/Cargo.toml | 3 +- apps/texturecraft-web/src/main.rs | 2 +- apps/texturecraft/src/control_server.rs | 39 +++----- apps/texturecraft/src/main.rs | 13 --- crates/automation/src/render.rs | 8 -- crates/automation/tests/perf.rs | 12 --- crates/bake/src/tests.rs | 18 ---- crates/compose/src/pattern.rs | 6 -- crates/compose/src/solo.rs | 5 - crates/compose/src/tile_length.rs | 5 - crates/core/src/project.rs | 11 --- crates/core/tests/bake_settings.rs | 1 - crates/engine/src/commands.rs | 2 +- crates/engine/src/filter_about.rs | 14 --- crates/engine/src/link_cmds.rs | 17 +++- crates/engine/src/link_cmds/link_job.rs | 6 +- crates/engine/src/template_cmds.rs | 6 +- crates/engine/tests/it/filter_card.rs | 7 +- crates/engine/tests/it/filter_light.rs | 10 +- crates/engine/tests/session.rs | 50 +++------- crates/formats/Cargo.toml | 5 +- crates/formats/src/mesh_import/stl.rs | 10 -- crates/formats/src/mesh_import/usd/tests.rs | 60 +----------- crates/render/Cargo.toml | 2 +- crates/render/src/neutral_material.rs | 22 ----- crates/ui-egui/src/docking.rs | 22 ----- crates/ui-egui/src/i18n.rs | 13 --- crates/ui-egui/src/render_mode/tests.rs | 6 -- crates/ui-egui/src/resource_picker_item.rs | 6 -- crates/ui-egui/src/updates_ui.rs | 9 -- crates/ui-egui/src/viewport.rs | 10 -- crates/ui-egui/tests/it/alpha_parameters.rs | 10 -- crates/ui-egui/tests/it/bake_mode.rs | 12 --- .../ui-egui/tests/it/brush_section_reset.rs | 10 -- crates/ui-egui/tests/it/camera_views.rs | 10 -- .../ui-egui/tests/it/display_environment.rs | 16 +--- .../ui-egui/tests/it/display_post_effects.rs | 9 -- crates/ui-egui/tests/it/export_settings.rs | 18 +--- crates/ui-egui/tests/it/filter_light.rs | 13 --- crates/ui-egui/tests/it/filter_simple.rs | 19 ---- crates/ui-egui/tests/it/help_menu_664.rs | 60 +----------- crates/ui-egui/tests/it/levels_editor.rs | 11 --- crates/ui-egui/tests/it/main.rs | 1 - crates/ui-egui/tests/it/mask_export.rs | 10 -- crates/ui-egui/tests/it/named_layouts.rs | 19 +--- crates/ui-egui/tests/it/nav_buttons.rs | 7 -- crates/ui-egui/tests/it/new_project_window.rs | 75 +-------------- crates/ui-egui/tests/it/project_config.rs | 88 +----------------- crates/ui-egui/tests/it/reference_order.rs | 51 ---------- crates/ui-egui/tests/it/settings_window.rs | 35 ------- crates/ui-egui/tests/it/shelf_panel.rs | 22 ----- crates/ui-egui/tests/it/shortcut_gestures.rs | 33 ------- crates/ui-egui/tests/it/shortcut_keys.rs | 9 -- crates/ui-egui/tests/it/shortcut_list.rs | 92 +------------------ crates/ui-egui/tests/it/symmetry.rs | 11 --- crates/ui-egui/tests/it/templates_681.rs | 21 ----- crates/ui-egui/tests/it/view_mode_picker.rs | 65 ------------- xtask/src/version.rs | 6 -- 61 files changed, 75 insertions(+), 1074 deletions(-) delete mode 100644 crates/ui-egui/tests/it/shortcut_gestures.rs diff --git a/Cargo.lock b/Cargo.lock index 34c2e112..84a1a752 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5215,7 +5215,6 @@ dependencies = [ "gltf", "half", "image", - "lz4_flex", "png", "quick-xml 0.41.0", "rayon", diff --git a/Cargo.toml b/Cargo.toml index e4f86a12..de6fc98d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,8 +8,6 @@ default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose version = "0.6.1" edition = "2024" license = "MIT OR Apache-2.0" -rust-version = "1.95" -repository = "https://github.com/storytold/texturecraft" [workspace.dependencies] craft-usd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } @@ -53,10 +51,8 @@ rfd = "0.17" zip = { version = "9", default-features = false, features = ["deflate"] } gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] } flate2 = "1" -lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } quick-xml = "0.41" mikktspace = { version = "0.3", default-features = false, features = ["glam"] } -proptest = "1" rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } schemars = "1" diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index 4cb6a5aa..ce209c3e 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -16,17 +16,6 @@ fn cli_binary_path(runner_path: Option) -> OsString { runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into()) } -#[test] -fn cli_binary_prefers_relocated_runner_path() { - let relocated = OsString::from("relocated archive/texturecraft-cli"); - assert_eq!(cli_binary_path(Some(relocated.clone())), relocated); -} - -#[test] -fn cli_binary_defaults_to_cargo_path() { - assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli"))); -} - fn cli(args: &[&str]) -> Output { Command::new(cli_binary()).args(args).output().unwrap() } diff --git a/apps/texturecraft-web/Cargo.toml b/apps/texturecraft-web/Cargo.toml index e5512768..bb5c79a6 100644 --- a/apps/texturecraft-web/Cargo.toml +++ b/apps/texturecraft-web/Cargo.toml @@ -13,12 +13,11 @@ workspace = true name = "texturecraft-web" path = "src/main.rs" -[dependencies] +[target.'cfg(target_arch = "wasm32")'.dependencies] texturecraft-engine = { workspace = true } texturecraft-ui-egui = { workspace = true } log = { workspace = true } -[target.'cfg(target_arch = "wasm32")'.dependencies] # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] } wasm-bindgen = "0.2" diff --git a/apps/texturecraft-web/src/main.rs b/apps/texturecraft-web/src/main.rs index cd4045c4..742cb5a8 100644 --- a/apps/texturecraft-web/src/main.rs +++ b/apps/texturecraft-web/src/main.rs @@ -1,6 +1,6 @@ //! TextureCraft in the browser. //! -//! Runs the same [`texturecraft_ui_egui::TextureCraftApp`] as the desktop app through eframe's web +//! Runs the same `TextureCraftApp` as the desktop app through eframe's web //! runner (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release` //! from this directory (`packaging/web/package.sh` zips the result). //! diff --git a/apps/texturecraft/src/control_server.rs b/apps/texturecraft/src/control_server.rs index b502fe55..7576083d 100644 --- a/apps/texturecraft/src/control_server.rs +++ b/apps/texturecraft/src/control_server.rs @@ -197,32 +197,21 @@ mod tests { } #[test] - fn connections_are_limited_and_idle_ones_time_out() { + fn authenticated_connections_hold_server_slots() { let addr = server(); - let idle: Vec<_> = (0..MAX_CONNECTIONS).map(|_| connect(addr)).collect(); - // Let the server take every idle connection before the one over the limit. - std::thread::sleep(Duration::from_millis(300)); - // Read without writing: the server closes at once, and unread input would reset the - // connection before its reply arrives. - let (_, mut r) = connect(addr); - let mut full = String::new(); - r.read_line(&mut full).unwrap(); - assert_eq!(serde_json::from_str::(&full).unwrap()["error"], "too many connections"); - // Unauthenticated connections are closed after AUTH_TIMEOUT, which frees their slots. - for (_, mut r) in idle { - let mut rest = String::new(); - assert_eq!(r.read_line(&mut rest).unwrap(), 0); - } - // A slot frees once its thread has ended, which can trail the client's EOF a little. let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); - let authed = (0..50).any(|_| { - let (mut w, mut r) = connect(addr); - let ok = call(&mut w, &mut r, &right).is_some_and(|v| v["ok"] == true); - if !ok { - std::thread::sleep(Duration::from_millis(100)); - } - ok - }); - assert!(authed, "slots are freed after the auth deadline"); + let _held: Vec<_> = (0..MAX_CONNECTIONS) + .map(|_| { + let (mut w, mut r) = connect(addr); + // The reply confirms that this connection is holding a slot. + assert_eq!(call(&mut w, &mut r, &right).unwrap()["ok"], true); + (w, r) + }) + .collect(); + + let (_, mut r) = connect(addr); + let mut reply = String::new(); + r.read_line(&mut reply).unwrap(); + assert_eq!(serde_json::from_str::(&reply).unwrap()["error"], "too many connections"); } } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 0ebfaa86..7787e1cf 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -330,19 +330,6 @@ mod tests { assert_eq!(args.gpu.as_deref(), Some("3080")); } - #[test] - fn only_a_run_without_a_control_port_checks_for_updates_at_start() { - assert!(checks_for_updates_at_start(None)); - assert!(!checks_for_updates_at_start(Some(9000))); - } - - #[test] - fn bundled_app_icon_decodes_to_rgba() { - let icon = icon().unwrap(); - assert!(icon.width > 0 && icon.height > 0); - assert_eq!(icon.rgba.len(), (icon.width * icon.height * 4) as usize); - } - #[test] fn rejects_missing_or_invalid_gpu_args() { assert!(parse_args_from(["--gpu".to_string()]).is_err()); diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index d626849e..c12ce621 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -228,14 +228,6 @@ mod tests { out } - #[test] - fn the_unlit_switch_decides_whether_a_channel_view_is_lit() { - let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); - assert!(!shade(&s).solo_lit, "channel views are flat by default"); - execute(&mut s, "display.set", &json!({"soloUnlit": false})).unwrap(); - assert!(shade(&s).solo_lit); - } - #[test] fn renders_with_an_imported_hdr_environment() { let mesh = texturecraft_engine::geom::primitives::material_ball(); diff --git a/crates/automation/tests/perf.rs b/crates/automation/tests/perf.rs index 8b49f36f..ef73dc98 100644 --- a/crates/automation/tests/perf.rs +++ b/crates/automation/tests/perf.rs @@ -141,18 +141,6 @@ fn sample_for_project_bake(resolution: u32) -> Headless { backend } -#[test] -fn project_bake_uses_documented_ray_count() { - let backend = sample_for_project_bake(256); - - for texture_set in 0..backend.session.set_count() { - let task = backend.session.bake_task(texture_set).unwrap(); - assert_eq!(task.settings.maps.ao.parameters.rays.rays, 32); - assert_eq!(task.settings.maps.thickness.parameters.rays.rays, 32); - assert_eq!(task.settings.maps.bent_normal.parameters.rays.rays, 32); - } -} - /// The whole-project bake at benchmark settings (1024², 32 rays, AA 1), then 2048². #[test] #[ignore] diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index dab94f80..eaa64cf2 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -1056,24 +1056,6 @@ fn occlusion_falls_off_linearly_to_the_max_distance() { assert!((ambient_occlusion - 0.5).abs() < 0.01, "{ambient_occlusion}"); } -#[test] -fn secondary_ray_defaults_preserve_per_map_distances() { - let parameters = BakeSettings::default(); - let expected_rays = RaySettings { - rays: 64, - min_distance: 0.00001, - max_distance: 1.0, - relative_to_bounding_box: true, - spread: 180.0, - distribution: RayDistribution::Cosine, - }; - - assert_eq!(parameters.maps.ao.parameters.rays, expected_rays); - assert_eq!(parameters.maps.ao.parameters.attenuation, texturecraft_core::AmbientOcclusionAttenuation::Linear); - assert_eq!(parameters.maps.bent_normal.parameters.rays, expected_rays); - assert_eq!(parameters.maps.thickness.parameters.rays, RaySettings { max_distance: 0.1, ..expected_rays }); -} - #[test] fn bent_normals_and_thickness_have_their_own_rays() { let m = floor_and_wall(false); diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index 4e134daf..d75805dc 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -780,12 +780,6 @@ mod tests { assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); } - /// A stored cylinder axis past Z (only a hand-edited project holds one) wraps round Y - #[test] - fn a_cylinder_axis_past_z_reads_as_y() { - assert_eq!([0, 1, 2, 3, u8::MAX].map(cylinder_axis_index), [0, 1, 2, 1, 1]); - } - /// A decal saved before image placement reads its frame coordinates bit for bit as it did: its image at them, its procedural at them times the pattern scale #[test] fn an_unplaced_decal_reads_its_frame_coordinates_bit_for_bit() { diff --git a/crates/compose/src/solo.rs b/crates/compose/src/solo.rs index 11427c3a..64d6b9f7 100644 --- a/crates/compose/src/solo.rs +++ b/crates/compose/src/solo.rs @@ -173,9 +173,4 @@ mod tests { assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible); } - - #[test] - fn a_layer_in_no_stack_gives_nothing() { - assert!(solo_project(&project(), LayerId(99), true).is_none()); - } } diff --git a/crates/compose/src/tile_length.rs b/crates/compose/src/tile_length.rs index d84b08ee..04926df0 100644 --- a/crates/compose/src/tile_length.rs +++ b/crates/compose/src/tile_length.rs @@ -147,9 +147,4 @@ mod tests { assert!(length[0] > 0.0, "{length:?}"); assert!(tiling_for_length(&flat, SIZE, length).unwrap()[0] > 0.0, "a written-back tiling is never 0"); } - - #[test] - fn spherical_has_no_physical_size() { - assert_eq!(tile_length(&Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default() }, SIZE), None); - } } diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index c836f0ba..649f4f6d 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -829,17 +829,6 @@ mod tests { assert_eq!(p.next_layer_name(0, "Layer"), "Layer 2"); } - #[test] - fn serde_round_trip_is_stable() { - let mut p = project(); - let l = paint(&mut p, "x"); - p.insert_layer(0, l, None, false).unwrap(); - let json = serde_json::to_string(&p).unwrap(); - let back: Project = serde_json::from_str(&json).unwrap(); - assert_eq!(back, p); - assert_eq!(serde_json::to_string(&back).unwrap(), json); - } - #[test] fn per_map_bake_settings_round_trip() { use crate::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 800efd98..1616604f 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -118,7 +118,6 @@ fn components_keep_their_own_defaults() { })) .unwrap(); assert_eq!(settings, bake::BakeSettings::default()); - assert_eq!(settings.maps.thickness.parameters.rays.max_distance, 0.1); } #[test] diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index b8da2ca6..e34e9327 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -448,7 +448,7 @@ mod tests { fn no_bindable_command_asks_for_a_parameter() { // Effect commands need a selected effect, which this session lacks for spec in command_specs().iter().filter(|c| c.bindable() && c.shortcut.is_none() && !c.id.starts_with("effect.")) { - let mut session = crate::sample_session(256, 64).unwrap(); + let mut session = crate::sample_session(texturecraft_core::MIN_RESOLUTION, 16).unwrap(); if (spec.enabled)(&session).is_ok() && let Err(err) = execute(&mut session, spec.id, &Value::Null) { diff --git a/crates/engine/src/filter_about.rs b/crates/engine/src/filter_about.rs index c7d7375b..f0255e1b 100644 --- a/crates/engine/src/filter_about.rs +++ b/crates/engine/src/filter_about.rs @@ -69,17 +69,3 @@ const ABOUT: &[(&str, FilterAbout)] = &[ pub fn of(id: &str) -> Option { ABOUT.iter().find(|(entry, _)| *entry == id).map(|(_, about)| *about) } - -#[cfg(test)] -mod tests { - use super::of; - use crate::filter_lib::FILTERS; - - #[test] - fn every_library_filter_is_described_and_tagged() { - for def in FILTERS { - let about = of(def.id).unwrap_or_else(|| panic!("{} has no description", def.id)); - assert!(about.description.ends_with('.') && !about.tags.is_empty(), "{}", def.id); - } - } -} diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index f080daf8..a20182f6 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -359,7 +359,7 @@ pub fn source_extension(name: &str) -> &'static str { fn cook_source( bytes: Vec, size: u32, - baked: Option, + #[cfg(not(target_arch = "wasm32"))] baked: Option, mut budget: LinkMemoryBudget, canceled: Arc, reservation: CookReservation, @@ -384,7 +384,9 @@ fn cook_source( size, values: Map::new(), input_identifiers: Vec::new(), + #[cfg(not(target_arch = "wasm32"))] baked, + #[cfg(not(target_arch = "wasm32"))] budget, canceled, }; @@ -439,7 +441,15 @@ impl Session { let mut source = Vec::new(); source.try_reserve_exact(bytes.len()).map_err(|error| EngineError::Other(format!("cannot allocate linked source: {error}")))?; source.extend_from_slice(bytes); - let (job, material) = cook_source(source, size, self.doc.baked.get(&ts).cloned(), budget, Arc::default(), reservation)?; + let (job, material) = cook_source( + source, + size, + #[cfg(not(target_arch = "wasm32"))] + self.doc.baked.get(&ts).cloned(), + budget, + Arc::default(), + reservation, + )?; self.add_cooked_material(&material, job.package, job.source_ext, place) } @@ -542,6 +552,7 @@ impl Session { /// Prepare a re-cook with current parameter values and matching baked mesh maps pub fn link_job(&self, id: LayerId, overrides: &Map) -> Result { let link = link_of(self, "material.link", id)?; + #[cfg(not(target_arch = "wasm32"))] let (texture_set, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("layer {} is not in a stack", id.0)))?; let mut values = self.link_values(id)?; values.extend(overrides.clone()); @@ -554,7 +565,9 @@ impl Session { size: self.link_size(id)?, values, input_identifiers: link.inputs.clone(), + #[cfg(not(target_arch = "wasm32"))] baked: self.doc.baked.get(&texture_set).cloned(), + #[cfg(not(target_arch = "wasm32"))] budget: self.link_memory_budget(), canceled: Arc::default(), }) diff --git a/crates/engine/src/link_cmds/link_job.rs b/crates/engine/src/link_cmds/link_job.rs index dba31f78..145be0e3 100644 --- a/crates/engine/src/link_cmds/link_job.rs +++ b/crates/engine/src/link_cmds/link_job.rs @@ -1,12 +1,12 @@ use std::sync::{Arc, atomic::AtomicBool}; -use super::{CookReservation, CookedMaterial, EngineError, LinkMemoryBudget, Result}; +use super::{CookReservation, CookedMaterial, EngineError, Result}; use serde_json::{Map, Value}; use texturecraft_core::LayerId; #[cfg(not(target_arch = "wasm32"))] use { - super::{CookedMap, MaterialInterface, cook_report::CookReport, materialcraft_tool, quiet}, + super::{CookedMap, LinkMemoryBudget, MaterialInterface, cook_report::CookReport, materialcraft_tool, quiet}, std::{io::Read, path::Path}, texturecraft_core::{BakedMap, Channel}, }; @@ -27,7 +27,9 @@ pub struct LinkJob { pub values: Map, /// Graph inputs matched to mesh maps and encoded one at a time in the worker. pub input_identifiers: Vec, + #[cfg(not(target_arch = "wasm32"))] pub(super) baked: Option, + #[cfg(not(target_arch = "wasm32"))] pub(super) budget: LinkMemoryBudget, pub canceled: Arc, } diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index 27de192d..db283d7e 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -533,11 +533,7 @@ mod tests { } #[test] - fn the_list_names_templates_like_the_reference() { - assert_eq!(template_label(DEFAULT_TEMPLATE, true), "Default (OpenPBR)"); - assert_eq!(template_label("Unlit - Emissive", true), "Unlit - Emissive (starter_assets)"); - assert_eq!(template_label("Mine", false), "Mine (your_assets)"); - + fn a_listed_template_resolves_by_its_display_label() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); execute(&mut s, "project.template.save", &json!({"name": "Mine"})).unwrap(); let labels: Vec = diff --git a/crates/engine/tests/it/filter_card.rs b/crates/engine/tests/it/filter_card.rs index 4009ece3..4c2a29ce 100644 --- a/crates/engine/tests/it/filter_card.rs +++ b/crates/engine/tests/it/filter_card.rs @@ -145,11 +145,10 @@ fn restore_defaults_puts_the_filters_parameters_back() { fn filter_list_describes_and_tags_every_filter() { let mut s = session(); let listed = execute(&mut s, "filter.list", &Value::Null).unwrap(); - for def in listed.as_array().unwrap() { + let entries = listed.as_array().unwrap(); + assert_eq!(entries.len(), texturecraft_engine::filter_lib::FILTERS.len()); + for def in entries { assert!(def["description"].as_str().is_some_and(|text| !text.is_empty()), "{def}"); assert!(def["tags"].as_array().is_some_and(|tags| !tags.is_empty()), "{def}"); } - let blur = listed.as_array().unwrap().iter().find(|def| def["id"] == "blur").unwrap(); - - assert_eq!(blur["tags"], json!(["blur", "soften"])); } diff --git a/crates/engine/tests/it/filter_light.rs b/crates/engine/tests/it/filter_light.rs index 770d57e3..1e91c781 100644 --- a/crates/engine/tests/it/filter_light.rs +++ b/crates/engine/tests/it/filter_light.rs @@ -2,7 +2,7 @@ use serde_json::json; use texturecraft_engine::core::{Channel, DirectionalLight, EffectKind, Filter, LayerId, LightingOutput}; -use texturecraft_engine::filter_lib::{LIBRARY_DROP_SHADOW, LIBRARY_ENVIRONMENT_LIGHTING, LIBRARY_GLOW, library_baked_lighting}; +use texturecraft_engine::filter_lib::{LIBRARY_ENVIRONMENT_LIGHTING, LIBRARY_GLOW, library_baked_lighting}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; @@ -54,22 +54,16 @@ fn glow_settings_set_clamp_and_refuse() { assert_eq!(filter_of(&s, effect), LIBRARY_GLOW); } -/// Drop Shadow: the workflow's defaults, then Angle wrapping, Distance both ways, Size, Spread, Opacity and Color #[test] -fn drop_shadow_defaults_and_settings() { +fn drop_shadow_clamps_settings_and_rejects_invalid_color() { let mut s = session(); let effect = masked(&mut s, "Drop Shadow"); - assert_eq!(filter_of(&s, effect), LIBRARY_DROP_SHADOW, "the workflow's defaults"); set(&mut s, effect, json!({"angle": 450.0, "distance": -0.9, "size": 2.0, "spread": 0.3, "opacity": 0.25, "color": "#ffffff"})); assert_eq!(filter_of(&s, effect), Filter::DropShadow { angle: 90.0, distance: -0.5, size: 1.0, spread: 0.3, opacity: 0.25, color: [1.0; 3] }); refused(&mut s, effect, &[json!({"color": [1.0]})]); - - let listed = execute(&mut s, "filter.list", &json!({})).unwrap(); - - assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "dropShadow" && f["mask"] == true)); } /// A content fill layer with library filter `id` on its content: the effect diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 52427422..dd4972cf 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1,11 +1,15 @@ use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{Channel, MIN_RESOLUTION}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, command_specs, execute}; fn session() -> Session { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + session_at(256) +} + +fn session_at(texture_size: u32) -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, texture_size).unwrap(); s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); s.camera.yaw = 0.0; s.camera.pitch = 0.0; @@ -229,20 +233,8 @@ fn polygon_fill_boxes_survive_hostile_params() { } } -/// A small project still gets the production bake defaults; only panic_hunt overrides them. -#[test] -fn new_project_keeps_full_resolution_bake_defaults() { - let s = session(); - assert!(!s.doc.project.texture_sets.is_empty()); - for texture_set in &s.doc.project.texture_sets { - assert_eq!(texture_set.resolution, 256); - assert_eq!(texture_set.bake, texturecraft_engine::core::BakeSettings::default()); - assert_eq!(texture_set.bake.common.output_size(), (2048, 2048)); - assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 64); - } -} - /// Every command must return Ok or Err — never panic — for hostile params. +/// Small texture and bake sizes retain the same command and parameter cases without a full-size bake per case. #[test] fn panic_hunt() { let hostile = [ @@ -259,11 +251,9 @@ fn panic_hunt() { } for p in &hostile { - let mut s = session(); - - // Match the fixture resolution to avoid a full 2048px bake for each unrelated input + let mut s = session_at(MIN_RESOLUTION); for texture_set in &mut s.doc.project.texture_sets { - texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256; + texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R64; } let _ = execute(&mut s, spec.id, p); s.update(); @@ -433,7 +423,7 @@ fn hunt_filters(hostile: &[Value]) { let extremes: Vec = [3.0e38, -3.0e38, 0.0].into_iter().map(filter_extreme).collect(); for def in texturecraft_engine::filter_lib::FILTERS { - let mut s = session(); + let mut s = session_at(MIN_RESOLUTION); execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap(); for target in ["content", "mask"] { if target == "mask" { @@ -471,7 +461,7 @@ fn hunt_filters(hostile: &[Value]) { /// An empty filter effect on the content and on a mask swapped through `effect.set` to every library filter with each of `hostile` and `extremes`, and rendered fn hunt_filter_swaps(hostile: &[Value], extremes: &[Value]) { - let mut s = session(); + let mut s = session_at(MIN_RESOLUTION); execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap(); for target in ["content", "mask"] { if target == "mask" { @@ -495,24 +485,8 @@ fn hunt_filter_swaps(hostile: &[Value], extremes: &[Value]) { } } -/// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ -/// between the two, so every command that takes a colour says which form is which. #[test] -fn colour_params_name_their_colour_space() { - for spec in command_specs() { - if ["color?", "colors?", "Color?"].iter().any(|k| spec.params.contains(k)) { - assert!(spec.params.contains("linear"), "{}: {}", spec.id, spec.params); - let hex = spec.params.matches("\"#rrggbb\"").count(); - assert_eq!(hex, spec.params.matches("\"#rrggbb\" sRGB").count(), "{}: {}", spec.id, spec.params); - } - } - // These read their colours through `color_param`, which takes both forms. - for id in - ["layer.add.fill", "layer.fill.set", "effect.add.fill", "effect.add.filter", "tool.material", "mask.add.colorSelection", "resource.text", "display.set"] - { - let spec = command_specs().iter().find(|c| c.id == id).unwrap(); - assert!(spec.params.contains("[r,g,b] linear or \"#rrggbb\" sRGB"), "{id}: {}", spec.params); - } +fn an_srgb_hex_colour_matches_its_linear_rgb_value() { let base_color = |color: Value| { let mut s = session(); execute(&mut s, "layer.add.fill", &json!({ "color": color })).unwrap(); diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 486db142..fbc4138a 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -27,9 +27,7 @@ png = "0.18" bytemuck = { workspace = true, features = ["extern_crate_alloc"] } craft-image-codecs = { workspace = true } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b130ac1fa44f923c3024884ab8ceb5ccdb88f15f" } -gltf = { workspace = true } flate2 = { workspace = true } -lz4_flex = { workspace = true } half = { workspace = true } quick-xml = { workspace = true } zip = { workspace = true } @@ -42,3 +40,6 @@ base64 = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] sysinfo = { workspace = true } + +[dev-dependencies] +gltf = { workspace = true } diff --git a/crates/formats/src/mesh_import/stl.rs b/crates/formats/src/mesh_import/stl.rs index 95eeee6b..7e8e06e9 100644 --- a/crates/formats/src/mesh_import/stl.rs +++ b/crates/formats/src/mesh_import/stl.rs @@ -64,13 +64,3 @@ pub(crate) fn read(bytes: &[u8]) -> Result { fn stl_limits() -> craft_mesh::Limits { craft_mesh::Limits { max_vertices: MAX_VERTICES, ..craft_mesh::Limits::default() } } - -#[cfg(test)] -mod tests { - #[test] - fn shared_reader_accepts_the_app_vertex_limit() { - let limits = super::stl_limits(); - assert_eq!(limits.max_vertices, super::MAX_VERTICES); - assert_eq!(limits.max_triangles, texturecraft_geom::MAX_TRIANGLES); - } -} diff --git a/crates/formats/src/mesh_import/usd/tests.rs b/crates/formats/src/mesh_import/usd/tests.rs index f4a84c23..9eef4537 100644 --- a/crates/formats/src/mesh_import/usd/tests.rs +++ b/crates/formats/src/mesh_import/usd/tests.rs @@ -2,9 +2,7 @@ use std::io::Read as _; -use craft_usd::scene::{ - Budget, MAX_DECODED_BYTES, Prop, SceneError, UsdAttr, UsdLayer, UsdPrim, UsdValue, Val, read_layer, read_layer_with_budget, write_usda, write_usdc, -}; +use craft_usd::scene::{Budget, Prop, SceneError, UsdAttr, UsdLayer, UsdPrim, UsdValue, Val, read_layer, read_layer_with_budget, write_usda, write_usdc}; use texturecraft_geom::Mesh; use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; @@ -406,55 +404,6 @@ fn usd_extension_detects_the_encoding() { assert!(import_mesh_bytes("a.usdz", &binary).is_err()); } -#[test] -fn integer_coding_round_trips() { - let values: Vec = vec![0, 1, 2, 3, 3, 3, -5, 1000, -70000, i64::from(i32::MAX), i64::from(i32::MIN), 7, 7, 7, 8]; - for (w_enum, width) in [(craft_usd::integers::Width::I32, 4), (craft_usd::integers::Width::I64, 8)] { - let enc = craft_usd::integers::encode(&values, w_enum, MAX_DECODED_BYTES).unwrap(); - assert!(enc.len() <= craft_usd::codec::encoded_ints_len(values.len(), width)); - assert_eq!(craft_usd::integers::decode(&enc, values.len(), w_enum, MAX_DECODED_BYTES).unwrap(), values); - assert!(craft_usd::integers::decode(&enc[..enc.len() - 1], values.len(), w_enum, MAX_DECODED_BYTES).is_err()); - } - let wide = vec![i64::MAX, i64::MIN, 0, 1 << 40]; - let enc_wide = craft_usd::integers::encode(&wide, craft_usd::integers::Width::I64, MAX_DECODED_BYTES).unwrap(); - assert_eq!(craft_usd::integers::decode(&enc_wide, 4, craft_usd::integers::Width::I64, MAX_DECODED_BYTES).unwrap(), wide); - let big: Vec = (0..5000u32).flat_map(|i| (i % 7).to_le_bytes()).collect(); - let comp = craft_usd::compress::compress(&big, MAX_DECODED_BYTES).unwrap(); - assert_eq!(craft_usd::decompress(&comp, big.len()).unwrap(), big); - assert!(craft_usd::decompress(&[0, 0xF0], 10).is_err()); -} - -#[test] -fn shared_crate_lz4_writer_preserves_bytes() { - for len in [0, 1, 15, 16, 255, 4096] { - let data: Vec = (0..len).map(|i| (i % 251) as u8).collect(); - let mut previous = vec![0]; - previous.extend(lz4_flex::block::compress(&data)); - assert_eq!(craft_usd::compress::compress(&data, MAX_DECODED_BYTES).unwrap(), previous); - } -} - -#[test] -fn shared_integer_decoder_rejects_oversized_output() { - assert!(craft_usd::integers::decode(&[], MAX_DECODED_BYTES / 8 + 1, craft_usd::integers::Width::I64, MAX_DECODED_BYTES).is_err()); - assert!(craft_usd::integers::decode(&[], 0, craft_usd::integers::Width::I32, MAX_DECODED_BYTES).unwrap().is_empty()); -} - -#[test] -fn shared_crate_lz4_retains_chunk_and_budget_policy() { - let mut frame = vec![2]; - for raw in [b"abc".as_slice(), b"def".as_slice()] { - let block = lz4_flex::block::compress(raw); - frame.extend((block.len() as i32).to_le_bytes()); - frame.extend(block); - } - frame.extend(b"old reader ignores this tail"); - assert_eq!(craft_usd::decompress(&frame, 6).unwrap(), b"abcdef"); - assert!(craft_usd::decompress(&frame, 5).is_err()); - assert!(craft_usd::decompress(&[1, 255, 255, 255, 255], 64).is_err()); - assert!(craft_usd::decompress(&[128], 64).is_err()); -} - #[test] fn malformed_usd_never_panics() { // A small two-material mesh keeps the byte loops fast. @@ -513,13 +462,6 @@ fn loose_layer_textures_are_packaged() { } } -#[test] -fn shared_integer_writer_preserves_tie_wire_and_rejects_oversized_budget() { - assert_eq!(craft_usd::integers::encode(&[1, 3, 4, 6], craft_usd::integers::Width::I32, MAX_DECODED_BYTES).unwrap(), vec![2, 0, 0, 0, 17, 1, 1]); - assert!(craft_usd::integers::encode(&[1], craft_usd::integers::Width::I32, 16).is_err()); - assert!(craft_usd::integers::encode(&[], craft_usd::integers::Width::I64, 0).unwrap().is_empty()); -} - /// Keep the final mesh contract of the binary fixture used before the shared USD cutover. #[test] fn crafted_usdc_references_time_samples_and_inlined_values_reach_mesh() { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index ee15b556..c9f0692f 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -13,7 +13,6 @@ texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } texturecraft-compose = { workspace = true } -texturecraft-bake = { workspace = true } wgpu = { workspace = true } bytemuck = { workspace = true } half = { workspace = true } @@ -22,6 +21,7 @@ rayon = { workspace = true } serde = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +texturecraft-bake = { workspace = true } pollster = "0.4" # The browser's WebGPU resolves error scopes later: their results are awaited on the page. diff --git a/crates/render/src/neutral_material.rs b/crates/render/src/neutral_material.rs index d3331185..57c372c5 100644 --- a/crates/render/src/neutral_material.rs +++ b/crates/render/src/neutral_material.rs @@ -51,25 +51,3 @@ impl NeutralMaterial { if self.bent_normal { [self.bent_normal_diffuse, self.bent_normal_specular, 0.0, 0.0] } else { [0.0; 4] } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_frame_takes_the_whole_quality() { - let quality = |samples_per_pixel| NeutralMaterial { samples_per_pixel, ..NeutralMaterial::default() }; - assert_eq!(quality(16).samples_per_frame(), 16); - assert_eq!(quality(256).samples_per_frame(), 256); - assert_eq!(quality(u32::MAX).samples_per_frame(), MAX_SAMPLES_PER_PIXEL, "a damaged file is held to the highest quality"); - assert_eq!(quality(0).samples_per_frame(), 1); - } - - #[test] - fn the_bent_normal_reaches_the_shader_only_when_on() { - let off = NeutralMaterial::default(); - assert_eq!(off.bent_normal_globals(), [0.0; 4]); - let on = NeutralMaterial { bent_normal: true, bent_normal_diffuse: 0.5, bent_normal_specular: 0.25, ..off }; - assert_eq!(on.bent_normal_globals(), [0.5, 0.25, 0.0, 0.0]); - } -} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 05eb9ae9..ff8aa145 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -702,20 +702,6 @@ mod tests { assert_eq!(panels_of(&workspace), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]); } - #[test] - fn the_default_right_column_gives_properties_about_two_thirds_under_the_texture_sets() { - let workspace = default_workspace(); - let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_ref() else { panic!("assets | rest") }; - let Node::Split { second: column, .. } = right.as_ref() else { panic!("viewport | right column") }; - let Node::Split { second: below_sets, .. } = column.as_ref() else { panic!("texture sets | rest") }; - let Node::Split { size: SplitSize::Ratio(layers), first, second, .. } = below_sets.as_ref() else { panic!("layers | properties") }; - assert!(matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.first() == Some(&Panel::Layers))); - assert!(matches!(second.as_ref(), Node::Tabs { panels, .. } if panels == &[Panel::Properties])); - - let properties = 1.0 - layers; - assert!((2.0 / 3.0..0.7).contains(&properties), "Properties takes about 69% of the column, at least two thirds: {properties}"); - } - #[test] fn a_saved_split_keeps_its_own_share() { let mut workspace = default_workspace(); @@ -729,14 +715,6 @@ mod tests { assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged"); } - #[test] - fn default_dock_round_trips() { - let dock = Dock::default(); - let json = serde_json::to_string(&dock).unwrap(); - let back: Dock = serde_json::from_str(&json).unwrap(); - assert_eq!(back, dock); - } - #[test] fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { let dock = Dock::for_baking(); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index d1d19dc1..02198a5a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -421,19 +421,6 @@ mod tests", set_language("en"); } - #[test] - fn shared_lookup_overrides_and_missing_translations() { - static CATALOGS: &craft_i18n::Embedded = &[("es", "\tSave\tGuardar\n\tOpen\tAbrir\n", "\tSave\tGuardar proyecto\n")]; - let (runtime, problems) = craft_i18n::I18n::new(CATALOGS, &["es"]); - assert!(problems.is_empty()); - assert!(runtime.check_all().is_empty()); - let lang = runtime.from_code("es").unwrap(); - assert_eq!(runtime.t(lang, "Save"), "Guardar proyecto"); - assert_eq!(runtime.t(lang, "Open"), "Abrir"); - assert_eq!(runtime.t(lang, "New feature"), "New feature"); - assert_eq!(runtime.t(craft_i18n::Lang::EN, "Save"), "Save"); - } - #[test] fn saved_language_codes_and_spanish_lookup() { let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index b51c9760..114bef4c 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -359,9 +359,3 @@ fn loading_textures_are_taken_in_at_a_limited_rate() { assert!(take_in_textures(true, 1.0 + LOADING_RESTART_S, 1.0)); assert!(take_in_textures(true, 0.0, f64::MIN), "the first frame always"); } - -/// The placeholder appears only before the first image has been traced. -#[test] -fn nothing_traced_yet_shows_the_placeholder() { - assert!(!show_image(false, 0)); -} diff --git a/crates/ui-egui/src/resource_picker_item.rs b/crates/ui-egui/src/resource_picker_item.rs index 4c029ecd..4d02d20c 100644 --- a/crates/ui-egui/src/resource_picker_item.rs +++ b/crates/ui-egui/src/resource_picker_item.rs @@ -63,12 +63,6 @@ mod tests { assert!(!item("Rust").matches("dust")); } - #[test] - fn an_empty_search_keeps_every_item() { - assert!(item("Rust").matches("")); - assert!(item("").matches("")); - } - #[test] fn a_search_lowercases_a_label_beyond_ascii() { assert!(item("ÜBERZUG Grün").matches("überzug")); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index da935fbe..809a20fd 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -142,15 +142,6 @@ mod tests { h.run_steps(2); } - #[test] - fn default_runtime_is_idle() { - let rt = Runtime::default(); - assert!(!rt.startup_check); - assert!(!rt.check_requested); - assert!(!rt.updater.prompt_open()); - assert_eq!(rt.updater.status(), &Status::Idle); - } - #[test] fn the_menu_item_runs_a_check_that_reports_its_outcome() { let _language = language(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 96d8b6a4..3c5a3d7e 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2536,16 +2536,6 @@ mod tests { assert!((u - egui::vec2(0.0, -1.0)).length() < 1e-4 && (v - egui::vec2(-1.0, 0.0)).length() < 1e-4, "a counter-clockwise quarter turn: U up, V left"); } - #[test] - fn one_switch_turns_the_wireframe_on_in_both_views_and_polygon_fill_shows_it_without_changing_the_switch() { - let mut ui = crate::state::UiState::default(); - assert!(!wireframe_shown(&ui, false), "off by default"); - assert!(wireframe_shown(&ui, true), "polygon fill shows the polygons it fills"); - assert!(!ui.mesh_wireframe); - ui.mesh_wireframe = true; - assert!(wireframe_shown(&ui, false)); - } - #[test] fn the_hover_label_names_the_set_and_the_tile_under_the_cursor() { assert_eq!(hover_label_text("UdimMat", true, true, Some(1001)).as_deref(), Some("UdimMat - 1001")); diff --git a/crates/ui-egui/tests/it/alpha_parameters.rs b/crates/ui-egui/tests/it/alpha_parameters.rs index 3a261eed..09e48082 100644 --- a/crates/ui-egui/tests/it/alpha_parameters.rs +++ b/crates/ui-egui/tests/it/alpha_parameters.rs @@ -50,16 +50,6 @@ fn show_group(harness: &mut Harness<'_, TextureCraftApp>) { harness.run_steps(SETTLE_FRAMES); } -#[test] -fn the_group_shows_hardness_and_every_shared_parameter() { - let harness = app_with_brush(BrushSettings::default()); - - for label in ["Parameters", "Hardness", "Size X", "Size Y", "Roundness", "Contrast"] { - assert!(harness.query_by_label(label).is_some(), "{label} is in the Alpha tab"); - } - assert!(invert_checkbox(&harness).is_some()); -} - #[test] fn restore_defaults_puts_back_hardness_and_the_parameters_but_keeps_the_alpha() { let brush = BrushSettings { hardness: 0.9, alpha: BrushAlpha::Star, alpha_params: changed_params(), size: 0.1, flow: 0.4, ..BrushSettings::default() }; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 787f8645..b2603842 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -559,18 +559,6 @@ fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() { harness.get_by_value("Material"); } -#[test] -fn the_baking_visualization_panel_opens_like_the_reference_at_first_launch() { - let harness = harness(None); - for shown in ["Show for Selected Texture Set Only", "Mesh", "Matching Error", "Cage Surface", "Cage Wireframe Opacity"] { - harness.get_by_label(shown); - } - for closed in ["Missing Seams on Hard Edges", "Project Mesh", "Roughness"] { - assert!(harness.query_by_label(closed).is_none(), "{closed} sits in a section that starts closed"); - } - assert!(harness.state().ui.bake_visualization.missing_seams.shown, "missing seams are ticked in every reference capture"); -} - #[test] fn texture_set_names_show_in_full_beside_their_resolution() { let mut harness = harness(None); diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index c01726ad..8504adc1 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -177,16 +177,6 @@ fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { } } -#[test] -fn reset_icons_identify_their_sections() { - let harness = app_with_brush(changed_brush()); - - for (title, _, _, _) in SECTIONS { - let label = format!("{title}: Reset to defaults"); - assert!(harness.query_by_role_and_label(egui::Role::Button, &label).is_some(), "the reset button must name its {title} section"); - } -} - #[test] fn narrow_headers_keep_title_clicks_separate_from_reset() { use texturecraft_ui_egui::widgets::section_with_reset; diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs index 83e05d2c..b4ef8539 100644 --- a/crates/ui-egui/tests/it/camera_views.rs +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -354,13 +354,3 @@ fn next_camera_advances_from_the_destination_before_the_glide_ends() { assert!((harness.state().session.camera.yaw.to_degrees() - 50.0).abs() < 0.5, "two presses reach the second camera"); } - -#[test] -fn the_view_picker_offers_the_combined_normal_view() { - let mut h = harness(); - h.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("Material")).expect("the view picker").click(); - h.run_steps(2); - h.get_by_label("Normal+height+mesh").click(); - h.run_steps(2); - assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::NormalHeightMesh); -} diff --git a/crates/ui-egui/tests/it/display_environment.rs b/crates/ui-egui/tests/it/display_environment.rs index 5635d651..66cfff9f 100644 --- a/crates/ui-egui/tests/it/display_environment.rs +++ b/crates/ui-egui/tests/it/display_environment.rs @@ -45,13 +45,8 @@ fn values(h: &Harness<'_, TextureCraftApp>) -> Vec { } #[test] -fn the_sliders_run_over_the_reference_ranges_and_defaults() { +fn the_sliders_clamp_drags_to_their_supported_ranges() { let mut h = app(); - let shown = values(&h); - for expected in ["0", "0.00", "35", "0"] { - assert!(shown.iter().any(|value| value == expected), "{expected} is shown: {shown:?}"); - } - assert_eq!(display(&h).env_blur, 0.35, "the blur default is 35 of 100"); drag(&mut h, "Environment Opacity", 3000.0); assert_eq!(display(&h).env_opacity, 1.0, "opacity ends at 100"); @@ -140,15 +135,6 @@ fn the_environment_section_is_greyed_while_a_mesh_map_shows() { assert!(!h.get_by_role_and_label(Role::Button, "Studio Soft").accesskit_node().is_disabled()); } -#[test] -fn the_tabs_end_with_render_and_visualization_settings() { - let h = app(); - for label in ["Environment settings", "Camera settings", "Post effects", "Render settings", "Visualization settings"] { - assert!(h.query_all_by_label(label).next().is_some(), "the tab {label}"); - } - assert!(h.query_all_by_label("Viewer settings").next().is_none(), "the fourth tab is no longer Viewer settings"); -} - #[test] fn settings_general_has_a_working_background_color_with_two_eyedroppers() { let mut h = app(); diff --git a/crates/ui-egui/tests/it/display_post_effects.rs b/crates/ui-egui/tests/it/display_post_effects.rs index 96a355fa..df35a767 100644 --- a/crates/ui-egui/tests/it/display_post_effects.rs +++ b/crates/ui-egui/tests/it/display_post_effects.rs @@ -74,15 +74,6 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, label: &str, x: f32) { harness.run_steps(SETTLE_FRAMES); } -#[test] -fn the_defaults_are_off() { - let harness = app(); - let d = display(&harness); - assert!(!d.post_effects); - assert_eq!(amounts(&d), [0.0; 4]); - assert!(reset_icon(&harness).accesskit_node().is_disabled(), "nothing to reset yet"); -} - #[test] fn each_slider_sets_only_its_own_amount() { for (i, label) in SLIDERS.into_iter().enumerate() { diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 0e7e158a..98af3660 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -108,9 +108,8 @@ fn the_lists_hold_the_reference_entries() { } #[test] -fn the_default_template_has_the_reference_name_and_old_settings_follow_it() { +fn a_saved_legacy_preset_name_resolves_to_its_current_name() { let mut h = harness(); - assert_eq!(h.state().ui.export.preset, "Document channels + Normal + AO (No Alpha)"); h.state_mut().ui.export.preset = "Document channels + Normal + AO".into(); h.run_steps(3); assert_eq!(h.state().ui.export.preset, "Document channels + Normal + AO (No Alpha)"); @@ -159,21 +158,6 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { assert!(h.query_by_label("Dilation (pixels)").is_some(), "the menu stays open"); } -#[test] -fn export_actions_explain_what_they_change() { - let mut h = harness(); - for (button, tip) in [ - ("Include all", "Select every texture set, UV tile and output map"), - ("Reset all", "Restore the export defaults and select every texture"), - ("Cancel", "Restore the settings from when you opened this window"), - ("Save settings", "Keep these settings for the next export"), - ("Export", "Write the selected textures using the settings above"), - ] { - hover(&mut h, button); - assert!(h.query_by_label(tip).is_some(), "{button}: {tip}"); - } -} - #[test] fn the_page_reset_puts_the_parameters_back() { let mut h = harness(); diff --git a/crates/ui-egui/tests/it/filter_light.rs b/crates/ui-egui/tests/it/filter_light.rs index 40e8190c..700b118e 100644 --- a/crates/ui-egui/tests/it/filter_light.rs +++ b/crates/ui-egui/tests/it/filter_light.rs @@ -61,19 +61,6 @@ fn drop_shadow_angle_drag_is_one_undo_step() { assert!(matches!(filter_of(&harness, effect), Filter::DropShadow { angle, .. } if angle == 90.0), "{:?}", filter_of(&harness, effect)); } -/// The Sun card's angles read Sun Horizontal Angle and Sun Vertical Angle; Light 1 and 2 keep Horizontal Angle and Vertical Angle -#[test] -fn baked_lighting_stylized_sun_angles_take_the_sun_names() { - let (harness, _) = app_with("bakedLighting", "content", TALL_WINDOW_HEIGHT); - - for label in ["Sun Horizontal Angle", "Sun Vertical Angle"] { - assert_eq!(harness.query_all_by_role_and_label(Role::Slider, label).count(), 1, "{label}"); - } - for label in ["Horizontal Angle", "Vertical Angle"] { - assert_eq!(harness.query_all_by_role_and_label(Role::Slider, label).count(), 2, "{label}: Light 1 and 2"); - } -} - /// Baked Lighting Stylized's cards edit their own settings: Sun Intensity's right end, Light 1's Intensity and Output's Specular only #[test] fn baked_lighting_stylized_cards_set_the_sun_a_light_and_the_output() { diff --git a/crates/ui-egui/tests/it/filter_simple.rs b/crates/ui-egui/tests/it/filter_simple.rs index 9157f62d..a5c68c1f 100644 --- a/crates/ui-egui/tests/it/filter_simple.rs +++ b/crates/ui-egui/tests/it/filter_simple.rs @@ -67,17 +67,6 @@ fn posterize_switch_under_its_slider() { assert_eq!(filter_of(&harness, effect), Filter::Posterize { levels: 8.0, alpha: true }); } -/// Clamp's Min and Max, Smoothstep's Minimum and Maximum and Sharpen Intensity -#[test] -fn reference_names_on_the_sliders() { - for (filter, labels) in [("clamp", &["Min", "Max"][..]), ("smoothstep", &["Minimum", "Maximum"]), ("sharpen", &["Sharpen Intensity"])] { - let (harness, _) = app_with(filter, "mask", WINDOW_HEIGHT); - for label in labels { - assert!(harness.query_by_role_and_label(Role::Slider, label).is_some(), "{filter}: {label}"); - } - } -} - /// Histogram Shift's Position: a click on its middle shifts by a half turn back #[test] fn histogram_shift_position_middle_is_a_half_turn_back() { @@ -178,14 +167,6 @@ fn fxaa_rows() { assert_eq!(filter_of(&harness, effect), Filter::Fxaa { alpha: true }); } -/// Blur's Blur Intensity takes the reference's name and starts at 0.30 -#[test] -fn blur_intensity_takes_the_reference_name() { - let (harness, _) = app_with("blur", "mask", WINDOW_HEIGHT); - let intensity = harness.get_by_role_and_label(Role::Slider, "Blur Intensity"); - assert_eq!(intensity.accesskit_node().numeric_value().map(|value| (value * 100.0).round()), Some(30.0)); -} - /// Blur Directional's Intensity and Angle take the reference's names, and Intensity's right end is the widest blur #[test] fn blur_directional_rows_take_the_reference_names() { diff --git a/crates/ui-egui/tests/it/help_menu_664.rs b/crates/ui-egui/tests/it/help_menu_664.rs index 96f5ea43..db39c6a8 100644 --- a/crates/ui-egui/tests/it/help_menu_664.rs +++ b/crates/ui-egui/tests/it/help_menu_664.rs @@ -1,5 +1,4 @@ -//! Help ▸ Release notes... opens the releases page; Help ▸ Export log... saves the log to a text file; -//! Help ▸ Join the community (Discord)... opens the community Discord. +//! Help > Export log... saves the log with each entry's time and level. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -25,55 +24,6 @@ fn click_help_item(h: &mut Harness<'_, TextureCraftApp>, label: &str) { h.run_steps(4); } -#[test] -fn release_notes_opens_the_releases_page() { - for id in ["ui.help.releaseNotes", "ui.help.exportLog"] { - assert!(texturecraft_ui_egui::keymap::bindings().iter().any(|binding| binding.id == id)); - } - - let mut h = harness(); - h.get_by_label("Help").click(); - h.run_steps(3); - h.get_by_label("Release notes...").click(); - - // The open-url command is in the output of the frame that handled the click only - h.step(); - let opened = h - .output() - .platform_output - .commands - .iter() - .any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url == "https://github.com/storytold/texturecraft/releases")); - assert!(opened, "the releases page was opened"); -} - -const DISCORD: &str = "https://discord.gg/artcraft"; - -fn opened(h: &Harness<'_, TextureCraftApp>, url: &str) -> bool { - h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url == url)) -} - -#[test] -fn join_the_community_opens_the_discord() { - let mut h = harness(); - h.get_by_label("Help").click(); - h.run_steps(3); - h.get_by_label("Join the community (Discord)...").click(); - h.step(); - assert!(opened(&h, DISCORD), "the community Discord was opened"); -} - -#[test] -fn join_the_community_is_bindable_and_a_bound_key_opens_the_discord() { - assert!(texturecraft_ui_egui::keymap::bindings().iter().any(|b| b.id == "ui.help.discord"), "ui.help.discord can be bound"); - let mut h = harness(); - h.state_mut().ui.keymap.insert("ui.help.discord".into(), "F12".into()); - h.run_steps(2); - h.event(egui::Event::Key { key: egui::Key::F12, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); - h.step(); - assert!(opened(&h, DISCORD), "the bound key opened the community Discord"); -} - #[test] fn export_log_writes_every_line_with_time_and_level() { let mut h = harness(); @@ -97,11 +47,3 @@ fn export_log_writes_every_line_with_time_and_level() { assert_eq!(lines.len(), logged.len() + 1); let _ = std::fs::remove_dir_all(&dir); } - -#[test] -fn a_canceled_export_log_dialog_writes_nothing() { - let mut h = harness(); - h.state_mut().file_dialogs.set_override(Some(Box::new(|_| Answer::Cancelled))); - click_help_item(&mut h, "Export log..."); - assert!(h.state().toasts.is_empty()); -} diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs index d962f022..0a1656a3 100644 --- a/crates/ui-egui/tests/it/levels_editor.rs +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -283,17 +283,6 @@ fn a_typed_value_keeps_input_low_below_input_high() { assert!((levels(&harness, effect).in_low - 0.49).abs() < 1e-4, "{:?}", levels(&harness, effect)); } -#[test] -fn the_levels_filter_shows_the_same_editor() { - let (harness, _) = levels_harness("effect.add.filter", json!({"target": "mask", "filter": "levels"})); - for label in ["Input low", "Gamma", "Input high", "Output low", "Output high"] { - harness.get_by_role_and_label(Role::Slider, label); - } - for button in ["Reset", "Auto", "Invert"] { - harness.get_by_role_and_label(Role::Button, button); - } -} - /// Bounds of the handle pointers in paint order, the last one drawn on top fn painted_handles(harness: &Harness<'_, TextureCraftApp>) -> Vec { let centres = HANDLE_LABELS.map(|label| handle(harness, label)); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 9196bd46..ef91cc44 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -80,7 +80,6 @@ mod shelf_hover_preview; mod shelf_panel; mod shift_lines_2d; mod shift_lines_3d; -mod shortcut_gestures; mod shortcut_keys; mod shortcut_list; mod side_panels; diff --git a/crates/ui-egui/tests/it/mask_export.rs b/crates/ui-egui/tests/it/mask_export.rs index 808c4055..c58fd4ff 100644 --- a/crates/ui-egui/tests/it/mask_export.rs +++ b/crates/ui-egui/tests/it/mask_export.rs @@ -68,16 +68,6 @@ fn export_mask_to_file_writes_the_mask_where_the_dialog_answered() { let _ = std::fs::remove_dir_all(file.parent().unwrap()); } -#[test] -fn a_canceled_dialog_writes_nothing() { - let mut h = harness(true); - h.state_mut().file_dialogs.set_override(Some(Box::new(|_| Answer::Cancelled))); - open_menu(&mut h); - h.get_by_label("Export mask to file...").click(); - h.run_steps(4); - assert!(h.state().toasts.is_empty()); -} - #[test] fn copy_mask_to_clipboard_puts_the_gray_image_on_the_clipboard() { let mut h = harness(true); diff --git a/crates/ui-egui/tests/it/named_layouts.rs b/crates/ui-egui/tests/it/named_layouts.rs index 18264949..8aa12225 100644 --- a/crates/ui-egui/tests/it/named_layouts.rs +++ b/crates/ui-egui/tests/it/named_layouts.rs @@ -110,23 +110,14 @@ fn invoke(harness: &mut Harness<'_, TextureCraftApp>, params: serde_json::Value) } #[test] -fn the_layout_items_are_in_the_menu_catalog_and_open_their_dialogs() { - use texturecraft_ui_egui::menus::CATALOG; - use texturecraft_ui_egui::named_layouts::LayoutDialog; - - for id in ["ui.layout.saveAs", "ui.layout.manage"] { - assert!(CATALOG.iter().any(|item| item.id == id && item.menu == "Window" && item.sub == Some("Layouts")), "{id}"); - } +fn managing_layouts_requires_a_saved_layout() { let mut harness = app(); - assert!(!texturecraft_ui_egui::menus::enabled(harness.state(), "ui.layout.manage"), "nothing to manage yet"); - - assert_eq!(invoke(&mut harness, serde_json::json!({"id": "ui.layout.saveAs"}))["ok"], true); - assert!(matches!(harness.state().ui.layout_dialog, Some(LayoutDialog::Save(_)))); + let command = "ui.layout.manage"; + assert!(!texturecraft_ui_egui::menus::enabled(harness.state(), command)); harness.state_mut().ui.save_named_layout("A"); - harness.state_mut().ui.layout_dialog = None; - assert_eq!(invoke(&mut harness, serde_json::json!({"id": "ui.layout.manage"}))["ok"], true); - assert!(matches!(harness.state().ui.layout_dialog, Some(LayoutDialog::Manage { .. }))); + + assert!(texturecraft_ui_egui::menus::enabled(harness.state(), command)); } #[test] diff --git a/crates/ui-egui/tests/it/nav_buttons.rs b/crates/ui-egui/tests/it/nav_buttons.rs index 9138d0e9..b21569e0 100644 --- a/crates/ui-egui/tests/it/nav_buttons.rs +++ b/crates/ui-egui/tests/it/nav_buttons.rs @@ -184,13 +184,6 @@ fn a_press_in_the_gap_between_buttons_or_in_the_margin_paints_nothing() { } } -#[test] -fn the_2d_view_has_no_orbit_button() { - let view = Rect::from_min_size(Pos2::ZERO, vec2(600.0, 500.0)); - assert!(button_rect(view, NavView::Uv, NavButton::Orbit).is_none()); - assert!(button_rect(view, NavView::Scene, NavButton::Orbit).is_some()); -} - #[test] fn buttons_stay_clear_of_the_pickers_the_gizmo_and_the_split_divider_at_1280_by_800() { let (harness, _) = app(ViewLayout::Split); diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index 7d95b501..1f97f815 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -1,9 +1,6 @@ -//! File > New project: the sections and their order, the defaults, settings shown disabled with a -//! hint until TextureCraft has them, Create waiting for a mesh file, and the settings that reach -//! the `file.new` command. +//! New project creation, including mesh selection, disabled controls and settings passed to file.new. use egui::Role; -use egui::accesskit::Toggled; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::template_cmds::DEFAULT_TEMPLATE; @@ -89,81 +86,15 @@ fn create_keeps_the_mesh_buffer_for_retry_and_drops_it_after_success() { assert_eq!(h.state().session.doc.project.name, "retry"); } -fn top(h: &Harness<'_, TextureCraftApp>, label: &str) -> f32 { - h.get_all_by_label(label).map(|node| node.rect().top()).fold(f32::INFINITY, f32::min) -} - fn disabled(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { h.get_by_role_and_label(role, label).accesskit_node().is_disabled() } -fn ticked(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { - h.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(Toggled::True) -} - #[test] -fn the_sections_follow_the_project_setup_order() { - let h = harness(); - let order = [ - "BASIC SETTINGS", - "3D mesh", - "Project template", - "Document resolution (px)", - "ADVANCED SETTINGS", - "Normal map format", - "Compute tangent space per fragment", - "UV Tile settings (UDIMs)", - "You can enable or disable UV tiles later in Texture Set Settings.", - "Use UV Tile workflow", - "Keep UV tiles together per material", - "Use a separate texture set for each tile", - "Import settings", - "Import cameras", - "Auto-unwrap", - "Import baked maps", - "Import mesh normal maps and baked maps for all materials.", - "Normal map filename: _normal", - "Physical size", - "Use the mesh file’s unit scale", - "Custom unit scale", - "Scale material fills in real-world units", - "Color management", - "Working color space", - ]; - let tops: Vec = order.iter().map(|label| top(&h, label)).collect(); - for (pair, labels) in tops.windows(2).zip(order.windows(2)) { - assert!(pair[0] < pair[1], "{} comes before {}: {pair:?}", labels[0], labels[1]); - } - assert!(h.query_by_label("Linear - sRGB Chrominance (ITU-R BT.709)").is_some()); -} - -#[test] -fn the_defaults_match_the_reference() { +fn the_uv_layout_control_is_disabled_when_uv_tiles_are_off() { let h = harness(); - assert!(h.query_by_label("No file selected").is_some()); - assert!(h.query_by_value("Default (OpenPBR)").is_some(), "the default template"); - assert!(h.query_by_value("1024 x 1024").is_some()); - assert!(h.query_by_value("OpenGL").is_some()); - assert!(h.query_by_value("Legacy").is_some()); - assert!(!ticked(&h, Role::CheckBox, "Compute tangent space per fragment")); - assert!(!ticked(&h, Role::CheckBox, "Use UV Tile workflow")); - assert!(ticked(&h, Role::RadioButton, "Keep UV tiles together per material")); - assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material"), "greyed while UV tiles are off"); - assert!(ticked(&h, Role::CheckBox, "Import cameras") && !disabled(&h, Role::CheckBox, "Import cameras")); - assert!(ticked(&h, Role::CheckBox, "Auto-unwrap")); - assert!(ticked(&h, Role::RadioButton, "Use the mesh file’s unit scale")); - assert!(!ticked(&h, Role::CheckBox, "Scale material fills in real-world units")); -} - -#[test] -fn template_controls_name_and_built_in_meshes_are_gone() { - let h = harness(); - - for label in ["Template name", "Save current project as template", "Name", "UV tiles (UDIM)"] { - assert!(h.query_by_label(label).is_none(), "{label} is not in the window"); - } - assert!(h.query_by_label_contains("Built-in:").is_none(), "no built-in mesh dropdown"); + assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material")); } #[test] diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 6bfb2a84..91dec76d 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -17,10 +17,6 @@ const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 const FORMAT_HINT: &str = "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export"; const TITLE: &str = "Project configuration"; -/// The window sits at the middle of the 1600-point-wide screen and is 560 points wide -const WINDOW_MIDDLE_X: f32 = 800.0; -const WINDOW_HALF_WIDTH: f32 = 280.0; - fn temp_dir(test: &str) -> TempDir { TempDir::new(test) } @@ -86,21 +82,6 @@ fn own_tick(h: &Harness<'_, TextureCraftApp>) -> bool { h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.reimport) } -#[test] -fn the_menu_opens_the_window() { - let dir = temp_dir("menu"); - let mut h = app_on_a_quad(&dir); - - assert!(!window_is_open(&h)); - - open_window(&mut h); - - assert!(window_is_open(&h)); - assert!(h.query_by_label("3D MESH").is_some(), "the 3D mesh section"); - assert!(!reimport_ticked(&h), "nothing is ticked at first"); - assert!(h.state().ui.rail_panel.is_none(), "the Display panel stays where it was"); -} - #[test] fn many_texture_sets_keep_dialog_actions_reachable_in_a_short_viewport() { let dir = temp_dir("many-tiles"); @@ -130,69 +111,12 @@ fn many_texture_sets_keep_dialog_actions_reachable_in_a_short_viewport() { } #[test] -fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() { - let dir = temp_dir("info"); - let mut h = app_on_a_quad(&dir); - - open_window(&mut h); - - let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect(); - let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."; - - assert!(h.query_by_label("Changing the mesh or normal format can recalculate texture channels.").is_some(), "the note above the buttons"); - assert_eq!( - icons.len(), - 13, - "3D mesh, Reimport mesh, Normal map format, tangent space, UV tiles and its two layouts, Import cameras, Preserve strokes, Auto-unwrap, \ - Physical size, Color management, Working color space" - ); - assert!(h.query_by_label(tip).is_none(), "no tooltip before hovering"); - - // The format icon is third in the window's rows - let mut centers: Vec<_> = icons.iter().map(|n| n.rect().center()).collect(); - centers.sort_by(|a, b| a.y.total_cmp(&b.y)); - let format_center = centers[2]; - h.hover_at(format_center); - h.run_steps(30); - - assert!(h.query_by_label(tip).is_some(), "hovering the normal map format icon explains it"); -} - -#[test] -fn the_window_follows_the_reference_layout() { - let dir = temp_dir("layout"); +fn unsupported_project_settings_are_disabled() { + let dir = temp_dir("unsupported-settings"); let mut h = app_on_a_quad(&dir); h.set_size(egui::vec2(1600.0, 2000.0)); - open_window(&mut h); - let order = [ - "3D MESH", - "Reimport mesh", - "PROJECT SETTINGS", - "Compute tangent space per fragment", - "UV Tile settings (UDIMs)", - "Change the UV tiles of a texture set in Texture Set Settings", - "Use UV Tile workflow", - "Use a separate texture set for each tile", - "Import settings", - "Import cameras", - "Preserve stroke positions on mesh", - "Auto-unwrap", - "Physical size", - "Working color space", - ]; - - // Only the window's own rows: a dock panel may show the same text (the fill's Scale switch offers Physical size) - let in_window = |node: &egui_kittest::Node<'_>| (node.rect().center().x - WINDOW_MIDDLE_X).abs() <= WINDOW_HALF_WIDTH; - let top = |label: &str| h.get_all_by_label(label).filter(in_window).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min); - for labels in order.windows(2) { - assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]); - } - - assert!(h.query_by_label("Custom unit scale").is_none(), "Physical size starts collapsed"); - - let disabled = |role: Role, label: &str| h.get_by_role_and_label(role, label).accesskit_node().is_disabled(); for (role, label) in [ (Role::CheckBox, "Compute tangent space per fragment"), (Role::CheckBox, "Use UV Tile workflow"), @@ -202,14 +126,8 @@ fn the_window_follows_the_reference_layout() { (Role::CheckBox, "Auto-unwrap"), (Role::Button, "Auto-unwrap options"), ] { - assert!(disabled(role, label), "{label} is disabled"); + assert!(h.get_by_role_and_label(role, label).accesskit_node().is_disabled(), "{label}"); } - - let center = h.get_by_role_and_label(Role::CheckBox, "Compute tangent space per fragment").rect().center(); - h.hover_at(center); - h.run_steps(30); - - assert!(h.query_by_label("Not available yet").is_some(), "the hint of a setting TextureCraft does not have yet"); } #[test] diff --git a/crates/ui-egui/tests/it/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs index f3943aee..dc191571 100644 --- a/crates/ui-egui/tests/it/reference_order.rs +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -31,57 +31,6 @@ fn named<'a>(found: &'a [(f32, String, bool)], name: &str) -> Option<&'a (f32, S found.iter().find(|(_, label, _)| label == name || label.starts_with(&format!("{name} ("))) } -#[test] -fn every_menu_lists_its_items_in_the_reference_order() { - // Items the reference has and TextureCraft lacks are absent; TextureCraft's own sit where they fit - let expected = [ - "File: New project... | Open... | - | Open sample project... | - | Close | - | Save | Save as... | More save options > Save as template... | More save options > Save and reduce file size | More save options > Save as copy... | Remove unused resources... | - | Import resources... | Import MaterialX material... | Import PBR texture folder... | Import material... | Export Textures... | Export Mesh... | - | Quit", - "Edit: Undo | Redo | Project Configuration... | Reimport mesh | Settings...", - "Mode: Bake Mesh Maps | Painting | Rendering (path traced)", - "Window: Views > Assets | Views > Common Settings | Views > Display Settings | Views > Export | Views > History | Views > Layers | Views > Log | Views > Mesh Map Bakers | Views > Mesh Map Settings | Views > Properties | Views > Python Console | Views > Renderer Settings | Views > Shader Settings | Views > Online assets | Views > Texture Sets | Views > Texture Set Settings | Toolbars > Docks | Toolbars > Plugins | Toolbars > Tools | - | Save UI Layout > Painting mode | Save UI Layout > Rendering mode | Save UI Layout > Baking mode | Load UI Layout | Layouts > Save current layout as... | Layouts > Manage layouts... | - | Hide UI | Reset panel layout | Reset UI", - "Viewport: Display material | Display next channel | Display previous channel | Display next mesh map | Display previous mesh map | UV checker | - | Frame texture set | Show entire mesh | Front view | Back view | Left view | Right view | Top view | Bottom view | - | Perspective | Orthographic | - | 3D/2D views | 3D view only | 2D view only | Swap 3D/2D | - | Navigation buttons | - | Enable quick mask | Edit quick mask | Invert quick mask", - "Help: Release notes... | Documentation... | Shortcuts list... | - | Join the community (Discord)... | ArtCraft website... | Report a bug... | Show log... | Export log... | - | Check for Updates... | About TextureCraft...", - ]; - let actual: Vec = menus::TOP - .iter() - .map(|top| { - let items: Vec = menus::CATALOG - .iter() - .filter(|item| item.menu == *top) - .map(|item| match item.sub { - Some(sub) => format!("{sub} > {}", item.label), - None => item.label.to_string(), - }) - .collect(); - format!("{top}: {}", items.join(" | ")) - }) - .collect(); - for (expected, actual) in expected.iter().zip(&actual) { - assert_eq!(expected, actual); - } - assert_eq!(menus::TOP, ["File", "Edit", "Mode", "Window", "Viewport", "Help"], "the reference's top menus, minus the scripting ones"); -} - -#[test] -fn the_tool_shelf_keeps_the_reference_order() { - let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); - let shelf = buttons_in(&harness, 0.0..60.0); - let order = ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Material picker", "Geometry mask"]; - let row_positions: Vec = order.iter().map(|name| named(&shelf, name).unwrap_or_else(|| panic!("{name} on the shelf: {shelf:?}")).0).collect(); - - assert!(row_positions.windows(2).all(|pair| pair[0] < pair[1]), "{row_positions:?}"); -} - -#[test] -fn the_right_bar_keeps_the_reference_order() { - let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); - let bar = buttons_in(&harness, 1562.0..1600.0); - let order = ["Export", "Log", "Display Settings", "Shader Settings", "History"]; - let row_positions: Vec = order.iter().map(|name| named(&bar, name).unwrap_or_else(|| panic!("{name} on the bar: {bar:?}")).0).collect(); - - assert!(row_positions.windows(2).all(|pair| pair[0] < pair[1]), "{row_positions:?}"); -} - #[test] fn the_blank_screen_enables_what_the_reference_enables() { let harness = harness(Session::closed().unwrap()); diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index 477283c9..028a265f 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -11,23 +11,6 @@ use texturecraft_ui_egui::{TextureCraftApp, menus}; use crate::memory_storage::MemoryStorage; -/// The section captions of the General page, top to bottom. -const SECTIONS: [&str; 13] = [ - "INTERFACE OPTIONS", - "LAYER STACK OPTIONS", - "CAMERA OPTIONS", - "BAKING OPTIONS", - "PREVIEW OPTIONS", - "TEMPORARY FILES", - "SPARSE VIRTUAL TEXTURE", - "IRAY HARDWARE", - "APPEARANCE", - "VIEWPORT", - "RESOURCES", - "AUTOSAVE", - "FOLDERS", -]; - fn harness(session: Session) -> Harness<'static, TextureCraftApp> { let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); @@ -97,24 +80,6 @@ fn the_left_column_switches_between_the_three_pages() { assert_eq!(page(&h), Some(SettingsPage::General)); } -#[test] -fn the_general_page_lists_the_reference_sections_in_order_without_privacy() { - let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); - open_settings(&mut h); - - // Rows below the scrolled view are laid out too, in page order - let mut shown: Vec = h - .query_all(egui_kittest::kittest::by().predicate(|node| node.label().or_else(|| node.value()).is_some_and(|text| SECTIONS.contains(&text.as_str())))) - .filter_map(|node| node.accesskit_node().label().or_else(|| node.accesskit_node().value())) - .collect(); - - // A label on screen also has a node for its text run - shown.dedup(); - assert_eq!(shown, SECTIONS.map(String::from).to_vec()); - assert!(h.query_by_label("PRIVACY").is_none(), "no Privacy section"); - assert!(h.query_by_label("Automatically send usage statistics").is_none()); -} - #[test] fn the_general_page_starts_at_the_reference_defaults() { let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index d8b7a30c..cbfdf687 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -3,7 +3,6 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::brush_preset_cmds::UserBrush; -use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::core::project::ENVIRONMENTS; use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -19,7 +18,6 @@ const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0); const MATERIALS_TYPE: usize = 0; const SMART_MASKS_TYPE: usize = 2; const BRUSHES_TYPE: usize = 4; -const TEXTURES_TYPE: usize = 6; const ENVIRONMENTS_TYPE: usize = 7; /// How far the saved brush's spacing differs from the current brush's, so loading it shows const SAVED_SPACING_CHANGE: f32 = 0.25; @@ -329,26 +327,6 @@ fn saved_smart_materials_keep_their_type_pickable_in_your_assets() { assert!(button(&harness, "Materials").accesskit_node().is_disabled(), "no plain material is"); } -#[test] -fn saved_smart_materials_are_read_whatever_the_type_and_after_a_refresh() { - let mut harness = shelf(REFERENCE_WINDOW); - assert!(harness.state().library.is_some(), "read on the Materials type"); - - button(&harness, "Refresh").click(); - harness.run_steps(2); - - assert!(harness.state().library.is_some(), "read again after a refresh"); -} - -#[test] -fn procedurals_are_in_the_textures_type() { - let mut harness = shelf(REFERENCE_WINDOW); - harness.state_mut().ui.shelf_tab = TEXTURES_TYPE; - harness.run_steps(3); - - assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some()); -} - /// The reference's type dropdown, top to bottom const TYPE_DROPDOWN: [&str; 10] = ["Materials", "Smart materials", "Smart masks", "Filters", "Brushes", "Alphas", "Textures", "Environments", "Fonts", "Show all"]; diff --git a/crates/ui-egui/tests/it/shortcut_gestures.rs b/crates/ui-egui/tests/it/shortcut_gestures.rs deleted file mode 100644 index fdcddf9f..00000000 --- a/crates/ui-egui/tests/it/shortcut_gestures.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! The shortcut window's fixed list names the mouse gestures and hold keys of the painting tools. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable as _; - -#[test] -fn the_gesture_grid_of_the_shortcut_window_lists_the_stencil_clone_line_and_path_gestures() { - let mut h = Harness::builder() - .with_size(egui::vec2(700.0, 900.0)) - .with_context_setup(texturecraft_ui_egui::theme::install) - .build_ui(texturecraft_ui_egui::keymap::fixed_gestures_grid); - h.run_steps(3); - for text in [ - "Shift + LMB", - "Paint a straight line from where the last stroke ended", - "S + LMB drag", - "Projection: rotate the stencil", - "S + RMB drag", - "S + MMB drag", - "V + LMB", - "Clone: pick the point to copy from", - "Path: add a point; on the curve it inserts one", - "Path: close it (needs 3 points)", - "Path: apply it with the brush", - "Path: remove the selected or last point", - "Path: cancel it", - "Shift + RMB drag", - "Alt + Shift + LMB drag", - "Camera snap rotate", - ] { - assert!(h.query_by_label(text).is_some(), "the overview lacks {text}"); - } -} diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs index 3d10749b..927edd86 100644 --- a/crates/ui-egui/tests/it/shortcut_keys.rs +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -113,12 +113,3 @@ fn a_command_without_a_default_key_runs_from_the_key_it_is_bound_to() { h.run_steps(2); assert_eq!(h.state().session.doc.project.layers.len(), before + 1, "F7 added a fill layer"); } - -#[test] -fn the_shortcut_editor_lists_a_command_without_a_key_and_hides_one_that_needs_a_parameter() { - let mut h = harness(); - h.state_mut().ui.windows.shortcuts = true; - h.run_steps(4); - assert!(h.query_by_label("Toggle layer visibility").is_some(), "Toggle layer visibility is listed"); - assert!(h.query_by_label("Select texture set").is_none(), "Select texture set needs a texture set"); -} diff --git a/crates/ui-egui/tests/it/shortcut_list.rs b/crates/ui-egui/tests/it/shortcut_list.rs index f99db223..c603cbde 100644 --- a/crates/ui-egui/tests/it/shortcut_list.rs +++ b/crates/ui-egui/tests/it/shortcut_list.rs @@ -4,8 +4,7 @@ use egui::{Event, Key, Modifiers, Role}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; -use texturecraft_ui_egui::keymap::{self, NOT_AVAILABLE_ACTIONS, bindings, shortcut_of}; -use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::keymap::{NOT_AVAILABLE_ACTIONS, bindings}; use texturecraft_ui_egui::{TextureCraftApp, menus}; fn harness() -> Harness<'static, TextureCraftApp> { @@ -21,46 +20,6 @@ fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key, modifiers: Modifiers) { h.run_steps(3); } -#[test] -fn the_list_starts_with_the_reference_names_and_keys_in_the_reference_order() { - let expected = [ - ("Hide UI", "Tab"), - ("Undo", "Ctrl+Z"), - ("Redo", "Ctrl+Y"), - ("Open project", "Ctrl+O"), - ("Close project", "Ctrl+F4"), - ("Save project", "Ctrl+S"), - ("Save as project", "Ctrl+Shift+S"), - ("New project", "Ctrl+N"), - ("Quit application", "Ctrl+Q"), - ("Export Textures...", "Ctrl+Shift+E"), - ("Reimport mesh", "Ctrl+Shift+R"), - ("Switch to baking mode", "Ctrl+Shift+B"), - ("Switch to edition mode", "F9"), - ("Switch to rendering mode (path traced)", "F10"), - ("Show mesh wireframe", ""), - ("Camera projection: Perspective view", "F5"), - ("Camera projection: Orthographic view", "F6"), - ("Display next channel", "C"), - ("Display previous channel", "Shift+C"), - ("Display material", "M"), - ("Display next mesh map", "B"), - ("Display previous mesh map", "Shift+B"), - ("Show entire mesh/path", "F"), - ("Select next camera", ">"), - ("Select previous camera", "<"), - ("Enable quick mask", "Y"), - ("Edit quick mask", "U"), - ("Invert quick mask", "Ctrl+Shift+I"), - ("Viewers layout: 3D/2D", "F1"), - ("Viewers layout: 3D only", "F2"), - ("Viewers layout: 2D only", "F3"), - ("Viewers layout: Swap 3D/2D", "F4"), - ]; - let actual: Vec<(&str, &str)> = bindings().iter().take(expected.len()).map(|b| (b.label, keymap::shown(b.default.unwrap_or("")))).collect(); - assert_eq!(actual, expected); -} - #[test] fn no_two_default_shortcuts_are_the_same() { let mut seen = std::collections::BTreeMap::new(); @@ -76,29 +35,13 @@ fn no_two_default_shortcuts_are_the_same() { } #[test] -fn the_menus_keep_their_texts_and_quit_keeps_ctrl_q() { - let label = |id: &str| menus::CATALOG.iter().find(|item| item.id == id).map(|item| item.label); - assert_eq!(label("file.open"), Some("Open...")); - assert_eq!(label("file.saveAs"), Some("Save as...")); - assert_eq!(label("ui.quit"), Some("Quit")); - assert_eq!(label("ui.mode.bake"), Some("Bake Mesh Maps")); - assert_eq!(label("viewport.frame"), Some("Show entire mesh")); - assert_eq!(shortcut_of(&keymap::Keymap::new(), "ui.quit"), Some("Ctrl+Q")); - assert_eq!(shortcut_of(&keymap::Keymap::new(), "ui.mode.bake"), Some("Ctrl+Shift+B")); -} - -#[test] -fn the_settings_page_lists_the_reference_names_and_shows_the_missing_functions_disabled() { +fn the_settings_page_disables_editing_shortcuts_for_unavailable_actions() { let mut h = harness(); let ctx = h.ctx.clone(); menus::invoke(h.state_mut(), &ctx, "ui.settings"); h.run_steps(4); h.get_by_role_and_label(Role::Tab, "Shortcuts").click(); h.run_steps(4); - for name in ["Open project", "Save as project", "Quit application", "Switch to baking mode", "Show entire mesh/path", "Viewers layout: Swap 3D/2D"] { - assert!(h.query_by_label(name).is_some(), "{name} is listed"); - } - assert!(h.query_by_label("Open...").is_none(), "the menu's text is not the list's"); for (_, row) in &NOT_AVAILABLE_ACTIONS { let action = row.label; h.get_by_label(action).scroll_to_me(); @@ -107,27 +50,6 @@ fn the_settings_page_lists_the_reference_names_and_shows_the_missing_functions_d } } -#[test] -fn the_listed_keys_run_their_commands() { - let mut h = harness(); - press(&mut h, Key::B, Modifiers::COMMAND | Modifiers::SHIFT); - assert_eq!(h.state().ui.mode, Mode::Baking, "Ctrl+Shift+B switches to baking mode"); - press(&mut h, Key::F9, Modifiers::NONE); - assert_eq!(h.state().ui.mode, Mode::Painting, "F9 switches to edition mode"); - press(&mut h, Key::F10, Modifiers::NONE); - assert_eq!(h.state().ui.mode, Mode::Rendering); - press(&mut h, Key::F9, Modifiers::NONE); - - // Show mesh wireframe has no key until one is given - assert!(!h.state().ui.mesh_wireframe); - h.state_mut().ui.keymap.insert("ui.wireframe".into(), "F7".into()); - h.run_steps(2); - press(&mut h, Key::F7, Modifiers::NONE); - assert!(h.state().ui.mesh_wireframe, "the wireframe is shown"); - press(&mut h, Key::F7, Modifiers::NONE); - assert!(!h.state().ui.mesh_wireframe, "and hidden again"); -} - #[test] fn greater_and_less_select_the_next_and_previous_camera() { let mut h = harness(); @@ -161,13 +83,3 @@ fn a_key_listed_for_a_missing_function_is_reported_as_shared() { assert!(h.query_by_label_contains("One or several errors").is_some(), "Space is Toggle animation's"); assert!(h.get_by_label("OK").accesskit_node().is_disabled()); } - -#[test] -fn the_shortcut_window_shows_the_reference_keys_and_the_missing_functions() { - let mut h = harness(); - h.state_mut().ui.windows.shortcuts = true; - h.run_steps(4); - assert!(h.query_by_label("Pause Engine Computation").is_some() && h.query_by_label("Toggle animation").is_some()); - assert!(h.query_all_by_label(">").next().is_some() && h.query_all_by_label("<").next().is_some(), "the camera keys read as the reference's"); - assert!(h.query_by_label("Shift+Period").is_none()); -} diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index d148d41f..e5ea44f6 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -398,14 +398,3 @@ fn escape_cancels_picking_the_symmetry_point() { assert!(!harness.state().picking_symmetry_plane); assert_eq!(harness.state().session.tool.brush.symmetry.offset, [0.0; 3]); } - -#[test] -fn the_smudge_tool_offers_the_symmetry_toggle() { - let mut harness = app_harness(); - harness.state_mut().session.tool.tool = Tool::Smudge; - harness.run_steps(2); - - harness.get_by_label("Symmetry").click(); - harness.run_steps(2); - assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false]), "the toggle mirrors the smudge on X"); -} diff --git a/crates/ui-egui/tests/it/templates_681.rs b/crates/ui-egui/tests/it/templates_681.rs index c73ebe1d..4c147db4 100644 --- a/crates/ui-egui/tests/it/templates_681.rs +++ b/crates/ui-egui/tests/it/templates_681.rs @@ -93,27 +93,6 @@ fn save_and_reduce_file_size_is_greyed_with_the_hint() { assert!(!menus::implemented("ui.saveReduced")); } -#[test] -fn the_project_template_info_tooltip_lists_the_settings_templates_apply() { - let mut h = app(); - h.state_mut().ui.windows.new_project = true; - h.run_steps(4); - let row = h.get_by_label("Project template").rect().center().y; - let icon = h - .get_all_by_label(egui_phosphor::regular::INFO) - .find(|node| (node.rect().center().y - row).abs() < 6.0) - .expect("the info icon in the Project template row"); - - // The icon's node is wider than the glyph: hover its left part - let at = icon.rect().center() - egui::vec2(6.0, 0.0); - h.hover_at(egui::pos2(1.0, 1.0)); - h.run_steps(2); - h.hover_at(at); - h.run_steps(30); - let tip = "Templates set the starting channels, resolution, normal map format and shader settings."; - assert!(h.query_by_label(tip).is_some(), "hovering the info icon of the Project template row"); -} - #[test] fn new_project_opens_on_the_template_of_the_last_project() { let dir = TempDir::new("last-template"); diff --git a/crates/ui-egui/tests/it/view_mode_picker.rs b/crates/ui-egui/tests/it/view_mode_picker.rs index 98f32d58..e0009a84 100644 --- a/crates/ui-egui/tests/it/view_mode_picker.rs +++ b/crates/ui-egui/tests/it/view_mode_picker.rs @@ -4,7 +4,6 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable as _; use texturecraft_engine::ViewMode; -use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; fn harness() -> Harness<'static, TextureCraftApp> { @@ -38,39 +37,6 @@ fn query_field<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a h.get_all_by_role(Role::TextInput).find(|node| node.value().as_deref() == Some("u:image PRs")).expect("the query starts as in the reference") } -#[test] -fn the_combo_lists_the_reference_sections_and_names() { - let mut h = harness(); - open(&mut h, "Material"); - for label in [ - "Lighting", - "Material", - "Single channel", - "Base color", - "Base metalness", - "Specular roughness", - "Normal", - "Height", - "Normal+height+mesh", - "Mesh maps", - "World space normal", - "ID", - "Ambient occlusion", - "Curvature", - "Position", - "Thickness", - "Bent normals", - "Opacity", - "Other...", - ] { - assert!(h.query_all_by_label(label).next().is_some(), "{label}"); - } - for old in ["Metallic", "Roughness", "Mesh map: Normal", "Mesh map: World Space Normal", "Ambient Occlusion", "Bent Normals"] { - assert!(h.query_by_label(old).is_none(), "{old} is not offered"); - } - assert!(h.query_all_by_label("Normal").count() >= 2, "Normal is a channel and a mesh map"); -} - #[test] fn the_section_titles_cannot_be_picked() { let mut h = harness(); @@ -79,25 +45,6 @@ fn the_section_titles_cannot_be_picked() { assert_eq!(h.state().session.view, ViewMode::Material, "a title is no mode"); } -#[test] -fn a_channel_shows_under_its_reference_name_in_this_combo_only() { - let mut h = harness(); - open(&mut h, "Material"); - pick(&mut h, "Specular roughness"); - assert_eq!(h.state().session.view, ViewMode::Channel(Channel::Roughness)); - picker(&h, "Specular roughness"); - assert_eq!(Channel::Roughness.label(), "Roughness", "other places keep the channel's name"); -} - -#[test] -fn a_mesh_map_shows_without_a_prefix() { - let mut h = harness(); - open(&mut h, "Material"); - pick(&mut h, "Ambient occlusion"); - assert_eq!(h.state().session.view, ViewMode::MeshMap(texturecraft_engine::core::BakedMap::AmbientOcclusion)); - picker(&h, "Ambient occlusion"); -} - fn png() -> Vec { let mut png = Vec::new(); let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 40, 40, 255])); @@ -190,15 +137,3 @@ fn removing_the_shown_image_brings_the_material_back() { assert_eq!(h.state().session.view, ViewMode::Material); picker(&h, "Material"); } - -#[test] -fn bake_mode_keeps_its_own_view_list() { - let mut h = harness(); - h.state_mut().ui.mode = texturecraft_ui_egui::state::Mode::Baking; - h.run_steps(4); - open(&mut h, "Neutral Material"); - h.get_by_label("Mesh map: Ambient Occlusion").scroll_to_me(); - h.run_steps(3); - assert!(h.query_by_label("Mesh map: Ambient Occlusion").is_some(), "mesh maps keep their prefix in Bake mode"); - assert!(h.query_by_label("Lighting").is_none() && h.query_by_label("Mesh maps").is_none(), "no section titles in Bake mode"); -} diff --git a/xtask/src/version.rs b/xtask/src/version.rs index b2f31b20..746d57c0 100644 --- a/xtask/src/version.rs +++ b/xtask/src/version.rs @@ -139,10 +139,4 @@ mod tests { assert!(validate(bad).is_err(), "{bad}"); } } - - #[test] - fn the_real_manifest_has_a_valid_version() { - let text = std::fs::read_to_string(crate::root().join("Cargo.toml")).unwrap(); - validate(&read(&text).unwrap()).unwrap(); - } } From 30b1f3b938135b0b31e996f4a31d0813195d0e76 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 23 Nov 2026 04:25:29 -0500 Subject: [PATCH 049/153] Validate control-server test replies as bounded bytes --- apps/texturecraft/src/control_server.rs | 34 +++++++++++++++---------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/apps/texturecraft/src/control_server.rs b/apps/texturecraft/src/control_server.rs index 7576083d..cf0a6df4 100644 --- a/apps/texturecraft/src/control_server.rs +++ b/apps/texturecraft/src/control_server.rs @@ -134,7 +134,7 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender, ctx: &egui #[cfg(test)] mod tests { - use std::io::BufRead; + use std::io::{BufRead, Read}; use super::*; @@ -196,22 +196,28 @@ mod tests { assert_eq!(call(&mut w, &mut r, r#"{"id":4,"method":"ping"}"#).unwrap()["id"], 4, "bad JSON keeps an authenticated connection"); } + fn assert_reply(reader: &mut BufReader, expected: Value) -> std::io::Result<()> { + let expected = format!("{expected}\n"); + let mut received = vec![0; expected.len()]; + reader.read_exact(&mut received)?; + assert_eq!(received, expected.as_bytes(), "unexpected control server reply"); + Ok(()) + } + #[test] - fn authenticated_connections_hold_server_slots() { + fn authenticated_connections_hold_server_slots() -> std::io::Result<()> { let addr = server(); let right = format!(r#"{{"id":1,"method":"auth","params":{{"token":"{TOKEN}"}}}}"#); - let _held: Vec<_> = (0..MAX_CONNECTIONS) - .map(|_| { - let (mut w, mut r) = connect(addr); - // The reply confirms that this connection is holding a slot. - assert_eq!(call(&mut w, &mut r, &right).unwrap()["ok"], true); - (w, r) - }) - .collect(); + let mut held = Vec::with_capacity(MAX_CONNECTIONS); + for _ in 0..MAX_CONNECTIONS { + let (mut writer, mut reader) = connect(addr); + writeln!(writer, "{right}")?; + // The reply confirms that this connection is holding a slot. + assert_reply(&mut reader, json!({"ok": true, "id": 1}))?; + held.push((writer, reader)); + } - let (_, mut r) = connect(addr); - let mut reply = String::new(); - r.read_line(&mut reply).unwrap(); - assert_eq!(serde_json::from_str::(&reply).unwrap()["error"], "too many connections"); + let (_writer, mut reader) = connect(addr); + assert_reply(&mut reader, json!({"id": null, "ok": false, "error": "too many connections"})) } } From 097017211d1387c19acfdb28d776c032931f1eca Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 09:34:20 -0500 Subject: [PATCH 050/153] ci(release): forward ARTCRAFT_SERVICES_DISPATCH_TOKEN secret (#781) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23727788..c8c04b32 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -49,3 +49,4 @@ jobs: AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} From 1c2f91759b1d81b8e872073d238565ad117d971e Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 23 Nov 2026 09:38:12 -0500 Subject: [PATCH 051/153] Measure translation lookup speed in a standalone benchmark Move i18n::tests::lookup_is_fast to the translation_lookup benchmark (F2). Keep the 1,000 ns budget for warm lookups over the embedded Japanese catalog. Verify borrowed translations and the English fallback deterministically in the language-switch unit test. --- crates/ui-egui/Cargo.toml | 5 +++ crates/ui-egui/benches/translation_lookup.rs | 45 ++++++++++++++++++++ crates/ui-egui/src/i18n.rs | 29 ++++--------- 3 files changed, 59 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/benches/translation_lookup.rs diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5b3ed2d3..8414598a 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -8,6 +8,11 @@ license.workspace = true [lints] workspace = true +[[bench]] +name = "translation_lookup" +harness = false +test = false + [dependencies] chrono = { workspace = true } texturecraft-engine = { workspace = true } diff --git a/crates/ui-egui/benches/translation_lookup.rs b/crates/ui-egui/benches/translation_lookup.rs new file mode 100644 index 00000000..c01f5875 --- /dev/null +++ b/crates/ui-egui/benches/translation_lookup.rs @@ -0,0 +1,45 @@ +//! Time warm lookups with the Japanese catalog embedded by the regular build. +//! With `CRAFT_I18N_DIR` pointing at the pinned catalog checkout, run +//! `cargo bench -p texturecraft-ui-egui --bench translation_lookup --profile dev`. + +use std::{hint::black_box, time::Instant}; + +use texturecraft_ui_egui::i18n::{set_language, tr}; + +include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); + +fn main() -> Result<(), String> { + // Cargo can run this binary under test --all-targets too. Only bench passes --bench. + if !std::env::args().any(|arg| arg == "--bench") { + return Ok(()); + } + + let &(_, shared, app) = CRAFT_I18N.iter().find(|(code, _, _)| *code == "ja").ok_or("set CRAFT_I18N_DIR to the pinned craft-i18n checkout")?; + + // The plain rows with literal English keys are representative of the labels tr() looks up. + let mut keys: Vec<_> = shared + .lines() + .chain(app.lines()) + .filter_map(|row| row.strip_prefix('\t')?.split_once('\t').map(|(key, _)| key)) + .filter(|key| !key.is_empty() && !key.contains('\\')) + .collect(); + keys.sort_unstable(); + keys.dedup(); + if keys.is_empty() { + return Err("the Japanese catalog has no plain translation keys".into()); + } + + set_language("ja"); + black_box(tr(keys[0])); + const ROUNDS: usize = 100; + let started = Instant::now(); + for _ in 0..ROUNDS { + for key in &keys { + black_box(tr(black_box(key))); + } + } + let ns_per_lookup = started.elapsed().as_secs_f64() * 1e9 / (ROUNDS * keys.len()) as f64; + println!("{ns_per_lookup:.0} ns per lookup across {} Japanese keys", keys.len()); + assert!(ns_per_lookup < 1000.0, "{ns_per_lookup:.0} ns per lookup exceeded the 1000 ns budget"); + Ok(()) +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 02198a5a..2073a222 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -428,28 +428,17 @@ mod tests", set_language(language.code); assert_eq!(current().code, if available(language.code) { language.code } else { "en" }); } + let key = String::from("Layers"); set_language("es"); - assert_eq!(tr("Layers"), if available("es") { "Capas" } else { "Layers" }); + let label = tr(&key); set_language("en"); - } - - #[test] - fn lookup_is_fast() { - let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let keys = keys(); - set_language("ja"); - let started = std::time::Instant::now(); - let mut total_chars = 0usize; - for _ in 0..100 { - for key in &keys { - total_chars += tr(key).len(); - } - } - let ns_per_lookup = started.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64; + let english = tr(&key); + set_language("es"); + let reused = tr(&key); set_language("en"); - assert!(total_chars > 0); - - // A frame looks up a few hundred strings, each expected below one microsecond - assert!(ns_per_lookup < 1000.0, "{ns_per_lookup:.0} ns per lookup"); + assert_eq!(label, if available("es") { "Capas" } else { "Layers" }); + assert!(std::ptr::eq(english, key.as_str())); + // Switching away and back reuses the translation already stored in the catalog. + assert!(std::ptr::eq(reused, label)); } } From 175e92dde672a3ab712cf16c01e498dd44a02fb3 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 23 Nov 2026 10:03:38 -0500 Subject: [PATCH 052/153] Check translation lookup behavior without timing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Account for 1c2f9175 by removing its standalone benchmark. Replace the lookup_is_fast wall-clock check (F2) with language-switch and missing-translation assertions in saved_language_codes_and_spanish_lookup, following PhotoCraft’s translation tests. Verified all seven i18n tests with coverage instrumentation and pinned catalogs, formatting, layering, and strict UI Clippy. --- crates/ui-egui/Cargo.toml | 5 --- crates/ui-egui/benches/translation_lookup.rs | 45 -------------------- crates/ui-egui/src/i18n.rs | 18 ++++---- 3 files changed, 10 insertions(+), 58 deletions(-) delete mode 100644 crates/ui-egui/benches/translation_lookup.rs diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 8414598a..5b3ed2d3 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -8,11 +8,6 @@ license.workspace = true [lints] workspace = true -[[bench]] -name = "translation_lookup" -harness = false -test = false - [dependencies] chrono = { workspace = true } texturecraft-engine = { workspace = true } diff --git a/crates/ui-egui/benches/translation_lookup.rs b/crates/ui-egui/benches/translation_lookup.rs deleted file mode 100644 index c01f5875..00000000 --- a/crates/ui-egui/benches/translation_lookup.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! Time warm lookups with the Japanese catalog embedded by the regular build. -//! With `CRAFT_I18N_DIR` pointing at the pinned catalog checkout, run -//! `cargo bench -p texturecraft-ui-egui --bench translation_lookup --profile dev`. - -use std::{hint::black_box, time::Instant}; - -use texturecraft_ui_egui::i18n::{set_language, tr}; - -include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); - -fn main() -> Result<(), String> { - // Cargo can run this binary under test --all-targets too. Only bench passes --bench. - if !std::env::args().any(|arg| arg == "--bench") { - return Ok(()); - } - - let &(_, shared, app) = CRAFT_I18N.iter().find(|(code, _, _)| *code == "ja").ok_or("set CRAFT_I18N_DIR to the pinned craft-i18n checkout")?; - - // The plain rows with literal English keys are representative of the labels tr() looks up. - let mut keys: Vec<_> = shared - .lines() - .chain(app.lines()) - .filter_map(|row| row.strip_prefix('\t')?.split_once('\t').map(|(key, _)| key)) - .filter(|key| !key.is_empty() && !key.contains('\\')) - .collect(); - keys.sort_unstable(); - keys.dedup(); - if keys.is_empty() { - return Err("the Japanese catalog has no plain translation keys".into()); - } - - set_language("ja"); - black_box(tr(keys[0])); - const ROUNDS: usize = 100; - let started = Instant::now(); - for _ in 0..ROUNDS { - for key in &keys { - black_box(tr(black_box(key))); - } - } - let ns_per_lookup = started.elapsed().as_secs_f64() * 1e9 / (ROUNDS * keys.len()) as f64; - println!("{ns_per_lookup:.0} ns per lookup across {} Japanese keys", keys.len()); - assert!(ns_per_lookup < 1000.0, "{ns_per_lookup:.0} ns per lookup exceeded the 1000 ns budget"); - Ok(()) -} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2073a222..235ebc5e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -428,17 +428,19 @@ mod tests", set_language(language.code); assert_eq!(current().code, if available(language.code) { language.code } else { "en" }); } - let key = String::from("Layers"); + const MISSING: &str = "missing test label"; set_language("es"); - let label = tr(&key); + let spanish = tr("Layers"); + let missing = tr(MISSING); set_language("en"); - let english = tr(&key); + let english = tr("Layers"); set_language("es"); - let reused = tr(&key); + let spanish_again = tr("Layers"); set_language("en"); - assert_eq!(label, if available("es") { "Capas" } else { "Layers" }); - assert!(std::ptr::eq(english, key.as_str())); - // Switching away and back reuses the translation already stored in the catalog. - assert!(std::ptr::eq(reused, label)); + + assert_eq!(spanish, if available("es") { "Capas" } else { "Layers" }); + assert_eq!(missing, MISSING); + assert_eq!(english, "Layers"); + assert_eq!(spanish_again, spanish); } } From b53c9312482b34592c37a96737b00767e08d5487 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 18:49:37 +0100 Subject: [PATCH 053/153] Add a MaterialX export option to the export window --- ROADMAP.md | 6 +- crates/ui-egui/src/export_window.rs | 16 +++- crates/ui-egui/src/state.rs | 5 ++ crates/ui-egui/tests/it/export_materialx.rs | 94 +++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/features.md | 6 ++ docs/ui-parity.md | 5 +- 7 files changed, 126 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/tests/it/export_materialx.rs diff --git a/ROADMAP.md b/ROADMAP.md index 759dfde7..cb114376 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -63,7 +63,7 @@ Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material dra and generator editing, UV rectangle fill, UI baking, native saving and texture export. Separate command checks covered high-to-low transfer, UDIM sizes/packing and scene/material exports. The interface is recognizably close in its painting, bake and export workspaces, but still lacks -mask-thumbnail effect menus, several fill controls and a MaterialX export option. +mask-thumbnail effect menus and several fill controls. Generator depth is limited, bake equivalence is open, and hardware/performance coverage is incomplete. There were **96 open issues** on the review date; these include requests and older reports, not 96 reproduced defects. The published @@ -118,7 +118,7 @@ menu entries. Feature rows overlap and are not an additional additive score. | Baking | ~60% | TBD | All ten maps completed through the UI on CPU at 256 px and through commands on GPU at 128 px. Separate high/low normal/height transfer produced varying maps; cross-app pixel equivalence, larger assets and resolution-stable wear remain unproven | | Viewport, shading and rendering | ~70% | TBD | PBR/IBL, extra shading lobes, 3D/2D views, displacement and CPU/GPU path-tracing paths. Matching material/display behavior, larger scenes and hardware ray tracing remain open | | Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces and profile metadata; display model has Linear/ACES-filmic tone mapping. Configurable OCIO project/display workflows are absent | -| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX UI output, complex materials and larger UDIM assets remain incomplete | +| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX export covers OpenPBR only (no standard_surface); complex materials and larger UDIM assets remain incomplete | | Read-only `.spp` compatibility | 0% | TBD after feasibility study | Planned; no reader, version matrix or import-fidelity corpus. `.tcraft` remains the save format | | Workspace, panels and preferences | ~65% | TBD | Current views/layouts checked; narrow labels truncate. Incoming ArtCraft UI refactoring/shared components can change these surfaces; task, shortcut, accessibility and layout/preferences persistence checks must be repeated | | Automation | ~80% | TBD | Command inspection and scripted editing/export work; UI, CLI and MCP surfaces share engine commands. This review exercised the control channel and CLI, not every MCP/tool path | @@ -135,7 +135,7 @@ the legacy promise must not be carried forward automatically. The [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows) records reproduction routes and acceptance checks: mask context/save/export actions; independent U/V tiling, -filtering/wrap, physical-size and warp/per-tile projections; MaterialX UI output; +filtering/wrap, physical-size and warp/per-tile projections; and configurable color-management settings. Generator depth and narrow-layout readability are tracked as partial areas. Direct hardness/angle controls and polygon/UV rectangle fill already exist; older reports must not turn them into fresh missing-feature claims. diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 37590454..5a014fd3 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -374,6 +374,12 @@ pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value { if !e.color_space.is_empty() { p["colorSpace"] = json!(e.color_space); } + + // The browser downloads the textures only + #[cfg(not(target_arch = "wasm32"))] + if e.materialx { + p["materialX"] = json!(true); + } p } @@ -631,8 +637,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] if reset { let d = ExportUi::default(); let e = &mut app.ui.export; - (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space) = - (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space); + (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space, e.materialx) = + (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space, d.materialx); crate::export_templates::select(app, d.preset); } let (first, rest) = template_groups(app, builtins); @@ -678,6 +684,12 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // Unavailable export controls stay disabled unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + + // The browser downloads the textures only, so it has no MaterialX file to add + #[cfg(not(target_arch = "wasm32"))] + ui.checkbox(&mut app.ui.export.materialx, tr("Export MaterialX")); + #[cfg(target_arch = "wasm32")] + crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let e = &mut app.ui.export; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e2a36d40..8f949d76 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -357,6 +357,10 @@ pub struct ExportUi { /// "" (by file format: sRGB, or linear for float files), or a colour space name. #[serde(default)] pub color_space: String, + /// Also write an OpenPBR MaterialX (`.mtlx`) file per texture set (`materialX` of + /// `file.exportTextures`). + #[serde(default)] + pub materialx: bool, /// Texture sets excluded from export. pub skip: Vec, /// Per texture set (by index) overrides of the settings above. @@ -418,6 +422,7 @@ impl Default for ExportUi { size: 0, normal_format: String::new(), color_space: String::new(), + materialx: false, skip: Vec::new(), sets: Default::default(), owner: Vec::new(), diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs new file mode 100644 index 00000000..0431fa62 --- /dev/null +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -0,0 +1,94 @@ +//! Export textures › SETTINGS: the Export MaterialX option (texturecraft #760). It passes +//! `materialX: true` to `file.exportTextures`, which writes an OpenPBR material per texture set. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; +use texturecraft_ui_egui::TextureCraftApp; + +const OPENPBR: &str = "OpenPBR (separate maps)"; + +/// The Export textures window writing into a scratch folder of its own for `name` +fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, std::path::PathBuf) { + 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.prefs.language = "en".into(); + h.run_steps(4); + let dir = std::env::temp_dir().join(format!("tc-export-materialx-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + (h, dir) +} + +fn checkbox<'a>(h: &'a Harness<'static, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_by_role_and_label(egui::Role::CheckBox, "Export MaterialX") +} + +/// Click Export and run frames until the export ends +fn export(h: &mut Harness<'static, TextureCraftApp>) { + h.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + h.run_steps(1); + if h.state().ui.export.job.is_none() { + break; + } + } + h.run_steps(2); +} + +fn mtlx_files(dir: &std::path::Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut files: Vec<_> = entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "mtlx")).collect(); + files.sort(); + files +} + +#[test] +fn the_window_offers_export_materialx_off_by_default() { + let (h, _dir) = harness("offer"); + assert!(!checkbox(&h).accesskit_node().is_disabled()); + assert!(!h.state().ui.export.materialx); +} + +#[test] +fn ticking_export_materialx_writes_one_mtlx_per_texture_set() { + let (mut h, dir) = harness("on"); + h.state_mut().ui.export.preset = OPENPBR.into(); + h.run_steps(3); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.materialx); + export(&mut h); + + let files = mtlx_files(&dir); + assert_eq!(files.len(), h.state().session.set_count(), "one material per texture set: {files:?}"); + for file in &files { + let text = std::fs::read_to_string(file).unwrap(); + assert!(text.contains(" Date: Mon, 23 Nov 2026 13:17:38 -0500 Subject: [PATCH 054/153] ci(release): publish scheduled nightly prereleases (#785) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c8c04b32..6a6f238d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,7 +27,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - dry-run: ${{ github.event_name == 'schedule' }} + nightly: ${{ github.event_name == 'schedule' }} app-name: texturecraft app-title: "TextureCraft" craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc From b84f7b56e4852f21027b0ff940a0c926e2159473 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 19:23:50 +0100 Subject: [PATCH 055/153] Write the OpenPBR maps for the MaterialX whatever template is selected --- crates/engine/src/file_cmds.rs | 79 ++++++++- crates/engine/tests/it/materialx.rs | 172 +++++++++++++++++++- crates/ui-egui/tests/it/export_materialx.rs | 25 +++ docs/features.md | 5 +- 4 files changed, 270 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..98ad2ad5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files)}", always, export_textures ), @@ -645,23 +645,86 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { - written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?); + // The material reads OpenPBR maps whatever template was chosen: a template without + // their file names gets an extra pass of the built-in OpenPBR template beside its own files + let extra = openpbr_options(&opts); + let material_opts = extra.as_ref().unwrap_or(&opts); + let mut taken = std::collections::HashSet::new(); + if extra.is_some() { + taken.extend(files.iter().map(|f| f.name.to_ascii_lowercase())); + let mut maps = s.export_files(&sets, material_opts)?; + for file in &maps { + for warning in &file.warnings { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + } + + // A file of the chosen template is never replaced; the material leaves out the map it would have used + let before = maps.len(); + maps.retain(|f| !taken.contains(&f.name.to_ascii_lowercase())); + if maps.len() < before { + warnings + .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template, so the material does not use it".into()); + } + written.extend(texturecraft_formats::write_files(&maps, std::path::Path::new(&dir)).map_err(fe)?); + } + written.extend(write_materialx(s, &sets, material_opts, std::path::Path::new(&dir), &mut warnings, taken, extra.is_some())?); } s.log.info("MapExporter", format!("Exported {} textures to {dir}", written.len())); Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::>(), "warnings": warnings })) } +/// The options of the extra pass that writes the maps a MaterialX reads, or None when `opts`' +/// template already has maps with the OpenPBR file names (`texturecraft_formats::materialx`). +/// The pass uses the built-in "OpenPBR (separate maps)" template with the export's size, +/// padding, normal format, colour space, atlas and dithering, but not `opts.maps` (its indexes +/// belong to the chosen template). A file type override stays when a material can refer to it; +/// PSD, JNG, PGM (colour maps become luminance) and WebP (few readers) fall back to the +/// template's own PNG 8-bit (16-bit for height), so the bit depth override goes with them. +#[cfg(not(target_arch = "wasm32"))] +fn openpbr_options(opts: &ExportOptions) -> Option { + use texturecraft_formats::materialx::input_of_template; + if opts.preset.maps.iter().any(|map| input_of_template(&map.file).is_some()) { + return None; + } + + let mut options = ExportOptions::new(texturecraft_formats::builtin_preset("OpenPBR (separate maps)")?); + options.padding = opts.padding; + options.size = opts.size; + options.normal_format = opts.normal_format; + options.atlas = opts.atlas; + options.color_space = opts.color_space; + options.dither = opts.dither; + if let Some(format) = opts.format_override.filter(|format| !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp)) { + options.format_override = Some(format); + options.bit_depth_override = opts.bit_depth_override; + } + Some(options) +} + /// One `_.mtlx` per texture set, next to the textures `opts` just wrote: the /// OpenPBR inputs those textures feed (see `texturecraft_formats::materialx`). UDIM sets name /// their files with the `` token. Sets with no recognised map, or whose name gives the -/// same file name as an earlier set's, are skipped with a warning. +/// same file name as an earlier set's, are skipped with a warning. `taken` holds the lower-case +/// names of files this export wrote for other maps: a texture of that name is not referenced. +/// `own_maps`: `opts` is the extra OpenPBR pass, not the template the user chose. #[cfg(not(target_arch = "wasm32"))] -fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec) -> Result> { +fn write_materialx( + s: &Session, + sets: &[usize], + opts: &ExportOptions, + dir: &std::path::Path, + warnings: &mut Vec, + taken: std::collections::HashSet, + own_maps: bool, +) -> Result> { use texturecraft_formats::materialx::{self, Texture}; let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); let mut stems = std::collections::HashSet::new(); - let mut written_names = std::collections::HashSet::new(); + let mut written_names = taken; let mut normal_map_written = false; let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065); let mut aces2065_written = false; @@ -692,7 +755,11 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: } normal_map_written |= textures.iter().any(|t| t.input == "geometry_normal"); if textures.is_empty() { - warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name)); + warnings.push(if own_maps { + format!("MaterialX: texture set \"{}\" has no channels an OpenPBR map can use", set.name) + } else { + format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name) + }); continue; } diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 9af10e2c..4bf38421 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -5,6 +5,7 @@ use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; const OPENPBR: &str = "OpenPBR (separate maps)"; +const DEFAULT: &str = "Document channels + Normal + AO (No Alpha)"; /// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. struct Scratch(std::path::PathBuf); @@ -64,16 +65,181 @@ fn writes_a_material_that_names_the_exported_textures() { } #[test] -fn off_by_default_and_warns_without_openpbr_maps() { +fn off_by_default() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); let dir = temp("off"); assert!(!files(&export(&mut s, &dir, OPENPBR, false)).iter().any(|f| f.ends_with(".mtlx"))); - let dir = temp("other"); - let r = export(&mut s, &dir, "Document channels + Normal + AO", true); + let dir = temp("off-other"); + assert!(!files(&export(&mut s, &dir, DEFAULT, false)).iter().any(|f| f.ends_with(".mtlx") || f.ends_with("_base_color.png"))); +} + +#[test] +fn warns_when_a_template_with_openpbr_names_has_no_channels_to_write() { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // The default set has no coat + let preset = ExportPreset { + name: "coat".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet_coat_weight".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::L, SourceRef::Channel { channel: texturecraft_engine::core::Channel::CoatWeight, component: 0 })], + inverted: Vec::new(), + }], + }; + let dir = temp("nocoat"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "materialX": true})).unwrap(); assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx"))); assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("OpenPBR")), "{r}"); } +/// The `file` values a `.mtlx` refers to +fn referenced(text: &str) -> Vec { + text.split("name=\"file\" type=\"filename\" value=\"").skip(1).map(|part| part.split('"').next().unwrap().to_string()).collect() +} + +fn names(r: &Value) -> Vec { + files(r).iter().map(|f| f.rsplit(['/', '\\']).next().unwrap().to_string()).collect() +} + +#[test] +fn any_template_gets_the_openpbr_maps_beside_its_own_files() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let plain = temp("plain"); + let own = names(&export(&mut s, &plain, DEFAULT, false)); + let dir = temp("default-template"); + let r = export(&mut s, &dir, DEFAULT, true); + let all = names(&r); + for file in &own { + assert!(all.contains(file), "the template's own file {file} is still written: {all:?}"); + } + + let mtlx: Vec = files(&r).into_iter().filter(|f| f.ends_with(".mtlx")).collect(); + assert_eq!(mtlx.len(), s.set_count(), "{all:?}"); + for path in &mtlx { + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("= 3, "{text}"); + for file in refs { + assert!(dir.join(&file).is_file(), "{file} is not in {all:?}"); + assert!(!own.contains(&file), "{file} is a file of the chosen template"); + } + } + + // Every file is written once + let mut sorted = all.clone(); + sorted.sort(); + sorted.dedup(); + assert_eq!(sorted.len(), all.len(), "{all:?}"); +} + +#[test] +fn the_openpbr_template_writes_no_second_set_of_maps() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let without = temp("openpbr-without"); + let plain = names(&export(&mut s, &without, OPENPBR, false)); + let dir = temp("openpbr-with"); + let mut all = names(&export(&mut s, &dir, OPENPBR, true)); + all.retain(|f| !f.ends_with(".mtlx")); + let mut plain = plain; + plain.sort(); + all.sort(); + assert_eq!(all, plain); +} + +#[test] +fn per_map_overrides_of_the_template_do_not_reach_the_openpbr_maps() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("override"); + + // Map 0 is the base colour of the default template and also of the OpenPBR template; map 19 is the default template's normal map + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "materialX": true, "maps": [{"map": 0, "enabled": false}, {"map": 19, "format": "tiff", "bitDepth": 16}]}), + ) + .unwrap(); + let all = names(&r); + assert!(!all.iter().any(|f| f.ends_with("_baseColor.png")), "the template's base colour was left out: {all:?}"); + assert!(all.iter().any(|f| f.ends_with("_base_color.png")), "the material's base colour is still written: {all:?}"); + assert!(all.iter().any(|f| f.ends_with("_geometry_normal.png")), "{all:?}"); + assert!(all.iter().any(|f| f.ends_with("_normal.tif")), "the override applies to the template's own normal map: {all:?}"); + assert!(!all.iter().any(|f| f.ends_with(".tif") && f.contains("_geometry_")), "{all:?}"); +} + +#[test] +fn a_file_type_a_material_cannot_use_falls_back_to_png() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for (format, bit_depth, ext) in [("psd", 16, "psd"), ("pgm", 8, "pgm"), ("jng", 8, "jng"), ("tiff", 16, "tif")] { + let dir = temp(format); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "format": format, "bitDepth": bit_depth, "materialX": true}), + ) + .unwrap(); + let all = names(&r); + assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}"); + let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("{format}: no .mtlx in {all:?}")); + let text = std::fs::read_to_string(mtlx).unwrap(); + let wanted = if format == "tiff" { "tif" } else { "png" }; + assert!(text.contains(&format!("_base_color.{wanted}\"")), "{format}: {text}"); + for file in referenced(&text) { + assert!(dir.join(&file).is_file(), "{format}: {file} is not in {all:?}"); + } + } +} + +#[test] +fn the_openpbr_maps_follow_the_size_and_colour_space_of_the_export() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("size"); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "size": 64, "colorSpace": "ACEScg", "materialX": true}), + ) + .unwrap(); + let png = files(&r).into_iter().find(|f| f.ends_with("_base_color.png")).unwrap(); + assert_eq!(image::image_dimensions(png).unwrap(), (64, 64)); + let text = std::fs::read_to_string(files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap()).unwrap(); + assert!(text.contains("_base_color.png\" colorspace=\"acescg\""), "{text}"); + assert!(text.contains("_specular_roughness.png\" colorspace=\"lin_rec709\""), "{text}"); +} + +#[test] +fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + + // Set 1's file from the template has the name set 0's OpenPBR base colour would get + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a_base_color"})).unwrap(); + let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component }; + let preset = ExportPreset { + name: "base colour only".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))], + inverted: Vec::new(), + }], + }; + let params = |dir: &std::path::Path, mtlx: bool| json!({"dir": dir.display().to_string(), "preset": preset, "ts": [0, 1], "materialX": mtlx}); + let plain = temp("clash-plain"); + execute(&mut s, "file.exportTextures", ¶ms(&plain, false)).unwrap(); + let dir = temp("clash"); + let r = execute(&mut s, "file.exportTextures", ¶ms(&dir, true)).unwrap(); + assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), std::fs::read(plain.join("material_ball_a_base_color.png")).unwrap()); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("file name of a map of the chosen template")), "{r}"); + let first = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); + assert!(!referenced(&first).contains(&"material_ball_a_base_color.png".to_string()), "{first}"); +} + #[test] fn float_colour_maps_are_tagged_linear() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 0431fa62..175f91d3 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -70,6 +70,31 @@ fn ticking_export_materialx_writes_one_mtlx_per_texture_set() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn ticking_export_materialx_with_any_template_writes_the_openpbr_maps_beside_its_files() { + let (mut h, dir) = harness("any-template"); + assert_eq!(h.state().ui.export.preset, texturecraft_engine::formats::DEFAULT_PRESET); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let files = mtlx_files(&dir); + assert_eq!(files.len(), h.state().session.set_count(), "one material per texture set: {files:?}"); + let mut references = 0; + for file in &files { + for reference in std::fs::read_to_string(file).unwrap().split("name=\"file\" type=\"filename\" value=\"").skip(1) { + let name = reference.split('"').next().unwrap(); + assert!(dir.join(name).is_file(), "{name} is not next to the material"); + references += 1; + } + } + assert!(references > 0); + let written: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + assert!(written.iter().any(|f| f.ends_with("_baseColor.png")), "the template's own maps are still written: {written:?}"); + assert!(written.iter().any(|f| f.ends_with("_base_color.png")), "{written:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// The option is off by default, so a plain export writes no `.mtlx` even with the OpenPBR template #[test] fn no_mtlx_is_written_when_the_option_is_off() { diff --git a/docs/features.md b/docs/features.md index 98daa7a0..13fdb52b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -179,8 +179,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA between texture sets). - **MaterialX export:** the *Export MaterialX* checkbox on the Export textures window's Global settings (off by default, remembered with the other settings) writes one OpenPBR `.mtlx` per - texture set next to the exported maps. It reads the maps of output templates that use the - OpenPBR file names, such as *OpenPBR (separate maps)*. Not covered yet: MaterialX + texture set next to the exported maps. The material always uses OpenPBR maps, whatever output + template is selected: a template without their file names gets them written beside its own + files. Not covered yet: MaterialX standard_surface, Coat Normal, Specular Level, Anisotropy Angle and constants such as IOR. In the browser the option is greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for From fa47c2c183103b4898d89fae988e630966436982 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 19:40:01 +0100 Subject: [PATCH 056/153] Force an OpenGL normal and keep the bit depth for the MaterialX maps --- crates/engine/src/file_cmds.rs | 32 +++++++----- crates/engine/tests/it/materialx.rs | 76 +++++++++++++++++++++++++++-- docs/control-protocol.md | 4 ++ docs/features.md | 9 ++-- 4 files changed, 101 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 98ad2ad5..d057f030 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}", always, export_textures ), @@ -644,14 +644,18 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let files = s.export_files(&sets, &opts)?; let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; + + // The rendered files are not needed after this; only their names are + let mut taken: std::collections::HashSet = files.iter().map(|f| f.name.to_ascii_lowercase()).collect(); + drop(files); if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { // The material reads OpenPBR maps whatever template was chosen: a template without // their file names gets an extra pass of the built-in OpenPBR template beside its own files let extra = openpbr_options(&opts); let material_opts = extra.as_ref().unwrap_or(&opts); - let mut taken = std::collections::HashSet::new(); - if extra.is_some() { - taken.extend(files.iter().map(|f| f.name.to_ascii_lowercase())); + if extra.is_none() { + taken.clear(); + } else { let mut maps = s.export_files(&sets, material_opts)?; for file in &maps { for warning in &file.warnings { @@ -677,12 +681,14 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { } /// The options of the extra pass that writes the maps a MaterialX reads, or None when `opts`' -/// template already has maps with the OpenPBR file names (`texturecraft_formats::materialx`). +/// template already has a map with an OpenPBR file name (`texturecraft_formats::materialx`). /// The pass uses the built-in "OpenPBR (separate maps)" template with the export's size, -/// padding, normal format, colour space, atlas and dithering, but not `opts.maps` (its indexes -/// belong to the chosen template). A file type override stays when a material can refer to it; -/// PSD, JNG, PGM (colour maps become luminance) and WebP (few readers) fall back to the -/// template's own PNG 8-bit (16-bit for height), so the bit depth override goes with them. +/// padding, atlas, colour space and dithering, but not `opts.maps` (its indexes belong to the +/// chosen template). The normal map is always OpenGL, which the material's normalmap node reads, +/// whatever normal format the export asks for. A file type and bit depth override stay when a +/// material can refer to the file type; PSD, JNG, PGM (colour maps become luminance) and WebP +/// (few readers) fall back to the template's own PNG 8-bit (16-bit for height), and the bit +/// depth override goes with them. #[cfg(not(target_arch = "wasm32"))] fn openpbr_options(opts: &ExportOptions) -> Option { use texturecraft_formats::materialx::input_of_template; @@ -693,12 +699,12 @@ fn openpbr_options(opts: &ExportOptions) -> Option { let mut options = ExportOptions::new(texturecraft_formats::builtin_preset("OpenPBR (separate maps)")?); options.padding = opts.padding; options.size = opts.size; - options.normal_format = opts.normal_format; + options.normal_format = Some(NormalFormat::OpenGl); options.atlas = opts.atlas; options.color_space = opts.color_space; options.dither = opts.dither; - if let Some(format) = opts.format_override.filter(|format| !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp)) { - options.format_override = Some(format); + if !opts.format_override.is_some_and(|format| matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp)) { + options.format_override = opts.format_override; options.bit_depth_override = opts.bit_depth_override; } Some(options) @@ -756,7 +762,7 @@ fn write_materialx( normal_map_written |= textures.iter().any(|t| t.input == "geometry_normal"); if textures.is_empty() { warnings.push(if own_maps { - format!("MaterialX: texture set \"{}\" has no channels an OpenPBR map can use", set.name) + format!("MaterialX: texture set \"{}\" has no OpenPBR maps to refer to", set.name) } else { format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name) }); diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 4bf38421..1b92b827 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -200,14 +200,23 @@ fn the_openpbr_maps_follow_the_size_and_colour_space_of_the_export() { let r = execute( &mut s, "file.exportTextures", - &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "size": 64, "colorSpace": "ACEScg", "materialX": true}), + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "size": 256, "colorSpace": "ACEScg", "materialX": true}), ) .unwrap(); let png = files(&r).into_iter().find(|f| f.ends_with("_base_color.png")).unwrap(); - assert_eq!(image::image_dimensions(png).unwrap(), (64, 64)); + assert_eq!(image::image_dimensions(png).unwrap(), (256, 256)); let text = std::fs::read_to_string(files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap()).unwrap(); assert!(text.contains("_base_color.png\" colorspace=\"acescg\""), "{text}"); - assert!(text.contains("_specular_roughness.png\" colorspace=\"lin_rec709\""), "{text}"); + + // Only colour inputs carry a colour space, and the data maps are still referenced + let roughness = referenced(&text).into_iter().find(|f| f.ends_with("_specular_roughness.png")).unwrap_or_else(|| panic!("{text}")); + assert!(dir.join(&roughness).is_file()); + for part in text.split("name=\"file\" type=\"filename\" value=\"").skip(1) { + let (file, rest) = part.split_once('"').unwrap(); + if rest.starts_with(" colorspace=\"acescg\"") { + assert!(["_base_color.", "_fuzz_color.", "_emission_color."].iter().any(|input| file.contains(input)), "{file}"); + } + } } #[test] @@ -405,3 +414,64 @@ fn the_directx_warning_comes_once_and_only_with_a_normal_map() { let r = export(&mut s, &dir, OPENPBR, true); assert!(!r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("DirectX")), "{r}"); } + +/// A tangent-space normal image of one colour as PNG bytes +fn normal_png(rgb: [u8; 3]) -> Vec { + let image = image::RgbImage::from_pixel(4, 4, image::Rgb(rgb)); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +fn green_at_centre(path: &str) -> u8 { + let image = image::open(path).unwrap().to_rgb8(); + image.get_pixel(image.width() / 2, image.height() / 2)[1] +} + +#[test] +fn the_materials_normal_map_is_opengl_whatever_the_export_asks_for() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // A baked normal that tilts: green 64 in the file, 71 / 184 once normalised in OpenGL / DirectX + let image = s.import_resource_bytes("n.png", normal_png([128, 64, 255])).unwrap(); + execute(&mut s, "textureSet.meshMap.set", &json!({"map": "normal", "image": image})).unwrap(); + let dir = temp("normal-format"); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": 0, "normalFormat": "directX", "materialX": true}), + ) + .unwrap(); + let all = files(&r); + let own = all.iter().find(|f| f.ends_with("_normal.png")).unwrap(); + let material = all.iter().find(|f| f.ends_with("_geometry_normal.png")).unwrap(); + assert!(green_at_centre(own).abs_diff(184) <= 3, "the template's own normal map is DirectX: {}", green_at_centre(own)); + assert!(green_at_centre(material).abs_diff(71) <= 3, "the material's normal map is OpenGL: {}", green_at_centre(material)); + assert!(!r["warnings"].to_string().contains("DirectX"), "nothing to flip in the material: {r}"); +} + +#[test] +fn the_bit_depth_of_the_export_applies_to_the_openpbr_maps_unless_the_file_type_fell_back() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for (extra, expected) in [(json!({}), image::ColorType::Rgb16), (json!({"format": "psd"}), image::ColorType::Rgb8)] { + let dir = temp("depth"); + let mut params = json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": 0, "bitDepth": 16, "materialX": true}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = execute(&mut s, "file.exportTextures", ¶ms).unwrap(); + let png = files(&r).into_iter().find(|f| f.ends_with("_base_color.png")).unwrap(); + assert_eq!(image::open(png).unwrap().color(), expected, "{params}"); + } +} + +#[test] +fn a_set_whose_openpbr_maps_were_all_skipped_gets_no_material_and_a_warning() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + assert!(s.set_count() >= 2); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a b"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "A_B"})).unwrap(); + let dir = temp("all-skipped"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": DEFAULT, "ts": "all", "materialX": true})).unwrap(); + assert_eq!(files(&r).iter().filter(|f| f.ends_with(".mtlx")).count(), s.set_count() - 1, "{r}"); + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).collect(); + assert!(warnings.contains(&"MaterialX: texture set \"A_B\" has no OpenPBR maps to refer to"), "{warnings:?}"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d963eb9c..8d6ed911 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,6 +47,10 @@ template. `enabled: false` suppresses that file while reserving its name. When s sets produce the same name (ignoring case), programmatic and browser exports keep the first file and warn about later duplicates. The desktop export window reports the collision before writing. +`file.exportTextures` with `materialX: true` also writes a `.mtlx` OpenPBR material per texture set. +A template without OpenPBR file names gets the maps of the "OpenPBR (separate maps)" template written +beside its own files for it; the `maps` overrides above do not reach those maps. + `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and diff --git a/docs/features.md b/docs/features.md index 13fdb52b..f7c6be63 100644 --- a/docs/features.md +++ b/docs/features.md @@ -180,10 +180,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **MaterialX export:** the *Export MaterialX* checkbox on the Export textures window's Global settings (off by default, remembered with the other settings) writes one OpenPBR `.mtlx` per texture set next to the exported maps. The material always uses OpenPBR maps, whatever output - template is selected: a template without their file names gets them written beside its own - files. Not covered yet: MaterialX - standard_surface, Coat Normal, Specular Level, Anisotropy Angle and constants such as IOR. In - the browser the option is greyed. + template is selected: a template without OpenPBR file names gets the maps of *OpenPBR (separate + maps)* written beside its own files, with the export's size, padding, colour space, file type + and bit depth (PNG when that file type has no use in a material) and always an OpenGL normal + map. Not covered yet: MaterialX standard_surface, Coat Normal, Specular Level, Anisotropy + Angle and constants such as IOR. In the browser the option is greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). From 927fedf31390dad8c2ea8c6c2f18a3f7ec45d457 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:18:21 +0100 Subject: [PATCH 057/153] Show the export's warnings in the export console --- crates/ui-egui/src/export_window.rs | 16 ++++++++++- crates/ui-egui/src/state/export_job.rs | 2 ++ crates/ui-egui/tests/it/export_materialx.rs | 32 +++++++++++++++++++++ docs/features.md | 4 +-- 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 5a014fd3..f64498b0 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -245,7 +245,7 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, written: Vec::new(), frame: 0 }); + e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, written: Vec::new(), frame: 0, warned: Vec::new() }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -345,6 +345,20 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { lines.push(set()); lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); } + + // The export's warnings go to the console and the log, each once per export + let warnings = response.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()); + for warning in warnings { + let Some(job) = app.ui.export.job.as_mut() else { break }; + if job.warned.iter().any(|seen| seen == warning) { + continue; + } + + job.warned.push(warning.to_string()); + app.session.log.warn("MapExporter", warning); + lines.push(set()); + lines.push(ConsoleLine::Step(trf("Warning: {message}", &[("message", &warning)]))); + } lines.extend([set(), ConsoleLine::Step(tr("Finished writing this texture set").into())]); app.ui.export.console.extend(lines); if let Some(job) = app.ui.export.job.as_mut() { diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index 4ba0d485..570fe3b4 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -15,4 +15,6 @@ pub struct ExportJob { pub written: Vec, /// The frame that wrote the last texture set (a frame's second pass writes none). pub frame: u64, + /// The warnings already shown, so a warning every texture set raises shows once per export. + pub warned: Vec, } diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 175f91d3..59d379cb 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -4,6 +4,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ConsoleLine; const OPENPBR: &str = "OpenPBR (separate maps)"; @@ -117,3 +118,34 @@ fn restoring_the_default_parameters_unticks_export_materialx() { h.run_steps(3); assert!(!h.state().ui.export.materialx); } + +/// Every texture set's export raises this warning: the material's normal map is read as OpenGL +const DIRECTX_WARNING: &str = "MaterialX: the normalmap node reads OpenGL (+Y) normals"; + +#[test] +fn a_warning_every_texture_set_raises_shows_once_in_the_console_and_the_log() { + let (mut h, dir) = harness("warning"); + assert!(h.state().session.set_count() >= 2, "the warning has to come from more than one texture set"); + let e = &mut h.state_mut().ui.export; + e.preset = OPENPBR.into(); + e.normal_format = "directX".into(); + h.run_steps(3); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let lines: Vec<&str> = h + .state() + .ui + .export + .console + .iter() + .filter_map(|line| match line { + ConsoleLine::Step(text) if text.starts_with("Warning: ") => Some(text.as_str()), + _ => None, + }) + .collect(); + assert_eq!(lines.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1, "{lines:?}"); + assert_eq!(h.state().session.log.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features.md b/docs/features.md index f7c6be63..4e3d40d3 100644 --- a/docs/features.md +++ b/docs/features.md @@ -175,8 +175,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA *Cancel* goes back to the settings the window opened with, *Maximum size for all Texture Sets* exports every set at the largest set's size; a click on a texture set overrides its template, file type, size or padding, and each output map's file type and bit depth, or leaves a map out; - Export shows the progress, a console of its steps and the written files, and can be canceled - between texture sets). + Export shows the progress, a console of its steps, the written files and the export's + warnings (each once), and can be canceled between texture sets). - **MaterialX export:** the *Export MaterialX* checkbox on the Export textures window's Global settings (off by default, remembered with the other settings) writes one OpenPBR `.mtlx` per texture set next to the exported maps. The material always uses OpenPBR maps, whatever output From c9640bae075c3fecc4b2e88c436359474eb4916d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:23:09 +0100 Subject: [PATCH 058/153] Keep the files of earlier texture sets of an export when writing the MaterialX maps --- crates/engine/src/file_cmds.rs | 47 +++++++++-- crates/engine/tests/it/materialx.rs | 90 +++++++++++++++++++++ crates/ui-egui/src/export_window.rs | 4 + crates/ui-egui/tests/it/export_materialx.rs | 72 +++++++++++++++++ docs/control-protocol.md | 5 ++ docs/features.md | 5 +- 6 files changed, 213 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d057f030..1f8d2415 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names] (files an earlier command of the same export wrote, compared ignoring case: this command leaves out its own files and OpenPBR maps of these names and says so in `warnings`; the export window passes it), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}", always, export_textures ), @@ -641,21 +641,29 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let opts = export_options(s, p, "file.exportTextures")?; let sets = sets_param(s, p, "file.exportTextures")?; std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; + let reserved = reserved_names(p)?; let files = s.export_files(&sets, &opts)?; + + // A file an earlier command of the same export wrote keeps its name: the export window runs + // one command per texture set, and a later set's file must not replace an earlier one (which an + // earlier .mtlx may refer to) + let (files, skipped): (Vec<_>, Vec<_>) = files.into_iter().partition(|f| !reserved.contains(&f.name.to_ascii_lowercase())); let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); + warnings.extend(skipped.iter().map(|f| format!("\"{}\" was not written: an earlier file of this export has the same name", f.name))); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; // The rendered files are not needed after this; only their names are - let mut taken: std::collections::HashSet = files.iter().map(|f| f.name.to_ascii_lowercase()).collect(); + let own: std::collections::HashSet = files.iter().map(|f| f.name.to_ascii_lowercase()).collect(); drop(files); + drop(skipped); + let mut taken = reserved; if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { // The material reads OpenPBR maps whatever template was chosen: a template without // their file names gets an extra pass of the built-in OpenPBR template beside its own files let extra = openpbr_options(&opts); let material_opts = extra.as_ref().unwrap_or(&opts); - if extra.is_none() { - taken.clear(); - } else { + if extra.is_some() { + taken.extend(own); let mut maps = s.export_files(&sets, material_opts)?; for file in &maps { for warning in &file.warnings { @@ -665,12 +673,12 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { } } - // A file of the chosen template is never replaced; the material leaves out the map it would have used + // A file of the chosen template, or of an earlier command of this export, is never replaced; the material leaves out the map it would have used let before = maps.len(); maps.retain(|f| !taken.contains(&f.name.to_ascii_lowercase())); if maps.len() < before { warnings - .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template, so the material does not use it".into()); + .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template or of an earlier file of this export, so the material does not use it".into()); } written.extend(texturecraft_formats::write_files(&maps, std::path::Path::new(&dir)).map_err(fe)?); } @@ -680,6 +688,19 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::>(), "warnings": warnings })) } +/// `reservedNames`: the names of files earlier commands of the same export wrote (lower-cased). +#[cfg(not(target_arch = "wasm32"))] +fn reserved_names(p: &Value) -> Result> { + match p.get("reservedNames") { + None | Some(Value::Null) => Ok(Default::default()), + Some(Value::Array(names)) => names + .iter() + .map(|name| name.as_str().map(str::to_ascii_lowercase).ok_or_else(|| bad("file.exportTextures", "`reservedNames` must be a list of file names"))) + .collect(), + Some(_) => Err(bad("file.exportTextures", "`reservedNames` must be a list of file names")), + } +} + /// The options of the extra pass that writes the maps a MaterialX reads, or None when `opts`' /// template already has a map with an OpenPBR file name (`texturecraft_formats::materialx`). /// The pass uses the built-in "OpenPBR (separate maps)" template with the export's size, @@ -730,6 +751,7 @@ fn write_materialx( let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); let mut stems = std::collections::HashSet::new(); + let reserved = taken.clone(); let mut written_names = taken; let mut normal_map_written = false; let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065); @@ -780,7 +802,16 @@ fn write_materialx( continue; } - let path = dir.join(format!("{stem}.mtlx")); + let file_name = format!("{stem}.mtlx"); + if reserved.contains(&file_name.to_ascii_lowercase()) { + warnings.push(format!( + "MaterialX: texture set \"{}\" exports as \"{file_name}\" like an earlier file of this export, so its .mtlx was not written", + set.name + )); + continue; + } + + let path = dir.join(file_name); texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?; aces2065_written |= textures.iter().any(|texture| texture.colorspace == aces2065_tag && materialx::INPUTS.contains(&(texture.input.as_str(), materialx::Kind::Color))); diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 1b92b827..f1979d38 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -249,6 +249,96 @@ fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() { assert!(!referenced(&first).contains(&"material_ball_a_base_color.png".to_string()), "{first}"); } +/// A template with one map, the base colour, named `$mesh_$textureSet` (no input suffix) +fn base_colour_template() -> texturecraft_engine::formats::ExportPreset { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component }; + ExportPreset { + name: "base colour only".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))], + inverted: Vec::new(), + }], + } +} + +/// One `file.exportTextures` command of texture set `ts`, as the export window sends them: the +/// names of the files the earlier commands wrote are passed as `reservedNames` +fn export_set(s: &mut Session, dir: &std::path::Path, ts: usize, earlier: &[String]) -> Value { + let params = json!({"dir": dir.display().to_string(), "preset": base_colour_template(), "ts": ts, "materialX": true, "reservedNames": earlier}); + execute(s, "file.exportTextures", ¶ms).unwrap() +} + +fn warned(r: &Value, text: &str) -> bool { + r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains(text)) +} + +#[test] +fn an_openpbr_map_never_replaces_a_file_an_earlier_command_of_the_export_wrote() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // Set 0's own file is named like the base colour map set 1 gets from the OpenPBR template + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a_base_color"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a"})).unwrap(); + let dir = temp("later-extra"); + let first = export_set(&mut s, &dir, 0, &[]); + let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); + let second = export_set(&mut s, &dir, 1, &names(&first)); + assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched"); + assert!(warned(&second, "has the file name of a map of the chosen template or of an earlier file of this export"), "{second}"); + let material = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); + assert!(!referenced(&material).contains(&"material_ball_a_base_color.png".to_string()), "{material}"); + for file in referenced(&material) { + assert!(dir.join(&file).is_file(), "{file}"); + } +} + +#[test] +fn a_file_of_the_template_never_replaces_an_openpbr_map_an_earlier_command_wrote() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + // Set 0's OpenPBR base colour has the name set 1's own file gets from the template + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a_base_color"})).unwrap(); + let dir = temp("later-own"); + let first = export_set(&mut s, &dir, 0, &[]); + let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); + let second = export_set(&mut s, &dir, 1, &names(&first)); + assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched"); + assert!(warned(&second, "\"material_ball_a_base_color.png\" was not written"), "{second}"); + + // The earlier material still points at the file it was written with + let earlier = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); + assert!(referenced(&earlier).contains(&"material_ball_a_base_color.png".to_string()), "{earlier}"); + let later = std::fs::read_to_string(dir.join("material_ball_a_base_color.mtlx")).unwrap(); + assert!(!referenced(&later).contains(&"material_ball_a_base_color.png".to_string()), "{later}"); +} + +#[test] +fn a_material_is_not_written_over_a_file_an_earlier_command_wrote() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap(); + let dir = temp("mtlx-name"); + let r = export_set(&mut s, &dir, 0, &["MATERIAL_BALL_A.MTLX".to_string()]); + assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx")), "{r}"); + assert!(warned(&r, "exports as \"material_ball_a.mtlx\" like an earlier file of this export"), "{r}"); + let r = export_set(&mut s, &dir, 0, &["unrelated.mtlx".to_string()]); + assert!(files(&r).iter().any(|f| f.ends_with("material_ball_a.mtlx")), "{r}"); +} + +#[test] +fn reserved_names_must_be_a_list_of_names() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let dir = temp("bad-reserved"); + for bad in [json!("a.png"), json!([1])] { + let params = json!({"dir": dir.display().to_string(), "preset": OPENPBR, "reservedNames": bad}); + assert!(execute(&mut s, "file.exportTextures", ¶ms).is_err()); + } +} + #[test] fn float_colour_maps_are_tagged_linear() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index f64498b0..4eeca695 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -326,6 +326,10 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let set = || ConsoleLine::Set(name.clone()); app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); + // The files of the earlier texture sets keep their names, the material's extra maps and .mtlx files included + if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) { + params["reservedNames"] = json!(job.written); + } let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 59d379cb..099dcc5c 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -149,3 +149,75 @@ fn a_warning_every_texture_set_raises_shows_once_in_the_console_and_the_log() { assert_eq!(h.state().session.log.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1); let _ = std::fs::remove_dir_all(&dir); } + +/// A template with one map, the base colour, named `$mesh_$textureSet` (no input suffix) +fn base_colour_template() -> texturecraft_engine::formats::ExportPreset { + use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; + let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component }; + ExportPreset { + name: "base colour only".into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))], + inverted: Vec::new(), + }], + } +} + +/// The base colour of texture set `ts` as the template writes it, from a plain export +fn expected(h: &mut Harness<'static, TextureCraftApp>, ts: usize, preset: &str, file: &str, tag: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("tc-export-materialx-expected-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let params = serde_json::json!({"dir": dir.display().to_string(), "preset": preset, "ts": ts}); + texturecraft_engine::execute(&mut h.state_mut().session, "file.exportTextures", ¶ms).unwrap(); + let bytes = std::fs::read(dir.join(file)).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + bytes +} + +#[test] +fn texture_sets_of_one_export_never_overwrite_each_others_files() { + const SHARED: &str = "material_ball_a_base_color.png"; + + // (names of set 0 and set 1, the template whose export of set 0 must be what SHARED holds, + // the material that refers to SHARED) + let cases = [ + // Set 0's own file has the name set 1's OpenPBR base colour would get + ("a_base_color", "a", "base colour only", None), + // Set 0's OpenPBR base colour has the name set 1's own file would get + ("a", "a_base_color", "OpenPBR (separate maps)", Some("material_ball_a.mtlx")), + ]; + for (index, (first, second, template_of_set_0, referred_by)) in cases.into_iter().enumerate() { + let (mut h, dir) = harness(&format!("overwrite-{index}")); + let project = &mut h.state_mut().session.doc.project; + project.texture_sets[0].name = first.into(); + project.texture_sets[1].name = second.into(); + let template = base_colour_template(); + let name = template.name.clone(); + h.state_mut().session.export_presets.list.push(template); + h.state_mut().ui.export.preset = name; + h.run_steps(3); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let want = expected(&mut h, 0, template_of_set_0, SHARED, &index.to_string()); + assert_eq!(std::fs::read(dir.join(SHARED)).unwrap(), want, "case {index}: the earlier texture set's file was replaced"); + + // A material only points at files that exist, and only the earlier set's material at SHARED + let materials = mtlx_files(&dir); + assert_eq!(materials.len(), 2, "{materials:?}"); + for material in materials { + let text = std::fs::read_to_string(&material).unwrap(); + let file_name = material.file_name().unwrap().to_string_lossy().into_owned(); + for reference in text.split("name=\"file\" type=\"filename\" value=\"").skip(1) { + let name = reference.split('"').next().unwrap(); + assert!(dir.join(name).is_file(), "case {index}: {name} is missing"); + assert!(name != SHARED || referred_by == Some(file_name.as_str()), "case {index}: {file_name} refers to {name}"); + } + } + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8d6ed911..71c61b40 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -50,6 +50,11 @@ and warn about later duplicates. The desktop export window reports the collision `file.exportTextures` with `materialX: true` also writes a `.mtlx` OpenPBR material per texture set. A template without OpenPBR file names gets the maps of the "OpenPBR (separate maps)" template written beside its own files for it; the `maps` overrides above do not reach those maps. +`reservedNames: [file names]` lists the files earlier `file.exportTextures` commands of the same +export wrote (the export window runs one command per texture set and passes it). The command +compares them ignoring case, does not write a file, an OpenPBR map or a `.mtlx` of such a name, +and names it in `warnings`; a material leaves out the input of a map it did not write. Without it +nothing is reserved. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for diff --git a/docs/features.md b/docs/features.md index 4e3d40d3..0cf74ec4 100644 --- a/docs/features.md +++ b/docs/features.md @@ -183,8 +183,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA template is selected: a template without OpenPBR file names gets the maps of *OpenPBR (separate maps)* written beside its own files, with the export's size, padding, colour space, file type and bit depth (PNG when that file type has no use in a material) and always an OpenGL normal - map. Not covered yet: MaterialX standard_surface, Coat Normal, Specular Level, Anisotropy - Angle and constants such as IOR. In the browser the option is greyed. + map. A file of one texture set never replaces a file of an earlier one in the same export, the + material's maps included. Not covered yet: MaterialX standard_surface, Coat Normal, Specular + Level, Anisotropy Angle and constants such as IOR. In the browser the option is greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). From ff79e861f82ff615a797920eb054e676328e361b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 14:45:41 -0500 Subject: [PATCH 059/153] revert: restore scheduled release.yml dry-run on main (#787) --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6a6f238d..c8c04b32 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,7 +27,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: - nightly: ${{ github.event_name == 'schedule' }} + dry-run: ${{ github.event_name == 'schedule' }} app-name: texturecraft app-title: "TextureCraft" craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc From 94daa7370ce7c7631f2e72994f753d93ba476c13 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:33:42 +0100 Subject: [PATCH 060/153] Name the file in the MaterialX map warning and check reservedNames before creating the folder --- crates/engine/src/file_cmds.rs | 15 +++++++-------- crates/engine/tests/it/materialx.rs | 5 +++-- crates/ui-egui/tests/it/export_materialx.rs | 17 +++++++++++++---- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 1f8d2415..86837a42 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -640,8 +640,8 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let dir = native::path_param(p, "dir", "file.exportTextures")?.to_string(); let opts = export_options(s, p, "file.exportTextures")?; let sets = sets_param(s, p, "file.exportTextures")?; - std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let reserved = reserved_names(p)?; + std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let files = s.export_files(&sets, &opts)?; // A file an earlier command of the same export wrote keeps its name: the export window runs @@ -664,7 +664,7 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let material_opts = extra.as_ref().unwrap_or(&opts); if extra.is_some() { taken.extend(own); - let mut maps = s.export_files(&sets, material_opts)?; + let maps = s.export_files(&sets, material_opts)?; for file in &maps { for warning in &file.warnings { if !warnings.contains(warning) { @@ -674,12 +674,11 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { } // A file of the chosen template, or of an earlier command of this export, is never replaced; the material leaves out the map it would have used - let before = maps.len(); - maps.retain(|f| !taken.contains(&f.name.to_ascii_lowercase())); - if maps.len() < before { - warnings - .push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template or of an earlier file of this export, so the material does not use it".into()); - } + let (kept, dropped): (Vec<_>, Vec<_>) = maps.into_iter().partition(|f| !taken.contains(&f.name.to_ascii_lowercase())); + warnings.extend(dropped.iter().map(|f| { + format!("MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name, so the material does not use it", f.name) + })); + let maps = kept; written.extend(texturecraft_formats::write_files(&maps, std::path::Path::new(&dir)).map_err(fe)?); } written.extend(write_materialx(s, &sets, material_opts, std::path::Path::new(&dir), &mut warnings, taken, extra.is_some())?); diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index f1979d38..2836f7c5 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -244,7 +244,7 @@ fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() { let dir = temp("clash"); let r = execute(&mut s, "file.exportTextures", ¶ms(&dir, true)).unwrap(); assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), std::fs::read(plain.join("material_ball_a_base_color.png")).unwrap()); - assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("file name of a map of the chosen template")), "{r}"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("material_ball_a_base_color.png\" was not written")), "{r}"); let first = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); assert!(!referenced(&first).contains(&"material_ball_a_base_color.png".to_string()), "{first}"); } @@ -288,7 +288,7 @@ fn an_openpbr_map_never_replaces_a_file_an_earlier_command_of_the_export_wrote() let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(); let second = export_set(&mut s, &dir, 1, &names(&first)); assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched"); - assert!(warned(&second, "has the file name of a map of the chosen template or of an earlier file of this export"), "{second}"); + assert!(warned(&second, "\"material_ball_a_base_color.png\" was not written: a file of the chosen template or of an earlier command"), "{second}"); let material = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap(); assert!(!referenced(&material).contains(&"material_ball_a_base_color.png".to_string()), "{material}"); for file in referenced(&material) { @@ -337,6 +337,7 @@ fn reserved_names_must_be_a_list_of_names() { let params = json!({"dir": dir.display().to_string(), "preset": OPENPBR, "reservedNames": bad}); assert!(execute(&mut s, "file.exportTextures", ¶ms).is_err()); } + assert!(!dir.exists(), "a bad parameter creates no folder"); } #[test] diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 099dcc5c..424de7a8 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -182,14 +182,14 @@ fn texture_sets_of_one_export_never_overwrite_each_others_files() { const SHARED: &str = "material_ball_a_base_color.png"; // (names of set 0 and set 1, the template whose export of set 0 must be what SHARED holds, - // the material that refers to SHARED) + // the template whose export of set 1 would replace it, the material that refers to SHARED) let cases = [ // Set 0's own file has the name set 1's OpenPBR base colour would get - ("a_base_color", "a", "base colour only", None), + ("a_base_color", "a", "base colour only", "OpenPBR (separate maps)", None), // Set 0's OpenPBR base colour has the name set 1's own file would get - ("a", "a_base_color", "OpenPBR (separate maps)", Some("material_ball_a.mtlx")), + ("a", "a_base_color", "OpenPBR (separate maps)", "base colour only", Some("material_ball_a.mtlx")), ]; - for (index, (first, second, template_of_set_0, referred_by)) in cases.into_iter().enumerate() { + for (index, (first, second, template_of_set_0, template_of_set_1, referred_by)) in cases.into_iter().enumerate() { let (mut h, dir) = harness(&format!("overwrite-{index}")); let project = &mut h.state_mut().session.doc.project; project.texture_sets[0].name = first.into(); @@ -204,8 +204,17 @@ fn texture_sets_of_one_export_never_overwrite_each_others_files() { export(&mut h); let want = expected(&mut h, 0, template_of_set_0, SHARED, &index.to_string()); + let rival = expected(&mut h, 1, template_of_set_1, SHARED, &format!("{index}-rival")); + assert_ne!(want, rival, "case {index}: the two files differ, so a replacement shows"); assert_eq!(std::fs::read(dir.join(SHARED)).unwrap(), want, "case {index}: the earlier texture set's file was replaced"); + let console = h.state().ui.export.console.iter().filter_map(|line| if let ConsoleLine::Step(text) = line { Some(text.as_str()) } else { None }); + assert!( + console.clone().any(|text| text.starts_with("Warning: ") && text.contains("\"material_ball_a_base_color.png\" was not written")), + "case {index}: {:?}", + console.collect::>() + ); + // A material only points at files that exist, and only the earlier set's material at SHARED let materials = mtlx_files(&dir); assert_eq!(materials.len(), 2, "{materials:?}"); From c0523d2f68336ad9855dc9813bd4041bbe3f07a3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 20:40:46 +0100 Subject: [PATCH 061/153] Write the model as a USD file that uses the exported textures from the export window --- Cargo.lock | 2 + crates/engine/Cargo.toml | 1 + crates/engine/src/file_cmds.rs | 75 +++- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/usd_asset.rs | 319 ++++++++++++++ crates/formats/README.md | 8 + crates/formats/src/export/mod.rs | 2 +- crates/formats/src/lib.rs | 5 +- crates/formats/src/mesh_export.rs | 2 +- crates/formats/src/mesh_export/usd.rs | 440 +++++++++++++++++++- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/export_window.rs | 45 +- crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/state/export_job.rs | 5 + crates/ui-egui/tests/it/export_usd_asset.rs | 211 ++++++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/side_panels.rs | 3 +- docs/control-protocol.md | 12 + docs/features.md | 13 + docs/ui-parity.md | 6 +- 20 files changed, 1138 insertions(+), 19 deletions(-) create mode 100644 crates/engine/tests/it/usd_asset.rs create mode 100644 crates/ui-egui/tests/it/export_usd_asset.rs diff --git a/Cargo.lock b/Cargo.lock index 84a1a752..18976898 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5173,6 +5173,7 @@ name = "texturecraft-engine" version = "0.6.1" dependencies = [ "chrono", + "craft-usd", "epaint_default_fonts", "image", "processkit", @@ -5292,6 +5293,7 @@ dependencies = [ "craft-quit", "craft-ui", "craft-update", + "craft-usd", "craft-window", "eframe", "egui", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b6082f63..52b37891 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -37,5 +37,6 @@ tokio = { workspace = true } rustix = { workspace = true } [dev-dependencies] +craft-usd.workspace = true image = { workspace = true } zip = { workspace = true } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..43dc4087 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts and options, a list gives each texture set's own `ts` and options, the export window sends it with the last command; a failure is a warning)}", always, export_textures ), @@ -640,6 +640,7 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let dir = native::path_param(p, "dir", "file.exportTextures")?.to_string(); let opts = export_options(s, p, "file.exportTextures")?; let sets = sets_param(s, p, "file.exportTextures")?; + let usd_asset = usd_asset_param(s, p, &opts, &sets)?; std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; let files = s.export_files(&sets, &opts)?; let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); @@ -647,10 +648,82 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?); } + if let Some(exports) = &usd_asset { + written.extend(write_usd_asset(s, std::path::Path::new(&dir), exports, &mut warnings)); + } s.log.info("MapExporter", format!("Exported {} textures to {dir}", written.len())); Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::>(), "warnings": warnings })) } +/// What the warning of a USD asset that could not be written starts with (`file.exportTextures`). +pub const USD_ASSET_FAILED: &str = "The USD asset was not written"; + +/// The texture sets and options of the exports a USD asset refers to. +#[cfg(not(target_arch = "wasm32"))] +type UsdExports = Vec<(Vec, ExportOptions)>; + +/// What `usdAsset` asks for: the texture sets and options of each export whose textures the USD +/// asset refers to. `true` is this command's own; a list gives every entry's `ts` and options. +#[cfg(not(target_arch = "wasm32"))] +fn usd_asset_param(s: &Session, p: &Value, opts: &ExportOptions, sets: &[usize]) -> Result> { + match p.get("usdAsset") { + None | Some(Value::Null | Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(vec![(sets.to_vec(), opts.clone())])), + Some(Value::Array(exports)) if !exports.is_empty() && exports.iter().all(Value::is_object) => exports + .iter() + .map(|export| Ok((sets_param(s, export, "file.exportTextures")?, export_options(s, export, "file.exportTextures")?))) + .collect::>>() + .map(Some), + Some(_) => Err(bad("file.exportTextures", "`usdAsset` must be true, false or a non-empty list of export param objects")), + } +} + +/// `.usd` (binary USD) next to the textures: the whole mesh (every texture set, not only the sets of this +/// command) with a UsdPreviewSurface material per texture set that reads the files `exports` +/// wrote (see `texturecraft_formats::usd_texture_bindings`). A failure to build or write it is a +/// warning: the textures of the command are already written. +#[cfg(not(target_arch = "wasm32"))] +fn write_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, ExportOptions)], warnings: &mut Vec) -> Option { + match build_usd_asset(s, dir, exports) { + Ok(path) => Some(path), + Err(e) => { + warnings.push(format!("{USD_ASSET_FAILED}: {e}")); + None + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn build_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, ExportOptions)]) -> Result { + use texturecraft_formats::{export::list_set_outputs, usd_layer_with_textures, usd_texture_bindings}; + let project = &s.doc.project; + let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); + + // The bindings of every texture set that was exported, from the files its export planned + let mut taken = std::collections::HashSet::new(); + let mut by_set = std::collections::HashMap::new(); + for (sets, opts) in exports { + // A file whose name an earlier export of this job has was not written by this one + let planned: Vec<_> = list_set_outputs(project, sets, &mesh_name, opts) + .map_err(fe)? + .into_iter() + .filter(|(_, file)| taken.insert(file.name.to_ascii_lowercase())) + .collect(); + for &set in sets { + let files: Vec<_> = planned.iter().filter(|(ts, _)| *ts == set).map(|(_, file)| file.clone()).collect(); + let texture_set = project.texture_set(set).map_err(|e| EngineError::Other(e.to_string()))?; + by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, opts, project.normal_format, &files)); + } + } + + let mesh = s.source_mesh(); + let bindings: Vec<_> = (0..mesh.materials.len()).map(|m| s.texture_set_of_material(m).and_then(|set| by_set.remove(&set)).unwrap_or_default()).collect(); + let layer = usd_layer_with_textures(&mesh, &project.name, &bindings).map_err(fe)?; + let path = dir.join(format!("{}.usd", texturecraft_formats::export::sanitize_file_stem(&mesh_name))); + texturecraft_formats::write_atomic(&path, &layer).map_err(fe)?; + Ok(path) +} + /// One `_.mtlx` per texture set, next to the textures `opts` just wrote: the /// OpenPBR inputs those textures feed (see `texturecraft_formats::materialx`). UDIM sets name /// their files with the `` token. Sets with no recognised map, or whose name gives the diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c38e850b..ce9f1614 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -66,5 +66,6 @@ mod tool_availability; mod tool_settings; mod tools; mod udim; +mod usd_asset; mod user_smart_mask; mod uv_strokes; diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs new file mode 100644 index 00000000..3c6458a4 --- /dev/null +++ b/crates/engine/tests/it/usd_asset.rs @@ -0,0 +1,319 @@ +//! `file.exportTextures` with `usdAsset`: `.usd` next to the textures, the whole mesh with +//! a material per texture set that reads the textures the export wrote. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn temp(tag: &str) -> Scratch { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("tc_usd_asset_{tag}_{}_{seq}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Scratch(dir) +} + +fn ball() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +fn files(r: &Value) -> Vec { + r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect() +} + +fn export(s: &mut Session, dir: &std::path::Path, params: Value) -> Value { + let mut params = params; + params["dir"] = json!(dir.display().to_string()); + execute(s, "file.exportTextures", ¶ms).unwrap() +} + +/// What a UsdPreviewSurface input reads +#[derive(Debug, PartialEq, Clone)] +struct Read { + file: String, + output: String, + colour_space: String, + /// The texture shader flips green (a DirectX normal map) + flips_green: bool, +} + +/// The prim name the exporter gives a mesh material +fn identifier(name: &str) -> String { + let mut id: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); + if !id.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') { + id.insert(0, '_'); + } + id +} + +/// The binary USD file read back: per mesh material, the inputs of its UsdPreviewSurface that read a texture, and the number of texture shaders +fn materials(bytes: &[u8], mesh_materials: &[String]) -> Vec<(BTreeMap, usize)> { + use craft_usd::scene::Val; + let layer = craft_usd::scene::read_layer(bytes).unwrap(); + let prim = |path: &str| layer.prims.iter().find(|p| p.path == path).unwrap_or_else(|| panic!("no prim {path}")); + let first = |prop: Option<&craft_usd::scene::Prop>| match prop.and_then(|p| p.value.as_ref()) { + Some(Val::Tok(values)) => values.first().cloned().unwrap_or_default(), + other => panic!("not a token or an asset: {other:?}"), + }; + mesh_materials + .iter() + .map(|name| { + let id = identifier(name); + let material = layer.prims.iter().find(|p| p.type_name == "Material" && p.name == id).unwrap_or_else(|| panic!("no material {id}")); + let pbr = prim(&format!("{}/PBR", material.path)); + let mut inputs = BTreeMap::new(); + for (key, prop) in &pbr.props { + let (Some(input), Some(source)) = (key.strip_prefix("inputs:"), &prop.connect) else { continue }; + let (shader, output) = source.rsplit_once('/').unwrap().1.split_once(".outputs:").unwrap(); + let texture = prim(&format!("{}/{shader}", material.path)); + let flips_green = match texture.props.get("inputs:scale").and_then(|p| p.value.as_ref()) { + Some(Val::Num(scale)) => scale.get(1).is_some_and(|green| *green < 0.0), + _ => false, + }; + let read = Read { + file: first(texture.props.get("inputs:file")).trim_start_matches("./").to_string(), + output: output.into(), + colour_space: first(texture.props.get("inputs:sourceColorSpace")), + flips_green, + }; + inputs.insert(input.to_string(), read); + } + let prefix = format!("{}/", material.path); + (inputs, layer.prims.iter().filter(|p| p.path.starts_with(&prefix) && p.props.contains_key("inputs:file")).count()) + }) + .collect() +} + +/// The materials of `

/material_ball.usd`, indexed by mesh material +fn read_back(s: &Session, dir: &std::path::Path) -> Vec<(BTreeMap, usize)> { + let materials = materials(&std::fs::read(dir.join("material_ball.usd")).unwrap(), &s.mesh.materials); + assert_eq!(materials.len(), s.set_count()); + materials +} + +fn material_of(s: &Session, set: usize) -> usize { + s.doc.project.texture_sets[set].material +} + +#[test] +fn it_writes_the_mesh_with_materials_that_read_the_exported_textures() { + let mut s = ball(); + assert!(s.set_count() > 1, "the test needs several texture sets"); + let dir = temp("default"); + let r = export(&mut s, &dir, json!({"usdAsset": true})); + assert!(files(&r).iter().any(|f| f.ends_with("material_ball.usd")), "the asset is listed: {r}"); + + let materials = read_back(&s, &dir); + for set in 0..s.set_count() { + let name = &texturecraft_formats::export::sanitize_file_stem(&s.doc.project.texture_sets[set].name); + let inputs = &materials[material_of(&s, set)].0; + let read = |input: &str| inputs.get(input).unwrap_or_else(|| panic!("{input} of {name}: {inputs:?}")).clone(); + for (input, output, space) in [("diffuseColor", "rgb", "sRGB"), ("roughness", "r", "raw"), ("metallic", "r", "raw"), ("normal", "rgb", "raw")] { + let read = read(input); + assert_eq!((read.output.as_str(), read.colour_space.as_str()), (output, space), "{input} of {name}"); + assert!(read.file.starts_with(&format!("material_ball_{name}_")), "{input} reads a file of its own texture set: {}", read.file); + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + assert!(!read.flips_green, "the project's normals are OpenGL"); + } + assert!(!inputs.contains_key("opacity") && !inputs.contains_key("clearcoat"), "channels the set does not have stay unbound: {inputs:?}"); + } +} + +#[test] +fn a_packed_template_reads_different_outputs_of_one_file() { + let mut s = ball(); + let dir = temp("packed"); + export(&mut s, &dir, json!({"preset": "Unreal Engine (Packed)", "usdAsset": true})); + + for (inputs, shaders) in read_back(&s, &dir) { + assert_eq!(shaders, 3, "four inputs read three files: {inputs:?}"); + let (roughness, metallic) = (&inputs["roughness"], &inputs["metallic"]); + assert_eq!(roughness.file, metallic.file, "{inputs:?}"); + assert!(roughness.file.contains("OcclusionRoughnessMetallic"), "{}", roughness.file); + assert_eq!((roughness.output.as_str(), metallic.output.as_str()), ("g", "b")); + assert_ne!(inputs["diffuseColor"].file, roughness.file); + + // The template writes DirectX normals + assert!(inputs["normal"].flips_green, "{inputs:?}"); + assert!(!inputs.contains_key("opacity"), "the base colour file has no alpha without an opacity channel"); + } +} + +#[test] +fn the_normal_convention_of_the_files_decides_whether_green_is_flipped() { + let mut s = ball(); + let (open_gl, direct_x) = (temp("normal-gl"), temp("normal-dx")); + export(&mut s, &open_gl, json!({"usdAsset": true, "normalFormat": "openGl"})); + export(&mut s, &direct_x, json!({"usdAsset": true, "normalFormat": "directX"})); + for (inputs, _) in read_back(&s, &open_gl) { + assert!(!inputs["normal"].flips_green); + } + for (inputs, _) in read_back(&s, &direct_x) { + assert!(inputs["normal"].flips_green); + } +} + +#[test] +fn a_texture_set_outside_the_export_has_no_textures() { + let mut s = ball(); + let dir = temp("subset"); + export(&mut s, &dir, json!({"ts": 0, "usdAsset": true})); + + let materials = read_back(&s, &dir); + assert!(!materials[material_of(&s, 0)].0.is_empty()); + assert!(materials[material_of(&s, 1)].0.is_empty(), "{:?}", materials[material_of(&s, 1)]); + let name = texturecraft_formats::export::sanitize_file_stem(&s.doc.project.texture_sets[1].name); + assert!(!std::fs::read_dir(&*dir).unwrap().flatten().any(|e| e.file_name().to_string_lossy().contains(&format!("_{name}_"))), "set 1 was not written"); +} + +#[test] +fn a_list_gives_each_texture_set_its_own_options() { + let mut s = ball(); + let dir = temp("list"); + export(&mut s, &dir, json!({"ts": 0})); + let list = json!([{"ts": 0}, {"ts": 1, "preset": "Unreal Engine (Packed)"}]); + export(&mut s, &dir, json!({"ts": 1, "preset": "Unreal Engine (Packed)", "usdAsset": list})); + + let materials = read_back(&s, &dir); + let first = &materials[material_of(&s, 0)].0; + let second = &materials[material_of(&s, 1)].0; + assert_eq!(first["roughness"].output, "r", "{first:?}"); + assert_eq!(second["roughness"].output, "g", "{second:?}"); + for read in first.values().chain(second.values()) { + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + } +} + +#[test] +fn it_is_not_written_unless_asked_for() { + let mut s = ball(); + let dir = temp("off"); + let off = export(&mut s, &dir, json!({})); + let explicit = export(&mut s, &dir, json!({"usdAsset": false})); + for r in [off, explicit] { + assert!(!files(&r).is_empty(), "the textures are written"); + assert!(!files(&r).iter().any(|f| f.ends_with(".usd")), "{r}"); + } + assert!(!dir.join("material_ball.usd").exists()); +} + +#[test] +fn a_failure_to_write_it_is_a_warning_and_the_textures_are_still_reported() { + let mut s = ball(); + let dir = temp("blocked"); + + // A folder where the file belongs: the asset cannot be written there + std::fs::create_dir_all(dir.join("material_ball.usd")).unwrap(); + let r = export(&mut s, &dir, json!({"usdAsset": true})); + + assert!(!files(&r).iter().any(|f| f.ends_with(".usd")), "{r}"); + assert!(files(&r).iter().any(|f| f.ends_with(".png")), "the textures are reported: {r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().unwrap().starts_with("The USD asset was not written")), "{r}"); + assert!(dir.join("material_ball.usd").is_dir()); +} + +#[test] +fn the_asset_opens_again_with_its_textures_from_the_folder() { + let mut s = ball(); + let dir = temp("roundtrip"); + export(&mut s, &dir, json!({"usdAsset": true})); + + // The importer reads only the texture of the base colour, but every input the file binds reads a file of the folder + for (inputs, _) in read_back(&s, &dir) { + assert!(inputs.len() >= 4, "{inputs:?}"); + for read in inputs.values() { + assert!(dir.join(&read.file).is_file(), "{} is in the folder", read.file); + } + } + + let file = texturecraft_formats::read_mesh_file(&dir.join("material_ball.usd")).unwrap(); + assert!(file.warnings.is_empty(), "every texture it names is in the folder: {:?}", file.warnings); + assert!(file.name.ends_with(".usdz"), "the base colour texture is found and packaged: {}", file.name); + let package = zip::ZipArchive::new(std::io::Cursor::new(&file.bytes)).unwrap(); + assert!(package.file_names().any(|name| name.is_ok_and(|name| name.ends_with(".png")))); + + let back = texturecraft_formats::import_mesh_bytes(&file.name, &file.bytes).unwrap(); + assert_eq!(back.mesh.triangle_count(), s.mesh.triangle_count()); + assert_eq!(back.mesh.materials.len(), s.set_count()); +} + +#[test] +fn a_bad_usd_asset_value_is_an_error_before_anything_is_written() { + let mut s = ball(); + for value in [json!("x"), json!([]), json!([1]), json!([{"ts": 0}, "x"]), json!([{"ts": 99}]), json!({"ts": 0})] { + let dir = temp("bad"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "usdAsset": value})); + assert!(r.is_err(), "{value}"); + assert!(!dir.exists(), "nothing was written for {value}"); + } +} + +#[test] +fn the_tiles_of_a_uv_tiled_set_are_read_through_one_udim_name() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let dir = temp("udim"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &s.mesh.materials); + let colour = &materials[0].0["diffuseColor"]; + assert!(colour.file.ends_with("..png"), "{}", colour.file); + for tile in ["1001", "1002"] { + assert!(dir.join(colour.file.replace("", tile)).is_file(), "tile {tile} was written"); + } +} + +/// A template with one map, the base colour, whose name does not tell texture sets apart +fn shared_name_template() -> Value { + let rgb: Vec = (0..3) + .map(|k| { + let dest = ["R", "G", "B"][k]; + json!([dest, {"Channel": {"channel": "BaseColor", "component": k}}]) + }) + .collect(); + json!({"name": "shared", "maps": [{"file": "colour", "format": "Png", "bit_depth": 8, "channels": rgb}]}) +} + +#[test] +fn a_file_name_an_earlier_export_of_the_job_has_is_not_read_by_a_later_one() { + let mut s = ball(); + let dir = temp("same-name"); + let list = json!([{"ts": 0, "preset": shared_name_template()}, {"ts": 1, "preset": shared_name_template()}]); + export(&mut s, &dir, json!({"ts": 1, "preset": shared_name_template(), "usdAsset": list})); + + let materials = read_back(&s, &dir); + assert_eq!(materials[material_of(&s, 0)].0["diffuseColor"].file, "colour.png"); + assert!(materials[material_of(&s, 1)].0.is_empty(), "the later set's file would have replaced the earlier one: {:?}", materials[material_of(&s, 1)]); +} + +#[test] +fn a_material_without_a_texture_set_has_no_textures() { + let mut s = ball(); + + // Both texture sets paint the first material (which the first set stands for): the second has none + s.doc.project.texture_sets[1].material = 0; + let dir = temp("no-set"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = read_back(&s, &dir); + assert!(!materials[0].0.is_empty()); + assert!(materials[1].0.is_empty(), "{:?}", materials[1]); +} diff --git a/crates/formats/README.md b/crates/formats/README.md index 4033b1be..f56dbc36 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -52,6 +52,9 @@ pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format pub fn usd_export_options() -> ExportOptions; // render each material's textures with these pub enum UsdFormat { Usda, Usdc, Usdz } pub struct UsdExport { pub bytes: Vec, pub textures: Vec<(String, Vec)> } // textures: usda/usdc only +pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec; // which UsdPreviewSurface input reads which output of which exported file +pub fn usd_layer_with_textures(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result>; // binary `.usd` (Crate) only; material m reads bindings[m] as ./ +pub struct UsdTextureBinding { /* opaque */ } ``` OBJ export propagates shared writer validation and limit errors rather than returning empty bytes. @@ -65,6 +68,11 @@ emissive maps dropped, and both clear coat maps when the coat is black). Meters, `.usdc` is a Crate 0.8.0 file; `.usdz` is that layer first plus the PNGs, stored uncompressed at 64-byte aligned offsets; `.usda` / `.usdc` reference `__.png` next to the layer. +`usd_layer_with_textures` writes the same scene as a binary `.usd` (Crate) whose materials read texture files the +caller already wrote (the Export textures window's USD asset): `usd_texture_bindings` binds base +color, roughness, metallic, normal (scale/bias for the file's green convention), emissive color, +opacity, clear coat and clear coat roughness by what each map of the template holds, each reading +the `rgb`, `r`, `g`, `b` or `a` output of its file; one texture shader per file, so packed maps work. GLB: one primitive per submesh, one metallic-roughness material per mesh material with its textures embedded in the binary chunk (base color sRGB, `alphaMode: BLEND` when it has alpha; diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index cdcb9c36..35edb66a 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -514,7 +514,7 @@ fn normal_present(set: &TextureSet) -> bool { } /// A source with real data in this texture set (constants never count). -fn source_present(set: &TextureSet, s: &SourceRef) -> bool { +pub(crate) fn source_present(set: &TextureSet, s: &SourceRef) -> bool { match s { SourceRef::Channel { channel: Channel::Normal, .. } => normal_present(set), SourceRef::Channel { channel, .. } => set.has_channel(*channel), diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 3fd12036..8dc7d67e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -46,7 +46,10 @@ pub use export::{ render_maps, skip_repeated_names, }; pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource}; -pub use mesh_export::{GlbTextures, NamedFiles, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options}; +pub use mesh_export::{ + GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, + usd_layer_with_textures, usd_texture_bindings, +}; pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index d35156a9..4cc3b24e 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -15,7 +15,7 @@ use crate::export::sanitize_file_stem; use crate::presets::{GLTF_BASE_COLOR, GLTF_CLEARCOAT, GLTF_EMISSIVE, GLTF_NORMAL, GLTF_ORM, GLTF_SHEEN, gltf_pbr_maps}; use crate::{ExportOptions, ExportPreset, ExportedFile, FileFormat, FormatError, Result}; -pub use usd::{NamedFiles, UsdExport, UsdFormat, usd_bytes, usd_export_options}; +pub use usd::{NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings}; /// The mesh as OBJ text (UV v flipped back to OBJ's bottom-up convention). /// Invalid mesh data or shared writer limits return an error, never an empty successful export. diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index ee1a7166..c9ace034 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -6,11 +6,15 @@ //! UsdUVTexture shaders. Meters, Y up. use craft_usd::scene::{SceneError, UsdAttr, UsdLayer, UsdPrim, UsdValue, write_usda, write_usdc}; -use texturecraft_core::{Channel, NormalFormat}; +use texturecraft_core::{Channel, NormalFormat, TextureSet}; use texturecraft_geom::Mesh; +use texturecraft_texel::ColorSpace; + use super::{is_black, parts}; -use crate::export::{ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, VirtualMap, sanitize_file_stem}; +use crate::export::{ + Dest, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, PlannedFile, SourceRef, VirtualMap, sanitize_file_stem, source_present, +}; use crate::presets::{ch, gray, rgb, virt}; use crate::{FormatError, Result}; @@ -103,9 +107,9 @@ fn identifier(s: &str, taken: &mut Vec) -> String { id } -/// The export scene: `/` with the `Mesh` and `Materials`. `files[m]` are the texture -/// file names (by slot) of material `m`. -fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result { +/// The export scene: `/` with the `Mesh` and `Materials`. `material(m, path, id)` makes the +/// Material prim `id` at `path` for mesh material `m`. +fn scene(mesh: &Mesh, name: &str, material: impl Fn(usize, &str, &str) -> UsdPrim) -> Result { let vertex_count = mesh.positions.len(); if vertex_count == 0 || mesh.indices.len() < 3 { return Err(FormatError::Invalid("the mesh is empty".into())); @@ -177,7 +181,7 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result UsdPrim { pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format: UsdFormat) -> Result { let stem = sanitize_file_stem(name); let (names, files) = material_maps(mesh, &stem, textures); - let layer = scene(mesh, name, &names)?; + let layer = scene(mesh, name, |m, path, id| material(path, id, names.get(m).map_or(&[][..], Vec::as_slice)))?; Ok(match format { UsdFormat::Usda => UsdExport { bytes: write_usda(&layer).into_bytes(), textures: files }, UsdFormat::Usdc => UsdExport { bytes: write_usdc(&layer).map_err(map_scene_err)?, textures: files }, @@ -291,6 +295,219 @@ pub(crate) fn usdz(layer_name: &str, layer: &[u8], files: &[(String, Vec)]) zip.finish().map_err(err) } +/// A UsdPreviewSurface input that reads a texture file the export wrote. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdTextureBinding { + /// The input, as an index into the table of UsdPreviewSurface inputs (`SLOTS`). + slot: usize, + /// The file name, `` for a UV-tiled set's tiles. + file: String, + /// The texture output the input reads: `r`, `g`, `b`, `a` or `rgb`. + output: &'static str, + /// The file holds sRGB-encoded colour. + srgb: bool, + /// A normal map: the green convention of its file. + normal: Option, +} + +/// Whether `source` is what UsdPreviewSurface input `slot` (an index into [`SLOTS`]) reads. +fn feeds_slot(slot: usize, source: &SourceRef) -> bool { + let channel = match (slot, source) { + (1, SourceRef::Virtual { map: VirtualMap::Roughness, .. }) => return true, + (3, SourceRef::Virtual { map: VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX, .. }) => return true, + (_, SourceRef::Channel { channel, .. }) => *channel, + _ => return false, + }; + let wanted = match slot { + 0 => Channel::BaseColor, + 1 => Channel::Roughness, + 2 => Channel::Metallic, + 3 => Channel::Normal, + 4 => Channel::Emissive, + 5 => Channel::Opacity, + 6 => Channel::CoatWeight, + _ => Channel::CoatRoughness, + }; + channel == wanted +} + +fn component_of(source: &SourceRef) -> u8 { + match source { + SourceRef::Channel { component, .. } | SourceRef::Virtual { component, .. } | SourceRef::Baked { component, .. } => *component, + SourceRef::Constant(_) => 0, + } +} + +/// The texture output of `map` that input `slot` reads, and the source it takes: a colour or +/// normal input needs the three components in R, G and B, a scalar input reads the destination +/// that holds it. None when the map does not hold the input, when `set` has no data for it (the +/// file then holds a default), when it is written inverted, or when `format` cannot keep it: JPEG +/// and HDR files drop alpha, a PGM file holds one gray channel (a colour map becomes its +/// luminance), which only a map written as L can bind. +fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: FileFormat) -> Option<(&'static str, &'m SourceRef)> { + let holds = |dest: Dest, component: Option| { + map.channels + .iter() + .find(|(d, source)| { + *d == dest + && feeds_slot(slot, source) + && source_present(set, source) + && component.is_none_or(|k| component_of(source) == k) + && !map.inverted.contains(d) + }) + .map(|(_, source)| source) + }; + if SLOTS[slot].2 == "float" { + return [(Dest::R, "r"), (Dest::L, "r"), (Dest::G, "g"), (Dest::B, "b"), (Dest::A, "a")] + .into_iter() + .filter(|(dest, _)| match format { + FileFormat::Pgm => *dest == Dest::L, + FileFormat::Jpeg | FileFormat::Hdr => *dest != Dest::A, + _ => true, + }) + .find_map(|(dest, output)| holds(dest, None).map(|source| (output, source))); + } + + if format == FileFormat::Pgm { + return None; + } + + let red = holds(Dest::R, Some(0))?; + holds(Dest::G, Some(1))?; + holds(Dest::B, Some(2))?; + Some(("rgb", red)) +} + +/// The UsdPreviewSurface inputs the exported `files` of texture set `set` (planned with `opts`) +/// can feed, by what each map holds: base colour, roughness, metallic, normal, emissive colour, +/// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion, +/// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has +/// no data for. `project_normal` is the project's normal convention, used by normal maps that +/// follow it. +pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec { + let mut out: Vec = Vec::new(); + let mut seen_maps = Vec::new(); + for file in files { + // The first tile stands for all the tiles of a map + if seen_maps.contains(&file.map) { + continue; + } + + seen_maps.push(file.map); + let Some(map) = opts.preset.maps.get(file.map) else { continue }; + + // A tile whose name has no `` token cannot stand for the others + let name = match (&file.udim_name, file.tile) { + (Some(udim), _) => udim.clone(), + (None, None) => file.name.clone(), + (None, Some(_)) => continue, + }; + let srgb = opts.space_for_map(map, file.format, file.bit_depth) == ColorSpace::Srgb; + for slot in 0..SLOTS.len() { + if out.iter().any(|binding| binding.slot == slot) { + continue; + } + + let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue }; + let normal = (slot == 3).then(|| { + opts.normal_format.unwrap_or(match source { + SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl, + SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX, + _ => project_normal, + }) + }); + out.push(UsdTextureBinding { slot, file: name.clone(), output, srgb, normal }); + } + } + out +} + +/// The mesh as a layer named `name` whose material `m` reads the textures of `bindings[m]`, by +/// relative file name (`./`). +fn textured_layer(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result { + scene(mesh, name, |m, path, id| textured_material(path, id, bindings.get(m).map_or(&[][..], Vec::as_slice))) +} + +/// The mesh as a binary USD (Crate) file named `name` whose material `m` reads the textures of +/// `bindings[m]`, by relative file name (`./`): the textures are not part of the result. +pub fn usd_layer_with_textures(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result> { + write_usdc(&textured_layer(mesh, name, bindings)?).map_err(map_scene_err) +} + +/// A UsdPreviewSurface material at `path` whose inputs read `bindings`. One texture shader reads +/// each file (once per colour space and normal convention), so inputs packed into one file read +/// different outputs of it. +fn textured_material(path: &str, id: &str, bindings: &[UsdTextureBinding]) -> UsdPrim { + let mut mat = UsdPrim::new(id, "Material"); + mat.attrs.push(UsdAttr::connected("outputs:surface", "token", format!("{path}/PBR.outputs:surface"))); + let mut pbr = UsdPrim::new("PBR", "Shader"); + pbr.attrs.push(UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPreviewSurface".into()))).uniform()); + + // (shader name, a binding that has its file, colour space and normal convention, outputs read) + let mut taken = vec!["PBR".to_string(), "st".to_string()]; + let mut shaders: Vec<(String, &UsdTextureBinding, Vec<&'static str>)> = Vec::new(); + for binding in bindings { + let Some(&(_, input, input_type, ..)) = SLOTS.get(binding.slot) else { continue }; + let at = match shaders.iter().position(|(_, key, _)| (&key.file, key.srgb, key.normal) == (&binding.file, binding.srgb, binding.normal)) { + Some(at) => at, + None => { + let stem = binding.file.rsplit_once('.').map_or(binding.file.as_str(), |(stem, _)| stem); + shaders.push((identifier(stem, &mut taken), binding, Vec::new())); + shaders.len() - 1 + } + }; + let (shader, _, outputs) = &mut shaders[at]; + if !outputs.contains(&binding.output) { + outputs.push(binding.output); + } + + pbr.attrs.push(UsdAttr::connected(&format!("inputs:{input}"), input_type, format!("{path}/{shader}.outputs:{}", binding.output))); + } + + let mut textures = Vec::new(); + for (shader, binding, outputs) in shaders { + let mut tex = UsdPrim::new(&shader, "Shader"); + let token = |s: &str| Some(UsdValue::Token(s.into())); + tex.attrs = vec![ + UsdAttr::new("info:id", "token", token("UsdUVTexture")).uniform(), + UsdAttr::new("inputs:file", "asset", Some(UsdValue::Asset(format!("./{}", binding.file)))), + UsdAttr::connected("inputs:st", "float2", format!("{path}/st.outputs:result")), + UsdAttr::new("inputs:sourceColorSpace", "token", token(if binding.srgb { "sRGB" } else { "raw" })), + UsdAttr::new("inputs:wrapS", "token", token("repeat")), + UsdAttr::new("inputs:wrapT", "token", token("repeat")), + ]; + + // Unpack 0..1 texels to -1..1 vectors; a DirectX file also flips green to the OpenGL convention + if let Some(format) = binding.normal { + let (scale, bias) = match format { + NormalFormat::OpenGl => ([2.0, 2.0, 2.0, 1.0], [-1.0, -1.0, -1.0, 0.0]), + NormalFormat::DirectX => ([2.0, -2.0, 2.0, 1.0], [-1.0, 1.0, -1.0, 0.0]), + }; + tex.attrs.push(UsdAttr::new("inputs:scale", "float4", Some(UsdValue::Float4(scale)))); + tex.attrs.push(UsdAttr::new("inputs:bias", "float4", Some(UsdValue::Float4(bias)))); + } + for output in outputs { + tex.attrs.push(UsdAttr::new(&format!("outputs:{output}"), if output == "rgb" { "float3" } else { "float" }, None)); + } + textures.push(tex); + } + pbr.attrs.push(UsdAttr::new("inputs:useSpecularWorkflow", "int", Some(UsdValue::Int(0)))); + pbr.attrs.push(UsdAttr::new("outputs:surface", "token", None)); + mat.children.push(pbr); + if !textures.is_empty() { + let mut st = UsdPrim::new("st", "Shader"); + st.attrs = vec![ + UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPrimvarReader_float2".into()))).uniform(), + // A string, not a token: usdchecker's ARKit profile refuses a token here. + UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))), + UsdAttr::new("outputs:result", "float2", None), + ]; + mat.children.push(st); + mat.children.extend(textures); + } + mat +} + #[cfg(test)] mod aligned_package_tests { use super::*; @@ -328,3 +545,212 @@ mod aligned_package_tests { assert!(matches!(err, FormatError::Invalid(ref why) if why.starts_with("usdz package:"))); } } + +#[cfg(test)] +mod texture_binding_tests { + use super::*; + use texturecraft_core::ChannelFormat; + + const BASE_COLOR: usize = 0; + const ROUGHNESS: usize = 1; + const METALLIC: usize = 2; + const NORMAL: usize = 3; + const OPACITY: usize = 5; + + fn set_with(extra: &[Channel]) -> TextureSet { + let mut set = TextureSet::new("Body", 0, 128); + set.channels.extend(extra.iter().map(|c| (*c, ChannelFormat::default_for(*c)))); + set + } + + fn map(file: &str, format: FileFormat, channels: Vec<(Dest, SourceRef)>) -> MapSpec { + MapSpec { file: file.into(), format, bit_depth: 8, channels, inverted: Vec::new() } + } + + fn options(maps: Vec) -> ExportOptions { + ExportOptions::new(ExportPreset { name: "test".into(), maps }) + } + + fn planned(opts: &ExportOptions, index: usize) -> PlannedFile { + let map = &opts.preset.maps[index]; + PlannedFile { + name: format!("{}.{}", map.file, map.format.extension()), + map: index, + format: map.format, + bit_depth: map.bit_depth, + dither: false, + tile: None, + udim_name: None, + warnings: Vec::new(), + } + } + + fn bind(set: &TextureSet, opts: &ExportOptions, normal: NormalFormat) -> Vec { + let files: Vec = (0..opts.preset.maps.len()).map(|i| planned(opts, i)).collect(); + usd_texture_bindings(set, opts, normal, &files) + } + + fn slot(bindings: &[UsdTextureBinding], slot: usize) -> Option<&UsdTextureBinding> { + bindings.iter().find(|b| b.slot == slot) + } + + fn rgba() -> Vec<(Dest, SourceRef)> { + vec![ + (Dest::R, ch(Channel::BaseColor, 0)), + (Dest::G, ch(Channel::BaseColor, 1)), + (Dest::B, ch(Channel::BaseColor, 2)), + (Dest::A, ch(Channel::Opacity, 0)), + ] + } + + #[test] + fn colour_and_opacity_of_one_file_are_read_by_one_texture_shader() { + let opts = options(vec![map("albedo", FileFormat::Png, rgba())]); + let bindings = bind(&set_with(&[Channel::Opacity]), &opts, NormalFormat::OpenGl); + assert_eq!(slot(&bindings, BASE_COLOR).map(|b| b.output), Some("rgb")); + assert_eq!(slot(&bindings, OPACITY).map(|b| (b.output, b.file.as_str())), Some(("a", "albedo.png"))); + + // PBR, the st reader and a single texture shader + assert_eq!(textured_material("/m", "M", &bindings).children.len(), 3); + + // A set without opacity has no alpha in the file + let bindings = bind(&set_with(&[]), &opts, NormalFormat::OpenGl); + assert!(slot(&bindings, OPACITY).is_none()); + assert!(slot(&bindings, BASE_COLOR).is_some()); + } + + #[test] + fn the_layer_reads_each_file_with_its_output_and_colour_space() { + let opts = options(vec![ + map("albedo", FileFormat::Png, rgba()), + map("orm", FileFormat::Png, vec![(Dest::G, ch(Channel::Roughness, 0)), (Dest::B, ch(Channel::Metallic, 0))]), + ]); + let bindings = vec![bind(&set_with(&[Channel::Opacity]), &opts, NormalFormat::OpenGl), Vec::new()]; + let mesh = texturecraft_geom::primitives::material_ball(); + assert_eq!(mesh.materials.len(), 2); + + let text = write_usda(&textured_layer(&mesh, "ball", &bindings).unwrap()); + for expected in [ + "asset inputs:file = @./albedo.png@", + "asset inputs:file = @./orm.png@", + "color3f inputs:diffuseColor.connect = ") && text.contains("/orm.outputs:b>") && text.contains("/albedo.outputs:a>"), "{text}"); + assert!(text.contains("token inputs:sourceColorSpace = \"sRGB\"") && text.contains("token inputs:sourceColorSpace = \"raw\""), "{text}"); + assert_eq!(text.matches("\"UsdUVTexture\"").count(), 2, "one texture shader per file: {text}"); + + // The binary file holds the same layer + let bytes = usd_layer_with_textures(&mesh, "ball", &bindings).unwrap(); + assert!(bytes.starts_with(b"PXR-USDC")); + } + + #[test] + fn an_inverted_destination_is_not_bound() { + let mut inverted = map("rough", FileFormat::Png, vec![(Dest::L, ch(Channel::Roughness, 0))]); + inverted.inverted = vec![Dest::L]; + let plain = map("rough", FileFormat::Png, vec![(Dest::L, ch(Channel::Roughness, 0))]); + let set = set_with(&[]); + assert!(slot(&bind(&set, &options(vec![inverted]), NormalFormat::OpenGl), ROUGHNESS).is_none()); + assert!(slot(&bind(&set, &options(vec![plain]), NormalFormat::OpenGl), ROUGHNESS).is_some()); + } + + #[test] + fn the_tiles_of_a_uv_tiled_set_are_read_through_the_udim_name() { + let opts = options(vec![map("color.$udim", FileFormat::Png, rgba())]); + let set = set_with(&[]); + let mut tile = planned(&opts, 0); + tile.name = "color.1001.png".into(); + tile.tile = Some(1001); + let mut second = tile.clone(); + second.name = "color.1002.png".into(); + second.tile = Some(1002); + + // Tiles without a `` name cannot stand for the others + assert!(usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[tile.clone(), second.clone()]).is_empty()); + + tile.udim_name = Some("color..png".into()); + second.udim_name = tile.udim_name.clone(); + let bindings = usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[tile, second]); + assert_eq!(slot(&bindings, BASE_COLOR).map(|b| b.file.as_str()), Some("color..png")); + assert_eq!(bindings.len(), 1, "the tiles of one map make one binding"); + } + + #[test] + fn only_colour_maps_in_integer_srgb_files_are_tagged_srgb() { + let colour = || vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::BaseColor, 1)), (Dest::B, ch(Channel::BaseColor, 2))]; + let set = set_with(&[]); + let tag = |format: FileFormat, depth: u8, space: Option| { + let mut spec = map("c", format, colour()); + spec.bit_depth = depth; + let mut opts = options(vec![spec]); + opts.color_space = space; + let file = planned(&opts, 0); + let expected = opts.space_for_map(&opts.preset.maps[0], file.format, file.bit_depth) == ColorSpace::Srgb; + let bindings = usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[PlannedFile { bit_depth: depth, ..file }]); + let srgb = slot(&bindings, BASE_COLOR).unwrap().srgb; + assert_eq!(srgb, expected); + srgb + }; + assert!(tag(FileFormat::Png, 8, None)); + assert!(tag(FileFormat::Png, 16, None)); + assert!(!tag(FileFormat::Exr, 16, None), "float files hold linear colour"); + assert!(!tag(FileFormat::Png, 8, Some(ColorSpace::AcesCg)), "UsdPreviewSurface knows only sRGB and raw"); + + // Data maps are raw + let data = options(vec![map("m", FileFormat::Png, vec![(Dest::L, ch(Channel::Metallic, 0))])]); + assert!(!slot(&bind(&set, &data, NormalFormat::OpenGl), METALLIC).unwrap().srgb); + } + + #[test] + fn roughness_from_glossiness_is_bound_only_for_a_set_with_glossiness() { + let from_glossiness = options(vec![map("r", FileFormat::Png, vec![(Dest::L, virt(VirtualMap::Roughness, 0))])]); + assert!(slot(&bind(&set_with(&[Channel::Glossiness]), &from_glossiness, NormalFormat::OpenGl), ROUGHNESS).is_some()); + assert!(slot(&bind(&set_with(&[]), &from_glossiness, NormalFormat::OpenGl), ROUGHNESS).is_none()); + + // Glossiness itself is the opposite of roughness + let glossiness = options(vec![map("g", FileFormat::Png, vec![(Dest::L, virt(VirtualMap::Glossiness, 0))])]); + assert!(bind(&set_with(&[]), &glossiness, NormalFormat::OpenGl).is_empty()); + } + + #[test] + fn a_file_that_cannot_hold_alpha_or_colour_is_not_bound_for_them() { + let set = set_with(&[Channel::Opacity]); + for format in [FileFormat::Jpeg, FileFormat::Hdr] { + let bindings = bind(&set, &options(vec![map("albedo", format, rgba())]), NormalFormat::OpenGl); + assert!(slot(&bindings, BASE_COLOR).is_some(), "{format:?} keeps the colour"); + assert!(slot(&bindings, OPACITY).is_none(), "{format:?} drops alpha"); + } + assert!(slot(&bind(&set, &options(vec![map("albedo", FileFormat::Png, rgba())]), NormalFormat::OpenGl), OPACITY).is_some()); + + // PGM is one gray channel: colour becomes luminance, and only a map written as L is bound + let pgm = options(vec![ + map("albedo", FileFormat::Pgm, rgba()), + map("orm", FileFormat::Pgm, vec![(Dest::G, ch(Channel::Roughness, 0)), (Dest::B, ch(Channel::Metallic, 0))]), + map("metal", FileFormat::Pgm, vec![(Dest::L, ch(Channel::Metallic, 0))]), + ]); + let bindings = bind(&set, &pgm, NormalFormat::OpenGl); + assert!(slot(&bindings, BASE_COLOR).is_none()); + assert!(slot(&bindings, ROUGHNESS).is_none()); + assert_eq!(slot(&bindings, METALLIC).map(|b| (b.output, b.file.as_str())), Some(("r", "metal.pgm"))); + } + + #[test] + fn a_normal_map_unpacks_with_the_convention_of_its_file() { + let set = set_with(&[]); + let normal = |source: fn(u8) -> SourceRef| { + options(vec![map("n", FileFormat::Png, (0..3).map(|k| ([Dest::R, Dest::G, Dest::B][k as usize], source(k))).collect())]) + }; + let convention = |opts: &ExportOptions| slot(&bind(&set, opts, NormalFormat::DirectX), NORMAL).unwrap().normal; + assert_eq!(convention(&normal(|k| ch(Channel::Normal, k))), Some(NormalFormat::DirectX), "follows the project"); + assert_eq!(convention(&normal(|k| virt(VirtualMap::NormalOpenGl, k))), Some(NormalFormat::OpenGl)); + + let mut forced = normal(|k| virt(VirtualMap::NormalOpenGl, k)); + forced.normal_format = Some(NormalFormat::DirectX); + assert_eq!(convention(&forced), Some(NormalFormat::DirectX), "the export's normal format wins"); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5b3ed2d3..c60a2bbf 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -70,6 +70,7 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H # winit needs a window system on Linux, so the crate's own tests build with X11. [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +craft-usd.workspace = true eframe = { workspace = true, features = ["x11"] } # Offscreen pictures of the whole window (tests/ui_snapshots.rs). egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 37590454..02678d0d 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -245,7 +245,16 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, written: Vec::new(), frame: 0 }); + e.job = Some(crate::state::ExportJob { + total: pending.len(), + pending, + preview, + directory: dir, + written: Vec::new(), + frame: 0, + usd_asset: e.usd_asset, + sent: Vec::new(), + }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -326,11 +335,31 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let set = || ConsoleLine::Set(name.clone()); app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); + // The USD asset covers the whole mesh and refers to the textures of every texture set: the last command writes it, given + // the params every command of the export ran with, so a canceled or failed export writes none + if let Some(job) = app.ui.export.job.as_mut().filter(|job| job.usd_asset) { + job.sent.push(params.clone()); + if job.pending.is_empty() { + params["usdAsset"] = json!(job.sent); + } + } let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; }; + // The one warning the window shows: the USD asset that could not be written + let usd_failure = response + .get("warnings") + .and_then(|w| w.as_array()) + .into_iter() + .flatten() + .filter_map(|w| w.as_str()) + .find(|w| w.starts_with(texturecraft_engine::file_cmds::USD_ASSET_FAILED)); + if let Some(warning) = usd_failure { + app.toast(warning.to_string(), true); + } + let files: Vec = response .get("files") .and_then(|file| file.as_array()) @@ -340,7 +369,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; - for file in &files { + // The USD asset is no texture: it stays in the list of written files only + for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); @@ -631,8 +661,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] if reset { let d = ExportUi::default(); let e = &mut app.ui.export; - (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space) = - (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space); + (e.dir, e.format, e.bit_depth, e.dithering, e.size, e.padding, e.dilation, e.normal_format, e.color_space, e.usd_asset) = + (d.dir, d.format, d.bit_depth, d.dithering, d.size, d.padding, d.dilation, d.normal_format, d.color_space, d.usd_asset); crate::export_templates::select(app, d.preset); } let (first, rest) = template_groups(app, builtins); @@ -675,8 +705,13 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ui.end_row(); }); - // Unavailable export controls stay disabled + // The browser downloads the textures only, so it has no USD asset to add + #[cfg(not(target_arch = "wasm32"))] + ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")).on_hover_text(tr("Package the mesh, materials and textures together as USD")); + #[cfg(target_arch = "wasm32")] unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); + + // Unavailable export controls stay disabled unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e2a36d40..a3c458c4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -357,6 +357,10 @@ pub struct ExportUi { /// "" (by file format: sRGB, or linear for float files), or a colour space name. #[serde(default)] pub color_space: String, + /// Also write `.usd`: the mesh and a material per texture set that reads the exported + /// textures (`usdAsset` of `file.exportTextures`). + #[serde(default)] + pub usd_asset: bool, /// Texture sets excluded from export. pub skip: Vec, /// Per texture set (by index) overrides of the settings above. @@ -418,6 +422,7 @@ impl Default for ExportUi { size: 0, normal_format: String::new(), color_space: String::new(), + usd_asset: false, skip: Vec::new(), sets: Default::default(), owner: Vec::new(), diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index 4ba0d485..a2143a8c 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -15,4 +15,9 @@ pub struct ExportJob { pub written: Vec, /// The frame that wrote the last texture set (a frame's second pass writes none). pub frame: u64, + /// Also write the mesh and materials as a USD asset with the last texture set, as ticked when + /// Export was clicked. + pub usd_asset: bool, + /// The params of the texture sets written so far, for the USD asset. + pub sent: Vec, } diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs new file mode 100644 index 00000000..ddc54014 --- /dev/null +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -0,0 +1,211 @@ +//! Export textures › SETTINGS: the Export USD asset option. It writes `.usd` (the mesh and a +//! material per texture set that reads the exported textures) next to the textures, with the +//! export's last texture set. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::{ConsoleLine, ExportJob}; + +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The Export textures window writing into a scratch folder of its own for `name` +fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, Scratch) { + 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.prefs.language = "en".into(); + h.run_steps(4); + let dir = std::env::temp_dir().join(format!("tc-export-usd-asset-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let dir = Scratch(dir); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + (h, dir) +} + +fn checkbox<'a>(h: &'a Harness<'static, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_by_role_and_label(egui::Role::CheckBox, "Export USD asset") +} + +/// Click Export and run frames until the export ends +fn export(h: &mut Harness<'static, TextureCraftApp>) { + h.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + h.run_steps(1); + if h.state().ui.export.job.is_none() { + break; + } + } + h.run_steps(2); +} + +/// The texture files `/material_ball.usd` refers to +fn referenced_files(dir: &std::path::Path) -> Vec { + let bytes = std::fs::read(dir.join("material_ball.usd")).expect("material_ball.usd"); + let layer = craft_usd::scene::read_layer(&bytes).unwrap(); + layer + .prims + .iter() + .filter_map(|prim| match prim.props.get("inputs:file")?.value.as_ref()? { + craft_usd::scene::Val::Tok(values) => values.first().map(|file| file.trim_start_matches("./").to_string()), + _ => None, + }) + .collect() +} + +#[test] +fn the_window_offers_export_usd_asset_off_by_default() { + let (h, _dir) = harness("offer"); + assert!(!checkbox(&h).accesskit_node().is_disabled()); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn ticking_export_usd_asset_writes_one_file_that_refers_to_the_exported_textures() { + let (mut h, dir) = harness("on"); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.usd_asset); + export(&mut h); + + let files = referenced_files(&dir); + assert!(h.state().session.set_count() >= 2, "one file has to cover several texture sets"); + assert!(files.len() >= h.state().session.set_count(), "every material reads textures: {files:?}"); + for file in &files { + assert!(dir.join(file).is_file(), "{file} was written"); + } + let usd = std::fs::read_dir(&*dir).unwrap().flatten().filter(|e| e.path().extension().is_some_and(|x| x == "usd")).count(); + assert_eq!(usd, 1, "one file for the whole export, not one per texture set"); +} + +#[test] +fn the_file_refers_to_the_textures_each_texture_set_was_exported_with() { + let (mut h, dir) = harness("overrides"); + h.state_mut().ui.export.sets.entry(1).or_default().preset = Some("Unreal Engine (Packed)".into()); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let files = referenced_files(&dir); + assert!(files.iter().any(|f| f.ends_with("_OcclusionRoughnessMetallic.png")), "the second texture set's template: {files:?}"); + assert!(files.iter().any(|f| f.ends_with("_roughness.png")), "the first texture set's template: {files:?}"); + for file in &files { + assert!(dir.join(file).is_file(), "{file} was written"); + } +} + +#[test] +fn only_the_exported_texture_sets_have_textures() { + let (mut h, dir) = harness("subset"); + h.state_mut().ui.export.skip = vec![0]; + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let first = texturecraft_engine::formats::export::sanitize_file_stem(&h.state().session.doc.project.texture_sets[0].name); + let files = referenced_files(&dir); + assert!(!files.is_empty()); + assert!(files.iter().all(|f| !f.starts_with(&format!("material_ball_{first}_"))), "the skipped texture set has none: {files:?}"); +} + +#[test] +fn the_console_lists_the_asset_as_a_file_but_not_as_a_saved_texture() { + let (mut h, _dir) = harness("console"); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let console = &h.state().ui.export.console; + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Done(file) if file == "material_ball.usd")), "{console:?}"); + assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Saved texture material_ball")), "{console:?}"); + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Saved texture "))), "the textures are still listed"); +} + +#[test] +fn a_canceled_export_writes_no_asset() { + let (mut h, dir) = harness("cancel"); + + // A long export, as the window starts it with the option ticked + let sets = h.state().session.set_count(); + let params = serde_json::json!({"dir": dir.display().to_string()}); + let pending: Vec<(usize, serde_json::Value)> = (0..sets).cycle().take(sets * 8).map(|ts| (ts, params.clone())).collect(); + let e = &mut h.state_mut().ui.export; + e.tab = 2; + e.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, ..ExportJob::default() }); + h.run_steps(2); + h.get_all_by_label("Cancel Export").last().unwrap().click(); + h.run_steps(3); + assert!(h.state().ui.export.job.is_none()); + assert!(!dir.join("material_ball.usd").exists()); + + // The same job run to its end writes it + let pending: Vec<(usize, serde_json::Value)> = (0..sets).map(|ts| (ts, params.clone())).collect(); + h.state_mut().ui.export.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, ..ExportJob::default() }); + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + h.run_steps(1); + } + assert!(dir.join("material_ball.usd").is_file()); +} + +#[test] +fn no_asset_is_written_when_the_option_is_off() { + let (mut h, dir) = harness("off"); + export(&mut h); + assert!(std::fs::read_dir(&*dir).unwrap().next().is_some(), "the textures were written"); + assert!(!dir.join("material_ball.usd").exists()); +} + +#[test] +fn restoring_the_default_parameters_unticks_export_usd_asset() { + let (mut h, _dir) = harness("reset"); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.usd_asset); + h.get_by_label("Restore the default export parameters").click(); + h.run_steps(3); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn reset_all_unticks_export_usd_asset() { + let (mut h, _dir) = harness("reset-all"); + checkbox(&h).click(); + h.run_steps(3); + h.get_by_label("Reset all").click(); + h.run_steps(3); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn an_asset_that_cannot_be_written_shows_an_error_toast_and_the_textures_stay() { + let (mut h, dir) = harness("blocked"); + + // A folder where the file belongs: the asset cannot be written there + std::fs::create_dir_all(dir.join("material_ball.usd")).unwrap(); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let toast = h.state().toasts.iter().find(|toast| toast.text.starts_with("The USD asset was not written")).expect("a toast names the failure"); + assert!(toast.error); + assert!(h.state().ui.export.job.is_none(), "the export ran to its end"); + assert!(std::fs::read_dir(&*dir).unwrap().flatten().any(|e| e.path().extension().is_some_and(|x| x == "png")), "the textures were written"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index ef91cc44..246e7c8d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -26,6 +26,7 @@ mod export_overrides; mod export_progress; mod export_settings; mod export_template_guards; +mod export_usd_asset; mod file_dialogs; mod fill_channel_image; mod fill_material_rows; diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index d05f19a1..80bd801d 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -116,7 +116,8 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { assert!(harness.query_by_label(label).is_some(), "{label}"); } assert!(harness.query_by_label_contains("textures selected for export").is_some()); - assert!(says_not_available(&mut harness, "Export USD asset")); + assert!(!says_not_available(&mut harness, "Export USD asset")); + assert!(says_not_available(&mut harness, "Export shader settings")); harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d963eb9c..2b7e3638 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,6 +47,18 @@ template. `enabled: false` suppresses that file while reserving its name. When s sets produce the same name (ignoring case), programmatic and browser exports keep the first file and warn about later duplicates. The desktop export window reports the collision before writing. +`file.exportTextures` with `usdAsset` also writes `.usd` (binary USD, Crate) next to the textures: the whole mesh +(every texture set, whatever `ts` selects) with one UsdPreviewSurface material per texture set. A +material's inputs read the texture files the export planned for that set with its output template +(`usdAsset: true`: the sets and options of this command; a list of export params such as +`[{"ts": 0, "preset": "..."}, {"ts": 1}]`, not empty, every entry an object: each entry's sets and options, the way the export window, +which runs one command per texture set, passes the params of all its commands with the last one). +Bound inputs: `diffuseColor`, `roughness`, `metallic`, `normal`, `emissiveColor`, `opacity`, +`clearcoat` and `clearcoatRoughness`, each reading the `rgb`, `r`, `g`, `b` or `a` output of the +file that holds it; maps with no such input are not bound, and a texture set outside the export has +no textures. A file name is relative to the file (`./`, with `` for UV tiles). A failure +to build or write it is named in `warnings` and the command still succeeds. The file is in `files`. + `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and diff --git a/docs/features.md b/docs/features.md index 82c650a4..bb428323 100644 --- a/docs/features.md +++ b/docs/features.md @@ -177,6 +177,19 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA file type, size or padding, and each output map's file type and bit depth, or leaves a map out; Export shows the progress, a console of its steps and the written files, and can be canceled between texture sets). +- **USD asset export:** the *Export USD asset* checkbox on the Export textures window's Global + settings (off by default, remembered with the other settings) also writes `.usd` (binary USD) next to + the exported textures when the last selected texture set is written. It holds the whole mesh with + one UsdPreviewSurface material per texture set; each material refers to the textures that texture + set was exported with (its own output template, file type, size and normal format) by relative + file name. Base colour, roughness, metallic, normal, emissive colour, opacity, clear coat and clear + coat roughness are bound; a packed template (ORM, mask map) binds several inputs to different + channels of one file. Ambient occlusion, height, specular/glossiness, sheen, anisotropy, + transmission, scatter, coat normal and baked maps have no UsdPreviewSurface input and are not + bound. Colour maps written as sRGB are tagged sRGB, other maps raw; a DirectX normal map is + flipped back in the material. A texture set outside the export has no textures in the file. A + canceled export writes none, and a failure to write it is a warning. In the browser the option is + greyed. - **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f7dad7ed..f4454953 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -68,8 +68,10 @@ that closes it back onto the bar; the float is saved with the UI state. *Send to compositing app* and *Send to 3D staging app*. EXPORT has *Export Mesh...* (the *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* - and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected - for export"). The prompt's *With displacement/tessellation* choice and both option checkboxes are + (off by default; it adds `usdAsset` to the last texture set's export, which writes `.usd` + with materials that refer to the exported textures; greyed in the browser), *Export shaders + parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). The + prompt's *With displacement/tessellation* choice and both option checkboxes are greyed; TextureCraft exports the mesh as it is. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering From 4be73547bf6c8510943698ae92e79d127e9594df Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 21:56:35 +0100 Subject: [PATCH 062/153] Fix USD asset review findings: UDIM name clashes, material-less meshes, normal convention, sent params, docs --- crates/engine/src/file_cmds.rs | 32 ++++++++---- crates/engine/tests/it/usd_asset.rs | 55 +++++++++++++++++++++ crates/formats/src/mesh_export/usd.rs | 29 +++++++++-- crates/ui-egui/src/export_window.rs | 11 +++++ crates/ui-egui/tests/it/export_usd_asset.rs | 45 +++++++++++++++++ docs/control-protocol.md | 2 +- docs/features.md | 7 +-- 7 files changed, 162 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 43dc4087..30106178 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -695,7 +695,7 @@ fn write_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, E #[cfg(not(target_arch = "wasm32"))] fn build_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, ExportOptions)]) -> Result { - use texturecraft_formats::{export::list_set_outputs, usd_layer_with_textures, usd_texture_bindings}; + use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings}; let project = &s.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); @@ -703,20 +703,32 @@ fn build_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, E let mut taken = std::collections::HashSet::new(); let mut by_set = std::collections::HashMap::new(); for (sets, opts) in exports { - // A file whose name an earlier export of this job has was not written by this one - let planned: Vec<_> = list_set_outputs(project, sets, &mesh_name, opts) - .map_err(fe)? - .into_iter() - .filter(|(_, file)| taken.insert(file.name.to_ascii_lowercase())) - .collect(); for &set in sets { - let files: Vec<_> = planned.iter().filter(|(ts, _)| *ts == set).map(|(_, file)| file.clone()).collect(); let texture_set = project.texture_set(set).map_err(|e| EngineError::Other(e.to_string()))?; - by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, opts, project.normal_format, &files)); + + // A file whose name an earlier file of this job has was not written by this export. A + // map that lost any file (a tile of a UDIM map) is not bound: its `` name would + // read the tile of another texture set. + let mut skipped_maps = std::collections::HashSet::new(); + let mut kept = Vec::new(); + for file in list_outputs(project, set, &mesh_name, opts).map_err(fe)? { + if taken.insert(file.name.to_ascii_lowercase()) { + kept.push(file); + } else { + skipped_maps.insert(file.map); + } + } + + kept.retain(|file| !skipped_maps.contains(&file.map)); + by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, opts, project.normal_format, &kept)); } } - let mesh = s.source_mesh(); + // A mesh without materials has one implicit material (and texture set) + let mut mesh = s.source_mesh(); + if mesh.materials.is_empty() { + mesh.materials.push("default".into()); + } let bindings: Vec<_> = (0..mesh.materials.len()).map(|m| s.texture_set_of_material(m).and_then(|set| by_set.remove(&set)).unwrap_or_default()).collect(); let layer = usd_layer_with_textures(&mesh, &project.name, &bindings).map_err(fe)?; let path = dir.join(format!("{}.usd", texturecraft_formats::export::sanitize_file_stem(&mesh_name))); diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index 3c6458a4..dfba38fa 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -317,3 +317,58 @@ fn a_material_without_a_texture_set_has_no_textures() { assert!(!materials[0].0.is_empty()); assert!(materials[1].0.is_empty(), "{:?}", materials[1]); } + +/// A material per half of a two-tile plane: the first material covers tiles 1001 and 1002, the second 1002 and 1003 +fn overlapping_tiles() -> Session { + let mut mesh = primitives::udim_plane(); + let mut second = primitives::udim_plane(); + second.materials[0] = "Other".into(); + for uv in &mut second.uvs { + uv.x += 1.0; + } + mesh.append(&second); + let s = Session::new_project("t", mesh, "builtin:udim_plane", None, 128).unwrap(); + assert_eq!(s.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + assert_eq!(s.doc.project.texture_sets[1].uv_tiles, [1002, 1003]); + s +} + +#[test] +fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_are() { + let mut s = overlapping_tiles(); + let dir = temp("udim-clash"); + + // The colour map's names do not tell the sets apart, so tile 1002 of the second set is not written; + // the roughness map's names do. + let gray = json!([["L", {"Channel": {"channel": "Roughness", "component": 0}}]]); + let mut preset = shared_name_template(); + preset["maps"].as_array_mut().unwrap().push(json!({"file": "rough_$textureSet", "format": "Png", "bit_depth": 8, "channels": gray})); + export(&mut s, &dir, json!({"ts": [0, 1], "preset": preset, "usdAsset": true})); + + let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &s.mesh.materials); + let (first, second) = (&materials[material_of(&s, 0)].0, &materials[material_of(&s, 1)].0); + assert_eq!(first["diffuseColor"].file, "colour..png", "{first:?}"); + assert!(first["roughness"].file.starts_with("rough_") && first["roughness"].file.contains(""), "{first:?}"); + assert!(!second.contains_key("diffuseColor"), "tile 1002 would read the first set's file: {second:?}"); + assert!(second["roughness"].file.starts_with("rough_") && second["roughness"].file.contains(""), "{second:?}"); + assert_ne!(first["roughness"].file, second["roughness"].file); +} + +#[test] +fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { + let mut mesh = primitives::plane(2.0, 4); + mesh.materials.clear(); + mesh.submeshes.clear(); + let mut s = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + assert_eq!(s.set_count(), 1); + let dir = temp("no-materials"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = materials(&std::fs::read(dir.join("plane.usd")).unwrap(), &["default".to_string()]); + let inputs = &materials[0].0; + assert!(["diffuseColor", "roughness", "metallic", "normal"].iter().all(|input| inputs.contains_key(*input)), "{inputs:?}"); + for read in inputs.values() { + assert!(read.file.starts_with("plane_Default_"), "reads the Default texture set's files: {}", read.file); + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + } +} diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index c9ace034..49125502 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -339,8 +339,8 @@ fn component_of(source: &SourceRef) -> u8 { } /// The texture output of `map` that input `slot` reads, and the source it takes: a colour or -/// normal input needs the three components in R, G and B, a scalar input reads the destination -/// that holds it. None when the map does not hold the input, when `set` has no data for it (the +/// normal input needs the three components in R, G and B (the source is the green one's), a scalar +/// input reads the destination that holds it. None when the map does not hold the input, when `set` has no data for it (the /// file then holds a default), when it is written inverted, or when `format` cannot keep it: JPEG /// and HDR files drop alpha, a PGM file holds one gray channel (a colour map becomes its /// luminance), which only a map written as L can bind. @@ -372,10 +372,13 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: return None; } - let red = holds(Dest::R, Some(0))?; - holds(Dest::G, Some(1))?; + holds(Dest::R, Some(0))?; + let green = holds(Dest::G, Some(1))?; holds(Dest::B, Some(2))?; - Some(("rgb", red)) + + // The green source is returned: only the green channel differs between the OpenGL and DirectX + // normal conventions + Some(("rgb", green)) } /// The UsdPreviewSurface inputs the exported `files` of texture set `set` (planned with `opts`) @@ -753,4 +756,20 @@ mod texture_binding_tests { forced.normal_format = Some(NormalFormat::DirectX); assert_eq!(convention(&forced), Some(NormalFormat::DirectX), "the export's normal format wins"); } + + #[test] + fn a_normal_map_takes_its_convention_from_the_green_channel() { + let set = set_with(&[]); + // Red and blue are the same in both conventions; green decides + let mixed = |green: VirtualMap| { + options(vec![map( + "n", + FileFormat::Png, + vec![(Dest::R, virt(VirtualMap::NormalOpenGl, 0)), (Dest::G, virt(green, 1)), (Dest::B, virt(VirtualMap::NormalOpenGl, 2))], + )]) + }; + let convention = |opts: &ExportOptions| slot(&bind(&set, opts, NormalFormat::OpenGl), NORMAL).unwrap().normal; + assert_eq!(convention(&mixed(VirtualMap::NormalDirectX)), Some(NormalFormat::DirectX)); + assert_eq!(convention(&mixed(VirtualMap::NormalOpenGl)), Some(NormalFormat::OpenGl)); + } } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 02678d0d..ef572e07 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1119,6 +1119,17 @@ fn follow_texture_sets(app: &mut TextureCraftApp) { set.index = set.index.and_then(moved); } + // The sets already written follow too (the USD asset reads their params); a removed one leaves + job.sent = std::mem::take(&mut job.sent) + .into_iter() + .filter_map(|mut params| { + let Some(index) = params.get("ts").and_then(serde_json::Value::as_u64) else { return Some(params) }; + let index = moved(usize::try_from(index).ok()?)?; + params["ts"] = json!(index); + Some(params) + }) + .collect(); + // Removed sets leave the count too, so the bar keeps its pace job.total -= queued - job.pending.len(); } else { diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs index ddc54014..6934c09c 100644 --- a/crates/ui-egui/tests/it/export_usd_asset.rs +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -209,3 +209,48 @@ fn an_asset_that_cannot_be_written_shows_an_error_toast_and_the_textures_stay() assert!(h.state().ui.export.job.is_none(), "the export ran to its end"); assert!(std::fs::read_dir(&*dir).unwrap().flatten().any(|e| e.path().extension().is_some_and(|x| x == "png")), "the textures were written"); } + +/// A running USD export that has already written texture sets 0 and 1 (the `tag` of each sent command tells them apart) +fn running_with_two_sent(h: &mut Harness<'static, TextureCraftApp>, dir: &std::path::Path) { + let sets = h.state().session.set_count(); + let params = serde_json::json!({"dir": dir.display().to_string()}); + let pending: Vec<(usize, serde_json::Value)> = (0..sets).cycle().take(sets * 8).map(|ts| (ts, params.clone())).collect(); + let sent = (0..2).map(|ts| serde_json::json!({"dir": dir.display().to_string(), "ts": ts, "tag": ts})).collect(); + let e = &mut h.state_mut().ui.export; + e.tab = 2; + e.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, sent, ..ExportJob::default() }); +} + +/// The `ts` of the sent commands that carry `tag` +fn sent_ts(h: &Harness<'static, TextureCraftApp>, tag: u64) -> Vec { + let job = h.state().ui.export.job.as_ref().expect("the export is still running"); + job.sent.iter().filter(|params| params["tag"] == tag).map(|params| params["ts"].as_u64().unwrap()).collect() +} + +#[test] +fn the_sent_commands_of_a_running_export_follow_their_texture_sets_when_they_move() { + let (mut h, dir) = harness("sent-move"); + running_with_two_sent(&mut h, &dir); + h.run_steps(1); + assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![0], vec![1])); + + // The two texture sets trade places (names), as a reorder does + let names: Vec = h.state().session.doc.project.texture_sets.iter().map(|t| t.name.clone()).collect(); + for (ts, name) in [(0, "swap"), (1, names[0].as_str()), (0, names[1].as_str())] { + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.rename", &serde_json::json!({"ts": ts, "name": name})).unwrap(); + } + h.run_steps(1); + assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![1], vec![0]), "each command stays with its texture set"); +} + +#[test] +fn the_sent_command_of_a_texture_set_that_leaves_the_export_is_dropped() { + let (mut h, dir) = harness("sent-drop"); + running_with_two_sent(&mut h, &dir); + h.run_steps(1); + + // A rename the export cannot follow takes the texture set out of it + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.rename", &serde_json::json!({"ts": 1, "name": "renamed"})).unwrap(); + h.run_steps(1); + assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![0], vec![])); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2b7e3638..e8ec37e6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -55,7 +55,7 @@ material's inputs read the texture files the export planned for that set with it which runs one command per texture set, passes the params of all its commands with the last one). Bound inputs: `diffuseColor`, `roughness`, `metallic`, `normal`, `emissiveColor`, `opacity`, `clearcoat` and `clearcoatRoughness`, each reading the `rgb`, `r`, `g`, `b` or `a` output of the -file that holds it; maps with no such input are not bound, and a texture set outside the export has +file that holds it; other maps (ambient occlusion, height, specular...) are not bound, and a texture set outside the export has no textures. A file name is relative to the file (`./`, with `` for UV tiles). A failure to build or write it is named in `warnings` and the command still succeeds. The file is in `files`. diff --git a/docs/features.md b/docs/features.md index bb428323..7aad167d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -184,9 +184,10 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA set was exported with (its own output template, file type, size and normal format) by relative file name. Base colour, roughness, metallic, normal, emissive colour, opacity, clear coat and clear coat roughness are bound; a packed template (ORM, mask map) binds several inputs to different - channels of one file. Ambient occlusion, height, specular/glossiness, sheen, anisotropy, - transmission, scatter, coat normal and baked maps have no UsdPreviewSurface input and are not - bound. Colour maps written as sRGB are tagged sRGB, other maps raw; a DirectX normal map is + channels of one file. Ambient occlusion, height and specular/glossiness are not bound (the + material has occlusion, displacement and specularColor inputs, but TextureCraft does not fill + them), nor are baked maps; sheen, anisotropy, transmission, scatter and coat normal have no + UsdPreviewSurface input. Colour maps written as sRGB are tagged sRGB, other maps raw; a DirectX normal map is flipped back in the material. A texture set outside the export has no textures in the file. A canceled export writes none, and a failure to write it is a warning. In the browser the option is greyed. From 8f7c9563358b69333c4a08a8a2d15c77aa9cdbf6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 21:59:01 +0100 Subject: [PATCH 063/153] Document unbound UDIM maps and the implicit default material in the USD asset --- docs/control-protocol.md | 3 ++- docs/features.md | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e8ec37e6..fa911460 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -55,7 +55,8 @@ material's inputs read the texture files the export planned for that set with it which runs one command per texture set, passes the params of all its commands with the last one). Bound inputs: `diffuseColor`, `roughness`, `metallic`, `normal`, `emissiveColor`, `opacity`, `clearcoat` and `clearcoatRoughness`, each reading the `rgb`, `r`, `g`, `b` or `a` output of the -file that holds it; other maps (ambient occlusion, height, specular...) are not bound, and a texture set outside the export has +file that holds it; other maps (ambient occlusion, height, specular...) are not bound, a UDIM map that lost a tile to an earlier +set's file name is not bound, a mesh with no materials gets one implicit `default` material bound to the Default set, and a texture set outside the export has no textures. A file name is relative to the file (`./`, with `` for UV tiles). A failure to build or write it is named in `warnings` and the command still succeeds. The file is in `files`. diff --git a/docs/features.md b/docs/features.md index 7aad167d..e4506932 100644 --- a/docs/features.md +++ b/docs/features.md @@ -184,9 +184,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA set was exported with (its own output template, file type, size and normal format) by relative file name. Base colour, roughness, metallic, normal, emissive colour, opacity, clear coat and clear coat roughness are bound; a packed template (ORM, mask map) binds several inputs to different - channels of one file. Ambient occlusion, height and specular/glossiness are not bound (the - material has occlusion, displacement and specularColor inputs, but TextureCraft does not fill - them), nor are baked maps; sheen, anisotropy, transmission, scatter and coat normal have no + channels of one file. A UDIM map that lost a tile to an earlier texture set's file name gets no + binding, and a mesh with no materials gets one implicit "default" material bound to the Default + texture set. Ambient occlusion, height and specular are not bound (the material has occlusion, + displacement and specularColor inputs, but TextureCraft does not fill them), nor are glossiness + (no matching input) and baked maps; sheen, anisotropy, transmission, scatter and coat normal have no UsdPreviewSurface input. Colour maps written as sRGB are tagged sRGB, other maps raw; a DirectX normal map is flipped back in the material. A texture set outside the export has no textures in the file. A canceled export writes none, and a failure to write it is a warning. In the browser the option is From 0203f23ee097e9b6b1615dadfc0c6f49516541fc Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:00:04 +0100 Subject: [PATCH 064/153] Export UI parity: drop SEND TO from the Export dock, restore the reference texts, 1100x740 window The Export dock shows EXPORT only. The export window, its console lines, tooltips and the Output templates texts read as in the reference again, and the window has the reference size. --- crates/ui-egui/src/export_panel.rs | 37 +--------- crates/ui-egui/src/export_templates.rs | 6 +- crates/ui-egui/src/export_window.rs | 52 +++++++------- .../ui-egui/tests/it/export_map_overrides.rs | 4 +- crates/ui-egui/tests/it/export_materialx.rs | 2 +- crates/ui-egui/tests/it/export_overrides.rs | 6 +- crates/ui-egui/tests/it/export_progress.rs | 18 ++--- .../tests/it/export_reference_texts.rs | 69 +++++++++++++++++++ crates/ui-egui/tests/it/export_settings.rs | 4 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/output_templates.rs | 6 +- crates/ui-egui/tests/it/side_panels.rs | 8 ++- docs/ui-parity.md | 18 ++--- 13 files changed, 136 insertions(+), 95 deletions(-) create mode 100644 crates/ui-egui/tests/it/export_reference_texts.rs diff --git a/crates/ui-egui/src/export_panel.rs b/crates/ui-egui/src/export_panel.rs index a9f63f17..13dc88a7 100644 --- a/crates/ui-egui/src/export_panel.rs +++ b/crates/ui-egui/src/export_panel.rs @@ -1,48 +1,17 @@ -//! The Export panel on the rail: where to send the project, then Export Mesh and Export Textures +//! The Export panel on the rail: Export Mesh and Export Textures -use egui::{RichText, Ui}; -use egui_phosphor::regular as ic; +use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; -use crate::theme::{Tokens, caption}; -use crate::unavailable; +use crate::theme::caption; use crate::widgets::primary_button; -/// The SEND TO rows: none has a counterpart in TextureCraft yet -pub const SEND_TO: [&str; 3] = ["Export to image editor", "Send to compositing app", "Send to 3D staging app"]; - /// Width of the Export Mesh and Export Textures buttons const EXPORT_BUTTON_WIDTH: f32 = 176.0; -/// Size of the Configure button beside a SEND TO row -const CONFIGURE_SIZE: f32 = 20.0; - -/// Space between the SEND TO and EXPORT parts -const PART_GAP: f32 = 12.0; - /// The Export panel body (a rail popup or dock tab); its buttons need an open project pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); - ui.label(caption(&tr("Send to").to_uppercase())); - for (index, target) in SEND_TO.into_iter().enumerate() { - ui.horizontal(|ui| { - unavailable::greyed(ui, |ui| ui.add(egui::Button::new(tr(target)).frame(false))); - - // The reference's second row has a Configure button - if index == 1 { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - unavailable::greyed(ui, |ui| { - ui.add( - egui::Button::new(RichText::new(ic::GEAR).color(tokens.text_dim)).frame(false).min_size(egui::vec2(CONFIGURE_SIZE, CONFIGURE_SIZE)), - ) - }); - }); - } - }); - } - - ui.add_space(PART_GAP); ui.label(caption(&tr("Export").to_uppercase())); let project_open = app.session.project_open; ui.vertical_centered(|ui| { diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index c1c0eddc..f6fb56df 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -273,8 +273,8 @@ fn naming_pattern(ui: &mut Ui) { } }); ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { - ui.label(tr("Choose how the input maps are named in this editor.")); - ui.label(tr("The active texture set’s shader can affect the available map names.")); + ui.label(tr("Select the naming pattern used to display the input maps on this page.")); + ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); }); }); } @@ -641,7 +641,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); + ui.label(RichText::new(tr("Drag and drop maps on output's channels to setup your export.")).color(tokens.text_dim)); // Count only maps that have sources in the current set if let Ok(names) = &preview { diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3aee5ed8..ba01ae14 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -22,7 +22,7 @@ use inherited_settings::InheritedSettings; use map_row::MapRow; /// Height of the window's tab body, above its buttons -const BODY_HEIGHT: f32 = 440.0; +const BODY_HEIGHT: f32 = 660.0; /// Width of the texture set list const LIST_WIDTH: f32 = 180.0; const ICON: f32 = 20.0; @@ -177,7 +177,7 @@ fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, b ui.add_enabled(false, egui::Button::selectable(false, *name)).on_disabled_hover_text(tr(NOT_AVAILABLE)); } } - ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); + ui.separator().on_hover_text(tr("This preset is not available for the current project")); for name in rest { changed |= ui.selectable_value(current, name.clone(), name).on_hover_text(name).changed(); } @@ -241,7 +241,7 @@ fn start_export(app: &mut TextureCraftApp) { let e = &mut app.ui.export; e.tab = 2; - e.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; + e.console = vec![ConsoleLine::Step(tr("Preparing export...").into())]; if let Some(error) = error { e.console.push(ConsoleLine::Step(error.clone())); app.toast(error, true); @@ -299,14 +299,14 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { if job.pending.is_empty() { let written = std::mem::take(&mut job.written); let console = &mut app.ui.export.console; - console.push(ConsoleLine::Step(tr("All selected texture sets processed").into())); + console.push(ConsoleLine::Step(tr("Bitmaps write finalization...").into())); if written.is_empty() { console.push(ConsoleLine::Step(tr("No files were written").into())); } else { console.extend([ - ConsoleLine::Step(tr("Collecting the exported files").into()), - ConsoleLine::Done(tr("Texture export complete").into()), - ConsoleLine::Done(tr("Files saved").into()), + ConsoleLine::Step(tr("Finalizing export...").into()), + ConsoleLine::Done(tr("Export successfully finished").into()), + ConsoleLine::Done(tr("Successfully exported:").into()), ]); console.extend(written.into_iter().map(ConsoleLine::Done)); } @@ -332,7 +332,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } let set = || ConsoleLine::Set(name.clone()); - app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); + app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Computing textures results").into())]); // Protect concrete files and UDIM references from earlier texture sets if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) { @@ -347,11 +347,11 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); - let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; + let mut lines = vec![set(), ConsoleLine::Step(tr("Preparing textures writing").into())]; for file in &files { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); - lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); + lines.push(ConsoleLine::Step(trf("Writing {file} texture on disk", &[("file", &stem)]))); } // The export's warnings go to the console and the log, each once per export @@ -368,7 +368,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { lines.push(ConsoleLine::Step(trf("Warning: {message}", &[("message", &warning)]))); } - lines.extend([set(), ConsoleLine::Step(tr("Finished writing this texture set").into())]); + lines.extend([set(), ConsoleLine::Step(tr("Finalizing textures writing").into())]); app.ui.export.console.extend(lines); if let Some(job) = app.ui.export.job.as_mut() { job.written.extend(files); @@ -526,7 +526,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { } } ui.separator(); - for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { + for (i, label) in [tr("Enable override for all items"), tr("Disable override for all items")].into_iter().enumerate() { if ui.button(label).clicked() { menu = Some(3 + i); } @@ -644,7 +644,7 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { if enabled { r.response.on_hover_text(tr("Dilation in pixels")); } else { - r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); + r.response.on_disabled_hover_text(tr("Dilation cannot be applied to selected padding type")); } } @@ -661,7 +661,7 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { let mut reset = false; header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); + reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Resets all settings to default values"), false, ICON).clicked(); }); if reset { let defaults = ExportUi::default(); @@ -732,8 +732,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] }); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); - unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + unavailable_checkbox(ui, tr("Export USD asset"), tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); + unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); // The browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] @@ -874,10 +874,10 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor let mut all = None; header(ui, tr("General Export Parameters"), |ui| { list_menu(ui, |ui| { - if ui.button(tr("Override every item")).clicked() { + if ui.button(tr("Enable override for all items")).clicked() { all = Some(true); } - if ui.button(tr("Clear all overrides")).clicked() { + if ui.button(tr("Disable override for all items")).clicked() { all = Some(false); } ui.separator(); @@ -1005,9 +1005,9 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// "Texture set " with the name in bold +/// "Exporting texture set ..." with the name in bold fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { - let text = tr("Texture set {set}"); + let text = tr("Exporting texture set {set}..."); let (before, after) = text.split_once("{set}").unwrap_or((text, "")); let font = egui::TextStyle::Body.resolve(ui.style()); let plain = egui::TextFormat::simple(font.clone(), tk.text); @@ -1266,7 +1266,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(900.0, 520.0)).show(ctx, |ui| { + crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(1100.0, 740.0)).show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { ui.label(tr("No project is open")); @@ -1290,7 +1290,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.button(tr("Open output directory")).clicked() { open_output_directory(app); } - } else if ui.button(tr("Include all")).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { + } else if ui.button(tr("Include all")).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { o.maps.values_mut().for_each(|m| m.enabled = true); @@ -1346,7 +1346,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let selected = selected_texture_count(app); ui.horizontal(|ui| { // Not on LIST OF EXPORTS - if app.ui.export.tab != 2 && ui.button(tr("Reset all")).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() { + if app.ui.export.tab != 2 && ui.button(tr("Reset all")).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() { // Keep ownership so Cancel can restore the opening settings let e = &mut app.ui.export; let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); @@ -1355,15 +1355,15 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Nothing to write without a ticked texture set let any = !export_selection(app).is_empty(); - if ui.add_enabled(any, primary_button(ui, tr("Export"))).on_hover_text(tr("Write the selected textures using the settings above")).clicked() { + if ui.add_enabled(any, primary_button(ui, tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { do_export = true; } // Saving closes the window without starting an export - if ui.button(tr("Save settings")).on_hover_text(tr("Keep these settings for the next export")).clicked() { + if ui.button(tr("Save settings")).on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } - if ui.button(tr("Cancel")).on_hover_text(tr("Restore the settings from when you opened this window")).clicked() { + if ui.button(tr("Cancel")).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { canceled = true; } ui.label(trf("{n} textures selected for export", &[("n", &selected)])); diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 77d67503..8e627895 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -104,10 +104,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { assert!(h.query_by_label("*").is_some(), "the set is marked"); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Override every item"); + click(&mut h, "Enable override for all items"); assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Clear all overrides"); + click(&mut h, "Disable override for all items"); assert!(maps(&h).is_empty()); } diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 9a26f2be..b90d785e 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -161,7 +161,7 @@ fn restoring_the_default_parameters_unticks_export_materialx() { app_harness.run_steps(3); assert!(app_harness.state().ui.export.materialx); - app_harness.get_by_label("Restore the default export parameters").click(); + app_harness.get_by_label("Resets all settings to default values").click(); app_harness.run_steps(3); assert!(!app_harness.state().ui.export.materialx); } diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 9edb2ee5..2ca24b0d 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -117,14 +117,14 @@ fn the_header_menu_switches_every_override() { // The set list has the same menu button; the page header's is the second page_menu(&mut h); - click(&mut h, "Override every item"); + click(&mut h, "Enable override for all items"); let o = overrides(&h); assert!(o.preset.is_some() && o.file_type.is_some() && o.size.is_some() && o.padding.is_some(), "{o:?}"); // The default template writes 8- and 16-bit files: the override keeps them until a type is picked assert_eq!(o.file_type.unwrap().format, ""); page_menu(&mut h); - click(&mut h, "Clear all overrides"); + click(&mut h, "Disable override for all items"); assert!(h.state().ui.export.sets.is_empty()); } @@ -157,7 +157,7 @@ fn export_writes_each_set_with_its_overrides_and_cancel_drops_them() { h.run_steps(1); } h.run_steps(2); - let finished = h.state().ui.export.console.iter().any(|l| matches!(l, ConsoleLine::Done(t) if t == "Texture export complete")); + let finished = h.state().ui.export.console.iter().any(|l| matches!(l, ConsoleLine::Done(t) if t == "Export successfully finished")); assert!(h.state().ui.export.job.is_none() && finished, "the export finished"); let sets: Vec = h.state().session.doc.project.texture_sets.iter().map(|t| format!("_{}_", t.name)).collect(); let files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "png")).collect(); diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 84015102..46cee48f 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -34,7 +34,7 @@ fn console(h: &Harness<'_, TextureCraftApp>) -> Vec { .iter() .map(|l| match l { ConsoleLine::Step(t) | ConsoleLine::Done(t) => t.clone(), - ConsoleLine::Set(name) => format!("Texture set {name}"), + ConsoleLine::Set(name) => format!("Exporting texture set {name}..."), }) .collect() } @@ -48,7 +48,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { h.run_steps(1); assert!(h.query_by_label("Cancel Export").is_some()); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); - assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export")); + assert_eq!(console(&h).first().map(String::as_str), Some("Preparing export...")); for _ in 0..64 { if h.state().ui.export.job.is_none() { @@ -61,14 +61,14 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { assert!(h.state().ui.windows.export, "the window stays open"); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Cancel Export").is_none()); let lines = console(&h); - let set = format!("Texture set {}", sets[0]); + let set = format!("Exporting texture set {}...", sets[0]); let start = lines.iter().position(|l| *l == set).unwrap(); - assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Rendering the selected maps".into(), set.clone(), "Saving texture files".into()]); - assert!(lines[start + 6].starts_with("Saved texture "), "{lines:?}"); + assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Computing textures results".into(), set.clone(), "Preparing textures writing".into()]); + assert!(lines[start + 6].starts_with("Writing ") && lines[start + 6].ends_with(" texture on disk"), "{lines:?}"); let written: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); - let finished = lines.iter().position(|l| l == "Texture export complete").unwrap(); - assert_eq!(&lines[finished - 3..finished], ["Finished writing this texture set", "All selected texture sets processed", "Collecting the exported files"]); - assert_eq!(lines[finished + 1], "Files saved"); + let finished = lines.iter().position(|l| l == "Export successfully finished").unwrap(); + assert_eq!(&lines[finished - 3..finished], ["Finalizing textures writing", "Bitmaps write finalization...", "Finalizing export..."]); + assert_eq!(lines[finished + 1], "Successfully exported:"); assert_eq!(lines.len() - finished - 2, written.len(), "every written file is listed"); assert!(matches!(h.state().ui.export.console.last(), Some(ConsoleLine::Done(_))), "in green"); let _ = std::fs::remove_dir_all(&dir); @@ -113,7 +113,7 @@ fn cancel_export_stops_the_export() { assert!(h.state().ui.export.job.is_none()); assert!(h.state().ui.windows.export); let lines = console(&h); - assert!(!lines.iter().any(|l| l == "Collecting the exported files" || l == "Texture export complete"), "the export did not finish: {lines:?}"); + assert!(!lines.iter().any(|l| l == "Finalizing export..." || l == "Export successfully finished"), "the export did not finish: {lines:?}"); assert!(h.query_by_label("Cancel").is_some(), "the buttons are back"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs new file mode 100644 index 00000000..39d9b959 --- /dev/null +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -0,0 +1,69 @@ +//! Export textures window (texturecraft #789): the reference's size, tab labels, button tooltips +//! and settings texts, word for word. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; + +/// The Export textures window open on SETTINGS +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.prefs.language = "en".into(); + h.run_steps(4); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + h +} + +/// Hover the newest node labelled `label` until its tooltip shows +fn hover(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + let center = h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).rect().center(); + h.hover_at(center); + h.run_steps(30); +} + +/// Hover `label` and check that its tooltip says `tooltip` +fn tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, tooltip: &str) { + hover(h, label); + assert!(h.query_all_by_label(tooltip).next().is_some(), "{label}: {tooltip}"); +} + +#[test] +fn the_window_is_as_wide_as_the_reference_window() { + let h = harness(); + let reset = h.get_by_label("Reset all").rect(); + let save = h.get_by_label("Save settings").rect(); + + // The reference window is 1100 wide; the buttons sit at its two ends (it was 900 wide) + assert!(save.max.x - reset.min.x > 900.0, "{reset:?} {save:?}"); +} + +#[test] +fn the_tabs_read_in_capitals() { + let h = harness(); + for tab in ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS"] { + assert!(h.query_by_label(tab).is_some(), "{tab}"); + } +} + +#[test] +fn the_buttons_carry_the_reference_tooltips() { + let mut h = harness(); + tooltip_is(&mut h, "Include all", "Includes all Texture Sets, UV Tiles and output maps."); + tooltip_is(&mut h, "Reset all", "Resets all settings to their default values, including all textures."); + tooltip_is(&mut h, "Cancel", "Closes the export window and undoes all recent changes"); + tooltip_is(&mut h, "Save settings", "Closes the export window and saves changes"); + tooltip_is(&mut h, "Export", "Exports all selected textures and additional files"); +} + +#[test] +fn the_unavailable_checkboxes_carry_the_reference_texts() { + let mut h = harness(); + tooltip_is( + &mut h, + "Export USD asset", + "Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise", + ); + tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); +} diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 98af3660..afabdee1 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -143,7 +143,7 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); - assert!(h.query_by_label("This padding mode does not use a dilation width").is_some()); + assert!(h.query_by_label("Dilation cannot be applied to selected padding type").is_some()); h.state_mut().ui.export.padding = "dilation".into(); h.run_steps(3); hover(&mut h, "16"); @@ -166,7 +166,7 @@ fn the_page_reset_puts_the_parameters_back() { e.padding = "none".into(); e.skip = vec![0]; h.run_steps(3); - click(&mut h, "Restore the default export parameters"); + click(&mut h, "Resets all settings to default values"); let e = &h.state().ui.export; assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d9ed98f0..a4bbd233 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -25,6 +25,7 @@ mod export_map_overrides; mod export_materialx; mod export_overrides; mod export_progress; +mod export_reference_texts; mod export_settings; mod export_template_guards; mod file_dialogs; diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index aaf66fce..bb9c5d5e 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -45,7 +45,7 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drag and drop maps on output's channels to setup your export."] { assert!(h.query_by_label(text).is_some(), "{text}"); } assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); @@ -63,8 +63,8 @@ fn the_tab_shows_the_preset_tools_and_map_editor() { let info = h.get_by_label(egui_phosphor::regular::INFO).rect().center(); h.hover_at(info); h.run_steps(30); - assert!(h.query_by_label("Choose how the input maps are named in this editor.").is_some()); - assert!(h.query_by_label("The active texture set’s shader can affect the available map names.").is_some()); + assert!(h.query_by_label("Select the naming pattern used to display the input maps on this page.").is_some()); + assert!(h.query_by_label("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.").is_some()); } #[test] diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index d05f19a1..052068a6 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -101,10 +101,12 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { assert_eq!(harness.state().ui.rail_panel, Some(Panel::Export)); assert!(!harness.state().ui.windows.export, "the rail opens the Export panel, not a window"); - for label in ["SEND TO", "EXPORT", "Export to image editor", "Send to compositing app", "Send to 3D staging app"] { - assert!(harness.query_all_by_label(label).next().is_some(), "{label}"); + assert!(harness.query_all_by_label("EXPORT").next().is_some(), "the EXPORT caption"); + for label in ["SEND TO", "Export to image editor", "Send to compositing app", "Send to 3D staging app"] { + assert!(harness.query_all_by_label(label).next().is_none(), "the dock has no {label} row"); } - assert!(says_not_available(&mut harness, "Send to compositing app")); + assert!(harness.query_all_by_label_contains("Send to").next().is_none(), "no SEND TO text at all"); + button_left_of_rail(&harness, "Export Mesh..."); button_left_of_rail(&harness, "Export Textures...").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b8e6d060..8c392573 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -63,9 +63,8 @@ when it is not docked). Each opens a popup beside the bar with its title in capi button that turns it into a floating window, and *Close*. A floating rail panel has a *Dock* button that closes it back onto the bar; the float is saved with the UI state. -- **Export:** SEND TO lists three targets and a Configure button, all greyed with "Not available - yet". The reference names other products there; TextureCraft says *Export to image editor*, - *Send to compositing app* and *Send to 3D staging app*. EXPORT has *Export Mesh...* (the +- **Export:** the dock shows EXPORT only (the reference's SEND TO part has no counterpart here and + is left out, [#789](https://github.com/storytold/texturecraft/issues/789)). EXPORT has *Export Mesh...* (the *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected @@ -280,24 +279,25 @@ that numbers hide once a tile is under 40 points on screen. - **SETTINGS** ([#671](https://github.com/storytold/texturecraft/issues/671)): the texture set list has the reference's menu (*Check all*, *Uncheck all*, *Invert all*); *General Export - Parameters* has its reset button ("Restore the default export parameters"). *Output directory* + Parameters* has its reset button ("Resets all settings to default values"). *Output directory* is a button showing the path (it opens the folder picker) with an *R* button ("Reset to default"). The template list starts with the reference's first group (TextureCraft has "Document channels + Normal + AO (No Alpha)", the new name of its default template, and "glTF PBR Metal Roughness"; the others are greyed with "Not available yet"; one entry names another - vendor's product and is left out), then a separator ("Some templates in this list are unavailable") and every other template sorted by name. File type lists "Based on output + vendor's product and is left out), then a separator ("This preset is not available for the current project") and every other template sorted by name. File type lists "Based on output template", then the types in the reference order and names ("targa", "jpeg", "tiff"). Size adds "Maximum size for all Texture Sets" and 128. Padding uses the reference order; the dilation width is a button with a "Dilation (pixels)" slider, greyed for paddings without a - width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry - tooltips explaining which settings are applied, kept or restored. + width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry the + reference's tooltips word for word. The window is 1100 x 740 as in the reference + ([#789](https://github.com/storytold/texturecraft/issues/789)). Cancel, and closing the window, go back to the settings the window opened with; the window always opens on SETTINGS. - **Texture set pages** ([#669](https://github.com/storytold/texturecraft/issues/669)): a click on a texture set row shows its *General Export Parameters*: Output template, File type, Size and Padding with the inherited value as text (for example "1024x1024 (Texture Set size)"). The pencil button ("Enable override") turns a row into its list; a set with an override gets "*" - ("Override(s) active"). The header menu has *Override every item* and *Disable + ("Override(s) active"). The header menu has *Enable override for all items* and *Disable override for all items*. The template list leaves out the entries the reference leaves out there; sizes read "128x128" ... "8192x8192". Export, the footer count and LIST OF EXPORTS use each set's own settings. Ticks and overrides belong to the project and follow each texture set @@ -307,7 +307,7 @@ that numbers hide once a tile is under 40 points on screen. parameters, one row per map the set exports: a tick, the file name pattern (cut at the front with "…" when long, the whole pattern as tooltip), its own *Enable override* and the inherited "png 8 bits". An override gives the map its own file type and bit depth (`maps` of - `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Override every item* and *Clear all overrides*; *Include all* ticks every map + `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Enable override for all items* and *Disable override for all items*; *Include all* ticks every map again. The patterns are cut after 26 characters (the reference cuts by pixel width). - **File types** ([#672](https://github.com/storytold/texturecraft/issues/672)): File type lists bmp, jpeg, jng, pgm, png, targa, tiff, hdr, exr, j2k, jp2, webp, psd and sbsar; j2k, jp2 From 7e129c3968011dc976e6b9e85213d4bfd917c086 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:00:35 +0100 Subject: [PATCH 065/153] Put the MaterialX export option directly below the USD one --- crates/ui-egui/src/export_window.rs | 4 ++-- crates/ui-egui/tests/it/export_materialx.rs | 10 ++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index ba01ae14..4c1d87ae 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -733,13 +733,13 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // Unavailable export controls stay disabled unavailable_checkbox(ui, tr("Export USD asset"), tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); - unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); - // The browser downloads the textures only + // The MaterialX export sits below the USD one; the browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] ui.checkbox(&mut app.ui.export.materialx, tr("Export MaterialX")); #[cfg(target_arch = "wasm32")] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); + unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index b90d785e..328078aa 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -47,6 +47,16 @@ fn mtlx_files(dir: &std::path::Path) -> Vec { files } +#[test] +fn export_materialx_sits_directly_below_the_usd_option() { + let (app_harness, _dir) = harness("order"); + let usd = app_harness.get_by_label("Export USD asset").rect().min.y; + let materialx = checkbox(&app_harness).rect().min.y; + let shaders = app_harness.get_by_label("Export shaders parameters").rect().min.y; + + assert!(usd < materialx && materialx < shaders, "USD {usd}, MaterialX {materialx}, shaders {shaders}"); +} + #[test] fn the_window_offers_export_materialx_off_by_default() { let (app_harness, _dir) = harness("offer"); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8c392573..3cb62522 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -68,7 +68,7 @@ that closes it back onto the bar; the float is saved with the UI state. *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected - for export"). *Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` + for export"). *Export MaterialX* below *Export USD asset* is a TextureCraft addition: it adds `materialX: true` to the export. The prompt's *With displacement/tessellation* choice and both option checkboxes are greyed; TextureCraft exports the mesh as it is. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the From 81627ab8c71ec62e52fad7142bd7bdc649aee354 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:09:54 +0100 Subject: [PATCH 066/153] Fit the export window to small screens and tighten its tests --- crates/ui-egui/src/export_window.rs | 34 +++++--- crates/ui-egui/src/state/console_line.rs | 2 +- .../tests/it/export_reference_texts.rs | 86 +++++++++++++------ 3 files changed, 84 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 4c1d87ae..3fe1b4e1 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -21,8 +21,14 @@ mod map_row; use inherited_settings::InheritedSettings; use map_row::MapRow; -/// Height of the window's tab body, above its buttons -const BODY_HEIGHT: f32 = 660.0; +/// The reference window's size; a smaller screen gets a smaller window +const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); +/// Space kept free around the content on a small screen: the title bar, the frame and a gap +const WINDOW_VIEWPORT_MARGIN_POINTS: f32 = 72.0; +/// Height of the tab row, the separators and the bottom bar around the tab body +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 80.0; +/// The smallest tab body, so the lists and pages stay usable +const MIN_BODY_HEIGHT_POINTS: f32 = 160.0; /// Width of the texture set list const LIST_WIDTH: f32 = 180.0; const ICON: f32 = 20.0; @@ -732,7 +738,11 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] }); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export USD asset"), tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); + unavailable_checkbox( + ui, + tr("Export USD asset"), + tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise"), + ); // The MaterialX export sits below the USD one; the browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] @@ -769,7 +779,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] /// The left column: Global settings, then a row per texture set with its export tick; a click /// on a row shows the set's page, "*" marks a set with overrides -fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { +fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, body_height: f32) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); }); @@ -779,7 +789,7 @@ fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { } // Many texture sets scroll inside the list; the footer stays in view - let list_height = BODY_HEIGHT - header.rect.height() - ui.spacing().item_spacing.y; + let list_height = body_height - header.rect.height() - ui.spacing().item_spacing.y; egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); } @@ -1266,7 +1276,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(1100.0, 740.0)).show(ctx, |ui| { + let window_size = REFERENCE_WINDOW_SIZE_POINTS.min(ctx.content_rect().size() - vec2(WINDOW_VIEWPORT_MARGIN_POINTS, WINDOW_VIEWPORT_MARGIN_POINTS)); + let body_height = (window_size.y - WINDOW_CHROME_HEIGHT_POINTS).max(MIN_BODY_HEIGHT_POINTS); + crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(window_size).show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { ui.label(tr("No project is open")); @@ -1300,8 +1312,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); ui.separator(); - ui.allocate_ui_with_layout(vec2(ui.available_width(), BODY_HEIGHT), egui::Layout::left_to_right(egui::Align::Min), |ui| { - ui.set_height(BODY_HEIGHT); + ui.allocate_ui_with_layout(vec2(ui.available_width(), body_height), egui::Layout::left_to_right(egui::Align::Min), |ui| { + ui.set_height(body_height); match app.ui.export.tab { 1 => { crate::export_templates::tab(app, ui, &presets); @@ -1316,7 +1328,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.vertical(|ui| { ui.set_width(LIST_WIDTH); - set_list(app, ui); + set_list(app, ui, body_height); }); ui.separator(); ui.vertical(|ui| match app.ui.export.page { @@ -1346,7 +1358,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let selected = selected_texture_count(app); ui.horizontal(|ui| { // Not on LIST OF EXPORTS - if app.ui.export.tab != 2 && ui.button(tr("Reset all")).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() { + if app.ui.export.tab != 2 + && ui.button(tr("Reset all")).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() + { // Keep ownership so Cancel can restore the opening settings let e = &mut app.ui.export; let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); diff --git a/crates/ui-egui/src/state/console_line.rs b/crates/ui-egui/src/state/console_line.rs index 196a5b60..26baa2ce 100644 --- a/crates/ui-egui/src/state/console_line.rs +++ b/crates/ui-egui/src/state/console_line.rs @@ -2,7 +2,7 @@ #[derive(Clone, Debug, PartialEq)] pub enum ConsoleLine { Step(String), - /// "Texture set " with the name in bold. + /// "Exporting texture set ..." with the name in bold. Set(String), /// A success line, in green. Done(String), diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 39d9b959..6c176f56 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -1,14 +1,24 @@ -//! Export textures window (texturecraft #789): the reference's size, tab labels, button tooltips -//! and settings texts, word for word. +//! Export textures window (texturecraft #789): the reference's size, button tooltips and settings +//! texts, word for word. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable as _; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; -/// The Export textures window open on SETTINGS -fn harness() -> Harness<'static, TextureCraftApp> { +/// The reference window's content size in points +const REFERENCE_WINDOW_WIDTH_POINTS: f32 = 1100.0; +const REFERENCE_WINDOW_HEIGHT_POINTS: f32 = 740.0; + +/// How far the measured content may differ from the reference size (item spacing, borders) +const SIZE_TOLERANCE_POINTS: f32 = 40.0; + +/// The right bar is the last 38 points of the window +const RAIL_WIDTH_POINTS: f32 = 38.0; + +/// The Export textures window open on SETTINGS in a screen of `screen_size` +fn harness(screen_size: egui::Vec2) -> 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)); + let mut h = Harness::builder().with_size(screen_size).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.windows.export = true; @@ -16,40 +26,53 @@ fn harness() -> Harness<'static, TextureCraftApp> { h } -/// Hover the newest node labelled `label` until its tooltip shows -fn hover(h: &mut Harness<'_, TextureCraftApp>, label: &str) { - let center = h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).rect().center(); - h.hover_at(center); - h.run_steps(30); +/// The rectangle of the window's button named `label`; the rail has an Export icon of its own +fn window_button_rect(h: &Harness<'_, TextureCraftApp>, label: &str, screen_width: f32) -> egui::Rect { + h.get_all_by_role(egui::Role::Button) + .filter(|button| button.rect().max.x < screen_width - RAIL_WIDTH_POINTS && button.accesskit_node().label().as_deref() == Some(label)) + .map(|button| button.rect()) + .next_back() + .unwrap_or_else(|| panic!("no {label} button in the window")) } -/// Hover `label` and check that its tooltip says `tooltip` +/// Hover the window's button `label` and check that its tooltip says `tooltip` fn tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, tooltip: &str) { - hover(h, label); + let screen_width = h.ctx.content_rect().width(); + h.hover_at(window_button_rect(h, label, screen_width).center()); + h.run_steps(30); + assert!(h.query_all_by_label(tooltip).next().is_some(), "{label}: {tooltip}"); } #[test] -fn the_window_is_as_wide_as_the_reference_window() { - let h = harness(); - let reset = h.get_by_label("Reset all").rect(); - let save = h.get_by_label("Save settings").rect(); +fn the_window_has_the_reference_size() { + let h = harness(egui::vec2(1600.0, 960.0)); + let reset = window_button_rect(&h, "Reset all", 1600.0); + let export = window_button_rect(&h, "Export", 1600.0); + let tabs = h.get_by_label("SETTINGS").rect(); - // The reference window is 1100 wide; the buttons sit at its two ends (it was 900 wide) - assert!(save.max.x - reset.min.x > 900.0, "{reset:?} {save:?}"); + let width = export.max.x - reset.min.x; + let height = export.max.y - tabs.min.y; + + assert!((width - REFERENCE_WINDOW_WIDTH_POINTS).abs() < SIZE_TOLERANCE_POINTS, "width {width}"); + assert!((height - REFERENCE_WINDOW_HEIGHT_POINTS).abs() < SIZE_TOLERANCE_POINTS, "height {height}"); } #[test] -fn the_tabs_read_in_capitals() { - let h = harness(); - for tab in ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS"] { - assert!(h.query_by_label(tab).is_some(), "{tab}"); +fn on_a_small_screen_the_window_fits_with_its_buttons_in_view() { + let screen = egui::vec2(1000.0, 700.0); + let h = harness(screen); + + for label in ["Reset all", "Cancel", "Save settings", "Export"] { + let rect = window_button_rect(&h, label, screen.x); + assert!(rect.min.x >= 0.0 && rect.max.x <= screen.x, "{label} {rect:?}"); + assert!(rect.min.y >= 0.0 && rect.max.y <= screen.y, "{label} {rect:?}"); } } #[test] fn the_buttons_carry_the_reference_tooltips() { - let mut h = harness(); + let mut h = harness(egui::vec2(1600.0, 960.0)); tooltip_is(&mut h, "Include all", "Includes all Texture Sets, UV Tiles and output maps."); tooltip_is(&mut h, "Reset all", "Resets all settings to their default values, including all textures."); tooltip_is(&mut h, "Cancel", "Closes the export window and undoes all recent changes"); @@ -57,13 +80,22 @@ fn the_buttons_carry_the_reference_tooltips() { tooltip_is(&mut h, "Export", "Exports all selected textures and additional files"); } +/// Hover the checkbox `label` and check that its tooltip says `tooltip` +fn checkbox_tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, tooltip: &str) { + let center = h.get_by_role_and_label(egui::Role::CheckBox, label).rect().center(); + h.hover_at(center); + h.run_steps(30); + + assert!(h.query_all_by_label(tooltip).next().is_some(), "{label}: {tooltip}"); +} + #[test] fn the_unavailable_checkboxes_carry_the_reference_texts() { - let mut h = harness(); - tooltip_is( + let mut h = harness(egui::vec2(1600.0, 960.0)); + checkbox_tooltip_is( &mut h, "Export USD asset", "Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise", ); - tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); + checkbox_tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); } From e1577e36866da074ffad238524c631452b4bcaaf Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:06:35 +0100 Subject: [PATCH 067/153] Bind only the textures the export kept in the USD asset Each usdAsset entry now carries the reservedNames its command ran with, and the asset applies the same reservation rule as the texture export (reserved file names and UDIM patterns, then earlier files of the job), so it never binds a file the export skipped. --- crates/engine/src/file_cmds.rs | 70 ++++++++++----------- crates/engine/tests/it/usd_asset.rs | 51 ++++++++++++--- crates/ui-egui/src/export_window.rs | 7 +-- crates/ui-egui/tests/it/export_usd_asset.rs | 21 +++++++ docs/control-protocol.md | 6 +- docs/features.md | 4 +- 6 files changed, 106 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ddc612b2..006bb979 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts and options, a list gives each texture set's own `ts` and options, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -735,20 +735,22 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { /// What the warning of a USD asset that could not be written starts with (`file.exportTextures`). pub const USD_ASSET_FAILED: &str = "The USD asset was not written"; -/// The texture sets and options of the exports a USD asset refers to. +/// The texture sets, options and `reservedNames` of one export a USD asset refers to. #[cfg(not(target_arch = "wasm32"))] -type UsdExports = Vec<(Vec, ExportOptions)>; +type UsdAssetExport = (Vec, ExportOptions, HashMap>); -/// What `usdAsset` asks for: the texture sets and options of each export whose textures the USD -/// asset refers to. `true` is this command's own; a list gives every entry's `ts` and options. +/// What `usdAsset` asks for: the texture sets, options and `reservedNames` of each export whose +/// textures the USD asset refers to. `true` is this command's own; a list gives every entry's. #[cfg(not(target_arch = "wasm32"))] -fn usd_asset_param(s: &Session, p: &Value, opts: &ExportOptions, sets: &[usize]) -> Result> { - match p.get("usdAsset") { +fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, sets: &[usize]) -> Result>> { + match params.get("usdAsset") { None | Some(Value::Null | Value::Bool(false)) => Ok(None), - Some(Value::Bool(true)) => Ok(Some(vec![(sets.to_vec(), opts.clone())])), + Some(Value::Bool(true)) => Ok(Some(vec![(sets.to_vec(), options.clone(), reserved_names(params)?)])), Some(Value::Array(exports)) if !exports.is_empty() && exports.iter().all(Value::is_object) => exports .iter() - .map(|export| Ok((sets_param(s, export, "file.exportTextures")?, export_options(s, export, "file.exportTextures")?))) + .map(|export| { + Ok((sets_param(session, export, "file.exportTextures")?, export_options(session, export, "file.exportTextures")?, reserved_names(export)?)) + }) .collect::>>() .map(Some), Some(_) => Err(bad("file.exportTextures", "`usdAsset` must be true, false or a non-empty list of export param objects")), @@ -760,53 +762,49 @@ fn usd_asset_param(s: &Session, p: &Value, opts: &ExportOptions, sets: &[usize]) /// wrote (see `texturecraft_formats::usd_texture_bindings`). A failure to build or write it is a /// warning: the textures of the command are already written. #[cfg(not(target_arch = "wasm32"))] -fn write_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, ExportOptions)], warnings: &mut Vec) -> Option { - match build_usd_asset(s, dir, exports) { +fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Option { + match build_usd_asset(session, dir, exports) { Ok(path) => Some(path), - Err(e) => { - warnings.push(format!("{USD_ASSET_FAILED}: {e}")); + Err(error) => { + warnings.push(format!("{USD_ASSET_FAILED}: {error}")); None } } } #[cfg(not(target_arch = "wasm32"))] -fn build_usd_asset(s: &Session, dir: &std::path::Path, exports: &[(Vec, ExportOptions)]) -> Result { +fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result { use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings}; - let project = &s.doc.project; + let project = &session.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); - // The bindings of every texture set that was exported, from the files its export planned - let mut taken = std::collections::HashSet::new(); - let mut by_set = std::collections::HashMap::new(); - for (sets, opts) in exports { + // Keep the files each export kept, by the rule `file.exportTextures` applies to its reserved and earlier names + let mut taken_names = HashMap::new(); + let mut by_set = HashMap::new(); + for (sets, options, reserved) in exports { + for name in reserved.keys() { + taken_names.entry(name.clone()).or_insert(None); + } + let reserved_patterns: Vec<_> = reserved.keys().filter(|name| name.contains("")).cloned().collect(); + for &set in sets { - let texture_set = project.texture_set(set).map_err(|e| EngineError::Other(e.to_string()))?; - - // A file whose name an earlier file of this job has was not written by this export. A - // map that lost any file (a tile of a UDIM map) is not bound: its `` name would - // read the tile of another texture set. - let mut skipped_maps = std::collections::HashSet::new(); - let mut kept = Vec::new(); - for file in list_outputs(project, set, &mesh_name, opts).map_err(fe)? { - if taken.insert(file.name.to_ascii_lowercase()) { - kept.push(file); - } else { - skipped_maps.insert(file.map); - } - } + let texture_set = project.texture_set(set).map_err(|error| EngineError::Other(error.to_string()))?; + let mut kept = list_outputs(project, set, &mesh_name, options).map_err(fe)?; + let skipped_maps = reserve_export_names(set, &mut kept, &mut taken_names, &reserved_patterns, &mut Vec::new(), false); + // A map that lost any file (a tile of a UDIM map) is not bound: its `` name would read a file it does not own kept.retain(|file| !skipped_maps.contains(&file.map)); - by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, opts, project.normal_format, &kept)); + by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept)); } } // A mesh without materials has one implicit material (and texture set) - let mut mesh = s.source_mesh(); + let mut mesh = session.source_mesh(); if mesh.materials.is_empty() { mesh.materials.push("default".into()); } - let bindings: Vec<_> = (0..mesh.materials.len()).map(|m| s.texture_set_of_material(m).and_then(|set| by_set.remove(&set)).unwrap_or_default()).collect(); + let bindings: Vec<_> = + (0..mesh.materials.len()).map(|material| session.texture_set_of_material(material).and_then(|set| by_set.remove(&set)).unwrap_or_default()).collect(); let layer = usd_layer_with_textures(&mesh, &project.name, &bindings).map_err(fe)?; let path = dir.join(format!("{}.usd", texturecraft_formats::export::sanitize_file_stem(&mesh_name))); texturecraft_formats::write_atomic(&path, &layer).map_err(fe)?; diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index dfba38fa..e6ef7bd9 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -318,21 +318,34 @@ fn a_material_without_a_texture_set_has_no_textures() { assert!(materials[1].0.is_empty(), "{:?}", materials[1]); } -/// A material per half of a two-tile plane: the first material covers tiles 1001 and 1002, the second 1002 and 1003 -fn overlapping_tiles() -> Session { +/// Two two-tile planes, a material each: the first covers tiles 1001 and 1002, the second starts `shift_tiles` tiles to the right +fn two_udim_sets(shift_tiles: f32) -> Session { let mut mesh = primitives::udim_plane(); let mut second = primitives::udim_plane(); second.materials[0] = "Other".into(); for uv in &mut second.uvs { - uv.x += 1.0; + uv.x += shift_tiles; } mesh.append(&second); - let s = Session::new_project("t", mesh, "builtin:udim_plane", None, 128).unwrap(); + Session::new_project("t", mesh, "builtin:udim_plane", None, 128).unwrap() +} + +/// A material per half of a two-tile plane: the first material covers tiles 1001 and 1002, the second 1002 and 1003 +fn overlapping_tiles() -> Session { + let s = two_udim_sets(1.0); assert_eq!(s.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); assert_eq!(s.doc.project.texture_sets[1].uv_tiles, [1002, 1003]); s } +/// The shared colour map plus a roughness map whose names tell the texture sets apart +fn colour_and_own_roughness_template() -> Value { + let gray = json!([["L", {"Channel": {"channel": "Roughness", "component": 0}}]]); + let mut preset = shared_name_template(); + preset["maps"].as_array_mut().unwrap().push(json!({"file": "rough_$textureSet", "format": "Png", "bit_depth": 8, "channels": gray})); + preset +} + #[test] fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_are() { let mut s = overlapping_tiles(); @@ -340,10 +353,7 @@ fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_a // The colour map's names do not tell the sets apart, so tile 1002 of the second set is not written; // the roughness map's names do. - let gray = json!([["L", {"Channel": {"channel": "Roughness", "component": 0}}]]); - let mut preset = shared_name_template(); - preset["maps"].as_array_mut().unwrap().push(json!({"file": "rough_$textureSet", "format": "Png", "bit_depth": 8, "channels": gray})); - export(&mut s, &dir, json!({"ts": [0, 1], "preset": preset, "usdAsset": true})); + export(&mut s, &dir, json!({"ts": [0, 1], "preset": colour_and_own_roughness_template(), "usdAsset": true})); let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &s.mesh.materials); let (first, second) = (&materials[material_of(&s, 0)].0, &materials[material_of(&s, 1)].0); @@ -354,6 +364,31 @@ fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_a assert_ne!(first["roughness"].file, second["roughness"].file); } +#[test] +fn a_udim_map_whose_tiles_the_window_reserved_for_an_earlier_command_is_not_bound() { + let mut session = two_udim_sets(2.0); + assert_eq!(session.doc.project.texture_sets[1].uv_tiles, [1003, 1004]); + let dir = temp("reserved"); + let first = json!({"ts": 0, "preset": colour_and_own_roughness_template()}); + let written = export(&mut session, &dir, first.clone()); + + // The window reserves the earlier files and the UDIM patterns of earlier MaterialX documents + let mut reserved: Vec = files(&written).iter().map(|file| json!(std::path::Path::new(file).file_name().unwrap().to_str().unwrap())).collect(); + reserved.push(json!("colour..png")); + let second = json!({"ts": 1, "preset": colour_and_own_roughness_template(), "reservedNames": reserved}); + let mut last = second.clone(); + last["usdAsset"] = json!([first, second]); + export(&mut session, &dir, last); + + let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &session.mesh.materials); + let (first, second) = (&materials[material_of(&session, 0)].0, &materials[material_of(&session, 1)].0); + assert_eq!(first["diffuseColor"].file, "colour..png", "{first:?}"); + assert!(!dir.join("colour.1003.png").exists(), "the texture export skipped the reserved pattern"); + assert!(!second.contains_key("diffuseColor"), "the second set's colour tiles were not written: {second:?}"); + assert!(second["roughness"].file.starts_with("rough_") && second["roughness"].file.contains(""), "{second:?}"); + assert!(dir.join(second["roughness"].file.replace("", "1003")).is_file()); +} + #[test] fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { let mut mesh = primitives::plane(2.0, 4); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 4d41e787..1d4c9868 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -339,8 +339,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { params["reservedNames"] = job.written.iter().chain(&job.material_udim_patterns).map(|name| json!(name)).collect(); } - // The USD asset covers the whole mesh and refers to the textures of every texture set: the last command writes it, given - // the params every command of the export ran with, so a canceled or failed export writes none + // The last command writes the USD asset from the params of every command, so a canceled or failed export writes none if let Some(job) = app.ui.export.job.as_mut().filter(|job| job.usd_asset) { job.sent.push(params.clone()); if job.pending.is_empty() { @@ -353,8 +352,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { return; }; - // The one warning the window shows: the USD asset that could not be written - let usd_failure = response_strings(&response, "warnings").find(|w| w.starts_with(texturecraft_engine::file_cmds::USD_ASSET_FAILED)); + // A USD asset that could not be written also shows as an error toast + let usd_failure = response_strings(&response, "warnings").find(|warning| warning.starts_with(texturecraft_engine::file_cmds::USD_ASSET_FAILED)); if let Some(warning) = usd_failure { app.toast(warning.to_string(), true); } diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs index 6934c09c..68f310df 100644 --- a/crates/ui-egui/tests/it/export_usd_asset.rs +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -254,3 +254,24 @@ fn the_sent_command_of_a_texture_set_that_leaves_the_export_is_dropped() { h.run_steps(1); assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![0], vec![])); } + +#[test] +fn each_sent_command_keeps_the_names_it_reserved_for_the_asset() { + let (mut app_harness, dir) = harness("sent-reserved"); + let params = serde_json::json!({"dir": dir.display().to_string()}); + let pending = vec![(0, params.clone()), (1, params)]; + let settings = &mut app_harness.state_mut().ui.export; + settings.tab = 2; + settings.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, written: vec!["earlier.png".into()], ..ExportJob::default() }); + + for _ in 0..8 { + app_harness.run_steps(1); + if app_harness.state().ui.export.job.as_ref().is_none_or(|job| !job.sent.is_empty()) { + break; + } + } + + let job = app_harness.state().ui.export.job.as_ref().expect("the export is still running"); + let reserved = job.sent.first().and_then(|params| params["reservedNames"].as_array()).expect("the sent command carries its reserved names"); + assert!(reserved.iter().any(|name| name == "earlier.png"), "the asset skips what the texture export skipped: {reserved:?}"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8afab57e..7d1a1f33 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -50,13 +50,13 @@ and warn about later duplicates. The desktop export window reports the collision `file.exportTextures` with `usdAsset` also writes `.usd` (binary USD, Crate) next to the textures: the whole mesh (every texture set, whatever `ts` selects) with one UsdPreviewSurface material per texture set. A material's inputs read the texture files the export planned for that set with its output template -(`usdAsset: true`: the sets and options of this command; a list of export params such as -`[{"ts": 0, "preset": "..."}, {"ts": 1}]`, not empty, every entry an object: each entry's sets and options, the way the export window, +(`usdAsset: true`: the sets, options and `reservedNames` of this command; a list of export params such as +`[{"ts": 0, "preset": "..."}, {"ts": 1}]`, not empty, every entry an object: each entry's sets, options and `reservedNames`, the way the export window, which runs one command per texture set, passes the params of all its commands with the last one). Bound inputs: `diffuseColor`, `roughness`, `metallic`, `normal`, `emissiveColor`, `opacity`, `clearcoat` and `clearcoatRoughness`, each reading the `rgb`, `r`, `g`, `b` or `a` output of the file that holds it; other maps (ambient occlusion, height, specular...) are not bound, a UDIM map that lost a tile to an earlier -set's file name is not bound, a mesh with no materials gets one implicit `default` material bound to the Default set, and a texture set outside the export has +set's file name or to an entry's `reservedNames` is not bound, a mesh with no materials gets one implicit `default` material bound to the Default set, and a texture set outside the export has no textures. A file name is relative to the file (`./`, with `` for UV tiles). A failure to build or write it is named in `warnings` and the command still succeeds. The file is in `files`. diff --git a/docs/features.md b/docs/features.md index d4290f13..04702ee9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -184,8 +184,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA set was exported with (its own output template, file type, size and normal format) by relative file name. Base colour, roughness, metallic, normal, emissive colour, opacity, clear coat and clear coat roughness are bound; a packed template (ORM, mask map) binds several inputs to different - channels of one file. A UDIM map that lost a tile to an earlier texture set's file name gets no - binding, and a mesh with no materials gets one implicit "default" material bound to the Default + channels of one file. A UDIM map that lost a tile to an earlier texture set's file name or to a + UDIM pattern an earlier MaterialX document of the export uses gets no binding, and a mesh with no materials gets one implicit "default" material bound to the Default texture set. Ambient occlusion, height and specular are not bound (the material has occlusion, displacement and specularColor inputs, but TextureCraft does not fill them), nor are glossiness (no matching input) and baked maps; sheen, anisotropy, transmission, scatter and coat normal have no From cfc4b8b3a72732e2bd496eb7dd5fbdfa34c15081 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:29:18 +0100 Subject: [PATCH 068/153] Export textures and Mesh Export Options: plain Export buttons, fixed footer widths, reference dock buttons --- crates/ui-egui/src/export_panel.rs | 21 +++++++++++++------ crates/ui-egui/src/export_window.rs | 17 ++++++++++----- crates/ui-egui/src/mesh_export_options.rs | 14 ++++++++++--- .../tests/it/export_reference_texts.rs | 9 ++++++++ 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/export_panel.rs b/crates/ui-egui/src/export_panel.rs index 13dc88a7..d845d4d5 100644 --- a/crates/ui-egui/src/export_panel.rs +++ b/crates/ui-egui/src/export_panel.rs @@ -4,23 +4,32 @@ use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; -use crate::theme::caption; +use crate::theme::{Tokens, caption}; use crate::widgets::primary_button; -/// Width of the Export Mesh and Export Textures buttons -const EXPORT_BUTTON_WIDTH: f32 = 176.0; +/// Space around each button's text, so the buttons are as wide as their text as in the reference +const EXPORT_BUTTON_PADDING: egui::Vec2 = egui::vec2(18.0, 5.0); + +/// Gap between the Export Mesh and Export Textures buttons +const EXPORT_BUTTON_GAP: f32 = 12.0; /// The Export panel body (a rail popup or dock tab); its buttons need an open project pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(caption(&tr("Export").to_uppercase())); let project_open = app.session.project_open; + let tokens = Tokens::get(ui.ctx()); ui.vertical_centered(|ui| { - let size = [EXPORT_BUTTON_WIDTH, ui.spacing().interact_size.y]; - if ui.add_enabled(project_open, egui::Button::new(tr("Export Mesh...")).min_size(size.into())).clicked() { + ui.spacing_mut().button_padding = EXPORT_BUTTON_PADDING; + ui.spacing_mut().item_spacing.y = EXPORT_BUTTON_GAP; + + // Fully rounded: Export Mesh outlined, Export Textures filled + let pill = ui.spacing().interact_size.y + 2.0 * EXPORT_BUTTON_PADDING.y; + let outlined = egui::Button::new(tr("Export Mesh...")).fill(egui::Color32::TRANSPARENT).stroke(egui::Stroke::new(1.0, tokens.button_border)); + if ui.add_enabled(project_open, outlined.corner_radius(pill / 2.0)).clicked() { app.ui.windows.mesh_export_options = Some(app.session.project_id); app.ui.rail_panel = None; } - if ui.add_enabled(project_open, primary_button(ui, tr("Export Textures...")).min_size(size.into())).clicked() { + if ui.add_enabled(project_open, primary_button(ui, tr("Export Textures...")).corner_radius(pill / 2.0)).clicked() { app.ui.windows.export = true; app.ui.rail_panel = None; } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3fe1b4e1..cec6252c 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -14,7 +14,7 @@ use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; use crate::theme::{Tokens, caption}; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::{icon_button, primary_button}; +use crate::widgets::icon_button; mod inherited_settings; mod map_row; @@ -34,6 +34,8 @@ const LIST_WIDTH: f32 = 180.0; const ICON: f32 = 20.0; /// Width of the value column of the parameter rows const VALUE_WIDTH: f32 = 360.0; +/// Width of the bottom bar's buttons, the same for all as in the reference +const FOOTER_BUTTON_WIDTH: f32 = 125.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -584,6 +586,11 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } +/// A bottom bar button, as wide as the others +fn footer_button(text: &str) -> egui::Button<'_> { + egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) +} + /// A header with a menu or tool at its right end fn header(ui: &mut Ui, title: &str, right: impl FnOnce(&mut Ui)) { ui.horizontal(|ui| { @@ -1359,7 +1366,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { // Not on LIST OF EXPORTS if app.ui.export.tab != 2 - && ui.button(tr("Reset all")).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() + && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() { // Keep ownership so Cancel can restore the opening settings let e = &mut app.ui.export; @@ -1369,15 +1376,15 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Nothing to write without a ticked texture set let any = !export_selection(app).is_empty(); - if ui.add_enabled(any, primary_button(ui, tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { + if ui.add_enabled(any, footer_button(tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { do_export = true; } // Saving closes the window without starting an export - if ui.button(tr("Save settings")).on_hover_text(tr("Closes the export window and saves changes")).clicked() { + if ui.add(footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } - if ui.button(tr("Cancel")).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { + if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { canceled = true; } ui.label(trf("{n} textures selected for export", &[("n", &selected)])); diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 3c8a4ef4..95e2bae7 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -5,13 +5,18 @@ use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; use crate::unavailable; -use crate::widgets::primary_button; /// Indent of an option's checkbox under its choice const OPTION_INDENT: f32 = 20.0; /// Width of the Cancel and Export buttons -const BUTTON_WIDTH: f32 = 130.0; +const BUTTON_WIDTH: f32 = 110.0; + +/// The reference dialog's content width +const DIALOG_WIDTH: f32 = 510.0; + +/// Gap between the two option groups, as in the reference +const GROUP_GAP: f32 = 25.0; /// The prompt, while File > Export Mesh waits on it pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { @@ -23,9 +28,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut export, mut cancel) = (false, false); crate::windows::dialog("mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH); + // TextureCraft exports the mesh as it is: triangulated, without displacement ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); option(ui, true, tr("Apply triangulation")); + ui.add_space(GROUP_GAP); unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); option(ui, true, tr("Recompute vertex normals")); ui.add_space(8.0); @@ -34,7 +42,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let size = egui::vec2(BUTTON_WIDTH, ui.spacing().interact_size.y); - export = ui.add(primary_button(ui, tr("Export")).min_size(size)).clicked(); + export = ui.add(egui::Button::new(tr("Export")).min_size(size)).clicked(); cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(size)).clicked(); }); }); diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 6c176f56..46dcd4b9 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -99,3 +99,12 @@ fn the_unavailable_checkboxes_carry_the_reference_texts() { ); checkbox_tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); } + +#[test] +fn the_bottom_bar_buttons_share_one_width() { + let h = harness(egui::vec2(1600.0, 960.0)); + + let widths: Vec = ["Reset all", "Cancel", "Save settings", "Export"].iter().map(|label| window_button_rect(&h, label, 1600.0).width()).collect(); + + assert!(widths.windows(2).all(|pair| (pair[0] - pair[1]).abs() < 1.0), "{widths:?}"); +} From e83c3f88c83bb694ba3ea8bd2d76c8cc4e390f3c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:29:43 +0100 Subject: [PATCH 069/153] Output templates tab: Naming pattern on the tab row, no Include all, Reset all or count, Save settings and Export greyed --- crates/ui-egui/src/export_templates.rs | 27 +++++++++---------- crates/ui-egui/src/export_window.rs | 18 ++++++++----- crates/ui-egui/tests/it/output_templates.rs | 30 +++++++++++++++++++++ 3 files changed, 55 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index f6fb56df..eea551c6 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -73,6 +73,8 @@ const CREATE: [(&str, Layout); 5] = /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; +/// Width of the Naming pattern list +const NAMING_PATTERN_WIDTH: f32 = 150.0; /// The input maps palette: (group, [(label, source)]). type Palette = [(&'static str, Vec<(&'static str, SourceRef)>); 4]; @@ -244,7 +246,6 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { ui.vertical(|ui| { ui.set_width(INPUTS_WIDTH); ui.set_height(height); - naming_pattern(ui); input_maps(ui); }); if let Some(a) = list_action { @@ -262,21 +263,19 @@ pub fn select(app: &mut TextureCraftApp, name: String) { } } -/// "Naming pattern" with its info icon -fn naming_pattern(ui: &mut Ui) { +/// "Naming pattern" with its info icon, at the right end of the tab row (laid out right to left) +pub(crate) fn naming_pattern(ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(tr("Naming pattern")); - egui::ComboBox::from_id_salt("exp_naming").width(90.0).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { - for p in NAMING_PATTERNS { - let _ = ui.selectable_label(true, p); - } - }); - ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { - ui.label(tr("Select the naming pattern used to display the input maps on this page.")); - ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); - }); + ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { + ui.label(tr("Select the naming pattern used to display the input maps on this page.")); + ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); }); + egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + for p in NAMING_PATTERNS { + let _ = ui.selectable_label(true, p); + } + }); + ui.label(tr("Naming pattern")); } /// The Presets list: the templates sorted by name (built-in and user); a right click offers diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index cec6252c..82bdbb4d 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1309,6 +1309,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.button(tr("Open output directory")).clicked() { open_output_directory(app); } + } else if app.ui.export.tab == 1 { + crate::export_templates::naming_pattern(ui); } else if ui.button(tr("Include all")).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { @@ -1362,10 +1364,12 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - let selected = selected_texture_count(app); + // OUTPUT TEMPLATES edits the templates only: no count, nothing to reset, save or export there + let templates_tab = app.ui.export.tab == 1; + let selected = if templates_tab { 0 } else { selected_texture_count(app) }; ui.horizontal(|ui| { - // Not on LIST OF EXPORTS - if app.ui.export.tab != 2 + // Only on SETTINGS + if app.ui.export.tab == 0 && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() { // Keep ownership so Cancel can restore the opening settings @@ -1375,19 +1379,21 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Nothing to write without a ticked texture set - let any = !export_selection(app).is_empty(); + let any = !export_selection(app).is_empty() && !templates_tab; if ui.add_enabled(any, footer_button(tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { do_export = true; } // Saving closes the window without starting an export - if ui.add(footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { + if ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { canceled = true; } - ui.label(trf("{n} textures selected for export", &[("n", &selected)])); + if !templates_tab { + ui.label(trf("{n} textures selected for export", &[("n", &selected)])); + } }); }); }); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index bb9c5d5e..2831dc9c 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -30,6 +30,9 @@ fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> { h } +/// Left edge of the right rail in the 1600 point wide harness +const RAIL_LEFT_EDGE: f32 = 1560.0; + fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click(); h.run_steps(4); @@ -284,3 +287,30 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { assert_eq!(current, saved, "the corrected draft was saved in its own order"); assert_eq!(harness.state().ui.export.sets[&0].maps, [(1, disabled)].into()); } + +#[test] +fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { + let library = TemplateLibrary::new("bottom-bar"); + let h = harness(&library); + + let naming = h.get_by_label("Naming pattern").rect(); + let tabs = h.get_by_label("OUTPUT TEMPLATES").rect(); + let presets = h.get_by_label("Presets").rect(); + + assert!(naming.center().y < presets.top() && (naming.center().y - tabs.center().y).abs() < tabs.height(), "on the tab row: {naming:?}"); + assert!(naming.left() > presets.right(), "at the right end"); + for absent in ["Include all", "Reset all"] { + assert!(h.query_by_label(absent).is_none(), "{absent}"); + } + assert!(h.query_by_label_contains("textures selected for export").is_none()); + for greyed in ["Save settings", "Export"] { + // The rail at the right edge has an Export button of its own + let button = h + .get_all_by_role(egui::Role::Button) + .filter(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)) + .last() + .unwrap(); + assert!(button.accesskit_node().is_disabled(), "{greyed}"); + } + assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); +} From 043de59f340f7268c8861d0e9bac77d1d57124cb Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:42:37 +0100 Subject: [PATCH 070/153] Output templates: reference map panes, channel swatches with the From popup, reference output map rows and Presets row --- crates/ui-egui/src/export_templates.rs | 1008 ++++++++++++----- .../src/export_templates/channel_target.rs | 24 + .../ui-egui/src/export_templates/map_drag.rs | 3 + .../ui-egui/src/export_templates/map_lists.rs | 150 +++ .../src/export_templates/pending_drop.rs | 14 + .../ui-egui/src/export_templates/row_edit.rs | 11 + crates/ui-egui/src/export_window.rs | 6 +- crates/ui-egui/src/state.rs | 14 + crates/ui-egui/tests/it/output_templates.rs | 185 ++- crates/ui-egui/tests/it/template_invert.rs | 30 +- 10 files changed, 1163 insertions(+), 282 deletions(-) create mode 100644 crates/ui-egui/src/export_templates/channel_target.rs create mode 100644 crates/ui-egui/src/export_templates/map_drag.rs create mode 100644 crates/ui-egui/src/export_templates/map_lists.rs create mode 100644 crates/ui-egui/src/export_templates/pending_drop.rs create mode 100644 crates/ui-egui/src/export_templates/row_edit.rs diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index eea551c6..2e109a1c 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1,10 +1,10 @@ //! Export dialog › Output templates: create and edit export presets. Built-in presets are //! read-only; the selected user preset is edited as a draft that is saved through //! `export.preset.save` whenever it validates, so a half-typed file name never reaches disk. +//! Maps dragged from the Input maps, Mesh maps and Converted maps panes onto an output map's +//! channel swatches fill its channels. -use std::sync::LazyLock; - -use egui::{RichText, Ui, vec2}; +use egui::{Color32, RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{BakedMap, Channel}; @@ -14,15 +14,84 @@ use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, Sour use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, icon_button}; +use crate::unavailable::NOT_AVAILABLE; +use crate::widgets::{chip, icon_button_without_tooltip}; + +mod channel_target; +mod map_drag; +mod map_lists; +mod pending_drop; +mod row_edit; + +pub use channel_target::ChannelTarget; +use map_drag::MapDrag; +use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; +pub use pending_drop::PendingDrop; +use row_edit::RowEdit; const ICON: f32 = 20.0; -const LIST_WIDTH: f32 = 190.0; +const LIST_WIDTH: f32 = 220.0; +/// Width of the Input maps pane const INPUTS_WIDTH: f32 = 170.0; +/// Width of the pane with Mesh maps above Converted maps +const SIDE_MAPS_WIDTH: f32 = 165.0; +/// Share of the side pane's height that Mesh maps take; Converted maps get the rest +const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; /// The name "+" gives a new template, as in the reference const NEW_PRESET: &str = "new_export_preset"; -const RGB: [&str; 3] = ["R", "G", "B"]; + +/// Height of a Presets list row, and where its icon and name start +const PRESET_ROW_HEIGHT: f32 = 18.0; +const PRESET_ICON_INDENT: f32 = 2.0; +const PRESET_TEXT_INDENT: f32 = 20.0; + +/// Height of a map list entry, the gap between entries, and where its marker and name sit +const ENTRY_HEIGHT: f32 = 21.0; +const ENTRY_GAP: f32 = 2.0; +const ENTRY_TEXT_INDENT: f32 = 22.0; +const ENTRY_TEXT_SIZE: f32 = 12.0; +const MARKER_INDENT: f32 = 10.0; +const MARKER_SIZE: f32 = 10.0; +/// How strongly a map TextureCraft does not have yet is dimmed +const UNAVAILABLE_FADE: f32 = 0.6; + +/// An output map row: padding, gap below it, grip width, file name field width, icon size +const ROW_MARGIN: f32 = 6.0; +const ROW_GAP: f32 = 4.0; +const GRIP_WIDTH: f32 = 5.0; +const NAME_FIELD_WIDTH: f32 = 150.0; +const ROW_ICON: f32 = 16.0; + +/// A channel swatch: its side, the label's size and offset from the top, and the bars that show +/// which channels of the source it reads +const SWATCH_SIZE: f32 = 32.0; +const SWATCH_TEXT_SIZE: f32 = 11.0; +const SWATCH_TEXT_TOP: f32 = 3.0; +const SWATCH_BAR_WIDTH: f32 = 18.0; +const SWATCH_BAR_HEIGHT: f32 = 2.0; +const SWATCH_BAR_BOTTOM: f32 = 9.0; + +/// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to +/// keep the white label readable +const HUE_STEP: f32 = 0.618_034; +const SWATCH_SATURATION: f32 = 0.45; +const SWATCH_VALUE_DARK: f32 = 0.42; +const SWATCH_VALUE_LIGHT: f32 = 0.62; + +/// The bars of the R, G and B channels a swatch reads +const COMPONENT_COLORS: [Color32; 3] = [Color32::from_rgb(220, 70, 70), Color32::from_rgb(80, 190, 90), Color32::from_rgb(80, 120, 230)]; + +/// What a cleared channel writes: black, or opaque in the alpha channel +const CLEARED_VALUE: f32 = 0.0; +const CLEARED_ALPHA: f32 = 1.0; + +/// The reference's file name variables in its order; ones TextureCraft does not have are greyed +const REFERENCE_TOKENS: [&str; 6] = ["$project", "$mesh", "$textureSet", "$udim", "$uvTileName", "$colorSpace"]; + +/// The file types an output map lists, by extension in the reference order; the ones that +/// TextureCraft cannot write yet are greyed +const MAP_FILE_TYPES: [&str; 14] = ["bmp", "jpg", "jng", "pgm", "png", "tga", "tif", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"]; /// An output file's channel layout. #[derive(Clone, Copy, Debug, PartialEq)] @@ -34,17 +103,6 @@ enum Layout { } impl Layout { - const ALL: [Layout; 4] = [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha]; - - fn label(self) -> &'static str { - match self { - Layout::Rgb => "RGB", - Layout::Rgba => "RGBA", - Layout::Gray => n_("Gray"), - Layout::GrayAlpha => n_("Gray + A"), - } - } - fn dests(self) -> &'static [Dest] { match self { Layout::Rgb => &[Dest::R, Dest::G, Dest::B], @@ -65,10 +123,15 @@ impl Layout { } } -/// The reference's Create buttons: (label, the layout the new output map gets). The split ones -/// ("R+G+B", "R+G+B+A") make the same map; each channel can take its own source in either. -const CREATE: [(&str, Layout); 5] = - [(n_("Gray"), Layout::Gray), ("RGB", Layout::Rgb), ("R+G+B", Layout::Rgb), ("RGB+A", Layout::Rgba), ("R+G+B+A", Layout::Rgba)]; +/// The reference's Create buttons: (label, the layout the new output map gets, whether R, G and +/// B show as separate swatches) +const CREATE: [(&str, Layout, bool); 5] = [ + (n_("Gray"), Layout::Gray, false), + ("RGB", Layout::Rgb, false), + ("R+G+B", Layout::Rgb, true), + ("RGB+A", Layout::Rgba, false), + ("R+G+B+A", Layout::Rgba, true), +]; /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) @@ -76,27 +139,6 @@ const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; /// Width of the Naming pattern list const NAMING_PATTERN_WIDTH: f32 = 150.0; -/// The input maps palette: (group, [(label, source)]). -type Palette = [(&'static str, Vec<(&'static str, SourceRef)>); 4]; - -static PALETTE: LazyLock = LazyLock::new(|| { - [ - (n_("Texture set channels"), Channel::ALL.iter().map(|&channel| (channel.label(), SourceRef::Channel { channel, component: 0 })).collect()), - (n_("Converted maps"), VirtualMap::ALL.iter().map(|&map| (map.label(), SourceRef::Virtual { map, component: 0 })).collect()), - (n_("Mesh maps"), BakedMap::ALL.iter().map(|&map| (crate::i18n::baked_map_label(map), SourceRef::Baked { map, component: 0 })).collect()), - (n_("Constants"), vec![(n_("Black"), SourceRef::Constant(0.0)), (n_("Gray 50%"), SourceRef::Constant(0.5)), (n_("White"), SourceRef::Constant(1.0))]), - ] -}); - -fn source_label(s: &SourceRef) -> &'static str { - match s { - SourceRef::Channel { channel, .. } => channel.label(), - SourceRef::Virtual { map, .. } => map.label(), - SourceRef::Baked { map, .. } => crate::i18n::baked_map_label(*map), - SourceRef::Constant(_) => n_("Constant"), - } -} - /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { let k = if s.components() == 3 { k.min(2) } else { 0 }; @@ -107,6 +149,14 @@ fn with_component(s: &SourceRef, k: u8) -> SourceRef { s } +/// The component `s` reads (0 for constants). +fn component_of(s: &SourceRef) -> u8 { + match s { + SourceRef::Channel { component, .. } | SourceRef::Virtual { component, .. } | SourceRef::Baked { component, .. } => *component, + SourceRef::Constant(_) => 0, + } +} + /// Same input map (any component), or the same constant. fn same_source(a: &SourceRef, b: &SourceRef) -> bool { match (a, b) { @@ -187,12 +237,18 @@ fn sync_draft(app: &mut TextureCraftApp) { e.draft = None; e.draft_maps.clear(); e.draft_base = None; + e.draft_split.clear(); + e.active_map = None; + e.pending_drop = None; } Some(saved) => { if e.draft.as_ref().is_none_or(|d| d.name != saved.name || (d != saved && d.validate().is_ok())) { e.draft = Some(saved.clone()); e.draft_maps = (0..saved.maps.len()).map(Some).collect(); e.draft_base = Some(saved.clone()); + e.draft_split.clear(); + e.active_map = None; + e.pending_drop = None; } else if e.draft_base.as_ref() != Some(saved) { // Match only unambiguous maps from the previous saved order for origin in &mut e.draft_maps { @@ -218,13 +274,15 @@ pub use crate::ask::Ask; pub use crate::list_action::ListAction; enum MapAction { - Add(Layout), - Up(usize), - Down(usize), + /// A new output map with this layout, its R, G and B split or not + Add(Layout, bool), + Move { from: usize, to: usize }, + Duplicate(usize), Remove(usize), } -/// The Output templates tab: template list, the selected template's outputs, input maps. +/// The Output templates tab: template list, the selected template's outputs, then the Input maps +/// pane and the pane with Mesh maps above Converted maps. pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { sync_draft(app); let height = ui.available_height(); @@ -237,16 +295,26 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { }); ui.separator(); ui.vertical(|ui| { - // Leave room for the input maps column and two separators - ui.set_width((ui.available_width() - INPUTS_WIDTH - 5.0 * ui.spacing().item_spacing.x - 4.0).max(200.0)); + // Leave room for the two map panes and three separators + let panes = INPUTS_WIDTH + SIDE_MAPS_WIDTH + 8.0 * ui.spacing().item_spacing.x + 6.0; + ui.set_width((ui.available_width() - panes).max(200.0)); ui.set_height(height); outputs(app, ui); }); + + // The panes mark the sources of the output map edited last + let marked = marked_sources(app, &Tokens::get(ui.ctx())); ui.separator(); ui.vertical(|ui| { ui.set_width(INPUTS_WIDTH); ui.set_height(height); - input_maps(ui); + input_maps(ui, &marked); + }); + ui.separator(); + ui.vertical(|ui| { + ui.set_width(SIDE_MAPS_WIDTH); + ui.set_height(height); + mesh_and_converted_maps(ui, height, &marked); }); if let Some(a) = list_action { apply(app, ui.ctx(), a); @@ -284,28 +352,21 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti let mut act = None; let sel = app.ui.export.preset.clone(); let user = app.ui.export.draft.is_some(); - ui.label(caption(tr("Presets"))); ui.horizontal(|ui| { - let tool = |ui: &mut Ui, enabled: bool, icon: &str, tip: &str| ui.add_enabled_ui(enabled, |ui| icon_button(ui, icon, tip, false, ICON)).inner.clicked(); - if tool(ui, true, ic::PLUS, tr("New template")) { - act = Some(ListAction::New); - } - if tool(ui, true, ic::COPY, tr("Duplicate the selected template")) { - act = Some(ListAction::Duplicate(sel.clone())); - } - if tool(ui, user, ic::PENCIL_SIMPLE, tr("Rename the selected template")) { - act = Some(ListAction::StartRename(sel.clone())); - } - if tool(ui, user, ic::TRASH, tr("Delete the selected template")) { - act = Some(ListAction::Remove(sel.clone())); - } - ui.separator(); - if tool(ui, true, ic::DOWNLOAD_SIMPLE, tr("Import a template (.json)")) { - act = Some(ListAction::Import); - } - if tool(ui, true, ic::UPLOAD_SIMPLE, tr("Export the selected template (.json)")) { - act = Some(ListAction::Export); - } + ui.label(caption(tr("Presets"))); + + // Copy, "−" and "+" from left to right, without tooltips as in the reference + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON).clicked() { + act = Some(ListAction::New); + } + if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON)).inner.clicked() { + act = Some(ListAction::Remove(sel.clone())); + } + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON).clicked() { + act = Some(ListAction::Duplicate(sel.clone())); + } + }); }); ui.add_space(2.0); if std::mem::take(&mut app.ui.export.rename_key) && user { @@ -326,7 +387,7 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti } } None => { - let r = ui.selectable_label(*name == sel, name).on_hover_text(name); + let r = preset_row(ui, name, *name == sel).on_hover_text(name); if r.double_clicked() && is_user { act = Some(ListAction::StartRename(name.clone())); } else if r.clicked() { @@ -343,6 +404,15 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { act = Some(ListAction::Remove(name.clone())); } + + // TextureCraft's template files, after the reference's entries + ui.separator(); + if ui.button(tr("Import a template (.json)")).clicked() { + act = Some(ListAction::Import); + } + if *name == sel && ui.button(tr("Export the selected template (.json)")).clicked() { + act = Some(ListAction::Export); + } }); } } @@ -351,6 +421,28 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti act } +/// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in +/// the accent colour +fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect, tokens.radius, tokens.row_hover); + } + let font = egui::TextStyle::Body.resolve(ui.style()); + painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); + let color = if selected { tokens.accent } else { tokens.text }; + let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); + job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT); + let galley = painter.layout_job(job); + let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT, rect.center().y - galley.size().y / 2.0); + painter.galley(top_left, galley, color); + response +} + /// The error of the selected template's draft when it does not validate: that edit is not saved. fn unfinished(app: &TextureCraftApp) -> Option { app.ui.export.draft.as_ref().and_then(|d| d.validate().err()).map(|e| e.to_string()) @@ -600,43 +692,54 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } }; let preview = preview_names(app, &preset); - let mut action = None; - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Current preset:")).color(tokens.text_dim)); - ui.label(RichText::new(&preset.name).strong().color(tokens.text_strong)); - if !editable { - ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); - } - }); - ui.label(caption(tr("Output maps"))); - ui.add_enabled_ui(editable, |ui| { + let mut edit = RowEdit::default(); + + // The selected template in a strip, "Current preset:" in bold + egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN).show(ui, |ui| { + ui.set_width(ui.available_width()); ui.horizontal(|ui| { - ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); - for (label, layout) in CREATE { - if ui.small_button(tr(label)).clicked() { - action = Some(MapAction::Add(layout)); - } + ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); + ui.label(&preset.name); + if !editable { + ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); } }); }); + + // "Output maps", with the Create buttons at the right end of the same row + ui.horizontal(|ui| { + ui.label(caption(tr("Output maps"))); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(editable, |ui| { + for (label, layout, split) in CREATE.iter().rev() { + if ui.button(tr(label)).clicked() { + edit.action = Some(MapAction::Add(*layout, *split)); + } + } + ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); + }); + }); + }); if let Err(e) = &preview { ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); } let mut changed = false; let map_count = preset.maps.len(); + let mut split = app.ui.export.draft_split.clone(); + split.resize(map_count, false); - // Leave room for the footer below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y; + // Leave room for the footer text and the framed count below + let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN; egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { - if map_count == 0 { - ui.add_space(8.0); - ui.label(RichText::new(tr("No outputs yet: add one above, then drag input maps onto its channels.")).color(tokens.text_dim)); - } ui.add_enabled_ui(editable, |ui| { - for (map_index, map) in preset.maps.iter_mut().enumerate() { - let file = preview.as_ref().ok().and_then(|names| names.get(map_index).cloned().flatten()); - changed |= output_card(ui, map_index, map_count, map, file.as_deref(), &mut action); - ui.add_space(4.0); + for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { + let file = preview.as_ref().ok().and_then(|names| names.get(index).cloned().flatten()); + let planned = match file { + Some(file) => format!("{} {file}", ic::ARROW_RIGHT), + None => tr("Not exported: no source in this texture set").to_string(), + }; + changed |= output_row(ui, index, map_count, map, row_split, &planned, &mut edit); + ui.add_space(ROW_GAP); } }); }); @@ -645,38 +748,80 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { // Count only maps that have sources in the current set if let Ok(names) = &preview { let exported = names.iter().flatten().count(); - ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); + egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); + }); } if !editable { return; } + // A drop asks for the source channel from the next frame on; one waiting from before shows now + let mut active = edit.touched.or(app.ui.export.active_map); + let mut pending = app.ui.export.pending_drop.take(); + if edit.pending.is_some() { + pending = edit.pending.take(); + ui.ctx().request_repaint(); + } else { + changed |= source_channel_popup(ui, &mut pending, &mut preset.maps, &mut active); + } + // Where each map came from in the saved template, moved along with the maps let mut origin = app.ui.export.draft_maps.clone(); if origin.len() != map_count { origin = (0..map_count).map(Some).collect(); } - match action { - Some(MapAction::Add(layout)) => { + let acted = match edit.action { + Some(MapAction::Add(layout, split_rgb)) => { preset.maps.push(new_map(layout)); origin.push(None); + split.push(split_rgb); + active = Some(map_count); + true } - Some(MapAction::Up(index)) if index > 0 && index < map_count => { - preset.maps.swap(index, index - 1); - origin.swap(index, index - 1); + Some(MapAction::Move { from, to }) if from < map_count && to < map_count && from != to => { + let map = preset.maps.remove(from); + preset.maps.insert(to, map); + let map_origin = origin.remove(from); + origin.insert(to, map_origin); + let map_split = split.remove(from); + split.insert(to, map_split); + active = Some(to); + true } - Some(MapAction::Down(index)) if index + 1 < map_count => { - preset.maps.swap(index, index + 1); - origin.swap(index, index + 1); + Some(MapAction::Duplicate(index)) if index < map_count => { + let copy = preset.maps.get(index).cloned(); + let copy_split = split.get(index).copied().unwrap_or(false); + if let Some(copy) = copy { + preset.maps.insert(index + 1, copy); + origin.insert(index + 1, None); + split.insert(index + 1, copy_split); + active = Some(index + 1); + } + true } Some(MapAction::Remove(index)) if index < map_count => { preset.maps.remove(index); origin.remove(index); + split.remove(index); + active = None; + true } - _ if !changed => return, - _ => {} + _ => false, + }; + + // Indices changed under a waiting drop: it is dropped + if acted { + pending = None; + } + let e = &mut app.ui.export; + e.draft_split = split; + e.active_map = active.filter(|index| *index < preset.maps.len()); + e.pending_drop = pending; + if acted || changed { + commit(app, preset, origin); } - commit(app, preset, origin); } /// Keep the edited draft; save it when valid. `origin` gives each map's index in the saved @@ -715,166 +860,482 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result, action: &mut Option) -> bool { - let tk = Tokens::get(ui.ctx()); +/// One output map row: drag grip, file name, "$", the channel swatches, then file type, bit depth, +/// duplicate and remove. `planned` is the file it writes for the current texture set. +fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: &str, edit: &mut RowEdit) -> bool { + let tokens = Tokens::get(ui.ctx()); let mut changed = false; - egui::Frame::new().fill(tk.row).corner_radius(tk.radius).inner_margin(6.0).show(ui, |ui| { + let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { - let width = ui.available_width() - 4.0 * (ICON + ui.spacing().item_spacing.x); - changed |= ui - .add(egui::TextEdit::singleline(&mut map.file).font(egui::TextStyle::Monospace).desired_width(width)) - .on_hover_text(tr("File name without extension; variables insert names")) - .changed(); - ui.menu_button(RichText::new(ic::CURRENCY_DOLLAR).size(13.0), |ui| { - for (token, what) in FILE_TOKENS { - if ui.button(RichText::new(token).monospace()).on_hover_text(what).clicked() { - map.file.push_str(token); - changed = true; - ui.close(); + grip(ui, index, count, edit); + let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(NAME_FIELD_WIDTH)).on_hover_ui(|ui| { + ui.label(tr("File name without extension; variables insert names")); + ui.label(planned); + }); + changed |= name.changed(); + changed |= token_menu(ui, &mut map.file); + changed |= channel_swatches(ui, index, map, split, edit); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.vertical(|ui| { + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON).clicked() { + edit.action = Some(MapAction::Duplicate(index)); } - } - }) - .response - .on_hover_text(tr("Insert a variable")); - if ui.add_enabled_ui(mi > 0, |ui| icon_button(ui, ic::ARROW_UP, tr("Move up"), false, ICON)).inner.clicked() { - *action = Some(MapAction::Up(mi)); - } - if ui.add_enabled_ui(mi + 1 < n, |ui| icon_button(ui, ic::ARROW_DOWN, tr("Move down"), false, ICON)).inner.clicked() { - *action = Some(MapAction::Down(mi)); - } - if icon_button(ui, ic::TRASH, tr("Remove this output"), false, ICON).clicked() { - *action = Some(MapAction::Remove(mi)); - } + if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON).clicked() { + edit.action = Some(MapAction::Remove(index)); + } + }); + ui.vertical(|ui| { + changed |= format_menu(ui, map); + changed |= depth_menu(ui, map); + }); + }); }); - ui.horizontal(|ui| { - egui::ComboBox::from_id_salt(("exp_map_fmt", mi)).width(56.0).selected_text(map.format.extension()).show_ui(ui, |ui| { - for f in FileFormat::ALL { - if ui.selectable_value(&mut map.format, f, f.extension()).changed() { - map.bit_depth = f.depth(map.bit_depth); - changed = true; - } - } - }); - egui::ComboBox::from_id_salt(("exp_map_bits", mi)).width(64.0).selected_text(trf("{n} bits", &[("n", &map.bit_depth)])).show_ui(ui, |ui| { - for &d in map.format.bit_depths() { - changed |= ui.selectable_value(&mut map.bit_depth, d, trf("{n} bits", &[("n", &d)])).changed(); - } - }); - let layout = Layout::of(map); - egui::ComboBox::from_id_salt(("exp_map_layout", mi)).width(72.0).selected_text(tr(layout.label())).show_ui(ui, |ui| { - for l in Layout::ALL { - if ui.selectable_label(l == layout, tr(l.label())).clicked() && l != layout { - set_layout(map, l); - changed = true; - } - } - }); - let (text, color) = match file { - Some(f) => (format!("{} {f}", ic::ARROW_RIGHT), tk.text_dim), - None => (tr("Not exported: no source in this texture set").to_string(), tk.text_dim), - }; - ui.add(egui::Label::new(RichText::new(text).size(11.0).color(color)).truncate()); - }); - changed |= channel_slots(ui, mi, map); }); - changed -} -/// A source picker per output channel that also takes input maps dropped from the palette. -fn channel_slots(ui: &mut Ui, mi: usize, map: &mut MapSpec) -> bool { - let tk = Tokens::get(ui.ctx()); - let mut changed = false; - let mut dropped = None; - let MapSpec { channels, inverted, .. } = map; - for (k, (dest, src)) in channels.iter_mut().enumerate() { - ui.horizontal(|ui| { - let dest_name = match *dest { - Dest::L => tr("Gray"), - Dest::A => "A", - d => RGB.get(slot_component(d) as usize).copied().unwrap_or("R"), - }; - ui.add_sized(vec2(30.0, 18.0), egui::Label::new(RichText::new(dest_name).size(11.0).color(tk.text_dim))); - let combo = egui::ComboBox::from_id_salt(("exp_slot", mi, k)).width(170.0).selected_text(tr(source_label(src))).show_ui(ui, |ui| { - for (group, inputs) in PALETTE.iter() { - ui.label(caption(tr(group))); - for (label, s) in inputs { - if ui.selectable_label(same_source(src, s), tr(label)).clicked() { - *src = with_component(s, slot_component(*dest)); - changed = true; - } - } - } - }); - let r = &combo.response; - if r.dnd_hover_payload::().is_some() { - ui.painter().rect_stroke(r.rect.expand(2.0), 3.0, egui::Stroke::new(1.5, tk.accent), egui::StrokeKind::Outside); - } - if let Some(input) = r.dnd_release_payload::() { - dropped = Some((*dest, (*input).clone())); - } - let three = src.components() == 3; - match src { - SourceRef::Constant(v) => { - changed |= ui.add(egui::DragValue::new(v).range(0.0..=1.0).speed(0.005).fixed_decimals(2)).changed(); - } - SourceRef::Channel { component, .. } | SourceRef::Virtual { component, .. } | SourceRef::Baked { component, .. } if three => { - let shown = RGB.get(*component as usize).copied().unwrap_or("R"); - egui::ComboBox::from_id_salt(("exp_slot_c", mi, k)).width(36.0).selected_text(shown).show_ui(ui, |ui| { - for (i, l) in (0u8..).zip(RGB) { - changed |= ui.selectable_value(component, i, l).changed(); - } - }); - } - _ => {} - } - let on = inverted.contains(dest); - if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { - inverted.retain(|x| x != dest); - if !on { - inverted.push(*dest); - } - changed = true; - } - }); + // Another row's grip dropped here moves that row to this place + // Check the payload type before taking it, so a map list drop is not lost + let row = frame.response; + let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); + if row_dragged_over { + ui.painter().rect_stroke(row.rect, tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); } - if let Some((dest, input)) = dropped { - drop_input(map, dest, &input); - changed = true; + if row_dragged_over + && let Some(from) = row.dnd_release_payload::() + { + edit.action = Some(MapAction::Move { from: from.0, to: index }); + } + if changed { + edit.touched = Some(index); } changed } -/// Input maps to drag onto output channels. -fn input_maps(ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Input maps"))); - ui.label(RichText::new(tr("Drag onto an output channel")).size(11.0).color(tk.text_dim)); - egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { - for (gi, (group, inputs)) in PALETTE.iter().enumerate() { - ui.add_space(4.0); - ui.label(RichText::new(tr(group)).strong().size(11.0)); - ui.horizontal_wrapped(|ui| { - for (k, (label, s)) in inputs.iter().enumerate() { - let label = tr(label); +/// The grip at a row's left: drag it onto another row to move the map there; the arrow keys and +/// its right-click menu move it one place +fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { + let tokens = Tokens::get(ui.ctx()); + let enabled = ui.is_enabled(); + let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH, SWATCH_SIZE), egui::Sense::click_and_drag()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); + let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; + ui.painter().rect_filled(rect, 1.0, color); + let response = response.on_hover_cursor(egui::CursorIcon::Grab); + response.dnd_set_drag_payload(MapDrag(index)); - // `dnd_drag_source` cannot wrap inside `horizontal_wrapped` - let r = chip(ui, label, false).interact(egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); - r.dnd_set_drag_payload(s.clone()); - if r.dragged() - && let Some(at) = r.interact_pointer_pos() - { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - egui::Area::new(egui::Id::unique(("exp_input_drag", gi, k))) - .order(egui::Order::Tooltip) - .fixed_pos(at + vec2(8.0, 8.0)) - .show(ui.ctx(), |ui| chip(ui, label, true)); - } - } - }); + let mut to = None; + if response.has_focus() { + if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) { + to = index.checked_sub(1); + } + if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) && index + 1 < count { + to = Some(index + 1); + } + } + response.context_menu(|ui| { + if ui.add_enabled(index > 0, egui::Button::new(tr("Move up"))).clicked() { + to = index.checked_sub(1); + } + if ui.add_enabled(index + 1 < count, egui::Button::new(tr("Move down"))).clicked() { + to = Some(index + 1); } }); + if let Some(to) = to { + edit.action = Some(MapAction::Move { from: index, to }); + } +} + +/// The "$" button: the file name variables, the reference's first, then TextureCraft's own +fn token_menu(ui: &mut Ui, file: &mut String) -> bool { + let mut changed = false; + ui.menu_button("$", |ui| { + let mut add = |ui: &mut Ui, token: &str, what: &str| { + if ui.button(RichText::new(token).monospace()).on_hover_text(what).clicked() { + file.push_str(token); + changed = true; + ui.close(); + } + }; + for token in REFERENCE_TOKENS { + match FILE_TOKENS.iter().find(|(ours, _)| *ours == token) { + Some(&(token, what)) => add(ui, token, what), + None => { + ui.add_enabled(false, egui::Button::new(RichText::new(token).monospace())).on_disabled_hover_text(tr(NOT_AVAILABLE)); + } + } + } + for &(token, what) in FILE_TOKENS.iter().filter(|(token, _)| !REFERENCE_TOKENS.contains(token)) { + add(ui, token, what); + } + }); + changed +} + +/// The file type menu of an output map ("png˅") +fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { + let mut changed = false; + ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + for extension in MAP_FILE_TYPES { + let Some(format) = FileFormat::from_extension(extension) else { + ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); + continue; + }; + + if ui.selectable_label(map.format == format, extension).clicked() { + changed |= map.format != format; + map.bit_depth = format.depth(map.bit_depth); + map.format = format; + ui.close(); + } + } + }); + changed +} + +/// The bit depth menu of an output map ("8 bits˅"); templates do not keep dithering yet +fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { + let format = map.format; + let mut changed = false; + let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); + ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + for (depth, dithering) in crate::export_window::depth_options(format) { + let label = crate::export_window::depth_label(Some(format), depth, dithering); + if dithering { + ui.add_enabled(false, egui::Button::selectable(false, label)).on_disabled_hover_text(tr(NOT_AVAILABLE)); + } else if ui.selectable_label(map.bit_depth == depth, label).clicked() { + changed |= map.bit_depth != depth; + map.bit_depth = depth; + ui.close(); + } + } + }); + changed +} + +/// Whether R, G and B read one map as one RGB swatch can show it: a color map's R, G and B, or +/// the same gray map or constant in all three +fn rgb_collapsed(map: &MapSpec) -> bool { + let get = |dest: Dest| map.channels.iter().find(|(d, _)| *d == dest).map(|(_, s)| s); + let (Some(red), Some(green), Some(blue)) = (get(Dest::R), get(Dest::G), get(Dest::B)) else { return true }; + + let one_map = same_source(red, green) && same_source(green, blue); + let spread = red.components() == 3 && [red, green, blue].into_iter().zip(0u8..).all(|(s, k)| component_of(s) == k); + one_map && (spread || red.components() == 1) +} + +/// The swatches an output map shows: Gray, or RGB (R, G, B when split), then A when it has alpha +fn swatch_targets(map: &MapSpec, split: bool) -> Vec { + let layout = Layout::of(map); + let mut targets = match layout { + Layout::Gray | Layout::GrayAlpha => vec![ChannelTarget::One(Dest::L)], + Layout::Rgb | Layout::Rgba if split || !rgb_collapsed(map) => [Dest::R, Dest::G, Dest::B].into_iter().map(ChannelTarget::One).collect(), + Layout::Rgb | Layout::Rgba => vec![ChannelTarget::Rgb], + }; + if matches!(layout, Layout::GrayAlpha | Layout::Rgba) { + targets.push(ChannelTarget::One(Dest::A)); + } + targets +} + +/// The label on a swatch +fn target_label(target: ChannelTarget) -> &'static str { + match target { + ChannelTarget::Rgb => "RGB", + ChannelTarget::One(Dest::R) => "R", + ChannelTarget::One(Dest::G) => "G", + ChannelTarget::One(Dest::B) => "B", + ChannelTarget::One(Dest::A) => "A", + ChannelTarget::One(Dest::L) => tr("Gray"), + } +} + +/// The source the swatch shows (R's for the RGB swatch) +fn source_of(map: &MapSpec, target: ChannelTarget) -> Option<&SourceRef> { + let dest = target.dests().first()?; + map.channels.iter().find(|(d, _)| d == dest).map(|(_, s)| s) +} + +/// The source channel choices of "From ": (label, the component read; None: not available yet) +fn source_choices(source: &SourceRef) -> Vec<(&'static str, Option)> { + if source.components() == 3 { + vec![(n_("Gray Channel"), None), (n_("R Channel"), Some(0)), (n_("G Channel"), Some(1)), (n_("B Channel"), Some(2)), (n_("A Channel"), None)] + } else { + vec![(n_("Gray Channel"), Some(0)), (n_("A Channel"), None)] + } +} + +/// A source as a swatch names it: the map, and for one channel of a color map that channel +fn source_name(source: &SourceRef, target: ChannelTarget) -> Option { + let map = tr(map_lists::name_of(source)?); + let picked = source_choices(source).into_iter().find(|(_, component)| *component == Some(component_of(source))); + match picked { + Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])), + _ => Some(map.to_string()), + } +} + +/// The colour of a map on swatches and list markers (None for constants) +fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { + let channels = Channel::ALL.len(); + let converted = VirtualMap::ALL.len(); + let index = match source { + SourceRef::Channel { channel, .. } => Channel::ALL.iter().position(|c| c == channel)?, + SourceRef::Virtual { map, .. } => channels + VirtualMap::ALL.iter().position(|m| m == map)?, + SourceRef::Baked { map, .. } => channels + converted + BakedMap::ALL.iter().position(|m| m == map)?, + SourceRef::Constant(_) => return None, + }; + let hue = (index as f32 * HUE_STEP).fract(); + let value = if tokens.dark { SWATCH_VALUE_DARK } else { SWATCH_VALUE_LIGHT }; + Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) +} + +/// The bars under a swatch's label: R, G and B for a color map on the RGB swatch, else the one +/// channel read +fn swatch_bars(source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { + match source { + SourceRef::Constant(_) => Vec::new(), + _ if source.components() == 3 && target == ChannelTarget::Rgb => COMPONENT_COLORS.to_vec(), + _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), + _ => vec![tokens.text_strong], + } +} + +/// An output map's channel swatches: drop targets for the map lists; a click opens Clear channel +/// and Split/Collapse RGB, a right click Invert +fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { + let tokens = Tokens::get(ui.ctx()); + let mut changed = false; + let shows_split = *split || !rgb_collapsed(map); + for (slot, target) in swatch_targets(map, *split).into_iter().enumerate() { + let Some(source) = source_of(map, target).cloned() else { continue }; + + let label = target_label(target); + let name = match source_name(&source, target) { + Some(source) => trf("{channel}: {map}", &[("channel", &label), ("map", &source)]), + None => label.to_string(), + }; + let response = swatch(ui, label, &name, source_color(&source, &tokens), &swatch_bars(&source, target, &tokens)).on_hover_text(&name); + + // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row + let map_dragged_over = response.dnd_hover_payload::().is_some(); + if map_dragged_over { + ui.painter().rect_stroke(response.rect.expand(2.0), tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); + } + if map_dragged_over && let Some(input) = response.dnd_release_payload::() { + edit.touched = Some(index); + if target == ChannelTarget::Rgb && input.components() == 3 { + drop_input(map, Dest::R, &input); + changed = true; + } else { + edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); + } + } + + let rgb = matches!(target, ChannelTarget::Rgb | ChannelTarget::One(Dest::R | Dest::G | Dest::B)); + let menu_id = ui.make_persistent_id(("exp_swatch_menu", index, slot)); + egui::Popup::menu(&response).id(menu_id).show(|ui| { + if ui.button(tr("Clear channel")).clicked() { + clear_channel(map, target); + changed = true; + edit.touched = Some(index); + } + if rgb && ui.button(tr("Split/Collapse RGB")).clicked() { + changed |= split_or_collapse(map, split, shows_split); + edit.touched = Some(index); + } + }); + + // Not in the reference's menu: inverting stays on the right click + response.context_menu(|ui| { + let on = target.dests().iter().all(|dest| map.inverted.contains(dest)); + if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { + map.inverted.retain(|dest| !target.dests().contains(dest)); + if !on { + map.inverted.extend_from_slice(target.dests()); + } + changed = true; + edit.touched = Some(index); + ui.close(); + } + }); + } + changed +} + +/// One channel swatch: `label` on top, filled with the source's colour, bars below for the +/// channels it reads +fn swatch(ui: &mut Ui, label: &str, name: &str, fill: Option, bars: &[Color32]) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let enabled = ui.is_enabled(); + let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE, SWATCH_SIZE), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); + + let painter = ui.painter(); + let border = if response.hovered() { tokens.accent } else { tokens.button_border }; + painter.rect(rect, tokens.radius, fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, egui::FontId::proportional(SWATCH_TEXT_SIZE), tokens.text_strong); + let bar_width = SWATCH_BAR_WIDTH / bars.len().max(1) as f32; + let left = rect.center().x - SWATCH_BAR_WIDTH / 2.0; + for (k, color) in bars.iter().enumerate() { + let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM); + painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT)), 0.0, *color); + } + response +} + +/// Clear channel: the swatch's channels write black, or opaque alpha +fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { + for (dest, source) in &mut map.channels { + if target.dests().contains(dest) { + *source = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); + } + } +} + +/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones collapse into one RGB +/// swatch reading R's map. True when the map changed. +fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> bool { + if !shows_split { + *split = true; + return false; + } + + *split = false; + if rgb_collapsed(map) { + return false; + } + + let Some(red) = source_of(map, ChannelTarget::One(Dest::R)).map(|s| with_component(s, 0)) else { return false }; + if red.components() == 3 { + drop_input(map, Dest::R, &red); + } else { + for (dest, source) in &mut map.channels { + if is_rgb(*dest) { + *source = red.clone(); + } + } + } + true +} + +/// "From ": which channel of the dropped map the output channel reads. True when the map +/// changed. +fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec], active: &mut Option) -> bool { + let Some(drop) = pending.clone() else { return false }; + let Some(map) = maps.get_mut(drop.map) else { + *pending = None; + return false; + }; + + let name = map_lists::name_of(&drop.source).map_or_else(String::new, |name| tr(name).to_string()); + let mut picked = None; + let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(drop.position), ui.layer_id()) + .kind(egui::PopupKind::Menu) + .layout(egui::Layout::top_down_justified(egui::Align::Min)) + .style(egui::containers::menu::menu_style) + .open(true) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); + for (label, component) in source_choices(&drop.source) { + match component { + Some(component) => { + if ui.button(tr(label)).clicked() { + picked = Some(component); + } + } + None => { + ui.add_enabled(false, egui::Button::new(tr(label))).on_disabled_hover_text(tr(NOT_AVAILABLE)); + } + } + } + }); + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + *pending = None; + } + let Some(component) = picked else { return false }; + + let source = with_component(&drop.source, component); + for (dest, channel_source) in &mut map.channels { + if drop.target.dests().contains(dest) { + *channel_source = source.clone(); + } + } + *active = Some(drop.map); + true +} + +/// The sources of the output map edited last, with their colours, for the panes' markers +fn marked_sources(app: &TextureCraftApp, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { + let Some(index) = app.ui.export.active_map else { return Vec::new() }; + let Some(map) = app.ui.export.draft.as_ref().and_then(|draft| draft.maps.get(index)) else { return Vec::new() }; + + map.channels.iter().filter_map(|(_, source)| source_color(source, tokens).map(|color| (source.clone(), color))).collect() +} + +/// The Input maps pane: the input maps in their groups +fn input_maps(ui: &mut Ui, marked: &[(SourceRef, Color32)]) { + ui.label(caption(tr("Input maps"))); + egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { + for (group, entries) in INPUT_MAPS.iter() { + ui.label(RichText::new(tr(group)).italics()); + map_entries(ui, entries, marked, false); + } + }); +} + +/// The side pane: Mesh maps above Converted maps (in the highlight colour, as in the reference) +fn mesh_and_converted_maps(ui: &mut Ui, height: f32, marked: &[(SourceRef, Color32)]) { + ui.label(caption(tr("Mesh maps"))); + egui::ScrollArea::vertical() + .id_salt("exp_mesh_maps") + .auto_shrink([false; 2]) + .max_height(height * MESH_MAPS_SHARE) + .show(ui, |ui| map_entries(ui, &MESH_MAPS, marked, false)); + ui.separator(); + ui.label(caption(tr("Converted maps"))); + egui::ScrollArea::vertical().id_salt("exp_converted_maps").auto_shrink([false; 2]).show(ui, |ui| map_entries(ui, &CONVERTED_MAPS, marked, true)); +} + +fn map_entries(ui: &mut Ui, entries: &[MapEntry], marked: &[(SourceRef, Color32)], converted: bool) { + let tokens = Tokens::get(ui.ctx()); + let text_color = if converted { tokens.warning } else { tokens.text }; + for (name, source) in entries { + let marker = source.as_ref().and_then(|source| marked.iter().find(|(used, _)| same_source(used, source)).map(|(_, color)| *color)); + map_entry(ui, tr(name), source.as_ref(), text_color, marker); + } +} + +/// A map list entry to drag onto an output channel, with the colour marker of an output map that +/// reads it; a map TextureCraft does not have yet is greyed and cannot be dragged +fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Color32, marker: Option) { + let tokens = Tokens::get(ui.ctx()); + let available = source.is_some(); + let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); + + let painter = ui.painter(); + let row = rect.shrink2(vec2(0.0, ENTRY_GAP / 2.0)); + painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); + if let Some(color) = marker { + painter.rect_filled(egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT, 0.0), egui::Vec2::splat(MARKER_SIZE)), 1.0, color); + } + let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; + painter.text(row.left_center() + vec2(ENTRY_TEXT_INDENT, 0.0), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(ENTRY_TEXT_SIZE), color); + let Some(source) = source else { + response.on_hover_text(tr(NOT_AVAILABLE)); + return; + }; + + let response = response.on_hover_cursor(egui::CursorIcon::Grab); + response.dnd_set_drag_payload(source.clone()); + if response.dragged() + && let Some(at) = response.interact_pointer_pos() + { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)).show(ui.ctx(), |ui| chip(ui, name, true)); + } } #[cfg(test)] @@ -899,7 +1360,7 @@ mod tests { assert_eq!(map.channels, vec![(Dest::L, ch(Channel::BaseColor, 0)), (Dest::A, SourceRef::Constant(1.0))]); set_layout(&mut map, Layout::Rgb); assert_eq!(map.channels.get(1), Some(&(Dest::G, ch(Channel::BaseColor, 1))), "gray to RGB spreads a color source"); - for l in Layout::ALL { + for l in [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha] { let m = new_map(l); assert_eq!(Layout::of(&m), l); ExportPreset { name: "t".into(), maps: vec![m] }.validate().unwrap(); @@ -927,4 +1388,43 @@ mod tests { assert_eq!(map.inverted, vec![Dest::B], "a dropped map keeps the channel's toggle, like picking from the list"); ExportPreset { name: "t".into(), maps: vec![map] }.validate().unwrap(); } + + #[test] + fn split_and_collapse_keep_r_g_b_on_one_or_three_swatches() { + let mut map = new_map(Layout::Rgb); + let mut split = false; + assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb], "an empty RGB map shows one swatch"); + + assert!(!split_or_collapse(&mut map, &mut split, false), "splitting changes only the view"); + assert_eq!(swatch_targets(&map, split).len(), 3); + + map.channels = vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.0))]; + assert!(split_or_collapse(&mut map, &mut split, true)); + assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb]); + assert_eq!(map.channels.get(2), Some(&(Dest::B, ch(Channel::BaseColor, 2))), "collapsing spreads R's color map over R, G and B"); + + map.channels = vec![(Dest::R, ch(Channel::Roughness, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.5))]; + assert_eq!(swatch_targets(&map, false).len(), 3, "different maps in R, G and B show split even when not asked to"); + } + + #[test] + fn clear_channel_writes_black_or_opaque_alpha() { + let mut map = new_map(Layout::Rgba); + drop_input(&mut map, Dest::R, &ch(Channel::BaseColor, 0)); + drop_input(&mut map, Dest::A, &ch(Channel::Opacity, 0)); + + clear_channel(&mut map, ChannelTarget::Rgb); + clear_channel(&mut map, ChannelTarget::One(Dest::A)); + + let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); + assert_eq!(map.channels, cleared); + } + + #[test] + fn a_gray_map_offers_its_gray_channel_and_a_color_map_its_r_g_b() { + let offered = |source: &SourceRef| source_choices(source).into_iter().filter_map(|(label, component)| component.map(|_| label)).collect::>(); + + assert_eq!(offered(&ch(Channel::Metallic, 0)), ["Gray Channel"]); + assert_eq!(offered(&ch(Channel::BaseColor, 0)), ["R Channel", "G Channel", "B Channel"]); + } } diff --git a/crates/ui-egui/src/export_templates/channel_target.rs b/crates/ui-egui/src/export_templates/channel_target.rs new file mode 100644 index 00000000..61da155b --- /dev/null +++ b/crates/ui-egui/src/export_templates/channel_target.rs @@ -0,0 +1,24 @@ +use texturecraft_engine::formats::Dest; + +/// The channel swatch of an output map that a map was dropped on. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ChannelTarget { + /// The single RGB swatch: R, G and B together. + Rgb, + /// One destination channel: R, G, B, A or the gray channel. + One(Dest), +} + +impl ChannelTarget { + /// The destination channels the swatch writes. + pub fn dests(self) -> &'static [Dest] { + match self { + ChannelTarget::Rgb => &[Dest::R, Dest::G, Dest::B], + ChannelTarget::One(Dest::R) => &[Dest::R], + ChannelTarget::One(Dest::G) => &[Dest::G], + ChannelTarget::One(Dest::B) => &[Dest::B], + ChannelTarget::One(Dest::A) => &[Dest::A], + ChannelTarget::One(Dest::L) => &[Dest::L], + } + } +} diff --git a/crates/ui-egui/src/export_templates/map_drag.rs b/crates/ui-egui/src/export_templates/map_drag.rs new file mode 100644 index 00000000..0df33947 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_drag.rs @@ -0,0 +1,3 @@ +/// The drag payload of an output map row's grip: the row's index. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MapDrag(pub usize); diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs new file mode 100644 index 00000000..7690e805 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -0,0 +1,150 @@ +//! The maps the Output templates tab lists for dragging onto output channels, with the reference's +//! names (naming pattern OpenPBR). An entry without a source names a map TextureCraft does not +//! have yet; it is listed greyed. + +use std::sync::LazyLock; + +use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::formats::{SourceRef, VirtualMap}; + +use crate::i18n::n_; + +/// One entry of a map list: its name and what it reads (None: not available yet). +pub type MapEntry = (&'static str, Option); + +fn channel(channel: Channel) -> Option { + Some(SourceRef::Channel { channel, component: 0 }) +} + +fn converted(map: VirtualMap) -> Option { + Some(SourceRef::Virtual { map, component: 0 }) +} + +fn mesh(map: BakedMap) -> Option { + Some(SourceRef::Baked { map, component: 0 }) +} + +/// Input maps in groups, as the reference lists them up to Fuzz/Sheen; the groups after it are +/// cut off in the reference screenshots and use the OpenPBR names of the channels left over. +pub static INPUT_MAPS: LazyLock)>> = LazyLock::new(|| { + vec![ + ( + n_("Base"), + vec![ + (n_("Base weight"), None), + (n_("Base color"), channel(Channel::BaseColor)), + (n_("Base metalness"), channel(Channel::Metallic)), + (n_("Base diffuse roughness"), None), + ], + ), + ( + n_("Specular"), + vec![ + (n_("Specular weight"), None), + (n_("Specular color"), None), + (n_("Specular roughness"), channel(Channel::Roughness)), + (n_("Specular level"), channel(Channel::SpecularLevel)), + (n_("Specular anisotropy"), channel(Channel::AnisotropyLevel)), + (n_("Anisotropy angle"), channel(Channel::AnisotropyAngle)), + ], + ), + (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Transmission color"), None)]), + ( + n_("Subsurface"), + vec![(n_("Subsurface weight"), channel(Channel::ScatterWeight)), (n_("Subsurface color"), None), (n_("Subsurface radius scale"), None)], + ), + ( + n_("Coat"), + vec![ + (n_("Coat weight"), channel(Channel::CoatWeight)), + (n_("Coat color"), None), + (n_("Coat roughness"), channel(Channel::CoatRoughness)), + (n_("Coat anisotropy"), None), + (n_("Coat specular level"), None), + (n_("Coat normal"), channel(Channel::CoatNormal)), + (n_("Coat tangent"), None), + ], + ), + ( + n_("Fuzz/Sheen"), + vec![(n_("Fuzz weight"), channel(Channel::SheenWeight)), (n_("Fuzz color"), channel(Channel::SheenColor)), (n_("Fuzz roughness"), channel(Channel::SheenRoughness))], + ), + (n_("Emission"), vec![(n_("Emission color"), channel(Channel::Emissive))]), + (n_("Geometry"), vec![(n_("Geometry opacity"), channel(Channel::Opacity)), (n_("Geometry normal"), channel(Channel::Normal))]), + ( + n_("Other"), + vec![ + (n_("Height"), channel(Channel::Height)), + (n_("Ambient occlusion"), channel(Channel::AmbientOcclusion)), + (n_("Specular"), channel(Channel::Specular)), + (n_("Glossiness"), channel(Channel::Glossiness)), + ], + ), + ] +}); + +/// Mesh maps, in the reference order and case. +pub static MESH_MAPS: LazyLock> = LazyLock::new(|| { + vec![ + (n_("Normal"), mesh(BakedMap::Normal)), + (n_("World space normal"), mesh(BakedMap::WorldNormal)), + (n_("ID"), mesh(BakedMap::Id)), + (n_("Ambient occlusion"), mesh(BakedMap::AmbientOcclusion)), + (n_("Curvature"), mesh(BakedMap::Curvature)), + (n_("Position"), mesh(BakedMap::Position)), + (n_("Thickness"), mesh(BakedMap::Thickness)), + (n_("Height"), mesh(BakedMap::Height)), + (n_("Bent normals"), mesh(BakedMap::BentNormal)), + (n_("Opacity"), mesh(BakedMap::Opacity)), + ] +}); + +/// Converted maps in the reference order, then the ones only TextureCraft has (templates use them). +pub static CONVERTED_MAPS: LazyLock> = LazyLock::new(|| { + vec![ + ("1/ior", None), + (n_("Mixed AO"), converted(VirtualMap::AoMixed)), + (n_("Diffuse"), None), + ("f0", converted(VirtualMap::F0)), + (n_("Glossiness"), converted(VirtualMap::Glossiness)), + (n_("Glossiness²"), None), + (n_("Normal DirectX"), converted(VirtualMap::NormalDirectX)), + (n_("Normal OpenGL"), converted(VirtualMap::NormalOpenGl)), + (n_("Reflection"), None), + (n_("Specular"), None), + ("Unity4 Diffuse", None), + ("Unity4 Gloss", None), + (n_("2D View"), None), + (VirtualMap::HeightNormal.label(), converted(VirtualMap::HeightNormal)), + (VirtualMap::Roughness.label(), converted(VirtualMap::Roughness)), + (VirtualMap::SheenTint.label(), converted(VirtualMap::SheenTint)), + ] +}); + +/// The listed name of `source` (any component), or None for a constant. +pub fn name_of(source: &SourceRef) -> Option<&'static str> { + let lists = INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()); + let mut entries = lists.filter_map(|(name, entry)| entry.as_ref().map(|entry| (*name, entry))); + entries.find(|(_, entry)| super::same_source(entry, source)).map(|(name, _)| name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_channel_and_map_can_be_dragged() { + let listed: Vec = + INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()).filter_map(|(_, s)| s.clone()).collect(); + + for channel in Channel::ALL { + assert!(listed.contains(&SourceRef::Channel { channel, component: 0 }), "{channel:?}"); + } + for map in BakedMap::ALL { + assert!(listed.contains(&SourceRef::Baked { map, component: 0 }), "{map:?}"); + } + for map in VirtualMap::ALL { + assert!(listed.contains(&SourceRef::Virtual { map, component: 0 }), "{map:?}"); + } + } +} diff --git a/crates/ui-egui/src/export_templates/pending_drop.rs b/crates/ui-egui/src/export_templates/pending_drop.rs new file mode 100644 index 00000000..00b13a84 --- /dev/null +++ b/crates/ui-egui/src/export_templates/pending_drop.rs @@ -0,0 +1,14 @@ +use texturecraft_engine::formats::SourceRef; + +use super::ChannelTarget; + +/// A map dropped on an output channel, waiting for the user to pick which of its channels to use. +#[derive(Clone, Debug, PartialEq)] +pub struct PendingDrop { + /// The output map, by index into the template's maps. + pub map: usize, + pub target: ChannelTarget, + pub source: SourceRef, + /// Where the popup opens. + pub position: egui::Pos2, +} diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs new file mode 100644 index 00000000..e813e574 --- /dev/null +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -0,0 +1,11 @@ +use super::{MapAction, PendingDrop}; + +/// What the output map rows asked for in this frame. +#[derive(Default)] +pub(super) struct RowEdit { + pub(super) action: Option, + /// A map dropped on a channel swatch, to ask which of its channels to use. + pub(super) pending: Option, + /// The row edited last. + pub(super) touched: Option, +} diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 82bdbb4d..59ed790e 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -76,12 +76,12 @@ pub(crate) const FILE_TYPES: [(&str, Option); 14] = [ /// The bit depths `format` is written with, as the bit depth list offers them: (bits, /// dithering) -fn depth_options(format: FileFormat) -> Vec<(u8, bool)> { +pub(crate) fn depth_options(format: FileFormat) -> Vec<(u8, bool)> { format.bit_depths().iter().flat_map(|&d| if d == 8 && !format.holds_float(8) { vec![(8, false), (8, true)] } else { vec![(d, false)] }).collect() } /// A bit depth as listed: "8 bits", "8 bits + dithering", "16 bits", "16f bits", "32f bits" -fn depth_label(format: Option, bit_depth: u8, dithering: bool) -> String { +pub(crate) fn depth_label(format: Option, bit_depth: u8, dithering: bool) -> String { match (bit_depth, dithering) { (8, true) => tr("8 bits + dithering").to_string(), (16, _) if format == Some(FileFormat::Exr) => tr("16f bits").to_string(), @@ -1238,6 +1238,7 @@ fn cancel(app: &mut TextureCraftApp) { before.draft = None; before.renaming = None; before.ask = None; + before.pending_drop = None; // A template deleted since keeps the default instead if app.session.export_preset(&before.preset).is_none() { @@ -1259,6 +1260,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let e = &mut app.ui.export; e.job = None; e.ask = None; + e.pending_drop = None; e.opened_with = None; e.tab = 0; e.page = None; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8f949d76..89cb751a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -387,6 +387,17 @@ pub struct ExportUi { /// Output templates tab: the saved template `draft_maps` counts from. #[serde(skip)] pub draft_base: Option, + /// Output templates tab: for each map of `draft`, whether its R, G and B show as separate + /// channel swatches (R+G+B) instead of one RGB swatch. + #[serde(skip)] + pub draft_split: Vec, + /// Output templates tab: the output map edited last; the map lists mark its sources. + #[serde(skip)] + pub active_map: Option, + /// Output templates tab: a map dropped on an output channel, waiting for the source channel + /// ("From "). + #[serde(skip)] + pub pending_drop: Option, /// Output templates tab: the new name while renaming the selected preset. #[serde(skip)] pub renaming: Option, @@ -432,6 +443,9 @@ impl Default for ExportUi { draft: None, draft_maps: Vec::new(), draft_base: None, + draft_split: Vec::new(), + active_map: None, + pending_drop: None, renaming: None, rename_key: false, ask: None, diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 2831dc9c..53c5daa1 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -1,9 +1,12 @@ //! Export textures › OUTPUT TEMPLATES (texturecraft #674): the reference's layout, names and the //! preset list's right-click menu and F2. +use egui::{Event, Modifiers, PointerButton}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::formats::{Dest, SourceRef}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{MapExport, SetExport}; @@ -38,6 +41,47 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { h.run_steps(4); } +/// Right-click the grip of output map `index` and pick `item` ("Move up" or "Move down") +fn move_map(h: &mut Harness<'_, TextureCraftApp>, index: usize, item: &str) { + h.get_all_by_label("Reorder").nth(index).unwrap_or_else(|| panic!("no grip {index}")).click_secondary(); + h.run_steps(4); + h.get_by_label(item).click(); + h.run_steps(4); +} + +/// The file name field of output map `index`: the text field on its grip's row +fn name_field(h: &Harness<'_, TextureCraftApp>, index: usize) -> egui::Rect { + let grip = h.get_all_by_label("Reorder").nth(index).unwrap_or_else(|| panic!("no grip {index}")).rect(); + h.get_all_by_role(egui::Role::TextInput) + .map(|field| field.rect()) + .find(|field| (field.center().y - grip.center().y).abs() < 6.0 && field.left() > grip.right()) + .unwrap_or_else(|| panic!("no file name field on row {index}")) +} + +/// Hover the file name field of output map `index` until its tooltip shows +fn hover_name_field(h: &mut Harness<'_, TextureCraftApp>, index: usize) { + let field = name_field(h, index); + h.hover_at(field.center()); + h.run_steps(30); +} + +/// The last button labelled `label` in the window (the newest output map's swatch) +fn last_window_button<'h>(h: &'h Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'h> { + h.get_all_by_role(egui::Role::Button) + .filter(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) + .last() + .unwrap_or_else(|| panic!("no {label} button")) +} + +/// Drop `source` on the point `at`, as a drag from the map lists ends there +fn drop_on(h: &mut Harness<'_, TextureCraftApp>, source: SourceRef, at: egui::Pos2) { + egui::DragAndDrop::set_payload(&h.ctx, source); + h.hover_at(at); + h.run_steps(2); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(4); +} + /// Right-click the Presets list's `label` (listed before the selected one's name in the middle) fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { h.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).click_secondary(); @@ -147,7 +191,10 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show"); - assert!(h.query_all_by_label_contains(egui_phosphor::regular::ARROW_RIGHT).count() >= 2, "both maps show their files"); + for index in 0..2 { + hover_name_field(&mut h, index); + assert!(h.query_all_by_label_contains(egui_phosphor::regular::ARROW_RIGHT).next().is_some(), "map {index} shows its file"); + } } #[test] @@ -205,7 +252,8 @@ fn the_footer_counts_only_the_maps_the_texture_set_exports() { let ts = h.state().session.ts(); let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); assert_eq!(plan.as_array().unwrap().len(), 1, "the sample set has no sheen: {plan}"); - assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen card says so"); + hover_name_field(&mut h, 1); + assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen row says so"); assert!(h.query_by_label("1 output maps will be exported.").is_some()); assert!(h.query_by_label("2 output maps will be exported.").is_none()); } @@ -220,8 +268,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone(); - h.get_all_by_label("Move down").next().unwrap().click(); - h.run_steps(4); + move_map(&mut h, 0, "Move down"); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[1].file, first, "the map moved down"); let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); assert_eq!(maps, [(1, off)].into(), "the setting moved with its map"); @@ -240,8 +287,7 @@ fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { // An unfinished edit (an empty file name is not saved) moves the first map down h.state_mut().ui.export.draft.as_mut().unwrap().maps[last].file.clear(); h.run_steps(2); - h.get_all_by_label("Move down").next().unwrap().click(); - h.run_steps(4); + move_map(&mut h, 0, "Move down"); // An agent saves the template in that order meanwhile: overrides now count from it let mut agent = saved.clone(); @@ -252,8 +298,7 @@ fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { // Stabilize the layout after fixing the draft so the next click hits the move button h.state_mut().ui.export.draft.as_mut().unwrap().maps[last].file = saved.maps[last].file.clone(); h.run_steps(2); - h.get_all_by_label("Move down").next().unwrap().click(); - h.run_steps(4); + move_map(&mut h, 0, "Move down"); let now = h.state().session.export_preset("Mine").unwrap(); assert_eq!(now.maps[1].file, saved.maps[1].file, "{:?}", now.maps.iter().map(|m| &m.file).collect::>()); let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); @@ -275,12 +320,8 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { harness.run_steps(3); // Repair the invalid first filename through the editor so the draft commits on that frame - let first_row = harness.get_all_by_label("Move down").next().unwrap().rect().center().y; - harness - .get_all_by_role(egui::Role::TextInput) - .find(|field| (field.rect().center().y - first_row).abs() < 4.0) - .unwrap() - .set_text_value_accesskit(&saved.maps[0].file); + let first_field = name_field(&harness, 0); + harness.get_all_by_role(egui::Role::TextInput).find(|field| field.rect() == first_field).unwrap().set_text_value_accesskit(&saved.maps[0].file); harness.run_steps(4); let current = harness.state().session.export_preset("Mine").unwrap(); @@ -314,3 +355,119 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { } assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); } + +#[test] +fn the_presets_row_holds_copy_minus_and_plus_without_tooltips() { + let library = TemplateLibrary::new("preset-icons"); + let mut h = harness(&library); + + let presets = h.get_by_label("Presets").rect(); + let icons = ["Duplicate the selected template", "Delete the selected template", "New template"].map(|label| h.get_by_label(label).rect()); + + assert!(icons.iter().all(|icon| (icon.center().y - presets.center().y).abs() < presets.height()), "on the Presets row: {icons:?}"); + assert!(icons.windows(2).all(|pair| pair[0].center().x < pair[1].center().x), "copy, minus, plus from left to right"); + h.hover_at(icons[2].center()); + h.run_steps(30); + assert_eq!(h.query_all_by_label("New template").count(), 1, "no tooltip repeats the name"); + assert!(h.query_by_label("Import a template (.json)").is_none(), "no import button"); + + right_click(&mut h, "Mine"); + assert!(h.query_by_label("Import a template (.json)").is_some(), "import and export stay in the right-click menu"); + assert!(h.query_by_label("Export the selected template (.json)").is_some()); +} + +#[test] +fn the_map_lists_stand_in_three_panes_with_the_reference_names() { + let library = TemplateLibrary::new("panes"); + let h = harness(&library); + + let input = h.get_by_label("Input maps").rect(); + let mesh = h.get_by_label("Mesh maps").rect(); + let converted = h.get_by_label("Converted maps").rect(); + + assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); + assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); + for group in ["Base", "Transmission", "Subsurface", "Coat", "Fuzz/Sheen"] { + assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); + } + for name in ["Base metalness", "Specular roughness", "Coat normal", "Fuzz weight", "World space normal", "Bent normals", "Normal DirectX", "f0"] { + let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); + assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); + } + for name in ["Base weight", "Coat tangent", "1/ior", "Glossiness²", "2D View"] { + let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); + assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); + } + for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal"] { + assert!(h.query_by_label(gone).is_none(), "{gone}"); + } +} + +#[test] +fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { + let library = TemplateLibrary::new("drop"); + let mut h = harness(&library); + click(&mut h, "R+G+B+A"); + let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; + + let green = last_window_button(&h, "G").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, green); + + assert!(h.query_by_label("From Base color").is_some(), "the popup names the dropped map"); + for choice in ["R Channel", "G Channel", "B Channel"] { + assert!(!h.get_by_label(choice).accesskit_node().is_disabled(), "{choice}"); + } + for greyed in ["Gray Channel", "A Channel"] { + assert!(h.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed}"); + } + h.get_by_label("B Channel").click(); + h.run_steps(4); + + let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); + assert!(map.channels.contains(&(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 2 })), "{:?}", map.channels); + assert!(h.query_by_label("From Base color").is_none(), "the popup closed"); + assert!(h.query_all_by_label("G: Base color (B Channel)").next().is_some(), "the swatch names its map"); + assert_eq!(h.state().ui.export.active_map, Some(last), "the lists mark this map's sources"); +} + +#[test] +fn a_gray_map_dropped_on_a_channel_offers_its_gray_channel() { + let library = TemplateLibrary::new("drop-gray"); + let mut h = harness(&library); + click(&mut h, "R+G+B+A"); + + let alpha = last_window_button(&h, "A").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, alpha); + + assert!(h.query_by_label("From Base metalness").is_some()); + assert!(!h.get_by_label("Gray Channel").accesskit_node().is_disabled()); + assert!(h.get_by_label("A Channel").accesskit_node().is_disabled()); + assert!(h.query_by_label("R Channel").is_none(), "a gray map has no R, G or B"); +} + +#[test] +fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_invert() { + let library = TemplateLibrary::new("swatch-menu"); + let mut h = harness(&library); + click(&mut h, "RGB"); + let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; + + // The RGB swatch is the last "RGB" button, after the Create button of that name + last_window_button(&h, "RGB").click(); + h.run_steps(4); + assert!(h.query_by_label("Clear channel").is_some()); + h.get_by_label("Split/Collapse RGB").click(); + h.run_steps(4); + assert_eq!(h.state().ui.export.draft_split.get(last), Some(&true), "R, G and B show apart"); + + let green = last_window_button(&h, "G"); + let at = green.rect().center(); + green.click_secondary(); + h.run_steps(4); + + // The properties panel has Invert controls of its own: take the menu's, next to the swatch + let invert = h.get_all_by_label("Invert").min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at))).unwrap(); + invert.click(); + h.run_steps(4); + assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); +} diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs index 748d5035..fc8f19f6 100644 --- a/crates/ui-egui/tests/it/template_invert.rs +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -1,4 +1,5 @@ -//! Export dialog › Output templates: each output channel has an Invert toggle that is saved in the template. +//! Export dialog › Output templates: each output channel can be inverted from its swatch's +//! right-click menu, and the inversion is saved in the template. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -26,12 +27,17 @@ fn harness() -> (Harness<'static, TextureCraftApp>, Library) { (h, Library(dir)) } -/// The channel toggles of the open dialog (the dialog sits left of the properties panel, which has its own Invert controls) -fn toggles<'h>(h: &'h Harness<'_, TextureCraftApp>) -> Vec> { - h.get_all_by_label("Invert").filter(|n| n.rect().max.x < DIALOG_RIGHT_EDGE).collect() -} +/// Right-click the swatch `swatch` and click the Invert of its menu (the properties panel has Invert controls of its own) +fn toggle_invert(h: &mut Harness<'_, TextureCraftApp>, swatch: &str) { + let node = h.get_all_by_label(swatch).next().unwrap_or_else(|| panic!("no {swatch} swatch")); + let at = node.rect().center(); + node.click_secondary(); + h.run_steps(4); -const DIALOG_RIGHT_EDGE: f32 = 1200.0; + let invert = h.get_all_by_label("Invert").min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at))).unwrap(); + invert.click(); + h.run_steps(4); +} fn template() -> ExportPreset { let ch = |channel| SourceRef::Channel { channel, component: 0 }; @@ -60,12 +66,12 @@ fn invert_toggle_changes_the_saved_template() { let saved = |h: &Harness<'_, TextureCraftApp>| h.state().session.export_preset(TEMPLATE).unwrap().maps[0].inverted.clone(); assert!(saved(&h).is_empty()); - // One Invert toggle per channel: R, G, B - assert_eq!(toggles(&h).len(), 3); - toggles(&h)[1].click(); - h.run_steps(4); + // Three maps in R, G and B: one swatch per channel + for swatch in ["R: Specular roughness", "G: Base metalness", "B"] { + assert!(h.query_all_by_label(swatch).next().is_some(), "{swatch}"); + } + toggle_invert(&mut h, "G: Base metalness"); assert_eq!(saved(&h), vec![Dest::G], "the second channel (G) is inverted"); - toggles(&h)[1].click(); - h.run_steps(4); + toggle_invert(&mut h, "G: Base metalness"); assert!(saved(&h).is_empty(), "a second click turns it off"); } From 2cea24fe7135a84a289eeb983e69d10cf050cd45 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:44:49 +0100 Subject: [PATCH 071/153] Export textures: boxed tabs, full-width Global settings, reference label column, dilation arrow, console header band and bold set names, one name per output map row --- crates/ui-egui/src/export_window.rs | 161 +++++++++++++++--- .../ui-egui/tests/it/export_map_overrides.rs | 11 ++ 2 files changed, 148 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 59ed790e..3c3ae50a 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -5,14 +5,14 @@ use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::formats::{ExportPreset, FileFormat}; +use texturecraft_engine::formats::{ExportPreset, FileFormat, MapSpec, SourceRef}; use crate::TextureCraftApp; #[cfg(not(target_arch = "wasm32"))] use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; -use crate::theme::{Tokens, caption}; +use crate::theme::{Tokens, caption, semibold}; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; @@ -30,10 +30,26 @@ const WINDOW_CHROME_HEIGHT_POINTS: f32 = 80.0; /// The smallest tab body, so the lists and pages stay usable const MIN_BODY_HEIGHT_POINTS: f32 = 160.0; /// Width of the texture set list -const LIST_WIDTH: f32 = 180.0; +const LIST_WIDTH: f32 = 250.0; const ICON: f32 = 20.0; +/// Width of the label column of the parameter rows, as in the reference +const LABEL_COLUMN_WIDTH: f32 = 200.0; /// Width of the value column of the parameter rows const VALUE_WIDTH: f32 = 360.0; +/// Width of the first File type list; the bit depth list fills the rest of the row +const FILE_TYPE_WIDTH: f32 = 166.0; +/// Width of the dilation button, with room for its drop-down arrow +const DILATION_BUTTON_WIDTH: f32 = 60.0; +/// Size of a drop-down arrow, and its distance from the button's right edge +const CARET_SIZE: f32 = 10.0; +const CARET_INSET: f32 = 6.0; +/// A tab: padding around its name, the accent line on top of the open one, the name's size +const TAB_PADDING: egui::Vec2 = egui::vec2(10.0, 6.0); +const TAB_ACCENT_HEIGHT: f32 = 2.0; +const TAB_TEXT_SIZE: f32 = 12.5; +/// Height of a full-width row of the texture set list and where its text starts +const LIST_ROW_HEIGHT: f32 = 24.0; +const LIST_ROW_INDENT: f32 = 16.0; /// Width of the bottom bar's buttons, the same for all as in the reference const FOOTER_BUTTON_WIDTH: f32 = 125.0; @@ -104,7 +120,7 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f let shown = if format.is_empty() { tr("Based on output template").to_string() } else { file_type_name(format) }; // Tall enough for the whole list - let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { 166.0 } else { 90.0 }).height(f32::INFINITY); + let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { FILE_TYPE_WIDTH } else { 90.0 }).height(f32::INFINITY); list.selected_text(shown).show_ui(ui, |ui| { if from_template { if ui.selectable_label(format.is_empty(), tr("Based on output template")).clicked() { @@ -130,7 +146,9 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; ui.add_enabled_ui(options.len() > 1, |ui| { - egui::ComboBox::from_id_salt(("bits", id)).width(if from_template { 160.0 } else { 120.0 }).selected_text(shown).show_ui(ui, |ui| { + // On the global page the bit depth list fills the row + let width = if from_template { VALUE_WIDTH - FILE_TYPE_WIDTH - ui.spacing().item_spacing.x } else { 120.0 }; + egui::ComboBox::from_id_salt(("bits", id)).width(width).selected_text(shown).show_ui(ui, |ui| { for (d, dither) in options { if ui.selectable_label((*bit_depth, *dithering) == (d, dither), depth_label(parsed, d, dither)).clicked() { (*bit_depth, *dithering) = (d, dither); @@ -510,12 +528,23 @@ fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset.as_ref().and_then(|p| p.maps.get(map)).map(|m| m.file.clone()).unwrap_or_default(); + let pattern = preset.as_ref().and_then(|p| p.maps.get(map)).map(|m| m.file.replace("$channel", channel_id(m))).unwrap_or_default(); rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); } rows } +/// What `$channel` becomes in `map`'s file name: the id of its first map, as the export names it +fn channel_id(map: &MapSpec) -> &'static str { + let first = map.channels.iter().find_map(|(_, source)| match source { + SourceRef::Channel { channel, .. } => Some(channel.id()), + SourceRef::Virtual { map, .. } => Some(map.id()), + SourceRef::Baked { map, .. } => Some(map.id()), + SourceRef::Constant(_) => None, + }); + first.unwrap_or("constant") +} + /// The Output maps section of texture set `ts`'s page fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { let rows = map_rows(app, ts); @@ -586,6 +615,28 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } +/// A window tab: a box, lighter and with an accent line on top when open +fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let color = if selected { tokens.text_strong } else { tokens.text }; + let galley = ui.painter().layout_no_wrap(label.to_string(), semibold(TAB_TEXT_SIZE), color); + let (rect, response) = ui.allocate_exact_size(galley.size() + 2.0 * TAB_PADDING, egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, selected, label)); + + let painter = ui.painter(); + let fill = match (selected, response.hovered()) { + (true, _) => tokens.panel, + (false, true) => tokens.row_hover, + (false, false) => tokens.row, + }; + painter.rect(rect, 0.0, fill, egui::Stroke::new(1.0, tokens.separator), egui::StrokeKind::Inside); + if selected { + painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); + } + painter.galley(rect.min + TAB_PADDING, galley, color); + response +} + /// A bottom bar button, as wide as the others fn footer_button(text: &str) -> egui::Button<'_> { egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) @@ -649,11 +700,18 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { // The menu stays open while the slider is used let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); let r = ui.add_enabled_ui(enabled, |ui| { - egui::containers::menu::MenuButton::new(dilation.to_string()).config(config).ui(ui, |ui| { + let button = egui::Button::new(dilation.to_string()).min_size(vec2(DILATION_BUTTON_WIDTH, 0.0)); + egui::containers::menu::MenuButton::from_button(button).config(config).ui(ui, |ui| { ui.label(tr("Dilation (pixels)")); ui.add(egui::Slider::new(dilation, 0..=256).step_by(1.0)); }) }); + + // The drop-down arrow is drawn apart, so the button's name stays the number + let tokens = Tokens::get(ui.ctx()); + let arrow_color = if enabled { tokens.text } else { tokens.text_dim }; + let arrow_at = r.response.rect.right_center() - vec2(CARET_INSET, 0.0); + ui.painter().text(arrow_at, egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_SIZE), arrow_color); if enabled { r.response.on_hover_text(tr("Dilation in pixels")); } else { @@ -705,7 +763,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::export_templates::select(app, defaults.preset); } let (first, rest) = template_groups(app, builtins); - egui::Grid::new("exp_grid").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("exp_grid").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { // The browser downloads the files instead #[cfg(not(target_arch = "wasm32"))] output_directory(app, ui); @@ -734,7 +792,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ui.end_row(); ui.label(tr("Padding")); ui.horizontal(|ui| { - egui::ComboBox::from_id_salt("exp_pad").width(260.0).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { + let width = VALUE_WIDTH - DILATION_BUTTON_WIDTH - ui.spacing().item_spacing.x; + egui::ComboBox::from_id_salt("exp_pad").width(width).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { for (value, label) in PADDINGS { ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); } @@ -758,7 +817,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); ui.add_space(8.0); - egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; ui.label(tr("Normal map format")); let normal_label = match settings.normal_format.as_str() { @@ -790,7 +849,7 @@ fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, body_height: f32) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); }); - let header = ui.selectable_label(app.ui.export.page.is_none(), RichText::new(tr("Global settings")).strong()); + let header = list_row(ui, tr("Global settings"), app.ui.export.page.is_none()); if header.clicked() { app.ui.export.page = None; } @@ -800,6 +859,23 @@ fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, body_height: f32) { egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); } +/// A row across the whole list, its name in bold; the selected one framed +fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), LIST_ROW_HEIGHT), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, text)); + + let painter = ui.painter(); + if selected { + painter.rect(rect, 0.0, tokens.row_selected, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, tokens.row_hover); + } + let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); + painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); + response +} + /// A row per texture set: its export tick, its name and the override mark fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { for i in 0..app.session.set_count() { @@ -822,6 +898,7 @@ fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { }); } }); + ui.separator(); } } @@ -901,7 +978,7 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor }); }); let mut toggled = None; - egui::Grid::new(("exp_set_grid", ts)).num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new(("exp_set_grid", ts)).num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let on = o.preset.is_some(); if override_row(ui, tr("Output template"), on, &from.preset, |ui| { if let Some(p) = &mut o.preset { @@ -974,6 +1051,16 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor /// Width of the LIST OF EXPORTS console const CONSOLE_WIDTH: f32 = 300.0; +/// Width of the strip between the file tree and the console +const SPLITTER_WIDTH: f32 = 14.0; +/// Padding of the CONSOLE header band, about 45 points high as in the reference +const CONSOLE_HEADER_MARGIN_X: i8 = 12; +const CONSOLE_HEADER_MARGIN_Y: i8 = 14; +/// The file tree: indent of the file rows under their texture set, and the row height +const TREE_INDENT: f32 = 35.0; +const TREE_ROW_HEIGHT: f32 = 17.0; +/// Half the width of the tree's chevron +const CHEVRON_HALF_WIDTH: f32 = 4.0; /// Green of the console's success lines fn success(tk: &Tokens) -> egui::Color32 { @@ -991,9 +1078,11 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); - // The thin toggle at the console's left edge + // The thin toggle at the console's left edge, on a strip the whole height let toggle = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let r = ui.add_sized(vec2(14.0, ui.available_height()), egui::Button::new(toggle).frame(false)); + let strip = egui::Rect::from_min_size(ui.cursor().min, vec2(SPLITTER_WIDTH, ui.available_height())); + ui.painter().rect_filled(strip, 0.0, tk.chrome); + let r = ui.add_sized(strip.size(), egui::Button::new(toggle).frame(false)); let r = if hidden { r } else { r.on_hover_text(tr("Hide Console")) }; if r.clicked() { app.ui.export.console_hidden = !hidden; @@ -1001,9 +1090,12 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { if !hidden { ui.vertical(|ui| { ui.set_width(CONSOLE_WIDTH); - ui.label(caption(&tr("Console").to_uppercase()).strong()); - ui.separator(); - egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true).show(ui, |ui| { + egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(caption(&tr("Console").to_uppercase()).strong()); + }); + let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); + console.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show(ui, |ui| { for line in &app.ui.export.console { match line { ConsoleLine::Step(t) => { @@ -1030,7 +1122,7 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { let plain = egui::TextFormat::simple(font.clone(), tk.text); let mut job = egui::text::LayoutJob::default(); job.append(before, 0.0, plain.clone()); - job.append(name, 0.0, egui::TextFormat::simple(font, tk.text_strong)); + job.append(name, 0.0, egui::TextFormat::simple(semibold(font.size), tk.text_strong)); job.append(after, 0.0, plain); job } @@ -1063,9 +1155,11 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) } fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &str, tokens: &Tokens) { - egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).show(ui, |ui| match &set.files { + ui.spacing_mut().indent = TREE_INDENT; + let header = egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).icon(chevron); + header.show(ui, |ui| match &set.files { Ok(files) => { - egui::Grid::new(("exp_tree_grid", index)).num_columns(4).spacing(vec2(12.0, 4.0)).show(ui, |ui| { + egui::Grid::new(("exp_tree_grid", index)).num_columns(4).min_row_height(TREE_ROW_HEIGHT).spacing(vec2(12.0, 4.0)).show(ui, |ui| { for output in files.as_array().into_iter().flatten() { let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); @@ -1088,6 +1182,21 @@ fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &s }); } +/// The tree's outline chevron: pointing down when open, right (left in right-to-left) when closed +fn chevron(ui: &mut Ui, openness: f32, response: &egui::Response) { + let color = Tokens::get(ui.ctx()).text; + let center = response.rect.center(); + let half = CHEVRON_HALF_WIDTH; + let points = if openness > 0.5 { + [center + vec2(-half, -half / 2.0), center + vec2(0.0, half / 2.0), center + vec2(half, -half / 2.0)] + } else if ui.style().right_to_left { + [center + vec2(half / 2.0, -half), center + vec2(-half / 2.0, 0.0), center + vec2(half / 2.0, half)] + } else { + [center + vec2(-half / 2.0, -half), center + vec2(half / 2.0, 0.0), center + vec2(-half / 2.0, half)] + }; + ui.painter().add(egui::Shape::line(points.to_vec(), egui::Stroke::new(1.5, color))); +} + /// Show the output folder in the system's file manager (created first when missing) #[cfg(not(target_arch = "wasm32"))] fn open_output_directory(app: &mut TextureCraftApp) { @@ -1295,11 +1404,15 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } ui.horizontal(|ui| { - for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if ui.selectable_label(app.ui.export.tab == i as u8, caption(&t.to_uppercase())).clicked() { - app.ui.export.tab = i as u8; + // Boxed tabs side by side + ui.scope(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { + if tab_button(ui, &t.to_uppercase(), app.ui.export.tab == i as u8).clicked() { + app.ui.export.tab = i as u8; + } } - } + }); // The file list opens the destination folder ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 8e627895..45ce9297 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -152,3 +152,14 @@ fn a_map_the_template_no_longer_has_is_ignored() { h.run_steps(3); assert_eq!(selected(&h), before, "the export still plans every file"); } + +#[test] +fn each_row_names_its_own_map() { + let h = harness(); + + // The default template names its maps with $channel: each row shows the map it writes + assert!(h.query_all_by_label_contains("$channel").next().is_none(), "the channel variable is filled in"); + for id in ["baseColor", "metallic", "roughness"] { + assert!(h.query_all_by_label_contains(&format!("_{id}")).next().is_some(), "a row for {id}"); + } +} From 52e428300f9ff82f8d26be95c5511d16d51981b9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:45:11 +0100 Subject: [PATCH 072/153] Describe the reference Output templates tab in the UI parity notes --- docs/ui-parity.md | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3cb62522..49271c38 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -337,9 +337,30 @@ that numbers hide once a tile is under 40 points on screen. list is titled *Presets* and lists the templates sorted by name, without the template list's first group. A right click on a preset offers *Rename*, *Duplicate* and *Remove* (Rename and Remove are greyed for built-in templates, which are read-only); F2 renames the selected one. - "+" creates "new_export_preset", Duplicate "_copy". *Naming pattern* (*OpenPBR*; the - reference's second pattern names another vendor's material and is left out) with its info - tooltip sits above the input maps. The middle reads "Current preset: ", *Output maps* - with *Create:* Gray, RGB, R+G+B, RGB+A, R+G+B+A, and a footer with drag-and-drop guidance and the number of output maps. TextureCraft keeps its - own list tools (rename, import, export) and asks before deleting; R+G+B and R+G+B+A create the - same maps as RGB and RGB+A (each channel takes its own source in either). + "+" creates "new_export_preset", Duplicate "_copy". The *Presets* row holds copy, "−" + and "+" without tooltips ([#789](https://github.com/storytold/texturecraft/issues/789)). + *Naming pattern* (*OpenPBR*; the reference's second pattern names another vendor's material and + is left out) with its info tooltip sits at the right end of the tab row; this tab has no + *Include all*, *Reset all* or texture count, and *Save settings* and *Export* are greyed. The + middle reads "Current preset: ", *Output maps* with *Create:* Gray, RGB, R+G+B, RGB+A, + R+G+B+A on the same row, and a footer with drag-and-drop guidance and the number of output + maps. Each output map is one row: a drag grip (drag it onto another row to move the map), the + file name, "$" with the file name variables ($project, $mesh, $textureSet, $udim, $uvTileName + greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gray, RGB or R, G, B, + then A), the file type and bit depth lists ("8 bits + dithering" greyed: templates do not keep + it), duplicate and "×". Dropping a map on a swatch opens "From ": a gray map offers *Gray + Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G Channel*, *B Channel* + and *A Channel* (TextureCraft has no alpha or gray of a map yet: those are greyed). A colour + map dropped on the RGB swatch fills R, G and B at once. The swatch then takes the map's + colour, and the map lists mark the maps of the output map edited last with that colour. A + click on a swatch offers *Clear channel* and *Split/Collapse RGB*. The right side has the + *Input maps* pane, grouped as in the reference (Base, Specular, Transmission, Subsurface, + Coat, Fuzz/Sheen; then Emission, Geometry and Other for the channels the reference screenshot + cuts off), and a pane with *Mesh maps* above *Converted maps* (highlighted); maps TextureCraft + does not have yet are greyed and cannot be dragged. TextureCraft keeps a few things the + reference does not show, out of the way: Import and Export of template files at the end of a + preset's right-click menu, Invert in a swatch's right-click menu, *Move up* and *Move down* + in the grip's right-click menu (and the arrow keys on a focused grip), the planned file name + in the file name's tooltip, and three converted maps of its own (Normal from height, Roughness + from glossiness, Sheen color × weight) after the reference's. Built-in templates stay + read-only and deleting asks first. From 0642f1d29e421024ab42d2e454e42ef9d8ab67fa Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:46:33 +0100 Subject: [PATCH 073/153] Output templates: shorter lines and a type alias for the map groups --- crates/ui-egui/src/export_templates.rs | 26 +++++++++++-------- .../ui-egui/src/export_templates/map_lists.rs | 15 ++++++++--- crates/ui-egui/src/export_window.rs | 3 ++- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 2e109a1c..73cf3bd4 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1069,7 +1069,9 @@ fn source_name(source: &SourceRef, target: ChannelTarget) -> Option { let map = tr(map_lists::name_of(source)?); let picked = source_choices(source).into_iter().find(|(_, component)| *component == Some(component_of(source))); match picked { - Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])), + Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => { + Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])) + } _ => Some(map.to_string()), } } @@ -1173,7 +1175,8 @@ fn swatch(ui: &mut Ui, label: &str, name: &str, fill: Option, bars: &[C let painter = ui.painter(); let border = if response.hovered() { tokens.accent } else { tokens.button_border }; painter.rect(rect, tokens.radius, fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, egui::FontId::proportional(SWATCH_TEXT_SIZE), tokens.text_strong); + let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE); + painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); let bar_width = SWATCH_BAR_WIDTH / bars.len().max(1) as f32; let left = rect.center().x - SWATCH_BAR_WIDTH / 2.0; for (k, color) in bars.iter().enumerate() { @@ -1221,15 +1224,15 @@ fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> /// "From ": which channel of the dropped map the output channel reads. True when the map /// changed. fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec], active: &mut Option) -> bool { - let Some(drop) = pending.clone() else { return false }; - let Some(map) = maps.get_mut(drop.map) else { + let Some(waiting) = pending.clone() else { return false }; + let Some(map) = maps.get_mut(waiting.map) else { *pending = None; return false; }; - let name = map_lists::name_of(&drop.source).map_or_else(String::new, |name| tr(name).to_string()); + let name = map_lists::name_of(&waiting.source).map_or_else(String::new, |name| tr(name).to_string()); let mut picked = None; - let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(drop.position), ui.layer_id()) + let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(waiting.position), ui.layer_id()) .kind(egui::PopupKind::Menu) .layout(egui::Layout::top_down_justified(egui::Align::Min)) .style(egui::containers::menu::menu_style) @@ -1237,7 +1240,7 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); - for (label, component) in source_choices(&drop.source) { + for (label, component) in source_choices(&waiting.source) { match component { Some(component) => { if ui.button(tr(label)).clicked() { @@ -1255,13 +1258,13 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } let Some(component) = picked else { return false }; - let source = with_component(&drop.source, component); + let source = with_component(&waiting.source, component); for (dest, channel_source) in &mut map.channels { - if drop.target.dests().contains(dest) { + if waiting.target.dests().contains(dest) { *channel_source = source.clone(); } } - *active = Some(drop.map); + *active = Some(waiting.map); true } @@ -1334,7 +1337,8 @@ fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Co && let Some(at) = response.interact_pointer_pos() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)).show(ui.ctx(), |ui| chip(ui, name, true)); + let dragged = egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)); + dragged.show(ui.ctx(), |ui| chip(ui, name, true)); } } diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index 7690e805..1595c440 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -12,6 +12,9 @@ use crate::i18n::n_; /// One entry of a map list: its name and what it reads (None: not available yet). pub type MapEntry = (&'static str, Option); +/// A group of the Input maps pane: its name and entries. +pub type MapGroup = (&'static str, Vec); + fn channel(channel: Channel) -> Option { Some(SourceRef::Channel { channel, component: 0 }) } @@ -26,7 +29,7 @@ fn mesh(map: BakedMap) -> Option { /// Input maps in groups, as the reference lists them up to Fuzz/Sheen; the groups after it are /// cut off in the reference screenshots and use the OpenPBR names of the channels left over. -pub static INPUT_MAPS: LazyLock)>> = LazyLock::new(|| { +pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ ( n_("Base"), @@ -67,7 +70,11 @@ pub static INPUT_MAPS: LazyLock)>> = LazyLock:: ), ( n_("Fuzz/Sheen"), - vec![(n_("Fuzz weight"), channel(Channel::SheenWeight)), (n_("Fuzz color"), channel(Channel::SheenColor)), (n_("Fuzz roughness"), channel(Channel::SheenRoughness))], + vec![ + (n_("Fuzz weight"), channel(Channel::SheenWeight)), + (n_("Fuzz color"), channel(Channel::SheenColor)), + (n_("Fuzz roughness"), channel(Channel::SheenRoughness)), + ], ), (n_("Emission"), vec![(n_("Emission color"), channel(Channel::Emissive))]), (n_("Geometry"), vec![(n_("Geometry opacity"), channel(Channel::Opacity)), (n_("Geometry normal"), channel(Channel::Normal))]), @@ -134,8 +141,8 @@ mod tests { #[test] fn every_channel_and_map_can_be_dragged() { - let listed: Vec = - INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()).filter_map(|(_, s)| s.clone()).collect(); + let entries = INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()); + let listed: Vec = entries.filter_map(|(_, source)| source.clone()).collect(); for channel in Channel::ALL { assert!(listed.contains(&SourceRef::Channel { channel, component: 0 }), "{channel:?}"); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3c3ae50a..f9088406 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1500,7 +1500,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } // Saving closes the window without starting an export - if ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { + let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); + if save.on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { From e4a377e5022c9a00b7223c3fd2945e92e937a32d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 01:23:24 +0100 Subject: [PATCH 074/153] Export textures: rows on the texture set page use the export's channel ids, the console strip drags and toggles, buttons 126 wide --- crates/formats/src/export/mod.rs | 3 +- crates/ui-egui/src/export_window.rs | 60 +++++++++++++++++------------ 2 files changed, 38 insertions(+), 25 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f92ebbb4..8c56e0e2 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -546,7 +546,8 @@ fn layout<'m>(set: &TextureSet, map: &'m MapSpec) -> Vec<(Dest, &'m SourceRef)> out } -fn channel_label(map: &MapSpec) -> &'static str { +/// What `$channel` becomes in `map`'s file names: the id of its first non-constant source. +pub fn channel_label(map: &MapSpec) -> &'static str { map.channels .iter() .find_map(|(_, s)| match s { diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index f9088406..c02948b1 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -5,7 +5,7 @@ use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::formats::{ExportPreset, FileFormat, MapSpec, SourceRef}; +use texturecraft_engine::formats::{ExportPreset, FileFormat}; use crate::TextureCraftApp; #[cfg(not(target_arch = "wasm32"))] @@ -51,7 +51,7 @@ const TAB_TEXT_SIZE: f32 = 12.5; const LIST_ROW_HEIGHT: f32 = 24.0; const LIST_ROW_INDENT: f32 = 16.0; /// Width of the bottom bar's buttons, the same for all as in the reference -const FOOTER_BUTTON_WIDTH: f32 = 125.0; +const FOOTER_BUTTON_WIDTH: f32 = 126.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -528,23 +528,16 @@ fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset.as_ref().and_then(|p| p.maps.get(map)).map(|m| m.file.replace("$channel", channel_id(m))).unwrap_or_default(); + let pattern = preset + .as_ref() + .and_then(|p| p.maps.get(map)) + .map(|m| m.file.replace("$channel", texturecraft_engine::formats::export::channel_label(m))) + .unwrap_or_default(); rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); } rows } -/// What `$channel` becomes in `map`'s file name: the id of its first map, as the export names it -fn channel_id(map: &MapSpec) -> &'static str { - let first = map.channels.iter().find_map(|(_, source)| match source { - SourceRef::Channel { channel, .. } => Some(channel.id()), - SourceRef::Virtual { map, .. } => Some(map.id()), - SourceRef::Baked { map, .. } => Some(map.id()), - SourceRef::Constant(_) => None, - }); - first.unwrap_or("constant") -} - /// The Output maps section of texture set `ts`'s page fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { let rows = map_rows(app, ts); @@ -1049,8 +1042,9 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor } } -/// Width of the LIST OF EXPORTS console +/// The LIST OF EXPORTS console's and file tree's least width, as in the reference const CONSOLE_WIDTH: f32 = 300.0; +const MIN_TREE_WIDTH: f32 = 300.0; /// Width of the strip between the file tree and the console const SPLITTER_WIDTH: f32 = 14.0; /// Padding of the CONSOLE header band, about 45 points high as in the reference @@ -1072,24 +1066,37 @@ fn success(tk: &Tokens) -> egui::Color32 { fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; - let tree_width = ui.available_width() - if hidden { 24.0 } else { CONSOLE_WIDTH + 24.0 }; + + // Tree and console keep at least their reference width + let spacing = ui.spacing().item_spacing.x; + let room = ui.available_width() - SPLITTER_WIDTH - 2.0 * spacing; + let console_width = app.ui.export.console_width.min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); + let tree_width = if hidden { room } else { room - console_width }; ui.vertical(|ui| { ui.set_width(tree_width); egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); - // The thin toggle at the console's left edge, on a strip the whole height - let toggle = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let strip = egui::Rect::from_min_size(ui.cursor().min, vec2(SPLITTER_WIDTH, ui.available_height())); + // The strip at the console's left edge: a click hides or shows the console, a drag resizes it + let (strip, response) = ui.allocate_exact_size(vec2(SPLITTER_WIDTH, ui.available_height()), egui::Sense::click_and_drag()); + let tooltip = if hidden { tr("Show Console") } else { tr("Hide Console") }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip)); + let glyph = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; + let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; ui.painter().rect_filled(strip, 0.0, tk.chrome); - let r = ui.add_sized(strip.size(), egui::Button::new(toggle).frame(false)); - let r = if hidden { r } else { r.on_hover_text(tr("Hide Console")) }; - if r.clicked() { + ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); + let response = response.on_hover_text(tooltip); + if !hidden && (response.hovered() || response.dragged()) { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if response.dragged() && !hidden { + app.ui.export.console_width = (console_width - response.drag_delta().x).min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); + } else if response.clicked() { app.ui.export.console_hidden = !hidden; } if !hidden { ui.vertical(|ui| { - ui.set_width(CONSOLE_WIDTH); + ui.set_width(console_width); egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(caption(&tr("Console").to_uppercase()).strong()); @@ -1384,6 +1391,11 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } keep_file_type_visible(&mut app.ui.export); follow_texture_sets(app); + + // A map waiting for its source channel belongs to the OUTPUT TEMPLATES tab + if app.ui.export.tab != 1 { + app.ui.export.pending_drop = None; + } if app.ui.export.opened_with.is_none() { let mut now = app.ui.export.clone(); now.draft = None; @@ -1426,7 +1438,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } else if app.ui.export.tab == 1 { crate::export_templates::naming_pattern(ui); - } else if ui.button(tr("Include all")).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { + } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { o.maps.values_mut().for_each(|m| m.enabled = true); From 36c6cd597e8ad1888a5d97d7b9a123f2d95019c0 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 01:23:31 +0100 Subject: [PATCH 075/153] Output templates: the reference's map lists, From popup, swatch texts and menus, row names and tooltips; narrow windows keep rows whole --- crates/ui-egui/src/export_templates.rs | 660 ++++++++++++------ .../ui-egui/src/export_templates/map_lists.rs | 61 +- .../ui-egui/src/export_templates/row_edit.rs | 2 - .../src/export_templates/source_pick.rs | 8 + .../src/export_templates/swatch_look.rs | 10 + crates/ui-egui/src/state.rs | 13 +- crates/ui-egui/tests/it/export_progress.rs | 13 +- crates/ui-egui/tests/it/output_templates.rs | 131 +++- crates/ui-egui/tests/it/template_invert.rs | 6 +- 9 files changed, 626 insertions(+), 278 deletions(-) create mode 100644 crates/ui-egui/src/export_templates/source_pick.rs create mode 100644 crates/ui-egui/src/export_templates/swatch_look.rs diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 73cf3bd4..79f713e0 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -22,19 +22,30 @@ mod map_drag; mod map_lists; mod pending_drop; mod row_edit; +mod source_pick; +mod swatch_look; pub use channel_target::ChannelTarget; use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; pub use pending_drop::PendingDrop; use row_edit::RowEdit; +use source_pick::SourcePick; +use swatch_look::SwatchLook; -const ICON: f32 = 20.0; -const LIST_WIDTH: f32 = 220.0; +const ICON_POINTS: f32 = 20.0; +/// Width of the Presets list +const LIST_WIDTH_POINTS: f32 = 220.0; +/// The tab's width in the reference-size window: a narrower window narrows the side panes in +/// proportion, so the output rows keep their room +const REFERENCE_TAB_WIDTH_POINTS: f32 = 1085.0; +/// The middle column's least width, and room for the separators and their spacing +const MIN_OUTPUTS_WIDTH_POINTS: f32 = 200.0; +const SEPARATOR_ALLOWANCE_POINTS: f32 = 6.0; /// Width of the Input maps pane -const INPUTS_WIDTH: f32 = 170.0; +const INPUTS_WIDTH_POINTS: f32 = 170.0; /// Width of the pane with Mesh maps above Converted maps -const SIDE_MAPS_WIDTH: f32 = 165.0; +const SIDE_MAPS_WIDTH_POINTS: f32 = 165.0; /// Share of the side pane's height that Mesh maps take; Converted maps get the rest const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; @@ -42,35 +53,46 @@ const RENAME_ID: &str = "exp_rename"; const NEW_PRESET: &str = "new_export_preset"; /// Height of a Presets list row, and where its icon and name start -const PRESET_ROW_HEIGHT: f32 = 18.0; -const PRESET_ICON_INDENT: f32 = 2.0; -const PRESET_TEXT_INDENT: f32 = 20.0; +const PRESET_ROW_HEIGHT_POINTS: f32 = 18.0; +const PRESET_ICON_INDENT_POINTS: f32 = 2.0; +const PRESET_TEXT_INDENT_POINTS: f32 = 20.0; /// Height of a map list entry, the gap between entries, and where its marker and name sit -const ENTRY_HEIGHT: f32 = 21.0; -const ENTRY_GAP: f32 = 2.0; -const ENTRY_TEXT_INDENT: f32 = 22.0; -const ENTRY_TEXT_SIZE: f32 = 12.0; -const MARKER_INDENT: f32 = 10.0; -const MARKER_SIZE: f32 = 10.0; +const ENTRY_HEIGHT_POINTS: f32 = 21.0; +const ENTRY_GAP_POINTS: f32 = 2.0; +const ENTRY_TEXT_INDENT_POINTS: f32 = 22.0; +const ENTRY_TEXT_SIZE_POINTS: f32 = 12.0; +const MARKER_INDENT_POINTS: f32 = 10.0; +const MARKER_SIZE_POINTS: f32 = 10.0; /// How strongly a map TextureCraft does not have yet is dimmed const UNAVAILABLE_FADE: f32 = 0.6; /// An output map row: padding, gap below it, grip width, file name field width, icon size -const ROW_MARGIN: f32 = 6.0; -const ROW_GAP: f32 = 4.0; -const GRIP_WIDTH: f32 = 5.0; -const NAME_FIELD_WIDTH: f32 = 150.0; -const ROW_ICON: f32 = 16.0; +const ROW_MARGIN_POINTS: f32 = 6.0; +const ROW_GAP_POINTS: f32 = 4.0; +const GRIP_WIDTH_POINTS: f32 = 5.0; +const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; +const ROW_ICON_POINTS: f32 = 16.0; +/// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a +/// row's right end, and the gaps between a row's controls (besides the swatches') +const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; +const DOLLAR_BUTTON_WIDTH_POINTS: f32 = 22.0; +const ROW_LISTS_WIDTH_POINTS: f32 = 100.0; +const ROW_GAPS: f32 = 4.0; +/// The accent frame around a drop target: its stroke and its gap to the target +const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; +const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; +/// Side of the corner mark of an inverted swatch +const INVERTED_MARK_POINTS: f32 = 8.0; /// A channel swatch: its side, the label's size and offset from the top, and the bars that show /// which channels of the source it reads -const SWATCH_SIZE: f32 = 32.0; -const SWATCH_TEXT_SIZE: f32 = 11.0; -const SWATCH_TEXT_TOP: f32 = 3.0; -const SWATCH_BAR_WIDTH: f32 = 18.0; -const SWATCH_BAR_HEIGHT: f32 = 2.0; -const SWATCH_BAR_BOTTOM: f32 = 9.0; +const SWATCH_SIZE_POINTS: f32 = 32.0; +const SWATCH_TEXT_SIZE_POINTS: f32 = 11.0; +const SWATCH_TEXT_TOP_POINTS: f32 = 3.0; +const SWATCH_BAR_WIDTH_POINTS: f32 = 18.0; +const SWATCH_BAR_HEIGHT_POINTS: f32 = 2.0; +const SWATCH_BAR_BOTTOM_POINTS: f32 = 9.0; /// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to /// keep the white label readable @@ -103,6 +125,17 @@ enum Layout { } impl Layout { + const ALL: [Layout; 4] = [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha]; + + fn label(self) -> &'static str { + match self { + Layout::Rgb => "RGB", + Layout::Rgba => "RGBA", + Layout::Gray => n_("Gray"), + Layout::GrayAlpha => n_("Gray + A"), + } + } + fn dests(self) -> &'static [Dest] { match self { Layout::Rgb => &[Dest::R, Dest::G, Dest::B], @@ -124,20 +157,25 @@ impl Layout { } /// The reference's Create buttons: (label, the layout the new output map gets, whether R, G and -/// B show as separate swatches) -const CREATE: [(&str, Layout, bool); 5] = [ - (n_("Gray"), Layout::Gray, false), - ("RGB", Layout::Rgb, false), - ("R+G+B", Layout::Rgb, true), - ("RGB+A", Layout::Rgba, false), - ("R+G+B+A", Layout::Rgba, true), +/// B show as separate swatches, the new map's file name) +const CREATE: [(&str, Layout, bool, &str); 5] = [ + (n_("Gray"), Layout::Gray, false, "Grayscale"), + ("RGB", Layout::Rgb, false, "RGB"), + ("R+G+B", Layout::Rgb, true, "RGB"), + ("RGB+A", Layout::Rgba, false, "RGB Alpha"), + ("R+G+B+A", Layout::Rgba, true, "RGB Alpha"), ]; +/// The swatch right-click menu's constants: (label, value) +const CONSTANTS: [(&str, f32); 3] = [(n_("Black"), 0.0), (n_("Gray 50%"), 0.5), (n_("White"), 1.0)]; +/// How fast dragging changes a constant +const CONSTANT_DRAG_SPEED: f64 = 0.005; + /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; /// Width of the Naming pattern list -const NAMING_PATTERN_WIDTH: f32 = 150.0; +const NAMING_PATTERN_WIDTH_POINTS: f32 = 150.0; /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { @@ -206,12 +244,23 @@ fn set_layout(map: &mut MapSpec, layout: Layout) { map.inverted = inverted; } -fn new_map(layout: Layout) -> MapSpec { - let mut map = MapSpec { file: "$mesh_$textureSet_Output".into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new(), inverted: Vec::new() }; +/// A new empty png / 8 bits output map named `file` +fn new_map(layout: Layout, file: &str) -> MapSpec { + let mut map = MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new(), inverted: Vec::new() }; set_layout(&mut map, layout); map } +/// `name`, or with "_1", "_2", ... when a map of `maps` already has it, as the reference names new rows +fn unique_file(maps: &[MapSpec], name: &str) -> String { + let taken = |file: &str| maps.iter().any(|map| map.file == file); + if !taken(name) { + return name.to_string(); + } + + (1..).map(|n| format!("{name}_{n}")).find(|file| !taken(file)).unwrap_or_else(|| name.to_string()) +} + /// An input map dropped on channel `dest`: a color or normal input dropped on R, G or B fills /// all three. fn drop_input(map: &mut MapSpec, dest: Dest, input: &SourceRef) { @@ -238,7 +287,6 @@ fn sync_draft(app: &mut TextureCraftApp) { e.draft_maps.clear(); e.draft_base = None; e.draft_split.clear(); - e.active_map = None; e.pending_drop = None; } Some(saved) => { @@ -247,7 +295,6 @@ fn sync_draft(app: &mut TextureCraftApp) { e.draft_maps = (0..saved.maps.len()).map(Some).collect(); e.draft_base = Some(saved.clone()); e.draft_split.clear(); - e.active_map = None; e.pending_drop = None; } else if e.draft_base.as_ref() != Some(saved) { // Match only unambiguous maps from the previous saved order @@ -274,9 +321,12 @@ pub use crate::ask::Ask; pub use crate::list_action::ListAction; enum MapAction { - /// A new output map with this layout, its R, G and B split or not - Add(Layout, bool), - Move { from: usize, to: usize }, + /// A new output map with this layout, its R, G and B split or not, and this file name + Add(Layout, bool, &'static str), + Move { + from: usize, + to: usize, + }, Duplicate(usize), Remove(usize), } @@ -287,32 +337,34 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { sync_draft(app); let height = ui.available_height(); let names = crate::export_window::template_groups(app, builtins).1; + let scale = (ui.available_width() / REFERENCE_TAB_WIDTH_POINTS).min(1.0); + let (list_width, inputs_width, side_width) = (LIST_WIDTH_POINTS * scale, INPUTS_WIDTH_POINTS * scale, SIDE_MAPS_WIDTH_POINTS * scale); let mut list_action = None; ui.vertical(|ui| { - ui.set_width(LIST_WIDTH); + ui.set_width(list_width); ui.set_height(height); list_action = preset_list(app, ui, &names); }); ui.separator(); ui.vertical(|ui| { // Leave room for the two map panes and three separators - let panes = INPUTS_WIDTH + SIDE_MAPS_WIDTH + 8.0 * ui.spacing().item_spacing.x + 6.0; - ui.set_width((ui.available_width() - panes).max(200.0)); + let panes = inputs_width + side_width + 8.0 * ui.spacing().item_spacing.x + SEPARATOR_ALLOWANCE_POINTS; + ui.set_width((ui.available_width() - panes).max(MIN_OUTPUTS_WIDTH_POINTS)); ui.set_height(height); outputs(app, ui); }); - // The panes mark the sources of the output map edited last + // The panes mark the maps the selected template's outputs read let marked = marked_sources(app, &Tokens::get(ui.ctx())); ui.separator(); ui.vertical(|ui| { - ui.set_width(INPUTS_WIDTH); + ui.set_width(inputs_width); ui.set_height(height); input_maps(ui, &marked); }); ui.separator(); ui.vertical(|ui| { - ui.set_width(SIDE_MAPS_WIDTH); + ui.set_width(side_width); ui.set_height(height); mesh_and_converted_maps(ui, height, &marked); }); @@ -338,7 +390,7 @@ pub(crate) fn naming_pattern(ui: &mut Ui) { ui.label(tr("Select the naming pattern used to display the input maps on this page.")); ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); }); - egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { for p in NAMING_PATTERNS { let _ = ui.selectable_label(true, p); } @@ -357,13 +409,14 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti // Copy, "−" and "+" from left to right, without tooltips as in the reference ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON).clicked() { + if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON_POINTS).clicked() { act = Some(ListAction::New); } - if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON)).inner.clicked() { + if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON_POINTS)).inner.clicked() + { act = Some(ListAction::Remove(sel.clone())); } - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON).clicked() { + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { act = Some(ListAction::Duplicate(sel.clone())); } }); @@ -425,7 +478,7 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti /// the accent colour fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT), egui::Sense::click()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT_POINTS), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); let painter = ui.painter(); @@ -433,12 +486,12 @@ fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { painter.rect_filled(rect, tokens.radius, tokens.row_hover); } let font = egui::TextStyle::Body.resolve(ui.style()); - painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); + painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT_POINTS, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); let color = if selected { tokens.accent } else { tokens.text }; let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); - job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT); + job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT_POINTS); let galley = painter.layout_job(job); - let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT, rect.center().y - galley.size().y / 2.0); + let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT_POINTS, rect.center().y - galley.size().y / 2.0); painter.galley(top_left, galley, color); response } @@ -695,7 +748,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { let mut edit = RowEdit::default(); // The selected template in a strip, "Current preset:" in bold - egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN).show(ui, |ui| { + egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); @@ -711,9 +764,9 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(caption(tr("Output maps"))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_enabled_ui(editable, |ui| { - for (label, layout, split) in CREATE.iter().rev() { + for (label, layout, split, file) in CREATE.iter().rev() { if ui.button(tr(label)).clicked() { - edit.action = Some(MapAction::Add(*layout, *split)); + edit.action = Some(MapAction::Add(*layout, *split, file)); } } ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); @@ -729,7 +782,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { split.resize(map_count, false); // Leave room for the footer text and the framed count below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN; + let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN_POINTS; egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { ui.add_enabled_ui(editable, |ui| { for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { @@ -739,7 +792,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { None => tr("Not exported: no source in this texture set").to_string(), }; changed |= output_row(ui, index, map_count, map, row_split, &planned, &mut edit); - ui.add_space(ROW_GAP); + ui.add_space(ROW_GAP_POINTS); } }); }); @@ -748,7 +801,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { // Count only maps that have sources in the current set if let Ok(names) = &preview { let exported = names.iter().flatten().count(); - egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN).show(ui, |ui| { + egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); }); @@ -758,13 +811,12 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } // A drop asks for the source channel from the next frame on; one waiting from before shows now - let mut active = edit.touched.or(app.ui.export.active_map); let mut pending = app.ui.export.pending_drop.take(); if edit.pending.is_some() { pending = edit.pending.take(); ui.ctx().request_repaint(); } else { - changed |= source_channel_popup(ui, &mut pending, &mut preset.maps, &mut active); + changed |= source_channel_popup(ui, &mut pending, &mut preset.maps); } // Where each map came from in the saved template, moved along with the maps @@ -773,11 +825,11 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { origin = (0..map_count).map(Some).collect(); } let acted = match edit.action { - Some(MapAction::Add(layout, split_rgb)) => { - preset.maps.push(new_map(layout)); + Some(MapAction::Add(layout, split_rgb, file)) => { + let file = unique_file(&preset.maps, file); + preset.maps.push(new_map(layout, &file)); origin.push(None); split.push(split_rgb); - active = Some(map_count); true } Some(MapAction::Move { from, to }) if from < map_count && to < map_count && from != to => { @@ -787,7 +839,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { origin.insert(to, map_origin); let map_split = split.remove(from); split.insert(to, map_split); - active = Some(to); true } Some(MapAction::Duplicate(index)) if index < map_count => { @@ -797,7 +848,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { preset.maps.insert(index + 1, copy); origin.insert(index + 1, None); split.insert(index + 1, copy_split); - active = Some(index + 1); } true } @@ -805,7 +855,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { preset.maps.remove(index); origin.remove(index); split.remove(index); - active = None; true } _ => false, @@ -817,7 +866,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } let e = &mut app.ui.export; e.draft_split = split; - e.active_map = active.filter(|index| *index < preset.maps.len()); e.pending_drop = pending; if acted || changed { commit(app, preset, origin); @@ -865,11 +913,17 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; - let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN).show(ui, |ui| { + let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { + // The name field gives way in a narrow window, so the swatches and lists stay in the row + let swatches = swatch_targets(map, *split).len() as f32; + let spacing = ui.spacing().item_spacing.x; + let others = GRIP_WIDTH_POINTS + DOLLAR_BUTTON_WIDTH_POINTS + swatches * (SWATCH_SIZE_POINTS + spacing) + ROW_LISTS_WIDTH_POINTS; + let name_width = (ui.available_width() - others - ROW_GAPS * spacing).clamp(MIN_NAME_FIELD_WIDTH_POINTS, NAME_FIELD_WIDTH_POINTS); + grip(ui, index, count, edit); - let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(NAME_FIELD_WIDTH)).on_hover_ui(|ui| { + let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { ui.label(tr("File name without extension; variables insert names")); ui.label(planned); }); @@ -878,10 +932,10 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: changed |= channel_swatches(ui, index, map, split, edit); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.vertical(|ui| { - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON).clicked() { + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Duplicate(index)); } - if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON).clicked() { + if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Remove(index)); } }); @@ -893,21 +947,15 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: }); }); - // Another row's grip dropped here moves that row to this place - // Check the payload type before taking it, so a map list drop is not lost + // Another row's grip dropped here moves that row here (the type check keeps a map list drop) let row = frame.response; let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); if row_dragged_over { - ui.painter().rect_stroke(row.rect, tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); + drop_highlight(ui, row.rect, &tokens); } - if row_dragged_over - && let Some(from) = row.dnd_release_payload::() - { + if row_dragged_over && let Some(from) = row.dnd_release_payload::() { edit.action = Some(MapAction::Move { from: from.0, to: index }); } - if changed { - edit.touched = Some(index); - } changed } @@ -916,15 +964,18 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { let tokens = Tokens::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH, SWATCH_SIZE), egui::Sense::click_and_drag()); + let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click_and_drag()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; ui.painter().rect_filled(rect, 1.0, color); let response = response.on_hover_cursor(egui::CursorIcon::Grab); response.dnd_set_drag_payload(MapDrag(index)); + // Up and down arrows move the focused grip's map instead of the focus let mut to = None; if response.has_focus() { + let arrows = egui::EventFilter { vertical_arrows: true, ..Default::default() }; + ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, arrows)); if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) { to = index.checked_sub(1); } @@ -945,50 +996,54 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the file name variables, the reference's first, then TextureCraft's own +/// The "$" button: the reference's file name variables, then TextureCraft's own ($channel) fn token_menu(ui: &mut Ui, file: &mut String) -> bool { let mut changed = false; - ui.menu_button("$", |ui| { - let mut add = |ui: &mut Ui, token: &str, what: &str| { - if ui.button(RichText::new(token).monospace()).on_hover_text(what).clicked() { + let menu = ui.menu_button("$", |ui| { + let mut add = |ui: &mut Ui, token: &str| { + if ui.button(RichText::new(token).monospace()).clicked() { file.push_str(token); changed = true; ui.close(); } }; for token in REFERENCE_TOKENS { - match FILE_TOKENS.iter().find(|(ours, _)| *ours == token) { - Some(&(token, what)) => add(ui, token, what), - None => { - ui.add_enabled(false, egui::Button::new(RichText::new(token).monospace())).on_disabled_hover_text(tr(NOT_AVAILABLE)); - } + if FILE_TOKENS.iter().any(|(ours, _)| *ours == token) { + add(ui, token); + } else { + ui.add_enabled(false, egui::Button::new(RichText::new(token).monospace())).on_disabled_hover_text(tr(NOT_AVAILABLE)); } } - for &(token, what) in FILE_TOKENS.iter().filter(|(token, _)| !REFERENCE_TOKENS.contains(token)) { - add(ui, token, what); + for &(token, _) in FILE_TOKENS.iter().filter(|(token, _)| !REFERENCE_TOKENS.contains(token)) { + add(ui, token); } }); + menu.response.on_hover_text(tr("Add expressions in the path that will be replaced during export")); changed } /// The file type menu of an output map ("png˅") fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { let mut changed = false; - ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + let menu = ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { for extension in MAP_FILE_TYPES { let Some(format) = FileFormat::from_extension(extension) else { ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); continue; }; + // A new format starts at its default bit depth, as in the reference if ui.selectable_label(map.format == format, extension).clicked() { - changed |= map.format != format; - map.bit_depth = format.depth(map.bit_depth); - map.format = format; + if map.format != format { + map.bit_depth = format.default_depth(); + map.format = format; + changed = true; + } ui.close(); } } }); + menu.response.on_hover_text(tr("File format")); changed } @@ -997,7 +1052,7 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { let format = map.format; let mut changed = false; let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); - ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + let menu = ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { for (depth, dithering) in crate::export_window::depth_options(format) { let label = crate::export_window::depth_label(Some(format), depth, dithering); if dithering { @@ -1009,21 +1064,40 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); + menu.response.on_hover_text(tr("Bit depth")); changed } -/// Whether R, G and B read one map as one RGB swatch can show it: a color map's R, G and B, or -/// the same gray map or constant in all three -fn rgb_collapsed(map: &MapSpec) -> bool { +/// R, G and B's sources, when the map has them +fn rgb_sources(map: &MapSpec) -> Option<[&SourceRef; 3]> { let get = |dest: Dest| map.channels.iter().find(|(d, _)| *d == dest).map(|(_, s)| s); - let (Some(red), Some(green), Some(blue)) = (get(Dest::R), get(Dest::G), get(Dest::B)) else { return true }; - - let one_map = same_source(red, green) && same_source(green, blue); - let spread = red.components() == 3 && [red, green, blue].into_iter().zip(0u8..).all(|(s, k)| component_of(s) == k); - one_map && (spread || red.components() == 1) + Some([get(Dest::R)?, get(Dest::G)?, get(Dest::B)?]) } -/// The swatches an output map shows: Gray, or RGB (R, G, B when split), then A when it has alpha +/// Whether R, G and B read one map (or one constant) and are inverted alike, so one RGB swatch +/// can stand for them +fn rgb_one_map(map: &MapSpec) -> bool { + let Some([red, green, blue]) = rgb_sources(map) else { return true }; + + let inverted = [Dest::R, Dest::G, Dest::B].map(|dest| map.inverted.contains(&dest)); + same_source(red, green) && same_source(green, blue) && inverted.iter().all(|on| *on == inverted[0]) +} + +/// Whether R, G and B read a colour map's R, G and B in that order +fn rgb_spread(map: &MapSpec) -> bool { + rgb_sources(map).is_some_and(|sources| sources.iter().zip(0u8..).all(|(source, k)| source.components() == 3 && component_of(source) == k)) +} + +/// Whether one RGB swatch shows R, G and B: one map, read as its R, G and B or as one channel in +/// all three +fn rgb_collapsed(map: &MapSpec) -> bool { + let Some(sources) = rgb_sources(map) else { return true }; + + let one_component = sources.iter().all(|source| component_of(source) == component_of(sources[0])); + rgb_one_map(map) && (rgb_spread(map) || one_component) +} + +/// The swatches an output map shows: Gr, or RGB (R, G, B when split), then A when it has alpha fn swatch_targets(map: &MapSpec, split: bool) -> Vec { let layout = Layout::of(map); let mut targets = match layout { @@ -1037,7 +1111,7 @@ fn swatch_targets(map: &MapSpec, split: bool) -> Vec { targets } -/// The label on a swatch +/// The letters on a swatch, as in the reference fn target_label(target: ChannelTarget) -> &'static str { match target { ChannelTarget::Rgb => "RGB", @@ -1045,7 +1119,7 @@ fn target_label(target: ChannelTarget) -> &'static str { ChannelTarget::One(Dest::G) => "G", ChannelTarget::One(Dest::B) => "B", ChannelTarget::One(Dest::A) => "A", - ChannelTarget::One(Dest::L) => tr("Gray"), + ChannelTarget::One(Dest::L) => "Gr", } } @@ -1055,24 +1129,71 @@ fn source_of(map: &MapSpec, target: ChannelTarget) -> Option<&SourceRef> { map.channels.iter().find(|(d, _)| d == dest).map(|(_, s)| s) } -/// The source channel choices of "From ": (label, the component read; None: not available yet) -fn source_choices(source: &SourceRef) -> Vec<(&'static str, Option)> { - if source.components() == 3 { - vec![(n_("Gray Channel"), None), (n_("R Channel"), Some(0)), (n_("G Channel"), Some(1)), (n_("B Channel"), Some(2)), (n_("A Channel"), None)] - } else { - vec![(n_("Gray Channel"), Some(0)), (n_("A Channel"), None)] +/// The choices of "From " in the reference order: "RGB Channels" only for a colour map on +/// the RGB swatch; None marks a choice TextureCraft cannot read yet (a map's gray or alpha) +fn source_choices(source: &SourceRef, target: ChannelTarget) -> Vec<(&'static str, Option)> { + if source.components() != 3 { + return vec![(n_("Gray Channel"), Some(SourcePick::Component(0))), (n_("A Channel"), None)]; + } + + let mut choices = Vec::new(); + if target == ChannelTarget::Rgb { + choices.push((n_("RGB Channels"), Some(SourcePick::AllRgb))); + } + choices.extend([ + (n_("Gray Channel"), None), + (n_("R Channel"), Some(SourcePick::Component(0))), + (n_("G Channel"), Some(SourcePick::Component(1))), + (n_("B Channel"), Some(SourcePick::Component(2))), + (n_("A Channel"), None), + ]); + choices +} + +/// Fill the swatch `target` from `source` as `pick` says +fn apply_pick(map: &mut MapSpec, target: ChannelTarget, source: &SourceRef, pick: SourcePick) { + for (dest, channel_source) in &mut map.channels { + if !target.dests().contains(dest) { + continue; + } + + let component = match pick { + SourcePick::AllRgb => slot_component(*dest), + SourcePick::Component(component) => component, + }; + *channel_source = with_component(source, component); } } -/// A source as a swatch names it: the map, and for one channel of a color map that channel -fn source_name(source: &SourceRef, target: ChannelTarget) -> Option { - let map = tr(map_lists::name_of(source)?); - let picked = source_choices(source).into_iter().find(|(_, component)| *component == Some(component_of(source))); - match picked { - Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => { - Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])) +/// The channel of the source a swatch reads, as the reference's swatch tooltip names it +fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> &'static str { + if source.components() != 3 { + return n_("Grayscale"); + } + + if target == ChannelTarget::Rgb && rgb_spread(map) { + return "RGB"; + } + + match component_of(source) { + 0 => n_("Red"), + 1 => n_("Green"), + _ => n_("Blue"), + } +} + +/// A swatch's tooltip in the reference's words: "Default black" or "Default white" when empty, +/// else " ()"; another constant (TextureCraft's own) gives its value +fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> String { + let alpha = target == ChannelTarget::One(Dest::A); + match source { + SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Default white").to_string(), + SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Default black").to_string(), + SourceRef::Constant(value) => trf("Constant {value}", &[("value", &format!("{value:.2}"))]), + _ => { + let name = map_lists::name_of(source).map_or_else(String::new, |name| tr(name).to_string()); + trf("{map} ({channel})", &[("map", &name), ("channel", &tr(read_channel_name(map, source, target)))]) } - _ => Some(map.to_string()), } } @@ -1091,19 +1212,19 @@ fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) } -/// The bars under a swatch's label: R, G and B for a color map on the RGB swatch, else the one -/// channel read -fn swatch_bars(source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { +/// The bars under a swatch's letters: red, green and blue for a colour map's RGB, else the one +/// channel read (white for gray) +fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { match source { SourceRef::Constant(_) => Vec::new(), - _ if source.components() == 3 && target == ChannelTarget::Rgb => COMPONENT_COLORS.to_vec(), + _ if source.components() == 3 && target == ChannelTarget::Rgb && rgb_spread(map) => COMPONENT_COLORS.to_vec(), _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), _ => vec![tokens.text_strong], } } -/// An output map's channel swatches: drop targets for the map lists; a click opens Clear channel -/// and Split/Collapse RGB, a right click Invert +/// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel +/// (and Split/Collapse RGB on R, G, B), a right click TextureCraft's own tools. fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; @@ -1112,25 +1233,27 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo let Some(source) = source_of(map, target).cloned() else { continue }; let label = target_label(target); - let name = match source_name(&source, target) { - Some(source) => trf("{channel}: {map}", &[("channel", &label), ("map", &source)]), - None => label.to_string(), - }; - let response = swatch(ui, label, &name, source_color(&source, &tokens), &swatch_bars(&source, target, &tokens)).on_hover_text(&name); + let inverted = target.dests().iter().all(|dest| map.inverted.contains(dest)); + let tooltip = swatch_tooltip(map, &source, target); + let mut name = trf("{channel}: {tooltip}", &[("channel", &label), ("tooltip", &tooltip)]); + if inverted { + name = trf("{swatch}, inverted", &[("swatch", &name)]); + } + let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; + let response = swatch(ui, label, &name, &look).on_hover_ui(|ui| { + ui.label(&tooltip); + if inverted { + ui.label(tr("Inverted")); + } + }); // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); if map_dragged_over { - ui.painter().rect_stroke(response.rect.expand(2.0), tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); + drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS), &tokens); } if map_dragged_over && let Some(input) = response.dnd_release_payload::() { - edit.touched = Some(index); - if target == ChannelTarget::Rgb && input.components() == 3 { - drop_input(map, Dest::R, &input); - changed = true; - } else { - edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); - } + edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); } let rgb = matches!(target, ChannelTarget::Rgb | ChannelTarget::One(Dest::R | Dest::G | Dest::B)); @@ -1139,66 +1262,122 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo if ui.button(tr("Clear channel")).clicked() { clear_channel(map, target); changed = true; - edit.touched = Some(index); } - if rgb && ui.button(tr("Split/Collapse RGB")).clicked() { - changed |= split_or_collapse(map, split, shows_split); - edit.touched = Some(index); - } - }); - - // Not in the reference's menu: inverting stays on the right click - response.context_menu(|ui| { - let on = target.dests().iter().all(|dest| map.inverted.contains(dest)); - if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { - map.inverted.retain(|dest| !target.dests().contains(dest)); - if !on { - map.inverted.extend_from_slice(target.dests()); + if rgb { + // Collapsing would drop maps that R, G and B read differently + let mut checked = shows_split; + let can_toggle = !shows_split || rgb_one_map(map); + let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Split/Collapse RGB"))); + let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to collapse")); + if item.changed() { + changed |= split_or_collapse(map, split, shows_split); } - changed = true; - edit.touched = Some(index); - ui.close(); } }); + response.context_menu(|ui| changed |= swatch_extras_menu(ui, map, target)); } changed } +/// TextureCraft's own swatch tools on the right click (the reference has none there): invert, +/// constants and the output map's channel layout. True when the map changed. +fn swatch_extras_menu(ui: &mut Ui, map: &mut MapSpec, target: ChannelTarget) -> bool { + let mut changed = false; + let on = target.dests().iter().all(|dest| map.inverted.contains(dest)); + if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { + map.inverted.retain(|dest| !target.dests().contains(dest)); + if !on { + map.inverted.extend_from_slice(target.dests()); + } + changed = true; + ui.close(); + } + ui.separator(); + for (label, value) in CONSTANTS { + if ui.button(tr(label)).clicked() { + set_constant(map, target, value); + changed = true; + ui.close(); + } + } + if let Some(SourceRef::Constant(mut value)) = source_of(map, target).cloned() { + let constant = egui::DragValue::new(&mut value).range(0.0..=1.0).speed(CONSTANT_DRAG_SPEED).fixed_decimals(2); + if ui.add(constant).changed() { + set_constant(map, target, value); + changed = true; + } + } + ui.separator(); + ui.menu_button(tr("Layout"), |ui| { + let current = Layout::of(map); + for layout in Layout::ALL { + if ui.selectable_label(layout == current, tr(layout.label())).clicked() && layout != current { + set_layout(map, layout); + changed = true; + ui.close(); + } + } + }); + changed +} + +/// The swatch's channels write the constant `value` +fn set_constant(map: &mut MapSpec, target: ChannelTarget, value: f32) { + for (dest, source) in &mut map.channels { + if target.dests().contains(dest) { + *source = SourceRef::Constant(value); + } + } +} + +/// The accent frame around a drop target under a dragged map or row +fn drop_highlight(ui: &Ui, rect: egui::Rect, tokens: &Tokens) { + ui.painter().rect_stroke(rect, tokens.radius, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, tokens.accent), egui::StrokeKind::Outside); +} + /// One channel swatch: `label` on top, filled with the source's colour, bars below for the -/// channels it reads -fn swatch(ui: &mut Ui, label: &str, name: &str, fill: Option, bars: &[Color32]) -> egui::Response { +/// channels it reads, a corner mark when inverted +fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Response { let tokens = Tokens::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE, SWATCH_SIZE), egui::Sense::click()); + let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); let painter = ui.painter(); let border = if response.hovered() { tokens.accent } else { tokens.button_border }; - painter.rect(rect, tokens.radius, fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); - let bar_width = SWATCH_BAR_WIDTH / bars.len().max(1) as f32; - let left = rect.center().x - SWATCH_BAR_WIDTH / 2.0; - for (k, color) in bars.iter().enumerate() { - let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM); - painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT)), 0.0, *color); + painter.rect(rect, tokens.radius, look.fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE_POINTS); + painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP_POINTS), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); + let bar_width = SWATCH_BAR_WIDTH_POINTS / look.bars.len().max(1) as f32; + let left = rect.center().x - SWATCH_BAR_WIDTH_POINTS / 2.0; + for (k, color) in look.bars.iter().enumerate() { + let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM_POINTS); + painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT_POINTS)), 0.0, *color); + } + if look.inverted { + let corner = rect.right_top(); + let mark = vec![corner, corner - vec2(INVERTED_MARK_POINTS, 0.0), corner + vec2(0.0, INVERTED_MARK_POINTS)]; + painter.add(egui::Shape::convex_polygon(mark, tokens.text_strong, egui::Stroke::NONE)); } response } -/// Clear channel: the swatch's channels write black, or opaque alpha +/// Clear channel: the swatch is empty again ("Default black", "Default white" for alpha), not +/// inverted fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { for (dest, source) in &mut map.channels { if target.dests().contains(dest) { *source = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); } } + map.inverted.retain(|dest| !target.dests().contains(dest)); } -/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones collapse into one RGB -/// swatch reading R's map. True when the map changed. +/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones that read one map collapse +/// into one RGB swatch reading that map's R, G and B. R, G and B reading different maps stay split, +/// so no map is dropped. True when the map changed. fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> bool { - if !shows_split { + if !shows_split || !rgb_one_map(map) { *split = true; return false; } @@ -1221,9 +1400,9 @@ fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> true } -/// "From ": which channel of the dropped map the output channel reads. True when the map -/// changed. -fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec], active: &mut Option) -> bool { +/// "From ": which channel of the dropped map the swatch reads; Escape or a click elsewhere +/// assigns nothing. True when the map changed. +fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec]) -> bool { let Some(waiting) = pending.clone() else { return false }; let Some(map) = maps.get_mut(waiting.map) else { *pending = None; @@ -1232,7 +1411,7 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ let name = map_lists::name_of(&waiting.source).map_or_else(String::new, |name| tr(name).to_string()); let mut picked = None; - let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(waiting.position), ui.layer_id()) + let shown = egui::Popup::new(egui::Id::unique("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(waiting.position), ui.layer_id()) .kind(egui::PopupKind::Menu) .layout(egui::Layout::top_down_justified(egui::Align::Min)) .style(egui::containers::menu::menu_style) @@ -1240,11 +1419,11 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); - for (label, component) in source_choices(&waiting.source) { - match component { - Some(component) => { + for (label, pick) in source_choices(&waiting.source, waiting.target) { + match pick { + Some(pick) => { if ui.button(tr(label)).clicked() { - picked = Some(component); + picked = Some(pick); } } None => { @@ -1253,27 +1432,23 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } } }); - if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + // The app can consume Escape before the popup sees it, so read the raw event + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if picked.is_some() || escaped || shown.is_none_or(|menu| menu.response.should_close()) { *pending = None; } - let Some(component) = picked else { return false }; + let Some(pick) = picked else { return false }; - let source = with_component(&waiting.source, component); - for (dest, channel_source) in &mut map.channels { - if waiting.target.dests().contains(dest) { - *channel_source = source.clone(); - } - } - *active = Some(waiting.map); + apply_pick(map, waiting.target, &waiting.source, pick); true } -/// The sources of the output map edited last, with their colours, for the panes' markers +/// The maps the selected template's outputs read, with their colours, for the panes' markers fn marked_sources(app: &TextureCraftApp, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { - let Some(index) = app.ui.export.active_map else { return Vec::new() }; - let Some(map) = app.ui.export.draft.as_ref().and_then(|draft| draft.maps.get(index)) else { return Vec::new() }; + let Some(preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { return Vec::new() }; - map.channels.iter().filter_map(|(_, source)| source_color(source, tokens).map(|color| (source.clone(), color))).collect() + let sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); + sources.filter_map(|source| source_color(source, tokens).map(|color| (source.clone(), color))).collect() } /// The Input maps pane: the input maps in their groups @@ -1315,17 +1490,27 @@ fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Co let tokens = Tokens::get(ui.ctx()); let available = source.is_some(); let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT), sense); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT_POINTS), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); let painter = ui.painter(); - let row = rect.shrink2(vec2(0.0, ENTRY_GAP / 2.0)); + let row = rect.shrink2(vec2(0.0, ENTRY_GAP_POINTS / 2.0)); painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); if let Some(color) = marker { - painter.rect_filled(egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT, 0.0), egui::Vec2::splat(MARKER_SIZE)), 1.0, color); + painter.rect_filled( + egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT_POINTS, 0.0), egui::Vec2::splat(MARKER_SIZE_POINTS)), + 1.0, + color, + ); } let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; - painter.text(row.left_center() + vec2(ENTRY_TEXT_INDENT, 0.0), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(ENTRY_TEXT_SIZE), color); + painter.text( + row.left_center() + vec2(ENTRY_TEXT_INDENT_POINTS, 0.0), + egui::Align2::LEFT_CENTER, + name, + egui::FontId::proportional(ENTRY_TEXT_SIZE_POINTS), + color, + ); let Some(source) = source else { response.on_hover_text(tr(NOT_AVAILABLE)); return; @@ -1337,7 +1522,7 @@ fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Co && let Some(at) = response.interact_pointer_pos() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - let dragged = egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)); + let dragged = egui::Area::new(egui::Id::unique(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)); dragged.show(ui.ctx(), |ui| chip(ui, name, true)); } } @@ -1352,7 +1537,7 @@ mod tests { #[test] fn layouts_keep_sources_and_drops_fill_rgb() { - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); drop_input(&mut map, Dest::G, &ch(Channel::BaseColor, 0)); assert_eq!(map.channels, vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::BaseColor, 1)), (Dest::B, ch(Channel::BaseColor, 2))]); drop_input(&mut map, Dest::B, &ch(Channel::Metallic, 0)); @@ -1365,7 +1550,7 @@ mod tests { set_layout(&mut map, Layout::Rgb); assert_eq!(map.channels.get(1), Some(&(Dest::G, ch(Channel::BaseColor, 1))), "gray to RGB spreads a color source"); for l in [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha] { - let m = new_map(l); + let m = new_map(l, "t"); assert_eq!(Layout::of(&m), l); ExportPreset { name: "t".into(), maps: vec![m] }.validate().unwrap(); } @@ -1375,7 +1560,7 @@ mod tests { #[test] fn inversion_follows_its_source_through_layouts_and_drops() { - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); map.inverted = vec![Dest::R]; set_layout(&mut map, Layout::Gray); assert_eq!(map.inverted, vec![Dest::L], "the colour source keeps its inversion on L"); @@ -1386,7 +1571,7 @@ mod tests { map.inverted = vec![Dest::G]; set_layout(&mut map, Layout::GrayAlpha); assert!(map.inverted.is_empty(), "channels that leave take their inversion with them"); - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); map.inverted = vec![Dest::B]; drop_input(&mut map, Dest::B, &ch(Channel::Metallic, 0)); assert_eq!(map.inverted, vec![Dest::B], "a dropped map keeps the channel's toggle, like picking from the list"); @@ -1395,40 +1580,83 @@ mod tests { #[test] fn split_and_collapse_keep_r_g_b_on_one_or_three_swatches() { - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); let mut split = false; assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb], "an empty RGB map shows one swatch"); assert!(!split_or_collapse(&mut map, &mut split, false), "splitting changes only the view"); assert_eq!(swatch_targets(&map, split).len(), 3); - map.channels = vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.0))]; + map.channels = vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::BaseColor, 0)), (Dest::B, ch(Channel::BaseColor, 1))]; assert!(split_or_collapse(&mut map, &mut split, true)); assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb]); - assert_eq!(map.channels.get(2), Some(&(Dest::B, ch(Channel::BaseColor, 2))), "collapsing spreads R's color map over R, G and B"); - - map.channels = vec![(Dest::R, ch(Channel::Roughness, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.5))]; - assert_eq!(swatch_targets(&map, false).len(), 3, "different maps in R, G and B show split even when not asked to"); + assert_eq!(map.channels.get(2), Some(&(Dest::B, ch(Channel::BaseColor, 2))), "collapsing reads the map's R, G and B"); } #[test] - fn clear_channel_writes_black_or_opaque_alpha() { - let mut map = new_map(Layout::Rgba); + fn r_g_b_reading_different_maps_or_inverted_apart_stay_split() { + let differing = vec![(Dest::R, ch(Channel::Roughness, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.5))]; + let mut map = new_map(Layout::Rgb, "t"); + map.channels = differing.clone(); + let mut split = true; + + assert!(!split_or_collapse(&mut map, &mut split, true), "collapsing would drop maps"); + + assert_eq!(map.channels, differing); + assert_eq!(swatch_targets(&map, split).len(), 3); + let mut color = new_map(Layout::Rgb, "t"); + drop_input(&mut color, Dest::R, &ch(Channel::BaseColor, 0)); + color.inverted = vec![Dest::G]; + assert_eq!(swatch_targets(&color, false).len(), 3, "one map inverted in G only shows R, G and B apart"); + } + + #[test] + fn clear_channel_empties_the_swatch_and_its_inversion() { + let mut map = new_map(Layout::Rgba, "t"); drop_input(&mut map, Dest::R, &ch(Channel::BaseColor, 0)); drop_input(&mut map, Dest::A, &ch(Channel::Opacity, 0)); + map.inverted = vec![Dest::R, Dest::G, Dest::B, Dest::A]; clear_channel(&mut map, ChannelTarget::Rgb); clear_channel(&mut map, ChannelTarget::One(Dest::A)); let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); assert_eq!(map.channels, cleared); + assert!(map.inverted.is_empty(), "a cleared channel writes its default, not its inverse"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Default black"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Default white"); } #[test] - fn a_gray_map_offers_its_gray_channel_and_a_color_map_its_r_g_b() { - let offered = |source: &SourceRef| source_choices(source).into_iter().filter_map(|(label, component)| component.map(|_| label)).collect::>(); + fn the_from_popup_offers_the_reference_choices() { + let offered = |source: &SourceRef, target| source_choices(source, target).into_iter().map(|(label, pick)| (label, pick.is_some())).collect::>(); - assert_eq!(offered(&ch(Channel::Metallic, 0)), ["Gray Channel"]); - assert_eq!(offered(&ch(Channel::BaseColor, 0)), ["R Channel", "G Channel", "B Channel"]); + assert_eq!(offered(&ch(Channel::Metallic, 0), ChannelTarget::Rgb), [("Gray Channel", true), ("A Channel", false)]); + let color_on_gray = [("Gray Channel", false), ("R Channel", true), ("G Channel", true), ("B Channel", true), ("A Channel", false)]; + assert_eq!(offered(&ch(Channel::BaseColor, 0), ChannelTarget::One(Dest::L)), color_on_gray); + let color_on_rgb = offered(&ch(Channel::BaseColor, 0), ChannelTarget::Rgb); + assert_eq!(color_on_rgb.first(), Some(&("RGB Channels", true)), "only the RGB swatch offers RGB Channels"); + assert_eq!(color_on_rgb.get(1..), Some(color_on_gray.as_slice())); + } + + #[test] + fn rgb_channels_fill_r_g_b_and_one_channel_fills_every_swatch_channel() { + let mut map = new_map(Layout::Rgb, "t"); + + apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::AllRgb); + assert!(rgb_spread(&map)); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (RGB)"); + + apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::Component(0)); + assert_eq!(swatch_targets(&map, false), vec![ChannelTarget::Rgb], "R of one map in R, G and B stays one swatch"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (Red)"); + } + + #[test] + fn new_rows_take_the_reference_names_with_a_number_when_taken() { + let maps = vec![new_map(Layout::Rgb, "RGB"), new_map(Layout::Rgb, "RGB_1")]; + + assert_eq!(unique_file(&maps, "Grayscale"), "Grayscale"); + assert_eq!(unique_file(&maps, "RGB"), "RGB_2"); } } diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index 1595c440..afe9e2aa 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -27,8 +27,15 @@ fn mesh(map: BakedMap) -> Option { Some(SourceRef::Baked { map, component: 0 }) } -/// Input maps in groups, as the reference lists them up to Fuzz/Sheen; the groups after it are -/// cut off in the reference screenshots and use the OpenPBR names of the channels left over. +/// The reference's user channels, listed greyed: TextureCraft has no user channels yet +const USER_CHANNELS: [&str; 32] = [ + "User0", "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10", "User11", "User12", "User13", "User14", "User15", + "User16", "User17", "User18", "User19", "User20", "User21", "User22", "User23", "User24", "User25", "User26", "User27", "User28", "User29", "User30", + "User31", +]; + +/// Input maps in the reference's groups and order (naming pattern OpenPBR); entries without a +/// TextureCraft channel are listed greyed. pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ ( @@ -36,7 +43,7 @@ pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ (n_("Base weight"), None), (n_("Base color"), channel(Channel::BaseColor)), - (n_("Base metalness"), channel(Channel::Metallic)), + (n_("Metallic"), channel(Channel::Metallic)), (n_("Base diffuse roughness"), None), ], ), @@ -44,22 +51,19 @@ pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { n_("Specular"), vec![ (n_("Specular weight"), None), - (n_("Specular color"), None), - (n_("Specular roughness"), channel(Channel::Roughness)), + (n_("Specular edge color"), None), + (n_("Roughness"), channel(Channel::Roughness)), (n_("Specular level"), channel(Channel::SpecularLevel)), - (n_("Specular anisotropy"), channel(Channel::AnisotropyLevel)), + (n_("Anisotropy level"), channel(Channel::AnisotropyLevel)), (n_("Anisotropy angle"), channel(Channel::AnisotropyAngle)), ], ), - (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Transmission color"), None)]), - ( - n_("Subsurface"), - vec![(n_("Subsurface weight"), channel(Channel::ScatterWeight)), (n_("Subsurface color"), None), (n_("Subsurface radius scale"), None)], - ), + (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Absorption color"), None)]), + (n_("Subsurface"), vec![(n_("Translucency"), None), (n_("Scattering color"), None), (n_("Scattering"), channel(Channel::ScatterWeight))]), ( n_("Coat"), vec![ - (n_("Coat weight"), channel(Channel::CoatWeight)), + (n_("Coat opacity"), channel(Channel::CoatWeight)), (n_("Coat color"), None), (n_("Coat roughness"), channel(Channel::CoatRoughness)), (n_("Coat anisotropy"), None), @@ -71,22 +75,37 @@ pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { ( n_("Fuzz/Sheen"), vec![ - (n_("Fuzz weight"), channel(Channel::SheenWeight)), - (n_("Fuzz color"), channel(Channel::SheenColor)), - (n_("Fuzz roughness"), channel(Channel::SheenRoughness)), + (n_("Sheen opacity"), channel(Channel::SheenWeight)), + (n_("Sheen color"), channel(Channel::SheenColor)), + (n_("Sheen roughness"), channel(Channel::SheenRoughness)), ], ), - (n_("Emission"), vec![(n_("Emission color"), channel(Channel::Emissive))]), - (n_("Geometry"), vec![(n_("Geometry opacity"), channel(Channel::Opacity)), (n_("Geometry normal"), channel(Channel::Normal))]), + (n_("Emission"), vec![(n_("Emissive"), channel(Channel::Emissive))]), + (n_("Thin-film"), vec![(n_("Thin-film weight"), None)]), ( - n_("Other"), + n_("Geometry"), vec![ + (n_("Opacity"), channel(Channel::Opacity)), (n_("Height"), channel(Channel::Height)), + (n_("Normal"), channel(Channel::Normal)), + (n_("Tangent"), None), (n_("Ambient occlusion"), channel(Channel::AmbientOcclusion)), - (n_("Specular"), channel(Channel::Specular)), - (n_("Glossiness"), channel(Channel::Glossiness)), ], ), + ( + n_("Miscellaneous"), + vec![ + (n_("Blending mask"), None), + (n_("Diffuse"), None), + (n_("Displacement"), None), + (n_("Glossiness"), channel(Channel::Glossiness)), + ("Ior", None), + (n_("Reflection"), None), + (n_("Specular"), channel(Channel::Specular)), + (n_("Transmissive"), None), + ], + ), + (n_("User Channels"), USER_CHANNELS.iter().map(|name| (*name, None)).collect()), ] }); @@ -106,7 +125,7 @@ pub static MESH_MAPS: LazyLock> = LazyLock::new(|| { ] }); -/// Converted maps in the reference order, then the ones only TextureCraft has (templates use them). +/// Converted maps in the reference order, then the ones only TextureCraft has (built-in templates use them). pub static CONVERTED_MAPS: LazyLock> = LazyLock::new(|| { vec![ ("1/ior", None), diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs index e813e574..6568dac9 100644 --- a/crates/ui-egui/src/export_templates/row_edit.rs +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -6,6 +6,4 @@ pub(super) struct RowEdit { pub(super) action: Option, /// A map dropped on a channel swatch, to ask which of its channels to use. pub(super) pending: Option, - /// The row edited last. - pub(super) touched: Option, } diff --git a/crates/ui-egui/src/export_templates/source_pick.rs b/crates/ui-egui/src/export_templates/source_pick.rs new file mode 100644 index 00000000..89dc4769 --- /dev/null +++ b/crates/ui-egui/src/export_templates/source_pick.rs @@ -0,0 +1,8 @@ +/// What a "From " choice reads from the dropped map. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SourcePick { + /// "RGB Channels": the map's R, G and B into the swatch's R, G and B. + AllRgb, + /// One component of the map in every channel of the swatch. + Component(u8), +} diff --git a/crates/ui-egui/src/export_templates/swatch_look.rs b/crates/ui-egui/src/export_templates/swatch_look.rs new file mode 100644 index 00000000..99d81b19 --- /dev/null +++ b/crates/ui-egui/src/export_templates/swatch_look.rs @@ -0,0 +1,10 @@ +use egui::Color32; + +/// How a channel swatch is drawn. +pub(super) struct SwatchLook { + /// The source map's colour (None: empty or a constant). + pub(super) fill: Option, + /// One bar per channel of the source the swatch reads. + pub(super) bars: Vec, + pub(super) inverted: bool, +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 89cb751a..5acd63cf 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -391,9 +391,9 @@ pub struct ExportUi { /// channel swatches (R+G+B) instead of one RGB swatch. #[serde(skip)] pub draft_split: Vec, - /// Output templates tab: the output map edited last; the map lists mark its sources. - #[serde(skip)] - pub active_map: Option, + /// LIST OF EXPORTS: the console's width, set by dragging the strip at its left edge. + #[serde(skip, default = "default_console_width")] + pub console_width: f32, /// Output templates tab: a map dropped on an output channel, waiting for the source channel /// ("From "). #[serde(skip)] @@ -444,7 +444,7 @@ impl Default for ExportUi { draft_maps: Vec::new(), draft_base: None, draft_split: Vec::new(), - active_map: None, + console_width: default_console_width(), pending_drop: None, renaming: None, rename_key: false, @@ -457,6 +457,11 @@ impl Default for ExportUi { } } +/// The LIST OF EXPORTS console's width when the window opens, as in the reference +fn default_console_width() -> f32 { + 300.0 +} + fn default_export_dir() -> String { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 46cee48f..5210742a 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -139,14 +139,13 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { h.run_steps(30); assert!(h.query_by_label(&dir.join(&file).display().to_string()).is_some()); - // The console's toggle hides it - let toggle = h.get_by_label(egui_phosphor::regular::CARET_DOUBLE_RIGHT).rect().center(); - h.hover_at(toggle); - h.run_steps(30); - assert!(h.query_by_label("Hide Console").is_some()); - click(&mut h, egui_phosphor::regular::CARET_DOUBLE_RIGHT); - h.run_steps(2); + // The strip at the console's edge hides it, then shows it again + h.get_by_role_and_label(egui::Role::Button, "Hide Console").click(); + h.run_steps(4); assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none()); + h.get_by_role_and_label(egui::Role::Button, "Show Console").click(); + h.run_steps(4); + assert!(!h.state().ui.export.console_hidden); } #[test] diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 53c5daa1..2b888752 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -68,8 +68,7 @@ fn hover_name_field(h: &mut Harness<'_, TextureCraftApp>, index: usize) { /// The last button labelled `label` in the window (the newest output map's swatch) fn last_window_button<'h>(h: &'h Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'h> { h.get_all_by_role(egui::Role::Button) - .filter(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) - .last() + .rfind(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) .unwrap_or_else(|| panic!("no {label} button")) } @@ -191,9 +190,12 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show"); + let plan = h.state_mut().run("export.plan", json!({"preset": "Two", "ts": ts})).unwrap(); for index in 0..2 { + let file = plan.as_array().unwrap().iter().find(|f| f["map"] == index).unwrap()["file"].as_str().unwrap().to_string(); hover_name_field(&mut h, index); - assert!(h.query_all_by_label_contains(egui_phosphor::regular::ARROW_RIGHT).next().is_some(), "map {index} shows its file"); + let planned = format!("{} {file}", egui_phosphor::regular::ARROW_RIGHT); + assert!(h.query_all_by_label(&planned).next().is_some(), "map {index} shows its own file {file}"); } } @@ -346,11 +348,8 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { assert!(h.query_by_label_contains("textures selected for export").is_none()); for greyed in ["Save settings", "Export"] { // The rail at the right edge has an Export button of its own - let button = h - .get_all_by_role(egui::Role::Button) - .filter(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)) - .last() - .unwrap(); + let button = + h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)).unwrap(); assert!(button.accesskit_node().is_disabled(), "{greyed}"); } assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); @@ -382,23 +381,24 @@ fn the_map_lists_stand_in_three_panes_with_the_reference_names() { let h = harness(&library); let input = h.get_by_label("Input maps").rect(); - let mesh = h.get_by_label("Mesh maps").rect(); + // A built-in template is called "Mesh maps" too: the pane's title comes after the Presets list + let mesh = h.get_all_by_label("Mesh maps").last().unwrap().rect(); let converted = h.get_by_label("Converted maps").rect(); assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); - for group in ["Base", "Transmission", "Subsurface", "Coat", "Fuzz/Sheen"] { + for group in ["Transmission", "Subsurface", "Fuzz/Sheen", "Thin-film", "Miscellaneous", "User Channels"] { assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); } - for name in ["Base metalness", "Specular roughness", "Coat normal", "Fuzz weight", "World space normal", "Bent normals", "Normal DirectX", "f0"] { + for name in ["Specular level", "Sheen opacity", "Coat normal", "Emissive", "World space normal", "Bent normals", "Normal DirectX", "f0"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); } - for name in ["Base weight", "Coat tangent", "1/ior", "Glossiness²", "2D View"] { + for name in ["Base weight", "Coat tangent", "Thin-film weight", "User31", "1/ior", "Glossiness²", "2D View"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); } - for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal"] { + for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal", "Emission color", "Other"] { assert!(h.query_by_label(gone).is_none(), "{gone}"); } } @@ -410,10 +410,11 @@ fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { click(&mut h, "R+G+B+A"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let green = last_window_button(&h, "G").rect().center(); + let green = last_window_button(&h, "G: Default black").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, green); assert!(h.query_by_label("From Base color").is_some(), "the popup names the dropped map"); + assert!(h.query_by_label("RGB Channels").is_none(), "only the RGB swatch offers RGB Channels"); for choice in ["R Channel", "G Channel", "B Channel"] { assert!(!h.get_by_label(choice).accesskit_node().is_disabled(), "{choice}"); } @@ -426,23 +427,72 @@ fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); assert!(map.channels.contains(&(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 2 })), "{:?}", map.channels); assert!(h.query_by_label("From Base color").is_none(), "the popup closed"); - assert!(h.query_all_by_label("G: Base color (B Channel)").next().is_some(), "the swatch names its map"); - assert_eq!(h.state().ui.export.active_map, Some(last), "the lists mark this map's sources"); + assert!(h.query_all_by_label("G: Base color (Blue)").next().is_some(), "the swatch names its map and channel"); } #[test] -fn a_gray_map_dropped_on_a_channel_offers_its_gray_channel() { - let library = TemplateLibrary::new("drop-gray"); +fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { + let library = TemplateLibrary::new("drop-rgb"); let mut h = harness(&library); - click(&mut h, "R+G+B+A"); + click(&mut h, "RGB+A"); + let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let alpha = last_window_button(&h, "A").rect().center(); - drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, alpha); + let rgb = last_window_button(&h, "RGB: Default black").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, rgb); + h.get_by_label("RGB Channels").click(); + h.run_steps(4); - assert!(h.query_by_label("From Base metalness").is_some()); + let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); + let spread: Vec<_> = (0..3).map(|component| SourceRef::Channel { channel: Channel::BaseColor, component }).collect(); + assert_eq!(map.channels.iter().take(3).map(|(_, source)| source.clone()).collect::>(), spread); + assert!(h.query_all_by_label("RGB: Base color (RGB)").next().is_some()); +} + +#[test] +fn escape_closes_the_from_popup_without_assigning() { + let library = TemplateLibrary::new("drop-escape"); + let mut h = harness(&library); + click(&mut h, "Gray"); + let before = h.state().session.export_preset("Mine").unwrap(); + + let gray = last_window_button(&h, "Gr: Default black").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, gray); + assert!(h.query_by_label("From Metallic").is_some()); assert!(!h.get_by_label("Gray Channel").accesskit_node().is_disabled()); assert!(h.get_by_label("A Channel").accesskit_node().is_disabled()); assert!(h.query_by_label("R Channel").is_none(), "a gray map has no R, G or B"); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.query_by_label("From Metallic").is_none(), "Escape closes the popup"); + assert!(h.state().ui.export.pending_drop.is_none()); + assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); +} + +#[test] +fn dragging_a_grip_onto_another_row_moves_that_map_there() { + let library = TemplateLibrary::new("grip-drag"); + let mut h = harness(&library); + let files = |h: &Harness<'_, TextureCraftApp>| h.state().session.export_preset("Mine").unwrap().maps.iter().map(|m| m.file.clone()).collect::>(); + let before = files(&h); + + let from = h.get_all_by_label("Reorder").last().unwrap().rect().center(); + let to = h.get_all_by_label("Reorder").next().unwrap().rect().center(); + h.hover_at(from); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(2); + for step in 1..=4 { + h.hover_at(from + (to - from) * (step as f32 / 4.0)); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(4); + + let mut expected = before.clone(); + let moved = expected.pop().unwrap(); + expected.insert(0, moved); + assert_eq!(files(&h), expected, "the last map is first now"); } #[test] @@ -451,16 +501,16 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv let mut h = harness(&library); click(&mut h, "RGB"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; + assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].file, "RGB", "the reference's name for a new RGB row"); - // The RGB swatch is the last "RGB" button, after the Create button of that name - last_window_button(&h, "RGB").click(); + last_window_button(&h, "RGB: Default black").click(); h.run_steps(4); assert!(h.query_by_label("Clear channel").is_some()); h.get_by_label("Split/Collapse RGB").click(); h.run_steps(4); assert_eq!(h.state().ui.export.draft_split.get(last), Some(&true), "R, G and B show apart"); - let green = last_window_button(&h, "G"); + let green = last_window_button(&h, "G: Default black"); let at = green.rect().center(); green.click_secondary(); h.run_steps(4); @@ -470,4 +520,35 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv invert.click(); h.run_steps(4); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); + assert!(h.query_all_by_label("G: Default black, inverted").next().is_some(), "the swatch says it is inverted"); +} + +#[test] +fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let library = TemplateLibrary::new("small-screen"); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h.state_mut().session.load_export_presets(library.0.clone()); + let base = texturecraft_engine::formats::builtin_preset("Unreal Engine (Packed)").unwrap(); + h.state_mut().run("export.preset.save", json!({ "preset": texturecraft_engine::formats::ExportPreset { name: "Mine".into(), ..base } })).unwrap(); + let ui = &mut h.state_mut().ui; + ui.windows.export = true; + ui.export.tab = 1; + ui.export.preset = "Mine".into(); + h.run_steps(4); + click(&mut h, "R+G+B+A"); + + let input_maps = h.get_by_label("Input maps").rect(); + let removes: Vec = h.get_all_by_label("Remove this output").map(|node| node.rect()).collect(); + let alpha = last_window_button(&h, "A: Default white").rect(); + + assert!(!removes.is_empty()); + for remove in removes { + assert!(remove.right() < input_maps.left(), "a row's × stays left of the Input maps pane: {remove:?} {input_maps:?}"); + } + assert!(alpha.right() < input_maps.left(), "the last swatch too: {alpha:?}"); + let cancel = h.get_all_by_label("Cancel").last().unwrap().rect(); + assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); } diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs index fc8f19f6..be849be0 100644 --- a/crates/ui-egui/tests/it/template_invert.rs +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -67,11 +67,11 @@ fn invert_toggle_changes_the_saved_template() { assert!(saved(&h).is_empty()); // Three maps in R, G and B: one swatch per channel - for swatch in ["R: Specular roughness", "G: Base metalness", "B"] { + for swatch in ["R: Roughness (Grayscale)", "G: Metallic (Grayscale)", "B: Constant 0.50"] { assert!(h.query_all_by_label(swatch).next().is_some(), "{swatch}"); } - toggle_invert(&mut h, "G: Base metalness"); + toggle_invert(&mut h, "G: Metallic (Grayscale)"); assert_eq!(saved(&h), vec![Dest::G], "the second channel (G) is inverted"); - toggle_invert(&mut h, "G: Base metalness"); + toggle_invert(&mut h, "G: Metallic (Grayscale), inverted"); assert!(saved(&h).is_empty(), "a second click turns it off"); } From 740616c354bb17331926be66d6890b828faee461 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 01:23:31 +0100 Subject: [PATCH 076/153] Mesh Export Options: the reference's info icons; parity notes for the Output templates tab --- crates/ui-egui/src/mesh_export_options.rs | 43 +++++++++++++++++++--- docs/ui-parity.md | 45 +++++++++++++---------- 2 files changed, 63 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 95e2bae7..702589b3 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -4,6 +4,7 @@ use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; +use crate::theme::Tokens; use crate::unavailable; /// Indent of an option's checkbox under its choice @@ -13,7 +14,10 @@ const OPTION_INDENT: f32 = 20.0; const BUTTON_WIDTH: f32 = 110.0; /// The reference dialog's content width -const DIALOG_WIDTH: f32 = 510.0; +const DIALOG_WIDTH: f32 = 500.0; + +/// Width of an info icon's tooltip, as in the reference +const INFO_TOOLTIP_WIDTH: f32 = 250.0; /// Gap between the two option groups, as in the reference const GROUP_GAP: f32 = 25.0; @@ -32,10 +36,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // TextureCraft exports the mesh as it is: triangulated, without displacement ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); - option(ui, true, tr("Apply triangulation")); + option( + ui, + true, + tr("Apply triangulation"), + &[ + tr("Triangulation converts all mesh polygons with more than 3 sides to triangles (but doesn't change the triangular ones)."), + tr("Choosing to apply triangulation for export avoids unexpected results when rendering the mesh in another application."), + ], + ); ui.add_space(GROUP_GAP); unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); - option(ui, true, tr("Recompute vertex normals")); + option( + ui, + true, + tr("Recompute vertex normals"), + &[ + tr("Recomputing vertex normals is recommended if you don't plan on using the normal map in the target application."), + tr("Otherwise, keeping the original vertex normals is recommended if you plan on using the normal map in the target application."), + ], + ); ui.add_space(8.0); // One row keeps the window to its contents; a bare right-to-left layout fills the screen height @@ -56,10 +76,23 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// A greyed option under a choice, ticked as the reference shows it -fn option(ui: &mut Ui, checked: bool, label: &str) { +/// A greyed option under a choice, ticked as the reference shows it, with an info icon at the +/// row's right end whose tooltip has the paragraphs `info` +fn option(ui: &mut Ui, checked: bool, label: &str, info: &[&str]) { ui.horizontal(|ui| { ui.add_space(OPTION_INDENT); unavailable::checkbox(ui, checked, label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let icon = ui.label(egui::RichText::new(egui_phosphor::regular::INFO).color(Tokens::get(ui.ctx()).text_dim)); + icon.on_hover_ui(|ui| { + ui.set_max_width(INFO_TOOLTIP_WIDTH); + for (k, paragraph) in info.iter().enumerate() { + if k > 0 { + ui.add_space(ui.text_style_height(&egui::TextStyle::Body)); + } + ui.label(*paragraph); + } + }); + }); }); } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 49271c38..2c04591e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -70,7 +70,8 @@ that closes it back onto the bar; the float is saved with the UI state. and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). *Export MaterialX* below *Export USD asset* is a TextureCraft addition: it adds `materialX: true` to the export. The prompt's *With displacement/tessellation* choice and both option checkboxes are - greyed; TextureCraft exports the mesh as it is. + greyed; TextureCraft exports the mesh as it is. The two (i) icons carry the reference's + tooltips. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering mode), *Properties - Paint* while a project is open (other tools read "Properties - ", @@ -345,22 +346,26 @@ that numbers hide once a tile is under 40 points on screen. middle reads "Current preset: ", *Output maps* with *Create:* Gray, RGB, R+G+B, RGB+A, R+G+B+A on the same row, and a footer with drag-and-drop guidance and the number of output maps. Each output map is one row: a drag grip (drag it onto another row to move the map), the - file name, "$" with the file name variables ($project, $mesh, $textureSet, $udim, $uvTileName - greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gray, RGB or R, G, B, - then A), the file type and bit depth lists ("8 bits + dithering" greyed: templates do not keep - it), duplicate and "×". Dropping a map on a swatch opens "From ": a gray map offers *Gray - Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G Channel*, *B Channel* - and *A Channel* (TextureCraft has no alpha or gray of a map yet: those are greyed). A colour - map dropped on the RGB swatch fills R, G and B at once. The swatch then takes the map's - colour, and the map lists mark the maps of the output map edited last with that colour. A - click on a swatch offers *Clear channel* and *Split/Collapse RGB*. The right side has the - *Input maps* pane, grouped as in the reference (Base, Specular, Transmission, Subsurface, - Coat, Fuzz/Sheen; then Emission, Geometry and Other for the channels the reference screenshot - cuts off), and a pane with *Mesh maps* above *Converted maps* (highlighted); maps TextureCraft - does not have yet are greyed and cannot be dragged. TextureCraft keeps a few things the - reference does not show, out of the way: Import and Export of template files at the end of a - preset's right-click menu, Invert in a swatch's right-click menu, *Move up* and *Move down* - in the grip's right-click menu (and the arrow keys on a focused grip), the planned file name - in the file name's tooltip, and three converted maps of its own (Normal from height, Roughness - from glossiness, Sheen color × weight) after the reference's. Built-in templates stay - read-only and deleting asks first. + file name, "$" ("Add expressions in the path that will be replaced during export": $project, + $mesh, $textureSet, $udim, $uvTileName greyed, $colorSpace, then TextureCraft's $channel), the + channel swatches (Gr, RGB or R, G, B, then A), the file format ("File format") and bit depth + ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". + Create names new rows "Grayscale", "RGB" and "RGB Alpha", with "_1", "_2" when taken. An + empty swatch reads "Default black" ("Default white" for A), a filled one " ()", + e.g. "Base color (Red)" or "Metallic (Grayscale)". Dropping a map on a swatch opens "From ": + a gray map offers *Gray Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G + Channel*, *B Channel* and *A Channel*, on the RGB swatch first *RGB Channels*; Escape assigns + nothing. TextureCraft cannot read a map's gray or alpha yet, so those choices are greyed. A + click on a swatch offers *Clear channel*, on RGB, R, G and B also *Split/Collapse RGB*; R, G + and B that read different maps cannot collapse (the item is greyed). The right side has the + *Input maps* pane in the reference's groups and names (Base ... Miscellaneous, User Channels), + and a pane with *Mesh maps* above *Converted maps* (highlighted). Maps the selected template + uses get a square in their swatch's colour. Input and converted maps TextureCraft does not have + are greyed and cannot be dragged (the reference lists them all alike). TextureCraft keeps + some things the reference does not have, out of the way: Import and Export of template files + at the end of a preset's right-click menu; a swatch's right-click menu with Invert (an inverted + swatch has a corner mark), Black, Gray 50%, White, the constant's value and the map's layout + (RGB, RGBA, Gray, Gray + A); *Move up* and *Move down* in the grip's right-click menu and the + arrow keys on a focused grip; the planned file name in the file name's tooltip; and three + converted maps of its own (Normal from height, Roughness from glossiness, Sheen color × weight) + after the reference's. Built-in templates stay read-only and deleting asks first. From 5fe8fe7ae297a1794d5d29be1598bf5df6c10686 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 02:05:50 +0100 Subject: [PATCH 077/153] Output templates: rows keep one line, the Create buttons move below the title in a narrow column --- crates/ui-egui/src/export_templates.rs | 36 +++++++++++++++------ crates/ui-egui/tests/it/output_templates.rs | 16 +++++++++ 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 79f713e0..0dd0d996 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -73,6 +73,8 @@ const ROW_GAP_POINTS: f32 = 4.0; const GRIP_WIDTH_POINTS: f32 = 5.0; const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; const ROW_ICON_POINTS: f32 = 16.0; +/// Width the "Output maps" title and the Create buttons need on one row +const OUTPUT_MAPS_ROW_WIDTH_POINTS: f32 = 420.0; /// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a /// row's right end, and the gaps between a row's controls (besides the swatches') const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; @@ -759,9 +761,9 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { }); }); - // "Output maps", with the Create buttons at the right end of the same row - ui.horizontal(|ui| { - ui.label(caption(tr("Output maps"))); + // "Output maps", with the Create buttons at the right end of the same row, or of the next one + // when the column is too narrow for both + let create_buttons = |ui: &mut Ui, edit: &mut RowEdit| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_enabled_ui(editable, |ui| { for (label, layout, split, file) in CREATE.iter().rev() { @@ -772,7 +774,16 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); }); }); - }); + }; + if ui.available_width() >= OUTPUT_MAPS_ROW_WIDTH_POINTS { + ui.horizontal(|ui| { + ui.label(caption(tr("Output maps"))); + create_buttons(ui, &mut edit); + }); + } else { + ui.label(caption(tr("Output maps"))); + ui.horizontal(|ui| create_buttons(ui, &mut edit)); + } if let Err(e) = &preview { ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); } @@ -916,6 +927,8 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + // The name field gives way in a narrow window, so the swatches and lists stay in the row let swatches = swatch_targets(map, *split).len() as f32; let spacing = ui.spacing().item_spacing.x; @@ -930,19 +943,22 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: changed |= name.changed(); changed |= token_menu(ui, &mut map.file); changed |= channel_swatches(ui, index, map, split, edit); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.vertical(|ui| { + + // The lists and icons at the row's right end: file format and duplicate, bit depth and remove + ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); + ui.vertical(|ui| { + ui.horizontal(|ui| { + changed |= format_menu(ui, map); if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Duplicate(index)); } + }); + ui.horizontal(|ui| { + changed |= depth_menu(ui, map); if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Remove(index)); } }); - ui.vertical(|ui| { - changed |= format_menu(ui, map); - changed |= depth_menu(ui, map); - }); }); }); }); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 2b888752..e8bb3af9 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -549,6 +549,22 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { assert!(remove.right() < input_maps.left(), "a row's × stays left of the Input maps pane: {remove:?} {input_maps:?}"); } assert!(alpha.right() < input_maps.left(), "the last swatch too: {alpha:?}"); + + // Each row stays one line: its controls do not wrap into a tall row + let grips: Vec = h.get_all_by_label("Reorder").map(|grip| grip.rect()).collect(); + for pair in grips.windows(2) { + assert!(pair[1].top() - pair[0].top() < 2.5 * pair[0].height(), "row height {pair:?}"); + } + + // The row's file format list starts right of its last swatch instead of covering it + let format = + h.get_all_by_role(egui::Role::Button).rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png"))).unwrap().rect(); + assert!(alpha.right() <= format.left(), "the swatches and the lists do not overlap: {alpha:?} {format:?}"); + + // The panes stay inside the window: the side pane ends where the bottom bar's buttons end let cancel = h.get_all_by_label("Cancel").last().unwrap().rect(); + let export = last_window_button(&h, "Export").rect(); + let converted = h.get_by_label("Converted maps").rect(); assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); + assert!(converted.left() < export.right() && converted.right() <= export.right() + 1.0, "{converted:?} {export:?}"); } From 9f955aabb614ef45ce163b030634ce483d64d06a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 23 Nov 2026 23:52:57 -0500 Subject: [PATCH 078/153] Write TextureCraft browser downloads through craft-zip (#792) --- Cargo.lock | 5 +++-- crates/ui-egui/Cargo.toml | 6 +++++- crates/ui-egui/src/web_files.rs | 28 +++++++++++++++++----------- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 84a1a752..ac5ff960 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5293,6 +5293,7 @@ dependencies = [ "craft-ui", "craft-update", "craft-window", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", "eframe", "egui", "egui-phosphor", @@ -7079,9 +7080,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.8.1" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ "constant_time_eq", "crc32fast", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5b3ed2d3..d9822509 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -27,7 +27,6 @@ log = { workspace = true } base64 = "0.22" image = { workspace = true } craft-image-codecs = { workspace = true } -zip = { workspace = true } # The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] @@ -62,12 +61,17 @@ skrifa = { version = "0.48", default-features = false, features = ["std"] } # Browser file I/O (web_files.rs): async pickers and Blob downloads. [target.'cfg(target_arch = "wasm32")'.dependencies] +craft-zip = { workspace = true } rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] } +[dev-dependencies] +craft-zip = { workspace = true } +zip = { workspace = true } + # winit needs a window system on Linux, so the crate's own tests build with X11. [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] eframe = { workspace = true, features = ["x11"] } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 048d7a97..accc612e 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -9,6 +9,7 @@ use std::sync::{Mutex, PoisonError}; use texturecraft_engine::Session; use texturecraft_engine::core::PROJECT_EXT; +#[cfg(any(target_arch = "wasm32", test))] use texturecraft_engine::formats::ExportedFile; use texturecraft_engine::formats::export::sanitize_file_stem; use texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS; @@ -228,16 +229,14 @@ pub fn project_file_name(app: &TextureCraftApp) -> String { } /// Pack exported textures into one zip archive. -#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +#[cfg(any(target_arch = "wasm32", test))] fn zip_files(files: Vec) -> Result, String> { - use std::io::Write as _; - let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).large_file(true); + let mut zip = craft_zip::Writer::new(); for f in files { - zip.start_file(f.name.as_str(), opts).map_err(|e| e.to_string())?; - zip.write_all(&f.bytes).map_err(|e| e.to_string())?; + // add_with reserves ZIP64 headers up front, even for small entries. + zip.add_with(&f.name, craft_zip::Compression::Deflated, |out| out.write_all(&f.bytes)).map_err(|e| e.to_string())?; } - Ok(zip.finish().map_err(|e| e.to_string())?.into_inner()) + zip.finish().map_err(|e| e.to_string()) } #[cfg(target_arch = "wasm32")] @@ -525,16 +524,23 @@ mod tests { fn zip_round_trips_every_export_file() { let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; let normal = [7u8; 4096]; - let expected = [("a_BaseColor.png", b"one".as_slice()), ("a_Normal.png", normal.as_slice())]; + let expected = [("z_BaseColor.png", b"one".as_slice()), ("a_Normal.png", normal.as_slice())]; let files = expected.iter().map(|(name, bytes)| file(name, bytes)).collect(); let bytes = zip_files(files).unwrap(); - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); assert_eq!(zip.len(), expected.len()); - for (name, expected_bytes) in expected { + for (index, (name, expected_bytes)) in expected.into_iter().enumerate() { + let mut entry = zip.by_index(index).unwrap(); + assert_eq!(entry.name().unwrap(), name); + assert_eq!(entry.compression(), zip::CompressionMethod::Deflated); + let header = entry.header_start() as usize; + let name_len = u16::from_le_bytes(bytes[header + 26..header + 28].try_into().unwrap()) as usize; + let extra = header + 30 + name_len; + assert_eq!(&bytes[extra..extra + 4], &[1, 0, 16, 0], "expected a ZIP64 size extra field"); let mut out = Vec::new(); - std::io::Read::read_to_end(&mut zip.by_name(name).unwrap(), &mut out).unwrap(); + std::io::Read::read_to_end(&mut entry, &mut out).unwrap(); assert_eq!(out, expected_bytes); } } From 6bc4f3cafc20323b297c18426e5a8383b8063964 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 24 Nov 2026 02:23:29 -0500 Subject: [PATCH 079/153] Fix sample project picker and menu review findings --- crates/ui-egui/src/export_window.rs | 9 +++++++-- crates/ui-egui/src/import_resources.rs | 4 +++- crates/ui-egui/src/menus.rs | 6 ++++-- crates/ui-egui/src/mode_layout.rs | 18 ++++++++++++------ crates/ui-egui/src/named_layouts.rs | 6 +++++- crates/ui-egui/src/new_project_advanced.rs | 4 ++-- crates/ui-egui/src/project_config.rs | 4 ++-- crates/ui-egui/src/session_log_file.rs | 19 ++++++++++++------- crates/ui-egui/src/settings_window.rs | 8 ++++---- crates/ui-egui/src/state.rs | 6 ++++-- crates/ui-egui/src/ui_state_store.rs | 4 ++-- crates/ui-egui/src/web_files.rs | 9 +++++++-- crates/ui-egui/src/windows.rs | 10 ++++++++-- crates/ui-egui/tests/it/empty_start.rs | 9 ++++++++- crates/ui-egui/tests/it/import_resources.rs | 2 +- crates/ui-egui/tests/it/project_config.rs | 2 +- docs/control-protocol.md | 3 ++- 17 files changed, 84 insertions(+), 39 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c37a47d4..fc9e2f62 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -21,8 +21,11 @@ mod map_row; use inherited_settings::InheritedSettings; use map_row::MapRow; -/// Height of the window's tab body, above its buttons +/// Initial height of the window's tab body, above its buttons const BODY_HEIGHT: f32 = 440.0; +const DEFAULT_WINDOW_WIDTH_POINTS: f32 = 900.0; +// Initial space for the tabs, separators and footer +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 80.0; /// Width of the texture set list const LIST_WIDTH: f32 = 180.0; const ICON: f32 = 20.0; @@ -1266,7 +1269,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - crate::windows::dialog(ctx, "export_textures", tr("Export Textures"), &mut open).default_size(vec2(900.0, BODY_HEIGHT + 80.0)).show(ctx, |ui| { + let dialog = crate::windows::dialog(ctx, "export_textures", tr("Export Textures"), &mut open) + .default_size(vec2(DEFAULT_WINDOW_WIDTH_POINTS, BODY_HEIGHT + WINDOW_CHROME_HEIGHT_POINTS)); + dialog.show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { ui.label(tr("No project is open")); diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs index b4e1c7b1..ba49a07b 100644 --- a/crates/ui-egui/src/import_resources.rs +++ b/crates/ui-egui/src/import_resources.rs @@ -18,6 +18,8 @@ use crate::widgets::primary_button; const WINDOW_WIDTH_POINTS: f32 = 640.0; /// Height of the file list const LIST_HEIGHT_POINTS: f32 = 300.0; +// Initial space for the title, file controls, destination and footer +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 200.0; /// Width of a row's prefix field and usage dropdown const PREFIX_WIDTH_POINTS: f32 = 160.0; const USAGE_WIDTH_POINTS: f32 = 110.0; @@ -115,7 +117,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut remove = false; crate::windows::dialog(ctx, "import_resources", tr("Import Resources"), &mut open) - .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + 200.0)) + .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) .show(ctx, |ui| { ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index be4a4fc5..c33c0ddd 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -155,11 +155,13 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if id == "ui.recent.clear" { return !app.ui.recent.is_empty(); } - // Opening the import dialog is independent of importing into a project. + + // Opening the import dialog is independent of importing into a project #[cfg(not(target_arch = "wasm32"))] if id == "resource.import" { return true; } + if let Some(panel) = crate::docking::view_panel(id) { let mode = if app.session.project_open { app.ui.mode } else { Mode::Painting }; return panel.available_in(mode); @@ -380,7 +382,7 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, b = b.shortcut_text(sc); } if let Some(c) = checked { - // Keep the accessible checked state; the checkmark supplies the visual state. + // Keep the accessible checked state; the checkmark supplies the visual state b = b.selected(c); b.set_class(egui::Button::CLASS_SELECTED, false); } diff --git a/crates/ui-egui/src/mode_layout.rs b/crates/ui-egui/src/mode_layout.rs index 5bd7e85d..e449e1e7 100644 --- a/crates/ui-egui/src/mode_layout.rs +++ b/crates/ui-egui/src/mode_layout.rs @@ -45,15 +45,21 @@ impl ModeLayout { } pub fn read(bytes: &[u8]) -> Result { - let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?; - if value.get("windows").is_some() { - let state: UiState = serde_json::from_value(value).map_err(|e| e.to_string())?; - return Ok(Self::of(&state, state.mode)); - } - let layout: Self = serde_json::from_value(value).map_err(|e| e.to_string())?; + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|error| error.to_string())?; + let layout: Self = if value.get("windows").is_some() { + let state: UiState = serde_json::from_value(value).map_err(|error| error.to_string())?; + if !crate::ui_state_store::fully_read(&state) { + return Err("Invalid UI layout".into()); + } + + Self::of(&state, state.mode) + } else { + serde_json::from_value(value).map_err(|error| error.to_string())? + }; if !layout.split_ratio.is_finite() || !(0.0..=1.0).contains(&layout.split_ratio) || layout.dock.replaced_unreadable() { return Err("Invalid UI layout".into()); } + Ok(layout) } } diff --git a/crates/ui-egui/src/named_layouts.rs b/crates/ui-egui/src/named_layouts.rs index ba79e24a..61971f14 100644 --- a/crates/ui-egui/src/named_layouts.rs +++ b/crates/ui-egui/src/named_layouts.rs @@ -1,4 +1,4 @@ -//! Window > Layouts: panel arrangements saved under a name and switched from the menu. +//! Named panel arrangements retained for shortcuts and automation. //! //! A named layout holds the painting and the baking dock (which panels are shown, where, and //! how big). Switching to one touches nothing else: not the mode, the zoom, the wireframes, the @@ -52,6 +52,10 @@ impl UiState { let (current, other) = if self.dock_is_baking { (layout.baking, layout.painting) } else { (layout.painting, layout.baking) }; self.dock = current; self.inactive_mode_dock = other; + if self.dock_is_rendering { + // Legacy layouts share their painting arrangement with Rendering + self.inactive_render_dock = Some(self.dock.clone()); + } // A popup open against the rail shows a panel of the old arrangement self.rail_panel = None; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index caf7bb8c..6931cd63 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -80,13 +80,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut create, mut cancel) = (false, false); - // Start with a form that fits the viewport; subsequent sizes follow the user's resize. + // Start with a form that fits the viewport; subsequent sizes follow the user's resize let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); dialog(ctx, "new_project", tr("New Project"), &mut open).default_size(vec2(DIALOG_WIDTH_POINTS, form_height + DIALOG_CHROME_HEIGHT_POINTS)).show( ctx, |ui| { - // Lay out the actual footer first so it cannot make the window grow each frame. + // Lay out the actual footer first so it cannot make the window grow each frame ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { let can_create = app.ui.new_project.file.is_some(); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index b5486128..a399aa4e 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -137,7 +137,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - // Start with a form that fits the viewport; subsequent sizes follow the user's resize. + // Start with a form that fits the viewport; subsequent sizes follow the user's resize let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); let dialog = crate::windows::dialog(ctx, "project_config", tr("Project Configuration"), &mut open) @@ -158,7 +158,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let form_height = ui.available_height().max(0.0); let scroll = egui::ScrollArea::both() .id_salt("project_config_form") - .content_margin(crate::windows::dialog_scroll_margin(ui)) + .content_margin(crate::windows::dialog_scroll_margin(ui)) .min_scrolled_width(0.0) .min_scrolled_height(0.0) .max_height(form_height) diff --git a/crates/ui-egui/src/session_log_file.rs b/crates/ui-egui/src/session_log_file.rs index 96e0202f..0ee1a6b4 100644 --- a/crates/ui-egui/src/session_log_file.rs +++ b/crates/ui-egui/src/session_log_file.rs @@ -6,6 +6,9 @@ use std::{ }; use texturecraft_engine::LogEntry; +// Retain two segments to bound each run's log while preserving recent history +const MAX_LOG_SEGMENT_BYTES: u64 = 8 * 1024 * 1024; + pub(crate) struct SessionLogFile { pub path: PathBuf, file: File, @@ -20,6 +23,7 @@ impl SessionLogFile { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } + let file = OpenOptions::new().create_new(true).append(true).open(&path)?; Ok(Self { path, file, bytes: 0, log_id: 0, cursor: 0, last: None }) } @@ -41,16 +45,19 @@ impl SessionLogFile { if same_tail && self.cursor == entries.len() { return Ok(()); } + let start = if same_tail { self.cursor } else { 0 }; for entry in entries.get(start..).unwrap_or_default() { - // Clearing lines in the panel must not append the remaining old lines twice. - if self.log_id == log_id && self.last.as_ref().is_some_and(|last| entry.time <= last.time) { + // Only reconcile timestamps after removal; appended entries can predate the last sync + if !same_tail && self.log_id == log_id && self.last.as_ref().is_some_and(|last| entry.time <= last.time) { continue; } + let text = crate::windows::log_text(std::slice::from_ref(entry)); let line = text.split_once('\n').map(|(_, line)| line).unwrap_or_default(); - // Bound each run's disk use. Keep one previous segment when the active log rolls. - if self.bytes.saturating_add(line.len() as u64) > 8 * 1024 * 1024 { + + // Keep one previous segment when the active log rolls + if self.bytes.saturating_add(line.len() as u64) > MAX_LOG_SEGMENT_BYTES { self.file.flush()?; std::fs::copy(&self.path, self.path.with_file_name("log.previous.txt"))?; self.file.set_len(0)?; @@ -62,9 +69,7 @@ impl SessionLogFile { self.file.flush()?; self.log_id = log_id; self.cursor = entries.len(); - if let Some(last) = entries.last() { - self.last = Some(last.clone()); - } + self.last = entries.last().cloned(); Ok(()) } } diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index a933bfd9..8fda17b0 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -8,7 +8,7 @@ use crate::TextureCraftApp; #[cfg(not(target_arch = "wasm32"))] use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{LANGUAGES, SYSTEM_LANGUAGE, n_, tr, trf}; -use crate::state::{CAMERA_SPEED_RANGE, LibraryLocation, Prefs}; +use crate::state::{CAMERA_SPEED_RANGE, LibraryLocation, MAX_RECENT_PROJECTS, Prefs}; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; @@ -78,9 +78,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::windows::window("settings", tr("Settings"), &mut open) .default_size(vec2(content_width + frame_width, page_height + WINDOW_CHROME_HEIGHT_POINTS)) .show(ctx, |ui| { - // Measure the footer through layout, then let the pages use only what remains. + // Measure the footer through layout, then let the pages use only what remains ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - // Recheck after drawing the page as well, before accepting any edits. + // Recheck after drawing the page as well, before accepting any edits let conflict = crate::keymap::has_conflict(&app.settings_bindings); ui.horizontal(|ui| { if conflict { @@ -363,7 +363,7 @@ fn general( }); row(ui, tr("Recent projects limit"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.recent_projects_limit).range(0..=100)) + ui.add(egui::DragValue::new(&mut p.recent_projects_limit).range(0..=MAX_RECENT_PROJECTS)) .labelled_by(label) .on_hover_text(tr("Number of recent projects to remember. 0 disables recent-project history.")); }); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ebbbe52e..3b47c364 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -635,10 +635,12 @@ pub struct UiState { pub log_id: u64, } +pub(crate) const MAX_RECENT_PROJECTS: u16 = 100; + impl UiState { /// Keep recent-file history bounded, including values supplied through automation or old settings. pub(crate) fn trim_recent(&mut self) { - self.prefs.recent_projects_limit = self.prefs.recent_projects_limit.min(100); + self.prefs.recent_projects_limit = self.prefs.recent_projects_limit.min(MAX_RECENT_PROJECTS); self.recent.truncate(usize::from(self.prefs.recent_projects_limit)); } @@ -675,7 +677,7 @@ impl UiState { self.bake_layout_version = BAKE_LAYOUT_VERSION; } - /// Put the panels, tabs and floating panels of both modes back to their defaults; the view split, + /// Put the panels, tabs and floating panels of every mode back to their defaults; the view split, /// zoom, wireframes, symmetry display, mode and every setting stay as they are pub fn reset_panel_layout(&mut self) { let (painting, baking) = (Dock::default(), Dock::for_baking()); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index 80bad1c7..f49804c9 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -243,8 +243,8 @@ fn read_bytes(_file: &Path) -> std::io::Result> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "UI settings use browser storage")) } -/// Whether every dock, the two in use and those of the named layouts, was read rather than replaced by a default -fn fully_read(ui: &UiState) -> bool { +/// Whether every mode's dock and the named layouts were read rather than replaced by a default +pub(crate) fn fully_read(ui: &UiState) -> bool { ui.inactive_render_dock.as_ref().is_none_or(|dock| !dock.replaced_unreadable()) && !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 048d7a97..12dece87 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -242,8 +242,8 @@ fn zip_files(files: Vec) -> Result, String> { #[cfg(target_arch = "wasm32")] pub use web::{ - download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, pick_new_project_mesh, - save_project, sync_unsaved, unsaved, + download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, open_sample_project, + pick_new_project_mesh, save_project, sync_unsaved, unsaved, }; #[cfg(target_arch = "wasm32")] @@ -270,6 +270,11 @@ mod web { pick(ctx, tr("Projects and meshes"), OPEN_EXTS, false, Pick::Open); } + /// File > Open Sample Project: choose a saved TextureCraft project. + pub fn open_sample_project(ctx: &egui::Context) { + pick(ctx, tr("TextureCraft project"), &[PROJECT_EXT], false, Pick::Open); + } + /// File › Import material: pick materials; they add as layers on a later frame. pub fn import_material(ctx: &egui::Context) { pick(ctx, tr("Materials"), MATERIAL_EXTS, true, Pick::Open); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index e8a3ef80..7096b30b 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -520,8 +520,13 @@ pub fn load_layout(app: &mut TextureCraftApp) { #[cfg(not(target_arch = "wasm32"))] pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool { match id { - "file.open" => { - app.ask_file(FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS), Bound::App, |app, paths| { + "file.open" | "project.sample" => { + let dialog = if id == "project.sample" { + FileDialog::open().title(tr("Open Sample Project")).filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]) + } else { + FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS) + }; + app.ask_file(dialog, Bound::App, |app, paths| { if let Some(path) = paths.first() { open_path(app, &path.display().to_string()); } @@ -667,6 +672,7 @@ pub fn open_path(app: &mut TextureCraftApp, path: &str) { pub fn file_action(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) -> bool { match id { "file.open" => crate::web_files::open(ctx), + "project.sample" => crate::web_files::open_sample_project(ctx), "file.importResources" | "resource.import" => crate::web_files::import_images(ctx), "material.load" => crate::web_files::import_material(ctx), "file.save" | "file.saveAs" | "file.saveCopy" => crate::web_files::save_project(app), diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index a7917183..09f3c1ca 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -164,11 +164,18 @@ fn creating_or_opening_a_project_from_the_empty_state_works() { assert!(harness.state().ui.windows.new_project, "New project opens its dialog from the empty state"); + let directory = super::temp_dir::TempDir::new("picked-sample"); + let file = directory.join("sample.tcraft"); + let sample = Session::new_project("Chosen sample", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + std::fs::write(&file, sample.to_project_bytes().unwrap()).unwrap(); let mut harness = empty(); + let picked = file.clone(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| texturecraft_ui_egui::file_dialogs::Answer::Paths(vec![picked.clone()])))); invoke(&mut harness, "project.sample"); - assert!(harness.state().session.project_open && harness.state().session.set_count() == 2, "the sample is still one menu click away"); + assert!(harness.state().session.project_open); + assert_eq!(harness.state().session.doc.project.name, sample.doc.project.name, "the selected sample project opens"); } #[test] diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs index 173a3dc9..a933c168 100644 --- a/crates/ui-egui/tests/it/import_resources.rs +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -12,7 +12,7 @@ use texturecraft_ui_egui::file_dialogs::{Answer, Request}; use super::temp_dir::TempDir; -const TITLE: &str = "Import resources"; +const TITLE: &str = "Import Resources"; /// The prefix field's tooltip, which is its accessible label. const PREFIX_HINT: &str = "Put in front of the resource's name. Characters other than letters, digits and _ . - become _"; diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 91dec76d..2bbd3939 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -15,7 +15,7 @@ const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\n const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"; /// The format combo's tooltip, which is its accessible label. const FORMAT_HINT: &str = "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export"; -const TITLE: &str = "Project configuration"; +const TITLE: &str = "Project Configuration"; fn temp_dir(test: &str) -> TempDir { TempDir::new(test) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 304a58cb..7d39396f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -209,7 +209,8 @@ keeps its state in a throwaway file. | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | | `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` | -| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Select a UI layout file."); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | +| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | +| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. The direct `project.sample` engine command still creates the generated sample for automation. | | `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled | | `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) | | `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before | From e60448621652d060849df92f22daa3dabcd1f906 Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 24 Nov 2026 08:48:18 +0100 Subject: [PATCH 080/153] Bound the session log folders and import MaterialX from Import Resources Each desktop run made a new logs/session-* folder that was never removed, so the logs folder grew with every start. Starting a run now removes all but the newest earlier runs' folders, keeping ten in all. Removing File > Import MaterialX material... left no way to import a .mtlx from the GUI. Import Resources now lists .mtlx files and imports them as file.importMaterialX does, as a fill layer. The protocol doc no longer points at the removed Import PBR texture folder item. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/import_resources.rs | 21 +++++++-- crates/ui-egui/src/lib.rs | 6 +-- crates/ui-egui/src/session_log_file.rs | 50 ++++++++++++++++++++- crates/ui-egui/src/windows.rs | 31 ++++++++----- crates/ui-egui/tests/it/import_resources.rs | 27 +++++++++++ docs/control-protocol.md | 7 +-- 6 files changed, 120 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs index ba49a07b..6e979c85 100644 --- a/crates/ui-egui/src/import_resources.rs +++ b/crates/ui-egui/src/import_resources.rs @@ -1,5 +1,6 @@ //! File > Import resources...: a window to collect files, set what each is for, and import them -//! together. Images become project resources; materials load as smart materials. +//! together. Images become project resources; materials load as smart materials and MaterialX +//! documents as fill layers. use std::collections::BTreeSet; use std::sync::atomic::{AtomicU64, Ordering}; @@ -61,9 +62,18 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, n } } -/// Whether the file is a material (loaded as a smart material, so it has no usage or prefix) +fn extension_of(row: &ImportRow) -> String { + row.path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default() +} + +/// Whether the file is a MaterialX document (added as a fill layer) +fn is_materialx(row: &ImportRow) -> bool { + extension_of(row) == crate::windows::MATERIALX_EXT +} + +/// Whether the file is a material (a smart material or a MaterialX document, so it has no usage or prefix) fn is_material(row: &ImportRow) -> bool { - row.path.extension().and_then(|e| e.to_str()).is_some_and(|e| MATERIAL_EXTS.contains(&e.to_ascii_lowercase().as_str())) + MATERIAL_EXTS.contains(&extension_of(row).as_str()) || is_materialx(row) } fn file_name(row: &ImportRow) -> String { @@ -256,6 +266,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if add { let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec(); extensions.extend_from_slice(MATERIAL_EXTS); + extensions.push(crate::windows::MATERIALX_EXT); let opening_id = window.opening_id; app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| { let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return }; @@ -293,6 +304,10 @@ fn import_row(app: &mut TextureCraftApp, row: &ImportRow) -> bool { return false; }; + if is_materialx(row) { + return crate::windows::import_materialx(app, path); + } + if is_material(row) { return app.run("material.load", json!({ "path": path })).is_some(); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 89025239..850c226a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -457,11 +457,7 @@ impl TextureCraftApp { } #[cfg(not(target_arch = "wasm32"))] if cc.winit_window().is_some() { - let path = crate::data_dir() - .join("logs") - .join(format!("session-{}-{}", chrono::Utc::now().format("%Y%m%dT%H%M%S%.6fZ"), std::process::id())) - .join("log.txt"); - match session_log_file::SessionLogFile::new(path) { + match session_log_file::SessionLogFile::start(&crate::data_dir().join("logs")) { Ok(file) => app.session_log_file = Some(file), Err(error) => app.toast(format!("{}: {error}", i18n::tr("Could not create the session log")), true), } diff --git a/crates/ui-egui/src/session_log_file.rs b/crates/ui-egui/src/session_log_file.rs index 0ee1a6b4..f6292044 100644 --- a/crates/ui-egui/src/session_log_file.rs +++ b/crates/ui-egui/src/session_log_file.rs @@ -2,12 +2,15 @@ use std::{ fs::{File, OpenOptions}, io::{self, Write}, - path::PathBuf, + path::{Path, PathBuf}, }; use texturecraft_engine::LogEntry; // Retain two segments to bound each run's log while preserving recent history const MAX_LOG_SEGMENT_BYTES: u64 = 8 * 1024 * 1024; +/// Runs whose log folders stay in the logs folder, the new run's included, so the folder stays bounded +const KEPT_SESSION_FOLDERS: usize = 10; +const SESSION_FOLDER_PREFIX: &str = "session-"; pub(crate) struct SessionLogFile { pub path: PathBuf, @@ -18,7 +21,31 @@ pub(crate) struct SessionLogFile { last: Option, } +/// Remove all but the `keep` newest session folders in `logs`. Their names start with a UTC time, so +/// name order is age order. Errors are ignored: a folder an older run still holds open stays for a later start. +fn prune(logs: &Path, keep: usize) { + let Ok(entries) = std::fs::read_dir(logs) else { return }; + let mut folders: Vec = entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) + .filter(|entry| entry.file_name().to_str().is_some_and(|name| name.starts_with(SESSION_FOLDER_PREFIX))) + .map(|entry| entry.path()) + .collect(); + folders.sort(); + let old = folders.len().saturating_sub(keep); + for folder in &folders[..old] { + let _ = std::fs::remove_dir_all(folder); + } +} + impl SessionLogFile { + /// Start this run's log in a new session folder under `logs`, after removing the oldest runs' folders. + pub fn start(logs: &Path) -> io::Result { + prune(logs, KEPT_SESSION_FOLDERS - 1); + let folder = format!("{SESSION_FOLDER_PREFIX}{}-{}", chrono::Utc::now().format("%Y%m%dT%H%M%S%.6fZ"), std::process::id()); + Self::new(logs.join(folder).join("log.txt")) + } + pub fn new(path: PathBuf) -> io::Result { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; @@ -100,4 +127,25 @@ mod tests { drop(file); std::fs::remove_file(path).unwrap(); } + + #[test] + fn starting_a_run_removes_only_the_oldest_session_folders() { + let logs = std::env::temp_dir().join(format!("texturecraft-session-prune-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&logs); + let older: Vec = (0..KEPT_SESSION_FOLDERS + 2).map(|i| logs.join(format!("{SESSION_FOLDER_PREFIX}20260101T0000{i:02}.000000Z-1"))).collect(); + for folder in &older { + std::fs::create_dir_all(folder).unwrap(); + } + let other = logs.join("kept-by-the-user"); + std::fs::create_dir_all(&other).unwrap(); + + let file = SessionLogFile::start(&logs).unwrap(); + + let survivors = older.iter().filter(|folder| folder.exists()).count(); + assert_eq!(survivors + 1, KEPT_SESSION_FOLDERS, "the new run and the newest earlier runs remain"); + assert!(!older[0].exists() && older.last().unwrap().exists(), "the oldest go first"); + assert!(other.exists() && file.path.exists(), "other folders and the new log stay"); + drop(file); + std::fs::remove_dir_all(logs).unwrap(); + } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 7096b30b..fcd7d468 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -516,6 +516,24 @@ pub fn load_layout(app: &mut TextureCraftApp) { app.toast(tr("Saving UI layouts to files is available in the desktop app"), false); } +/// The extension of MaterialX documents (`file.importMaterialX`) +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const MATERIALX_EXT: &str = "mtlx"; + +/// Add the MaterialX material at `path` as a layer, logging what it could not read. Returns whether it was added. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn import_materialx(app: &mut TextureCraftApp, path: &str) -> bool { + let Some(result) = app.run("file.importMaterialX", json!({"path": path})) else { return false }; + + let name = result["material"].as_str().unwrap_or_default(); + for warning in result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str) { + app.session.log.warn(texturecraft_engine::log::LIBRARY_SOURCE, format!("MaterialX {name}: {warning}")); + } + app.toast(trf("Imported {name}", &[("name", &name)]), false); + app.ui.dock.focus(crate::docking::Panel::Layers); + true +} + /// File menu actions that need dialogs. Returns true when handled. #[cfg(not(target_arch = "wasm32"))] pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool { @@ -561,16 +579,9 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> true } "file.importMaterialX" => { - app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &["mtlx"]), Bound::Project, |app, paths| { - if let Some(path) = paths.first() - && let Some(result) = app.run("file.importMaterialX", json!({"path": path.display().to_string()})) - { - let name = result["material"].as_str().unwrap_or_default(); - for warning in result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str) { - app.session.log.warn(texturecraft_engine::log::LIBRARY_SOURCE, format!("MaterialX {name}: {warning}")); - } - app.toast(trf("Imported {name}", &[("name", &name)]), false); - app.ui.dock.focus(crate::docking::Panel::Layers); + app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &[MATERIALX_EXT]), Bound::Project, |app, paths| { + if let Some(path) = paths.first() { + import_materialx(app, &path.display().to_string()); } }); true diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs index a933c168..26badb0f 100644 --- a/crates/ui-egui/tests/it/import_resources.rs +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -208,6 +208,33 @@ fn the_engine_command_still_imports_a_path_with_an_optional_prefix() { assert_eq!(prefixed["name"], "a_b_tile.png"); } +#[test] +fn a_materialx_document_imports_as_a_layer() { + let dir = TempDir::new("import-resources-materialx"); + let file = dir.join("paint.mtlx"); + std::fs::write( + &file, + r#" + + + + + +"#, + ) + .unwrap(); + let mut h = app(); + let layers = h.state().session.doc.project.layers.len(); + invoke(&mut h); + add(&mut h, &[file]); + + click(&mut h, "Import"); + + assert!(!is_open(&h), "the document was imported"); + assert!(h.state().session.doc.project.layers.len() > layers, "the material became a layer"); + assert!(resources(&h).is_empty(), "the document itself is not an image resource"); +} + #[test] fn only_failed_rows_remain_after_a_partial_import() { let dir = TempDir::new("import-resources-retry"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7d39396f..1b212184 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -507,9 +507,10 @@ Maps are found by file name, case-insensitively, from the last known word in the import is an error that changes nothing. `maps` describes detection; `channels` and `resources` describe the successful import. Scan validates import options without decoding pixels. -In the app: File › Import PBR texture folder... or drop a folder, a `.zip` or several map files on the -window. The dialog shows the maps found, lets you pick between candidates, set the normal convention and -projection, and keep the material in the library (shelf › Materials). +In the app: drop a folder, a `.zip` or several map files on the window. The dialog shows the maps found, +lets you pick between candidates, set the normal convention and projection, and keep the material in the +library (shelf › Materials). A `.mtlx` added in File › Import Resources is imported as `file.importMaterialX` +does it. ## Smart masks From b6b761da86b28d45e9d4c083995292cb991316d6 Mon Sep 17 00:00:00 2001 From: "coderabbitai[bot]" <136622811+coderabbitai[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:00:34 +0000 Subject: [PATCH 081/153] Fix session log persistence and defer the sample project save prompt until selection --- crates/engine/src/session_log.rs | 60 +++++++++--- crates/ui-egui/src/lib.rs | 16 ++-- crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/named_layouts.rs | 4 - crates/ui-egui/src/session_log_file.rs | 118 ++++++++++++++++-------- crates/ui-egui/src/windows.rs | 4 +- crates/ui-egui/tests/it/empty_menus.rs | 2 +- crates/ui-egui/tests/it/file_dialogs.rs | 19 ++++ docs/control-protocol.md | 8 +- 9 files changed, 166 insertions(+), 67 deletions(-) diff --git a/crates/engine/src/session_log.rs b/crates/engine/src/session_log.rs index 9b7ce55c..2c4e6d62 100644 --- a/crates/engine/src/session_log.rs +++ b/crates/engine/src/session_log.rs @@ -4,33 +4,59 @@ use crate::log::DEFAULT_SOURCE; use crate::{LogEntry, LogLevel}; /// The current session's log in occurrence order -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct SessionLog(Vec); +#[derive(Clone, Debug, Default)] +pub struct SessionLog { + entries: Vec, + // IDs stay in occurrence order and are never reused after a clear or retain. + occurrences: Vec, + last_occurrence: u64, +} + +impl PartialEq for SessionLog { + fn eq(&self, other: &Self) -> bool { + self.entries == other.entries + } +} + +impl Eq for SessionLog {} impl SessionLog { pub fn new() -> SessionLog { - SessionLog(Vec::new()) + Self::default() } pub fn entries(&self) -> &[LogEntry] { - &self.0 + &self.entries + } + + /// Entries added after a previous occurrence in this log, in append order. + /// Pass zero to start at the beginning. + pub fn entries_after(&self, occurrence: u64) -> impl Iterator { + let start = self.occurrences.partition_point(|&id| id <= occurrence); + self.occurrences[start..].iter().copied().zip(&self.entries[start..]) + } + + fn record(&mut self, entry: LogEntry) { + self.last_occurrence += 1; + self.occurrences.push(self.last_occurrence); + self.entries.push(entry); } /// An info entry without a source of its own pub fn push(&mut self, message: String) { - self.0.push(LogEntry::new(LogLevel::Info, DEFAULT_SOURCE, message)); + self.record(LogEntry::new(LogLevel::Info, DEFAULT_SOURCE, message)); } pub fn info(&mut self, source: &str, message: impl Into) { - self.0.push(LogEntry::new(LogLevel::Info, source, message)); + self.record(LogEntry::new(LogLevel::Info, source, message)); } pub fn warn(&mut self, source: &str, message: impl Into) { - self.0.push(LogEntry::new(LogLevel::Warning, source, message)); + self.record(LogEntry::new(LogLevel::Warning, source, message)); } pub fn error(&mut self, source: &str, message: impl Into) { - self.0.push(LogEntry::new(LogLevel::Error, source, message)); + self.record(LogEntry::new(LogLevel::Error, source, message)); } /// Several warnings of one source @@ -42,23 +68,31 @@ impl SessionLog { /// Append the entries of another store pub fn append(&mut self, other: SessionLog) { - self.0.extend(other.0); + for entry in other.entries { + self.record(entry); + } } pub fn clear(&mut self) { - self.0.clear(); + self.entries.clear(); + self.occurrences.clear(); } /// Drop the entries for which `keep` is false pub fn retain(&mut self, keep: impl FnMut(&LogEntry) -> bool) { - self.0.retain(keep); + // Evaluate the predicate once and apply the same decisions to both vectors. + let kept: Vec<_> = self.entries.iter().map(keep).collect(); + let mut decisions = kept.iter().copied(); + self.entries.retain(|_| decisions.next().unwrap_or_default()); + let mut decisions = kept.into_iter(); + self.occurrences.retain(|_| decisions.next().unwrap_or_default()); } } impl Deref for SessionLog { type Target = [LogEntry]; fn deref(&self) -> &[LogEntry] { - &self.0 + &self.entries } } @@ -66,6 +100,6 @@ impl<'a> IntoIterator for &'a SessionLog { type Item = &'a LogEntry; type IntoIter = std::slice::Iter<'a, LogEntry>; fn into_iter(self) -> Self::IntoIter { - self.0.iter() + self.entries.iter() } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 850c226a..47259f2b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -455,13 +455,6 @@ impl TextureCraftApp { if cc.winit_window().is_none() { app.file_dialogs.without_window(); } - #[cfg(not(target_arch = "wasm32"))] - if cc.winit_window().is_some() { - match session_log_file::SessionLogFile::start(&crate::data_dir().join("logs")) { - Ok(file) => app.session_log_file = Some(file), - Err(error) => app.toast(format!("{}: {error}", i18n::tr("Could not create the session log")), true), - } - } app.ui.rename = None; app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); @@ -473,6 +466,13 @@ impl TextureCraftApp { // 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)); + if cc.winit_window().is_some() { + match session_log_file::SessionLogFile::start(&crate::data_dir().join("logs")) { + Ok(file) => app.session_log_file = Some(file), + Err(error) => app.toast(format!("{}: {error}", i18n::tr("Could not create the session log")), true), + } + } + // 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(); @@ -1150,7 +1150,7 @@ impl eframe::App for TextureCraftApp { self.toasts.retain(|toast| toast.until > now); #[cfg(not(target_arch = "wasm32"))] if let Some(file) = &mut self.session_log_file - && let Err(error) = file.sync(self.session.log_id, self.session.log.entries()) + && let Err(error) = file.sync(self.session.log_id, &self.session.log) { self.session_log_file = None; self.toast(format!("{}: {error}", i18n::tr("Could not update the session log")), true); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index c33c0ddd..1d4588ea 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -203,7 +203,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { return; } - if matches!(id, "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { + if matches!(id, "file.open" | "file.close") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { return; } diff --git a/crates/ui-egui/src/named_layouts.rs b/crates/ui-egui/src/named_layouts.rs index 61971f14..703690f7 100644 --- a/crates/ui-egui/src/named_layouts.rs +++ b/crates/ui-egui/src/named_layouts.rs @@ -52,10 +52,6 @@ impl UiState { let (current, other) = if self.dock_is_baking { (layout.baking, layout.painting) } else { (layout.painting, layout.baking) }; self.dock = current; self.inactive_mode_dock = other; - if self.dock_is_rendering { - // Legacy layouts share their painting arrangement with Rendering - self.inactive_render_dock = Some(self.dock.clone()); - } // A popup open against the rail shows a panel of the old arrangement self.rail_panel = None; diff --git a/crates/ui-egui/src/session_log_file.rs b/crates/ui-egui/src/session_log_file.rs index f6292044..ce5edfae 100644 --- a/crates/ui-egui/src/session_log_file.rs +++ b/crates/ui-egui/src/session_log_file.rs @@ -4,7 +4,7 @@ use std::{ io::{self, Write}, path::{Path, PathBuf}, }; -use texturecraft_engine::LogEntry; +use texturecraft_engine::SessionLog; // Retain two segments to bound each run's log while preserving recent history const MAX_LOG_SEGMENT_BYTES: u64 = 8 * 1024 * 1024; @@ -17,8 +17,7 @@ pub(crate) struct SessionLogFile { file: File, bytes: u64, log_id: u64, - cursor: usize, - last: Option, + cursor: u64, } /// Remove all but the `keep` newest session folders in `logs`. Their names start with a UTC time, so @@ -52,7 +51,7 @@ impl SessionLogFile { } let file = OpenOptions::new().create_new(true).append(true).open(&path)?; - Ok(Self { path, file, bytes: 0, log_id: 0, cursor: 0, last: None }) + Ok(Self { path, file, bytes: 0, log_id: 0, cursor: 0 }) } pub fn text(&mut self) -> io::Result { @@ -67,19 +66,12 @@ impl SessionLogFile { Ok(text) } - pub fn sync(&mut self, log_id: u64, entries: &[LogEntry]) -> io::Result<()> { - let same_tail = self.log_id == log_id && self.cursor.checked_sub(1).and_then(|i| entries.get(i)) == self.last.as_ref(); - if same_tail && self.cursor == entries.len() { - return Ok(()); + pub fn sync(&mut self, log_id: u64, log: &SessionLog) -> io::Result<()> { + if self.log_id != log_id { + self.log_id = log_id; + self.cursor = 0; } - - let start = if same_tail { self.cursor } else { 0 }; - for entry in entries.get(start..).unwrap_or_default() { - // Only reconcile timestamps after removal; appended entries can predate the last sync - if !same_tail && self.log_id == log_id && self.last.as_ref().is_some_and(|last| entry.time <= last.time) { - continue; - } - + for (occurrence, entry) in log.entries_after(self.cursor) { let text = crate::windows::log_text(std::slice::from_ref(entry)); let line = text.split_once('\n').map(|(_, line)| line).unwrap_or_default(); @@ -92,38 +84,25 @@ impl SessionLogFile { } self.file.write_all(line.as_bytes())?; self.bytes = self.bytes.saturating_add(line.len() as u64); + self.cursor = occurrence; } - self.file.flush()?; - self.log_id = log_id; - self.cursor = entries.len(); - self.last = entries.last().cloned(); - Ok(()) + self.file.flush() } } #[cfg(test)] mod tests { use super::*; - use texturecraft_engine::{LogLevel, SessionLog}; - #[test] - fn log_file_keeps_messages_after_panel_clear_and_across_projects() { + fn temp_log() -> SessionLogFile { let dir = std::env::temp_dir().join(format!("texturecraft-session-log-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join(format!("{}.txt", chrono::Utc::now().timestamp_nanos_opt().unwrap())); - let mut file = SessionLogFile::new(path.clone()).unwrap(); - let mut log = SessionLog::new(); - log.push("first".into()); - file.sync(1, log.entries()).unwrap(); - file.sync(1, log.entries()).unwrap(); - log.clear(); - file.sync(1, log.entries()).unwrap(); - log.error("UI", "second"); - file.sync(1, log.entries()).unwrap(); - file.sync(2, &[LogEntry::new(LogLevel::Info, "UI", "new project")]).unwrap(); - let text = std::fs::read_to_string(&path).unwrap(); - assert_eq!(text.matches("first").count(), 1); - assert!(text.contains("second") && text.contains("new project")); + SessionLogFile::new(path).unwrap() + } + + fn remove_log(file: SessionLogFile) { + let path = file.path.clone(); drop(file); std::fs::remove_file(path).unwrap(); } @@ -148,4 +127,69 @@ mod tests { drop(file); std::fs::remove_dir_all(logs).unwrap(); } + + #[test] + fn log_file_keeps_messages_after_panel_clear_and_across_projects() { + let mut file = temp_log(); + let mut log = SessionLog::new(); + log.push("first".into()); + file.sync(1, &log).unwrap(); + file.sync(1, &log).unwrap(); + log.clear(); + file.sync(1, &log).unwrap(); + log.error("UI", "second"); + file.sync(1, &log).unwrap(); + let mut next_project = SessionLog::new(); + next_project.info("UI", "new project"); + file.sync(2, &next_project).unwrap(); + let text = file.text().unwrap(); + assert_eq!(text.matches("first").count(), 1); + assert!(text.contains("second") && text.contains("new project")); + remove_log(file); + } + + #[test] + fn removing_the_tail_does_not_hide_an_earlier_timestamp_append() { + let mut file = temp_log(); + let mut pending = SessionLog::new(); + pending.push("deferred message".into()); + + let mut log = SessionLog::new(); + log.push("kept message".into()); + log.push("removed tail".into()); + file.sync(1, &log).unwrap(); + + assert!(pending[0].time <= log[1].time); + log.retain(|entry| entry.message != "removed tail"); + log.append(pending); + file.sync(1, &log).unwrap(); + + let text = file.text().unwrap(); + for message in ["deferred message", "kept message", "removed tail"] { + assert_eq!(text.matches(message).count(), 1, "{message}"); + } + remove_log(file); + } + + #[test] + fn removing_an_earlier_timestamp_tail_does_not_replay_the_survivors() { + let mut file = temp_log(); + let mut pending = SessionLog::new(); + pending.push("removed tail".into()); + + let mut log = SessionLog::new(); + log.push("kept message".into()); + log.append(pending); + assert!(log[0].time >= log[1].time); + file.sync(1, &log).unwrap(); + + log.retain(|entry| entry.message != "removed tail"); + file.sync(1, &log).unwrap(); + file.sync(1, &log).unwrap(); + + let text = file.text().unwrap(); + assert_eq!(text.matches("kept message").count(), 1); + assert_eq!(text.matches("removed tail").count(), 1); + remove_log(file); + } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index fcd7d468..d3e7d119 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -350,7 +350,7 @@ pub(crate) fn show_log(app: &mut TextureCraftApp, _ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { let result = match app.session_log_file.as_mut() { - Some(file) => file.sync(app.session.log_id, app.session.log.entries()).map(|()| file.path.clone()), + Some(file) => file.sync(app.session.log_id, &app.session.log).map(|()| file.path.clone()), None => Err(std::io::Error::other(tr("No session log file is available"))), }; match result.and_then(|path| app.file_dialogs.show_folder(&path)) { @@ -367,7 +367,7 @@ pub(crate) fn export_log(app: &mut TextureCraftApp) { let text = log_text(app.session.log.entries()); #[cfg(not(target_arch = "wasm32"))] let text = if let Some(file) = &mut app.session_log_file { - match file.sync(app.session.log_id, app.session.log.entries()).and_then(|()| file.text()) { + match file.sync(app.session.log_id, &app.session.log).and_then(|()| file.text()) { Ok(lines) => format!("{}{lines}", log_text(&[])), Err(error) => { app.toast(trf("Could not export the log: {error}", &[("error", &error)]), true); diff --git a/crates/ui-egui/tests/it/empty_menus.rs b/crates/ui-egui/tests/it/empty_menus.rs index 4092a8d7..3e669830 100644 --- a/crates/ui-egui/tests/it/empty_menus.rs +++ b/crates/ui-egui/tests/it/empty_menus.rs @@ -79,7 +79,7 @@ fn reset_restores_the_empty_workspace_and_checked_disabled_quick_mask() { assert!(!h.state().ui.dock.is_open(panel)); } assert!(h.state().ui.toolbar_tools && h.state().ui.toolbar_docks); - h.get_by_label("Viewport").click(); + h.get_all_by_label("Viewport").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); h.run_steps(3); let quick = h.get_by_label_contains("Enable Quick Mask"); assert!(quick.accesskit_node().is_disabled()); diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index a8876e9e..62c305ea 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -75,6 +75,25 @@ fn a_canceled_dialog_changes_nothing() { assert_eq!(h.state().file_dialogs.pending(), 0); } +#[test] +fn the_sample_picker_asks_to_save_only_after_a_path_is_chosen() { + let mut h = harness(true); + answer(&mut h, |_| Answer::Cancelled); + invoke(&mut h, "project.sample"); + assert_eq!(h.state().file_dialogs.pending(), 1); + h.run_steps(3); + assert!(h.state().ui.windows.unsaved.is_none()); + assert!(h.state().session.modified); + + let path = PathBuf::from("chosen.tcraft"); + let selected = path.clone(); + answer(&mut h, move |_| Answer::Paths(vec![selected.clone()])); + invoke(&mut h, "project.sample"); + h.run_steps(3); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Open(path.display().to_string()))); + assert!(h.state().session.modified); +} + #[test] fn a_dialog_that_cannot_show_is_reported() { let mut h = harness(false); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1b212184..292ce136 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -201,6 +201,10 @@ Scripted runs (agents, recordings, tests) can set `TEXTURECRAFT_NO_PREFS` (any v neither reads nor overwrites the user's saved layout and settings: it starts from the defaults and keeps its state in a throwaway file. + + + + | Method | Params | Result | |---|---|---| | `ping` | | `"pong"` | @@ -217,13 +221,15 @@ keeps its state in a throwaway file. | `ui.reset` | | resets the panels, view layout, zoom and every other view setting at once, without the question the Reset UI menu item asks; settings and shortcuts stay | | `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | | `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back | -| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`, `BakingLog`, `MeshMapBakers`, `MeshMapSettings`, `CommonSettings`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | +| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`, `BakingLog`, `MeshMapBakers`, `BakeMaps`, `BakeSettings`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | | `ui.resize` | `{width, height}` | Sets the window's inner size in points (640–7680), leaving maximized state; for recordings and screenshots at a fixed size | | `debug.paintTest` | `{from: [x, y], to: [x, y], frames?: 120}` | Paints a straight stroke through the real frame loop (viewport pixels, one point per frame) for performance work | | `debug.frames` | | Frame timing since the last call (then cleared): `{frames, intervalMs, uiMs, syncMs, logicMs}` each `{avg, p95, max}`; `syncMs` is compositing plus display tile conversion, `logicMs` input, control requests and scripted strokes before the UI is built; `worst` breaks down the slowest frame; `strokeEnd` lists the frame that committed a `debug.paintTest` stroke and the one after it (null without one) | + + The empty-project menus keep Recent Projects openable with Clear disabled when the list is empty. `ui.recent.clear` clears that list. More Save Options is disabled until a project is open. Help > Shortcuts list opens Settings on its Shortcuts page. Window > Reset UI restores the From b57657438cd679852965287ca9a656b559a85623 Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 24 Nov 2026 09:05:50 +0100 Subject: [PATCH 082/153] Drop CodeRabbit's marker comments from the protocol doc Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 292ce136..45248e26 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -201,10 +201,6 @@ Scripted runs (agents, recordings, tests) can set `TEXTURECRAFT_NO_PREFS` (any v neither reads nor overwrites the user's saved layout and settings: it starts from the defaults and keeps its state in a throwaway file. - - - - | Method | Params | Result | |---|---|---| | `ping` | | `"pong"` | @@ -228,8 +224,6 @@ keeps its state in a throwaway file. | `debug.paintTest` | `{from: [x, y], to: [x, y], frames?: 120}` | Paints a straight stroke through the real frame loop (viewport pixels, one point per frame) for performance work | | `debug.frames` | | Frame timing since the last call (then cleared): `{frames, intervalMs, uiMs, syncMs, logicMs}` each `{avg, p95, max}`; `syncMs` is compositing plus display tile conversion, `logicMs` input, control requests and scripted strokes before the UI is built; `worst` breaks down the slowest frame; `strokeEnd` lists the frame that committed a `debug.paintTest` stroke and the one after it (null without one) | - - The empty-project menus keep Recent Projects openable with Clear disabled when the list is empty. `ui.recent.clear` clears that list. More Save Options is disabled until a project is open. Help > Shortcuts list opens Settings on its Shortcuts page. Window > Reset UI restores the From 039b4548675c0ad986f688b6b87379907c05db29 Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 24 Nov 2026 11:03:23 +0100 Subject: [PATCH 083/153] Keep the resizable Export window from widening itself every frame The Output templates and List of exports tabs size their columns from the window's width, and some of their rows are a little wider than the column. In the fixed-size window that overflow was clipped; in the resizable one it widened the window, the next frame's columns took the new width, and the window grew each frame until it ran off the screen, so clicks and hovers missed their controls (nine export tests failed). - The tab body lays out in a child area fixed to the body's rect, so an overflow is clipped as before and cannot widen the window. - Each output map card takes the column's width; it took the width the card before it left, so every card was 9 points wider than the last. - The input maps column is 210 points, wide enough for its naming-pattern row; at 170 its info icon was outside the window. - The Save template and Load UI Layout pickers keep the reference titles the tests check ("Save template", "Select a UI layout file."). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_templates.rs | 15 ++++++++++----- crates/ui-egui/src/export_window.rs | 19 +++++++++++++------ crates/ui-egui/src/windows.rs | 4 ++-- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 061c31cf..250de679 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -18,7 +18,10 @@ use crate::widgets::{chip, icon_button}; const ICON: f32 = 20.0; const LIST_WIDTH: f32 = 190.0; -const INPUTS_WIDTH: f32 = 170.0; +/// Width of the input maps column; its naming-pattern row (label, dropdown, info icon) needs about 210 +const INPUTS_WIDTH: f32 = 210.0; +/// Inner margin of an output map's card +const CARD_MARGIN: f32 = 6.0; const RENAME_ID: &str = "exp_rename"; /// The name "+" gives a new template, as in the reference const NEW_PRESET: &str = "new_export_preset"; @@ -629,9 +632,11 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(tr("No outputs yet: add one above, then drag input maps onto its channels.")).color(tokens.text_dim)); } ui.add_enabled_ui(editable, |ui| { + // Every card takes the column's width, not the width a wider card before it left + let card_width = ui.available_width(); for (map_index, map) in preset.maps.iter_mut().enumerate() { let file = preview.as_ref().ok().and_then(|names| names.get(map_index).cloned().flatten()); - changed |= output_card(ui, map_index, map_count, map, file.as_deref(), &mut action); + changed |= output_card(ui, card_width, map_index, map_count, map, file.as_deref(), &mut action); ui.add_space(4.0); } }); @@ -712,11 +717,11 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result, action: &mut Option) -> bool { +fn output_card(ui: &mut Ui, card_width: f32, mi: usize, n: usize, map: &mut MapSpec, file: Option<&str>, action: &mut Option) -> bool { let tk = Tokens::get(ui.ctx()); let mut changed = false; - egui::Frame::new().fill(tk.row).corner_radius(tk.radius).inner_margin(6.0).show(ui, |ui| { - ui.set_width(ui.available_width()); + egui::Frame::new().fill(tk.row).corner_radius(tk.radius).inner_margin(CARD_MARGIN).show(ui, |ui| { + ui.set_width((card_width - 2.0 * CARD_MARGIN).max(0.0)); ui.horizontal(|ui| { let width = ui.available_width() - 4.0 * (ICON + ui.spacing().item_spacing.x); changed |= ui diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index fc9e2f62..5c7f6780 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1355,17 +1355,24 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); ui.separator(); - let body_height = ui.available_height().max(0.0); - ui.allocate_ui_with_layout(vec2(ui.available_width(), body_height), egui::Layout::left_to_right(egui::Align::Min), |ui| { - ui.set_height(body_height); + let body = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), ui.available_height().max(0.0))); + + // The tabs size their columns from the body's width. A child that cannot widen the + // resizable window holds them, so an overflow is clipped instead of growing the window each frame + let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); + body_ui.shrink_clip_rect(body); + ui.advance_cursor_after_rect(body); + let ui = &mut body_ui; + 'tab: { + ui.set_height(body.height()); match app.ui.export.tab { 1 => { crate::export_templates::tab(app, ui, &presets); - return; + break 'tab; } 2 => { list_tab(app, ui); - return; + break 'tab; } _ => {} } @@ -1385,7 +1392,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { _ => global_page(app, ui, &presets), }); }); - }); + } }); }); }); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index d3e7d119..f9e8fa5c 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -452,7 +452,7 @@ pub fn save_layout(app: &mut TextureCraftApp, mode: crate::state::Mode) { #[cfg(not(target_arch = "wasm32"))] pub fn load_layout(app: &mut TextureCraftApp) { let dir = crate::user_dir("layouts"); - let dialog = FileDialog::open().title(tr("Load UI Layout")).filter(tr("UI layout"), &["json"]).directory(dir); + let dialog = FileDialog::open().title(tr("Select a UI layout file.")).filter(tr("UI layout"), &["json"]).directory(dir); app.ask_file(dialog, Bound::App, move |app, paths| { let Some(path) = paths.first() else { return }; let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|bytes| crate::mode_layout::ModeLayout::read(&bytes)).map(|layout| { @@ -481,7 +481,7 @@ pub(crate) fn template_name_of(file_name: &str) -> &str { #[cfg(not(target_arch = "wasm32"))] pub fn save_as_template(app: &mut TextureCraftApp) { let dir = app.session.templates.dir.clone().unwrap_or_else(|| crate::user_dir("templates")); - let dialog = in_save_folder(app, FileDialog::save().title(tr("Save As Template")).filter(tr("Project template"), &["json"]), dir); + let dialog = in_save_folder(app, FileDialog::save().title(tr("Save template")).filter(tr("Project template"), &["json"]), dir); app.ask_file(dialog, Bound::Project, |app, paths| { let Some(path) = paths.first() else { return }; From 87a00221ec3b2711221134468321ad084278622e Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:08 +0100 Subject: [PATCH 084/153] Export window: restore the #789 wording the main merge dropped Merging main (c6894cc6) resolved three conflicts in export_window.rs with main's text, undoing this PR's renames, so five ui-egui tests failed: - the console step after rendering is "Preparing textures writing" again (main had brought back "Saving texture files"); - the greyed checkbox is "Export shaders parameters" with its tooltip again (main had "Export shader settings"); - the now working Export USD asset checkbox keeps this PR's tooltip. Note for review: TextureCraft always writes the mesh, so its "References the original mesh if possible" part never applies. Tests from #788 that named strings this PR renames on purpose follow the rename, as the PR already did for the MaterialX tests: - export_usd_asset: "Restore the default export parameters" is now "Resets all settings to default values"; "Saved texture " is now "Writing texture on disk" (both the positive and the negative check, so neither turns vacuous); - side_panels: "Export shader settings" is now "Export shaders parameters". Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_window.rs | 13 +++++++++---- crates/ui-egui/tests/it/export_usd_asset.rs | 9 ++++++--- crates/ui-egui/tests/it/side_panels.rs | 2 +- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 177d5288..3e923404 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -387,7 +387,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); - let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; + let mut lines = vec![set(), ConsoleLine::Step(tr("Preparing textures writing").into())]; // The USD asset is no texture: it stays in the list of written files only for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); @@ -815,9 +815,14 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // The browser downloads the textures only, so it has no USD asset to add #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")).on_hover_text(tr("Package the mesh, materials and textures together as USD")); + ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")) + .on_hover_text(tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); #[cfg(target_arch = "wasm32")] - unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); + unavailable_checkbox( + ui, + tr("Export USD asset"), + tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise"), + ); // The MaterialX export sits below the USD one; the browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] @@ -826,7 +831,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs index 68f310df..c8d71ddd 100644 --- a/crates/ui-egui/tests/it/export_usd_asset.rs +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -132,8 +132,11 @@ fn the_console_lists_the_asset_as_a_file_but_not_as_a_saved_texture() { let console = &h.state().ui.export.console; assert!(console.iter().any(|line| matches!(line, ConsoleLine::Done(file) if file == "material_ball.usd")), "{console:?}"); - assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Saved texture material_ball")), "{console:?}"); - assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Saved texture "))), "the textures are still listed"); + assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Writing material_ball texture on disk")), "{console:?}"); + assert!( + console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Writing ") && text.ends_with(" texture on disk"))), + "the textures are still listed" + ); } #[test] @@ -179,7 +182,7 @@ fn restoring_the_default_parameters_unticks_export_usd_asset() { checkbox(&h).click(); h.run_steps(3); assert!(h.state().ui.export.usd_asset); - h.get_by_label("Restore the default export parameters").click(); + h.get_by_label("Resets all settings to default values").click(); h.run_steps(3); assert!(!h.state().ui.export.usd_asset); } diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index aab7c36d..5728889f 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -119,7 +119,7 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { } assert!(harness.query_by_label_contains("textures selected for export").is_some()); assert!(!says_not_available(&mut harness, "Export USD asset")); - assert!(says_not_available(&mut harness, "Export shader settings")); + assert!(says_not_available(&mut harness, "Export shaders parameters")); harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); From 5f4a25e0b122da394402d884c95bab0db83b784f Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:12 +0100 Subject: [PATCH 085/153] Export window: show keyboard focus on the tabs, list rows and console strip The window's drawn tabs, the Global settings row and the console's hide/resize strip take focus by Tab but drew nothing for it. They now draw a 2-point outline in the strong text colour when focused, apart from the accent of the selected tab or row and the hover fill. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_window.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3e923404..f8360ecb 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1503,7 +1503,10 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.separator(); ui.vertical(|ui| match app.ui.export.page { Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), - _ => global_page(app, ui, &presets), + // A short or narrow window scrolls the settings, so the footer and every control stay reachable + _ => { + egui::ScrollArea::both().id_salt("exp_global_scroll").auto_shrink([false; 2]).show(ui, |ui| global_page(app, ui, &presets)); + } }); }); ui.add_space(8.0); From c68e8f9959d36f043a46ca4ce4bd4b019d49968f Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:15 +0100 Subject: [PATCH 086/153] Export window: the Global settings page scrolls on short or narrow screens On a short screen the settings pushed the footer (Cancel, Export) out of the fixed-size window, and at an 800-point-wide screen the 728-point window cut off the right end of the value lists. The page now sits in a scroll area (both directions), as the texture set list already does. The new test at 800x480 fails without it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_window.rs | 14 +++++++++ .../tests/it/export_reference_texts.rs | 29 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index f8360ecb..316e4454 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -52,6 +52,8 @@ const LIST_ROW_HEIGHT: f32 = 24.0; const LIST_ROW_INDENT: f32 = 16.0; /// Width of the bottom bar's buttons, the same for all as in the reference const FOOTER_BUTTON_WIDTH: f32 = 126.0; +/// Width of the keyboard focus outline on the window's drawn controls +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -623,6 +625,15 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } +/// The keyboard focus outline of a drawn control: inside `response`'s rect, in the strong text +/// colour, so it differs from the accent of the selected one and the fill of the hovered one +fn paint_focus(ui: &Ui, response: &egui::Response) { + if response.has_focus() { + let stroke = egui::Stroke::new(FOCUS_OUTLINE_WIDTH, Tokens::get(ui.ctx()).text_strong); + ui.painter().rect_stroke(response.rect, 0.0, stroke, egui::StrokeKind::Inside); + } +} + /// A window tab: a box, lighter and with an accent line on top when open fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { let tokens = Tokens::get(ui.ctx()); @@ -642,6 +653,7 @@ fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); } painter.galley(rect.min + TAB_PADDING, galley, color); + paint_focus(ui, &response); response } @@ -889,6 +901,7 @@ fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { } let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); + paint_focus(ui, &response); response } @@ -1108,6 +1121,7 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; ui.painter().rect_filled(strip, 0.0, tk.chrome); ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); + paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 46dcd4b9..1c5d5c23 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -108,3 +108,32 @@ fn the_bottom_bar_buttons_share_one_width() { assert!(widths.windows(2).all(|pair| (pair[0] - pair[1]).abs() < 1.0), "{widths:?}"); } + +/// The Size list of the Global settings page +fn size_list<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_all_by_role(egui::Role::ComboBox) + .find(|list| list.accesskit_node().value().as_deref() == Some("Based on each Texture Set's size")) + .expect("the Size list") +} + +#[test] +fn on_a_short_narrow_screen_the_settings_scroll_and_the_footer_stays_in_view() { + let screen = egui::vec2(800.0, 480.0); + let mut h = harness(screen); + for label in ["Cancel", "Export"] { + let rect = window_button_rect(&h, label, screen.x); + assert!(rect.max.x <= screen.x && rect.max.y <= screen.y, "{label} {rect:?}"); + } + let export = window_button_rect(&h, "Export", screen.x); + + // The last setting and the right end of the value lists scroll into the window, above the footer + h.get_by_label("Color space").scroll_to_me(); + h.run_steps(4); + let color_space = h.get_by_label("Color space").rect(); + assert!(color_space.max.y < export.min.y, "Color space {color_space:?}, footer {export:?}"); + + size_list(&h).scroll_to_me(); + h.run_steps(4); + let size = size_list(&h).rect(); + assert!(size.max.x <= export.max.x, "Size {size:?}, window right end {}", export.max.x); +} From 1abb7bda344511935379ebb6d8d52dff33778b14 Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:17 +0100 Subject: [PATCH 087/153] Output templates: new output maps get a per texture set file name Create named new rows just "Grayscale", "RGB" or "RGB Alpha", so every texture set of a multi-set export planned the same file and the export was refused for the name clash. New rows now start with "$mesh_$textureSet_" (as the old "$mesh_$textureSet_Output" default did), followed by the reference's row name. The output_templates test that pinned the bare "RGB" checks the suffix and the set token instead. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_templates.rs | 5 ++++- crates/ui-egui/tests/it/output_templates.rs | 4 +++- docs/ui-parity.md | 3 ++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 0dd0d996..4a6fd523 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -167,6 +167,9 @@ const CREATE: [(&str, Layout, bool, &str); 5] = [ ("RGB+A", Layout::Rgba, false, "RGB Alpha"), ("R+G+B+A", Layout::Rgba, true, "RGB Alpha"), ]; +/// What a new output map's file name starts with, so each texture set (and mesh) writes a file +/// of its own; the reference's row name follows it +const NEW_MAP_PREFIX: &str = "$mesh_$textureSet_"; /// The swatch right-click menu's constants: (label, value) const CONSTANTS: [(&str, f32); 3] = [(n_("Black"), 0.0), (n_("Gray 50%"), 0.5), (n_("White"), 1.0)]; @@ -837,7 +840,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } let acted = match edit.action { Some(MapAction::Add(layout, split_rgb, file)) => { - let file = unique_file(&preset.maps, file); + let file = unique_file(&preset.maps, &format!("{NEW_MAP_PREFIX}{file}")); preset.maps.push(new_map(layout, &file)); origin.push(None); split.push(split_rgb); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index e8bb3af9..918bea96 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -501,7 +501,9 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv let mut h = harness(&library); click(&mut h, "RGB"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].file, "RGB", "the reference's name for a new RGB row"); + let file = &h.state().session.export_preset("Mine").unwrap().maps[last].file; + assert!(file.ends_with("_RGB"), "the reference's name for a new RGB row: {file}"); + assert!(file.contains("$textureSet"), "each texture set writes a file of its own: {file}"); last_window_button(&h, "RGB: Default black").click(); h.run_steps(4); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1d52846a..573bed16 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -351,7 +351,8 @@ that numbers hide once a tile is under 40 points on screen. $mesh, $textureSet, $udim, $uvTileName greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gr, RGB or R, G, B, then A), the file format ("File format") and bit depth ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". - Create names new rows "Grayscale", "RGB" and "RGB Alpha", with "_1", "_2" when taken. An + Create names new rows "Grayscale", "RGB" and "RGB Alpha" after "$mesh_$textureSet_", so the + texture sets of one export do not write the same file, with "_1", "_2" when taken. An empty swatch reads "Default black" ("Default white" for A), a filled one " ()", e.g. "Base color (Red)" or "Metallic (Grayscale)". Dropping a map on a swatch opens "From ": a gray map offers *Gray Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G From 0af0c0f46197323f06f11a06a04f2bab95a78464 Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 12:53:55 +0100 Subject: [PATCH 088/153] Export UI: TextureCraft's own wording instead of the reference's texts The export dock, Mesh Export Options and Export textures window keep the reference's layout, but their texts are now our own. Where main had a TextureCraft text for a control (footer tooltips, console lines, override menu, reset button, dilation hint, naming pattern info), it is back. New texts describe what TextureCraft does: the USD tooltip says the mesh is always written, the Mesh Export Options info tooltips say the mesh is always triangles and normals are not recomputed. The drop popup asks "Which part of ?", empty swatches read "Empty (writes black)", new rows are named after their layout (Gray, RGB, RGBA), and the map panes use TextureCraft's channel, bake and converted map names with OpenPBR parameter names for the inputs TextureCraft lacks. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_templates.rs | 92 +++++------ .../ui-egui/src/export_templates/map_lists.rs | 148 +++++------------- .../src/export_templates/source_pick.rs | 4 +- crates/ui-egui/src/export_window.rs | 58 +++---- crates/ui-egui/src/mesh_export_options.rs | 8 +- crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/state/console_line.rs | 2 +- .../ui-egui/tests/it/export_map_overrides.rs | 4 +- crates/ui-egui/tests/it/export_materialx.rs | 4 +- crates/ui-egui/tests/it/export_overrides.rs | 6 +- crates/ui-egui/tests/it/export_progress.rs | 18 +-- .../tests/it/export_reference_texts.rs | 22 +-- crates/ui-egui/tests/it/export_settings.rs | 4 +- crates/ui-egui/tests/it/export_usd_asset.rs | 9 +- crates/ui-egui/tests/it/output_templates.rs | 63 ++++---- crates/ui-egui/tests/it/side_panels.rs | 2 +- crates/ui-egui/tests/it/template_invert.rs | 6 +- 17 files changed, 190 insertions(+), 262 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 4a6fd523..9be85946 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -158,17 +158,17 @@ impl Layout { } } -/// The reference's Create buttons: (label, the layout the new output map gets, whether R, G and +/// The Create buttons: (label, the layout the new output map gets, whether R, G and /// B show as separate swatches, the new map's file name) const CREATE: [(&str, Layout, bool, &str); 5] = [ - (n_("Gray"), Layout::Gray, false, "Grayscale"), + (n_("Gray"), Layout::Gray, false, "Gray"), ("RGB", Layout::Rgb, false, "RGB"), ("R+G+B", Layout::Rgb, true, "RGB"), - ("RGB+A", Layout::Rgba, false, "RGB Alpha"), - ("R+G+B+A", Layout::Rgba, true, "RGB Alpha"), + ("RGB+A", Layout::Rgba, false, "RGBA"), + ("R+G+B+A", Layout::Rgba, true, "RGBA"), ]; /// What a new output map's file name starts with, so each texture set (and mesh) writes a file -/// of its own; the reference's row name follows it +/// of its own; the layout's name follows it const NEW_MAP_PREFIX: &str = "$mesh_$textureSet_"; /// The swatch right-click menu's constants: (label, value) @@ -392,8 +392,8 @@ pub fn select(app: &mut TextureCraftApp, name: String) { pub(crate) fn naming_pattern(ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { - ui.label(tr("Select the naming pattern used to display the input maps on this page.")); - ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); + ui.label(tr("Choose how the input maps are named in this editor.")); + ui.label(tr("The active texture set’s shader can affect the available map names.")); }); egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { for p in NAMING_PATTERNS { @@ -810,7 +810,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - ui.label(RichText::new(tr("Drag and drop maps on output's channels to setup your export.")).color(tokens.text_dim)); + ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); // Count only maps that have sources in the current set if let Ok(names) = &preview { @@ -1015,7 +1015,7 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the reference's file name variables, then TextureCraft's own ($channel) +/// The "$" button: the file name variables in the reference's order, then $channel fn token_menu(ui: &mut Ui, file: &mut String) -> bool { let mut changed = false; let menu = ui.menu_button("$", |ui| { @@ -1037,7 +1037,7 @@ fn token_menu(ui: &mut Ui, file: &mut String) -> bool { add(ui, token); } }); - menu.response.on_hover_text(tr("Add expressions in the path that will be replaced during export")); + menu.response.on_hover_text(tr("Insert a variable")); changed } @@ -1130,7 +1130,7 @@ fn swatch_targets(map: &MapSpec, split: bool) -> Vec { targets } -/// The letters on a swatch, as in the reference +/// The letters on a swatch fn target_label(target: ChannelTarget) -> &'static str { match target { ChannelTarget::Rgb => "RGB", @@ -1148,23 +1148,23 @@ fn source_of(map: &MapSpec, target: ChannelTarget) -> Option<&SourceRef> { map.channels.iter().find(|(d, _)| d == dest).map(|(_, s)| s) } -/// The choices of "From " in the reference order: "RGB Channels" only for a colour map on +/// The choices of the drop popup ("Which part of ?"): "Red, green and blue" only for a colour map on /// the RGB swatch; None marks a choice TextureCraft cannot read yet (a map's gray or alpha) fn source_choices(source: &SourceRef, target: ChannelTarget) -> Vec<(&'static str, Option)> { if source.components() != 3 { - return vec![(n_("Gray Channel"), Some(SourcePick::Component(0))), (n_("A Channel"), None)]; + return vec![(n_("Gray value"), Some(SourcePick::Component(0))), (n_("Alpha channel"), None)]; } let mut choices = Vec::new(); if target == ChannelTarget::Rgb { - choices.push((n_("RGB Channels"), Some(SourcePick::AllRgb))); + choices.push((n_("Red, green and blue"), Some(SourcePick::AllRgb))); } choices.extend([ - (n_("Gray Channel"), None), - (n_("R Channel"), Some(SourcePick::Component(0))), - (n_("G Channel"), Some(SourcePick::Component(1))), - (n_("B Channel"), Some(SourcePick::Component(2))), - (n_("A Channel"), None), + (n_("Gray value"), None), + (n_("Red channel"), Some(SourcePick::Component(0))), + (n_("Green channel"), Some(SourcePick::Component(1))), + (n_("Blue channel"), Some(SourcePick::Component(2))), + (n_("Alpha channel"), None), ]); choices } @@ -1184,10 +1184,10 @@ fn apply_pick(map: &mut MapSpec, target: ChannelTarget, source: &SourceRef, pick } } -/// The channel of the source a swatch reads, as the reference's swatch tooltip names it +/// The part of its source a swatch reads, as its tooltip names it fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> &'static str { if source.components() != 3 { - return n_("Grayscale"); + return n_("gray value"); } if target == ChannelTarget::Rgb && rgb_spread(map) { @@ -1195,23 +1195,23 @@ fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) - } match component_of(source) { - 0 => n_("Red"), - 1 => n_("Green"), - _ => n_("Blue"), + 0 => n_("red channel"), + 1 => n_("green channel"), + _ => n_("blue channel"), } } -/// A swatch's tooltip in the reference's words: "Default black" or "Default white" when empty, -/// else " ()"; another constant (TextureCraft's own) gives its value +/// A swatch's tooltip: "Empty (writes black)" ("Empty (writes white)" for alpha) when empty, +/// else ", "; another constant (TextureCraft's own) gives its value fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> String { let alpha = target == ChannelTarget::One(Dest::A); match source { - SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Default white").to_string(), - SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Default black").to_string(), + SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Empty (writes white)").to_string(), + SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Empty (writes black)").to_string(), SourceRef::Constant(value) => trf("Constant {value}", &[("value", &format!("{value:.2}"))]), _ => { let name = map_lists::name_of(source).map_or_else(String::new, |name| tr(name).to_string()); - trf("{map} ({channel})", &[("map", &name), ("channel", &tr(read_channel_name(map, source, target)))]) + trf("{map}, {channel}", &[("map", &name), ("channel", &tr(read_channel_name(map, source, target)))]) } } } @@ -1243,7 +1243,7 @@ fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: } /// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Split/Collapse RGB on R, G, B), a right click TextureCraft's own tools. +/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; @@ -1286,8 +1286,8 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo // Collapsing would drop maps that R, G and B read differently let mut checked = shows_split; let can_toggle = !shows_split || rgb_one_map(map); - let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Split/Collapse RGB"))); - let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to collapse")); + let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Separate R, G and B"))); + let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to join them")); if item.changed() { changed |= split_or_collapse(map, split, shows_split); } @@ -1381,7 +1381,7 @@ fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Resp response } -/// Clear channel: the swatch is empty again ("Default black", "Default white" for alpha), not +/// Clear channel: the swatch is empty again ("Empty (writes black)", white for alpha), not /// inverted fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { for (dest, source) in &mut map.channels { @@ -1392,7 +1392,7 @@ fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { map.inverted.retain(|dest| !target.dests().contains(dest)); } -/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones that read one map collapse +/// Separate R, G and B: the RGB swatch splits into R, G and B; split ones that read one map collapse /// into one RGB swatch reading that map's R, G and B. R, G and B reading different maps stay split, /// so no map is dropped. True when the map changed. fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> bool { @@ -1419,7 +1419,7 @@ fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> true } -/// "From ": which channel of the dropped map the swatch reads; Escape or a click elsewhere +/// The drop popup ("Which part of ?"): which channel of the dropped map the swatch reads; Escape or a click elsewhere /// assigns nothing. True when the map changed. fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec]) -> bool { let Some(waiting) = pending.clone() else { return false }; @@ -1437,7 +1437,7 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ .open(true) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { - ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); + ui.label(RichText::new(trf("Which part of {map}?", &[("map", &name)])).strong()); for (label, pick) in source_choices(&waiting.source, waiting.target) { match pick { Some(pick) => { @@ -1642,19 +1642,19 @@ mod tests { let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); assert_eq!(map.channels, cleared); assert!(map.inverted.is_empty(), "a cleared channel writes its default, not its inverse"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Default black"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Default white"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Empty (writes black)"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Empty (writes white)"); } #[test] - fn the_from_popup_offers_the_reference_choices() { + fn the_drop_popup_offers_the_parts_of_the_map_the_swatch_can_take() { let offered = |source: &SourceRef, target| source_choices(source, target).into_iter().map(|(label, pick)| (label, pick.is_some())).collect::>(); - assert_eq!(offered(&ch(Channel::Metallic, 0), ChannelTarget::Rgb), [("Gray Channel", true), ("A Channel", false)]); - let color_on_gray = [("Gray Channel", false), ("R Channel", true), ("G Channel", true), ("B Channel", true), ("A Channel", false)]; + assert_eq!(offered(&ch(Channel::Metallic, 0), ChannelTarget::Rgb), [("Gray value", true), ("Alpha channel", false)]); + let color_on_gray = [("Gray value", false), ("Red channel", true), ("Green channel", true), ("Blue channel", true), ("Alpha channel", false)]; assert_eq!(offered(&ch(Channel::BaseColor, 0), ChannelTarget::One(Dest::L)), color_on_gray); let color_on_rgb = offered(&ch(Channel::BaseColor, 0), ChannelTarget::Rgb); - assert_eq!(color_on_rgb.first(), Some(&("RGB Channels", true)), "only the RGB swatch offers RGB Channels"); + assert_eq!(color_on_rgb.first(), Some(&("Red, green and blue", true)), "only the RGB swatch offers all three"); assert_eq!(color_on_rgb.get(1..), Some(color_on_gray.as_slice())); } @@ -1664,18 +1664,18 @@ mod tests { apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::AllRgb); assert!(rgb_spread(&map)); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (RGB)"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, RGB"); apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::Component(0)); assert_eq!(swatch_targets(&map, false), vec![ChannelTarget::Rgb], "R of one map in R, G and B stays one swatch"); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (Red)"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, red channel"); } #[test] - fn new_rows_take_the_reference_names_with_a_number_when_taken() { + fn new_rows_take_their_layout_name_with_a_number_when_taken() { let maps = vec![new_map(Layout::Rgb, "RGB"), new_map(Layout::Rgb, "RGB_1")]; - assert_eq!(unique_file(&maps, "Grayscale"), "Grayscale"); + assert_eq!(unique_file(&maps, "Gray"), "Gray"); assert_eq!(unique_file(&maps, "RGB"), "RGB_2"); } } diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index afe9e2aa..f190370c 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -1,6 +1,6 @@ -//! The maps the Output templates tab lists for dragging onto output channels, with the reference's -//! names (naming pattern OpenPBR). An entry without a source names a map TextureCraft does not -//! have yet; it is listed greyed. +//! The maps the Output templates tab lists for dragging onto output channels. Maps TextureCraft +//! has carry its own names; the input maps it does not have yet carry OpenPBR parameter names +//! (OpenPBR Surface specification, Academy Software Foundation) and are listed greyed. use std::sync::LazyLock; @@ -15,137 +15,63 @@ pub type MapEntry = (&'static str, Option); /// A group of the Input maps pane: its name and entries. pub type MapGroup = (&'static str, Vec); -fn channel(channel: Channel) -> Option { - Some(SourceRef::Channel { channel, component: 0 }) +/// A TextureCraft channel, under its own name +fn channel(channel: Channel) -> MapEntry { + (channel.label(), Some(SourceRef::Channel { channel, component: 0 })) } -fn converted(map: VirtualMap) -> Option { - Some(SourceRef::Virtual { map, component: 0 }) +/// An OpenPBR input TextureCraft has no channel for yet +fn missing(name: &'static str) -> MapEntry { + (name, None) } -fn mesh(map: BakedMap) -> Option { - Some(SourceRef::Baked { map, component: 0 }) -} - -/// The reference's user channels, listed greyed: TextureCraft has no user channels yet -const USER_CHANNELS: [&str; 32] = [ - "User0", "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10", "User11", "User12", "User13", "User14", "User15", - "User16", "User17", "User18", "User19", "User20", "User21", "User22", "User23", "User24", "User25", "User26", "User27", "User28", "User29", "User30", - "User31", -]; - -/// Input maps in the reference's groups and order (naming pattern OpenPBR); entries without a -/// TextureCraft channel are listed greyed. +/// Input maps in the OpenPBR parameter groups, then TextureCraft's channels outside OpenPBR pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ - ( - n_("Base"), - vec![ - (n_("Base weight"), None), - (n_("Base color"), channel(Channel::BaseColor)), - (n_("Metallic"), channel(Channel::Metallic)), - (n_("Base diffuse roughness"), None), - ], - ), + (n_("Base"), vec![missing(n_("Base weight")), channel(Channel::BaseColor), channel(Channel::Metallic), missing(n_("Base diffuse roughness"))]), ( n_("Specular"), vec![ - (n_("Specular weight"), None), - (n_("Specular edge color"), None), - (n_("Roughness"), channel(Channel::Roughness)), - (n_("Specular level"), channel(Channel::SpecularLevel)), - (n_("Anisotropy level"), channel(Channel::AnisotropyLevel)), - (n_("Anisotropy angle"), channel(Channel::AnisotropyAngle)), + missing(n_("Specular weight")), + missing(n_("Specular color")), + channel(Channel::Roughness), + channel(Channel::SpecularLevel), + channel(Channel::AnisotropyLevel), + channel(Channel::AnisotropyAngle), ], ), - (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Absorption color"), None)]), - (n_("Subsurface"), vec![(n_("Translucency"), None), (n_("Scattering color"), None), (n_("Scattering"), channel(Channel::ScatterWeight))]), + (n_("Transmission"), vec![channel(Channel::Transmission), missing(n_("Transmission color"))]), + (n_("Subsurface"), vec![channel(Channel::ScatterWeight), missing(n_("Subsurface color")), missing(n_("Subsurface radius"))]), ( n_("Coat"), vec![ - (n_("Coat opacity"), channel(Channel::CoatWeight)), - (n_("Coat color"), None), - (n_("Coat roughness"), channel(Channel::CoatRoughness)), - (n_("Coat anisotropy"), None), - (n_("Coat specular level"), None), - (n_("Coat normal"), channel(Channel::CoatNormal)), - (n_("Coat tangent"), None), + channel(Channel::CoatWeight), + missing(n_("Coat color")), + channel(Channel::CoatRoughness), + missing(n_("Coat roughness anisotropy")), + missing(n_("Coat IOR")), + channel(Channel::CoatNormal), + missing(n_("Coat tangent")), ], ), - ( - n_("Fuzz/Sheen"), - vec![ - (n_("Sheen opacity"), channel(Channel::SheenWeight)), - (n_("Sheen color"), channel(Channel::SheenColor)), - (n_("Sheen roughness"), channel(Channel::SheenRoughness)), - ], - ), - (n_("Emission"), vec![(n_("Emissive"), channel(Channel::Emissive))]), - (n_("Thin-film"), vec![(n_("Thin-film weight"), None)]), + (n_("Sheen"), vec![channel(Channel::SheenWeight), channel(Channel::SheenColor), channel(Channel::SheenRoughness)]), + (n_("Emission"), vec![channel(Channel::Emissive)]), + (n_("Thin film"), vec![missing(n_("Thin film weight")), missing(n_("Thin film thickness"))]), ( n_("Geometry"), - vec![ - (n_("Opacity"), channel(Channel::Opacity)), - (n_("Height"), channel(Channel::Height)), - (n_("Normal"), channel(Channel::Normal)), - (n_("Tangent"), None), - (n_("Ambient occlusion"), channel(Channel::AmbientOcclusion)), - ], + vec![channel(Channel::Opacity), channel(Channel::Height), channel(Channel::Normal), missing(n_("Tangent")), channel(Channel::AmbientOcclusion)], ), - ( - n_("Miscellaneous"), - vec![ - (n_("Blending mask"), None), - (n_("Diffuse"), None), - (n_("Displacement"), None), - (n_("Glossiness"), channel(Channel::Glossiness)), - ("Ior", None), - (n_("Reflection"), None), - (n_("Specular"), channel(Channel::Specular)), - (n_("Transmissive"), None), - ], - ), - (n_("User Channels"), USER_CHANNELS.iter().map(|name| (*name, None)).collect()), + (n_("Other"), vec![channel(Channel::Glossiness), channel(Channel::Specular)]), ] }); -/// Mesh maps, in the reference order and case. -pub static MESH_MAPS: LazyLock> = LazyLock::new(|| { - vec![ - (n_("Normal"), mesh(BakedMap::Normal)), - (n_("World space normal"), mesh(BakedMap::WorldNormal)), - (n_("ID"), mesh(BakedMap::Id)), - (n_("Ambient occlusion"), mesh(BakedMap::AmbientOcclusion)), - (n_("Curvature"), mesh(BakedMap::Curvature)), - (n_("Position"), mesh(BakedMap::Position)), - (n_("Thickness"), mesh(BakedMap::Thickness)), - (n_("Height"), mesh(BakedMap::Height)), - (n_("Bent normals"), mesh(BakedMap::BentNormal)), - (n_("Opacity"), mesh(BakedMap::Opacity)), - ] -}); +/// Mesh maps, under the names the bake panel gives them. +pub static MESH_MAPS: LazyLock> = + LazyLock::new(|| BakedMap::ALL.iter().map(|&map| (crate::i18n::baked_map_label(map), Some(SourceRef::Baked { map, component: 0 }))).collect()); -/// Converted maps in the reference order, then the ones only TextureCraft has (built-in templates use them). -pub static CONVERTED_MAPS: LazyLock> = LazyLock::new(|| { - vec![ - ("1/ior", None), - (n_("Mixed AO"), converted(VirtualMap::AoMixed)), - (n_("Diffuse"), None), - ("f0", converted(VirtualMap::F0)), - (n_("Glossiness"), converted(VirtualMap::Glossiness)), - (n_("Glossiness²"), None), - (n_("Normal DirectX"), converted(VirtualMap::NormalDirectX)), - (n_("Normal OpenGL"), converted(VirtualMap::NormalOpenGl)), - (n_("Reflection"), None), - (n_("Specular"), None), - ("Unity4 Diffuse", None), - ("Unity4 Gloss", None), - (n_("2D View"), None), - (VirtualMap::HeightNormal.label(), converted(VirtualMap::HeightNormal)), - (VirtualMap::Roughness.label(), converted(VirtualMap::Roughness)), - (VirtualMap::SheenTint.label(), converted(VirtualMap::SheenTint)), - ] -}); +/// Converted maps: the maps TextureCraft computes from others when it exports. +pub static CONVERTED_MAPS: LazyLock> = + LazyLock::new(|| VirtualMap::ALL.iter().map(|&map| (map.label(), Some(SourceRef::Virtual { map, component: 0 }))).collect()); /// The listed name of `source` (any component), or None for a constant. pub fn name_of(source: &SourceRef) -> Option<&'static str> { diff --git a/crates/ui-egui/src/export_templates/source_pick.rs b/crates/ui-egui/src/export_templates/source_pick.rs index 89dc4769..f3bbd650 100644 --- a/crates/ui-egui/src/export_templates/source_pick.rs +++ b/crates/ui-egui/src/export_templates/source_pick.rs @@ -1,7 +1,7 @@ -/// What a "From " choice reads from the dropped map. +/// What a choice of the drop popup ("Which part of ?") reads from the dropped map. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum SourcePick { - /// "RGB Channels": the map's R, G and B into the swatch's R, G and B. + /// "Red, green and blue": the map's R, G and B into the swatch's R, G and B. AllRgb, /// One component of the map in every channel of the swatch. Component(u8), diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 316e4454..246d32c2 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -205,7 +205,7 @@ fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, b ui.add_enabled(false, egui::Button::selectable(false, *name)).on_disabled_hover_text(tr(NOT_AVAILABLE)); } } - ui.separator().on_hover_text(tr("This preset is not available for the current project")); + ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); for name in rest { changed |= ui.selectable_value(current, name.clone(), name).on_hover_text(name).changed(); } @@ -269,7 +269,7 @@ fn start_export(app: &mut TextureCraftApp) { let e = &mut app.ui.export; e.tab = 2; - e.console = vec![ConsoleLine::Step(tr("Preparing export...").into())]; + e.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; if let Some(error) = error { e.console.push(ConsoleLine::Step(error.clone())); app.toast(error, true); @@ -315,7 +315,7 @@ fn start_export(app: &mut TextureCraftApp) { crate::web_files::export_textures(app, &jobs); } -/// Write the next texture set of the running export, logging the steps as the reference does; +/// Write the next texture set of the running export, logging each step; /// the last one finishes the export. A failed command (its error already shown) stops it. fn export_step(app: &mut TextureCraftApp, frame: u64) { let Some(job) = app.ui.export.job.as_mut() else { return }; @@ -327,14 +327,14 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { if job.pending.is_empty() { let written = std::mem::take(&mut job.written); let console = &mut app.ui.export.console; - console.push(ConsoleLine::Step(tr("Bitmaps write finalization...").into())); + console.push(ConsoleLine::Step(tr("All selected texture sets processed").into())); if written.is_empty() { console.push(ConsoleLine::Step(tr("No files were written").into())); } else { console.extend([ - ConsoleLine::Step(tr("Finalizing export...").into()), - ConsoleLine::Done(tr("Export successfully finished").into()), - ConsoleLine::Done(tr("Successfully exported:").into()), + ConsoleLine::Step(tr("Collecting the exported files").into()), + ConsoleLine::Done(tr("Texture export complete").into()), + ConsoleLine::Done(tr("Files saved").into()), ]); console.extend(written.into_iter().map(ConsoleLine::Done)); } @@ -360,7 +360,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } let set = || ConsoleLine::Set(name.clone()); - app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Computing textures results").into())]); + app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); // Protect concrete files and UDIM references from earlier texture sets if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) { @@ -389,12 +389,12 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); - let mut lines = vec![set(), ConsoleLine::Step(tr("Preparing textures writing").into())]; + let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; // The USD asset is no texture: it stays in the list of written files only for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); - lines.push(ConsoleLine::Step(trf("Writing {file} texture on disk", &[("file", &stem)]))); + lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); } // The export's warnings go to the console and the log, each once per export @@ -411,7 +411,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { lines.push(ConsoleLine::Step(trf("Warning: {message}", &[("message", &warning)]))); } - lines.extend([set(), ConsoleLine::Step(tr("Finalizing textures writing").into())]); + lines.extend([set(), ConsoleLine::Step(tr("Finished writing this texture set").into())]); app.ui.export.console.extend(lines); if let Some(job) = app.ui.export.job.as_mut() { job.written.extend(files); @@ -573,7 +573,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { } } ui.separator(); - for (i, label) in [tr("Enable override for all items"), tr("Disable override for all items")].into_iter().enumerate() { + for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { if ui.button(label).clicked() { menu = Some(3 + i); } @@ -735,11 +735,11 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { if enabled { r.response.on_hover_text(tr("Dilation in pixels")); } else { - r.response.on_disabled_hover_text(tr("Dilation cannot be applied to selected padding type")); + r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); } } -/// A greyed reference checkbox with its tooltip and the "not available" hint +/// A greyed checkbox with its tooltip and the "not available" hint fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { let mut off = false; ui.add_enabled(false, egui::Checkbox::new(&mut off, label)).on_disabled_hover_ui(|ui| { @@ -752,7 +752,7 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { let mut reset = false; header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Resets all settings to default values"), false, ICON).clicked(); + reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); }); if reset { let defaults = ExportUi::default(); @@ -828,12 +828,12 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // The browser downloads the textures only, so it has no USD asset to add #[cfg(not(target_arch = "wasm32"))] ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")) - .on_hover_text(tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); + .on_hover_text(tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures")); #[cfg(target_arch = "wasm32")] unavailable_checkbox( ui, tr("Export USD asset"), - tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise"), + tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"), ); // The MaterialX export sits below the USD one; the browser downloads the textures only @@ -843,7 +843,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); + unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; @@ -997,10 +997,10 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor let mut all = None; header(ui, tr("General Export Parameters"), |ui| { list_menu(ui, |ui| { - if ui.button(tr("Enable override for all items")).clicked() { + if ui.button(tr("Override every item")).clicked() { all = Some(true); } - if ui.button(tr("Disable override for all items")).clicked() { + if ui.button(tr("Clear all overrides")).clicked() { all = Some(false); } ui.separator(); @@ -1158,9 +1158,9 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// "Exporting texture set ..." with the name in bold +/// "Texture set " with the name in bold fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { - let text = tr("Exporting texture set {set}..."); + let text = tr("Texture set {set}"); let (before, after) = text.split_once("{set}").unwrap_or((text, "")); let font = egui::TextStyle::Body.resolve(ui.style()); let plain = egui::TextFormat::simple(font.clone(), tk.text); @@ -1486,7 +1486,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } else if app.ui.export.tab == 1 { crate::export_templates::naming_pattern(ui); - } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { + } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { o.maps.values_mut().for_each(|m| m.enabled = true); @@ -1548,7 +1548,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { // Only on SETTINGS if app.ui.export.tab == 0 - && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() + && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() { // Keep ownership so Cancel can restore the opening settings let e = &mut app.ui.export; @@ -1558,16 +1558,20 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Nothing to write without a ticked texture set let any = !export_selection(app).is_empty() && !templates_tab; - if ui.add_enabled(any, footer_button(tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { + if ui + .add_enabled(any, footer_button(tr("Export"))) + .on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")) + .clicked() + { do_export = true; } // Saving closes the window without starting an export let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); - if save.on_hover_text(tr("Closes the export window and saves changes")).clicked() { + if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { app.ui.windows.export = false; } - if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { + if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { canceled = true; } if !templates_tab { diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 702589b3..d8bbdcbd 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -41,8 +41,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { true, tr("Apply triangulation"), &[ - tr("Triangulation converts all mesh polygons with more than 3 sides to triangles (but doesn't change the triangular ones)."), - tr("Choosing to apply triangulation for export avoids unexpected results when rendering the mesh in another application."), + tr("Splits every face with more than three corners into triangles; triangles stay as they are."), + tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."), ], ); ui.add_space(GROUP_GAP); @@ -52,8 +52,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { true, tr("Recompute vertex normals"), &[ - tr("Recomputing vertex normals is recommended if you don't plan on using the normal map in the target application."), - tr("Otherwise, keeping the original vertex normals is recommended if you plan on using the normal map in the target application."), + tr("Replaces the mesh's vertex normals with newly computed ones in the exported file."), + tr("TextureCraft cannot do this yet: it writes the vertex normals the mesh has in the project."), ], ); ui.add_space(8.0); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ce308b37..3da5244e 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -399,7 +399,7 @@ pub struct ExportUi { #[serde(skip, default = "default_console_width")] pub console_width: f32, /// Output templates tab: a map dropped on an output channel, waiting for the source channel - /// ("From "). + /// ("Which part of ?"). #[serde(skip)] pub pending_drop: Option, /// Output templates tab: the new name while renaming the selected preset. diff --git a/crates/ui-egui/src/state/console_line.rs b/crates/ui-egui/src/state/console_line.rs index 26baa2ce..196a5b60 100644 --- a/crates/ui-egui/src/state/console_line.rs +++ b/crates/ui-egui/src/state/console_line.rs @@ -2,7 +2,7 @@ #[derive(Clone, Debug, PartialEq)] pub enum ConsoleLine { Step(String), - /// "Exporting texture set ..." with the name in bold. + /// "Texture set " with the name in bold. Set(String), /// A success line, in green. Done(String), diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 45ce9297..937ce100 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -104,10 +104,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { assert!(h.query_by_label("*").is_some(), "the set is marked"); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Enable override for all items"); + click(&mut h, "Override every item"); assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Disable override for all items"); + click(&mut h, "Clear all overrides"); assert!(maps(&h).is_empty()); } diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 328078aa..829fc2d6 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -52,7 +52,7 @@ fn export_materialx_sits_directly_below_the_usd_option() { let (app_harness, _dir) = harness("order"); let usd = app_harness.get_by_label("Export USD asset").rect().min.y; let materialx = checkbox(&app_harness).rect().min.y; - let shaders = app_harness.get_by_label("Export shaders parameters").rect().min.y; + let shaders = app_harness.get_by_label("Export shader settings").rect().min.y; assert!(usd < materialx && materialx < shaders, "USD {usd}, MaterialX {materialx}, shaders {shaders}"); } @@ -171,7 +171,7 @@ fn restoring_the_default_parameters_unticks_export_materialx() { app_harness.run_steps(3); assert!(app_harness.state().ui.export.materialx); - app_harness.get_by_label("Resets all settings to default values").click(); + app_harness.get_by_label("Restore the default export parameters").click(); app_harness.run_steps(3); assert!(!app_harness.state().ui.export.materialx); } diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 2ca24b0d..9edb2ee5 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -117,14 +117,14 @@ fn the_header_menu_switches_every_override() { // The set list has the same menu button; the page header's is the second page_menu(&mut h); - click(&mut h, "Enable override for all items"); + click(&mut h, "Override every item"); let o = overrides(&h); assert!(o.preset.is_some() && o.file_type.is_some() && o.size.is_some() && o.padding.is_some(), "{o:?}"); // The default template writes 8- and 16-bit files: the override keeps them until a type is picked assert_eq!(o.file_type.unwrap().format, ""); page_menu(&mut h); - click(&mut h, "Disable override for all items"); + click(&mut h, "Clear all overrides"); assert!(h.state().ui.export.sets.is_empty()); } @@ -157,7 +157,7 @@ fn export_writes_each_set_with_its_overrides_and_cancel_drops_them() { h.run_steps(1); } h.run_steps(2); - let finished = h.state().ui.export.console.iter().any(|l| matches!(l, ConsoleLine::Done(t) if t == "Export successfully finished")); + let finished = h.state().ui.export.console.iter().any(|l| matches!(l, ConsoleLine::Done(t) if t == "Texture export complete")); assert!(h.state().ui.export.job.is_none() && finished, "the export finished"); let sets: Vec = h.state().session.doc.project.texture_sets.iter().map(|t| format!("_{}_", t.name)).collect(); let files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "png")).collect(); diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 5210742a..b46b84a1 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -34,7 +34,7 @@ fn console(h: &Harness<'_, TextureCraftApp>) -> Vec { .iter() .map(|l| match l { ConsoleLine::Step(t) | ConsoleLine::Done(t) => t.clone(), - ConsoleLine::Set(name) => format!("Exporting texture set {name}..."), + ConsoleLine::Set(name) => format!("Texture set {name}"), }) .collect() } @@ -48,7 +48,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { h.run_steps(1); assert!(h.query_by_label("Cancel Export").is_some()); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); - assert_eq!(console(&h).first().map(String::as_str), Some("Preparing export...")); + assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export")); for _ in 0..64 { if h.state().ui.export.job.is_none() { @@ -61,14 +61,14 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { assert!(h.state().ui.windows.export, "the window stays open"); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Cancel Export").is_none()); let lines = console(&h); - let set = format!("Exporting texture set {}...", sets[0]); + let set = format!("Texture set {}", sets[0]); let start = lines.iter().position(|l| *l == set).unwrap(); - assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Computing textures results".into(), set.clone(), "Preparing textures writing".into()]); - assert!(lines[start + 6].starts_with("Writing ") && lines[start + 6].ends_with(" texture on disk"), "{lines:?}"); + assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Rendering the selected maps".into(), set.clone(), "Saving texture files".into()]); + assert!(lines[start + 6].starts_with("Saved texture "), "{lines:?}"); let written: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); - let finished = lines.iter().position(|l| l == "Export successfully finished").unwrap(); - assert_eq!(&lines[finished - 3..finished], ["Finalizing textures writing", "Bitmaps write finalization...", "Finalizing export..."]); - assert_eq!(lines[finished + 1], "Successfully exported:"); + let finished = lines.iter().position(|l| l == "Texture export complete").unwrap(); + assert_eq!(&lines[finished - 3..finished], ["Finished writing this texture set", "All selected texture sets processed", "Collecting the exported files"]); + assert_eq!(lines[finished + 1], "Files saved"); assert_eq!(lines.len() - finished - 2, written.len(), "every written file is listed"); assert!(matches!(h.state().ui.export.console.last(), Some(ConsoleLine::Done(_))), "in green"); let _ = std::fs::remove_dir_all(&dir); @@ -113,7 +113,7 @@ fn cancel_export_stops_the_export() { assert!(h.state().ui.export.job.is_none()); assert!(h.state().ui.windows.export); let lines = console(&h); - assert!(!lines.iter().any(|l| l == "Finalizing export..." || l == "Export successfully finished"), "the export did not finish: {lines:?}"); + assert!(!lines.iter().any(|l| l == "Collecting the exported files" || l == "Texture export complete"), "the export did not finish: {lines:?}"); assert!(h.query_by_label("Cancel").is_some(), "the buttons are back"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 1c5d5c23..6dd4c494 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -1,5 +1,5 @@ -//! Export textures window (texturecraft #789): the reference's size, button tooltips and settings -//! texts, word for word. +//! Export textures window (texturecraft #789): the reference's size, and the tooltips of the bottom +//! bar's buttons and of the settings' checkboxes. use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; @@ -71,13 +71,13 @@ fn on_a_small_screen_the_window_fits_with_its_buttons_in_view() { } #[test] -fn the_buttons_carry_the_reference_tooltips() { +fn the_buttons_carry_tooltips_saying_what_they_do() { let mut h = harness(egui::vec2(1600.0, 960.0)); - tooltip_is(&mut h, "Include all", "Includes all Texture Sets, UV Tiles and output maps."); - tooltip_is(&mut h, "Reset all", "Resets all settings to their default values, including all textures."); - tooltip_is(&mut h, "Cancel", "Closes the export window and undoes all recent changes"); - tooltip_is(&mut h, "Save settings", "Closes the export window and saves changes"); - tooltip_is(&mut h, "Export", "Exports all selected textures and additional files"); + tooltip_is(&mut h, "Include all", "Select every texture set, UV tile and output map"); + tooltip_is(&mut h, "Reset all", "Restore the export defaults and select every texture"); + tooltip_is(&mut h, "Cancel", "Close the window and go back to the settings it opened with"); + tooltip_is(&mut h, "Save settings", "Keep these settings for the next export and close the window"); + tooltip_is(&mut h, "Export", "Write the selected textures, and the extra files ticked in the settings"); } /// Hover the checkbox `label` and check that its tooltip says `tooltip` @@ -90,14 +90,14 @@ fn checkbox_tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, toolti } #[test] -fn the_unavailable_checkboxes_carry_the_reference_texts() { +fn the_extra_file_checkboxes_carry_tooltips_saying_what_they_write() { let mut h = harness(egui::vec2(1600.0, 960.0)); checkbox_tooltip_is( &mut h, "Export USD asset", - "Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise", + "Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures", ); - checkbox_tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); + checkbox_tooltip_is(&mut h, "Export shader settings", "Save the settings of each shader instance in a JSON file"); } #[test] diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index afabdee1..98af3660 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -143,7 +143,7 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); - assert!(h.query_by_label("Dilation cannot be applied to selected padding type").is_some()); + assert!(h.query_by_label("This padding mode does not use a dilation width").is_some()); h.state_mut().ui.export.padding = "dilation".into(); h.run_steps(3); hover(&mut h, "16"); @@ -166,7 +166,7 @@ fn the_page_reset_puts_the_parameters_back() { e.padding = "none".into(); e.skip = vec![0]; h.run_steps(3); - click(&mut h, "Resets all settings to default values"); + click(&mut h, "Restore the default export parameters"); let e = &h.state().ui.export; assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs index c8d71ddd..68f310df 100644 --- a/crates/ui-egui/tests/it/export_usd_asset.rs +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -132,11 +132,8 @@ fn the_console_lists_the_asset_as_a_file_but_not_as_a_saved_texture() { let console = &h.state().ui.export.console; assert!(console.iter().any(|line| matches!(line, ConsoleLine::Done(file) if file == "material_ball.usd")), "{console:?}"); - assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Writing material_ball texture on disk")), "{console:?}"); - assert!( - console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Writing ") && text.ends_with(" texture on disk"))), - "the textures are still listed" - ); + assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Saved texture material_ball")), "{console:?}"); + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Saved texture "))), "the textures are still listed"); } #[test] @@ -182,7 +179,7 @@ fn restoring_the_default_parameters_unticks_export_usd_asset() { checkbox(&h).click(); h.run_steps(3); assert!(h.state().ui.export.usd_asset); - h.get_by_label("Resets all settings to default values").click(); + h.get_by_label("Restore the default export parameters").click(); h.run_steps(3); assert!(!h.state().ui.export.usd_asset); } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 918bea96..c063ca31 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -91,7 +91,7 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drag and drop maps on output's channels to setup your export."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { assert!(h.query_by_label(text).is_some(), "{text}"); } assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); @@ -109,8 +109,8 @@ fn the_tab_shows_the_preset_tools_and_map_editor() { let info = h.get_by_label(egui_phosphor::regular::INFO).rect().center(); h.hover_at(info); h.run_steps(30); - assert!(h.query_by_label("Select the naming pattern used to display the input maps on this page.").is_some()); - assert!(h.query_by_label("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.").is_some()); + assert!(h.query_by_label("Choose how the input maps are named in this editor.").is_some()); + assert!(h.query_by_label("The active texture set’s shader can affect the available map names.").is_some()); } #[test] @@ -376,7 +376,7 @@ fn the_presets_row_holds_copy_minus_and_plus_without_tooltips() { } #[test] -fn the_map_lists_stand_in_three_panes_with_the_reference_names() { +fn the_map_lists_stand_in_three_panes_with_their_groups_and_names() { let library = TemplateLibrary::new("panes"); let h = harness(&library); @@ -387,18 +387,19 @@ fn the_map_lists_stand_in_three_panes_with_the_reference_names() { assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); - for group in ["Transmission", "Subsurface", "Fuzz/Sheen", "Thin-film", "Miscellaneous", "User Channels"] { + for group in ["Transmission", "Subsurface", "Sheen", "Thin film", "Other"] { assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); } - for name in ["Specular level", "Sheen opacity", "Coat normal", "Emissive", "World space normal", "Bent normals", "Normal DirectX", "f0"] { + for name in ["Specular level", "Sheen weight", "Coat normal", "Emissive", "World Space Normal", "Bent Normals", "Normal DirectX", "F0 from specular level"] + { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); } - for name in ["Base weight", "Coat tangent", "Thin-film weight", "User31", "1/ior", "Glossiness²", "2D View"] { + for name in ["Base weight", "Coat tangent", "Thin film weight", "Subsurface radius"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); } - for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal", "Emission color", "Other"] { + for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "Emission color"] { assert!(h.query_by_label(gone).is_none(), "{gone}"); } } @@ -410,24 +411,24 @@ fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { click(&mut h, "R+G+B+A"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let green = last_window_button(&h, "G: Default black").rect().center(); + let green = last_window_button(&h, "G: Empty (writes black)").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, green); - assert!(h.query_by_label("From Base color").is_some(), "the popup names the dropped map"); - assert!(h.query_by_label("RGB Channels").is_none(), "only the RGB swatch offers RGB Channels"); - for choice in ["R Channel", "G Channel", "B Channel"] { + assert!(h.query_by_label("Which part of Base color?").is_some(), "the popup names the dropped map"); + assert!(h.query_by_label("Red, green and blue").is_none(), "only the RGB swatch offers all three"); + for choice in ["Red channel", "Green channel", "Blue channel"] { assert!(!h.get_by_label(choice).accesskit_node().is_disabled(), "{choice}"); } - for greyed in ["Gray Channel", "A Channel"] { + for greyed in ["Gray value", "Alpha channel"] { assert!(h.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed}"); } - h.get_by_label("B Channel").click(); + h.get_by_label("Blue channel").click(); h.run_steps(4); let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); assert!(map.channels.contains(&(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 2 })), "{:?}", map.channels); - assert!(h.query_by_label("From Base color").is_none(), "the popup closed"); - assert!(h.query_all_by_label("G: Base color (Blue)").next().is_some(), "the swatch names its map and channel"); + assert!(h.query_by_label("Which part of Base color?").is_none(), "the popup closed"); + assert!(h.query_all_by_label("G: Base color, blue channel").next().is_some(), "the swatch names its map and channel"); } #[test] @@ -437,15 +438,15 @@ fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { click(&mut h, "RGB+A"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let rgb = last_window_button(&h, "RGB: Default black").rect().center(); + let rgb = last_window_button(&h, "RGB: Empty (writes black)").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, rgb); - h.get_by_label("RGB Channels").click(); + h.get_by_label("Red, green and blue").click(); h.run_steps(4); let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); let spread: Vec<_> = (0..3).map(|component| SourceRef::Channel { channel: Channel::BaseColor, component }).collect(); assert_eq!(map.channels.iter().take(3).map(|(_, source)| source.clone()).collect::>(), spread); - assert!(h.query_all_by_label("RGB: Base color (RGB)").next().is_some()); + assert!(h.query_all_by_label("RGB: Base color, RGB").next().is_some()); } #[test] @@ -455,17 +456,17 @@ fn escape_closes_the_from_popup_without_assigning() { click(&mut h, "Gray"); let before = h.state().session.export_preset("Mine").unwrap(); - let gray = last_window_button(&h, "Gr: Default black").rect().center(); + let gray = last_window_button(&h, "Gr: Empty (writes black)").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, gray); - assert!(h.query_by_label("From Metallic").is_some()); - assert!(!h.get_by_label("Gray Channel").accesskit_node().is_disabled()); - assert!(h.get_by_label("A Channel").accesskit_node().is_disabled()); - assert!(h.query_by_label("R Channel").is_none(), "a gray map has no R, G or B"); + assert!(h.query_by_label("Which part of Metallic?").is_some()); + assert!(!h.get_by_label("Gray value").accesskit_node().is_disabled()); + assert!(h.get_by_label("Alpha channel").accesskit_node().is_disabled()); + assert!(h.query_by_label("Red channel").is_none(), "a gray map has no R, G or B"); h.key_press(egui::Key::Escape); h.run_steps(4); - assert!(h.query_by_label("From Metallic").is_none(), "Escape closes the popup"); + assert!(h.query_by_label("Which part of Metallic?").is_none(), "Escape closes the popup"); assert!(h.state().ui.export.pending_drop.is_none()); assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); } @@ -502,17 +503,17 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv click(&mut h, "RGB"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; let file = &h.state().session.export_preset("Mine").unwrap().maps[last].file; - assert!(file.ends_with("_RGB"), "the reference's name for a new RGB row: {file}"); + assert!(file.ends_with("_RGB"), "a new RGB row is named after its layout: {file}"); assert!(file.contains("$textureSet"), "each texture set writes a file of its own: {file}"); - last_window_button(&h, "RGB: Default black").click(); + last_window_button(&h, "RGB: Empty (writes black)").click(); h.run_steps(4); assert!(h.query_by_label("Clear channel").is_some()); - h.get_by_label("Split/Collapse RGB").click(); + h.get_by_label("Separate R, G and B").click(); h.run_steps(4); assert_eq!(h.state().ui.export.draft_split.get(last), Some(&true), "R, G and B show apart"); - let green = last_window_button(&h, "G: Default black"); + let green = last_window_button(&h, "G: Empty (writes black)"); let at = green.rect().center(); green.click_secondary(); h.run_steps(4); @@ -522,7 +523,7 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv invert.click(); h.run_steps(4); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); - assert!(h.query_all_by_label("G: Default black, inverted").next().is_some(), "the swatch says it is inverted"); + assert!(h.query_all_by_label("G: Empty (writes black), inverted").next().is_some(), "the swatch says it is inverted"); } #[test] @@ -544,7 +545,7 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { let input_maps = h.get_by_label("Input maps").rect(); let removes: Vec = h.get_all_by_label("Remove this output").map(|node| node.rect()).collect(); - let alpha = last_window_button(&h, "A: Default white").rect(); + let alpha = last_window_button(&h, "A: Empty (writes white)").rect(); assert!(!removes.is_empty()); for remove in removes { diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 5728889f..aab7c36d 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -119,7 +119,7 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { } assert!(harness.query_by_label_contains("textures selected for export").is_some()); assert!(!says_not_available(&mut harness, "Export USD asset")); - assert!(says_not_available(&mut harness, "Export shaders parameters")); + assert!(says_not_available(&mut harness, "Export shader settings")); harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs index be849be0..bdb1ee65 100644 --- a/crates/ui-egui/tests/it/template_invert.rs +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -67,11 +67,11 @@ fn invert_toggle_changes_the_saved_template() { assert!(saved(&h).is_empty()); // Three maps in R, G and B: one swatch per channel - for swatch in ["R: Roughness (Grayscale)", "G: Metallic (Grayscale)", "B: Constant 0.50"] { + for swatch in ["R: Roughness, gray value", "G: Metallic, gray value", "B: Constant 0.50"] { assert!(h.query_all_by_label(swatch).next().is_some(), "{swatch}"); } - toggle_invert(&mut h, "G: Metallic (Grayscale)"); + toggle_invert(&mut h, "G: Metallic, gray value"); assert_eq!(saved(&h), vec![Dest::G], "the second channel (G) is inverted"); - toggle_invert(&mut h, "G: Metallic (Grayscale), inverted"); + toggle_invert(&mut h, "G: Metallic, gray value, inverted"); assert!(saved(&h).is_empty(), "a second click turns it off"); } From 5103d2256a6d5a6e60b9be166f4e3ee155acf730 Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 12:53:55 +0100 Subject: [PATCH 089/153] ui-parity: describe the export UI's own wording Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 573bed16..bba5be33 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -281,17 +281,17 @@ that numbers hide once a tile is under 40 points on screen. - **SETTINGS** ([#671](https://github.com/storytold/texturecraft/issues/671)): the texture set list has the reference's menu (*Check all*, *Uncheck all*, *Invert all*); *General Export - Parameters* has its reset button ("Resets all settings to default values"). *Output directory* + Parameters* has its reset button ("Restore the default export parameters"). *Output directory* is a button showing the path (it opens the folder picker) with an *R* button ("Reset to default"). The template list starts with the reference's first group (TextureCraft has "Document channels + Normal + AO (No Alpha)", the new name of its default template, and "glTF PBR Metal Roughness"; the others are greyed with "Not available yet"; one entry names another - vendor's product and is left out), then a separator ("This preset is not available for the current project") and every other template sorted by name. File type lists "Based on output + vendor's product and is left out), then a separator ("Some templates in this list are unavailable") and every other template sorted by name. File type lists "Based on output template", then the types in the reference order and names ("targa", "jpeg", "tiff"). Size adds "Maximum size for all Texture Sets" and 128. Padding uses the reference order; the dilation width is a button with a "Dilation (pixels)" slider, greyed for paddings without a - width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry the - reference's tooltips word for word. The window is 1100 x 740 as in the reference + width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry + tooltips saying what they select, write, keep or restore. The window is 1100 x 740 as in the reference ([#789](https://github.com/storytold/texturecraft/issues/789)). Cancel, and closing the window, go back to the settings the window opened with; the window always opens on SETTINGS. @@ -299,8 +299,8 @@ that numbers hide once a tile is under 40 points on screen. on a texture set row shows its *General Export Parameters*: Output template, File type, Size and Padding with the inherited value as text (for example "1024x1024 (Texture Set size)"). The pencil button ("Enable override") turns a row into its list; a set with an override gets "*" - ("Override(s) active"). The header menu has *Enable override for all items* and *Disable - override for all items*. The template list leaves out the entries the reference leaves out + ("Override(s) active"). The header menu has *Override every item* and *Clear all + overrides*. The template list leaves out the entries the reference leaves out there; sizes read "128x128" ... "8192x8192". Export, the footer count and LIST OF EXPORTS use each set's own settings. Ticks and overrides belong to the project and follow each texture set by name (another project starts without them); renaming a template on OUTPUT TEMPLATES takes @@ -309,7 +309,7 @@ that numbers hide once a tile is under 40 points on screen. parameters, one row per map the set exports: a tick, the file name pattern (cut at the front with "…" when long, the whole pattern as tooltip), its own *Enable override* and the inherited "png 8 bits". An override gives the map its own file type and bit depth (`maps` of - `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Enable override for all items* and *Disable override for all items*; *Include all* ticks every map + `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Override every item* and *Clear all overrides*; *Include all* ticks every map again. The patterns are cut after 26 characters (the reference cuts by pixel width). - **File types** ([#672](https://github.com/storytold/texturecraft/issues/672)): File type lists bmp, jpeg, jng, pgm, png, targa, tiff, hdr, exr, j2k, jp2, webp, psd and sbsar; j2k, jp2 @@ -347,27 +347,27 @@ that numbers hide once a tile is under 40 points on screen. middle reads "Current preset: ", *Output maps* with *Create:* Gray, RGB, R+G+B, RGB+A, R+G+B+A on the same row, and a footer with drag-and-drop guidance and the number of output maps. Each output map is one row: a drag grip (drag it onto another row to move the map), the - file name, "$" ("Add expressions in the path that will be replaced during export": $project, + file name, "$" ("Insert a variable": $project, $mesh, $textureSet, $udim, $uvTileName greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gr, RGB or R, G, B, then A), the file format ("File format") and bit depth ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". - Create names new rows "Grayscale", "RGB" and "RGB Alpha" after "$mesh_$textureSet_", so the + Create names new rows "Gray", "RGB" and "RGBA" after "$mesh_$textureSet_", so the texture sets of one export do not write the same file, with "_1", "_2" when taken. An - empty swatch reads "Default black" ("Default white" for A), a filled one " ()", - e.g. "Base color (Red)" or "Metallic (Grayscale)". Dropping a map on a swatch opens "From ": - a gray map offers *Gray Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G - Channel*, *B Channel* and *A Channel*, on the RGB swatch first *RGB Channels*; Escape assigns + empty swatch's tooltip reads "Empty (writes black)" ("Empty (writes white)" for A), a filled one + ", ", e.g. "Base color, red channel" or "Metallic, gray value". Dropping a map on a + swatch asks "Which part of ?": a gray map offers *Gray value* and *Alpha channel*, a colour map + *Gray value*, *Red channel*, *Green channel*, *Blue channel* and *Alpha channel*, on the RGB swatch first *Red, green and blue*; Escape assigns nothing. TextureCraft cannot read a map's gray or alpha yet, so those choices are greyed. A - click on a swatch offers *Clear channel*, on RGB, R, G and B also *Split/Collapse RGB*; R, G - and B that read different maps cannot collapse (the item is greyed). The right side has the - *Input maps* pane in the reference's groups and names (Base ... Miscellaneous, User Channels), + click on a swatch offers *Clear channel*, on RGB, R, G and B also *Separate R, G and B*; R, G + and B that read different maps cannot be joined (the item is greyed). The right side has the + *Input maps* pane in the OpenPBR parameter groups (Base ... Geometry, then Other for + TextureCraft's channels outside OpenPBR), each map TextureCraft has under its own name, and a pane with *Mesh maps* above *Converted maps* (highlighted). Maps the selected template - uses get a square in their swatch's colour. Input and converted maps TextureCraft does not have - are greyed and cannot be dragged (the reference lists them all alike). TextureCraft keeps + uses get a square in their swatch's colour. OpenPBR inputs TextureCraft has no channel for + are greyed and cannot be dragged; *Converted maps* lists the maps TextureCraft computes. TextureCraft keeps some things the reference does not have, out of the way: Import and Export of template files at the end of a preset's right-click menu; a swatch's right-click menu with Invert (an inverted swatch has a corner mark), Black, Gray 50%, White, the constant's value and the map's layout (RGB, RGBA, Gray, Gray + A); *Move up* and *Move down* in the grip's right-click menu and the - arrow keys on a focused grip; the planned file name in the file name's tooltip; and three - converted maps of its own (Normal from height, Roughness from glossiness, Sheen color × weight) - after the reference's. Built-in templates stay read-only and deleting asks first. + arrow keys on a focused grip; the planned file name in the file name's tooltip; and + converted maps of its own such as Normal from height, Roughness from glossiness and Sheen color × weight. Built-in templates stay read-only and deleting asks first. From 471b21cb7dd876b263b046c441c56d7641bef117 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 090/153] Generator picker: the reference's names on orb thumbnails, swapping the kind in place Generators carry the reference app's names (Metal Edge Wear, Ambient Occlusion, Light, Position). The generator slot opens the shared resource picker with each kind rendered as a mask on the smart masks' preview orb, a die on seeded kinds, larger thumbnails and no current-item outline. Thin areas stays loadable but is no longer offered. effect.set {generator} swaps a generator's kind in place, keeping its position, blending and opacity. --- crates/core/src/layer.rs | 43 +++++++- crates/engine/src/mask_cmds.rs | 40 +++++++- crates/engine/src/orb_preview.rs | 45 ++++++++- crates/engine/tests/it/generator_swap.rs | 65 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 9 +- crates/ui-egui/src/generator_slot.rs | 50 ++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/preview_request.rs | 3 +- crates/ui-egui/src/preview_worker.rs | 4 +- crates/ui-egui/src/resource_picker.rs | 28 +++++- crates/ui-egui/src/resource_slot.rs | 68 +++++++++++++ crates/ui-egui/src/shelf.rs | 2 +- crates/ui-egui/src/shelf_preview.rs | 9 +- crates/ui-egui/src/thumbs.rs | 7 +- crates/ui-egui/src/tile_picture.rs | 4 +- crates/ui-egui/tests/it/generator_panel.rs | 8 +- crates/ui-egui/tests/it/generator_picker.rs | 103 ++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 19 files changed, 463 insertions(+), 29 deletions(-) create mode 100644 crates/engine/tests/it/generator_swap.rs create mode 100644 crates/ui-egui/src/generator_slot.rs create mode 100644 crates/ui-egui/src/resource_slot.rs create mode 100644 crates/ui-egui/tests/it/generator_picker.rs diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index e352bbc0..b3186d4d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -940,16 +940,39 @@ impl GeneratorKind { ]; pub fn label(self) -> &'static str { match self { - GeneratorKind::EdgeWear => "Mask Editor: Edge wear", + GeneratorKind::EdgeWear => "Metal Edge Wear", GeneratorKind::Dirt => "Dirt", GeneratorKind::ThinAreas => "Thin areas", GeneratorKind::Curvature => "Curvature", - GeneratorKind::AmbientOcclusion => "Ambient occlusion", - GeneratorKind::Position => "Position gradient", - GeneratorKind::Direction => "Light / direction", + GeneratorKind::AmbientOcclusion => "Ambient Occlusion", + GeneratorKind::Position => "Position", + GeneratorKind::Direction => "Light", } } + /// The name commands and saved projects use for this kind + pub fn id(self) -> &'static str { + match self { + GeneratorKind::EdgeWear => "EdgeWear", + GeneratorKind::Dirt => "Dirt", + GeneratorKind::ThinAreas => "ThinAreas", + GeneratorKind::Curvature => "Curvature", + GeneratorKind::AmbientOcclusion => "AmbientOcclusion", + GeneratorKind::Position => "Position", + GeneratorKind::Direction => "Direction", + } + } + + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks) + pub fn in_picker(self) -> bool { + self != GeneratorKind::ThinAreas + } + + /// Whether the kind's result depends on its seed + pub fn includes_randomness(self) -> bool { + matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt) + } + /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. pub fn inputs(self) -> &'static [BakedMap] { match self { @@ -962,7 +985,7 @@ impl GeneratorKind { pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); - GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s)) + GeneratorKind::ALL.into_iter().find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s)) } } @@ -2245,6 +2268,16 @@ mod tests { assert_eq!((not_finite.scale, not_finite.rotation), (1.0, 0.0)); } + #[test] + fn generator_ids_are_the_saved_names_and_parse_back() { + for kind in GeneratorKind::ALL { + assert_eq!(serde_json::to_value(kind).unwrap(), serde_json::json!(kind.id())); + assert_eq!(GeneratorKind::parse(kind.id()), Some(kind)); + assert_eq!(GeneratorKind::parse(kind.label()), Some(kind)); + } + assert!(!GeneratorKind::ThinAreas.in_picker(), "Thin areas only loads from saved projects and smart masks"); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 385447a0..8cf8deef 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -785,10 +785,17 @@ fn set(session: &mut Session, params: &Value) -> Result { }; let swaps_filter = swapped.is_some(); let id_map = crate::color_selection_cmds::id_map_param(session, params)?; + let swapped_generator = match strp(params, "generator") { + Some(kind) => swapped_generator_kind(session, effect, kind)?, + None => None, + }; let mesh = session.mesh.clone(); session.edit("Edit effect", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let Some(generator) = swapped_generator { + edited.kind = EffectKind::Generator(generator); + } if let Some((kind, label)) = swapped { if let EffectKind::Filter(old) = &edited.kind && (edited.name == old.label() || Some(edited.name.as_str()) == old.former_label()) @@ -939,6 +946,37 @@ fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { } } +/// A generator of kind `name` at its defaults to replace generator effect `effect`, or None when it is that kind already +fn swapped_generator_kind(s: &Session, effect: LayerId, name: &str) -> Result> { + const CMD: &str = "effect.set"; + let kind = GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`")))?; + match &s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?.1.kind { + EffectKind::Generator(current) if current.kind == kind => Ok(None), + EffectKind::Generator(current) => Ok(Some(swapped_kind(current, kind))), + other => Err(bad(CMD, format!("`generator` changes generator effects only, not {}", other.name().to_ascii_lowercase()))), + } +} + +/// `current` as a `kind` generator: the settings every kind shares and the inputs `kind` reads stay, its own controls start from `kind`'s defaults +fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { + let mut inputs = current.inputs.clone(); + inputs.retain(|map, _| kind.inputs().contains(map)); + Generator { + level: current.level, + softness: current.softness, + noise_amount: current.noise_amount, + noise_scale: current.noise_scale, + seed: current.seed, + offset: current.offset, + direction: current.direction, + invert: current.invert, + global: current.global, + resolution: current.resolution, + inputs, + ..Generator::new(kind) + } +} + /// 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/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index f29a247d..a0b701a4 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId}; +use texturecraft_core::{BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, LayerId, MaskBackground}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::primitives; use texturecraft_texel::TILE; @@ -14,7 +14,7 @@ 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}; +use crate::{EngineError, Result, Session, materials, smart_masks}; /// Bake resolution in texels; 256 loses the thin edge lines const TEXTURE_PX: u32 = 512; @@ -80,7 +80,26 @@ impl OrbPreview { 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(); + self.mask_pixels(size) + } + /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape + /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + // Each generator goes on the bare shape, not over the previous mask + (self.session.doc, self.session.selected) = self.bare.clone(); + let effects = vec![(EffectKind::Generator(Generator::new(kind)), BlendMode::Normal)]; + let mask = smart_masks::build_mask(&mut self.session.doc.project, MaskBackground::Black, effects); + self.session.doc.project.layer_mut(self.layer).ok()?.mask = Some(mask); + self.mask_pixels(size) + } + + /// Row-major `size²` pixels of the preview layer's current mask, with None outside the shape + fn mask_pixels(&mut self, size: usize) -> Option>> { let camera = camera_for(&mut self.cameras, &self.session, size)?; let values = self.session.mask_at(self.layer, &camera.texels)?; @@ -262,6 +281,28 @@ mod tests { assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); } + #[test] + fn generator_previews_render_on_the_orb_and_each_starts_from_the_bare_shape() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for kind in GeneratorKind::ALL { + let pixels = preview.generator(kind, size).unwrap_or_else(|| panic!("{kind:?}")); + assert_eq!(pixels.len(), size * size, "{kind:?}"); + assert!(pixels[0].is_none(), "{kind:?}: the corners are outside the shape"); + for pixel in pixels.iter().flatten() { + assert!((0.0..=1.0).contains(&pixel.mask) && pixel.normal.is_finite() && pixel.coverage > 0.0, "{kind:?}: {pixel:?}"); + } + } + + let (edges, dirt) = (preview.generator(GeneratorKind::EdgeWear, size).unwrap(), preview.generator(GeneratorKind::Dirt, size).unwrap()); + assert!(difference(&edges, &dirt) > 0.05, "edge wear and dirt differ: {}", difference(&edges, &dirt)); + + // A smart mask rendered in between leaves nothing behind + preview.mask("dirt_cavities", size).unwrap(); + assert_eq!(preview.generator(GeneratorKind::EdgeWear, size).unwrap(), edges); + assert!(preview.generator(GeneratorKind::EdgeWear, 0).is_none()); + } + #[test] fn smart_materials_render_on_the_orb_and_show_their_wear() { let size = 24; diff --git a/crates/engine/tests/it/generator_swap.rs b/crates/engine/tests/it/generator_swap.rs new file mode 100644 index 00000000..a91790d0 --- /dev/null +++ b/crates/engine/tests/it/generator_swap.rs @@ -0,0 +1,65 @@ +//! Swapping a generator effect's kind in place with `effect.set {generator}` + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BlendMode, EffectKind, Generator, GeneratorKind, LayerId}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + texturecraft_engine::sample_session(128, 64).unwrap() +} + +/// A fill layer whose black mask holds a filter, then a Dirt generator at half opacity, multiplied: (filter, generator) +fn masked(session: &mut Session) -> (u64, u64) { + execute(session, "layer.add.fill", &Value::Null).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + let filter = execute(session, "effect.add.filter", &json!({"filter": "invert"})).unwrap()["effect"].as_u64().unwrap(); + let generator = + execute(session, "effect.add.generator", &json!({"generator": "Dirt", "level": 0.9, "blend": "multiply"})).unwrap()["effect"].as_u64().unwrap(); + execute(session, "effect.set", &json!({"effect": generator, "opacity": 0.5})).unwrap(); + (filter, generator) +} + +fn effect_kind(session: &Session, effect: u64) -> EffectKind { + session.doc.project.effect(LayerId(effect)).unwrap().1.kind.clone() +} + +#[test] +fn another_kind_keeps_the_shared_settings_and_starts_its_own_controls_from_defaults() { + let mut session = session(); + let (_, generator) = masked(&mut session); + let (owner, _) = session.doc.project.effect(LayerId(generator)).unwrap(); + let position = |session: &Session| session.doc.project.layer(owner).unwrap().mask.as_ref().unwrap().effects.iter().position(|e| e.id.0 == generator); + let before = position(&session); + + execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "Curvature"})).unwrap(); + + let defaults = Generator::new(GeneratorKind::Curvature); + let EffectKind::Generator(curvature) = effect_kind(&session, generator) else { panic!("still a generator") }; + assert_eq!(curvature.kind, GeneratorKind::Curvature); + assert_eq!(curvature.level, 0.9, "keeps the shared settings"); + assert_eq!(curvature.detail, defaults.detail, "its own controls start from defaults"); + let (_, swapped) = session.doc.project.effect(LayerId(generator)).unwrap(); + assert_eq!((swapped.blend, swapped.opacity), (BlendMode::Multiply, 0.5), "keeps blending and opacity"); + assert_eq!(position(&session), before, "keeps its place in the mask"); +} + +#[test] +fn naming_the_current_kind_edits_the_generator_without_resetting_it() { + let mut session = session(); + let (_, generator) = masked(&mut session); + + execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "Dirt", "softness": 0.4})).unwrap(); + + let EffectKind::Generator(edited) = effect_kind(&session, generator) else { panic!("still a generator") }; + assert_eq!((edited.level, edited.softness), (0.9, 0.4)); +} + +#[test] +fn only_generator_effects_take_a_generator_kind() { + let mut session = session(); + let (filter, generator) = masked(&mut session); + + assert!(execute(&mut session, "effect.set", &json!({"effect": filter, "generator": "Curvature"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "nope"})).is_err()); + assert!(matches!(effect_kind(&session, filter), EffectKind::Filter(_)), "a refused swap changes nothing"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ce9f1614..bd56a597 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,6 +36,7 @@ mod filters; mod folder_contents; mod frame_selection; mod generator_inputs; +mod generator_swap; mod gradient_map; mod high_poly_missed; mod instances; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index bfd9742e..47bf6aa1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -22,14 +22,7 @@ const INPUT_TILE_ICON_SIZE: f32 = 16.0; /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = 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() && kind != generator.kind { - app.run("effect.set", json!({"effect": id, "generator": format!("{kind:?}")})); - } - } - }); + crate::generator_slot::show(app, ui, id, generator); section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); diff --git a/crates/ui-egui/src/generator_slot.rs b/crates/ui-egui/src/generator_slot.rs new file mode 100644 index 00000000..99c19557 --- /dev/null +++ b/crates/ui-egui/src/generator_slot.rs @@ -0,0 +1,50 @@ +//! The generator slot atop a generator's properties: its orb and name, opening a picker that swaps its kind + +use egui::{Sense, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{Generator, GeneratorKind}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::resource_slot::{ResourceSlot, SLOT_HEIGHT}; +use crate::tile_picture::TilePicture; + +/// The slot of generator effect `effect`: a pick runs `effect.set {generator}` +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, generator: &Generator) { + let ctx = ui.ctx().clone(); + let current = generator.kind; + let thumbnail = app.thumbs.generator(&ctx, current); + let name = tr(current.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)); + let popup = ui.make_persistent_id(("generator_picker", effect)); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + + let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); + let slot = ResourceSlot { highlighted, focused: response.has_focus(), thumbnail: thumbnail.as_ref(), caption: tr("Generator"), name }; + slot.paint(ui, rect); + + let tabs = || { + let mut items: Vec> = GeneratorKind::ALL + .into_iter() + .filter(|kind| kind.in_picker()) + .map(|kind| ResourcePickerItem { id: kind, label: tr(kind.label()).to_owned(), caption: None, picture: TilePicture::Generator(kind) }) + .collect(); + + // One kind of resource: one grid in name order, no group captions + items.sort_by_cached_key(|item| item.label.to_lowercase()); + vec![PickerTab { icon: ic::SPARKLE, name: tr("Generators"), groups: vec![PickerGroup { header: None, items }] }] + }; + let picked = resource_picker::show(&response, popup, &mut app.thumbs, Some(¤t), true, tabs); + if let Some(kind) = picked.filter(|kind| *kind != current) { + app.run("effect.set", json!({"effect": effect, "generator": kind.id()})); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..a8e83fce 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -45,6 +45,7 @@ mod folder_properties; pub mod fonts; mod frame_gizmo; mod generator_panel; +mod generator_slot; pub mod gpu; mod gray_slider; mod grid_tile; @@ -124,6 +125,7 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; +mod resource_slot; mod round_gizmo; mod running_bake; pub mod saved_search; diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 7797a7e3..71c925ea 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -19,11 +19,12 @@ pub struct PreviewRequest { } impl PreviewRequest { - /// Render the asset, baking the orb on first use for smart masks and smart materials + /// Render the asset, baking the orb on first use for smart masks, generators and smart materials /// Unknown assets and failed bakes return None pub fn render(&self, shape: &mut OrbShape) -> Option { match &self.preview { ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), + ShelfPreview::Generator(kind) => Some(mask_preview_image(self.size_px, &shape.get()?.generator(*kind, 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 e58901b4..57879c71 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -156,6 +156,7 @@ mod tests { use std::collections::HashMap; use std::time::{Duration, Instant}; + use texturecraft_engine::core::GeneratorKind; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -196,6 +197,7 @@ mod tests { ("unknown material", ShelfPreview::Material("nope")), ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), ("unknown mask", ShelfPreview::SmartMask("nope")), + ("generator", ShelfPreview::Generator(GeneratorKind::Dirt)), ("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")), ("unknown smart material", ShelfPreview::SmartMaterial("nope")), ]; @@ -217,7 +219,7 @@ mod tests { std::thread::sleep(Duration::from_millis(10)); } - for key in ["material", "mask", "smart material"] { + for key in ["material", "mask", "generator", "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}"); } diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 311d8049..8c970158 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -45,6 +45,11 @@ const LOADING_GLYPH_SIZE: f32 = 24.0; /// The loading glyph is fainter than the other glyphs: it stands in for a picture still coming const LOADING_GLYPH_OPACITY: f32 = 0.5; const GLYPH_SIZE: f32 = 22.0; +/// The randomness badge: a see-through dark disc at the picture's bottom-right corner holding a die +const BADGE_RADIUS: f32 = 7.0; +const BADGE_ICON_SIZE: f32 = 10.0; +const BADGE_DISC: Color32 = Color32::from_black_alpha(140); +const BADGE_ICON: Color32 = Color32::from_gray(228); /// The bright group header row and the dim sub-caption row const HEADER_HEIGHT: f32 = 24.0; @@ -389,6 +394,7 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz TilePicture::Alpha(alpha) => thumbs.alpha(ui.ctx(), alpha), TilePicture::Image(name, image) => Some(thumbs.image(ui.ctx(), name, image)), TilePicture::Procedural(kind) => thumbs.procedural(ui.ctx(), *kind), + TilePicture::Generator(kind) => thumbs.generator(ui.ctx(), *kind), TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, }; @@ -396,7 +402,15 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz (_, Some(texture)) => { egui::Image::from_texture((texture.id(), picture.size())).corner_radius(rounding).paint_at(ui, picture); } - (TilePicture::Material(_) | TilePicture::Filter(_) | TilePicture::Alpha(_) | TilePicture::Image(..) | TilePicture::Procedural(_), None) => { + ( + TilePicture::Material(_) + | TilePicture::Filter(_) + | TilePicture::Alpha(_) + | TilePicture::Image(..) + | TilePicture::Procedural(_) + | TilePicture::Generator(_), + None, + ) => { painter.text( picture.center(), Align2::CENTER_CENTER, @@ -418,11 +432,23 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz painter.text(picture.center(), Align2::CENTER_CENTER, ic::PLUS, FontId::proportional(IMPORT_GLYPH_SIZE), color); } } + if let TilePicture::Generator(kind) = &item.picture + && kind.includes_randomness() + { + randomness_badge(painter, picture); + } name_lines(ui, rect, &item.label, hovered || chosen, chosen); response } +/// A die on a see-through dark disc at `picture`'s bottom-right corner: the item's result depends on a random seed +fn randomness_badge(painter: &egui::Painter, picture: Rect) { + let center = picture.right_bottom() - vec2(BADGE_RADIUS, BADGE_RADIUS); + painter.circle_filled(center, BADGE_RADIUS, BADGE_DISC); + painter.text(center, Align2::CENTER_CENTER, ic::DICE_FIVE, FontId::proportional(BADGE_ICON_SIZE), BADGE_ICON); +} + /// The tile's name under its picture: whole words on the first line, the rest on a second, each cut with "…" when too long fn name_lines(ui: &Ui, rect: Rect, label: &str, bright: bool, bold: bool) { let tokens = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/resource_slot.rs b/crates/ui-egui/src/resource_slot.rs new file mode 100644 index 00000000..e814dd27 --- /dev/null +++ b/crates/ui-egui/src/resource_slot.rs @@ -0,0 +1,68 @@ +//! The box atop an effect's properties that names its resource and opens a picker: thumbnail, a caption over the name, a caret + +use egui::{Align2, FontId, Rect, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; + +use crate::theme::Tokens; +use crate::widgets::elided; + +/// The slot's height in points +pub(crate) 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; +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; +/// Gap between the slot and its keyboard focus outline +const FOCUS_MARGIN: f32 = 2.0; + +/// What the slot shows and how: highlighted while hovered or its picker is open, outlined while focused +pub(crate) struct ResourceSlot<'a> { + pub highlighted: bool, + pub focused: bool, + pub thumbnail: Option<&'a egui::TextureHandle>, + pub caption: &'a str, + pub name: &'a str, +} + +impl ResourceSlot<'_> { + /// Paints the slot into `rect` + pub(crate) fn paint(&self, ui: &Ui, rect: Rect) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let (fill, border) = if self.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 self.focused { + painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } + + if let Some(texture) = self.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); + } + + // 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 = [(self.caption, CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (self.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 self.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/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3416a106..bc34317f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,7 +646,7 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_)); + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | 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 diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 5d06f8e8..20491e3a 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::compose::ImageStore; -use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; @@ -28,6 +28,8 @@ pub enum ShelfPreview { SmartMaterial(&'static str), /// Smart mask rendering requires the worker's baked orb SmartMask(&'static str), + /// A mask generator at its defaults, rendered like a smart mask on the worker's baked orb + Generator(GeneratorKind), /// A library filter on a sample material on a sphere Filter(&'static str), /// A procedural pattern as a grayscale swatch @@ -72,6 +74,7 @@ impl ShelfPreview { ShelfPreview::Material(id) => format!("mat:{id}"), ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), + ShelfPreview::Generator(kind) => format!("generator:{kind:?}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), @@ -83,11 +86,11 @@ impl ShelfPreview { } /// Render a `size²` image; unknown assets return None - /// Smart masks and smart materials return None here because their bake belongs to the worker + /// Smart masks, generators 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(_) | ShelfPreview::SmartMaterial(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | 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)), diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 875ac6ae..e847359e 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -9,7 +9,7 @@ use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::Session; use texturecraft_engine::compose::{ImageRes, ImageStore}; -use texturecraft_engine::core::{BakedMap, ProceduralKind}; +use texturecraft_engine::core::{BakedMap, GeneratorKind, ProceduralKind}; use texturecraft_engine::paint::presets::BrushPreset; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; @@ -295,6 +295,11 @@ impl Thumbs { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } + /// Generator thumbnail on the smart masks' orb; None until the worker returns it + pub fn generator(&mut self, ctx: &egui::Context, kind: GeneratorKind) -> Option { + self.worker_rendered(ctx, ShelfPreview::Generator(kind), SPHERE_PX, false) + } + /// 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) diff --git a/crates/ui-egui/src/tile_picture.rs b/crates/ui-egui/src/tile_picture.rs index c3f7dc5b..d031e666 100644 --- a/crates/ui-egui/src/tile_picture.rs +++ b/crates/ui-egui/src/tile_picture.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use egui::Color32; use texturecraft_engine::compose::ImageRes; -use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; use texturecraft_engine::paint::alphas::LibraryAlpha; /// A tile's picture source. Previews are requested only when its tile is drawn. @@ -14,6 +14,8 @@ pub(crate) enum TilePicture { Alpha(&'static LibraryAlpha), Image(String, Arc), Procedural(ProceduralKind), + /// A mask generator at its defaults on the smart masks' orb, a die in its corner when a seed changes its result + Generator(GeneratorKind), Swatch(Color32), Glyph(&'static str), Import, diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 796051e8..b256f537 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -83,12 +83,12 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { } #[test] -fn changing_kind_in_the_panel_preserves_the_effect() { +fn picking_a_kind_in_the_panel_is_one_undo_step() { let (mut harness, effect) = harness(false); let history = harness.state().session.history_labels().len(); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Curvature")).unwrap().click(); - harness.run_steps(2); - harness.get_by_label("Dirt").click(); + harness.get_by_role_and_label(Role::ComboBox, "Curvature").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::ListBoxOption, "Dirt").click(); harness.run_steps(3); assert_eq!(generator(&harness, effect).kind, GeneratorKind::Dirt); diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs new file mode 100644 index 00000000..d6d31dd8 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -0,0 +1,103 @@ +//! The generator slot in Properties swaps a generator's kind through its picker + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, GeneratorKind, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with a Dirt generator in a fill layer's black mask, selected so Properties shows its slot +fn app_with_dirt() -> (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(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "Dirt"})).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 generator effect `effect` now +fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Option { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => Some(generator.kind), + _ => None, + } +} + +/// Clicks the Dirt slot, which opens its picker +fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(Role::ComboBox, "Dirt").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_generator_kind() { + let (mut harness, effect) = app_with_dirt(); + open_picker(&mut harness); + + harness.event(egui::Event::Text("curv".into())); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Light").count(), 0, "the search hides generators that don't match"); + + harness.get_by_label("Curvature").click(); + harness.run_steps(3); + + assert_eq!(kind(&harness, effect), Some(GeneratorKind::Curvature)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); +} + +#[test] +fn the_picker_leaves_thin_areas_out() { + let (mut harness, _) = app_with_dirt(); + open_picker(&mut harness); + + for kind in GeneratorKind::ALL { + let offered = harness.query_all_by_label(kind.label()).count() > 0; + assert_eq!(offered, kind.in_picker(), "{kind:?}"); + } +} + +#[test] +#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] +fn generator_picker_snapshots() { + let output = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "EdgeWear"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(LayerId(effect["effect"].as_u64().unwrap())); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(20); + harness.get_by_role_and_label(Role::ComboBox, "Metal Edge Wear").click(); + + // The orbs render on the preview worker: give it time to bake and answer + for _ in 0..60 { + harness.run_steps(5); + std::thread::sleep(std::time::Duration::from_millis(500)); + } + for (brightness, name) in + [(texturecraft_ui_egui::theme::Brightness::MediumDark, "generator-picker"), (texturecraft_ui_egui::theme::Brightness::Light, "generator-picker-light")] + { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap(); + } + + // The Assets shelf may show a Dirt resource too: the picker draws over it, last + harness.query_all_by_label("Dirt").last().expect("the picker offers Dirt").hover(); + for _ in 0..10 { + harness.run_steps(5); + std::thread::sleep(std::time::Duration::from_millis(300)); + } + harness.render().unwrap().save(output.join("generator-picker-hover.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 831a009a..43cf6140 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -39,6 +39,7 @@ mod filter_picker; mod folder_properties; mod frame_selection; mod generator_panel; +mod generator_picker; mod help_menu_664; mod history_panel; mod import_resources; From 606fa3210682a10e3377917f42d7645937cf6449 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 091/153] Generators: Metal Edge Wear, Dirt and Fiber Glass Edge Wear on the reference's wear controls The wear kinds take the reference app's controls (wear level and contrast, grunge amount and scale, triplanar, edges smoothness, ambient occlusion masking, curvature weight, edges masking), computed from curvature, its blurred levels, ambient occlusion and a grunge pattern of our own per kind. Fiber Glass Edge Wear is a new kind. Generators saved before keep their level, softness and noise and render as before; editing a wear control moves one onto the new controls, and level, softness or noise keep an added one on the earlier model. --- crates/compose/src/eval.rs | 80 ++++++-- crates/compose/src/lib.rs | 3 + crates/compose/src/wear.rs | 202 ++++++++++++++++++++ crates/compose/src/wear_inputs.rs | 13 ++ crates/compose/src/wear_scan.rs | 29 +++ crates/core/src/layer.rs | 32 +++- crates/core/src/layer/wear_parameters.rs | 76 ++++++++ crates/core/src/lib.rs | 2 +- crates/engine/src/mask_cmds.rs | 70 ++++++- crates/engine/src/smart_masks.rs | 6 +- crates/engine/tests/it/generator_wear.rs | 69 +++++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/session.rs | 4 +- crates/ui-egui/src/generator_panel.rs | 177 ++++++++++++----- crates/ui-egui/tests/it/effect_sliders.rs | 11 +- crates/ui-egui/tests/it/generator_panel.rs | 44 ++++- crates/ui-egui/tests/it/generator_picker.rs | 7 +- 17 files changed, 740 insertions(+), 86 deletions(-) create mode 100644 crates/compose/src/wear.rs create mode 100644 crates/compose/src/wear_inputs.rs create mode 100644 crates/compose/src/wear_scan.rs create mode 100644 crates/core/src/layer/wear_parameters.rs create mode 100644 crates/engine/tests/it/generator_wear.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3097e768..763af1b9 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -16,7 +16,7 @@ use texturecraft_core::{ CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, - TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -40,6 +40,8 @@ use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use crate::wear; +use crate::wear_inputs::WearInputs; use draw_placement::DrawPlacement; use evaluation_inputs::EvaluationInputs; @@ -2358,12 +2360,24 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { prepare_mask_curvature_sizes(inp, masks); } +/// The blurred curvature sizes `generator` reads: its detail sizes and its wear's smoothing +fn curvature_sizes_in_use(generator: &Generator) -> [bool; CurvatureDetail::BLURRED_SIZES] { + let detail = generator.detail.as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + let wear = wear_parameters(generator).map(|wear| wear::levels_in_use(generator.kind, &wear)).unwrap_or_default(); + std::array::from_fn(|level| detail[level] || wear[level]) +} + +/// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None +fn wear_parameters(generator: &Generator) -> Option { + generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) +} + /// 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()) { + if let EffectKind::Generator(generator) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) { *slot |= in_use; } } @@ -2406,7 +2420,7 @@ fn effect_plans<'a>( None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; let curvature_sizes = match &effect.kind { - EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + EffectKind::Generator(generator) => CurvatureSizes::of(inp, &curvature_sizes_in_use(generator)), _ => None, }; let (depth, covers_all, projection) = match &effect.kind { @@ -3277,6 +3291,10 @@ impl<'a, 'b> Texel<'a, 'b> { } fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + if let Some(wear) = wear_parameters(generator) { + return self.wear_ramp(generator, &wear, curvature_sizes); + } + let coords = self.coords(); let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); let signal = match (generator.kind, &generator.detail) { @@ -3286,7 +3304,9 @@ impl<'a, 'b> Texel<'a, 'b> { let curvature = self.generator_input(generator, BakedMap::Curvature); self.curvature_detail(detail, sizes, curvature, micro) } - (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => { + (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0 + } (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), @@ -3323,7 +3343,7 @@ impl<'a, 'b> Texel<'a, 'b> { let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; let response = height.clamp(-1.0, 1.0) * amount; match kind { - GeneratorKind::Curvature | GeneratorKind::EdgeWear => response, + GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::FiberGlassEdgeWear => response, // Dirt gathers in dents; dents are occluded GeneratorKind::Dirt => -response, @@ -3332,6 +3352,41 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert + fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let curvature = self.generator_input(generator, BakedMap::Curvature).map_or(0.0, |curvature| curvature - 0.5); + + // Blurred levels are copies of the mesh map, so a replaced curvature input is read at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); + + let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0); + let grunge = wear::grunge(generator.kind, wear, generator.seed, &self.coords()); + wear::wear_value(generator.kind, wear, &WearInputs { curvature, blurred_curvature, occlusion, grunge }) + } + + /// The curvature deviation at this texel blurred to `sigma` (texels at 2K) between the two built levels around it; `curvature` without them + fn blurred_curvature(&self, sigma: f32, curvature_sizes: Option<&CurvatureSizes>, curvature: f32) -> f32 { + let Some((sizes, (baked_x, baked_y))) = curvature_sizes.zip(self.baked_curvature_texel()) else { return curvature }; + + let level = |index: usize| sizes.levels.get(index).and_then(Option::as_deref).map(|level| level.sample(baked_x, baked_y)); + let (narrower, wider, weight) = wear::levels_around(sigma); + let narrower = narrower.map_or(Some(curvature), level); + match (narrower, level(wider)) { + (Some(narrower), Some(wider)) => narrower + (wider - narrower) * weight, + _ => curvature, + } + } + + /// The baked curvature map's texel under this texel (None outside the baked layout) + fn baked_curvature_texel(&self) -> Option<(u32, u32)> { + 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 baked_uv = self.inp.block_scales.bake_uv(texel_uv, working_size)?; + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + Some(((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32)) + } + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); @@ -3362,13 +3417,8 @@ impl<'a, 'b> Texel<'a, 'b> { // Without baked curvature, only painted micro height supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; + let Some((baked_x, baked_y)) = self.baked_curvature_texel() 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 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); 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)) }; @@ -5656,7 +5706,7 @@ mod tests { /// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step). fn ridge_generator() -> Generator { - Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) } + Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, wear: None, ..Generator::new(GeneratorKind::EdgeWear) } } #[test] @@ -5755,7 +5805,7 @@ mod tests { fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() }; let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); let value_with = |fixture: &mut Fixture, input: Option| -> f32 { - let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) }; + let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, wear: None, ..Generator::new(GeneratorKind::Dirt) }; if let Some(value) = input { generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3])); } @@ -5796,7 +5846,7 @@ mod tests { for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { for mode in CurvatureMode::ALL { let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; - let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), ..Generator::new(kind) }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, ..Generator::new(kind) }; 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); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 2f5c0477..6318ea16 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -49,6 +49,9 @@ mod timber; pub mod warp; mod warp_source_sample; mod warp_texel; +mod wear; +mod wear_inputs; +mod wear_scan; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs new file mode 100644 index 00000000..0b075151 --- /dev/null +++ b/crates/compose/src/wear.rs @@ -0,0 +1,202 @@ +//! The wear generators' value at a texel (Metal Edge Wear, Fiber Glass Edge Wear, Dirt), fitted to the reference app's observed results + +use texturecraft_core::{CurvatureDetail, GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; + +use crate::pattern::{Coords, procedural}; + +use crate::wear_inputs::WearInputs; +use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; + +/// The radius of each blurred curvature level, in texels at 2K (the detail sizes after the map itself) +const LEVEL_RADII: [f32; CurvatureDetail::BLURRED_SIZES] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; + +/// Gaussian sigma per unit of edges smoothness, in texels at 2K +const EDGE_WEAR_SMOOTHNESS_SIGMA: f32 = 4.6; +const FIBER_GLASS_SMOOTHNESS_SIGMA: f32 = 4.5; +/// The share of the blurred curvature in the smoothed edges +const SMOOTHED_SHARE: f32 = 0.5; +/// Dirt reads its edges and cavities slightly softened, sigma in texels at 2K +const DIRT_CURVATURE_SIGMA: f32 = 1.49; + +/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`) +struct GrungePattern { + kind: ProceduralKind, + repeats_per_scale: f32, + rotation: f32, + mean: f32, + spread: f32, +} + +/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt +const EDGE_WEAR_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.037, spread: 0.149 }; +const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Weave, repeats_per_scale: 16.0, rotation: 45.0, mean: 0.665, spread: 0.21 }; +const DIRT_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.682, spread: 0.242 }; +/// The triplanar seams' sharpness at triplanar contrast 0 and 1 +const TRIPLANAR_SHARPNESS: std::ops::RangeInclusive = 1.0..=16.0; + +/// The Gaussian sigma (texels at 2K) the kind's blurred curvature is read at +pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { + match kind { + GeneratorKind::Dirt => DIRT_CURVATURE_SIGMA, + GeneratorKind::FiberGlassEdgeWear => FIBER_GLASS_SMOOTHNESS_SIGMA * wear.edges_smoothness, + _ => EDGE_WEAR_SMOOTHNESS_SIGMA * wear.edges_smoothness, + } +} + +/// The wear's grunge at `coords`, normalised to mean 0 and spread 1 +pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coords: &Coords) -> f32 { + let grunge = match kind { + GeneratorKind::Dirt => &DIRT_GRUNGE, + GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, + _ => &EDGE_WEAR_GRUNGE, + }; + let pattern = Procedural { scale: grunge.repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(grunge.kind) }; + let projection = if wear.triplanar { + let sharpness = TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast; + Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] } + } else { + Projection::Uv { scale: [1.0, 1.0], rotation: grunge.rotation, offset: [0.0, 0.0] } + }; + (procedural(&pattern, &projection, coords) - grunge.mean) / grunge.spread +} + +/// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself +pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { + // Three box blurs of radius r spread like a Gaussian of sigma √(r(r+1)) + let sigmas = LEVEL_RADII.map(|radius| (radius * (radius + 1.0)).sqrt()); + let wider = sigmas.iter().position(|level| *level >= sigma).unwrap_or(sigmas.len() - 1); + let (narrower, narrower_sigma) = match wider.checked_sub(1) { + Some(level) => (Some(level), sigmas[level]), + None => (None, 0.0), + }; + let span = sigmas[wider] - narrower_sigma; + let weight = if span > 0.0 { ((sigma - narrower_sigma) / span).clamp(0.0, 1.0) } else { 1.0 }; + (narrower, wider, weight) +} + +/// Which blurred curvature levels a wear generator reads +pub(crate) fn levels_in_use(kind: GeneratorKind, wear: &WearParameters) -> [bool; CurvatureDetail::BLURRED_SIZES] { + let (narrower, wider, _) = levels_around(blur_sigma(kind, wear)); + std::array::from_fn(|level| level == wider || Some(level) == narrower) +} + +/// The wear value (0..1) of `kind` at a texel +pub(crate) fn wear_value(kind: GeneratorKind, wear: &WearParameters, inputs: &WearInputs) -> f32 { + match kind { + GeneratorKind::Dirt => DIRT_SCAN.apply(dirt_signal(wear, inputs), wear), + GeneratorKind::FiberGlassEdgeWear => FIBER_GLASS_SCAN.apply(fiber_glass_signal(wear, inputs), wear), + _ => EDGE_WEAR_SCAN.apply(edge_wear_signal(wear, inputs), wear), + } +} + +/// Edges sharp and smoothed in equal parts +fn smoothed_edges(inputs: &WearInputs) -> f32 { + (1.0 - SMOOTHED_SHARE) * inputs.curvature + SMOOTHED_SHARE * inputs.blurred_curvature +} + +/// 1 where the area is open enough to wear, 0 where occluded: the cut-off sits at `offset + gain × masking`, softened over `width` +fn open_area(occlusion: f32, masking: f32, (offset, gain, width): (f32, f32, f32)) -> f32 { + ((occlusion - (offset + gain * masking)) / width + 0.5).clamp(0.0, 1.0) +} + +// The signals' coefficients are fitted to the reference app's sweeps on a hard-surface bake +fn edge_wear_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 { + let edges = smoothed_edges(inputs) * wear.curvature_weight; + let open = open_area(inputs.occlusion, wear.ao_masking, (-0.779, 2.244, 0.935)); + let grunge = wear.grunge_amount; + edges * open * (1.0 + 0.031 * grunge) - 0.009 * grunge + 0.057 * grunge.powf(0.731) * inputs.grunge +} + +fn fiber_glass_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 { + // The grunge takes over from the edges as it grows + let edges = smoothed_edges(inputs) * wear.curvature_weight * 1.02; + let open = open_area(inputs.occlusion, wear.ao_masking, (0.144, 0.726, 0.669)); + let grunge = wear.grunge_amount; + (edges * (1.0 - 0.989 * grunge) + 0.167 * grunge + 0.094 * grunge.powf(1.64) * inputs.grunge) * open +} + +fn dirt_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 { + let edges = inputs.blurred_curvature; + let grunge = wear.grunge_amount; + 0.486 * (0.869 - inputs.occlusion) - wear.edges_masking * 0.817 * edges.max(0.0) + + 0.203 * (-edges).max(0.0) + + 0.241 * grunge + + 0.0895 * grunge * inputs.grunge +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::glam::{Vec2, Vec3}; + + use super::*; + + fn inputs(curvature: f32, occlusion: f32) -> WearInputs { + WearInputs { curvature, blurred_curvature: curvature, occlusion, grunge: 0.0 } + } + + fn defaults(kind: GeneratorKind) -> WearParameters { + WearParameters { grunge_amount: 0.0, ..WearParameters::defaults(kind).unwrap() } + } + + #[test] + fn edge_wear_shows_on_open_convex_edges_only() { + for kind in [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear] { + let wear = WearParameters { curvature_weight: 1.0, ..defaults(kind) }; + let value = |curvature, occlusion| wear_value(kind, &wear, &inputs(curvature, occlusion)); + assert!(value(0.4, 1.0) > 0.9, "{kind:?}: a sharp open edge wears"); + assert!(value(0.0, 1.0) < 0.1, "{kind:?}: a flat face does not"); + assert!(value(-0.4, 1.0) < 0.1, "{kind:?}: nor a cavity"); + assert!(value(0.4, 0.0) < value(0.4, 1.0), "{kind:?}: occlusion masks the wear"); + } + } + + #[test] + fn dirt_gathers_in_occluded_cavities_and_spares_edges() { + let wear = defaults(GeneratorKind::Dirt); + let value = |curvature, occlusion| wear_value(GeneratorKind::Dirt, &wear, &inputs(curvature, occlusion)); + assert!(value(-0.3, 0.2) > value(0.0, 1.0), "occluded cavities collect dirt"); + assert!(value(0.3, 0.6) < value(0.0, 0.6), "edges are masked"); + } + + #[test] + fn a_higher_level_spreads_the_wear_and_a_full_level_is_a_hard_step() { + let low = WearParameters { level: 0.25, ..defaults(GeneratorKind::EdgeWear) }; + let high = WearParameters { level: 0.9, ..low }; + let mild = inputs(0.1, 1.0); + assert!(wear_value(GeneratorKind::EdgeWear, &high, &mild) > wear_value(GeneratorKind::EdgeWear, &low, &mild)); + + let full = WearParameters { level: 1.0, ..low }; + for curvature in [-0.5, 0.0, 0.05, 0.5] { + let value = wear_value(GeneratorKind::EdgeWear, &full, &inputs(curvature, 1.0)); + assert!(value == 0.0 || value == 1.0, "{curvature}: {value}"); + } + } + + #[test] + fn grunge_is_normalised() { + for (kind, pattern) in + [(GeneratorKind::EdgeWear, &EDGE_WEAR_GRUNGE), (GeneratorKind::FiberGlassEdgeWear, &FIBER_GLASS_GRUNGE), (GeneratorKind::Dirt, &DIRT_GRUNGE)] + { + let wear = WearParameters::defaults(kind).unwrap(); + let samples: Vec = (0..256 * 256) + .map(|texel| { + let uv = Vec2::new((texel % 256) as f32 / 256.0, (texel / 256) as f32 / 256.0); + grunge(kind, &wear, 7, &Coords { uv, pos: uv.extend(0.0), nrm: Vec3::Z }) + }) + .collect(); + let mean = samples.iter().sum::() / samples.len() as f32; + let spread = (samples.iter().map(|value| (value - mean).powi(2)).sum::() / samples.len() as f32).sqrt(); + let measured = (pattern.mean + mean * pattern.spread, spread * pattern.spread); + assert!(mean.abs() < 0.1 && (spread - 1.0).abs() < 0.1, "{kind:?}: normalised mean {mean}, spread {spread}; the pattern's own {measured:?}"); + } + } + + #[test] + fn the_blurred_levels_around_a_sigma_bracket_it() { + assert_eq!(levels_around(0.5).0, None, "below the first level the map itself is the narrower one"); + let (narrower, wider, weight) = levels_around(4.6); + assert_eq!((narrower, wider), (Some(2), 3)); + assert!((0.0..=0.1).contains(&weight), "4.6 sits just past radius 4's sigma: {weight}"); + assert_eq!(levels_around(500.0).1, LEVEL_RADII.len() - 1, "wider than every level reads the widest"); + } +} diff --git a/crates/compose/src/wear_inputs.rs b/crates/compose/src/wear_inputs.rs new file mode 100644 index 00000000..e9f83c42 --- /dev/null +++ b/crates/compose/src/wear_inputs.rs @@ -0,0 +1,13 @@ +//! What a wear generator reads at a texel + +/// What a wear generator reads at a texel +pub(crate) struct WearInputs { + /// The curvature map minus its flat 0.5 (above 0 convex, below 0 concave) + pub curvature: f32, + /// The curvature deviation blurred to the sigma the kind asks for ([`crate::wear::blur_sigma`]) + pub blurred_curvature: f32, + /// Ambient occlusion (1 open, 0 occluded) + pub occlusion: f32, + /// The grunge pattern normalised to mean 0 and spread 1 + pub grunge: f32, +} diff --git a/crates/compose/src/wear_scan.rs b/crates/compose/src/wear_scan.rs new file mode 100644 index 00000000..ceac28b9 --- /dev/null +++ b/crates/compose/src/wear_scan.rs @@ -0,0 +1,29 @@ +//! How a wear generator's level and contrast turn its signal into the mask (constants fitted to the reference app's sweeps) + +use texturecraft_core::WearParameters; + +/// Where a kind's level slides its edge and how wide the edge is +pub(crate) struct WearScan { + /// The edge at level 0, falling towards `floor` as the level rises + pub travel: f32, + pub floor: f32, + /// The edge's width at contrast 0, narrowed by (1 − contrast) to the power `narrowing` + pub width: f32, + pub narrowing: f32, +} + +pub(crate) const EDGE_WEAR_SCAN: WearScan = WearScan { travel: 0.284, floor: -0.009, width: 0.504, narrowing: 0.95 }; +pub(crate) const FIBER_GLASS_SCAN: WearScan = WearScan { travel: 0.162, floor: 0.029, width: 0.358, narrowing: 0.872 }; +pub(crate) const DIRT_SCAN: WearScan = WearScan { travel: 0.593, floor: -0.088, width: 1.386, narrowing: 1.42 }; + +/// The narrowest edge, so a level or contrast of 1 is a hard step rather than a division by zero +const MIN_EDGE_WIDTH: f32 = 1e-4; + +impl WearScan { + /// `signal` through the level and contrast: the level brings the edge down and narrows it, the contrast narrows it further + pub(crate) fn apply(&self, signal: f32, wear: &WearParameters) -> f32 { + let remaining = (1.0 - wear.level).max(0.0); + let width = (remaining * self.width * (1.0 - wear.contrast).max(0.0).powf(self.narrowing)).max(MIN_EDGE_WIDTH); + ((signal - self.floor - remaining * self.travel) / width + 0.5).clamp(0.0, 1.0) + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index b3186d4d..6f218f1f 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -31,6 +31,7 @@ mod tile_size_mode; mod tile_symmetry; mod uv_transform; mod uv_wrap; +mod wear_parameters; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; @@ -51,6 +52,7 @@ pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; pub use uv_transform::UvTransform; pub use uv_wrap::UvWrap; +pub use wear_parameters::WearParameters; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -926,10 +928,12 @@ pub enum GeneratorKind { Position, /// Surfaces facing a direction (e.g. up for dust). Direction, + /// Worn edges of a fibreglass-like coating: the edges fade into its grunge + FiberGlassEdgeWear, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 7] = [ + pub const ALL: [GeneratorKind; 8] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -937,6 +941,7 @@ impl GeneratorKind { GeneratorKind::AmbientOcclusion, GeneratorKind::Position, GeneratorKind::Direction, + GeneratorKind::FiberGlassEdgeWear, ]; pub fn label(self) -> &'static str { match self { @@ -947,6 +952,7 @@ impl GeneratorKind { GeneratorKind::AmbientOcclusion => "Ambient Occlusion", GeneratorKind::Position => "Position", GeneratorKind::Direction => "Light", + GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", } } @@ -960,6 +966,7 @@ impl GeneratorKind { GeneratorKind::AmbientOcclusion => "AmbientOcclusion", GeneratorKind::Position => "Position", GeneratorKind::Direction => "Direction", + GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", } } @@ -970,14 +977,15 @@ impl GeneratorKind { /// Whether the kind's result depends on its seed pub fn includes_randomness(self) -> bool { - matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt) + matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear) } /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. pub fn inputs(self) -> &'static [BakedMap] { match self { - GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature], - GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => &[BakedMap::Curvature, BakedMap::AmbientOcclusion], + GeneratorKind::Curvature => &[BakedMap::Curvature], + GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], GeneratorKind::Position | GeneratorKind::Direction => &[], } @@ -1021,6 +1029,9 @@ pub struct Generator { /// Painted height read from an anchor point below, added as micro detail (None: baked maps only). #[serde(default, skip_serializing_if = "Option::is_none")] pub micro: Option, + /// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wear: Option, } impl Generator { @@ -1059,6 +1070,7 @@ impl Generator { resolution: OutputResolution::default(), inputs: BTreeMap::new(), micro: None, + wear: WearParameters::defaults(kind), } } @@ -2278,6 +2290,18 @@ mod tests { assert!(!GeneratorKind::ThinAreas.in_picker(), "Thin areas only loads from saved projects and smart masks"); } + #[test] + fn wear_generators_saved_before_their_wear_controls_load_on_the_earlier_model() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::EdgeWear)).unwrap(); + assert!(saved.get("wear").is_some(), "new wear generators have wear controls"); + + saved.as_object_mut().unwrap().remove("wear"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.wear, None, "level, softness and noise keep driving it"); + let curvature = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + assert!(curvature.get("wear").is_none(), "other kinds save no wear controls"); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs new file mode 100644 index 00000000..b0c2de19 --- /dev/null +++ b/crates/core/src/layer/wear_parameters.rs @@ -0,0 +1,76 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; + +/// The controls of the wear generators (Metal Edge Wear, Fiber Glass Edge Wear, Dirt) as the reference app lays them out; each kind reads its own +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WearParameters { + /// How far the wear spreads (0..1) + pub level: f32, + /// How hard the wear's edge is (0 soft, 1 a hard step) + pub contrast: f32, + /// How much the grunge breaks the wear up (0..1) + pub grunge_amount: f32, + /// The grunge's size: repeats across the UV square ([`WearParameters::GRUNGE_SCALE_RANGE`]) + pub grunge_scale: f32, + /// The grunge projected from the world's three axes rather than laid out in UV + pub triplanar: bool, + /// How sharply the three projections meet (0..1) + pub triplanar_contrast: f32, + /// How far the worn edges spread over rounded edges ([`WearParameters::EDGES_SMOOTHNESS_RANGE`]; edge wear kinds) + pub edges_smoothness: f32, + /// How much occluded areas are kept clean (0..1; edge wear kinds) + pub ao_masking: f32, + /// How much the edges count against the grunge (0..1; edge wear kinds) + pub curvature_weight: f32, + /// How much convex edges are kept clean (0..1; Dirt) + pub edges_masking: f32, +} + +impl WearParameters { + pub const GRUNGE_SCALE_RANGE: std::ops::RangeInclusive = 1.0..=16.0; + pub const EDGES_SMOOTHNESS_RANGE: std::ops::RangeInclusive = 0.0..=16.0; + + /// The reference app's defaults for `kind`, or None for kinds without wear controls + pub fn defaults(kind: GeneratorKind) -> Option { + let shared = WearParameters { + level: 0.75, + contrast: 0.5, + grunge_amount: 0.3, + grunge_scale: 4.0, + triplanar: false, + triplanar_contrast: 0.5, + edges_smoothness: 1.0, + ao_masking: 0.5, + curvature_weight: 1.0, + edges_masking: 0.5, + }; + match kind { + GeneratorKind::EdgeWear | GeneratorKind::Dirt => Some(shared), + GeneratorKind::FiberGlassEdgeWear => Some(WearParameters { curvature_weight: 0.25, ..shared }), + GeneratorKind::ThinAreas | GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::Direction => None, + } + } + + /// Every value brought into its range, non-finite ones to the defaults of `kind` + pub fn clamped(self, kind: GeneratorKind) -> WearParameters { + let defaults = WearParameters::defaults(kind).unwrap_or(self); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + let within = |value: f32, default: f32, range: &std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + WearParameters { + level: unit(self.level, defaults.level), + contrast: unit(self.contrast, defaults.contrast), + grunge_amount: unit(self.grunge_amount, defaults.grunge_amount), + grunge_scale: within(self.grunge_scale, defaults.grunge_scale, &WearParameters::GRUNGE_SCALE_RANGE), + triplanar: self.triplanar, + triplanar_contrast: unit(self.triplanar_contrast, defaults.triplanar_contrast), + edges_smoothness: within(self.edges_smoothness, defaults.edges_smoothness, &WearParameters::EDGES_SMOOTHNESS_RANGE), + ao_masking: unit(self.ao_masking, defaults.ao_masking), + curvature_weight: unit(self.curvature_weight, defaults.curvature_weight), + edges_masking: unit(self.edges_masking, defaults.edges_masking), + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 88ee96d1..b494aa57 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -114,7 +114,7 @@ pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, + Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 8cf8deef..e7ee6cce 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, + GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), level?, softness?, noise?, offset?: -1..1 added to the result (instead keep edgeWear and dirt on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -388,7 +388,71 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { } /// Apply `params` to `generator`, using `command` in errors +/// The parameters that drive the wear generators' earlier model +const EARLIER_WEAR_KEYS: [&str; 5] = ["level", "softness", "noise", "noiseScale", "offset"]; + +/// The wear controls `effect.add.generator` and `effect.set` take +const WEAR_KEYS: [&str; 10] = [ + "wearLevel", + "wearContrast", + "grungeAmount", + "grungeScale", + "triplanar", + "triplanarContrast", + "edgesSmoothness", + "aoMasking", + "curvatureWeight", + "edgesMasking", +]; + +/// The wear controls in `params`: they move a wear generator onto them, while level, softness, noise or offset keep it on the earlier model +fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let Some(defaults) = WearParameters::defaults(generator.kind) else { + return if given(&WEAR_KEYS) { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; + }; + + if given(&EARLIER_WEAR_KEYS) { + if given(&WEAR_KEYS) { + return Err(bad(command, "level, softness, noise and offset drive the earlier wear model: give them or the wear controls, not both")); + } + if generator.kind == GeneratorKind::FiberGlassEdgeWear { + return Err(bad(command, "Fiber Glass Edge Wear has wear controls only (wearLevel, wearContrast…), no level, softness, noise or offset")); + } + generator.wear = None; + return Ok(()); + } + if !given(&WEAR_KEYS) { + return Ok(()); + } + + // The offset belongs to the earlier model: kept, it would shift the wear controls' result unseen + generator.offset = 0.0; + let wear = generator.wear.get_or_insert(defaults); + for (key, value) in [ + ("wearLevel", &mut wear.level), + ("wearContrast", &mut wear.contrast), + ("grungeAmount", &mut wear.grunge_amount), + ("grungeScale", &mut wear.grunge_scale), + ("triplanarContrast", &mut wear.triplanar_contrast), + ("edgesSmoothness", &mut wear.edges_smoothness), + ("aoMasking", &mut wear.ao_masking), + ("curvatureWeight", &mut wear.curvature_weight), + ("edgesMasking", &mut wear.edges_masking), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(triplanar) = boolp(params, "triplanar") { + wear.triplanar = triplanar; + } + *wear = wear.clamped(generator.kind); + Ok(()) +} + fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + wear_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 8c7a2791..244c412e 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,14 +79,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 (curvature as baked, without detail sizes). +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or wear controls) pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: 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, detail: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, wear: None, ..Generator::new(kind) }) } /// A triplanar grayscale pattern fill diff --git a/crates/engine/tests/it/generator_wear.rs b/crates/engine/tests/it/generator_wear.rs new file mode 100644 index 00000000..cd49c378 --- /dev/null +++ b/crates/engine/tests/it/generator_wear.rs @@ -0,0 +1,69 @@ +//! The wear generators' controls through `effect.add.generator` and `effect.set`, beside their earlier level, softness and noise + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, GeneratorKind, LayerId, WearParameters}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +#[test] +fn new_wear_generators_start_from_the_reference_defaults() { + let mut session = session(); + for kind in ["edgeWear", "dirt", "fiberGlassEdgeWear"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert_eq!(added.wear, WearParameters::defaults(added.kind), "{kind}"); + } +} + +#[test] +fn level_softness_or_noise_keep_a_generator_on_the_earlier_model() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "edgeWear", "level": 0.4})); + assert_eq!(generator(&session, effect).wear, None, "agents' earlier parameters still drive it"); + assert_eq!(generator(&session, effect).level, 0.4); +} + +#[test] +fn a_wear_control_moves_an_earlier_generator_onto_the_defaults_with_that_change() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "dirt", "softness": 0.3})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "wearLevel": 0.6, "grungeScale": 99.0})).unwrap(); + + let wear = generator(&session, effect).wear.expect("on the wear controls now"); + let defaults = WearParameters::defaults(GeneratorKind::Dirt).unwrap(); + assert_eq!( + wear, + WearParameters { level: 0.6, grunge_scale: *WearParameters::GRUNGE_SCALE_RANGE.end(), ..defaults }, + "the rest at defaults, values clamped" + ); +} + +#[test] +fn mixing_the_models_or_wear_controls_on_other_kinds_is_refused() { + let mut session = session(); + let edge_wear = add(&mut session, json!({"generator": "edgeWear"})); + let curvature = add(&mut session, json!({"generator": "curvature"})); + + assert!(execute(&mut session, "effect.set", &json!({"effect": edge_wear, "level": 0.5, "wearLevel": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "wearLevel": 0.5})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"generator": "fiberGlassEdgeWear", "level": 0.5})).is_err()); + assert_eq!(generator(&session, edge_wear).wear, WearParameters::defaults(GeneratorKind::EdgeWear), "a refused edit changes nothing"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index bd56a597..b3a87d44 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -37,6 +37,7 @@ mod folder_contents; mod frame_selection; mod generator_inputs; mod generator_swap; +mod generator_wear; mod gradient_map; mod high_poly_missed; mod instances; diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index dd4972cf..3bbeafe9 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -960,8 +960,8 @@ fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() { let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"uniform":[0.25,0.25,0.25]}}"#), "{inspect}"); - let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5})); - assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature"); + let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "thickness", "inputValue": 0.5})); + assert!(wrong_input.is_err(), "dirt reads ambient occlusion and curvature, not thickness"); let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"})); assert!(missing_image.is_err(), "the image must be a resource of the project"); let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true})); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 47bf6aa1..382a76df 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,7 +4,7 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, + BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, WearParameters, }; use crate::TextureCraftApp; @@ -19,6 +19,9 @@ const INPUT_TILE_SIZE: f32 = 32.0; const INPUT_TILE_ROUNDING: f32 = 2.0; const INPUT_TILE_ICON_SIZE: f32 = 16.0; +/// Width of a False/True button, so the buttons line up under each other +const TOGGLE_WIDTH: f32 = 136.0; + /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = Tokens::get(ui.ctx()); @@ -27,10 +30,15 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); section(ui, "generator_parameters", tr("Parameters"), true, |ui| { - global_adjustments(app, ui, id, generator); - ramp_parameters(app, ui, id, generator); - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + if let Some(defaults) = WearParameters::defaults(generator.kind) { + // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them + wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); + } else { + global_adjustments(app, ui, id, generator); + ramp_parameters(app, ui, id, generator); + if generator.kind == GeneratorKind::Curvature { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { micro_detail_properties(app, ui, id, generator.micro, layer); @@ -87,24 +95,14 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); let (description, tags) = match kind { - GeneratorKind::EdgeWear => ( - tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."), - [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], - ), - GeneratorKind::Dirt => ( - tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."), - [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")], - ), - GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), - GeneratorKind::Curvature => ( - tr("Convex edges, cavities or both from the curvature map, at several detail sizes."), - [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], - ), - GeneratorKind::AmbientOcclusion => { - (tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) - } - GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), - GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + GeneratorKind::EdgeWear => (tr("Worn metal edges, scratched."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), + GeneratorKind::FiberGlassEdgeWear => (tr("Worn fibreglass edges."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), + GeneratorKind::Dirt => (tr("Grime in cavities."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]), + GeneratorKind::ThinAreas => (tr("Thin parts of the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), + GeneratorKind::Curvature => (tr("Convex edges and cavities."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), + GeneratorKind::AmbientOcclusion => (tr("Occluded areas."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]), + GeneratorKind::Position => (tr("A gradient across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), }; // Wrapped rows: a long line must not widen the panel past its edge @@ -183,6 +181,73 @@ fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator } } +/// The wear controls of generator effect `id` in the reference app's order, showing `wear` +fn wear_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, wear: WearParameters) { + seed_row(app, ui, id, generator.seed); + let mut invert = generator.invert; + if true_false(ui, tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + + let dirt = generator.kind == GeneratorKind::Dirt; + let (level_label, contrast_label) = if dirt { (tr("Dirt level"), tr("Dirt contrast")) } else { (tr("Wear level"), tr("Wear contrast")) }; + let mut edited = wear; + let mut edit = slider_edit(ui, level_label, &mut edited.level, 0.0..=1.0, 2); + edit = edit.or(slider_edit(ui, contrast_label, &mut edited.contrast, 0.0..=1.0, 2)); + let triplanar_edit = true_false(ui, tr("Use triplanar"), &mut edited.triplanar).then_some(false); + edit = edit.or(triplanar_edit).or(slider_edit(ui, tr("Triplanar blending contrast"), &mut edited.triplanar_contrast, 0.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Grunge amount"), &mut edited.grunge_amount, 0.0..=1.0, 2)); + if generator.kind != GeneratorKind::FiberGlassEdgeWear { + edit = edit.or(slider_edit(ui, tr("Grunge scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); + } + if dirt { + edit = edit.or(slider_edit(ui, tr("Edges masking"), &mut edited.edges_masking, 0.0..=1.0, 2)); + } else { + edit = edit.or(slider_edit(ui, tr("Edges smoothness"), &mut edited.edges_smoothness, WearParameters::EDGES_SMOOTHNESS_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Ambient occlusion masking"), &mut edited.ao_masking, 0.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Curvature weight"), &mut edited.curvature_weight, 0.0..=1.0, 2)); + } + + if let Some(merge) = edit { + let mut params = wear_params(&edited); + params["effect"] = json!(id); + params["merge"] = json!(merge); + app.run("effect.set", params); + } +} + +/// The `effect.set` params that set every wear control to `wear` +fn wear_params(wear: &WearParameters) -> Value { + json!({ + "wearLevel": wear.level, + "wearContrast": wear.contrast, + "grungeAmount": wear.grunge_amount, + "grungeScale": wear.grunge_scale, + "triplanar": wear.triplanar, + "triplanarContrast": wear.triplanar_contrast, + "edgesSmoothness": wear.edges_smoothness, + "aoMasking": wear.ao_masking, + "curvatureWeight": wear.curvature_weight, + "edgesMasking": wear.edges_masking, + }) +} + +/// An on/off control as the reference app draws it: the name, then a full-width button reading False or True; returns whether it was clicked +fn true_false(ui: &mut Ui, label: &str, value: &mut bool) -> bool { + let mut clicked = false; + ui.horizontal(|ui| { + ui.label(label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let text = if *value { tr("True") } else { tr("False") }; + if ui.add_sized([TOGGLE_WIDTH, ui.spacing().interact_size.y], egui::Button::new(text)).clicked() { + *value = !*value; + clicked = true; + } + }); + }); + clicked +} + /// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = @@ -230,13 +295,19 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); - let mut params = json!({ + // A wear generator restores its wear controls; level, softness, noise and offset would keep it on the earlier model + let mut params = match &defaults.wear { + Some(wear) => wear_params(wear), + None => json!({ + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + }), + }; + let shared = json!({ "effect": id, - "level": defaults.level, - "softness": defaults.softness, - "noise": defaults.noise_amount, - "noiseScale": defaults.noise_scale, - "offset": defaults.offset, "seed": defaults.seed, "direction": defaults.direction, "invert": defaults.invert, @@ -248,6 +319,9 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "resolutionFactor": defaults.resolution.factor, "microAnchor": null, }); + if let (Some(params), Value::Object(shared)) = (params.as_object_mut(), shared) { + params.extend(shared); + } if let Some(detail) = defaults.detail { params["mode"] = json!(format!("{:?}", detail.mode)); params["sizes"] = json!(detail.weights); @@ -315,28 +389,31 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } }); }); - combo(ui, tr("Source"), current.clone(), |ui| { - let anchors = anchors_below(&app.session.doc.project, layer); - if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); - } - if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); - } - for (anchor, label) in &anchors { - if ui - .selectable_label( - matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), - trf("Anchor: {name}", &[("name", label)]), - ) - .clicked() - { - app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + // Each input's menu needs its own id: the dropdown's id comes from its label + ui.push_id(input, |ui| { + combo(ui, tr("Source"), current.clone(), |ui| { + let anchors = anchors_below(&app.session.doc.project, layer); + if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } - } - if let Some(name) = image_menu(app, ui) { - app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); - } + if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + } + for (anchor, label) in &anchors { + if ui + .selectable_label( + matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), + trf("Anchor: {name}", &[("name", label)]), + ) + .clicked() + { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + }) }); if let Some(Source::Uniform(value)) = source { let mut value = value[0]; diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index cf141d3b..30e53995 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -4,10 +4,10 @@ use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{Queryable, by}; use serde_json::json; -use texturecraft_engine::core::{EffectKind, LayerId}; +use texturecraft_engine::core::{EffectKind, LayerId, WearParameters}; use texturecraft_ui_egui::TextureCraftApp; -/// The sample session with its first generator effect selected, and that effect's id +/// The sample session with its first generator other than a wear one selected, and that effect's id fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session @@ -17,7 +17,12 @@ fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { .values() .find_map(|layer| { let mask_effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()); - layer.content_effects.iter().chain(mask_effects).find(|effect| matches!(effect.kind, EffectKind::Generator(_))).map(|effect| (layer.id, effect.id)) + layer + .content_effects + .iter() + .chain(mask_effects) + .find(|effect| matches!(&effect.kind, EffectKind::Generator(generator) if WearParameters::defaults(generator.kind).is_none())) + .map(|effect| (layer.id, effect.id)) }) .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index b256f537..b53f5012 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source}; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -12,12 +12,17 @@ use texturecraft_ui_egui::theme::Brightness; /// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + harness_with(render, json!({"generator": "curvature"})) +} + +/// The sample session with a fill layer whose black mask holds the generator `added` describes, selected in the properties panel +fn harness_with(render: bool, added: serde_json::Value) -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); session.active_set = 1; session.camera.pitch = 0.5; let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); execute(&mut session, "mask.add.black", &json!({})).unwrap(); - let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + let effect = execute(&mut session, "effect.add.generator", &added).unwrap()["effect"].as_u64().unwrap(); session.view = ViewMode::Mask(LayerId(layer)); session.update(); let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); @@ -95,6 +100,29 @@ fn picking_a_kind_in_the_panel_is_one_undo_step() { assert_eq!(harness.state().session.history_labels().len(), history + 1); } +#[test] +fn a_wear_control_moves_an_earlier_wear_generator_onto_the_wear_controls() { + let (mut harness, effect) = harness_with(false, json!({"generator": "edgeWear", "level": 0.4})); + assert_eq!(generator(&harness, effect).wear, None, "level keeps it on the earlier model"); + + drag_slider(&mut harness, "Wear level"); + + let wear = generator(&harness, effect).wear.expect("on the wear controls now"); + let defaults = WearParameters::defaults(GeneratorKind::EdgeWear).unwrap(); + assert_ne!(wear.level, defaults.level, "the drag set the level"); + assert_eq!(WearParameters { level: defaults.level, ..wear }, defaults, "the other controls start at their defaults"); +} + +#[test] +fn restore_defaults_keeps_a_wear_generator_on_its_wear_controls() { + let (mut harness, effect) = harness_with(false, json!({"generator": "dirt", "grungeAmount": 0.9, "seed": 3})); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Dirt)); +} + #[test] fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { let (mut harness, effect) = harness(false); @@ -145,3 +173,15 @@ fn generator_panel_snapshots() { harness.run_steps(12); harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap(); } + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn wear_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["edgeWear", "dirt", "fiberGlassEdgeWear"] { + let (mut harness, _) = harness_with(true, json!({"generator": kind})); + harness.run_steps(12); + harness.render().unwrap().save(directory.join(format!("wear-panel-{kind}.png"))).unwrap(); + } +} diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs index d6d31dd8..c68ebf26 100644 --- a/crates/ui-egui/tests/it/generator_picker.rs +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -47,7 +47,8 @@ fn picking_from_the_slot_swaps_the_generator_kind() { harness.run_steps(3); assert_eq!(harness.query_all_by_label("Light").count(), 0, "the search hides generators that don't match"); - harness.get_by_label("Curvature").click(); + // The panel's Curvature input shares the name as a label; the picker's tile is a list option + harness.get_by_role_and_label(Role::ListBoxOption, "Curvature").click(); harness.run_steps(3); assert_eq!(kind(&harness, effect), Some(GeneratorKind::Curvature)); @@ -93,8 +94,8 @@ fn generator_picker_snapshots() { harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap(); } - // The Assets shelf may show a Dirt resource too: the picker draws over it, last - harness.query_all_by_label("Dirt").last().expect("the picker offers Dirt").hover(); + // The picker's tile is the button named Dirt + harness.get_by_role_and_label(Role::Button, "Dirt").hover(); for _ in 0..10 { harness.run_steps(5); std::thread::sleep(std::time::Duration::from_millis(300)); From fdd2d72b7c04ffee5ef1db30c88bb7732331cc0e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 092/153] Fiber Glass Edge Wear: its seed breaks the woven grunge up differently The weave the fibreglass grunge uses has no seed, so changing the seed changed nothing. A seeded grunge now varies the weave's strength, and a test checks every wear kind's grunge changes with the seed. --- crates/compose/src/wear.rs | 45 ++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 0b075151..1e737deb 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -23,14 +23,28 @@ struct GrungePattern { kind: ProceduralKind, repeats_per_scale: f32, rotation: f32, + /// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change + breakup: Option<(ProceduralKind, f32)>, mean: f32, spread: f32, } /// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt -const EDGE_WEAR_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.037, spread: 0.149 }; -const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Weave, repeats_per_scale: 16.0, rotation: 45.0, mean: 0.665, spread: 0.21 }; -const DIRT_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.682, spread: 0.242 }; +const EDGE_WEAR_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149 }; +const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { + kind: ProceduralKind::Weave, + repeats_per_scale: 16.0, + rotation: 45.0, + breakup: Some((ProceduralKind::Grunge, 4.0)), + mean: 0.539, + spread: 0.198, +}; +const DIRT_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242 }; +/// How much a breakup pattern varies the grunge's strength (0 none, 1 down to nothing) +const BREAKUP_DEPTH: f32 = 0.6; + /// The triplanar seams' sharpness at triplanar contrast 0 and 1 const TRIPLANAR_SHARPNESS: std::ops::RangeInclusive = 1.0..=16.0; @@ -57,7 +71,12 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor } else { Projection::Uv { scale: [1.0, 1.0], rotation: grunge.rotation, offset: [0.0, 0.0] } }; - (procedural(&pattern, &projection, coords) - grunge.mean) / grunge.spread + let mut value = procedural(&pattern, &projection, coords); + if let Some((breakup, repeats_per_scale)) = grunge.breakup { + let breakup = Procedural { scale: repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(breakup) }; + value *= 1.0 - BREAKUP_DEPTH + BREAKUP_DEPTH * procedural(&breakup, &projection, coords); + } + (value - grunge.mean) / grunge.spread } /// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself @@ -191,6 +210,24 @@ mod tests { } } + #[test] + fn every_kind_s_grunge_changes_with_the_seed() { + for kind in [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::Dirt] { + let wear = WearParameters::defaults(kind).unwrap(); + let sample = |seed| -> Vec { + (0..64 * 64) + .map(|texel| { + let uv = Vec2::new((texel % 64) as f32 / 64.0, (texel / 64) as f32 / 64.0); + grunge(kind, &wear, seed, &Coords { uv, pos: uv.extend(0.0), nrm: Vec3::Z }) + }) + .collect() + }; + let (first, second) = (sample(1), sample(2)); + let difference = first.iter().zip(&second).map(|(a, b)| (a - b).abs()).sum::() / first.len() as f32; + assert!(difference > 0.2, "{kind:?}: another seed barely changes the grunge ({difference})"); + } + } + #[test] fn the_blurred_levels_around_a_sigma_bracket_it() { assert_eq!(levels_around(0.5).0, None, "below the first level the map itself is the narrower one"); From 4d00158fdb390e6f339d5eb5e79146b5cda93719 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 093/153] Wear generators: no dead controls Edges smoothness reached the widest blurred curvature level at about 7 of 16, so the rest of the slider changed nothing: two wider levels cover the whole range. Ambient occlusion masking below 0.14 masked nothing on Metal Edge Wear. Mode and sizes on a new Metal Edge Wear and global blur, balance or contrast on the wear controls were accepted and ignored; they now keep the earlier model or are refused, as are wear controls a kind doesn't have. Only the blurred levels a generator reads are built. The labels before the reference's names parse again. --- crates/compose/src/curvature_sizes.rs | 17 +++++-- crates/compose/src/eval.rs | 26 ++++++---- crates/compose/src/wear.rs | 49 +++++++++++++++---- crates/core/src/layer.rs | 17 ++++++- crates/engine/src/mask_cmds.rs | 23 ++++++++- crates/engine/tests/it/generator_wear.rs | 24 ++++++++++ crates/engine/tests/session.rs | 2 +- crates/ui-egui/src/generator_panel.rs | 53 +++++++++++---------- crates/ui-egui/tests/it/generator_picker.rs | 3 +- 9 files changed, 164 insertions(+), 50 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 0b7138bc..95525331 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -4,13 +4,16 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; -use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_core::{BakedMap, BlockScales}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; 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. +/// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches +pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]; + +/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`]. pub struct CurvatureSizes { /// One per blurred size, built once a generator gives that size a weight above 0. pub levels: Vec>>, @@ -70,9 +73,8 @@ impl CurvatureSizes { 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 + let levels = LEVEL_RADII .iter() - .skip(1) .enumerate() .map(|(level, size)| { if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { @@ -247,6 +249,8 @@ fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u3 #[cfg(test)] mod tests { + use texturecraft_core::CurvatureDetail; + use super::*; #[test] @@ -473,4 +477,9 @@ mod tests { } } } + + #[test] + fn the_first_levels_are_the_detail_sizes() { + assert_eq!(LEVEL_RADII[..CurvatureDetail::BLURRED_SIZES], CurvatureDetail::SIZES[1..]); + } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 763af1b9..933f9852 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -24,7 +24,7 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; -use crate::curvature_sizes::CurvatureSizes; +use crate::curvature_sizes::{CurvatureSizes, LEVEL_RADII}; use crate::effect_histogram::EffectHistogram; use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; @@ -508,8 +508,8 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // Use reference-resolution reach so all callers classify the same filters as stages - EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + EffectKind::Generator(generator) if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() => { + Some((index, texels(generator.applied_global().blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) } // A mirror reads anywhere in its UV tile @@ -1953,7 +1953,7 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; + let blur_radius = generator.applied_global().blur_radius_at(uv_tile).round() as usize; if blur_radius > 0 { let mut weights = cover.to_vec(); blur(&mut weights, columns, rows, blur_radius); @@ -2039,7 +2039,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, /// A generator's (possibly blurred) ramp after balance, contrast, invert and offset fn finish_generator(generator: &Generator, ramp: f32) -> f32 { - let value = generator.global.apply(ramp); + let value = generator.applied_global().apply(ramp); let value = if generator.invert { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (value + offset).clamp(0.0, 1.0) @@ -2360,11 +2360,17 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { prepare_mask_curvature_sizes(inp, masks); } -/// The blurred curvature sizes `generator` reads: its detail sizes and its wear's smoothing -fn curvature_sizes_in_use(generator: &Generator) -> [bool; CurvatureDetail::BLURRED_SIZES] { +/// The blurred curvature levels `generator` reads: its wear's smoothing, else its detail sizes (a replaced curvature input reads none) +fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { + if generator.inputs.contains_key(&BakedMap::Curvature) { + return [false; LEVEL_RADII.len()]; + } + if let Some(wear) = wear_parameters(generator) { + return wear::levels_in_use(generator.kind, &wear); + } + let detail = generator.detail.as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); - let wear = wear_parameters(generator).map(|wear| wear::levels_in_use(generator.kind, &wear)).unwrap_or_default(); - std::array::from_fn(|level| detail[level] || wear[level]) + std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) } /// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None @@ -2374,7 +2380,7 @@ fn wear_parameters(generator: &Generator) -> Option { /// 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]; + let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(generator) = &effect.kind { for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) { diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 1e737deb..b766f3e1 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -1,14 +1,16 @@ //! The wear generators' value at a texel (Metal Edge Wear, Fiber Glass Edge Wear, Dirt), fitted to the reference app's observed results -use texturecraft_core::{CurvatureDetail, GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; +use texturecraft_core::{GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; + +use crate::curvature_sizes::LEVEL_RADII; use crate::pattern::{Coords, procedural}; use crate::wear_inputs::WearInputs; use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; -/// The radius of each blurred curvature level, in texels at 2K (the detail sizes after the map itself) -const LEVEL_RADII: [f32; CurvatureDetail::BLURRED_SIZES] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; +/// The Gaussian sigma each blurred curvature level spreads like: three box blurs of radius r spread √(r(r+1)), radii from [`LEVEL_RADII`] +const LEVEL_SIGMAS: [f32; LEVEL_RADII.len()] = [1.414, 2.449, 4.472, 8.485, 16.492, 32.496, 64.498, 128.499]; /// Gaussian sigma per unit of edges smoothness, in texels at 2K const EDGE_WEAR_SMOOTHNESS_SIGMA: f32 = 4.6; @@ -81,8 +83,7 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor /// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { - // Three box blurs of radius r spread like a Gaussian of sigma √(r(r+1)) - let sigmas = LEVEL_RADII.map(|radius| (radius * (radius + 1.0)).sqrt()); + let sigmas = LEVEL_SIGMAS; let wider = sigmas.iter().position(|level| *level >= sigma).unwrap_or(sigmas.len() - 1); let (narrower, narrower_sigma) = match wider.checked_sub(1) { Some(level) => (Some(level), sigmas[level]), @@ -94,8 +95,13 @@ pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { } /// Which blurred curvature levels a wear generator reads -pub(crate) fn levels_in_use(kind: GeneratorKind, wear: &WearParameters) -> [bool; CurvatureDetail::BLURRED_SIZES] { - let (narrower, wider, _) = levels_around(blur_sigma(kind, wear)); +pub(crate) fn levels_in_use(kind: GeneratorKind, wear: &WearParameters) -> [bool; LEVEL_RADII.len()] { + let sigma = blur_sigma(kind, wear); + if sigma <= 0.0 { + return [false; LEVEL_RADII.len()]; + } + + let (narrower, wider, _) = levels_around(sigma); std::array::from_fn(|level| level == wider || Some(level) == narrower) } @@ -113,9 +119,19 @@ fn smoothed_edges(inputs: &WearInputs) -> f32 { (1.0 - SMOOTHED_SHARE) * inputs.curvature + SMOOTHED_SHARE * inputs.blurred_curvature } +/// The masking at which the fitted cut-off is pinned, the controls' default +const DEFAULT_MASKING: f32 = 0.5; + /// 1 where the area is open enough to wear, 0 where occluded: the cut-off sits at `offset + gain × masking`, softened over `width` fn open_area(occlusion: f32, masking: f32, (offset, gain, width): (f32, f32, f32)) -> f32 { - ((occlusion - (offset + gain * masking)) / width + 0.5).clamp(0.0, 1.0) + // A cut-off below this leaves every occlusion fully open, so the low end eases from it to the default's cut-off instead of masking nothing + let fully_open = -width * 0.5; + let cut_off = if masking < DEFAULT_MASKING && offset < fully_open { + fully_open + (offset + gain * DEFAULT_MASKING - fully_open) * masking / DEFAULT_MASKING + } else { + offset + gain * masking + }; + ((occlusion - cut_off) / width + 0.5).clamp(0.0, 1.0) } // The signals' coefficients are fitted to the reference app's sweeps on a hard-surface bake @@ -177,6 +193,15 @@ mod tests { assert!(value(0.3, 0.6) < value(0.0, 0.6), "edges are masked"); } + #[test] + fn every_ao_masking_above_0_masks_more_occluded_edges() { + let wear = |ao_masking| WearParameters { ao_masking, ..defaults(GeneratorKind::EdgeWear) }; + let occluded_edge = inputs(0.1, 0.0); + let values: Vec = [0.0, 0.05, 0.1, 0.3].iter().map(|masking| wear_value(GeneratorKind::EdgeWear, &wear(*masking), &occluded_edge)).collect(); + assert!(values.windows(2).all(|pair| pair[1] < pair[0]), "{values:?}"); + assert_eq!(wear_value(GeneratorKind::EdgeWear, &wear(1.0), &occluded_edge), 0.0, "full masking clears occluded areas"); + } + #[test] fn a_higher_level_spreads_the_wear_and_a_full_level_is_a_hard_step() { let low = WearParameters { level: 0.25, ..defaults(GeneratorKind::EdgeWear) }; @@ -235,5 +260,13 @@ mod tests { assert_eq!((narrower, wider), (Some(2), 3)); assert!((0.0..=0.1).contains(&weight), "4.6 sits just past radius 4's sigma: {weight}"); assert_eq!(levels_around(500.0).1, LEVEL_RADII.len() - 1, "wider than every level reads the widest"); + for (radius, sigma) in LEVEL_RADII.iter().zip(LEVEL_SIGMAS) { + assert!(((radius * (radius + 1.0)).sqrt() - sigma).abs() < 0.001, "{radius}: {sigma}"); + } + let widest = super::blur_sigma( + GeneratorKind::EdgeWear, + &WearParameters { edges_smoothness: *WearParameters::EDGES_SMOOTHNESS_RANGE.end(), ..WearParameters::defaults(GeneratorKind::EdgeWear).unwrap() }, + ); + assert!(widest < LEVEL_SIGMAS[LEVEL_RADII.len() - 1], "the whole smoothness range lands between built levels: {widest}"); } } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 6f218f1f..f2b3d7df 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -993,7 +993,16 @@ impl GeneratorKind { pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); - GeneratorKind::ALL.into_iter().find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s)) + // The labels before the reference app's names, which agents may still send + let earlier = |kind: GeneratorKind| match kind { + GeneratorKind::EdgeWear => Some("Mask Editor: Edge wear"), + GeneratorKind::Position => Some("Position gradient"), + GeneratorKind::Direction => Some("Light / direction"), + _ => None, + }; + GeneratorKind::ALL + .into_iter() + .find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s) || earlier(*k).is_some_and(|label| norm(label) == norm(s))) } } @@ -1042,6 +1051,11 @@ impl Generator { pub const MIN_NOISE_SCALE: f32 = 0.01; pub const MAX_NOISE_SCALE: f32 = 1000.0; + /// The global blur, balance and contrast the generator applies: none on the wear controls, which have no such controls + pub fn applied_global(&self) -> GeneratorGlobal { + if self.wear.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } + } + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -2288,6 +2302,7 @@ mod tests { assert_eq!(GeneratorKind::parse(kind.label()), Some(kind)); } assert!(!GeneratorKind::ThinAreas.in_picker(), "Thin areas only loads from saved projects and smart masks"); + assert_eq!(GeneratorKind::parse("Light / direction"), Some(GeneratorKind::Direction), "earlier labels still parse"); } #[test] diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e7ee6cce..9f5d493f 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -389,7 +389,10 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { /// Apply `params` to `generator`, using `command` in errors /// The parameters that drive the wear generators' earlier model -const EARLIER_WEAR_KEYS: [&str; 5] = ["level", "softness", "noise", "noiseScale", "offset"]; +const EARLIER_WEAR_KEYS: [&str; 7] = ["level", "softness", "noise", "noiseScale", "offset", "mode", "sizes"]; + +/// The global adjustments, which the wear kinds don't have +const GLOBAL_KEYS: [&str; 3] = ["blur", "balance", "contrast"]; /// The wear controls `effect.add.generator` and `effect.set` take const WEAR_KEYS: [&str; 10] = [ @@ -412,6 +415,14 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result return if given(&WEAR_KEYS) { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; }; + let earlier_model = given(&EARLIER_WEAR_KEYS) || (generator.wear.is_none() && !given(&WEAR_KEYS) && generator.kind != GeneratorKind::FiberGlassEdgeWear); + if given(&GLOBAL_KEYS) && !earlier_model { + return Err(bad(command, format!("{} has no global blur, balance or contrast on its wear controls", generator.kind.label()))); + } + if let Some(unused) = WEAR_KEYS.iter().find(|key| params.get(**key).is_some() && !wear_key_applies(generator.kind, key)) { + return Err(bad(command, format!("{} has no `{unused}`", generator.kind.label()))); + } + if given(&EARLIER_WEAR_KEYS) { if given(&WEAR_KEYS) { return Err(bad(command, "level, softness, noise and offset drive the earlier wear model: give them or the wear controls, not both")); @@ -451,6 +462,16 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result Ok(()) } +/// Whether wear control `key` changes a generator of `kind` +pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { + match key { + "edgesMasking" => kind == GeneratorKind::Dirt, + "edgesSmoothness" | "aoMasking" | "curvatureWeight" => kind != GeneratorKind::Dirt, + "grungeScale" => kind != GeneratorKind::FiberGlassEdgeWear, + _ => true, + } +} + fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { diff --git a/crates/engine/tests/it/generator_wear.rs b/crates/engine/tests/it/generator_wear.rs index cd49c378..c194dfe4 100644 --- a/crates/engine/tests/it/generator_wear.rs +++ b/crates/engine/tests/it/generator_wear.rs @@ -67,3 +67,27 @@ fn mixing_the_models_or_wear_controls_on_other_kinds_is_refused() { assert!(execute(&mut session, "effect.add.generator", &json!({"generator": "fiberGlassEdgeWear", "level": 0.5})).is_err()); assert_eq!(generator(&session, edge_wear).wear, WearParameters::defaults(GeneratorKind::EdgeWear), "a refused edit changes nothing"); } + +#[test] +fn controls_a_kind_does_not_use_are_refused_rather_than_ignored() { + let mut session = session(); + let edge_wear = add(&mut session, json!({"generator": "edgeWear"})); + let dirt = add(&mut session, json!({"generator": "dirt"})); + let fiber_glass = add(&mut session, json!({"generator": "fiberGlassEdgeWear"})); + + assert!(execute(&mut session, "effect.set", &json!({"effect": edge_wear, "edgesMasking": 0.2})).is_err(), "edge wear has no edges masking"); + assert!(execute(&mut session, "effect.set", &json!({"effect": dirt, "edgesSmoothness": 2.0})).is_err(), "dirt has no edges smoothness"); + assert!(execute(&mut session, "effect.set", &json!({"effect": fiber_glass, "grungeScale": 8.0})).is_err(), "fiber glass has no grunge scale"); + assert!(execute(&mut session, "effect.set", &json!({"effect": edge_wear, "blur": 0.5})).is_err(), "the wear controls have no global blur"); +} + +#[test] +fn mode_and_sizes_keep_edge_wear_on_the_earlier_model_where_they_apply() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "edgeWear", "mode": "both"})); + let added = generator(&session, effect); + assert_eq!(added.wear, None, "detail sizes belong to the earlier model"); + assert!(added.detail.is_some()); + execute(&mut session, "effect.set", &json!({"effect": effect, "blur": 0.5})).unwrap(); + assert_eq!(generator(&session, effect).global.blur, 0.5, "the earlier model keeps its global blur"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 3bbeafe9..0fc0b848 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -935,7 +935,7 @@ fn generators_take_blur_balance_and_contrast() { 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": "dirt", "blur": 0.25})).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "ambientOcclusion", "blur": 0.25})).unwrap(); let effect = added["effect"].clone(); execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap(); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 382a76df..54a2178e 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -209,16 +209,16 @@ fn wear_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: & } if let Some(merge) = edit { - let mut params = wear_params(&edited); + let mut params = wear_params(generator.kind, &edited); params["effect"] = json!(id); params["merge"] = json!(merge); app.run("effect.set", params); } } -/// The `effect.set` params that set every wear control to `wear` -fn wear_params(wear: &WearParameters) -> Value { - json!({ +/// The `effect.set` params that set every wear control a generator of `kind` has to `wear` +fn wear_params(kind: GeneratorKind, wear: &WearParameters) -> Value { + let mut params = json!({ "wearLevel": wear.level, "wearContrast": wear.contrast, "grungeAmount": wear.grunge_amount, @@ -229,7 +229,11 @@ fn wear_params(wear: &WearParameters) -> Value { "aoMasking": wear.ao_masking, "curvatureWeight": wear.curvature_weight, "edgesMasking": wear.edges_masking, - }) + }); + if let Some(params) = params.as_object_mut() { + params.retain(|key, _| texturecraft_engine::mask_cmds::wear_key_applies(kind, key)); + } + params } /// An on/off control as the reference app draws it: the name, then a full-width button reading False or True; returns whether it was clicked @@ -295,34 +299,35 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); - // A wear generator restores its wear controls; level, softness, noise and offset would keep it on the earlier model - let mut params = match &defaults.wear { - Some(wear) => wear_params(wear), + let mut params = json!({ + "effect": id, + "seed": defaults.seed, + "invert": defaults.invert, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + "microAnchor": null, + }); + + // A wear generator restores its wear controls only: the earlier model's keys would move it back onto that model + let own = match &defaults.wear { + Some(wear) => wear_params(kind, wear), None => json!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, "noiseScale": defaults.noise_scale, "offset": defaults.offset, + "direction": defaults.direction, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, }), }; - let shared = json!({ - "effect": id, - "seed": defaults.seed, - "direction": defaults.direction, - "invert": defaults.invert, - "blur": defaults.global.blur, - "balance": defaults.global.balance, - "contrast": defaults.global.contrast, - "resolution": format!("{:?}", defaults.resolution.mode), - "customResolution": defaults.resolution.custom, - "resolutionFactor": defaults.resolution.factor, - "microAnchor": null, - }); - if let (Some(params), Value::Object(shared)) = (params.as_object_mut(), shared) { - params.extend(shared); + if let (Some(params), Value::Object(own)) = (params.as_object_mut(), own) { + params.extend(own); } - if let Some(detail) = defaults.detail { + if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { params["mode"] = json!(format!("{:?}", detail.mode)); params["sizes"] = json!(detail.weights); } diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs index c68ebf26..b300a7e2 100644 --- a/crates/ui-egui/tests/it/generator_picker.rs +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -60,8 +60,9 @@ fn the_picker_leaves_thin_areas_out() { let (mut harness, _) = app_with_dirt(); open_picker(&mut harness); + // The picker's tiles are the list options named after generators for kind in GeneratorKind::ALL { - let offered = harness.query_all_by_label(kind.label()).count() > 0; + let offered = harness.query_all_by_role_and_label(Role::ListBoxOption, kind.label()).count() > 0; assert_eq!(offered, kind.in_picker(), "{kind:?}"); } } From 2539643ad97257426dc02ae0a4356aa2a8112823 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 094/153] Curvature sizes: comment without a trailing period --- crates/compose/src/curvature_sizes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 95525331..f47d9fcb 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -13,7 +13,7 @@ use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; /// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]; -/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`]. +/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`] pub struct CurvatureSizes { /// One per blurred size, built once a generator gives that size a weight above 0. pub levels: Vec>>, From d7d9f7bc437f8235080581238ee82ad9cc158a2f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 095/153] Generators: global blur reaches 72 texels at 2K The widest global blur matches the reference's: 16 steps of 4.5 texels at 2K, up from 64. Global blur is new in this pass, so no saved project changes. --- crates/core/src/layer/generator_global.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/core/src/layer/generator_global.rs b/crates/core/src/layer/generator_global.rs index 15349e0d..8133652d 100644 --- a/crates/core/src/layer/generator_global.rs +++ b/crates/core/src/layer/generator_global.rs @@ -13,7 +13,7 @@ pub struct GeneratorGlobal { impl GeneratorGlobal { /// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. - pub const MAX_BLUR: f32 = 64.0; + pub const MAX_BLUR: f32 = 72.0; /// Narrower than this, the balanced range is a hard step. pub const MIN_RANGE: f32 = 1e-6; /// The texels per side the blur radius is measured at (2K). From 05a0ff5118087e825f904fa191dd790cc7cd7a07 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 096/153] Generators: Position, World Space Normals and Curvature/AO sections on the reference's controls Curvature, Ambient Occlusion, Position and the new World Space Normals take the reference app's section controls under the global ones: invert, blur (occlusion and normals), balance (a power curve on position and normals, linear on occlusion), contrast and brightness, and for position and normals three axes, each inverted, blended over the others with its own mode and weighted. Position reads the baked position map, else the mesh's bounds; World Space Normals the baked world space normal, else the mesh's normal; both can read an image input instead. Generators saved before keep their level, softness and noise and render as before; a section control moves one onto the new controls, and level, softness, noise or direction move it back. The curvature section names its detail sizes Sharp to Huge and its modes Dual and Unprocessed; the global invert is a False/True button. --- crates/compose/src/eval.rs | 106 +++++++-- crates/compose/src/lib.rs | 1 + crates/compose/src/sections.rs | 199 +++++++++++++++++ crates/compose/tests/generator_sections.rs | 201 ++++++++++++++++++ crates/core/src/layer.rs | 49 ++++- crates/core/src/layer/axis_blend.rs | 52 +++++ crates/core/src/layer/axis_layer.rs | 14 ++ crates/core/src/layer/section_parameters.rs | 81 +++++++ crates/core/src/layer/wear_parameters.rs | 7 +- crates/core/src/lib.rs | 4 +- crates/engine/src/mask_cmds.rs | 111 +++++++++- crates/engine/src/smart_masks.rs | 16 +- crates/engine/tests/it/bake_resolution.rs | 6 +- crates/engine/tests/it/generator_sections.rs | 90 ++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 146 ++++++++++--- .../ui-egui/tests/it/curvature_generator.rs | 18 +- crates/ui-egui/tests/it/generator_panel.rs | 75 ++++++- 18 files changed, 1117 insertions(+), 60 deletions(-) create mode 100644 crates/compose/src/sections.rs create mode 100644 crates/compose/tests/generator_sections.rs create mode 100644 crates/core/src/layer/axis_blend.rs create mode 100644 crates/core/src/layer/axis_layer.rs create mode 100644 crates/core/src/layer/section_parameters.rs create mode 100644 crates/engine/tests/it/generator_sections.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 933f9852..896dab07 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -15,7 +15,7 @@ use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, - PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, + PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; @@ -36,6 +36,7 @@ use crate::mask_gray::MaskGray; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; @@ -53,6 +54,9 @@ const COVERED: f32 = 0.9999; /// Largest projected step as a share of the image's longer side for non-UV projections const SEAM_JUMP_SHARE: f32 = 0.25; +/// Narrowest extent of the mesh's bounds a position is normalised across +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; @@ -508,8 +512,13 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // Use reference-resolution reach so all callers classify the same filters as stages - EffectKind::Generator(generator) if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.applied_global().blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + EffectKind::Generator(generator) + if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() || sections::generator_blur_sigma(generator) > 0.0 => + { + let section_blur = sections::generator_blur_sigma(generator); + let section_reach = if section_blur > 0.0 { texels(section_blur) } else { 0.0 }; + let reach = texels(generator.applied_global().blur_radius()) + section_reach + generator.resolution.largest_cell(res) as f32; + Some((index, reach, Op::Blur(None))) } // A mirror reads anywhere in its UV tile @@ -1953,19 +1962,14 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.applied_global().blur_radius_at(uv_tile).round() as usize; - if blur_radius > 0 { - let mut weights = cover.to_vec(); - blur(&mut weights, columns, rows, blur_radius); - let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); - blur(&mut sums, columns, rows, blur_radius); - ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_READ_WEIGHT { - *ramp = sum / weight; - } - }); + // The section controls act on the signal before the global blur, their own blur first + if let Some(section) = generator.section_controls() { + blur_over_cover(&mut ramps, cover, (columns, rows), sections::blur_radius_at(generator.kind, §ion, uv_tile)); + ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); + // Finished and blended over the stack below, like the generator effect itself stack .par_chunks(2) @@ -1978,6 +1982,22 @@ fn generator_region( .collect() } +/// `values` blurred by three box passes of `radius`, weighted by `cover` so uncovered texels don't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], (columns, rows): (usize, usize), radius: usize) { + if radius == 0 { + return; + } + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, radius); + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + blur(&mut sums, columns, rows, radius); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(value, (sum, weight))| { + if *weight > MIN_READ_WEIGHT { + *value = sum / weight; + } + }); +} + /// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region @@ -2369,10 +2389,16 @@ fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { return wear::levels_in_use(generator.kind, &wear); } - let detail = generator.detail.as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + let detail = curvature_detail_in_use(generator).as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) } +/// The mode and detail sizes `generator` reads its curvature with: its own, the defaults on Curvature's section controls, else None +fn curvature_detail_in_use(generator: &Generator) -> Option { + let on_section = generator.kind == GeneratorKind::Curvature && generator.section_controls().is_some(); + generator.detail.clone().or_else(|| on_section.then(CurvatureDetail::default)) +} + /// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None fn wear_parameters(generator: &Generator) -> Option { generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) @@ -3296,10 +3322,14 @@ impl<'a, 'b> Texel<'a, 'b> { if needs_gray { [lum(value); 3] } else { value } } + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { if let Some(wear) = wear_parameters(generator) { return self.wear_ramp(generator, &wear, curvature_sizes); } + if let Some(section) = generator.section_controls() { + return self.section_signal(generator, §ion, curvature_sizes); + } let coords = self.coords(); let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); @@ -3319,6 +3349,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, 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, + (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, }; let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; @@ -3354,10 +3385,39 @@ impl<'a, 'b> Texel<'a, 'b> { // Dirt gathers in dents; dents are occluded GeneratorKind::Dirt => -response, GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => 0.0, } } + /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + match generator.kind { + GeneratorKind::Curvature => { + let detail = curvature_detail_in_use(generator).unwrap_or_default(); + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let curvature = self.generator_input(generator, BakedMap::Curvature); + let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + self.curvature_detail(&detail, sizes, curvature, micro) + } + GeneratorKind::AmbientOcclusion => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + GeneratorKind::Position => { + let position = self.generator_input_color(generator, BakedMap::Position).unwrap_or_else(|| self.bounds_position().to_array()); + sections::axes_signal(position, §ion.axes) + } + GeneratorKind::WorldSpaceNormals => { + let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); + sections::axes_signal(normal, §ion.axes) + } + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => 0.0, + } + } + + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) + fn bounds_position(&self) -> Vec3 { + let (low, high) = self.inp.bounds; + self.world().map_or(Vec3::ZERO, |position| ((position - low) / (high - low).max(Vec3::splat(MIN_BOUNDS_EXTENT))).clamp(Vec3::ZERO, Vec3::ONE)) + } + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let curvature = self.generator_input(generator, BakedMap::Curvature).map_or(0.0, |curvature| curvature - 0.5); @@ -3396,7 +3456,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); - finish_generator(generator, ramp) + let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + finish_generator(generator, adjusted) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). @@ -3408,6 +3469,14 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// Generator input `map` at this texel as three channels (an encoded normal or position): what replaces the mesh map, else the mesh map (None when not baked) + fn generator_input_color(&mut self, generator: &Generator, map: BakedMap) -> Option<[f32; 3]> { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + None => self.baked_color(map), + } + } + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { let combine = |edges: f32, cavities: f32| { @@ -5852,7 +5921,8 @@ mod tests { for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { for mode in CurvatureMode::ALL { let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; - let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, ..Generator::new(kind) }; + let generator = + Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, section: None, ..Generator::new(kind) }; 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); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 6318ea16..a2369743 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -36,6 +36,7 @@ pub mod projector_cover; pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; +mod sections; mod shape_distance; mod slope_texel; mod soft_box; diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs new file mode 100644 index 00000000..2a6f9294 --- /dev/null +++ b/crates/compose/src/sections.rs @@ -0,0 +1,199 @@ +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators + +use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, SectionParameters}; + +/// Gaussian sigma of the section blur per unit of its slider, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] +const BLUR_SIGMA_PER_UNIT: f32 = 4.5; + +/// Base of the section balance's power curve: balance 0 raises the signal to 1/25, balance 1 to 25 +const BALANCE_POWER_BASE: f32 = 25.0; + +/// How far above the middle a signal must be to turn white at full contrast +const FULL_CONTRAST_STEP_OFFSET: f32 = 4.6e-5; + +/// The order the axes combine in, as indices into [`SectionParameters::axes`]: top to bottom is the base, front to back goes last +const AXIS_ORDER: [usize; 3] = [SectionParameters::TOP_TO_BOTTOM, SectionParameters::RIGHT_TO_LEFT, SectionParameters::FRONT_TO_BACK]; + +/// A map's three channels (0..1) combined by `axes`: each axis read from its channel, inverted, blended over the axes before it and weighted +pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 { + AXIS_ORDER.iter().fold(0.0, |base, &index| { + let axis = axes[index]; + if axis.weight <= 0.0 { + return base; + } + let layer = if axis.invert { 1.0 - channels[index] } else { channels[index] }; + (base + (blended(axis.blend, base, layer) - base) * axis.weight).clamp(0.0, 1.0) + }) +} + +/// `layer` blended over `base` by `blend`, unclamped +pub(crate) fn blended(blend: AxisBlend, base: f32, layer: f32) -> f32 { + match blend { + AxisBlend::Normal => layer, + AxisBlend::Add => base + layer, + AxisBlend::Subtract => base - layer, + AxisBlend::Multiply => base * layer, + AxisBlend::AddSub => base + 2.0 * layer - 1.0, + AxisBlend::Max => base.max(layer), + } +} + +/// Gaussian sigma of the section blur of a generator of `kind`, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] (0 for kinds without it) +pub(crate) fn blur_sigma(kind: GeneratorKind, section: &SectionParameters) -> f32 { + if SectionParameters::has_blur(kind) { + section.blur.clamp(*SectionParameters::BLUR_RANGE.start(), *SectionParameters::BLUR_RANGE.end()) * BLUR_SIGMA_PER_UNIT + } else { + 0.0 + } +} + +/// Gaussian sigma of `generator`'s section blur in texels at 2K (0 without one) +pub(crate) fn generator_blur_sigma(generator: &Generator) -> f32 { + generator.section_controls().map_or(0.0, |section| blur_sigma(generator.kind, §ion)) +} + +/// The radius of the three box passes that blur like the section blur at `resolution` texels per side +pub(crate) fn blur_radius_at(kind: GeneratorKind, section: &SectionParameters, resolution: u32) -> usize { + let sigma = blur_sigma(kind, section) * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION; + + // Three boxes of radius r spread a texel with variance r (r + 1) + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize +} + +/// `signal` after the section's balance, contrast, brightness and invert, as far as a generator of `kind` has them +pub(crate) fn adjusted(kind: GeneratorKind, section: &SectionParameters, signal: f32) -> f32 { + let mut value = signal.clamp(0.0, 1.0); + if SectionParameters::has_balance(kind) { + let balance = section.balance.clamp(0.0, 1.0); + value = if kind == GeneratorKind::AmbientOcclusion { + GeneratorGlobal { balance, ..GeneratorGlobal::default() }.apply(value) + } else { + value.powf(BALANCE_POWER_BASE.powf(2.0 * balance - 1.0)) + }; + } + value = contrasted(value, section.contrast.clamp(0.0, 1.0)); + if SectionParameters::has_brightness(kind) { + let brightness = section.brightness.clamp(*SectionParameters::BRIGHTNESS_RANGE.start(), *SectionParameters::BRIGHTNESS_RANGE.end()); + value = if brightness > 0.0 { value + brightness * (1.0 - value) } else { value * (1.0 + brightness) }; + } + if section.invert { 1.0 - value } else { value } +} + +/// `value` with its range narrowed around the middle by `contrast` (1 a step just above the middle) +fn contrasted(value: f32, contrast: f32) -> f32 { + if contrast <= 0.0 { + return value; + } + let half_range = 0.5 * (1.0 - contrast); + if 2.0 * half_range < GeneratorGlobal::MIN_RANGE { + return if value > 0.5 + FULL_CONTRAST_STEP_OFFSET { 1.0 } else { 0.0 }; + } + ((value - (0.5 - half_range)) / (2.0 * half_range)).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn axis(blend: AxisBlend, weight: f32) -> AxisLayer { + AxisLayer { invert: false, blend, weight } + } + + fn defaults(kind: GeneratorKind) -> SectionParameters { + SectionParameters::defaults(kind).unwrap() + } + + #[test] + fn each_axis_reads_its_own_channel() { + let channels = [0.2, 0.5, 0.9]; + for (index, expected) in channels.iter().enumerate() { + let mut axes = [axis(AxisBlend::Add, 0.0); 3]; + axes[index].weight = 1.0; + assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "axis {index}"); + } + let mut inverted = [axis(AxisBlend::Add, 0.0); 3]; + inverted[SectionParameters::TOP_TO_BOTTOM] = AxisLayer { invert: true, ..axis(AxisBlend::Add, 1.0) }; + assert!((axes_signal(channels, &inverted) - 0.5).abs() < 1e-6); + inverted[SectionParameters::RIGHT_TO_LEFT] = AxisLayer { invert: true, ..axis(AxisBlend::Normal, 1.0) }; + assert!((axes_signal(channels, &inverted) - 0.8).abs() < 1e-6, "inverted red replaces the base"); + } + + #[test] + fn right_to_left_blends_over_top_to_bottom_and_front_to_back_goes_last() { + let channels = [0.3, 0.8, 0.6]; + let mut axes = [axis(AxisBlend::Add, 0.0), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + for (blend, expected) in [ + (AxisBlend::Normal, 0.3), + (AxisBlend::Add, 1.0), + (AxisBlend::Subtract, 0.5), + (AxisBlend::Multiply, 0.24), + (AxisBlend::AddSub, 0.4), + (AxisBlend::Max, 0.8), + ] { + axes[SectionParameters::RIGHT_TO_LEFT] = axis(blend, 1.0); + assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "{blend:?}"); + } + + axes[SectionParameters::RIGHT_TO_LEFT] = axis(AxisBlend::Normal, 1.0); + axes[SectionParameters::FRONT_TO_BACK] = axis(AxisBlend::Normal, 1.0); + assert!((axes_signal(channels, &axes) - 0.6).abs() < 1e-6, "front to back replaces both"); + } + + #[test] + fn a_weight_lerps_the_unclamped_blend_and_clamps_once() { + let channels = [0.9, 0.8, 0.0]; + let axes = [axis(AxisBlend::Add, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + assert!((axes_signal(channels, &axes) - 1.0).abs() < 1e-6, "0.8 + 0.45 clamps to 1"); + let axes = [axis(AxisBlend::Subtract, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + assert!((axes_signal(channels, &axes) - 0.35).abs() < 1e-6); + } + + #[test] + fn position_balance_is_a_power_curve_and_occlusion_balance_is_linear() { + let position = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::Position) }; + assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(0.2)).abs() < 1e-5); + let position = SectionParameters { balance: 0.75, ..position }; + assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(5.0)).abs() < 1e-5); + + let occlusion = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::AmbientOcclusion) }; + assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.0, "the lower half goes black"); + assert!((adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.75) - 0.5).abs() < 1e-6); + + let curvature = SectionParameters { balance: 0.0, ..defaults(GeneratorKind::Curvature) }; + assert_eq!(adjusted(GeneratorKind::Curvature, &curvature, 0.4), 0.4, "curvature has no balance"); + } + + #[test] + fn contrast_narrows_around_the_middle_and_full_contrast_steps_just_above_it() { + let half = SectionParameters { contrast: 0.5, ..defaults(GeneratorKind::Curvature) }; + assert_eq!(adjusted(GeneratorKind::Curvature, &half, 0.25), 0.0); + assert!((adjusted(GeneratorKind::Curvature, &half, 0.6) - 0.7).abs() < 1e-5); + + let full = SectionParameters { contrast: 1.0, ..half }; + assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5), 0.0, "the middle itself stays black"); + assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5001), 1.0); + } + + #[test] + fn brightness_lerps_towards_white_or_black_then_invert_flips() { + let brighter = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::WorldSpaceNormals) }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &brighter, 0.4) - 0.7).abs() < 1e-6); + let darker = SectionParameters { brightness: -0.5, ..brighter }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &darker, 0.4) - 0.2).abs() < 1e-6); + let inverted = SectionParameters { invert: true, ..darker }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &inverted, 0.4) - 0.8).abs() < 1e-6); + + let occlusion = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::AmbientOcclusion) }; + assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.4, "ambient occlusion has no brightness"); + } + + #[test] + fn only_ambient_occlusion_and_world_space_normals_blur() { + let section = SectionParameters { blur: 16.0, ..defaults(GeneratorKind::Position) }; + assert_eq!(blur_sigma(GeneratorKind::Position, §ion), 0.0); + assert_eq!(blur_sigma(GeneratorKind::WorldSpaceNormals, §ion), 72.0); + assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 0.0, ..section }, 2048), 0); + let radius = blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048) as f32; + assert!((radius * (radius + 1.0)).sqrt() - 4.5 < 0.6, "three boxes of radius {radius} spread like sigma 4.5"); + } +} diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs new file mode 100644 index 00000000..3a9b65c4 --- /dev/null +++ b/crates/compose/tests/generator_sections.rs @@ -0,0 +1,201 @@ +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators on a sphere, beside their earlier model + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, + SectionParameters, Source, TextureSet, +}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// How far a mask value may sit from the expected one +const TOLERANCE: f32 = 1e-3; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, +} + +/// A unit sphere with a white fill layer +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer, baked: BakedMaps::default() } +} + +/// A baked map of `map` holding `value` everywhere +fn uniform_map(map: BakedMap, value: f32) -> BakedMaps { + BakedMaps { resolution: RES, maps: [(map, Arc::new(vec![value; (RES * RES) as usize * map.components()]))].into() } +} + +/// Every covered texel with its world position and normal +fn surface(fixture: &Fixture) -> Vec<((u32, u32), Vec3, Vec3)> { + (0..RES * RES) + .filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos, surface.nrm))) + .collect() +} + +/// The mask of `generator` alone over black at `texels` +fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// The earlier model's smooth step of `signal` at `generator`'s level and softness +fn earlier_ramp(generator: &Generator, signal: f32) -> f32 { + let threshold = 1.0 - generator.level; + let ramp = ((signal - (threshold - generator.softness)) / (2.0 * generator.softness)).clamp(0.0, 1.0); + ramp * ramp * (3.0 - 2.0 * ramp) +} + +fn earlier(kind: GeneratorKind) -> Generator { + Generator { section: None, ..Generator::new(kind) } +} + +fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters)) -> Generator { + let mut generator = Generator::new(kind); + let mut section = generator.section.unwrap(); + change(&mut section); + generator.section = Some(section); + generator +} + +fn assert_close(actual: &[f32], expected: &[f32], what: &str) { + for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); + } +} + +#[test] +fn generators_saved_before_their_new_controls_render_as_before() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let (low, high) = fixture.mesh.bounds(); + let (center, radius) = ((low + high) * 0.5, (high - low).length() * 0.5); + + let position = earlier(GeneratorKind::Position); + let expected: Vec = points.iter().map(|(_, pos, _)| earlier_ramp(&position, ((*pos - center) / radius).y * 0.5 + 0.5)).collect(); + assert_close(&mask(&mut fixture, position, &texels), &expected, "position"); + + let direction = earlier(GeneratorKind::Direction); + let expected: Vec = points.iter().map(|(_, _, nrm)| earlier_ramp(&direction, nrm.y * 0.5 + 0.5)).collect(); + assert_close(&mask(&mut fixture, direction, &texels), &expected, "direction"); + + fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.3); + let occlusion = earlier(GeneratorKind::AmbientOcclusion); + let expected = vec![earlier_ramp(&occlusion, 0.3); texels.len()]; + assert_close(&mask(&mut fixture, occlusion, &texels), &expected, "ambient occlusion"); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion), &texels), &vec![0.3; texels.len()], "new ambient occlusion"); + + fixture.baked = uniform_map(BakedMap::Curvature, 0.7); + let curvature = Generator { detail: None, ..earlier(GeneratorKind::Curvature) }; + let expected = vec![earlier_ramp(&curvature, 0.7); texels.len()]; + assert_close(&mask(&mut fixture, curvature, &texels), &expected, "curvature"); +} + +#[test] +fn world_space_normals_combine_the_axes_of_the_normal() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let channel = |axis: usize| -> Vec { points.iter().map(|(_, _, nrm)| nrm[axis] * 0.5 + 0.5).collect() }; + + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::WorldSpaceNormals), &texels), &channel(1), "top to bottom by default"); + for (index, axis) in [(SectionParameters::RIGHT_TO_LEFT, 0), (SectionParameters::FRONT_TO_BACK, 2)] { + let generator = with_section(GeneratorKind::WorldSpaceNormals, |section| { + section.axes[SectionParameters::TOP_TO_BOTTOM].weight = 0.0; + section.axes[index].weight = 1.0; + }); + assert_close(&mask(&mut fixture, generator, &texels), &channel(axis), "one axis alone"); + } + + let multiplied = with_section(GeneratorKind::WorldSpaceNormals, |section| { + section.axes[SectionParameters::RIGHT_TO_LEFT] = texturecraft_core::AxisLayer { invert: true, blend: AxisBlend::Multiply, weight: 1.0 }; + }); + let expected: Vec = channel(1).iter().zip(channel(0)).map(|(top, right)| top * (1.0 - right)).collect(); + assert_close(&mask(&mut fixture, multiplied, &texels), &expected, "inverted right to left multiplies top to bottom"); + + // Without a baked map, the generator's own World Space Normal input reads instead of the mesh + let mut uniform = Generator::new(GeneratorKind::WorldSpaceNormals); + uniform.inputs.insert(BakedMap::WorldNormal, Source::Uniform([0.2, 0.9, 0.4])); + assert_close(&mask(&mut fixture, uniform, &texels), &vec![0.9; texels.len()], "a replaced input"); +} + +#[test] +fn position_reads_the_mesh_bounds_without_a_bake_and_the_baked_map_with_one() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let (low, high) = fixture.mesh.bounds(); + let expected: Vec = points.iter().map(|(_, pos, _)| (pos.y - low.y) / (high.y - low.y)).collect(); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::Position), &texels), &expected, "bounds"); + + fixture.baked = uniform_map(BakedMap::Position, 0.25); + let balanced = with_section(GeneratorKind::Position, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.25f32.powf(0.2); texels.len()], "a power curve balance"); +} + +#[test] +fn occlusion_balance_is_linear_and_brightness_lerps() { + let mut fixture = fixture(); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.0).collect(); + fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.6); + let balanced = with_section(GeneratorKind::AmbientOcclusion, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.2; texels.len()], "balance 0.25 stretches the upper half"); + + let inverted = with_section(GeneratorKind::AmbientOcclusion, |section| section.invert = true); + assert_close(&mask(&mut fixture, inverted, &texels), &vec![0.4; texels.len()], "section invert"); + + fixture.baked = uniform_map(BakedMap::Position, 0.4); + let brighter = with_section(GeneratorKind::Position, |section| section.brightness = 0.5); + assert_close(&mask(&mut fixture, brighter, &texels), &vec![0.7; texels.len()], "brightness 0.5 halves the way to white"); + let darker = with_section(GeneratorKind::Position, |section| section.brightness = -0.5); + assert_close(&mask(&mut fixture, darker, &texels), &vec![0.2; texels.len()], "brightness -0.5 halves the value"); +} + +#[test] +fn section_blur_spreads_occlusion_across_a_step() { + let mut fixture = fixture(); + let step: Vec = (0..RES * RES).map(|index| if index % RES < RES / 2 { 0.0 } else { 1.0 }).collect(); + fixture.baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(step))].into() }; + let row: Vec<(u32, u32)> = surface(&fixture).iter().map(|point| point.0).filter(|texel| texel.0.abs_diff(RES / 2) <= 2).collect(); + assert!(!row.is_empty()); + + let sharp = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion), &row); + assert!(sharp.iter().all(|value| *value == 0.0 || *value == 1.0), "unblurred: {sharp:?}"); + let blurred = mask(&mut fixture, with_section(GeneratorKind::AmbientOcclusion, |section| section.blur = 16.0), &row); + assert!(blurred.iter().all(|value| *value > 0.05 && *value < 0.95), "blurred across the step: {blurred:?}"); + + let position = with_section(GeneratorKind::Position, |section| section.blur = 16.0); + fixture.baked = uniform_map(BakedMap::Position, 0.3); + assert_close(&mask(&mut fixture, position, &row), &vec![0.3; row.len()], "position has no section blur"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index f2b3d7df..1e0f001d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -12,6 +12,8 @@ use crate::{ ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, }; +mod axis_blend; +mod axis_layer; mod curvature_detail; mod curvature_mode; mod decal_flip; @@ -23,6 +25,7 @@ mod output_resolution; mod resolution_mode; mod sampling; mod scale_mode; +mod section_parameters; mod tile_blending; mod tile_generator; mod tile_input_distribution; @@ -33,6 +36,8 @@ mod uv_transform; mod uv_wrap; mod wear_parameters; +pub use axis_blend::AxisBlend; +pub use axis_layer::AxisLayer; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; @@ -44,6 +49,7 @@ pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; pub use scale_mode::ScaleMode; +pub use section_parameters::SectionParameters; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; @@ -930,10 +936,12 @@ pub enum GeneratorKind { Direction, /// Worn edges of a fibreglass-like coating: the edges fade into its grunge FiberGlassEdgeWear, + /// The world space normal's axes combined into one gray + WorldSpaceNormals, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 8] = [ + pub const ALL: [GeneratorKind; 9] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -942,6 +950,7 @@ impl GeneratorKind { GeneratorKind::Position, GeneratorKind::Direction, GeneratorKind::FiberGlassEdgeWear, + GeneratorKind::WorldSpaceNormals, ]; pub fn label(self) -> &'static str { match self { @@ -953,6 +962,7 @@ impl GeneratorKind { GeneratorKind::Position => "Position", GeneratorKind::Direction => "Light", GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", + GeneratorKind::WorldSpaceNormals => "World Space Normals", } } @@ -967,6 +977,7 @@ impl GeneratorKind { GeneratorKind::Position => "Position", GeneratorKind::Direction => "Direction", GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", + GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", } } @@ -987,7 +998,9 @@ impl GeneratorKind { GeneratorKind::Curvature => &[BakedMap::Curvature], GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], - GeneratorKind::Position | GeneratorKind::Direction => &[], + GeneratorKind::Position => &[BakedMap::Position], + GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], + GeneratorKind::Direction => &[], } } @@ -1041,6 +1054,9 @@ pub struct Generator { /// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub wear: Option, + /// The section controls of Curvature, Ambient Occlusion, Position and World Space Normals (None: the level, softness and noise above, as saved before they existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub section: Option, } impl Generator { @@ -1056,6 +1072,16 @@ impl Generator { if self.wear.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } } + /// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None + pub fn section_controls(&self) -> Option { + self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals)) + } + + /// Whether the generator is on the level, softness and noise it had before the reference app's controls + pub fn on_earlier_model(&self) -> bool { + self.wear.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear + } + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -1085,6 +1111,7 @@ impl Generator { inputs: BTreeMap::new(), micro: None, wear: WearParameters::defaults(kind), + section: SectionParameters::defaults(kind), } } @@ -2317,6 +2344,24 @@ mod tests { assert!(curvature.get("wear").is_none(), "other kinds save no wear controls"); } + #[test] + fn generators_saved_before_their_section_controls_load_on_the_earlier_model() { + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position] { + let mut saved = serde_json::to_value(Generator::new(kind)).unwrap(); + assert!(saved.get("section").is_some(), "new {kind:?} generators have the reference's controls"); + + saved.as_object_mut().unwrap().remove("section"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert!(loaded.on_earlier_model(), "{kind:?}: level, softness and noise keep driving it"); + assert_eq!(loaded.applied_global(), loaded.global, "{kind:?} keeps its global adjustments"); + } + + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::WorldSpaceNormals)).unwrap(); + saved.as_object_mut().unwrap().remove("section"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.section_controls(), SectionParameters::defaults(GeneratorKind::WorldSpaceNormals), "it has no earlier model"); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/core/src/layer/axis_blend.rs b/crates/core/src/layer/axis_blend.rs new file mode 100644 index 00000000..bb53925d --- /dev/null +++ b/crates/core/src/layer/axis_blend.rs @@ -0,0 +1,52 @@ +use serde::{Deserialize, Serialize}; + +/// How an axis of a World Space Normals or Position generator combines with the axes before it +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AxisBlend { + /// The axis replaces what is below it + Normal, + /// The axis adds to what is below it + Add, + /// The axis is taken from what is below it + Subtract, + /// The axis multiplies what is below it + Multiply, + /// The axis adds above its middle gray and subtracts below it + AddSub, + /// The brighter of the axis and what is below it + Max, +} + +impl AxisBlend { + pub const ALL: [AxisBlend; 6] = [AxisBlend::Normal, AxisBlend::Add, AxisBlend::Subtract, AxisBlend::Multiply, AxisBlend::AddSub, AxisBlend::Max]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + AxisBlend::Normal => "Normal", + AxisBlend::Add => "Linear Dodge (Add)", + AxisBlend::Subtract => "Subtract", + AxisBlend::Multiply => "Multiply", + AxisBlend::AddSub => "Add/Sub", + AxisBlend::Max => "Max (Lighten)", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + AxisBlend::Normal => "normal", + AxisBlend::Add => "add", + AxisBlend::Subtract => "subtract", + AxisBlend::Multiply => "multiply", + AxisBlend::AddSub => "addSub", + AxisBlend::Max => "max", + } + } + + /// The blend named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + AxisBlend::ALL.into_iter().find(|blend| blend.id().eq_ignore_ascii_case(name) || blend.label().eq_ignore_ascii_case(name)) + } +} diff --git a/crates/core/src/layer/axis_layer.rs b/crates/core/src/layer/axis_layer.rs new file mode 100644 index 00000000..58e5bae6 --- /dev/null +++ b/crates/core/src/layer/axis_layer.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +use super::axis_blend::AxisBlend; + +/// One axis of a World Space Normals or Position generator: its channel, inverted or not, blended over the axes before it +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AxisLayer { + /// The axis read from its far side + pub invert: bool, + pub blend: AxisBlend, + /// How much of the blend shows (0..1) + pub weight: f32, +} diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs new file mode 100644 index 00000000..583c4a99 --- /dev/null +++ b/crates/core/src/layer/section_parameters.rs @@ -0,0 +1,81 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; +use super::axis_blend::AxisBlend; +use super::axis_layer::AxisLayer; + +/// The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, applied before the global ones +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SectionParameters { + pub invert: bool, + /// Blur of the signal ([`SectionParameters::BLUR_RANGE`]; Ambient Occlusion and World Space Normals) + pub blur: f32, + /// Shifts the signal darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged (not Curvature) + pub balance: f32, + /// Narrows the signal around its middle (0 unchanged, 1 a hard step) + pub contrast: f32, + /// Lifts the signal towards white (above 0) or black (below 0) ([`SectionParameters::BRIGHTNESS_RANGE`]; not Ambient Occlusion) + pub brightness: f32, + /// Right to left, top to bottom and front to back (Position and World Space Normals) + pub axes: [AxisLayer; 3], +} + +impl SectionParameters { + pub const BLUR_RANGE: std::ops::RangeInclusive = 0.0..=16.0; + pub const BRIGHTNESS_RANGE: std::ops::RangeInclusive = -1.0..=1.0; + /// Index in [`SectionParameters::axes`] of each axis + pub const RIGHT_TO_LEFT: usize = 0; + pub const TOP_TO_BOTTOM: usize = 1; + pub const FRONT_TO_BACK: usize = 2; + + /// The reference app's defaults for `kind`, or None for kinds without section controls + pub fn defaults(kind: GeneratorKind) -> Option { + let axis = |weight: f32| AxisLayer { invert: false, blend: AxisBlend::Add, weight }; + let defaults = SectionParameters { invert: false, blur: 0.0, balance: 0.5, contrast: 0.0, brightness: 0.0, axes: [axis(0.0), axis(1.0), axis(0.0)] }; + match kind { + GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals => Some(defaults), + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => None, + } + } + + /// Whether a generator of `kind` has the section blur + pub fn has_blur(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` has the section balance + pub fn has_balance(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` has the section brightness + pub fn has_brightness(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Curvature | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` combines the three axes of a map + pub fn has_axes(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Every value brought into its range, non-finite ones to the defaults of `kind` + pub fn clamped(self, kind: GeneratorKind) -> SectionParameters { + let defaults = SectionParameters::defaults(kind).unwrap_or(self); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + let axes = std::array::from_fn(|index| { + let (axis, default) = (self.axes[index], defaults.axes[index]); + AxisLayer { weight: within(axis.weight, default.weight, 0.0..=1.0), ..axis } + }); + SectionParameters { + invert: self.invert, + blur: within(self.blur, defaults.blur, SectionParameters::BLUR_RANGE), + balance: within(self.balance, defaults.balance, 0.0..=1.0), + contrast: within(self.contrast, defaults.contrast, 0.0..=1.0), + brightness: within(self.brightness, defaults.brightness, SectionParameters::BRIGHTNESS_RANGE), + axes, + } + } +} diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index b0c2de19..956dbd1a 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -49,7 +49,12 @@ impl WearParameters { match kind { GeneratorKind::EdgeWear | GeneratorKind::Dirt => Some(shared), GeneratorKind::FiberGlassEdgeWear => Some(WearParameters { curvature_weight: 0.25, ..shared }), - GeneratorKind::ThinAreas | GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::Direction => None, + GeneratorKind::ThinAreas + | GeneratorKind::Curvature + | GeneratorKind::AmbientOcclusion + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b494aa57..222613cf 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,10 +111,10 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, + AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, + Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9f5d493f..1b23275d 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::{ - BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, WearParameters, + AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, + GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), level?, softness?, noise?, offset?: -1..1 added to the result (instead keep edgeWear and dirt on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear and section controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -472,8 +472,111 @@ pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { } } +/// The parameters that drive the earlier model of the kinds with section controls +const EARLIER_SECTION_KEYS: [&str; 6] = ["level", "softness", "noise", "noiseScale", "offset", "direction"]; + +/// The section controls `effect.add.generator` and `effect.set` take, beside the axis keys made of [`AXIS_NAMES`] and [`AXIS_SUFFIXES`] +const SECTION_KEYS: [&str; 5] = ["sectionInvert", "sectionBlur", "sectionBalance", "sectionContrast", "sectionBrightness"]; + +/// The name of each axis in its keys, in the order of [`SectionParameters::axes`], and what follows it +const AXIS_NAMES: [&str; 3] = ["rightLeft", "topBottom", "frontBack"]; +const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; + +/// The section controls and the axis keys `params` gives +fn given_new_model_keys(params: &Value) -> Vec { + let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}"))); + SECTION_KEYS.iter().map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() +} + +/// The section controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model +fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let kind = generator.kind; + let new_keys = given_new_model_keys(params); + let earlier = EARLIER_SECTION_KEYS.iter().any(|key| params.get(*key).is_some()); + let Some(defaults) = SectionParameters::defaults(kind) else { + return match new_keys.first() { + Some(key) => { + Err(bad(command, format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position and World Space Normals have it", kind.label()))) + } + None => Ok(()), + }; + }; + if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) { + return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); + } + + if earlier { + if !new_keys.is_empty() { + return Err(bad(command, "level, softness, noise, offset and direction drive the earlier model: give them or the section controls, not both")); + } + if kind == GeneratorKind::WorldSpaceNormals { + return Err(bad( + command, + "World Space Normals has section controls only (sectionBalance, topBottomWeight…), no level, softness, noise, offset or direction", + )); + } + generator.section = None; + return Ok(()); + } + if new_keys.is_empty() { + return Ok(()); + } + + // Moving onto the reference's controls starts from the kind's defaults: the earlier model's values no longer apply + if generator.on_earlier_model() { + let defaults = Generator::new(kind); + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale) = + (defaults.level, defaults.softness, defaults.noise_amount, defaults.noise_scale); + (generator.offset, generator.direction) = (defaults.offset, defaults.direction); + } + + let mut section = generator.section_controls().unwrap_or(defaults); + for (key, value) in [ + ("sectionBlur", &mut section.blur), + ("sectionBalance", &mut section.balance), + ("sectionContrast", &mut section.contrast), + ("sectionBrightness", &mut section.brightness), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(invert) = boolp(params, "sectionInvert") { + section.invert = invert; + } + for (axis, name) in section.axes.iter_mut().zip(AXIS_NAMES) { + if let Some(invert) = boolp(params, &format!("{name}Invert")) { + axis.invert = invert; + } + if let Some(weight) = f32p(params, &format!("{name}Weight")) { + axis.weight = weight; + } + let blend_key = format!("{name}Blend"); + if let Some(blend) = params.get(&blend_key) { + let blend_name = blend.as_str().ok_or_else(|| bad(command, format!("`{blend_key}` must be a string")))?; + axis.blend = AxisBlend::parse(blend_name).ok_or_else(|| bad(command, format!("unknown blending mode `{blend_name}`")))?; + } + } + generator.section = Some(section.clamped(kind)); + Ok(()) +} + +/// Whether section control `key` changes a generator of `kind` +pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { + let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix))); + match key { + "sectionInvert" | "sectionContrast" => SectionParameters::defaults(kind).is_some(), + "sectionBlur" => SectionParameters::has_blur(kind), + "sectionBalance" => SectionParameters::has_balance(kind), + "sectionBrightness" => SectionParameters::has_brightness(kind), + _ if axis_key => SectionParameters::has_axes(kind), + _ => false, + } +} + fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; + section_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 244c412e..ceeb23cf 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,14 +79,24 @@ 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 (curvature as baked, without detail sizes or wear controls) +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear and section controls) pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: 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, detail: None, wear: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { + level, + softness, + noise_amount: noise, + direction, + invert, + detail: None, + wear: None, + section: None, + ..Generator::new(kind) + }) } /// A triplanar grayscale pattern fill diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index 6ea63f2f..b2c88885 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -127,5 +127,9 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { 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"); + let expected = [240.0 / 255.0, 20.0 / 255.0]; + assert!( + mask.iter().zip(expected).all(|(value, expected)| (value - expected).abs() < 0.001), + "generators sample the whole bake through the working layout: {mask:?}" + ); } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs new file mode 100644 index 00000000..02c68135 --- /dev/null +++ b/crates/engine/tests/it/generator_sections.rs @@ -0,0 +1,90 @@ +//! The section controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise + +use serde_json::{Value, json}; +use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters}; +use texturecraft_engine::mask_cmds::section_key_applies; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +#[test] +fn new_generators_start_on_the_reference_controls() { + let mut session = session(); + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert_eq!(added.section, SectionParameters::defaults(added.kind), "{kind}"); + } + assert_eq!(GeneratorKind::parse("World Space Normals"), Some(GeneratorKind::WorldSpaceNormals)); +} + +#[test] +fn a_section_control_moves_an_earlier_generator_onto_the_defaults_with_that_change() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "position", "level": 0.8})); + assert_eq!(generator(&session, effect).section, None, "level keeps it on the earlier model"); + + let edit = json!({"effect": effect, "sectionBalance": 0.3, "rightLeftBlend": "Max (Lighten)", "frontBackWeight": 4.0, "sectionBrightness": -3.0}); + execute(&mut session, "effect.set", &edit).unwrap(); + + let moved = generator(&session, effect); + let mut expected = SectionParameters::defaults(GeneratorKind::Position).unwrap(); + expected.balance = 0.3; + expected.brightness = -1.0; + expected.axes[SectionParameters::RIGHT_TO_LEFT].blend = AxisBlend::Max; + expected.axes[SectionParameters::FRONT_TO_BACK].weight = 1.0; + assert_eq!(moved.section, Some(expected), "the rest at defaults, values clamped"); + assert_eq!(moved.level, Generator::new(GeneratorKind::Position).level, "the earlier model's values start over"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "noise": 0.5})).unwrap(); + assert_eq!(generator(&session, effect).section, None, "noise moves it back"); +} + +#[test] +fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { + let mut session = session(); + let curvature = add(&mut session, json!({"generator": "curvature"})); + let occlusion = add(&mut session, json!({"generator": "ambientOcclusion"})); + let position = add(&mut session, json!({"generator": "position"})); + let normals = add(&mut session, json!({"generator": "worldSpaceNormals"})); + let dirt = add(&mut session, json!({"generator": "dirt"})); + + for (effect, key) in [ + (curvature, "sectionBalance"), + (curvature, "sectionBlur"), + (curvature, "topBottomWeight"), + (occlusion, "sectionBrightness"), + (occlusion, "rightLeftInvert"), + (position, "sectionBlur"), + (dirt, "sectionContrast"), + ] { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).is_err(), "{key} on {effect}"); + } + for (effect, key) in [(curvature, "sectionBrightness"), (occlusion, "sectionBlur"), (normals, "sectionBlur"), (normals, "frontBackWeight")] { + execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).unwrap(); + } + + assert!(execute(&mut session, "effect.set", &json!({"effect": position, "level": 0.5, "sectionContrast": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": normals, "softness": 0.5})).is_err(), "World Space Normals has no earlier model"); + assert!(execute(&mut session, "effect.set", &json!({"effect": position, "topBottomBlend": "overlay"})).is_err()); + assert_eq!(generator(&session, position).section, SectionParameters::defaults(GeneratorKind::Position), "a refused edit changes nothing"); + + assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); + assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b3a87d44..44effae5 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,6 +36,7 @@ mod filters; mod folder_contents; mod frame_selection; mod generator_inputs; +mod generator_sections; mod generator_swap; mod generator_wear; mod gradient_map; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 54a2178e..e9df3bba 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,7 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, SectionParameters, Source, + WearParameters, }; use crate::TextureCraftApp; @@ -35,9 +36,12 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); } else { global_adjustments(app, ui, id, generator); - ramp_parameters(app, ui, id, generator); - if generator.kind == GeneratorKind::Curvature { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + if generator.on_earlier_model() { + ramp_parameters(app, ui, id, generator); + } + // Saved before the section controls, a generator shows them at their defaults: editing one moves it onto them + if let Some(defaults) = SectionParameters::defaults(generator.kind) { + section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { @@ -51,9 +55,9 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer }); }); }); - if !generator.kind.inputs().is_empty() { + if !inputs_in_use(generator).is_empty() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { - for map in generator.kind.inputs() { + for map in inputs_in_use(generator) { input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); } }); @@ -91,6 +95,12 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr } } +/// The inputs `generator` reads: none for Position on its earlier model, which reads the mesh itself +fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { + let reads_geometry = generator.on_earlier_model() && generator.kind == GeneratorKind::Position; + if reads_geometry { &[] } else { generator.kind.inputs() } +} + /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -103,6 +113,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::AmbientOcclusion => (tr("Occluded areas."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]), GeneratorKind::Position => (tr("A gradient across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + GeneratorKind::WorldSpaceNormals => (tr("Surfaces facing along the world's axes."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), }; // Wrapped rows: a long line must not widen the panel past its edge @@ -169,7 +180,7 @@ fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: Outpu /// Global invert, blur, balance and contrast: what every generator applies to its finished value. fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { let (mut invert, mut global) = (generator.invert, generator.global); - let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let invert_edit = true_false(ui, tr("Global invert"), &mut invert).then_some(false); let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); @@ -299,7 +310,7 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); - let mut params = json!({ + let params = json!({ "effect": id, "seed": defaults.seed, "invert": defaults.invert, @@ -309,10 +320,12 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "microAnchor": null, }); - // A wear generator restores its wear controls only: the earlier model's keys would move it back onto that model - let own = match &defaults.wear { - Some(wear) => wear_params(kind, wear), - None => json!({ + // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model + let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); + let own = match (&defaults.wear, &defaults.section) { + (Some(wear), _) => wear_params(kind, wear), + (None, Some(section)) => merged(section_params(kind, section), global), + (None, None) => json!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, @@ -324,9 +337,7 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "contrast": defaults.global.contrast, }), }; - if let (Some(params), Value::Object(own)) = (params.as_object_mut(), own) { - params.extend(own); - } + let mut params = merged(params, own); if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { params["mode"] = json!(format!("{:?}", detail.mode)); params["sizes"] = json!(detail.weights); @@ -334,9 +345,99 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { params } +/// The keys of `extra` added to the object `params` +fn merged(mut params: Value, extra: Value) -> Value { + if let (Some(params), Value::Object(extra)) = (params.as_object_mut(), extra) { + params.extend(extra); + } + params +} + +/// The section controls of generator effect `id` under the kind's own heading, showing `shown` +fn section_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, shown: SectionParameters) { + let kind = generator.kind; + let title = match kind { + GeneratorKind::Curvature => tr("Curvature"), + GeneratorKind::AmbientOcclusion => tr("Ambient occlusion"), + GeneratorKind::Position => tr("Position"), + _ => tr("World space normal"), + }; + section(ui, "generator_section", title, true, |ui| { + let mut edited = shown; + let mut edit = true_false(ui, tr("Invert"), &mut edited.invert).then_some(false); + if kind == GeneratorKind::Curvature { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + if SectionParameters::has_blur(kind) { + edit = edit.or(slider_edit(ui, tr("Blur"), &mut edited.blur, SectionParameters::BLUR_RANGE, 2)); + } + if SectionParameters::has_balance(kind) { + edit = edit.or(slider_edit(ui, tr("Balance"), &mut edited.balance, 0.0..=1.0, 2)); + } + edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + if SectionParameters::has_brightness(kind) { + edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, SectionParameters::BRIGHTNESS_RANGE, 2)); + } + if SectionParameters::has_axes(kind) { + let titles = [tr("Right to left"), tr("Top to bottom"), tr("Front to back")]; + for (index, (axis, title)) in edited.axes.iter_mut().zip(titles).enumerate() { + // Each axis's dropdown needs its own id: the dropdown's id comes from its label + ui.push_id(("generator_axis", index), |ui| { + section(ui, "generator_axis", title, true, |ui| { + edit = edit.or(true_false(ui, tr("Invert"), &mut axis.invert).then_some(false)); + combo(ui, tr("Blending mode"), axis_blend_label(axis.blend), |ui| { + for blend in AxisBlend::ALL { + if ui.selectable_label(blend == axis.blend, axis_blend_label(blend)).clicked() { + axis.blend = blend; + edit = Some(false); + } + } + }); + }); + edit = edit.or(slider_edit(ui, title, &mut axis.weight, 0.0..=1.0, 2)); + }); + } + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), section_params(kind, &edited))); + } + }); +} + +/// The `effect.set` params that set every section control a generator of `kind` has to `section` +fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { + let mut params = json!({ + "sectionInvert": section.invert, + "sectionBlur": section.blur, + "sectionBalance": section.balance, + "sectionContrast": section.contrast, + "sectionBrightness": section.brightness, + }); + if let Some(params) = params.as_object_mut() { + for (name, axis) in ["rightLeft", "topBottom", "frontBack"].into_iter().zip(§ion.axes) { + params.insert(format!("{name}Invert"), json!(axis.invert)); + params.insert(format!("{name}Blend"), json!(axis.blend.id())); + params.insert(format!("{name}Weight"), json!(axis.weight)); + } + params.retain(|key, _| texturecraft_engine::mask_cmds::section_key_applies(kind, key)); + } + params +} + +/// The translated name of axis blending mode `blend` +fn axis_blend_label(blend: AxisBlend) -> &'static str { + match blend { + AxisBlend::Normal => tr("Normal"), + AxisBlend::Add => tr("Linear Dodge (Add)"), + AxisBlend::Subtract => tr("Subtract"), + AxisBlend::Multiply => tr("Multiply"), + AxisBlend::AddSub => tr("Add/Sub"), + AxisBlend::Max => tr("Max (Lighten)"), + } +} + /// 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 tokens = 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 { @@ -346,18 +447,15 @@ fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, } }); - ui.label(caption(tr("Detail sizes"))); + let names = [tr("Sharp"), tr("Fine"), tr("Soft"), tr("Medium"), tr("Large"), tr("Big"), tr("Huge")]; 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)); + for (weight, name) in weights.iter_mut().zip(names) { + edit = edit.or(slider_edit(ui, name, 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(tokens.text_dim)); - } } /// The translated name of curvature mode `mode`. @@ -365,8 +463,8 @@ 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"), + CurvatureMode::Both => tr("Dual"), + CurvatureMode::Raw => tr("Unprocessed"), } } diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index a5b321bc..aae768dc 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -26,10 +26,20 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { (harness, LayerId(effect)) } +/// The name the panel's Mode dropdown gives `mode` +fn mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => "Edges", + CurvatureMode::Cavities => "Cavities", + CurvatureMode::Both => "Dual", + CurvatureMode::Raw => "Unprocessed", + } +} + fn select_mode(harness: &mut Harness<'_, TextureCraftApp>, current: CurvatureMode, next: CurvatureMode) { - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(current.label())).unwrap().click(); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(mode_label(current))).unwrap().click(); harness.run_steps(2); - harness.get_by_label(next.label()).click(); + harness.get_by_label(mode_label(next)).click(); harness.run_steps(4); } @@ -44,9 +54,9 @@ fn mode_and_detail_controls_apply_and_undo() { assert_eq!(detail(&harness).mode, CurvatureMode::Cavities); let previous = detail(&harness); let history = harness.state().session.history_labels().len(); - harness.get_by_label("8 px").scroll_to_me(); + harness.get_by_label("Large").scroll_to_me(); harness.run_steps(3); - let label = harness.get_by_label("8 px").rect(); + let label = harness.get_by_label("Large").rect(); let start = egui::pos2(label.left() + 20.0, label.bottom() + 10.0); let end = start + egui::vec2(100.0, 0.0); harness.drag_at(start); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index b53f5012..edf21484 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -141,6 +141,67 @@ fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { assert!(generator(&harness, effect).inputs.is_empty()); } +/// How many nodes carry `label` +fn count(harness: &Harness<'_, TextureCraftApp>, label: &str) -> usize { + harness.query_all_by_label(label).count() +} + +#[test] +fn each_kind_shows_its_section_rows_and_no_earlier_ones() { + let rows = [ + ("curvature", &["Sharp", "Huge", "Brightness", "Global contrast"][..], &["Balance", "Blending mode", "Level"][..]), + ("ambientOcclusion", &["Blur", "Balance", "Global contrast"][..], &["Brightness", "Blending mode", "Level"][..]), + ("position", &["Balance", "Brightness", "Right to left", "Front to back"][..], &["Blur", "Level", "Sharp"][..]), + ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top to bottom"][..], &["Level", "Softness"][..]), + ]; + for (kind, shown, hidden) in rows { + let (harness, _) = harness_with(false, json!({"generator": kind})); + for label in shown { + assert!(count(&harness, label) > 0, "{kind} shows {label}"); + } + for label in hidden { + assert_eq!(count(&harness, label), 0, "{kind} hides {label}"); + } + } + + let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); + assert_eq!(count(&harness, "Blending mode"), 3); + let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); + assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); +} + +#[test] +fn each_axis_has_its_own_blending_mode_dropdown() { + let (mut harness, effect) = harness_with(false, json!({"generator": "worldSpaceNormals"})); + let added = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).count() + }; + assert_eq!(added(&harness), 3); + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + + let axes = generator(&harness, effect).section.unwrap().axes; + assert_eq!(axes.map(|axis| axis.blend), [AxisBlend::Add, AxisBlend::Add, AxisBlend::Multiply], "only front to back changed"); +} + +#[test] +fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { + let (mut harness, effect) = harness_with(false, json!({"generator": "position", "level": 0.4})); + assert_eq!(generator(&harness, effect).section, None); + + drag_slider(&mut harness, "Balance"); + + let section = generator(&harness, effect).section.expect("on the section controls now"); + let defaults = SectionParameters::defaults(GeneratorKind::Position).unwrap(); + assert_ne!(section.balance, defaults.balance, "the drag set the balance"); + assert_eq!(SectionParameters { balance: defaults.balance, ..section }, defaults, "the other controls start at their defaults"); + assert_eq!(count(&harness, "Level"), 0, "the earlier rows are gone"); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -185,3 +246,15 @@ fn wear_panel_snapshots() { harness.render().unwrap().save(directory.join(format!("wear-panel-{kind}.png"))).unwrap(); } } + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn section_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let (mut harness, _) = harness_with(true, json!({"generator": kind})); + harness.run_steps(12); + harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); + } +} From 02bda17b9faaa77ddc270eb87a213bccda23edb5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 097/153] Generators: Light on the reference's angles, highlight and attenuation Light takes the reference app's controls: a horizontal and a vertical angle, each a dial beside an Angle slider in degrees, highlight glossiness and level, and light attenuation. It shades the world space normal (else the mesh's normal) towards the light and fades the side away from it across the position map (else the mesh's bounds); invert shades the far side instead. Both maps can read an image input instead, and Light has no global adjustments. Light generators saved before keep their level, softness, noise and direction and render as before; a light control moves one onto the new controls. --- crates/compose/src/eval.rs | 10 +- crates/compose/src/sections.rs | 83 +++++++++++++- crates/compose/tests/generator_sections.rs | 49 ++++++++- crates/core/src/layer.rs | 23 ++-- crates/core/src/layer/light_parameters.rs | 50 +++++++++ crates/core/src/lib.rs | 2 +- crates/engine/src/mask_cmds.rs | 64 ++++++++--- crates/engine/src/smart_masks.rs | 5 +- crates/engine/tests/it/generator_sections.rs | 33 +++++- crates/ui-egui/src/generator_panel.rs | 109 +++++++++++++++++-- crates/ui-egui/src/widgets.rs | 31 ++++-- crates/ui-egui/tests/it/generator_panel.rs | 34 +++++- 12 files changed, 439 insertions(+), 54 deletions(-) create mode 100644 crates/core/src/layer/light_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 896dab07..1e342957 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2057,10 +2057,10 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset (the light controls invert their shading themselves) fn finish_generator(generator: &Generator, ramp: f32) -> f32 { let value = generator.applied_global().apply(ramp); - let value = if generator.invert { 1.0 - value } else { value }; + let value = if generator.invert && generator.light.is_none() { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (value + offset).clamp(0.0, 1.0) } @@ -3327,6 +3327,12 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(wear) = wear_parameters(generator) { return self.wear_ramp(generator, &wear, curvature_sizes); } + if let Some(light) = &generator.light { + let normal = + self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let position = self.generator_input_color(generator, BakedMap::Position).map_or_else(|| self.bounds_position(), Vec3::from); + return sections::light_value(light, normal, position, generator.invert); + } if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, curvature_sizes); } diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index 2a6f9294..a9da83bc 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -1,6 +1,7 @@ -//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, and the Light generator's shading -use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, SectionParameters}; +use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, LightParameters, SectionParameters}; +use texturecraft_geom::glam::Vec3; /// Gaussian sigma of the section blur per unit of its slider, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] const BLUR_SIGMA_PER_UNIT: f32 = 4.5; @@ -14,6 +15,15 @@ const FULL_CONTRAST_STEP_OFFSET: f32 = 4.6e-5; /// The order the axes combine in, as indices into [`SectionParameters::axes`]: top to bottom is the base, front to back goes last const AXIS_ORDER: [usize; 3] = [SectionParameters::TOP_TO_BOTTOM, SectionParameters::RIGHT_TO_LEFT, SectionParameters::FRONT_TO_BACK]; +/// Distance of a light-facing tangent plane from the centre of the position map's unit cube +const ATTENUATION_PLANE_OFFSET: f32 = 0.5; + +/// Light attenuation above which the falloff fades the whole mesh towards black instead of steepening +const ATTENUATION_STEEPEST: f32 = 0.5; + +/// Shortest decoded normal still given a direction +const MIN_NORMAL_LENGTH: f32 = 1e-6; + /// A map's three channels (0..1) combined by `axes`: each axis read from its channel, inverted, blended over the axes before it and weighted pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 { AXIS_ORDER.iter().fold(0.0, |base, &index| { @@ -91,6 +101,35 @@ fn contrasted(value: f32, contrast: f32) -> f32 { ((value - (0.5 - half_range)) / (2.0 * half_range)).clamp(0.0, 1.0) } +/// The direction the light comes from: `horizontal` degrees around the up axis from -X towards +Z, `vertical` degrees above the horizon +pub(crate) fn light_direction(horizontal: f32, vertical: f32) -> Vec3 { + let (horizontal, vertical) = (horizontal.to_radians(), vertical.to_radians()); + Vec3::new(-vertical.cos() * horizontal.cos(), vertical.sin(), vertical.cos() * horizontal.sin()) +} + +/// The Light generator at a texel with world `normal` and `position` (0..1 across the mesh's bounds): lit, highlighted and faded with depth +pub(crate) fn light_value(light: &LightParameters, normal: Vec3, position: Vec3, invert: bool) -> f32 { + let direction = light_direction(light.horizontal, light.vertical); + let normal = if normal.length() > MIN_NORMAL_LENGTH { normal.normalize() } else { Vec3::Y }; + + // Glossiness 0 lights the half facing away too, 0.5 is a plain diffuse falloff + let glossiness = light.glossiness.clamp(*LightParameters::GLOSSINESS_RANGE.start(), *LightParameters::GLOSSINESS_RANGE.end()); + let threshold = 2.0 * glossiness - 1.0; + let diffuse = ((normal.dot(direction) - threshold) / (1.0 - threshold)).clamp(0.0, 1.0); + let highlight_level = light.highlight_level.clamp(0.0, 1.0); + let diffuse = if highlight_level >= 1.0 { if diffuse > 0.0 { 1.0 } else { 0.0 } } else { (diffuse / (1.0 - highlight_level)).clamp(0.0, 1.0) }; + + // Depth from the tangent plane facing the light + let depth = ATTENUATION_PLANE_OFFSET - (position - Vec3::splat(0.5)).dot(direction); + let attenuation = light.attenuation.clamp(0.0, 1.0); + let kept = if attenuation <= ATTENUATION_STEEPEST { + (1.0 - 2.0 * attenuation * depth).clamp(0.0, 1.0) + } else { + (1.0 - depth).clamp(0.0, 1.0) * (2.0 - 2.0 * attenuation) + }; + kept * if invert { 1.0 - diffuse } else { diffuse } +} + #[cfg(test)] mod tests { use super::*; @@ -196,4 +235,44 @@ mod tests { let radius = blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048) as f32; assert!((radius * (radius + 1.0)).sqrt() - 4.5 < 0.6, "three boxes of radius {radius} spread like sigma 4.5"); } + + #[test] + fn light_angles_point_at_the_reference_axes() { + let close = |a: Vec3, b: Vec3| (a - b).length() < 1e-5; + assert!(close(light_direction(0.0, 0.0), Vec3::NEG_X)); + assert!(close(light_direction(90.0, 0.0), Vec3::Z)); + assert!(close(light_direction(180.0, 0.0), Vec3::X)); + assert!(close(light_direction(33.0, 90.0), Vec3::Y)); + } + + #[test] + fn light_lights_the_faces_towards_it() { + let light = LightParameters { horizontal: 0.0, vertical: 0.0, attenuation: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() }; + let middle = Vec3::splat(0.5); + assert_eq!(light_value(&light, Vec3::NEG_X, middle, false), 1.0); + assert_eq!(light_value(&light, Vec3::X, middle, false), 0.0); + assert!((light_value(&light, Vec3::new(-1.0, 1.0, 0.0), middle, false) - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5, "a plain diffuse falloff"); + assert_eq!(light_value(&light, Vec3::X, middle, true), 1.0, "invert lights the far side"); + + let half_lambert = LightParameters { glossiness: 0.0, ..light }; + assert!((light_value(&half_lambert, Vec3::Y, middle, false) - 0.5).abs() < 1e-6, "glossiness 0 lights the side faces half"); + let highlighted = LightParameters { highlight_level: 0.5, ..light }; + assert!((light_value(&highlighted, Vec3::new(-1.0, 3.0, 0.0), middle, false) - 2.0 * 10f32.sqrt().recip()).abs() < 1e-5); + let saturated = LightParameters { highlight_level: 1.0, ..light }; + assert_eq!(light_value(&saturated, Vec3::new(-0.01, 1.0, 0.0), middle, false), 1.0, "any lit texel is white"); + } + + #[test] + fn attenuation_darkens_the_side_away_from_the_light() { + let light = LightParameters { horizontal: 0.0, vertical: 0.0, glossiness: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() }; + let near = light_value(&light, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false); + let far = light_value(&light, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false); + assert!((near - 0.5).abs() < 1e-6, "the face of the bounds towards the light keeps its value"); + assert!((far - 0.25).abs() < 1e-6, "attenuation 0.25 halves it across the bounds"); + + let none = LightParameters { attenuation: 0.0, ..light }; + assert_eq!(light_value(&none, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false), near); + let full = LightParameters { attenuation: 1.0, ..light }; + assert_eq!(light_value(&full, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false), 0.0, "attenuation 1 is black everywhere"); + } } diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs index 3a9b65c4..27693163 100644 --- a/crates/compose/tests/generator_sections.rs +++ b/crates/compose/tests/generator_sections.rs @@ -1,11 +1,11 @@ -//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators on a sphere, beside their earlier model +//! The section and light controls of the Curvature, Ambient Occlusion, Position, World Space Normals and Light generators on a sphere, beside their earlier model use std::sync::Arc; use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, - SectionParameters, Source, TextureSet, + AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, LightParameters, Mask, MaskBackground, + Project, SectionParameters, Source, TextureSet, }; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -77,7 +77,7 @@ fn earlier_ramp(generator: &Generator, signal: f32) -> f32 { } fn earlier(kind: GeneratorKind) -> Generator { - Generator { section: None, ..Generator::new(kind) } + Generator { section: None, light: None, ..Generator::new(kind) } } fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters)) -> Generator { @@ -88,6 +88,14 @@ fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters) generator } +fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator { + let mut generator = Generator::new(GeneratorKind::Direction); + let mut light = generator.light.unwrap(); + change(&mut light); + generator.light = Some(light); + generator +} + fn assert_close(actual: &[f32], expected: &[f32], what: &str) { for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); @@ -199,3 +207,36 @@ fn section_blur_spreads_occlusion_across_a_step() { fixture.baked = uniform_map(BakedMap::Position, 0.3); assert_close(&mask(&mut fixture, position, &row), &vec![0.3; row.len()], "position has no section blur"); } + +#[test] +fn light_angles_light_the_faces_towards_them() { + let mut fixture = fixture(); + let points = surface(&fixture); + let facing = |axis: Vec3| -> Vec<(u32, u32)> { points.iter().filter(|(_, _, nrm)| nrm.dot(axis) > 0.97).map(|point| point.0).collect() }; + + for (horizontal, vertical, towards) in [(0.0, 0.0, Vec3::NEG_X), (90.0, 0.0, Vec3::Z), (180.0, 0.0, Vec3::X), (0.0, 90.0, Vec3::Y)] { + let light = with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (horizontal, vertical, 0.0)); + let lit = mask(&mut fixture, light.clone(), &facing(towards)); + let dark = mask(&mut fixture, light, &facing(-towards)); + assert!(lit.iter().all(|value| *value > 0.95), "{horizontal}° {vertical}° lights {towards}: {lit:?}"); + assert!(dark.iter().all(|value| *value == 0.0), "{horizontal}° {vertical}° leaves {} dark: {dark:?}", -towards); + } + + let inverted = Generator { invert: true, ..with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (0.0, 0.0, 0.0)) }; + assert!(mask(&mut fixture, inverted, &facing(Vec3::X)).iter().all(|value| *value > 0.95), "invert lights the far side"); +} + +#[test] +fn light_attenuation_darkens_the_side_away_from_the_light() { + let mut fixture = fixture(); + let sides: Vec<(u32, u32)> = surface(&fixture).iter().filter(|(_, _, nrm)| nrm.y > 0.97).map(|point| point.0).collect(); + let half_lit = + |attenuation: f32| with_light(|light| (light.horizontal, light.vertical, light.glossiness, light.attenuation) = (0.0, 0.0, 0.0, attenuation)); + + let kept = mask(&mut fixture, half_lit(0.0), &sides); + let attenuated = mask(&mut fixture, half_lit(0.5), &sides); + for (kept, attenuated) in kept.iter().zip(&attenuated) { + assert!((kept - 0.5).abs() < 0.15, "the top is about half lit from the side: {kept}"); + assert!(*attenuated < kept * 0.75, "halfway across the bounds, attenuation darkens it: {attenuated} vs {kept}"); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1e0f001d..fedcca8a 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -20,6 +20,7 @@ mod decal_flip; mod decal_symmetry; mod filtering; mod generator_global; +mod light_parameters; mod micro_detail; mod output_resolution; mod resolution_mode; @@ -44,6 +45,7 @@ pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; +pub use light_parameters::LightParameters; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; @@ -1000,7 +1002,7 @@ impl GeneratorKind { GeneratorKind::ThinAreas => &[BakedMap::Thickness], GeneratorKind::Position => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], - GeneratorKind::Direction => &[], + GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], } } @@ -1057,6 +1059,9 @@ pub struct Generator { /// The section controls of Curvature, Ambient Occlusion, Position and World Space Normals (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub section: Option, + /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub light: Option, } impl Generator { @@ -1067,9 +1072,9 @@ impl Generator { pub const MIN_NOISE_SCALE: f32 = 0.01; pub const MAX_NOISE_SCALE: f32 = 1000.0; - /// The global blur, balance and contrast the generator applies: none on the wear controls, which have no such controls + /// The global blur, balance and contrast the generator applies: none on the wear and light controls, which have no such controls pub fn applied_global(&self) -> GeneratorGlobal { - if self.wear.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } + if self.wear.is_some() || self.light.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } } /// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None @@ -1079,7 +1084,7 @@ impl Generator { /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { - self.wear.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear + self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear } pub fn new(kind: GeneratorKind) -> Generator { @@ -1112,6 +1117,7 @@ impl Generator { micro: None, wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), + light: LightParameters::defaults(kind), } } @@ -2345,12 +2351,13 @@ mod tests { } #[test] - fn generators_saved_before_their_section_controls_load_on_the_earlier_model() { - for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position] { + fn generators_saved_before_their_section_or_light_controls_load_on_the_earlier_model() { + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position, GeneratorKind::Direction] { let mut saved = serde_json::to_value(Generator::new(kind)).unwrap(); - assert!(saved.get("section").is_some(), "new {kind:?} generators have the reference's controls"); + let key = if kind == GeneratorKind::Direction { "light" } else { "section" }; + assert!(saved.get(key).is_some(), "new {kind:?} generators have the reference's controls"); - saved.as_object_mut().unwrap().remove("section"); + saved.as_object_mut().unwrap().remove(key); let loaded: Generator = serde_json::from_value(saved).unwrap(); assert!(loaded.on_earlier_model(), "{kind:?}: level, softness and noise keep driving it"); assert_eq!(loaded.applied_global(), loaded.global, "{kind:?} keeps its global adjustments"); diff --git a/crates/core/src/layer/light_parameters.rs b/crates/core/src/layer/light_parameters.rs new file mode 100644 index 00000000..5334675c --- /dev/null +++ b/crates/core/src/layer/light_parameters.rs @@ -0,0 +1,50 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; + +/// The Light generator's controls: where the light comes from, how its highlight spreads and how it fades across the mesh +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LightParameters { + /// Degrees around the up axis (0 from -X, 90 from +Z) + pub horizontal: f32, + /// Degrees above the horizon (90 from straight above) + pub vertical: f32, + /// How narrow the lit area is ([`LightParameters::GLOSSINESS_RANGE`]; 0.5 a plain diffuse falloff) + pub glossiness: f32, + /// How much the lit area is pushed to white (0..1; 1 every lit texel white) + pub highlight_level: f32, + /// How much the side away from the light darkens (0..1) + pub attenuation: f32, +} + +impl LightParameters { + pub const ANGLE_RANGE: std::ops::RangeInclusive = 0.0..=360.0; + pub const GLOSSINESS_RANGE: std::ops::RangeInclusive = 0.0..=0.999; + + /// The reference app's defaults for `kind`, or None for kinds other than Light + pub fn defaults(kind: GeneratorKind) -> Option { + (kind == GeneratorKind::Direction).then_some(LightParameters { + horizontal: 90.0, + vertical: 45.0, + glossiness: 0.5, + highlight_level: 0.0, + attenuation: 0.25, + }) + } + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> LightParameters { + let defaults = LightParameters::defaults(GeneratorKind::Direction).unwrap_or(self); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + LightParameters { + horizontal: within(self.horizontal, defaults.horizontal, LightParameters::ANGLE_RANGE), + vertical: within(self.vertical, defaults.vertical, LightParameters::ANGLE_RANGE), + glossiness: within(self.glossiness, defaults.glossiness, LightParameters::GLOSSINESS_RANGE), + highlight_level: within(self.highlight_level, defaults.highlight_level, 0.0..=1.0), + attenuation: within(self.attenuation, defaults.attenuation, 0.0..=1.0), + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 222613cf..c5ff7ec3 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,7 +112,7 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 1b23275d..2ed442d1 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, + GeneratorKind, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear and section controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -472,7 +472,7 @@ pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { } } -/// The parameters that drive the earlier model of the kinds with section controls +/// The parameters that drive the earlier model of the kinds with section or light controls const EARLIER_SECTION_KEYS: [&str; 6] = ["level", "softness", "noise", "noiseScale", "offset", "direction"]; /// The section controls `effect.add.generator` and `effect.set` take, beside the axis keys made of [`AXIS_NAMES`] and [`AXIS_SUFFIXES`] @@ -482,32 +482,41 @@ const SECTION_KEYS: [&str; 5] = ["sectionInvert", "sectionBlur", "sectionBalance const AXIS_NAMES: [&str; 3] = ["rightLeft", "topBottom", "frontBack"]; const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; -/// The section controls and the axis keys `params` gives +/// The Light generator's controls +const LIGHT_KEYS: [&str; 5] = ["lightHorizontal", "lightVertical", "highlightGlossiness", "highlightLevel", "lightAttenuation"]; + +/// The section controls, the axis keys and the light controls `params` gives fn given_new_model_keys(params: &Value) -> Vec { let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}"))); - SECTION_KEYS.iter().map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() + SECTION_KEYS.iter().chain(LIGHT_KEYS.iter()).map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() } -/// The section controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model +/// The section and light controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let kind = generator.kind; let new_keys = given_new_model_keys(params); let earlier = EARLIER_SECTION_KEYS.iter().any(|key| params.get(*key).is_some()); - let Some(defaults) = SectionParameters::defaults(kind) else { + let section_defaults = SectionParameters::defaults(kind); + let light_defaults = LightParameters::defaults(kind); + if section_defaults.is_none() && light_defaults.is_none() { return match new_keys.first() { - Some(key) => { - Err(bad(command, format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position and World Space Normals have it", kind.label()))) - } + Some(key) => Err(bad( + command, + format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position, World Space Normals and Light have them", kind.label()), + )), None => Ok(()), }; - }; + } if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) { return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); } if earlier { if !new_keys.is_empty() { - return Err(bad(command, "level, softness, noise, offset and direction drive the earlier model: give them or the section controls, not both")); + return Err(bad( + command, + "level, softness, noise, offset and direction drive the earlier model: give them or the section and light controls, not both", + )); } if kind == GeneratorKind::WorldSpaceNormals { return Err(bad( @@ -516,8 +525,13 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res )); } generator.section = None; + generator.light = None; return Ok(()); } + let on_light = generator.light.is_some() || (light_defaults.is_some() && !new_keys.is_empty()); + if on_light && GLOBAL_KEYS.iter().any(|key| params.get(*key).is_some()) { + return Err(bad(command, "Light has no global blur, balance or contrast on its light controls")); + } if new_keys.is_empty() { return Ok(()); } @@ -528,8 +542,28 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res (generator.level, generator.softness, generator.noise_amount, generator.noise_scale) = (defaults.level, defaults.softness, defaults.noise_amount, defaults.noise_scale); (generator.offset, generator.direction) = (defaults.offset, defaults.direction); + if light_defaults.is_some() { + generator.global = defaults.global; + } + } + if let Some(defaults) = light_defaults { + let light = generator.light.get_or_insert(defaults); + for (key, value) in [ + ("lightHorizontal", &mut light.horizontal), + ("lightVertical", &mut light.vertical), + ("highlightGlossiness", &mut light.glossiness), + ("highlightLevel", &mut light.highlight_level), + ("lightAttenuation", &mut light.attenuation), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + *light = light.clamped(); + return Ok(()); } + let Some(defaults) = section_defaults else { return Ok(()) }; let mut section = generator.section_controls().unwrap_or(defaults); for (key, value) in [ ("sectionBlur", &mut section.blur), @@ -561,7 +595,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res Ok(()) } -/// Whether section control `key` changes a generator of `kind` +/// Whether section or light control `key` changes a generator of `kind` pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix))); match key { @@ -570,7 +604,7 @@ pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { "sectionBalance" => SectionParameters::has_balance(kind), "sectionBrightness" => SectionParameters::has_brightness(kind), _ if axis_key => SectionParameters::has_axes(kind), - _ => false, + _ => LIGHT_KEYS.contains(&key) && LightParameters::defaults(kind).is_some(), } } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index ceeb23cf..6b98e571 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,9 +79,9 @@ 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 (curvature as baked, without detail sizes or the wear and section controls) +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear, section and light controls) pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, light: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). @@ -95,6 +95,7 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, detail: None, wear: None, section: None, + light: None, ..Generator::new(kind) }) } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 02c68135..60676684 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -1,7 +1,7 @@ -//! The section controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise +//! The section and light controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise use serde_json::{Value, json}; -use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters}; +use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, LightParameters, SectionParameters}; use texturecraft_engine::mask_cmds::section_key_applies; use texturecraft_engine::{Session, execute}; @@ -31,6 +31,9 @@ fn new_generators_start_on_the_reference_controls() { let added = generator(&session, effect); assert_eq!(added.section, SectionParameters::defaults(added.kind), "{kind}"); } + let effect = add(&mut session, json!({"generator": "direction"})); + let light = generator(&session, effect); + assert_eq!(light.light, LightParameters::defaults(GeneratorKind::Direction)); assert_eq!(GeneratorKind::parse("World Space Normals"), Some(GeneratorKind::WorldSpaceNormals)); } @@ -72,6 +75,7 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { (occlusion, "sectionBrightness"), (occlusion, "rightLeftInvert"), (position, "sectionBlur"), + (position, "lightHorizontal"), (dirt, "sectionContrast"), ] { assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).is_err(), "{key} on {effect}"); @@ -88,3 +92,28 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); } + +#[test] +fn light_takes_its_controls_and_refuses_the_global_ones() { + let mut session = session(); + let light = add(&mut session, json!({"generator": "direction"})); + execute(&mut session, "effect.set", &json!({"effect": light, "lightHorizontal": 400.0, "highlightGlossiness": 1.0, "invert": true})).unwrap(); + let edited = generator(&session, light); + let expected = LightParameters { + horizontal: 360.0, + glossiness: *LightParameters::GLOSSINESS_RANGE.end(), + ..LightParameters::defaults(GeneratorKind::Direction).unwrap() + }; + assert_eq!(edited.light, Some(expected)); + assert!(edited.invert); + + assert!(execute(&mut session, "effect.set", &json!({"effect": light, "blur": 0.5})).is_err(), "Light has no global blur"); + assert!(execute(&mut session, "effect.set", &json!({"effect": light, "sectionInvert": true})).is_err()); + + let earlier = add(&mut session, json!({"generator": "direction", "level": 0.4, "blur": 0.3})); + assert_eq!(generator(&session, earlier).light, None, "the earlier model keeps its global adjustments"); + execute(&mut session, "effect.set", &json!({"effect": earlier, "lightVertical": 60.0})).unwrap(); + let moved = generator(&session, earlier); + assert_eq!(moved.light.map(|light| light.vertical), Some(60.0)); + assert_eq!(moved.global, Generator::new(GeneratorKind::Direction).global, "the light controls have no global adjustments"); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index e9df3bba..effda2d1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,8 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, SectionParameters, Source, - WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, + SectionParameters, Source, WearParameters, }; use crate::TextureCraftApp; @@ -13,7 +13,7 @@ use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_be use crate::i18n::{baked_map_label, tr, trf}; use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; use crate::theme::{Tokens, caption}; -use crate::widgets::{combo, section, slider_edit}; +use crate::widgets::{combo, section, slider_edit, slider_edit_with_suffix}; /// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. const INPUT_TILE_SIZE: f32 = 32.0; @@ -23,6 +23,14 @@ const INPUT_TILE_ICON_SIZE: f32 = 16.0; /// Width of a False/True button, so the buttons line up under each other const TOGGLE_WIDTH: f32 = 136.0; +/// Edge of a light angle's dial, the width of its needle and the radius of its hub +const DIAL_SIZE: f32 = 36.0; +const DIAL_NEEDLE_WIDTH: f32 = 2.0; +const DIAL_HUB_RADIUS: f32 = 2.0; + +/// Closest to a dial's centre a pointer still turns it, so the angle is defined +const DIAL_DEAD_ZONE: f32 = 1.0; + /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = Tokens::get(ui.ctx()); @@ -34,15 +42,20 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer if let Some(defaults) = WearParameters::defaults(generator.kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); + } else if let Some(light) = generator.light { + light_parameters(app, ui, id, Some(generator.invert), light); } else { global_adjustments(app, ui, id, generator); if generator.on_earlier_model() { ramp_parameters(app, ui, id, generator); } - // Saved before the section controls, a generator shows them at their defaults: editing one moves it onto them + // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); } + if let Some(defaults) = LightParameters::defaults(generator.kind) { + light_parameters(app, ui, id, None, defaults); + } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { micro_detail_properties(app, ui, id, generator.micro, layer); @@ -95,9 +108,9 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr } } -/// The inputs `generator` reads: none for Position on its earlier model, which reads the mesh itself +/// The inputs `generator` reads: none for Position and Light on their earlier model, which read the mesh itself fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { - let reads_geometry = generator.on_earlier_model() && generator.kind == GeneratorKind::Position; + let reads_geometry = generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction); if reads_geometry { &[] } else { generator.kind.inputs() } } @@ -322,10 +335,11 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); - let own = match (&defaults.wear, &defaults.section) { - (Some(wear), _) => wear_params(kind, wear), - (None, Some(section)) => merged(section_params(kind, section), global), - (None, None) => json!({ + let own = match (&defaults.wear, &defaults.section, &defaults.light) { + (Some(wear), _, _) => wear_params(kind, wear), + (None, _, Some(light)) => light_params(light), + (None, Some(section), None) => merged(section_params(kind, section), global), + (None, None, None) => json!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, @@ -436,6 +450,81 @@ fn axis_blend_label(blend: AxisBlend) -> &'static str { } } +/// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) +fn light_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, invert: Option, shown: LightParameters) { + if let Some(mut invert) = invert + && true_false(ui, tr("Invert"), &mut invert) + { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + let mut edited = shown; + let mut edit = angle_row(ui, "generator_light_horizontal", tr("Horizontal angle"), &mut edited.horizontal); + edit = edit.or(angle_row(ui, "generator_light_vertical", tr("Vertical angle"), &mut edited.vertical)); + edit = edit.or(slider_edit(ui, tr("Highlight glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Highlight level"), &mut edited.highlight_level, 0.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Light attenuation"), &mut edited.attenuation, 0.0..=1.0, 2)); + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), light_params(&edited))); + } +} + +/// The `effect.set` params that set every light control to `light` +fn light_params(light: &LightParameters) -> Value { + json!({ + "lightHorizontal": light.horizontal, + "lightVertical": light.vertical, + "highlightGlossiness": light.glossiness, + "highlightLevel": light.highlight_level, + "lightAttenuation": light.attenuation, + }) +} + +/// A light angle in degrees: its name, then a dial beside an Angle slider; `Some(merge)` when either changes it +fn angle_row(ui: &mut Ui, id: &str, label: &str, degrees: &mut f32) -> Option { + ui.label(label); + ui.push_id(id, |ui| { + ui.horizontal(|ui| { + let dial = angle_dial(ui, label, degrees); + let slider = ui.vertical(|ui| slider_edit_with_suffix(ui, tr("Angle"), degrees, LightParameters::ANGLE_RANGE, 0, "°")).inner; + dial.or(slider) + }) + .inner + }) + .inner +} + +/// A round dial whose needle points at `degrees` (counterclockwise from the right); dragging it turns it, `Some(merge)` like [`slider_edit`] +fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(egui::vec2(DIAL_SIZE, DIAL_SIZE), egui::Sense::click_and_drag()); + let mut edit = None; + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() + { + let offset = pointer - rect.center(); + let turned = (-offset.y).atan2(offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); + if offset.length() > DIAL_DEAD_ZONE && (turned - *degrees).abs() > f32::EPSILON { + *degrees = turned; + // Later frames of one drag share its undo step + edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); + } + } + if response.drag_stopped() || response.clicked() { + ui.data_mut(|data| data.remove_temp::(response.id)); + } + let shown = *degrees; + response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(shown), label)); + + let painter = ui.painter(); + let radius = DIAL_SIZE * 0.5 - 1.0; + painter.circle(rect.center(), radius, tokens.field, egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.button_border)); + let (sin, cos) = degrees.to_radians().sin_cos(); + let tip = rect.center() + egui::vec2(cos, -sin) * radius; + painter.line_segment([rect.center(), tip], egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.accent)); + painter.circle_filled(rect.center(), DIAL_HUB_RADIUS, tokens.text); + edit +} + /// 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 shown = detail.cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 126f7be5..809fc048 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -19,7 +19,7 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { - slider_inner(ui, label, value, range, decimals).0 + slider_inner(ui, label, value, range, decimals, "").0 } /// For an editor `id` drawn every frame: `Some(merge)` when it `changed`, merge true for a press's later changes (one undo step per drag; typing never merges) @@ -57,7 +57,12 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { /// true for the later changes of one drag, so the edit that applies them (with the command's /// `merge` param) continues the drag's first undo step. pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> Option { - slider_inner(ui, label, value, range, decimals).1 + slider_inner(ui, label, value, range, decimals, "").1 +} + +/// [`slider_edit`] showing `suffix` after the value (a unit such as °), which a typed value may leave out +pub fn slider_edit_with_suffix(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> Option { + slider_inner(ui, label, value, range, decimals, suffix).1 } /// Least width of a slider's value field, wide enough for a short number @@ -75,12 +80,24 @@ const SLIDER_KNOB_RADIUS: f32 = 4.5; /// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { + suffixed_value_header(ui, label, value, range, decimals, "") +} + +/// [`value_header`] showing `suffix` after the value, which a typed value may leave out +fn suffixed_value_header( + ui: &mut Ui, + label: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + decimals: usize, + suffix: &str, +) -> (egui::Id, Option) { let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() - .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) + .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}{suffix}"), font.clone(), tokens.text).size().x) .fold(SLIDER_VALUE_MIN_WIDTH, f32::max); let mut edit = None; let field = ui @@ -88,7 +105,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std ui.label(RichText::new(label).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - let shown = format!("{value:.decimals$}"); + let shown = format!("{value:.decimals$}{suffix}"); // Keep unfinished input while the document value is re-read each frame let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); @@ -111,7 +128,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std if response.lost_focus() && !escape && text != shown - && let Ok(parsed) = text.trim().parse::() + && let Ok(parsed) = text.trim().strip_suffix(suffix).unwrap_or(text.trim()).trim_end().parse::() && parsed.is_finite() && parsed.clamp(minimum, maximum) != *value { @@ -127,10 +144,10 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std (field, edit) } -fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { +fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> (Response, Option) { let (minimum, maximum) = (*range.start(), *range.end()); let width = ui.available_width(); - let (field, mut edit) = value_header(ui, label, value, range, decimals); + let (field, mut edit) = suffixed_value_header(ui, label, value, range, decimals, suffix); let (rect, mut response) = ui.allocate_exact_size(vec2(width, SLIDER_TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index edf21484..6d49c460 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -153,6 +153,11 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { ("ambientOcclusion", &["Blur", "Balance", "Global contrast"][..], &["Brightness", "Blending mode", "Level"][..]), ("position", &["Balance", "Brightness", "Right to left", "Front to back"][..], &["Blur", "Level", "Sharp"][..]), ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top to bottom"][..], &["Level", "Softness"][..]), + ( + "direction", + &["Horizontal angle", "Vertical angle", "Highlight glossiness", "Highlight level", "Light attenuation"][..], + &["Global blur", "Level"][..], + ), ]; for (kind, shown, hidden) in rows { let (harness, _) = harness_with(false, json!({"generator": kind})); @@ -166,6 +171,8 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); assert_eq!(count(&harness, "Blending mode"), 3); + let (harness, _) = harness_with(false, json!({"generator": "direction"})); + assert_eq!(count(&harness, "Angle"), 2, "an Angle slider beside each dial"); let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); } @@ -202,6 +209,31 @@ fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { assert_eq!(count(&harness, "Level"), 0, "the earlier rows are gone"); } +#[test] +fn the_light_dial_turns_towards_the_pointer() { + let (mut harness, effect) = harness_with(false, json!({"generator": "direction"})); + harness.get_by_role_and_label(Role::Slider, "Horizontal angle").scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_role_and_label(Role::Slider, "Horizontal angle").rect(); + let left = egui::pos2(rect.left() + 2.0, rect.center().y); + harness.drag_at(left); + harness.run_steps(2); + harness.drop_at(left); + harness.run_steps(3); + let horizontal = generator(&harness, effect).light.unwrap().horizontal; + assert!((horizontal - 180.0).abs() < 1.0, "a click left of the centre points the needle left: {horizontal}"); +} + +#[test] +fn restore_defaults_puts_a_light_back_on_its_defaults() { + let (mut harness, effect) = harness_with(false, json!({"generator": "direction", "lightHorizontal": 10.0, "highlightLevel": 0.7, "invert": true})); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Direction)); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -252,7 +284,7 @@ fn wear_panel_snapshots() { fn section_panel_snapshots() { let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); - for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals", "direction"] { let (mut harness, _) = harness_with(true, json!({"generator": kind})); harness.run_steps(12); harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); From 35ac5bc2ea563dc2fd8b25167ec2a2613a220ce6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 098/153] Generators: Position and Light read the mesh bounds, review fixes Position and Light read the mesh's own position across its bounds (an image in the Position input still overrides it): the baked Position map's normalisation is a bake setting, bounding sphere by default, which squeezes the reference's 0..1 per axis. The light dials start at 0 on the left and turn clockwise like the reference's. Commands refuse an input the generator does not read and `direction` on kinds that point no way; the detail size hint follows the sizes in use; tests check the exact blur radius, a blurred position and the axis dropdown by its section. --- crates/compose/src/eval.rs | 24 ++++++++++++-------- crates/compose/src/sections.rs | 4 ++-- crates/compose/tests/generator_sections.rs | 23 ++++++++++++------- crates/core/src/layer.rs | 12 ++++++++++ crates/engine/src/mask_cmds.rs | 9 ++++++-- crates/engine/tests/it/generator_sections.rs | 18 +++++++++++++++ crates/ui-egui/src/generator_panel.rs | 21 +++++++---------- crates/ui-egui/tests/it/generator_panel.rs | 16 ++++++++++--- 8 files changed, 89 insertions(+), 38 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 1e342957..b0ae6b29 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2389,16 +2389,10 @@ fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { return wear::levels_in_use(generator.kind, &wear); } - let detail = curvature_detail_in_use(generator).as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + let detail = generator.detail_in_use().as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) } -/// The mode and detail sizes `generator` reads its curvature with: its own, the defaults on Curvature's section controls, else None -fn curvature_detail_in_use(generator: &Generator) -> Option { - let on_section = generator.kind == GeneratorKind::Curvature && generator.section_controls().is_some(); - generator.detail.clone().or_else(|| on_section.then(CurvatureDetail::default)) -} - /// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None fn wear_parameters(generator: &Generator) -> Option { generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) @@ -3330,7 +3324,7 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(light) = &generator.light { let normal = self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); - let position = self.generator_input_color(generator, BakedMap::Position).map_or_else(|| self.bounds_position(), Vec3::from); + let position = Vec3::from(self.position_input(generator)); return sections::light_value(light, normal, position, generator.invert); } if let Some(section) = generator.section_controls() { @@ -3355,6 +3349,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, 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, + // World Space Normals always computes with its section controls: this arm only keeps the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, }; let signal = @@ -3399,7 +3394,7 @@ impl<'a, 'b> Texel<'a, 'b> { fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { match generator.kind { GeneratorKind::Curvature => { - let detail = curvature_detail_in_use(generator).unwrap_or_default(); + let detail = generator.detail_in_use().unwrap_or_default(); let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; let curvature = self.generator_input(generator, BakedMap::Curvature); let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); @@ -3407,17 +3402,26 @@ impl<'a, 'b> Texel<'a, 'b> { } GeneratorKind::AmbientOcclusion => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), GeneratorKind::Position => { - let position = self.generator_input_color(generator, BakedMap::Position).unwrap_or_else(|| self.bounds_position().to_array()); + let position = self.position_input(generator); sections::axes_signal(position, §ion.axes) } GeneratorKind::WorldSpaceNormals => { let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); sections::axes_signal(normal, §ion.axes) } + // Only the kinds with section controls reach here: this arm only keeps the match whole GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => 0.0, } } + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds: the baked Position map is not read, its normalisation is a bake setting + fn position_input(&mut self, generator: &Generator) -> [f32; 3] { + match generator.inputs.get(&BakedMap::Position) { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + None => self.bounds_position().to_array(), + } + } + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) fn bounds_position(&self) -> Vec3 { let (low, high) = self.inp.bounds; diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index a9da83bc..bee4012d 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -232,8 +232,8 @@ mod tests { assert_eq!(blur_sigma(GeneratorKind::Position, §ion), 0.0); assert_eq!(blur_sigma(GeneratorKind::WorldSpaceNormals, §ion), 72.0); assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 0.0, ..section }, 2048), 0); - let radius = blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048) as f32; - assert!((radius * (radius + 1.0)).sqrt() - 4.5 < 0.6, "three boxes of radius {radius} spread like sigma 4.5"); + // Three boxes of radius 4 spread a texel with variance 4 × 5, the closest to sigma 4.5 squared + assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048), 4); } #[test] diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs index 27693163..0724f4e6 100644 --- a/crates/compose/tests/generator_sections.rs +++ b/crates/compose/tests/generator_sections.rs @@ -88,6 +88,12 @@ fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters) generator } +/// `generator` with a uniform `value` plugged into its Position input +fn plugged(mut generator: Generator, value: f32) -> Generator { + generator.inputs.insert(BakedMap::Position, Source::Uniform([value; 3])); + generator +} + fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator { let mut generator = Generator::new(GeneratorKind::Direction); let mut light = generator.light.unwrap(); @@ -159,7 +165,7 @@ fn world_space_normals_combine_the_axes_of_the_normal() { } #[test] -fn position_reads_the_mesh_bounds_without_a_bake_and_the_baked_map_with_one() { +fn position_reads_the_mesh_bounds_unless_an_image_is_plugged_in() { let mut fixture = fixture(); let points = surface(&fixture); let texels: Vec<_> = points.iter().map(|point| point.0).collect(); @@ -168,7 +174,9 @@ fn position_reads_the_mesh_bounds_without_a_bake_and_the_baked_map_with_one() { assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::Position), &texels), &expected, "bounds"); fixture.baked = uniform_map(BakedMap::Position, 0.25); - let balanced = with_section(GeneratorKind::Position, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::Position), &texels), &expected, "a baked Position map is not read"); + + let balanced = plugged(with_section(GeneratorKind::Position, |section| section.balance = 0.25), 0.25); assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.25f32.powf(0.2); texels.len()], "a power curve balance"); } @@ -183,10 +191,9 @@ fn occlusion_balance_is_linear_and_brightness_lerps() { let inverted = with_section(GeneratorKind::AmbientOcclusion, |section| section.invert = true); assert_close(&mask(&mut fixture, inverted, &texels), &vec![0.4; texels.len()], "section invert"); - fixture.baked = uniform_map(BakedMap::Position, 0.4); - let brighter = with_section(GeneratorKind::Position, |section| section.brightness = 0.5); + let brighter = plugged(with_section(GeneratorKind::Position, |section| section.brightness = 0.5), 0.4); assert_close(&mask(&mut fixture, brighter, &texels), &vec![0.7; texels.len()], "brightness 0.5 halves the way to white"); - let darker = with_section(GeneratorKind::Position, |section| section.brightness = -0.5); + let darker = plugged(with_section(GeneratorKind::Position, |section| section.brightness = -0.5), 0.4); assert_close(&mask(&mut fixture, darker, &texels), &vec![0.2; texels.len()], "brightness -0.5 halves the value"); } @@ -203,9 +210,9 @@ fn section_blur_spreads_occlusion_across_a_step() { let blurred = mask(&mut fixture, with_section(GeneratorKind::AmbientOcclusion, |section| section.blur = 16.0), &row); assert!(blurred.iter().all(|value| *value > 0.05 && *value < 0.95), "blurred across the step: {blurred:?}"); - let position = with_section(GeneratorKind::Position, |section| section.blur = 16.0); - fixture.baked = uniform_map(BakedMap::Position, 0.3); - assert_close(&mask(&mut fixture, position, &row), &vec![0.3; row.len()], "position has no section blur"); + let sharp_position = mask(&mut fixture, Generator::new(GeneratorKind::Position), &row); + let blurred_position = mask(&mut fixture, with_section(GeneratorKind::Position, |section| section.blur = 16.0), &row); + assert_close(&blurred_position, &sharp_position, "position has no section blur"); } #[test] diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index fedcca8a..663efd1f 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1082,6 +1082,18 @@ impl Generator { self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals)) } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None + pub fn detail_in_use(&self) -> Option { + let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); + self.detail.clone().or_else(|| on_section.then(CurvatureDetail::default)) + } + + /// The mesh maps the generator reads: none for Position and Light on the earlier model, which read the mesh itself + pub fn inputs_in_use(&self) -> &'static [BakedMap] { + let reads_geometry = self.on_earlier_model() && matches!(self.kind, GeneratorKind::Position | GeneratorKind::Direction); + if reads_geometry { &[] } else { self.kind.inputs() } + } + /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2ed442d1..19a61f09 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -511,6 +511,11 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); } + let reads_direction = matches!(kind, GeneratorKind::Position | GeneratorKind::Direction); + if params.get("direction").is_some() && !reads_direction { + return Err(bad(command, format!("{} has no `direction`: only Position and Light point one way", kind.label()))); + } + if earlier { if !new_keys.is_empty() { return Err(bad( @@ -1056,8 +1061,8 @@ fn set(session: &mut Session, params: &Value) -> Result { generator.micro = micro; } if let Some((map, source)) = input { - if !generator.kind.inputs().contains(&map) { - return Err(bad(CMD, format!("this generator has no `{}` input", map.id()))); + if !generator.inputs_in_use().contains(&map) { + return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); } match source { diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 60676684..6a639aaf 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -89,6 +89,10 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { assert!(execute(&mut session, "effect.set", &json!({"effect": position, "topBottomBlend": "overlay"})).is_err()); assert_eq!(generator(&session, position).section, SectionParameters::defaults(GeneratorKind::Position), "a refused edit changes nothing"); + let direction = json!([1.0, 0.0, 0.0]); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "direction": direction})).is_err(), "Curvature points no way"); + assert!(execute(&mut session, "effect.set", &json!({"effect": occlusion, "direction": direction})).is_err(), "nor does Ambient Occlusion"); + assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); } @@ -117,3 +121,17 @@ fn light_takes_its_controls_and_refuses_the_global_ones() { assert_eq!(moved.light.map(|light| light.vertical), Some(60.0)); assert_eq!(moved.global, Generator::new(GeneratorKind::Direction).global, "the light controls have no global adjustments"); } + +/// Position and Light read the mesh itself on the earlier model, so they take no Position input there +#[test] +fn an_input_the_generator_does_not_read_is_refused() { + let mut session = session(); + let earlier = add(&mut session, json!({"generator": "position", "level": 0.4})); + let plug = |effect: u64| json!({"effect": effect, "input": "position", "inputValue": 0.5}); + assert!(execute(&mut session, "effect.set", &plug(earlier)).is_err()); + assert!(generator(&session, earlier).inputs.is_empty()); + + let on_section = add(&mut session, json!({"generator": "position"})); + execute(&mut session, "effect.set", &plug(on_section)).unwrap(); + assert_eq!(generator(&session, on_section).inputs.len(), 1); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index effda2d1..7c6f7258 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -68,10 +68,10 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer }); }); }); - if !inputs_in_use(generator).is_empty() { + if !generator.inputs_in_use().is_empty() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { - for map in inputs_in_use(generator) { - input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); + for map in generator.inputs_in_use() { + input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail_in_use().is_some()); } }); } @@ -108,12 +108,6 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr } } -/// The inputs `generator` reads: none for Position and Light on their earlier model, which read the mesh itself -fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { - let reads_geometry = generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction); - if reads_geometry { &[] } else { generator.kind.inputs() } -} - /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -493,7 +487,7 @@ fn angle_row(ui: &mut Ui, id: &str, label: &str, degrees: &mut f32) -> Option Option { let tokens = Tokens::get(ui.ctx()); let (rect, response) = ui.allocate_exact_size(egui::vec2(DIAL_SIZE, DIAL_SIZE), egui::Sense::click_and_drag()); @@ -502,7 +496,7 @@ fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { && let Some(pointer) = response.interact_pointer_pos() { let offset = pointer - rect.center(); - let turned = (-offset.y).atan2(offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); + let turned = (-offset.y).atan2(-offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); if offset.length() > DIAL_DEAD_ZONE && (turned - *degrees).abs() > f32::EPSILON { *degrees = turned; // Later frames of one drag share its undo step @@ -516,10 +510,11 @@ fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(shown), label)); let painter = ui.painter(); - let radius = DIAL_SIZE * 0.5 - 1.0; + // The rim's stroke stays inside the dial + let radius = (DIAL_SIZE - DIAL_NEEDLE_WIDTH) * 0.5; painter.circle(rect.center(), radius, tokens.field, egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.button_border)); let (sin, cos) = degrees.to_radians().sin_cos(); - let tip = rect.center() + egui::vec2(cos, -sin) * radius; + let tip = rect.center() + egui::vec2(-cos, -sin) * radius; painter.line_segment([rect.center(), tip], egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.accent)); painter.circle_filled(rect.center(), DIAL_HUB_RADIUS, tokens.text); edit diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 6d49c460..513ca72b 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -171,12 +171,22 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); assert_eq!(count(&harness, "Blending mode"), 3); + for axis in ["Right to left", "Top to bottom", "Front to back"] { + assert_eq!(count(&harness, axis), 2, "{axis}: a section heading and its weight slider"); + } let (harness, _) = harness_with(false, json!({"generator": "direction"})); assert_eq!(count(&harness, "Angle"), 2, "an Angle slider beside each dial"); let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); } +/// The blending mode dropdown in the Front to back section: the first dropdown below its heading, the topmost "Front to back" +fn front_to_back_dropdown<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let heading = harness.query_all_by_label("Front to back").map(|node| node.rect().top()).fold(f32::INFINITY, f32::min); + let below = harness.get_all_by_role(Role::ComboBox).filter(|node| node.rect().top() > heading); + below.min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() +} + #[test] fn each_axis_has_its_own_blending_mode_dropdown() { let (mut harness, effect) = harness_with(false, json!({"generator": "worldSpaceNormals"})); @@ -184,9 +194,9 @@ fn each_axis_has_its_own_blending_mode_dropdown() { harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).count() }; assert_eq!(added(&harness), 3); - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().scroll_to_me(); + front_to_back_dropdown(&harness).scroll_to_me(); harness.run_steps(3); - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().click(); + front_to_back_dropdown(&harness).click(); harness.run_steps(2); harness.get_by_label("Multiply").click(); harness.run_steps(3); @@ -221,7 +231,7 @@ fn the_light_dial_turns_towards_the_pointer() { harness.drop_at(left); harness.run_steps(3); let horizontal = generator(&harness, effect).light.unwrap().horizontal; - assert!((horizontal - 180.0).abs() < 1.0, "a click left of the centre points the needle left: {horizontal}"); + assert!(!(1.0..=359.0).contains(&horizontal), "0 is on the left, as in the reference: {horizontal}"); } #[test] From 38f2f66719ba5185858060a7222a0bb5a6e7dd36 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 099/153] Generators: the offset belongs to the earlier controls Like level, softness and noise, the offset keeps a generator on its earlier controls, and moving onto the wear, section or light controls drops it, so no unseen shift stays under controls without an Offset. --- crates/engine/tests/it/generator_sections.rs | 19 +++++++++++++++++++ crates/engine/tests/it/generator_wear.rs | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 6a639aaf..ed9276f0 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -135,3 +135,22 @@ fn an_input_the_generator_does_not_read_is_refused() { execute(&mut session, "effect.set", &plug(on_section)).unwrap(); assert_eq!(generator(&session, on_section).inputs.len(), 1); } + +#[test] +fn the_offset_belongs_to_the_earlier_model() { + let mut session = session(); + for (kind, control) in [("position", json!({"sectionBalance": 0.3})), ("direction", json!({"highlightLevel": 0.5}))] { + let effect = add(&mut session, json!({"generator": kind, "offset": 0.4})); + assert_eq!(generator(&session, effect).offset, 0.4, "{kind}: the offset keeps it on the earlier model"); + + let mut edit = control.clone(); + edit["effect"] = json!(effect); + execute(&mut session, "effect.set", &edit).unwrap(); + assert_eq!(generator(&session, effect).offset, 0.0, "{kind}: moving onto the reference controls drops the unseen offset"); + + let mut both = control; + both["effect"] = json!(effect); + both["offset"] = json!(0.2); + assert!(execute(&mut session, "effect.set", &both).is_err(), "{kind}: offset and the reference controls at once are refused"); + } +} diff --git a/crates/engine/tests/it/generator_wear.rs b/crates/engine/tests/it/generator_wear.rs index c194dfe4..5d8bf639 100644 --- a/crates/engine/tests/it/generator_wear.rs +++ b/crates/engine/tests/it/generator_wear.rs @@ -91,3 +91,15 @@ fn mode_and_sizes_keep_edge_wear_on_the_earlier_model_where_they_apply() { execute(&mut session, "effect.set", &json!({"effect": effect, "blur": 0.5})).unwrap(); assert_eq!(generator(&session, effect).global.blur, 0.5, "the earlier model keeps its global blur"); } + +#[test] +fn a_wear_control_drops_the_earlier_models_offset() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "edgeWear", "offset": 0.4})); + assert_eq!(generator(&session, effect).wear, None, "the offset keeps it on the earlier model"); + assert_eq!(generator(&session, effect).offset, 0.4); + + execute(&mut session, "effect.set", &json!({"effect": effect, "wearLevel": 0.6})).unwrap(); + assert_eq!(generator(&session, effect).offset, 0.0, "on the wear controls the offset would shift the result unseen"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "offset": 0.2, "wearLevel": 0.5})).is_err(), "not both at once"); +} From 922c8e8a7adf644cf600ddec2e5c40107e51db37 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 100/153] Generators: Use Texture on Curvature, Ambient Occlusion, Position and World Space Normals A texture blends over the section-adjusted signal before the global controls: read in UV (scaled about the centre) or triplanar, turned gray by one of eight conversions, inverted, contrasted and brightened, then blended by one of ten modes at its opacity. Its image is the texture input of effect.set; an empty slot reads black. The panel shows Use texture at the end of Parameters, the texture's rows once it is on, and its slot first in Image inputs. --- crates/compose/src/below.rs | 2 +- crates/compose/src/eval.rs | 58 ++++- crates/compose/src/lib.rs | 1 + crates/compose/src/texture_layer.rs | 150 +++++++++++++ crates/compose/tests/cache_and_instances.rs | 38 ++++ crates/compose/tests/generator_texture.rs | 218 +++++++++++++++++++ crates/core/src/layer.rs | 26 ++- crates/core/src/layer/generator_grayscale.rs | 81 +++++++ crates/core/src/layer/texture_blend.rs | 80 +++++++ crates/core/src/layer/texture_layer.rs | 76 +++++++ crates/core/src/lib.rs | 4 +- crates/engine/src/inspect.rs | 3 + crates/engine/src/mask_cmds.rs | 119 ++++++++-- crates/engine/tests/it/generator_texture.rs | 106 +++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 180 ++++++++++++--- crates/ui-egui/tests/it/generator_panel.rs | 57 +++++ 17 files changed, 1134 insertions(+), 66 deletions(-) create mode 100644 crates/compose/src/texture_layer.rs create mode 100644 crates/compose/tests/generator_texture.rs create mode 100644 crates/core/src/layer/generator_grayscale.rs create mode 100644 crates/core/src/layer/texture_blend.rs create mode 100644 crates/core/src/layer/texture_layer.rs create mode 100644 crates/engine/tests/it/generator_texture.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cdca3b83..dd440224 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -165,7 +165,7 @@ impl StackKey { match &effect.kind { EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), - EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.sources().flat_map(Source::images).for_each(&mut record_image_name), EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b0ae6b29..2b0500a7 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -40,6 +40,7 @@ use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use crate::texture_layer; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use crate::wear; use crate::wear_inputs::WearInputs; @@ -1657,7 +1658,7 @@ fn filter_region( _ => None, }; let components = match job { - Job::Mask(_) if generator.is_some() => 2, + Job::Mask(_) if generator.is_some() => GENERATOR_STAGE_COMPONENTS, Job::Mask(_) => 1, Job::Content(_) => 4, }; @@ -1727,7 +1728,8 @@ fn filter_region( let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); - [texel.mask(mask_stack), ramp, 0.0, 0.0] + let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); + [texel.mask(mask_stack), ramp, texture, 0.0] } (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], @@ -1943,7 +1945,13 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } -/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +/// What a generator's texture reads with nothing in its slot +const EMPTY_TEXTURE_SLOT: Source = Source::Uniform([0.0; 3]); + +/// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray +const GENERATOR_STAGE_COMPONENTS: usize = 3; + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp, texture gray) per texel, sizes in texels per side fn generator_region( generator: &Generator, blend: BlendMode, @@ -1954,7 +1962,7 @@ fn generator_region( (uv_tile, texture_set): (u32, u32), ) -> Vec { let (columns, rows) = (width as usize, height as usize); - let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + let mut ramps: Vec = stack.par_chunks(GENERATOR_STAGE_COMPONENTS).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); // Coarser than the UV tile: averaged over cells, then the blur around them let cell = generator.resolution.cell(uv_tile, texture_set) as usize; @@ -1968,11 +1976,18 @@ fn generator_region( ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); } + // The texture blends over the adjusted signal, before the global blur + if let Some(texture) = generator.texture_in_use() { + ramps.par_iter_mut().zip(stack.par_chunks(GENERATOR_STAGE_COMPONENTS)).for_each(|(signal, texel)| { + *signal = texture_layer::blended_over(texture, *signal, texel.get(2).copied().unwrap_or(0.0)); + }); + } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); // Finished and blended over the stack below, like the generator effect itself stack - .par_chunks(2) + .par_chunks(GENERATOR_STAGE_COMPONENTS) .zip(ramps.par_iter()) .map(|(texel, ramp)| { let below = texel.first().copied().unwrap_or(0.0); @@ -3467,7 +3482,38 @@ impl<'a, 'b> Texel<'a, 'b> { fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); - finish_generator(generator, adjusted) + let textured = match (generator.texture_in_use(), self.generator_texture(generator)) { + (Some(texture), Some(gray)) => texture_layer::blended_over(texture, adjusted, gray), + _ => adjusted, + }; + finish_generator(generator, textured) + } + + /// The gray of the generator's texture at this texel (None when it blends no texture) + fn generator_texture(&mut self, generator: &Generator) -> Option { + let texture = generator.texture_in_use()?; + let rgb = match texture.source.as_ref().unwrap_or(&EMPTY_TEXTURE_SLOT) { + Source::Image { name, .. } => { + let image = self.inp.images.get(name)?.clone(); + let read = |coordinates: Vec2| { + let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); + Vec3::new(red, green, blue) + }; + if texture.triplanar { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(texture, normal); + let coordinates = texture_layer::triplanar_coordinates(texture, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight).to_array() + } else { + read(texture_layer::uv_coordinates(texture, self.coords().uv)).to_array() + } + } + // A value or an anchor reads the same wherever it is projected + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + Some(texture_layer::texture_gray(texture, rgb)) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a2369743..3c921ff9 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -42,6 +42,7 @@ mod slope_texel; mod soft_box; pub mod solo; pub mod store; +mod texture_layer; pub mod thumb; pub mod tile_length; mod tile_pattern; diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs new file mode 100644 index 00000000..95c40fa3 --- /dev/null +++ b/crates/compose/src/texture_layer.rs @@ -0,0 +1,150 @@ +//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal + +use texturecraft_core::{TextureBlend, TextureLayer}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +/// Exponent of the triplanar weights per unit of `1 / (1 − triplanar contrast)`: contrast 0 weighs the axes by the normal itself, 0.5 by its cube +const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58; + +/// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly +const MIN_NORMAL_COMPONENT: f32 = 1e-6; + +/// Where the texture is read in UV: scaled about the centre of the UV square +pub(crate) fn uv_coordinates(texture: &TextureLayer, uv: Vec2) -> Vec2 { + (uv - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5) +} + +/// Where the texture is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1), scaled about their centre +pub(crate) fn triplanar_coordinates(texture: &TextureLayer, position: Vec3) -> [Vec2; 3] { + let scaled = |u: f32, v: f32| (Vec2::new(u, v) - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5); + [scaled(-position.z, position.y), scaled(position.x, position.z), scaled(position.x, position.y)] +} + +/// How much each projection (facing X, Y and Z) counts for a surface facing `normal`, summing to 1 +pub(crate) fn triplanar_weights(texture: &TextureLayer, normal: Vec3) -> [f32; 3] { + let contrast = texture.triplanar_contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end()); + let sharpness = (1.0 - contrast).max(f32::EPSILON).powf(-TRIPLANAR_SHARPNESS_POWER); + let facing = normal.abs(); + let largest = facing.max_element().max(MIN_NORMAL_COMPONENT); + let weights = (facing / largest).powf(sharpness); + let total = weights.x + weights.y + weights.z; + if total > 0.0 { (weights / total).to_array() } else { [1.0 / 3.0; 3] } +} + +/// The texture's gray from its color: converted, inverted, contrasted, then brightened +pub(crate) fn texture_gray(texture: &TextureLayer, rgb: [f32; 3]) -> f32 { + let gray = texture.grayscale.gray(rgb).clamp(0.0, 1.0); + let gray = if texture.invert { 1.0 - gray } else { gray }; + + let contrast = texture.contrast.clamp(-1.0, 1.0); + let gray = if contrast > 0.0 { + let range = (1.0 - contrast).max(f32::EPSILON); + ((gray - 0.5) / range + 0.5).clamp(0.0, 1.0) + } else { + (gray - 0.5) * (1.0 + contrast) + 0.5 + }; + + let brightness = texture.brightness.clamp(-1.0, 1.0); + if brightness > 0.0 { gray + brightness * (1.0 - gray) } else { gray * (1.0 + brightness) } +} + +/// `gray` (the texture) blended over `signal` by the texture's blending mode and opacity +pub(crate) fn blended_over(texture: &TextureLayer, signal: f32, gray: f32) -> f32 { + let blend = match texture.blend { + TextureBlend::Normal => gray, + TextureBlend::Add => signal + gray, + TextureBlend::Subtract => signal - gray, + TextureBlend::Multiply => signal * gray, + TextureBlend::AddSub => signal + 2.0 * gray - 1.0, + TextureBlend::Max => signal.max(gray), + TextureBlend::Min => signal.min(gray), + TextureBlend::Overlay => { + if signal < 0.5 { + 2.0 * signal * gray + } else { + 1.0 - 2.0 * (1.0 - signal) * (1.0 - gray) + } + } + TextureBlend::Screen => 1.0 - (1.0 - signal) * (1.0 - gray), + TextureBlend::SoftLight => { + if gray < 0.5 { + 2.0 * signal * gray + signal * signal * (1.0 - 2.0 * gray) + } else { + 2.0 * signal * (1.0 - gray) + signal.max(0.0).sqrt() * (2.0 * gray - 1.0) + } + } + }; + let opacity = texture.opacity.clamp(0.0, 1.0); + (signal + (blend - signal) * opacity).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::GeneratorGrayscale; + + fn texture() -> TextureLayer { + TextureLayer { enabled: true, opacity: 1.0, ..TextureLayer::default() } + } + + #[test] + fn overlay_at_full_opacity_darkens_darks_and_lightens_lights() { + let texture = texture(); + assert!((blended_over(&texture, 0.25, 0.5) - 0.25).abs() < 1e-6, "mid gray leaves a dark signal unchanged"); + assert!(blended_over(&texture, 0.25, 0.2) < 0.25); + assert!(blended_over(&texture, 0.75, 0.8) > 0.75); + } + + #[test] + fn opacity_zero_leaves_the_signal() { + let texture = TextureLayer { opacity: 0.0, blend: TextureBlend::Normal, ..texture() }; + assert_eq!(blended_over(&texture, 0.3, 0.9), 0.3); + } + + #[test] + fn every_blend_stays_in_range() { + for blend in TextureBlend::ALL { + let texture = TextureLayer { blend, ..texture() }; + for signal in [0.0, 0.3, 0.5, 1.0] { + for gray in [0.0, 0.4, 1.0] { + let value = blended_over(&texture, signal, gray); + assert!((0.0..=1.0).contains(&value), "{blend:?} {signal} {gray} -> {value}"); + } + } + } + } + + #[test] + fn gray_is_converted_then_inverted_contrasted_and_brightened() { + let red = [1.0, 0.0, 0.0]; + assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Red, ..texture() }, red), 1.0); + assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Green, ..texture() }, red), 0.0); + assert!((texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Desaturation, ..texture() }, red) - 0.5).abs() < 1e-6); + let inverted = TextureLayer { grayscale: GeneratorGrayscale::Red, invert: true, ..texture() }; + assert_eq!(texture_gray(&inverted, red), 0.0); + let contrasted = TextureLayer { contrast: 0.5, ..texture() }; + assert!((texture_gray(&contrasted, [0.6; 3]) - 0.7).abs() < 1e-5, "contrast 0.5 doubles the distance from the middle"); + let flattened = TextureLayer { contrast: -1.0, ..texture() }; + assert!((texture_gray(&flattened, [0.9; 3]) - 0.5).abs() < 1e-6, "contrast −1 is flat gray"); + let brightened = TextureLayer { brightness: 0.5, ..texture() }; + assert!((texture_gray(&brightened, [0.4; 3]) - 0.7).abs() < 1e-6); + } + + #[test] + fn triplanar_weights_follow_the_normal_and_sharpen_with_contrast() { + let along_y = triplanar_weights(&texture(), Vec3::Y); + assert!((along_y[1] - 1.0).abs() < 1e-6); + let diagonal = Vec3::new(1.0, 0.5, 0.0).normalize(); + let soft = triplanar_weights(&TextureLayer { triplanar_contrast: 0.001, ..texture() }, diagonal); + let hard = triplanar_weights(&TextureLayer { triplanar_contrast: 0.9, ..texture() }, diagonal); + assert!(hard[0] > soft[0] && hard[1] < soft[1]); + assert!((soft.iter().sum::() - 1.0).abs() < 1e-5); + } + + #[test] + fn scale_is_about_the_centre() { + let texture = TextureLayer { scale: 2.0, ..texture() }; + assert_eq!(uv_coordinates(&texture, Vec2::splat(0.5)), Vec2::splat(0.5)); + assert_eq!(uv_coordinates(&texture, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); + } +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 7a96a5f9..dac833d1 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -1270,3 +1270,41 @@ fn a_folder_thumbnail_reads_compare_inputs_from_its_backdrop() { assert!(thumbnail.rgba[center] > thumbnail.rgba[center + 2], "visible red child"); } + +#[test] +fn replacing_a_generator_texture_image_invalidates_the_cached_stack() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore}; + use texturecraft_core::{TextureBlend, TextureLayer}; + + let mut fixture = fixture(); + let hot_layer = heavy_stack(&mut fixture); + let texture = TextureLayer { enabled: true, source: Some(Source::image("grunge")), opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(texture), ..Generator::new(GeneratorKind::AmbientOcclusion) }))); + let textured = add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), Some(mask)); + let stack = &mut fixture.project.texture_sets[0].stack; + stack.retain(|id| *id != textured); + stack.insert(0, textured); + + let image_with_value = |value| Arc::new(ImageRes::new(4, 4, vec![[value, value, value, 1.0]; 16], false)); + let mut images = ImageStore::default(); + let baked = Default::default(); + let tiles = all_tiles(RES, RES); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot_layer)); + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + + for (stage, value) in [("dark", 0.1), ("light", 0.9)] { + images.insert("grunge".into(), image_with_value(value)); + let input = inputs(&fixture, 0, &images, &baked); + composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + let retained = cache.len() - 1; + composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, 0, "{stage}: a new texture image drops the tiles cached below the hot layer"); + + let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); + } +} diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs new file mode 100644 index 00000000..3800ccb6 --- /dev/null +++ b/crates/compose/tests/generator_texture.rs @@ -0,0 +1,218 @@ +//! A generator's texture (Use Texture) on a sphere: read in UV or triplanar, turned gray, blended over the signal before the global controls + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorGrayscale, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, + SectionParameters, Source, TextureBlend, TextureLayer, TextureSet, +}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// How far a mask value may sit from the expected one +const TOLERANCE: f32 = 1e-3; + +/// The ambient occlusion every texel of the sphere reads +const OCCLUSION: f32 = 0.3; + +/// Width of the split image: its left half black, its right half white +const SPLIT_WIDTH: u32 = 64; + +/// How far from a split's edge (in UV) a texel must sit to read one side only +const SPLIT_MARGIN: f32 = 0.05; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, + images: ImageStore, +} + +/// A unit sphere with a white fill layer, uniform occlusion and the images `flat` (one color) and `split` (black left, white right) +fn fixture(flat: [f32; 3]) -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![OCCLUSION; (RES * RES) as usize]))].into() }; + + let [red, green, blue] = flat; + let flat = ImageRes::new(4, 4, vec![[red, green, blue, 1.0]; 16], false); + let split_texel = |index: u32| if index % SPLIT_WIDTH < SPLIT_WIDTH / 2 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }; + let split = ImageRes::new(SPLIT_WIDTH, SPLIT_WIDTH, (0..SPLIT_WIDTH * SPLIT_WIDTH).map(split_texel).collect(), false); + let images = [("flat".to_string(), Arc::new(flat)), ("split".to_string(), Arc::new(split))].into(); + Fixture { project, mesh, gbuf, layer, baked, images } +} + +/// A covered texel with its UV, world position and normal +struct SurfacePoint { + texel: (u32, u32), + uv: [f32; 2], + position: Vec3, + normal: Vec3, +} + +/// Every covered texel +fn surface(fixture: &Fixture) -> Vec { + (0..RES * RES) + .filter_map(|index| { + let texel = (index % RES, index / RES); + let uv = [(texel.0 as f32 + 0.5) / RES as f32, (texel.1 as f32 + 0.5) / RES as f32]; + fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| SurfacePoint { texel, uv, position: surface.pos, normal: surface.nrm }) + }) + .collect() +} + +/// The mask of `generator` alone over black at `texels` +fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// Ambient Occlusion on its section controls with `texture` reading image `image` +fn occlusion_with(image: &str, texture: TextureLayer) -> Generator { + Generator { texture: Some(TextureLayer { source: Some(Source::image(image)), ..texture }), ..Generator::new(GeneratorKind::AmbientOcclusion) } +} + +/// A texture turned on at full opacity, replacing the signal +fn replacing() -> TextureLayer { + TextureLayer { enabled: true, opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() } +} + +fn assert_all(actual: &[f32], expected: f32, what: &str) { + for (index, actual) in actual.iter().enumerate() { + assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); + } +} + +#[test] +fn a_texture_turned_off_or_at_opacity_zero_leaves_the_signal() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer { enabled: false, ..replacing() }), &texels), OCCLUSION, "turned off"); + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer { opacity: 0.0, ..replacing() }), &texels), OCCLUSION, "opacity 0"); + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer::default()), &texels), OCCLUSION, "the reference's defaults"); +} + +#[test] +fn an_empty_texture_slot_blends_black() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let empty = Generator { texture: Some(TextureLayer { opacity: 0.5, ..replacing() }), ..Generator::new(GeneratorKind::AmbientOcclusion) }; + assert_all(&mask(&mut fixture, empty, &texels), OCCLUSION * 0.5, "half way to black"); +} + +#[test] +fn a_texture_needs_the_section_controls() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let earlier = Generator { section: None, global: Default::default(), ..occlusion_with("flat", replacing()) }; + let without = Generator { texture: None, ..earlier.clone() }; + assert_eq!(mask(&mut fixture, earlier, &texels), mask(&mut fixture, without, &texels)); +} + +#[test] +fn the_texture_turns_gray_by_its_conversion() { + let mut fixture = fixture([1.0, 0.25, 0.0]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + for (grayscale, expected) in [ + (GeneratorGrayscale::Average, 1.25 / 3.0), + (GeneratorGrayscale::Red, 1.0), + (GeneratorGrayscale::Green, 0.25), + (GeneratorGrayscale::Desaturation, 0.5), + (GeneratorGrayscale::Luma, 0.299 + 0.587 * 0.25), + ] { + let generator = occlusion_with("flat", TextureLayer { grayscale, ..replacing() }); + assert_all(&mask(&mut fixture, generator, &texels), expected, &format!("{grayscale:?}")); + } +} + +#[test] +fn overlay_with_a_mid_gray_texture_doubles_a_dark_signal_times_the_gray() { + let mut fixture = fixture([0.4; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let generator = occlusion_with("flat", TextureLayer { blend: TextureBlend::Overlay, opacity: 0.5, ..replacing() }); + let overlay = 2.0 * OCCLUSION * 0.4; + assert_all(&mask(&mut fixture, generator, &texels), OCCLUSION + (overlay - OCCLUSION) * 0.5, "overlay at half opacity"); +} + +#[test] +fn the_texture_blends_after_the_section_controls_and_before_the_global_ones() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + + let mut section_inverted = occlusion_with("flat", replacing()); + section_inverted.section = Some(SectionParameters { invert: true, ..section_inverted.section.unwrap() }); + assert_all(&mask(&mut fixture, section_inverted, &texels), 0.6, "the texture replaces the inverted section"); + + let globally_inverted = Generator { invert: true, ..occlusion_with("flat", replacing()) }; + assert_all(&mask(&mut fixture, globally_inverted, &texels), 0.4, "the global invert flips the texture"); + + let mut blurred = occlusion_with("flat", replacing()); + blurred.section = Some(SectionParameters { blur: 2.0, ..blurred.section.unwrap() }); + assert_all(&mask(&mut fixture, blurred, &texels), 0.6, "with the section blur (computed over a region)"); +} + +#[test] +fn uv_scale_repeats_the_texture_about_the_centre() { + let mut fixture = fixture([0.0; 3]); + let points = surface(&fixture); + let side = |u: f32| (u.rem_euclid(1.0) >= 0.5) as u8 as f32; + for scale in [1.0, 2.0, 3.0] { + let read_at = |u: f32| (u - 0.5) * scale + 0.5; + let clear: Vec<_> = points + .iter() + .filter(|point| { + let u = read_at(point.uv[0]).rem_euclid(1.0); + [0.0, 0.5, 1.0].iter().all(|edge| (u - edge).abs() > SPLIT_MARGIN * scale) + }) + .collect(); + let texels: Vec<_> = clear.iter().map(|point| point.texel).collect(); + let values = mask(&mut fixture, occlusion_with("split", TextureLayer { scale, ..replacing() }), &texels); + for (point, value) in clear.iter().zip(values) { + let expected = side(read_at(point.uv[0])); + assert!((value - expected).abs() < TOLERANCE, "scale {scale} at u {}: {value}, expected {expected}", point.uv[0]); + } + } +} + +#[test] +fn triplanar_reads_the_top_from_the_plane_facing_up() { + let mut fixture = fixture([0.0; 3]); + let (low, high) = fixture.mesh.bounds(); + let across = |position: Vec3| (position.x - low.x) / (high.x - low.x); + let top: Vec<_> = surface(&fixture).into_iter().filter(|point| point.normal.y > 0.95 && (across(point.position) - 0.5).abs() > SPLIT_MARGIN).collect(); + assert!(!top.is_empty()); + + let texels: Vec<_> = top.iter().map(|point| point.texel).collect(); + let sharp = TextureLayer { triplanar: true, triplanar_contrast: 1.0, ..replacing() }; + let values = mask(&mut fixture, occlusion_with("split", sharp), &texels); + for (point, value) in top.iter().zip(values) { + let expected = if across(point.position) >= 0.5 { 1.0 } else { 0.0 }; + assert!((value - expected).abs() < TOLERANCE, "at x {}: {value}, expected {expected}", across(point.position)); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 663efd1f..a169516b 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -20,6 +20,7 @@ mod decal_flip; mod decal_symmetry; mod filtering; mod generator_global; +mod generator_grayscale; mod light_parameters; mod micro_detail; mod output_resolution; @@ -27,6 +28,8 @@ mod resolution_mode; mod sampling; mod scale_mode; mod section_parameters; +mod texture_blend; +mod texture_layer; mod tile_blending; mod tile_generator; mod tile_input_distribution; @@ -45,6 +48,7 @@ pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; +pub use generator_grayscale::GeneratorGrayscale; pub use light_parameters::LightParameters; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; @@ -52,6 +56,8 @@ pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; pub use scale_mode::ScaleMode; pub use section_parameters::SectionParameters; +pub use texture_blend::TextureBlend; +pub use texture_layer::TextureLayer; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; @@ -1062,6 +1068,9 @@ pub struct Generator { /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub light: Option, + /// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub texture: Option, } impl Generator { @@ -1094,6 +1103,16 @@ impl Generator { if reads_geometry { &[] } else { self.kind.inputs() } } + /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity + pub fn texture_in_use(&self) -> Option<&TextureLayer> { + self.texture.as_ref().filter(|texture| texture.in_use() && self.section_controls().is_some()) + } + + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture + pub fn sources(&self) -> impl Iterator { + self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())) + } + /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear @@ -1130,6 +1149,7 @@ impl Generator { wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), light: LightParameters::defaults(kind), + texture: None, } } @@ -2103,7 +2123,7 @@ impl EffectKind { EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)), EffectKind::Generator(generator) => { generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor)) - || generator.inputs.values().any(|source| source.reads_anchor(anchor)) + || generator.sources().any(|source| source.reads_anchor(anchor)) } _ => false, } @@ -2114,7 +2134,7 @@ impl EffectKind { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], EffectKind::Material(fill) => fill.sources.values().collect(), - EffectKind::Generator(generator) => generator.inputs.values().collect(), + EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; let mut anchors: Vec<_> = sources @@ -2137,7 +2157,7 @@ impl EffectKind { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], EffectKind::Material(fill) => fill.sources.values().collect(), - EffectKind::Generator(generator) => generator.inputs.values().collect(), + EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; let id_map = match self { diff --git a/crates/core/src/layer/generator_grayscale.rs b/crates/core/src/layer/generator_grayscale.rs new file mode 100644 index 00000000..01ac149b --- /dev/null +++ b/crates/core/src/layer/generator_grayscale.rs @@ -0,0 +1,81 @@ +use serde::{Deserialize, Serialize}; + +/// How a color texture becomes one gray value +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GeneratorGrayscale { + /// Halfway between the brightest and the darkest channel + Desaturation, + /// The channels weighted by how bright the eye sees them + Luma, + /// The mean of the three channels + #[default] + Average, + Max, + Min, + Red, + Green, + Blue, +} + +impl GeneratorGrayscale { + pub const ALL: [GeneratorGrayscale; 8] = [ + GeneratorGrayscale::Desaturation, + GeneratorGrayscale::Luma, + GeneratorGrayscale::Average, + GeneratorGrayscale::Max, + GeneratorGrayscale::Min, + GeneratorGrayscale::Red, + GeneratorGrayscale::Green, + GeneratorGrayscale::Blue, + ]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + GeneratorGrayscale::Desaturation => "Desaturation", + GeneratorGrayscale::Luma => "Luma", + GeneratorGrayscale::Average => "Average", + GeneratorGrayscale::Max => "Max", + GeneratorGrayscale::Min => "Min", + GeneratorGrayscale::Red => "Red channel", + GeneratorGrayscale::Green => "Green channel", + GeneratorGrayscale::Blue => "Blue channel", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + GeneratorGrayscale::Desaturation => "desaturation", + GeneratorGrayscale::Luma => "luma", + GeneratorGrayscale::Average => "average", + GeneratorGrayscale::Max => "max", + GeneratorGrayscale::Min => "min", + GeneratorGrayscale::Red => "red", + GeneratorGrayscale::Green => "green", + GeneratorGrayscale::Blue => "blue", + } + } + + /// The conversion named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + GeneratorGrayscale::ALL.into_iter().find(|mode| mode.id().eq_ignore_ascii_case(name) || mode.label().eq_ignore_ascii_case(name)) + } + + /// The gray of `rgb` + pub fn gray(self, [red, green, blue]: [f32; 3]) -> f32 { + // ITU-R BT.601 weights, the reference's Luma + const LUMA: [f32; 3] = [0.299, 0.587, 0.114]; + match self { + GeneratorGrayscale::Desaturation => (red.max(green).max(blue) + red.min(green).min(blue)) * 0.5, + GeneratorGrayscale::Luma => red * LUMA[0] + green * LUMA[1] + blue * LUMA[2], + GeneratorGrayscale::Average => (red + green + blue) / 3.0, + GeneratorGrayscale::Max => red.max(green).max(blue), + GeneratorGrayscale::Min => red.min(green).min(blue), + GeneratorGrayscale::Red => red, + GeneratorGrayscale::Green => green, + GeneratorGrayscale::Blue => blue, + } + } +} diff --git a/crates/core/src/layer/texture_blend.rs b/crates/core/src/layer/texture_blend.rs new file mode 100644 index 00000000..73c3f3cc --- /dev/null +++ b/crates/core/src/layer/texture_blend.rs @@ -0,0 +1,80 @@ +use serde::{Deserialize, Serialize}; + +/// How a generator's texture combines with its signal +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TextureBlend { + /// The texture replaces the signal + Normal, + /// The texture adds to the signal + Add, + /// The texture is taken from the signal + Subtract, + /// The texture multiplies the signal + Multiply, + /// The texture adds above its middle gray and subtracts below it + AddSub, + /// The brighter of the texture and the signal + Max, + /// The darker of the texture and the signal + Min, + /// The texture darkens the signal's darks and lightens its lights + #[default] + Overlay, + /// The inverse of multiplying the inverses: always lighter + Screen, + /// A gentler overlay led by the texture + SoftLight, +} + +impl TextureBlend { + pub const ALL: [TextureBlend; 10] = [ + TextureBlend::Normal, + TextureBlend::Add, + TextureBlend::Subtract, + TextureBlend::Multiply, + TextureBlend::AddSub, + TextureBlend::Max, + TextureBlend::Min, + TextureBlend::Overlay, + TextureBlend::Screen, + TextureBlend::SoftLight, + ]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + TextureBlend::Normal => "Normal", + TextureBlend::Add => "Linear Dodge (Add)", + TextureBlend::Subtract => "Subtract", + TextureBlend::Multiply => "Multiply", + TextureBlend::AddSub => "Add/Sub", + TextureBlend::Max => "Max (Lighten)", + TextureBlend::Min => "Min (Darken)", + TextureBlend::Overlay => "Overlay", + TextureBlend::Screen => "Screen", + TextureBlend::SoftLight => "Soft light", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + TextureBlend::Normal => "normal", + TextureBlend::Add => "add", + TextureBlend::Subtract => "subtract", + TextureBlend::Multiply => "multiply", + TextureBlend::AddSub => "addSub", + TextureBlend::Max => "max", + TextureBlend::Min => "min", + TextureBlend::Overlay => "overlay", + TextureBlend::Screen => "screen", + TextureBlend::SoftLight => "softLight", + } + } + + /// The blend named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + TextureBlend::ALL.into_iter().find(|blend| blend.id().eq_ignore_ascii_case(name) || blend.label().eq_ignore_ascii_case(name)) + } +} diff --git a/crates/core/src/layer/texture_layer.rs b/crates/core/src/layer/texture_layer.rs new file mode 100644 index 00000000..877e0f3d --- /dev/null +++ b/crates/core/src/layer/texture_layer.rs @@ -0,0 +1,76 @@ +use serde::{Deserialize, Serialize}; + +use super::Source; +use super::generator_grayscale::GeneratorGrayscale; +use super::texture_blend::TextureBlend; + +/// A texture a generator blends over its signal (the reference's Use Texture block): read as gray, adjusted, then blended before the global controls +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextureLayer { + /// Use Texture: off keeps the settings but leaves the signal as it is + pub enabled: bool, + /// What the texture reads (None: an empty slot, uniform black) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// How much of the blend shows (0..1) + pub opacity: f32, + pub invert: bool, + pub grayscale: GeneratorGrayscale, + pub blend: TextureBlend, + /// Repeats across the UV square, about its centre ([`TextureLayer::SCALE_RANGE`]) + pub scale: f32, + /// Narrows the texture around its middle (above 0) or flattens it towards gray (below 0) (−1..1) + pub contrast: f32, + /// Lifts the texture towards white (above 0) or black (below 0) (−1..1) + pub brightness: f32, + /// Projected from the world's three axes rather than laid out in UV + pub triplanar: bool, + /// How sharply the three projections meet ([`TextureLayer::TRIPLANAR_CONTRAST_RANGE`]) + pub triplanar_contrast: f32, +} + +impl Default for TextureLayer { + /// The reference app's defaults: off, and at opacity 0 even once turned on + fn default() -> Self { + TextureLayer { + enabled: false, + source: None, + opacity: 0.0, + invert: false, + grayscale: GeneratorGrayscale::default(), + blend: TextureBlend::default(), + scale: 1.0, + contrast: 0.0, + brightness: 0.0, + triplanar: false, + triplanar_contrast: 0.5, + } + } +} + +impl TextureLayer { + pub const SCALE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + pub const TRIPLANAR_CONTRAST_RANGE: std::ops::RangeInclusive = 0.001..=1.0; + + /// Whether the texture changes the signal: turned on with some opacity (an empty slot blends black) + pub fn in_use(&self) -> bool { + self.enabled && self.opacity > 0.0 + } + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> TextureLayer { + let defaults = TextureLayer::default(); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + TextureLayer { + opacity: within(self.opacity, defaults.opacity, 0.0..=1.0), + scale: within(self.scale, defaults.scale, TextureLayer::SCALE_RANGE), + contrast: within(self.contrast, defaults.contrast, -1.0..=1.0), + brightness: within(self.brightness, defaults.brightness, -1.0..=1.0), + triplanar_contrast: within(self.triplanar_contrast, defaults.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE), + ..self + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c5ff7ec3..b8d53dd9 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,9 +112,9 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, + Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 09cdaecb..39918d33 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -153,6 +153,9 @@ fn generator_json(generator: &Generator) -> Value { if !generator.inputs.is_empty() { out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::>().into(); } + if let Some(texture) = &generator.texture { + out["texture"] = json!(texture); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 19a61f09..8f67edf9 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, + GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id or texture + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -485,10 +485,38 @@ const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; /// The Light generator's controls const LIGHT_KEYS: [&str; 5] = ["lightHorizontal", "lightVertical", "highlightGlossiness", "highlightLevel", "lightAttenuation"]; -/// The section controls, the axis keys and the light controls `params` gives +/// The texture controls (Use Texture); the texture itself is the `texture` input +const TEXTURE_KEYS: [&str; 10] = [ + "useTexture", + "textureOpacity", + "textureInvert", + "textureGrayscale", + "textureBlend", + "textureScale", + "textureContrast", + "textureBrightness", + "textureTriplanar", + "textureTriplanarContrast", +]; + +/// The input name of a generator's texture, beside the mesh map ids +const TEXTURE_INPUT: &str = "texture"; + +/// The section controls, the axis keys, the texture controls and the light controls `params` gives (a texture input counts as `texture`) fn given_new_model_keys(params: &Value) -> Vec { let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}"))); - SECTION_KEYS.iter().chain(LIGHT_KEYS.iter()).map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() + let mut keys: Vec = SECTION_KEYS + .iter() + .chain(TEXTURE_KEYS.iter()) + .chain(LIGHT_KEYS.iter()) + .map(|key| key.to_string()) + .chain(axis_keys) + .filter(|key| params.get(key).is_some()) + .collect(); + if strp(params, "input") == Some(TEXTURE_INPUT) { + keys.push(TEXTURE_INPUT.to_string()); + } + keys } /// The section and light controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model @@ -597,6 +625,44 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res } } generator.section = Some(section.clamped(kind)); + texture_from(command, params, generator) +} + +/// The texture controls in `params` (the generator is on its section controls already) +fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if !TEXTURE_KEYS.iter().any(|key| params.get(*key).is_some()) { + return Ok(()); + } + let mut texture = generator.texture.clone().unwrap_or_default(); + if let Some(enabled) = boolp(params, "useTexture") { + texture.enabled = enabled; + } + for (key, value) in [ + ("textureOpacity", &mut texture.opacity), + ("textureScale", &mut texture.scale), + ("textureContrast", &mut texture.contrast), + ("textureBrightness", &mut texture.brightness), + ("textureTriplanarContrast", &mut texture.triplanar_contrast), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(invert) = boolp(params, "textureInvert") { + texture.invert = invert; + } + if let Some(triplanar) = boolp(params, "textureTriplanar") { + texture.triplanar = triplanar; + } + if let Some(value) = params.get("textureGrayscale") { + let name = value.as_str().ok_or_else(|| bad(command, "`textureGrayscale` must be a string"))?; + texture.grayscale = GeneratorGrayscale::parse(name).ok_or_else(|| bad(command, format!("unknown grayscale conversion `{name}`")))?; + } + if let Some(value) = params.get("textureBlend") { + let name = value.as_str().ok_or_else(|| bad(command, "`textureBlend` must be a string"))?; + texture.blend = TextureBlend::parse(name).ok_or_else(|| bad(command, format!("unknown blending mode `{name}`")))?; + } + generator.texture = Some(texture.clamped()); Ok(()) } @@ -604,7 +670,8 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix))); match key { - "sectionInvert" | "sectionContrast" => SectionParameters::defaults(kind).is_some(), + "sectionInvert" | "sectionContrast" | TEXTURE_INPUT => SectionParameters::defaults(kind).is_some(), + _ if TEXTURE_KEYS.contains(&key) => SectionParameters::defaults(kind).is_some(), "sectionBlur" => SectionParameters::has_blur(kind), "sectionBalance" => SectionParameters::has_balance(kind), "sectionBrightness" => SectionParameters::has_brightness(kind), @@ -736,12 +803,22 @@ fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value Ok(Some(Some(MicroDetail { anchor, amount }))) } -/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. -fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { +/// A generator input a command names: a mesh map it reads, or its texture +#[derive(Clone, Copy)] +enum GeneratorInput { + Map(BakedMap), + Texture, +} + +/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture slot), for a generator on layer `owner` +fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?; - let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id or `texture`"))?; + let input = match name { + TEXTURE_INPUT => GeneratorInput::Texture, + _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), + }; let image = strp(params, "inputImage"); let value = f32p(params, "inputValue"); @@ -762,7 +839,7 @@ fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> R (None, None, None, true) => None, _ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")), }; - Ok(Some((map, source))) + Ok(Some((input, source))) } fn add_generator(session: &mut Session, params: &Value) -> Result { @@ -1060,15 +1137,19 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(micro) = micro { generator.micro = micro; } - if let Some((map, source)) = input { - if !generator.inputs_in_use().contains(&map) { - return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); + match input { + Some((GeneratorInput::Map(map), source)) => { + if !generator.inputs_in_use().contains(&map) { + return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); + } + match source { + Some(source) => generator.inputs.insert(map, source), + None => generator.inputs.remove(&map), + }; } - - match source { - Some(source) => generator.inputs.insert(map, source), - None => generator.inputs.remove(&map), - }; + // generator_from refused the texture on kinds without one and moved the generator onto its section controls + Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source, + None => {} } } _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), diff --git a/crates/engine/tests/it/generator_texture.rs b/crates/engine/tests/it/generator_texture.rs new file mode 100644 index 00000000..9d640515 --- /dev/null +++ b/crates/engine/tests/it/generator_texture.rs @@ -0,0 +1,106 @@ +//! A generator's texture (Use Texture) through `effect.add.generator` and `effect.set`: its controls, its image as the `texture` input, and the kinds without one + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, GeneratorGrayscale, LayerId, Source, TextureBlend, TextureLayer}; +use texturecraft_engine::mask_cmds::section_key_applies; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +/// A gray image resource, by the name it was imported under +fn gray_image(session: &mut Session) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("grunge.png", bytes).unwrap() +} + +#[test] +fn texture_controls_start_from_the_reference_defaults_and_clamp() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "curvature"})); + assert_eq!(generator(&session, effect).texture, None, "untouched until a texture control is given"); + + let edit = + json!({"effect": effect, "useTexture": true, "textureScale": 40.0, "textureContrast": -3.0, "textureBlend": "Soft light", "textureGrayscale": "red"}); + execute(&mut session, "effect.set", &edit).unwrap(); + let expected = TextureLayer { + enabled: true, + scale: *TextureLayer::SCALE_RANGE.end(), + contrast: -1.0, + blend: TextureBlend::SoftLight, + grayscale: GeneratorGrayscale::Red, + ..TextureLayer::default() + }; + assert_eq!(generator(&session, effect).texture, Some(expected)); + assert_eq!(TextureLayer::default().opacity, 0.0, "the reference starts the texture at opacity 0"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureBlend": "dissolve"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureGrayscale": "hue"})).is_err()); +} + +#[test] +fn the_texture_image_is_the_texture_input_and_stays_a_used_resource() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "ambientOcclusion"})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputImage": name})).unwrap(); + let plugged = generator(&session, effect); + assert_eq!(plugged.texture.as_ref().and_then(|texture| texture.source.clone()), Some(Source::image(name.clone()))); + assert!(plugged.inputs.is_empty(), "the texture is not a mesh map input"); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the texture"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputBaked": true})).unwrap(); + assert_eq!(generator(&session, effect).texture.and_then(|texture| texture.source), None, "inputBaked empties the slot"); +} + +#[test] +fn a_texture_moves_an_earlier_generator_onto_its_section_controls() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "position", "level": 0.8})); + assert_eq!(generator(&session, effect).section, None); + + execute(&mut session, "effect.set", &json!({"effect": effect, "textureOpacity": 0.5})).unwrap(); + let moved = generator(&session, effect); + assert!(moved.section.is_some()); + assert_eq!(moved.texture.map(|texture| texture.opacity), Some(0.5)); + + let both = json!({"effect": effect, "useTexture": true, "level": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "a texture control and the earlier model at once"); +} + +#[test] +fn kinds_without_a_texture_refuse_its_controls_and_its_input() { + let mut session = session(); + let name = gray_image(&mut session); + for kind in ["dirt", "edgeWear", "fiberGlassEdgeWear", "direction", "thinAreas"] { + let effect = add(&mut session, json!({"generator": kind})); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "useTexture": true})).is_err(), "{kind} useTexture"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputImage": name})).is_err(), "{kind} texture input"); + assert_eq!(generator(&session, effect).texture, None, "{kind}"); + } + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert!(section_key_applies(added.kind, "textureTriplanar"), "{kind}"); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 44effae5..140ea6ff 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -38,6 +38,7 @@ mod frame_selection; mod generator_inputs; mod generator_sections; mod generator_swap; +mod generator_texture; mod generator_wear; mod gradient_map; mod high_poly_missed; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 7c6f7258..3cadca28 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,8 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, - SectionParameters, Source, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, + SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, }; use crate::TextureCraftApp; @@ -52,6 +52,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); + texture_parameters(app, ui, id, generator.texture.clone().unwrap_or_default()); } if let Some(defaults) = LightParameters::defaults(generator.kind) { light_parameters(app, ui, id, None, defaults); @@ -63,15 +64,19 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.button(tr("Restore defaults")).clicked() { - app.run("effect.set", defaults_of(id, generator.kind)); + app.run("effect.set", defaults_of(id, generator)); } }); }); }); - if !generator.inputs_in_use().is_empty() { + let texture = generator.texture.as_ref().filter(|texture| texture.enabled && SectionParameters::defaults(generator.kind).is_some()); + if !generator.inputs_in_use().is_empty() || texture.is_some() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + if let Some(texture) = texture { + input_slot(app, ui, (layer, id), InputSlot::Texture, texture.source.as_ref(), false); + } for map in generator.inputs_in_use() { - input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail_in_use().is_some()); + input_slot(app, ui, (layer, id), InputSlot::Map(*map), generator.inputs.get(map), generator.detail_in_use().is_some()); } }); } @@ -315,7 +320,8 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { } /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. -fn defaults_of(id: u64, kind: GeneratorKind) -> Value { +fn defaults_of(id: u64, generator: &Generator) -> Value { + let kind = generator.kind; let defaults = Generator::new(kind); let params = json!({ "effect": id, @@ -332,6 +338,10 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let own = match (&defaults.wear, &defaults.section, &defaults.light) { (Some(wear), _, _) => wear_params(kind, wear), (None, _, Some(light)) => light_params(light), + // The texture's controls only once it has them: its image stays in its slot + (None, Some(section), None) if generator.texture.is_some() => { + merged(merged(section_params(kind, section), global), texture_params(&TextureLayer::default())) + } (None, Some(section), None) => merged(section_params(kind, section), global), (None, None, None) => json!({ "level": defaults.level, @@ -433,6 +443,58 @@ fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { } /// The translated name of axis blending mode `blend` +/// Use Texture and, once it is on, the texture's controls and its opacity +fn texture_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, shown: TextureLayer) { + let mut edited = shown; + let mut edit = true_false(ui, tr("Use texture"), &mut edited.enabled).then_some(false); + if edited.enabled { + section(ui, "generator_texture", tr("Texture"), true, |ui| { + edit = edit.or(true_false(ui, tr("Invert"), &mut edited.invert).then_some(false)); + combo(ui, tr("Grayscale conversion"), tr(edited.grayscale.label()), |ui| { + for mode in GeneratorGrayscale::ALL { + if ui.selectable_label(mode == edited.grayscale, tr(mode.label())).clicked() { + edited.grayscale = mode; + edit = Some(false); + } + } + }); + combo(ui, tr("Blending mode"), tr(edited.blend.label()), |ui| { + for blend in TextureBlend::ALL { + if ui.selectable_label(blend == edited.blend, tr(blend.label())).clicked() { + edited.blend = blend; + edit = Some(false); + } + } + }); + edit = edit.or(slider_edit(ui, tr("Scale"), &mut edited.scale, TextureLayer::SCALE_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, -1.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, -1.0..=1.0, 2)); + edit = edit.or(true_false(ui, tr("Triplanar"), &mut edited.triplanar).then_some(false)); + edit = edit.or(slider_edit(ui, tr("Triplanar contrast"), &mut edited.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE, 2)); + }); + edit = edit.or(slider_edit(ui, tr("Texture opacity"), &mut edited.opacity, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), texture_params(&edited))); + } +} + +/// The texture controls as `effect.set` keys (its image is the `texture` input) +fn texture_params(texture: &TextureLayer) -> Value { + json!({ + "useTexture": texture.enabled, + "textureOpacity": texture.opacity, + "textureInvert": texture.invert, + "textureGrayscale": texture.grayscale.id(), + "textureBlend": texture.blend.id(), + "textureScale": texture.scale, + "textureContrast": texture.contrast, + "textureBrightness": texture.brightness, + "textureTriplanar": texture.triplanar, + "textureTriplanarContrast": texture.triplanar_contrast, + }) +} + fn axis_blend_label(blend: AxisBlend) -> &'static str { match blend { AxisBlend::Normal => tr("Normal"), @@ -552,26 +614,62 @@ fn curvature_mode_label(mode: CurvatureMode) -> &'static str { } } -/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. -fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { +/// What an image input slot of a generator replaces: a mesh map it reads, or its texture +#[derive(Clone, Copy)] +enum InputSlot { + Map(BakedMap), + Texture, +} + +impl InputSlot { + /// The input's name in `effect.set` + fn id(self) -> &'static str { + match self { + InputSlot::Map(map) => map.id(), + InputSlot::Texture => "texture", + } + } + + fn title(self) -> &'static str { + match self { + InputSlot::Map(map) => tr(baked_map_label(map)), + InputSlot::Texture => tr("Texture"), + } + } + + /// The value a slot set to a uniform value starts at + fn neutral(self) -> f32 { + match self { + InputSlot::Map(map) => map.neutral()[0], + InputSlot::Texture => 0.0, + } + } +} + +/// One image input: what it reads now, a menu to replace it with a value, an anchor point or an image, and a button to empty it +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), slot: InputSlot, source: Option<&Source>, detail_sizes: bool) { let tokens = Tokens::get(ui.ctx()); - let input = map.id(); - let current = match source { - None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), - Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), - Some(Source::Uniform(_)) => tr("Uniform value").to_string(), - Some(Source::Anchor { anchor, channel, .. }) => anchor_label(app, *anchor, *channel), - Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + let input = slot.id(); + let current = match (source, slot) { + (None, InputSlot::Map(map)) => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + (None, InputSlot::Texture) | (Some(Source::Uniform(_)), _) => tr("Uniform value").to_string(), + (Some(Source::Image { name, .. }), _) => trf("Image: {name}", &[("name", name)]), + (Some(Source::Anchor { anchor, channel, .. }), _) => anchor_label(app, *anchor, *channel), + (Some(Source::Procedural { .. }), _) => tr("Procedural").to_string(), + }; + let empty_hint = match slot { + InputSlot::Map(_) => tr("Read the mesh map again"), + InputSlot::Texture => tr("Empty the slot"), }; let group = ui.group(|ui| { ui.horizontal(|ui| { - input_tile(app, ui, map, source); + input_tile(app, ui, slot, source); ui.vertical(|ui| { - ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(slot.title()).strong()); ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + if source.is_some() && ui.button(ic::X).on_hover_text(empty_hint).clicked() { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } }); @@ -580,11 +678,14 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 ui.push_id(input, |ui| { combo(ui, tr("Source"), current.clone(), |ui| { let anchors = anchors_below(&app.session.doc.project, layer); - if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + if let InputSlot::Map(_) = slot + && ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() + { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } - if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + let uniform = matches!(source, Some(Source::Uniform(_))) || (source.is_none() && matches!(slot, InputSlot::Texture)); + if ui.selectable_label(uniform, tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": slot.neutral()})); } for (anchor, label) in &anchors { if ui @@ -602,13 +703,18 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } }) }); - if let Some(Source::Uniform(value)) = source { - let mut value = value[0]; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); - } + let uniform = match (source, slot) { + (Some(Source::Uniform(value)), _) => Some(value[0]), + (None, InputSlot::Texture) => Some(slot.neutral()), + _ => None, + }; + if let Some(mut value) = uniform + && let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) + { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); } - if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + let replaced_curvature = matches!(slot, InputSlot::Map(BakedMap::Curvature)) && source.is_some_and(|source| !matches!(source, Source::Uniform(_))); + if detail_sizes && replaced_curvature { ui.label( RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) .size(NOTE_FONT_SIZE) @@ -621,14 +727,15 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } } -/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). -fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { +/// The picture beside an image input: its image, its value as gray, an icon for an anchor or a procedural, else its mesh map's color (black for an empty texture) +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, slot: InputSlot, source: Option<&Source>) { let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); let painter = ui.painter(); let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); - match source { - Some(Source::Image { name, .. }) => match app.session.images.get(name) { + let gray = |value: f32| egui::Color32::from_gray((value.clamp(0.0, 1.0) * 255.0).round() as u8); + match (source, slot) { + (Some(Source::Image { name, .. }), _) => match app.session.images.get(name) { Some(image) => { let texture = app.thumbs.image(ui.ctx(), name, image); painter.image(texture.id(), rect, whole, egui::Color32::WHITE); @@ -637,15 +744,18 @@ fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Opt painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); } }, - Some(Source::Uniform(value)) => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + (Some(Source::Uniform(value)), _) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(value[0])); } - Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + (Some(Source::Anchor { .. } | Source::Procedural { .. }), _) => { let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); } - None => { + (None, InputSlot::Texture) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(slot.neutral())); + } + (None, InputSlot::Map(map)) => { let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 513ca72b..01bf845a 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -300,3 +300,60 @@ fn section_panel_snapshots() { harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); } } + +#[test] +fn use_texture_shows_the_texture_rows_and_its_slot() { + let (harness, _) = harness_with(false, json!({"generator": "position"})); + assert_eq!(count(&harness, "Use texture"), 1); + for label in ["Grayscale conversion", "Texture opacity", "Triplanar contrast", "Texture"] { + assert_eq!(count(&harness, label), 0, "{label} waits for Use texture"); + } + + let (harness, _) = harness_with(false, json!({"generator": "position", "useTexture": true})); + for label in ["Grayscale conversion", "Texture opacity", "Triplanar", "Triplanar contrast", "Scale"] { + assert_eq!(count(&harness, label), 1, "{label}"); + } + assert_eq!(count(&harness, "Texture"), 2, "the Texture section and the Texture slot in Image inputs"); + assert_eq!(count(&harness, "Blending mode"), 4, "the texture's beside the three axes'"); + + let (harness, _) = harness_with(false, json!({"generator": "dirt"})); + assert_eq!(count(&harness, "Use texture"), 0, "wear generators have no texture"); +} + +#[test] +fn the_texture_slot_reads_a_uniform_value_until_it_is_given_one() { + let (mut harness, effect) = harness_with(false, json!({"generator": "ambientOcclusion", "useTexture": true})); + let slot = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Uniform value")).count() + }; + assert_eq!(slot(&harness), 1, "an empty texture slot is a uniform value"); + assert_eq!(count(&harness, "Value"), 1, "with its value slider"); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + assert_eq!(count(&harness, "Mesh map"), 0, "the texture has no mesh map to go back to"); + // The slot's heading also reads "Uniform value": the menu entry is the button + harness.get_by_role_and_label(Role::Button, "Uniform value").click(); + harness.run_steps(3); + let texture = generator(&harness, effect).texture.unwrap(); + assert_eq!(texture.source, Some(Source::Uniform([0.0; 3]))); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn texture_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["position", "ambientOcclusion"] { + let (mut harness, _) = harness_with(true, json!({"generator": kind, "useTexture": true, "textureOpacity": 0.6, "textureBlend": "normal"})); + harness.get_by_label("Use texture").scroll_to_me(); + harness.run_steps(12); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("texture-panel-{kind}-{name}.png"))).unwrap(); + } + } +} From 31e834c10d272ddc2d14b23ae0e5979d9d667ef6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:31:37 +0000 Subject: [PATCH 101/153] Wear generators: Use Custom Grunge reads an image instead of the kind's own grunge Metal Edge Wear, Fiber Glass Edge Wear and Dirt take the reference's Use Custom Grunge switch and its grunge image (effect.set input: grunge). Once on, the image's gray replaces the kind's built-in pattern, fitted to the reference app: repeated grunge-scale times across the UV square from half way across the image, or across the mesh's bounds when triplanar; mid gray adds nothing, a brighter image wears edges more and leaves less dirt; the seed leaves it in place. An empty slot reads black. The image moves an earlier-model generator onto its wear controls, is refused on kinds without them, counts as a used resource and stays across swaps between wear kinds. Use Texture and the custom grunge share one slot placement; a generator's texture is boxed so the generator effect stays small. --- crates/compose/src/eval.rs | 47 ++++-- crates/compose/src/texture_layer.rs | 46 ++++-- crates/compose/src/wear.rs | 47 +++++- crates/compose/tests/cache_and_instances.rs | 3 +- .../compose/tests/generator_custom_grunge.rs | 155 ++++++++++++++++++ crates/compose/tests/generator_texture.rs | 4 +- crates/core/src/layer.rs | 14 +- crates/core/src/layer/wear_parameters.rs | 5 + crates/engine/src/inspect.rs | 3 + crates/engine/src/mask_cmds.rs | 39 +++-- .../tests/it/generator_custom_grunge.rs | 104 ++++++++++++ crates/engine/tests/it/generator_texture.rs | 2 +- crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 2 +- 14 files changed, 407 insertions(+), 65 deletions(-) create mode 100644 crates/compose/tests/generator_custom_grunge.rs create mode 100644 crates/engine/tests/it/generator_custom_grunge.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2b0500a7..44875108 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1945,8 +1945,8 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } -/// What a generator's texture reads with nothing in its slot -const EMPTY_TEXTURE_SLOT: Source = Source::Uniform([0.0; 3]); +/// What a generator's texture or custom grunge reads with nothing in its slot +const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); /// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray const GENERATOR_STAGE_COMPONENTS: usize = 3; @@ -3452,7 +3452,13 @@ impl<'a, 'b> Texel<'a, 'b> { let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0); - let grunge = wear::grunge(generator.kind, wear, generator.seed, &self.coords()); + let grunge = if wear.custom_grunge { + // An image not loaded yet reads mid gray, which leaves the wear as without grunge + let gray = self.slot_color(generator, generator.grunge.as_ref(), &wear::custom_grunge_placement(wear)).map_or(0.5, lum); + wear::custom_grunge(generator.kind, gray) + } else { + wear::grunge(generator.kind, wear, generator.seed, &self.coords()) + }; wear::wear_value(generator.kind, wear, &WearInputs { curvature, blurred_curvature, occlusion, grunge }) } @@ -3492,28 +3498,35 @@ impl<'a, 'b> Texel<'a, 'b> { /// The gray of the generator's texture at this texel (None when it blends no texture) fn generator_texture(&mut self, generator: &Generator) -> Option { let texture = generator.texture_in_use()?; - let rgb = match texture.source.as_ref().unwrap_or(&EMPTY_TEXTURE_SLOT) { + let rgb = self.slot_color(generator, texture.source.as_ref(), &texture_layer::texture_placement(texture))?; + Some(texture_layer::texture_gray(texture, rgb)) + } + + /// The color of a generator's image slot holding `source` (None: empty, read as black) at this texel, read where `placement` puts it (None when its image isn't loaded) + fn slot_color(&mut self, generator: &Generator, source: Option<&Source>, placement: &texture_layer::SlotPlacement) -> Option<[f32; 3]> { + match source.unwrap_or(&EMPTY_IMAGE_SLOT) { Source::Image { name, .. } => { let image = self.inp.images.get(name)?.clone(); let read = |coordinates: Vec2| { let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); Vec3::new(red, green, blue) }; - if texture.triplanar { - let normal = self - .generator_input_color(generator, BakedMap::WorldNormal) - .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); - let weights = texture_layer::triplanar_weights(texture, normal); - let coordinates = texture_layer::triplanar_coordinates(texture, self.bounds_position()); - weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight).to_array() - } else { - read(texture_layer::uv_coordinates(texture, self.coords().uv)).to_array() - } + let color = match placement.triplanar_contrast { + Some(contrast) => { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(contrast, normal); + let coordinates = texture_layer::triplanar_coordinates(placement, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight) + } + None => read(texture_layer::uv_coordinates(placement, self.coords().uv)), + }; + Some(color.to_array()) } // A value or an anchor reads the same wherever it is projected - other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), - }; - Some(texture_layer::texture_gray(texture, rgb)) + other => Some(self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + } } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs index 95c40fa3..e9042d05 100644 --- a/crates/compose/src/texture_layer.rs +++ b/crates/compose/src/texture_layer.rs @@ -1,4 +1,4 @@ -//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal +//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal; its custom grunge is read the same way use texturecraft_core::{TextureBlend, TextureLayer}; use texturecraft_geom::glam::{Vec2, Vec3}; @@ -9,20 +9,33 @@ const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58; /// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly const MIN_NORMAL_COMPONENT: f32 = 1e-6; -/// Where the texture is read in UV: scaled about the centre of the UV square -pub(crate) fn uv_coordinates(texture: &TextureLayer, uv: Vec2) -> Vec2 { - (uv - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5) +/// Where a generator's image slot is read: `scale` times across the UV square (or the mesh's bounds, triplanar), plus `offset` +pub(crate) struct SlotPlacement { + pub scale: f32, + pub offset: f32, + /// How sharply the three projections meet, or None to read in UV + pub triplanar_contrast: Option, } -/// Where the texture is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1), scaled about their centre -pub(crate) fn triplanar_coordinates(texture: &TextureLayer, position: Vec3) -> [Vec2; 3] { - let scaled = |u: f32, v: f32| (Vec2::new(u, v) - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5); - [scaled(-position.z, position.y), scaled(position.x, position.z), scaled(position.x, position.y)] +/// The texture is scaled about the centre of the UV square (or of the mesh's bounds) +pub(crate) fn texture_placement(texture: &TextureLayer) -> SlotPlacement { + SlotPlacement { scale: texture.scale, offset: 0.5 * (1.0 - texture.scale), triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast) } } -/// How much each projection (facing X, Y and Z) counts for a surface facing `normal`, summing to 1 -pub(crate) fn triplanar_weights(texture: &TextureLayer, normal: Vec3) -> [f32; 3] { - let contrast = texture.triplanar_contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end()); +/// Where a slot is read in UV +pub(crate) fn uv_coordinates(placement: &SlotPlacement, uv: Vec2) -> Vec2 { + uv * placement.scale + Vec2::splat(placement.offset) +} + +/// Where a slot is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1) +pub(crate) fn triplanar_coordinates(placement: &SlotPlacement, position: Vec3) -> [Vec2; 3] { + let placed = |u: f32, v: f32| Vec2::new(u, v) * placement.scale + Vec2::splat(placement.offset); + [placed(-position.z, position.y), placed(position.x, position.z), placed(position.x, position.y)] +} + +/// How much each projection (facing X, Y and Z) counts for a surface facing `normal` at triplanar `contrast`, summing to 1 +pub(crate) fn triplanar_weights(contrast: f32, normal: Vec3) -> [f32; 3] { + let contrast = contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end()); let sharpness = (1.0 - contrast).max(f32::EPSILON).powf(-TRIPLANAR_SHARPNESS_POWER); let facing = normal.abs(); let largest = facing.max_element().max(MIN_NORMAL_COMPONENT); @@ -132,19 +145,18 @@ mod tests { #[test] fn triplanar_weights_follow_the_normal_and_sharpen_with_contrast() { - let along_y = triplanar_weights(&texture(), Vec3::Y); + let along_y = triplanar_weights(texture().triplanar_contrast, Vec3::Y); assert!((along_y[1] - 1.0).abs() < 1e-6); let diagonal = Vec3::new(1.0, 0.5, 0.0).normalize(); - let soft = triplanar_weights(&TextureLayer { triplanar_contrast: 0.001, ..texture() }, diagonal); - let hard = triplanar_weights(&TextureLayer { triplanar_contrast: 0.9, ..texture() }, diagonal); + let (soft, hard) = (triplanar_weights(0.001, diagonal), triplanar_weights(0.9, diagonal)); assert!(hard[0] > soft[0] && hard[1] < soft[1]); assert!((soft.iter().sum::() - 1.0).abs() < 1e-5); } #[test] fn scale_is_about_the_centre() { - let texture = TextureLayer { scale: 2.0, ..texture() }; - assert_eq!(uv_coordinates(&texture, Vec2::splat(0.5)), Vec2::splat(0.5)); - assert_eq!(uv_coordinates(&texture, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); + let placement = texture_placement(&TextureLayer { scale: 2.0, ..texture() }); + assert_eq!(uv_coordinates(&placement, Vec2::splat(0.5)), Vec2::splat(0.5)); + assert_eq!(uv_coordinates(&placement, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); } } diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index b766f3e1..864ae755 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -5,6 +5,7 @@ use texturecraft_core::{GeneratorKind, Procedural, ProceduralKind, Projection, W use crate::curvature_sizes::LEVEL_RADII; use crate::pattern::{Coords, procedural}; +use crate::texture_layer::SlotPlacement; use crate::wear_inputs::WearInputs; use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; @@ -29,11 +30,13 @@ struct GrungePattern { breakup: Option<(ProceduralKind, f32)>, mean: f32, spread: f32, + /// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner) + custom_gain: f32, } /// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt const EDGE_WEAR_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149 }; + GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 }; const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Weave, repeats_per_scale: 16.0, @@ -41,15 +44,22 @@ const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { breakup: Some((ProceduralKind::Grunge, 4.0)), mean: 0.539, spread: 0.198, + custom_gain: 1.9, }; const DIRT_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242 }; + GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 }; /// How much a breakup pattern varies the grunge's strength (0 none, 1 down to nothing) const BREAKUP_DEPTH: f32 = 0.6; /// The triplanar seams' sharpness at triplanar contrast 0 and 1 const TRIPLANAR_SHARPNESS: std::ops::RangeInclusive = 1.0..=16.0; +/// The gray at which a custom grunge neither adds nor removes wear +const CUSTOM_GRUNGE_MID_GRAY: f32 = 0.5; + +/// Where the reference app reads a custom grunge at the UV square's origin: half way across the image (triplanar: at its origin) +const CUSTOM_GRUNGE_UV_OFFSET: f32 = 0.5; + /// The Gaussian sigma (texels at 2K) the kind's blurred curvature is read at pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { match kind { @@ -59,17 +69,24 @@ pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { } } -/// The wear's grunge at `coords`, normalised to mean 0 and spread 1 -pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coords: &Coords) -> f32 { - let grunge = match kind { +fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern { + match kind { GeneratorKind::Dirt => &DIRT_GRUNGE, GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, _ => &EDGE_WEAR_GRUNGE, - }; + } +} + +fn triplanar_sharpness(wear: &WearParameters) -> f32 { + TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast +} + +/// The wear's own grunge at `coords`, normalised to mean 0 and spread 1 +pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coords: &Coords) -> f32 { + let grunge = grunge_pattern(kind); let pattern = Procedural { scale: grunge.repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(grunge.kind) }; let projection = if wear.triplanar { - let sharpness = TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast; - Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] } + Projection::Triplanar { scale: 1.0, sharpness: triplanar_sharpness(wear), offset: [0.0; 3], uv: Default::default(), projector: Default::default() } } else { Projection::Uv { scale: [1.0, 1.0], rotation: grunge.rotation, offset: [0.0, 0.0] } }; @@ -81,6 +98,20 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor (value - grunge.mean) / grunge.spread } +/// Where a custom grunge image is read: repeated grunge-scale times across the UV square (or the mesh's bounds, triplanar) +pub(crate) fn custom_grunge_placement(wear: &WearParameters) -> SlotPlacement { + if wear.triplanar { + SlotPlacement { scale: wear.grunge_scale, offset: 0.0, triplanar_contrast: Some(wear.triplanar_contrast) } + } else { + SlotPlacement { scale: wear.grunge_scale, offset: CUSTOM_GRUNGE_UV_OFFSET, triplanar_contrast: None } + } +} + +/// A custom grunge's `gray` as the normalised grunge the fitted signals read; the reference app's seed leaves it where it is +pub(crate) fn custom_grunge(kind: GeneratorKind, gray: f32) -> f32 { + grunge_pattern(kind).custom_gain * (gray - CUSTOM_GRUNGE_MID_GRAY) +} + /// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { let sigmas = LEVEL_SIGMAS; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index dac833d1..b3d1c309 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -1281,7 +1281,8 @@ fn replacing_a_generator_texture_image_invalidates_the_cached_stack() { let hot_layer = heavy_stack(&mut fixture); let texture = TextureLayer { enabled: true, source: Some(Source::image("grunge")), opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() }; let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(texture), ..Generator::new(GeneratorKind::AmbientOcclusion) }))); + mask.effects + .push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(Box::new(texture)), ..Generator::new(GeneratorKind::AmbientOcclusion) }))); let textured = add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), Some(mask)); let stack = &mut fixture.project.texture_sets[0].stack; stack.retain(|id| *id != textured); diff --git a/crates/compose/tests/generator_custom_grunge.rs b/crates/compose/tests/generator_custom_grunge.rs new file mode 100644 index 00000000..ce652afc --- /dev/null +++ b/crates/compose/tests/generator_custom_grunge.rs @@ -0,0 +1,155 @@ +//! A wear generator's custom grunge on a sphere: read instead of the kind's own pattern, tiled by the grunge scale, the seed leaving it in place + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, TextureSet, + WearParameters, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// Width of the split image: its left half black, its right half white +const SPLIT_WIDTH: u32 = 64; + +const WEAR_KINDS: [GeneratorKind; 3] = [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::Dirt]; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, + images: ImageStore, +} + +/// A unit sphere with a white fill layer, no occlusion anywhere, no curvature map, and the images `black`, `white` and `split` +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; (RES * RES) as usize]))].into() }; + + let flat = |value: f32| Arc::new(ImageRes::new(4, 4, vec![[value, value, value, 1.0]; 16], false)); + let split_texel = |index: u32| if index % SPLIT_WIDTH < SPLIT_WIDTH / 2 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }; + let split = ImageRes::new(SPLIT_WIDTH, SPLIT_WIDTH, (0..SPLIT_WIDTH * SPLIT_WIDTH).map(split_texel).collect(), false); + let images = [("black".to_string(), flat(0.0)), ("white".to_string(), flat(1.0)), ("split".to_string(), Arc::new(split))].into(); + Fixture { project, mesh, gbuf, layer, baked, images } +} + +/// Every covered texel +fn covered(fixture: &Fixture) -> Vec<(u32, u32)> { + (0..RES * RES).filter(|index| fixture.gbuf.surface(&fixture.mesh, *index as usize).is_some()).map(|index| (index % RES, index / RES)).collect() +} + +/// The mask of `generator` alone over black at `texels` +fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// `kind` on its wear controls at full grunge amount, reading `image` (None: an empty slot) as its grunge once `custom` is on +fn wear(kind: GeneratorKind, image: Option<&str>, custom: bool, edit: impl Fn(&mut WearParameters)) -> Generator { + let mut wear = WearParameters { grunge_amount: 1.0, custom_grunge: custom, ..WearParameters::defaults(kind).unwrap() }; + edit(&mut wear); + Generator { wear: Some(wear), grunge: image.map(Source::image), ..Generator::new(kind) } +} + +fn mean(values: &[f32]) -> f32 { + values.iter().sum::() / values.len() as f32 +} + +/// The share of texels where `first` and `second` differ +fn differing(first: &[f32], second: &[f32]) -> f32 { + first.iter().zip(second).filter(|(a, b)| (*a - *b).abs() > 0.05).count() as f32 / first.len() as f32 +} + +#[test] +fn a_grunge_image_changes_nothing_until_use_custom_grunge_is_on() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + let own = mask(&mut fixture, wear(kind, None, false, |_| {}), &texels); + assert_eq!(mask(&mut fixture, wear(kind, Some("white"), false, |_| {}), &texels), own, "{kind:?}"); + assert!(differing(&mask(&mut fixture, wear(kind, Some("white"), true, |_| {}), &texels), &own) > 0.1, "{kind:?}: on, the image replaces the pattern"); + } +} + +#[test] +fn a_brighter_custom_grunge_wears_edges_more_and_dirties_less_in_uv_and_triplanar() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + for triplanar in [false, true] { + let read = |fixture: &mut Fixture, image| mean(&mask(fixture, wear(kind, Some(image), true, |wear| wear.triplanar = triplanar), &texels)); + let (white, black) = (read(&mut fixture, "white"), read(&mut fixture, "black")); + let (more, less) = if kind == GeneratorKind::Dirt { (black, white) } else { (white, black) }; + assert!(more > less + 0.3, "{kind:?} triplanar {triplanar}: white {white}, black {black}"); + } + } +} + +#[test] +fn an_empty_grunge_slot_reads_black() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + assert_eq!( + mask(&mut fixture, wear(kind, None, true, |_| {}), &texels), + mask(&mut fixture, wear(kind, Some("black"), true, |_| {}), &texels), + "{kind:?}" + ); + } +} + +#[test] +fn the_grunge_scale_repeats_a_custom_grunge_across_the_uv_square() { + let mut fixture = fixture(); + // Texel pairs half the UV square apart, both covered + let covered = covered(&fixture); + let pairs: Vec<((u32, u32), (u32, u32))> = + covered.iter().filter(|(x, _)| *x < RES / 2).map(|(x, y)| ((*x, *y), (x + RES / 2, *y))).filter(|(_, right)| covered.contains(right)).collect(); + let (left, right): (Vec<_>, Vec<_>) = pairs.into_iter().unzip(); + let halves = |fixture: &mut Fixture, scale: f32| { + let generator = wear(GeneratorKind::EdgeWear, Some("split"), true, |wear| wear.grunge_scale = scale); + (mask(fixture, generator.clone(), &left), mask(fixture, generator, &right)) + }; + + let (first, second) = halves(&mut fixture, 2.0); + assert!(differing(&first, &second) < 0.02, "twice across the square, half of it apart reads the same"); + let (first, second) = halves(&mut fixture, 1.0); + assert!(differing(&first, &second) > 0.5, "once across the square, half of it apart reads the other side of the image"); +} + +#[test] +fn the_seed_leaves_a_custom_grunge_in_place() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + for triplanar in [false, true] { + let seeded = |seed| Generator { seed, ..wear(kind, Some("split"), true, |wear| wear.triplanar = triplanar) }; + assert_eq!(mask(&mut fixture, seeded(1), &texels), mask(&mut fixture, seeded(2), &texels), "{kind:?} triplanar {triplanar}"); + } + } +} diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs index 3800ccb6..b9bd92ea 100644 --- a/crates/compose/tests/generator_texture.rs +++ b/crates/compose/tests/generator_texture.rs @@ -94,7 +94,7 @@ fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> V /// Ambient Occlusion on its section controls with `texture` reading image `image` fn occlusion_with(image: &str, texture: TextureLayer) -> Generator { - Generator { texture: Some(TextureLayer { source: Some(Source::image(image)), ..texture }), ..Generator::new(GeneratorKind::AmbientOcclusion) } + Generator { texture: Some(Box::new(TextureLayer { source: Some(Source::image(image)), ..texture })), ..Generator::new(GeneratorKind::AmbientOcclusion) } } /// A texture turned on at full opacity, replacing the signal @@ -122,7 +122,7 @@ fn a_texture_turned_off_or_at_opacity_zero_leaves_the_signal() { fn an_empty_texture_slot_blends_black() { let mut fixture = fixture([0.6; 3]); let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); - let empty = Generator { texture: Some(TextureLayer { opacity: 0.5, ..replacing() }), ..Generator::new(GeneratorKind::AmbientOcclusion) }; + let empty = Generator { texture: Some(Box::new(TextureLayer { opacity: 0.5, ..replacing() })), ..Generator::new(GeneratorKind::AmbientOcclusion) }; assert_all(&mask(&mut fixture, empty, &texels), OCCLUSION * 0.5, "half way to black"); } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index a169516b..0dbcc0d7 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1068,9 +1068,12 @@ pub struct Generator { /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub light: Option, - /// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed) + /// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] - pub texture: Option, + pub texture: Option>, + /// The image a wear generator reads as its grunge once Use Custom Grunge is on (None: an empty slot) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub grunge: Option, } impl Generator { @@ -1105,12 +1108,12 @@ impl Generator { /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity pub fn texture_in_use(&self) -> Option<&TextureLayer> { - self.texture.as_ref().filter(|texture| texture.in_use() && self.section_controls().is_some()) + self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) } - /// Everything the generator reads instead of its mesh maps: its inputs, then its texture + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture and its custom grunge pub fn sources(&self) -> impl Iterator { - self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())) + self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()) } /// Whether the generator is on the level, softness and noise it had before the reference app's controls @@ -1150,6 +1153,7 @@ impl Generator { section: SectionParameters::defaults(kind), light: LightParameters::defaults(kind), texture: None, + grunge: None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 956dbd1a..17975266 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -26,6 +26,9 @@ pub struct WearParameters { pub curvature_weight: f32, /// How much convex edges are kept clean (0..1; Dirt) pub edges_masking: f32, + /// The grunge read from the generator's custom grunge image instead of the kind's own pattern + #[serde(default)] + pub custom_grunge: bool, } impl WearParameters { @@ -45,6 +48,7 @@ impl WearParameters { ao_masking: 0.5, curvature_weight: 1.0, edges_masking: 0.5, + custom_grunge: false, }; match kind { GeneratorKind::EdgeWear | GeneratorKind::Dirt => Some(shared), @@ -76,6 +80,7 @@ impl WearParameters { ao_masking: unit(self.ao_masking, defaults.ao_masking), curvature_weight: unit(self.curvature_weight, defaults.curvature_weight), edges_masking: unit(self.edges_masking, defaults.edges_masking), + custom_grunge: self.custom_grunge, } } } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 39918d33..de36131e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -156,6 +156,9 @@ fn generator_json(generator: &Generator) -> Value { if let Some(texture) = &generator.texture { out["texture"] = json!(texture); } + if let Some(grunge) = &generator.grunge { + out["grunge"] = source_json(grunge); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 8f67edf9..4369c512 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id or texture + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture or grunge + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -395,7 +395,7 @@ const EARLIER_WEAR_KEYS: [&str; 7] = ["level", "softness", "noise", "noiseScale" const GLOBAL_KEYS: [&str; 3] = ["blur", "balance", "contrast"]; /// The wear controls `effect.add.generator` and `effect.set` take -const WEAR_KEYS: [&str; 10] = [ +const WEAR_KEYS: [&str; 11] = [ "wearLevel", "wearContrast", "grungeAmount", @@ -406,16 +406,21 @@ const WEAR_KEYS: [&str; 10] = [ "aoMasking", "curvatureWeight", "edgesMasking", + "useCustomGrunge", ]; -/// The wear controls in `params`: they move a wear generator onto them, while level, softness, noise or offset keep it on the earlier model +/// The input name of a wear generator's custom grunge image, beside the mesh map ids +const GRUNGE_INPUT: &str = "grunge"; + +/// The wear controls in `params` (a grunge input counts as one): they move a wear generator onto them, while level, softness, noise or offset keep it on the earlier model fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let wear_given = given(&WEAR_KEYS) || strp(params, "input") == Some(GRUNGE_INPUT); let Some(defaults) = WearParameters::defaults(generator.kind) else { - return if given(&WEAR_KEYS) { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; + return if wear_given { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; }; - let earlier_model = given(&EARLIER_WEAR_KEYS) || (generator.wear.is_none() && !given(&WEAR_KEYS) && generator.kind != GeneratorKind::FiberGlassEdgeWear); + let earlier_model = given(&EARLIER_WEAR_KEYS) || (generator.wear.is_none() && !wear_given && generator.kind != GeneratorKind::FiberGlassEdgeWear); if given(&GLOBAL_KEYS) && !earlier_model { return Err(bad(command, format!("{} has no global blur, balance or contrast on its wear controls", generator.kind.label()))); } @@ -424,7 +429,7 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result } if given(&EARLIER_WEAR_KEYS) { - if given(&WEAR_KEYS) { + if wear_given { return Err(bad(command, "level, softness, noise and offset drive the earlier wear model: give them or the wear controls, not both")); } if generator.kind == GeneratorKind::FiberGlassEdgeWear { @@ -433,7 +438,7 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result generator.wear = None; return Ok(()); } - if !given(&WEAR_KEYS) { + if !wear_given { return Ok(()); } @@ -458,6 +463,9 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result if let Some(triplanar) = boolp(params, "triplanar") { wear.triplanar = triplanar; } + if let Some(custom_grunge) = boolp(params, "useCustomGrunge") { + wear.custom_grunge = custom_grunge; + } *wear = wear.clamped(generator.kind); Ok(()) } @@ -633,7 +641,7 @@ fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Res if !TEXTURE_KEYS.iter().any(|key| params.get(*key).is_some()) { return Ok(()); } - let mut texture = generator.texture.clone().unwrap_or_default(); + let mut texture = generator.texture.as_deref().cloned().unwrap_or_default(); if let Some(enabled) = boolp(params, "useTexture") { texture.enabled = enabled; } @@ -662,7 +670,7 @@ fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Res let name = value.as_str().ok_or_else(|| bad(command, "`textureBlend` must be a string"))?; texture.blend = TextureBlend::parse(name).ok_or_else(|| bad(command, format!("unknown blending mode `{name}`")))?; } - generator.texture = Some(texture.clamped()); + generator.texture = Some(Box::new(texture.clamped())); Ok(()) } @@ -803,20 +811,22 @@ fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value Ok(Some(Some(MicroDetail { anchor, amount }))) } -/// A generator input a command names: a mesh map it reads, or its texture +/// A generator input a command names: a mesh map it reads, its texture or its custom grunge #[derive(Clone, Copy)] enum GeneratorInput { Map(BakedMap), Texture, + Grunge, } -/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture slot), for a generator on layer `owner` +/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id or `texture`"))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture` or `grunge`"))?; let input = match name { TEXTURE_INPUT => GeneratorInput::Texture, + GRUNGE_INPUT => GeneratorInput::Grunge, _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), }; @@ -1149,6 +1159,8 @@ fn set(session: &mut Session, params: &Value) -> Result { } // generator_from refused the texture on kinds without one and moved the generator onto its section controls Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source, + // generator_from refused the grunge on kinds without wear controls and moved the generator onto them + Some((GeneratorInput::Grunge, source)) => generator.grunge = source, None => {} } } @@ -1281,6 +1293,7 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { global: current.global, resolution: current.resolution, inputs, + grunge: current.grunge.clone().filter(|_| WearParameters::defaults(kind).is_some()), ..Generator::new(kind) } } diff --git a/crates/engine/tests/it/generator_custom_grunge.rs b/crates/engine/tests/it/generator_custom_grunge.rs new file mode 100644 index 00000000..4bb171b6 --- /dev/null +++ b/crates/engine/tests/it/generator_custom_grunge.rs @@ -0,0 +1,104 @@ +//! A wear generator's custom grunge through `effect.set`: Use Custom Grunge, its image as the `grunge` input, and the kinds without one + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, LayerId, Source}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +/// A gray image resource, by the name it was imported under +fn gray_image(session: &mut Session) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("grunge.png", bytes).unwrap() +} + +#[test] +fn use_custom_grunge_is_a_wear_control_of_every_wear_kind() { + let mut session = session(); + for kind in ["edgeWear", "fiberGlassEdgeWear", "dirt"] { + let effect = add(&mut session, json!({"generator": kind})); + let wear = |session: &Session| generator(session, effect).wear.map(|wear| wear.custom_grunge); + assert_ne!(wear(&session), Some(true), "{kind}: off until turned on"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "useCustomGrunge": true})).unwrap(); + assert_eq!(wear(&session), Some(true), "{kind}"); + } +} + +#[test] +fn the_grunge_image_is_the_grunge_input_and_stays_a_used_resource() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "dirt", "wearLevel": 0.6})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).unwrap(); + let plugged = generator(&session, effect); + assert_eq!(plugged.grunge, Some(Source::image(name.clone()))); + assert!(plugged.inputs.is_empty(), "the grunge is not a mesh map input"); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the grunge"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputBaked": true})).unwrap(); + assert_eq!(generator(&session, effect).grunge, None, "inputBaked empties the slot"); +} + +#[test] +fn a_grunge_image_moves_an_earlier_wear_generator_onto_its_wear_controls() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "edgeWear", "level": 0.8})); + assert_eq!(generator(&session, effect).wear, None); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).unwrap(); + assert!(generator(&session, effect).wear.is_some()); + + let both = json!({"effect": effect, "input": "grunge", "inputImage": name, "level": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "a grunge image and the earlier model at once"); + let both = json!({"effect": effect, "useCustomGrunge": true, "softness": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "Use Custom Grunge and the earlier model at once"); +} + +#[test] +fn kinds_without_wear_controls_refuse_a_custom_grunge() { + let mut session = session(); + let name = gray_image(&mut session); + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals", "direction", "thinAreas"] { + let effect = add(&mut session, json!({"generator": kind})); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "useCustomGrunge": true})).is_err(), "{kind} useCustomGrunge"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).is_err(), "{kind} grunge input"); + assert_eq!(generator(&session, effect).grunge, None, "{kind}"); + } +} + +#[test] +fn swapping_between_wear_kinds_keeps_the_grunge_image() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "edgeWear"})); + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "dirt"})).unwrap(); + assert_eq!(generator(&session, effect).grunge, Some(Source::image(name)), "Dirt reads a custom grunge too"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "curvature"})).unwrap(); + assert_eq!(generator(&session, effect).grunge, None, "Curvature has no grunge"); +} diff --git a/crates/engine/tests/it/generator_texture.rs b/crates/engine/tests/it/generator_texture.rs index 9d640515..b3dad7b7 100644 --- a/crates/engine/tests/it/generator_texture.rs +++ b/crates/engine/tests/it/generator_texture.rs @@ -48,7 +48,7 @@ fn texture_controls_start_from_the_reference_defaults_and_clamp() { grayscale: GeneratorGrayscale::Red, ..TextureLayer::default() }; - assert_eq!(generator(&session, effect).texture, Some(expected)); + assert_eq!(generator(&session, effect).texture, Some(Box::new(expected))); assert_eq!(TextureLayer::default().opacity, 0.0, "the reference starts the texture at opacity 0"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureBlend": "dissolve"})).is_err()); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 140ea6ff..de497d5a 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -35,6 +35,7 @@ mod filter_transform; mod filters; mod folder_contents; mod frame_selection; +mod generator_custom_grunge; mod generator_inputs; mod generator_sections; mod generator_swap; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 3cadca28..62b3d0bb 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -52,7 +52,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); - texture_parameters(app, ui, id, generator.texture.clone().unwrap_or_default()); + texture_parameters(app, ui, id, generator.texture.as_deref().cloned().unwrap_or_default()); } if let Some(defaults) = LightParameters::defaults(generator.kind) { light_parameters(app, ui, id, None, defaults); From 73900d425260ada3f91eabdf205b71236065afab Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:55:06 +0000 Subject: [PATCH 102/153] Generators: Micro Details add a height or normal image's curvature and occlusion Curvature, Ambient Occlusion and the three wear kinds take the reference's Micro Details: Use Micro Details (Curvature and Ambient Occlusion), Micro Height, Micro Normal, Curvature Type (Standard, Sobel, Smooth), Curvature Intensity, Height Details Intensity, AO Radius and AO Depth, with the images as the microHeight and microNormal inputs of effect.set (an image or a value; an empty slot reads black). Fitted to the reference app: the micro height becomes a normal, and that normal's divergence (Smooth: the height against blurred copies of itself) is added to the curvature input before the detail sizes blur it, with a small per-type lift; the micro normal adds its own divergence. Ambient Occlusion is multiplied by a horizon occlusion of the micro height over 16 directions. Both are built once per mesh map, image and settings and cached; derivatives and radii are per texel at 2K, so the look holds across resolutions. Off by default, so existing projects render as before; the controls move an earlier-model generator onto the reference's controls, are refused on kinds without them, and the images stay across swaps between kinds that have them. --- crates/compose/src/curvature_sizes.rs | 6 +- crates/compose/src/eval.rs | 277 ++++---- crates/compose/src/generator_maps.rs | 34 + crates/compose/src/lib.rs | 2 + crates/compose/src/micro_details.rs | 626 ++++++++++++++++++ .../compose/tests/generator_micro_details.rs | 211 ++++++ crates/core/src/block_scales.rs | 18 + crates/core/src/layer.rs | 90 ++- .../core/src/layer/anchored_micro_detail.rs | 18 + crates/core/src/layer/micro_curvature_type.rs | 30 + crates/core/src/layer/micro_detail.rs | 16 - crates/core/src/layer/micro_details.rs | 121 ++++ crates/core/src/lib.rs | 2 +- crates/engine/src/anchored_micro_edit.rs | 71 ++ crates/engine/src/inspect.rs | 6 +- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_cmds.rs | 74 +-- crates/engine/src/micro_params.rs | 91 +++ crates/engine/tests/it/content_effects.rs | 55 +- .../tests/it/generator_micro_details.rs | 133 ++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/dock.rs | 18 - crates/ui-egui/src/generator_panel.rs | 40 +- crates/ui-egui/tests/it/generator_panel.rs | 5 +- crates/ui-egui/tests/ui_snapshots.rs | 30 - 25 files changed, 1658 insertions(+), 319 deletions(-) create mode 100644 crates/compose/src/generator_maps.rs create mode 100644 crates/compose/src/micro_details.rs create mode 100644 crates/compose/tests/generator_micro_details.rs create mode 100644 crates/core/src/layer/anchored_micro_detail.rs create mode 100644 crates/core/src/layer/micro_curvature_type.rs delete mode 100644 crates/core/src/layer/micro_detail.rs create mode 100644 crates/core/src/layer/micro_details.rs create mode 100644 crates/engine/src/anchored_micro_edit.rs create mode 100644 crates/engine/src/micro_params.rs create mode 100644 crates/engine/tests/it/generator_micro_details.rs diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index f47d9fcb..4a95ff17 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -34,7 +34,11 @@ const CACHE_MAPS: usize = 16; impl CurvatureSizes { /// 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)?; + CurvatureSizes::of_map(inp, inp.baked.maps.get(&BakedMap::Curvature)?, needed) + } + + /// The sizes of `curvature`, a map in the baked curvature map's layout (the baked map or one derived from it) + pub fn of_map(inp: &Inputs, curvature: &Arc>, needed: &[bool]) -> Option> { let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); if !needed.contains(&true) || width == 0 || height == 0 { return None; diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 44875108..2bf1cf69 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -14,7 +14,7 @@ use rayon::prelude::*; use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, + HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; @@ -31,8 +31,10 @@ use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_depth::FillDepth; use crate::fill_place::FillPlace; +use crate::generator_maps::GeneratorMaps; use crate::held_fields::HeldFields; use crate::mask_gray::MaskGray; +use crate::micro_details::AnchorHeights; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; @@ -292,8 +294,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, - /// The curvature detail sizes a generator with detail reads. - curvature_sizes: Option>, + /// The detail sizes and micro details a generator reads + maps: GeneratorMaps, /// A filtered mask stage retained because an anchor above it records that stage. filtered_mask: Option<&'a Field>, /// The projector's depth map of a fill or material effect that culls by depth @@ -1694,7 +1696,7 @@ fn filter_region( let height_nodes = if heights { plan_in(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below), place, None) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); - let mut generator_sizes = None; + let mut generator_maps = GeneratorMaps::default(); match job { Job::Mask(layer_mask) => { // The layer's own filtered content, for a compare of it (this mask's field is not built yet) @@ -1702,7 +1704,7 @@ fn filter_region( continue; }; - generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); + generator_maps = mask_stack.effects.get(index).map(|effect| effect.maps.clone()).unwrap_or_default(); mask_stack.effects.truncate(index); mask_stack.start = start; mask = Some(mask_stack); @@ -1727,7 +1729,7 @@ fn filter_region( let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { - let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, &generator_maps)); let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); [texel.mask(mask_stack), ramp, texture, 0.0] } @@ -2298,6 +2300,7 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La draw_order(inp, list, 0, around.into(), &mut order); let ids: Vec = order.iter().map(|(id, _)| *id).collect(); prepare_curvature_sizes(inp, &ids); + prepare_micro_anchors(inp); // Walk backwards to find the region each Compare needs below its position in the stack let mut below_margin = (0u32, false); @@ -2395,6 +2398,59 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { prepare_mask_curvature_sizes(inp, masks); } +/// Build the height of every anchor point a visible generator's Micro Height reads, over the whole texture set, before tiles composite in parallel +fn prepare_micro_anchors(inp: &EvaluationInputs) { + let Ok(set) = inp.project.texture_set(inp.ts) else { return }; + let tree = inp.project.render_tree(&set.stack); + let visible = tree.iter().filter_map(|id| inp.project.layers.get(id)).filter(|layer| layer.visible); + let mut readers: Vec<(LayerId, LayerId)> = Vec::new(); + for layer in visible { + let effects = layer_mask(inp.project, layer.id).filter(|mask| mask.enabled).into_iter().flat_map(|mask| &mask.effects); + for effect in effects.filter(|effect| effect.visible) { + if let EffectKind::Generator(generator) = &effect.kind + && let Some(micro) = generator.micro_in_use().filter(|micro| micro.height) + && let Some(Source::Anchor { anchor, .. }) = µ.height_source + && !readers.iter().any(|(_, read)| read == anchor) + { + readers.push((layer.id, *anchor)); + } + } + } + if readers.is_empty() { + return; + } + + for (reader, anchor) in readers { + let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; + crate::micro_details::prepare_anchor_heights(inp, anchor, stack, || anchor_heights(inp, reader, anchor)); + } +} + +/// Anchor point `anchor`'s height over the whole texture set as layer `reader` reads it, in the working atlas's layout +fn anchor_heights(inp: &EvaluationInputs, reader: LayerId, anchor: LayerId) -> AnchorHeights { + let (width, height) = (inp.gbuf.width, inp.gbuf.height); + let channels = evaluation_channels(inp, vec![Channel::Height]); + let fields = evaluation_fields(inp, &channels, &all_tiles(width, height)); + let width_usize = width as usize; + let tile_side = TILE as usize; + let mut data = vec![0.0f32; width_usize * height as usize]; + + // Each tile row writes its own atlas rows + data.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let nodes = anchor_plan(inp, (reader, 0), &channels, tile_x, tile_y as u32, Some(&fields)); + for (x, y, offset) in tile_texels(inp.gbuf, tile_x, tile_y as u32) { + let mut texel = Texel::new(inp, x, y, offset, 0.0); + texel.anchors_below(&nodes, (reader, 0)); + if let Some(destination) = rows.get_mut((y as usize % tile_side) * width_usize + x as usize) { + *destination = texel.anchored(anchor, Channel::Height)[0]; + } + } + } + }); + AnchorHeights::new(data, (width, height), inp.block_scales.clone()) +} + /// The blurred curvature levels `generator` reads: its wear's smoothing, else its detail sizes (a replaced curvature input reads none) fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { if generator.inputs.contains_key(&BakedMap::Curvature) { @@ -2418,6 +2474,11 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator( Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let curvature_sizes = match &effect.kind { - EffectKind::Generator(generator) => CurvatureSizes::of(inp, &curvature_sizes_in_use(generator)), - _ => None, + let maps = match &effect.kind { + EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator)), + _ => GeneratorMaps::default(), }; let (depth, covers_all, projection) = match &effect.kind { EffectKind::Fill { projection, sampling, .. } | EffectKind::Material(Fill { projection, sampling, .. }) => { @@ -2492,7 +2553,7 @@ fn effect_plans<'a>( opacity: blend.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes, + maps, filtered_mask: None, depth, covers_all, @@ -3332,9 +3393,9 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). - fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + fn generator_ramp(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { if let Some(wear) = wear_parameters(generator) { - return self.wear_ramp(generator, &wear, curvature_sizes); + return self.wear_ramp(generator, &wear, maps); } if let Some(light) = &generator.light { let normal = @@ -3343,32 +3404,29 @@ impl<'a, 'b> Texel<'a, 'b> { return sections::light_value(light, normal, position, generator.invert); } if let Some(section) = generator.section_controls() { - return self.section_signal(generator, §ion, curvature_sizes); + return self.section_signal(generator, §ion, maps); } let coords = self.coords(); - let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + + // Micro details saved on the earlier model add to its curvature and occlusion inputs too let signal = match (generator.kind, &generator.detail) { (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; - let curvature = self.generator_input(generator, BakedMap::Curvature); - self.curvature_detail(detail, sizes, curvature, micro) + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(detail, sizes, curvature) } - (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => { - (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0 - } - (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => (self.curvature_input(generator, maps).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.curvature_input(generator, maps).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.occlusion_input(generator, maps).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.occlusion_input(generator, maps).unwrap_or(1.0), (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, 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, // World Space Normals always computes with its section controls: this arm only keeps the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, }; - let signal = - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -3389,33 +3447,16 @@ impl<'a, 'b> Texel<'a, 'b> { ramp * ramp * (3.0 - 2.0 * ramp) } - /// How a generator's micro detail moves its signal at this texel: the anchor's height (0 where - /// the anchor is not evaluated yet) as an edge where raised and a cavity where recessed. - fn micro_detail(&self, kind: GeneratorKind, micro: MicroDetail) -> f32 { - let height = self.anchor_value(micro.anchor, Channel::Height, ChannelKind::Signed)[0]; - let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; - let response = height.clamp(-1.0, 1.0) * amount; - match kind { - GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::FiberGlassEdgeWear => response, - - // Dirt gathers in dents; dents are occluded - GeneratorKind::Dirt => -response, - GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => 0.0, - } - } - /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion - fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, maps: &GeneratorMaps) -> f32 { match generator.kind { GeneratorKind::Curvature => { let detail = generator.detail_in_use().unwrap_or_default(); - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; - let curvature = self.generator_input(generator, BakedMap::Curvature); - let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); - self.curvature_detail(&detail, sizes, curvature, micro) + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(&detail, sizes, curvature) } - GeneratorKind::AmbientOcclusion => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + GeneratorKind::AmbientOcclusion => self.occlusion_input(generator, maps).unwrap_or(1.0), GeneratorKind::Position => { let position = self.position_input(generator); sections::axes_signal(position, §ion.axes) @@ -3444,14 +3485,14 @@ impl<'a, 'b> Texel<'a, 'b> { } /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert - fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let curvature = self.generator_input(generator, BakedMap::Curvature).map_or(0.0, |curvature| curvature - 0.5); + fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, maps: &GeneratorMaps) -> f32 { + let curvature = self.curvature_input(generator, maps).map_or(0.0, |curvature| curvature - 0.5); // Blurred levels are copies of the mesh map, so a replaced curvature input is read at its own size only - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); - let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0); + let occlusion = self.occlusion_input(generator, maps).unwrap_or(1.0); let grunge = if wear.custom_grunge { // An image not loaded yet reads mid gray, which leaves the wear as without grunge let gray = self.slot_color(generator, generator.grunge.as_ref(), &wear::custom_grunge_placement(wear)).map_or(0.5, lum); @@ -3485,8 +3526,8 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let ramp = self.generator_ramp(generator, curvature_sizes); + fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + let ramp = self.generator_ramp(generator, maps); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); let textured = match (generator.texture_in_use(), self.generator_texture(generator)) { (Some(texture), Some(gray)) => texture_layer::blended_over(texture, adjusted, gray), @@ -3529,6 +3570,22 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// The generator's curvature input at this texel with what its micro details add + fn curvature_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let curvature = self.generator_input(generator, BakedMap::Curvature)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_curvature.as_ref().and_then(|micro| micro.term.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(curvature + micro.unwrap_or(0.0)) + } + + /// The generator's occlusion input at this texel, darkened by its micro details + fn occlusion_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_occlusion.as_ref().and_then(|micro| micro.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(occlusion * micro.unwrap_or(1.0)) + } + /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { match generator.inputs.get(&map) { @@ -3547,19 +3604,15 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { - let combine = |edges: f32, cavities: f32| { - let edges = 1.0 - (1.0 - edges) * (1.0 - micro.max(0.0)); - let cavities = 1.0 - (1.0 - cavities) * (1.0 + micro.min(0.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), - } + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { + 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 baked curvature, only painted micro height supplies edges or cavities + // Without curvature to read the texel is flat: no edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; @@ -3649,7 +3702,7 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, fill) - value) * opacity * cover; } EffectKind::Generator(generator) => { - let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + let generated = self.generator(generator, &effect.maps); value += (blend1(effect.blend, value, generated) - value) * opacity; } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, @@ -5159,7 +5212,8 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti mod tests { use super::*; use texturecraft_core::{ - ChannelBlend, CompareOp, Effect, Layer, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, TextureSet, + ChannelBlend, CompareOp, Effect, Layer, MicroDetails, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, + TextureSet, }; use texturecraft_geom::primitives; @@ -6999,85 +7053,46 @@ soft {soft:?}" } #[test] - fn generator_micro_detail_follows_the_anchor_height() { + fn a_micro_height_read_from_an_anchor_follows_its_raised_region() { let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; + let disc = (0..64 * 64) + .map(|index| { + let (x, y) = ((index % 64) as f32 - 31.5, (index / 64) as f32 - 31.5); + if x * x + y * y < 100.0 { [1.0; 4] } else { [0.0, 0.0, 0.0, 1.0] } + }) + .collect(); + let images: ImageStore = [("disc".to_string(), Arc::new(ImageRes::new(64, 64, disc, false)))].into(); let low = fixture.project.alloc_id(); let mut fill = Fill::default(); - fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + fill.sources.insert(Channel::Height, Source::image("disc")); fixture.project.insert_layer(0, Layer::new(low, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); let anchor = content_fx(&mut fixture, low, EffectKind::Anchor); let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); - let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::Curvature) }; - let with = |fixture: &mut Fixture, generator: &Generator| { + let colors = |fixture: &mut Fixture, generator: &Generator| -> Vec { let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(generator.clone()))); fixture.project.layer_mut(top).unwrap().mask = Some(mask); - run(fixture, None).value(Channel::BaseColor, 5, 5)[0] + let composite = run_with_images(fixture, None, &images); + (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() }; + let largest_change = |a: &[f32], b: &[f32]| a.iter().zip(b).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); - // No curvature map: flat mid gray, so the mask is 0.5 and the base color 0.75 - let flat = with(&mut fixture, &generator); - assert!((flat - 0.75).abs() < 0.02, "{flat}"); + // Curvature on its section controls, then on the earlier model a project saved before Micro Details keeps + let section = Generator::new(GeneratorKind::Curvature); + let earlier = Generator { section: None, level: 0.5, softness: 0.5, noise_amount: 0.0, ..section.clone() }; + for plain in [section, earlier] { + let off = colors(&mut fixture, &plain); + let read = Generator { micro: MicroDetails::of_anchor(GeneratorKind::Curvature, anchor, 1.0).map(Box::new), ..plain.clone() }; - // Raised height reads as an edge - generator.micro = Some(MicroDetail { anchor, amount: 1.0 }); - assert!(with(&mut fixture, &generator) > flat + 0.2); + let raised = colors(&mut fixture, &read); + assert!(largest_change(&raised, &off) > 0.05, "the raised disc's rim reads as curvature"); - // Recessed height reads as a cavity; dirt gathers there - if let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(low).unwrap().kind { - fill.sources.insert(Channel::Height, Source::Uniform([-0.5; 3])); - } - assert!(with(&mut fixture, &generator) < flat - 0.2); - let dirt = - Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, micro: Some(MicroDetail { anchor, amount: 1.0 }), ..Generator::new(GeneratorKind::Dirt) }; - let plain = Generator { micro: None, ..dirt.clone() }; - assert!(with(&mut fixture, &dirt) > with(&mut fixture, &plain) + 0.2); - - // A hostile amount does nothing - generator.micro = Some(MicroDetail { anchor, amount: f32::NAN }); - assert!((with(&mut fixture, &generator) - flat).abs() < 0.02); - } - - #[test] - fn curvature_modes_classify_raised_and_recessed_micro_height() { - let mut fixture = fixture(); - fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; - let lower = fixture.project.alloc_id(); - let mut fill = Fill::default(); - fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); - fixture.project.insert_layer(0, Layer::new(lower, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); - let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); - let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); - - for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { - for (height, mode, responds) in [ - (0.5, CurvatureMode::Edges, true), - (-0.5, CurvatureMode::Edges, false), - (0.5, CurvatureMode::Cavities, false), - (-0.5, CurvatureMode::Cavities, true), - (0.5, CurvatureMode::Both, true), - (-0.5, CurvatureMode::Both, true), - ] { - if let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind { - fill.sources.insert(Channel::Height, Source::Uniform([height; 3])); - } - let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; - let generator = Generator { - level: 0.5, - softness: 0.5, - noise_amount: 0.0, - detail: Some(detail), - micro: Some(MicroDetail { anchor, amount: 1.0 }), - ..Generator::new(kind) - }; - let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); - fixture.project.layer_mut(top).unwrap().mask = Some(mask); - - let value = run(&fixture, None).value(Channel::BaseColor, 5, 5)[0]; - let expected = if responds { 0.75 } else { 0.5 }; - assert!((value - expected).abs() < 0.02, "{kind:?} {mode:?} height {height}: {value}"); + let mut emptied = read.clone(); + if let Some(micro) = emptied.micro.as_mut() { + micro.height_source = None; } + assert_eq!(colors(&mut fixture, &emptied), off, "without an anchor the micro details change nothing"); } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs new file mode 100644 index 00000000..6bc18477 --- /dev/null +++ b/crates/compose/src/generator_maps.rs @@ -0,0 +1,34 @@ +//! The precomputed maps one generator reads: its curvature detail sizes and its micro details + +use std::sync::Arc; + +use texturecraft_core::{BakedMap, Generator, MicroDetails}; + +use crate::curvature_sizes::CurvatureSizes; +use crate::eval::Inputs; +use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; + +/// What a generator reads beyond its texel: built once per map and settings, shared by every tile +#[derive(Clone, Default)] +pub(crate) struct GeneratorMaps { + /// The curvature detail sizes it reads (of its micro curvature when it has some) + pub sizes: Option>, + /// The curvature its micro details add + pub micro_curvature: Option>, + /// What its micro details multiply its occlusion by + pub micro_occlusion: Option>, +} + +impl GeneratorMaps { + /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size) + pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps { + let micro = generator.micro_in_use(); + let micro_curvature = micro.filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); + let micro_occlusion = micro.filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro)); + let sizes = match µ_curvature { + Some(micro) => CurvatureSizes::of_map(inp, µ.curvature, needed), + None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), + }; + GeneratorMaps { sizes, micro_curvature, micro_occlusion } + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 3c921ff9..b3f52141 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -25,9 +25,11 @@ mod fill_depth; mod fill_place; pub mod frame_placement; mod fur_lock; +mod generator_maps; mod held_fields; mod image_identity; mod mask_gray; +mod micro_details; pub mod mip_level; mod organic; pub mod pattern; diff --git a/crates/compose/src/micro_details.rs b/crates/compose/src/micro_details.rs new file mode 100644 index 00000000..d81fabf9 --- /dev/null +++ b/crates/compose/src/micro_details.rs @@ -0,0 +1,626 @@ +//! A generator's micro details: the curvature and occlusion its micro height (an image or an anchor point's height) and normal image add to its mesh maps, built once per map, image and settings + +use std::sync::{Arc, Mutex, Weak}; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, BlockScales, GeneratorKind, LayerId, MicroCurvatureType, MicroDetails, NormalFormat, Source}; + +use crate::below::StackKey; +use crate::eval::Inputs; +use crate::store::ImageRes; + +/// The resolution of a UV tile the reference's micro details were measured at: derivatives and radii are per texel at this size +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// How steeply the micro height tilts the normal it is turned into, per unit of Height Details Intensity (fitted) +const HEIGHT_NORMAL_STRENGTH: f32 = 5.9; + +/// Blur sizes of the Smooth type, in texels at 2K: the height against each of these blurred copies +const SMOOTH_SIGMAS: [f32; 7] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]; + +/// Below this sigma a blur is an explicit kernel; wider ones are three box passes +const BOX_BLUR_MIN_SIGMA: f32 = 2.0; + +/// Directions the occlusion looks along +const OCCLUSION_DIRECTIONS: usize = 16; + +/// Most steps the occlusion takes along each direction; longer radii step further each time +const OCCLUSION_STEPS: usize = 16; + +/// The occlusion radius in texels at 1K for AO Radius 1, and its exponent (fitted: radius 0.3 reaches about 6 texels, 1 about 48) +const OCCLUSION_RADIUS_TEXELS_1K: f32 = 47.675; +const OCCLUSION_RADIUS_POWER: f32 = 1.663; + +/// Shorter radii at 1K occlude nothing: the reference is unchanged at AO Radius 0.1 (about 1 texel) and occludes from 0.2 (about 3) +const MIN_OCCLUSION_RADIUS_TEXELS_1K: f32 = 2.0; + +/// How steep the micro height reads for occlusion per texel at 1K at AO Depth 1, and its exponent (fitted) +const OCCLUSION_DEPTH_SCALE_1K: f32 = 1473.8; +const OCCLUSION_DEPTH_POWER: f32 = 1.0654; + +/// How dark a fully occluding horizon makes the occlusion (fitted) +const OCCLUSION_STRENGTH: f32 = 0.3232; + +/// Cached micro maps; each entry is small next to the curvature sizes it feeds +const CACHE_ENTRIES: usize = 8; + +/// A map in a mesh map's layout: `size` texels, each UV tile one block +pub struct LayoutMap { + data: Vec, + size: (u32, u32), +} + +impl LayoutMap { + /// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout) + pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option { + let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = scales.bake_uv(uv, working_size)?; + let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1)); + let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1)); + self.data.get((row * self.size.0 + column) as usize).copied() + } +} + +/// The curvature a generator's micro details add +pub struct MicroCurvature { + /// What they add to the curvature input + pub term: LayoutMap, + /// The baked curvature with the term added, which the detail sizes blur + pub curvature: Arc>, +} + +/// An anchor point's height over the whole texture set, in the working atlas's layout +pub struct AnchorHeights { + data: Vec, + working_size: (u32, u32), + scales: BlockScales, +} + +impl AnchorHeights { + pub fn new(data: Vec, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights { + AnchorHeights { data, working_size, scales } + } + + /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) + fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { + let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; + let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 }; + + let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1)); + let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1)); + self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0) + } +} + +/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key +struct AnchorEntry { + baked: Weak>, + texture_set: usize, + anchor: LayerId, + stack: StackKey, + heights: Arc, +} + +/// The anchor heights prepared last, one per mesh maps, texture set and anchor +static ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); + +/// The mesh maps (by address) and texture sets whose anchor heights are being built: the build composites the stack, which prepares them again +static BUILDING_ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); + +/// A mesh map that tells one session's baked maps from another's (None without curvature or occlusion) +fn baked_identity(inp: &Inputs) -> Option>> { + [BakedMap::Curvature, BakedMap::AmbientOcclusion].iter().find_map(|map| inp.baked.maps.get(map)).map(Arc::downgrade) +} + +/// Keep anchor `anchor`'s heights for the micro details reading it, building them with `build` unless `stack` is the stack they were built for +pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: StackKey, build: impl FnOnce() -> AnchorHeights) { + let Some(baked) = baked_identity(inp) else { return }; + let matches = |entry: &AnchorEntry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor; + { + let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|entry| entry.baked.strong_count() > 0); + if entries.iter().any(|entry| matches(entry) && entry.stack == stack) { + return; + } + } + + // Built outside the lock: the build composites the stack in parallel, and leaves the anchors it meets unprepared + let building = (baked.as_ptr() as usize, inp.ts); + { + let mut active = BUILDING_ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if active.contains(&building) { + return; + } + active.push(building); + } + let heights = Arc::new(build()); + BUILDING_ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).retain(|active| *active != building); + let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|entry| !matches(entry)); + entries.push(AnchorEntry { baked, texture_set: inp.ts, anchor, stack, heights }); + let excess = entries.len().saturating_sub(CACHE_ENTRIES); + entries.drain(..excess); +} + +/// The heights prepared for anchor `anchor` (None before they are) +fn anchor_heights(inp: &Inputs, anchor: LayerId) -> Option> { + let baked = baked_identity(inp)?; + let entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.iter().find(|entry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor).map(|entry| entry.heights.clone()) +} + +/// What a micro details slot reads +#[derive(Clone)] +enum Slot { + Uniform([f32; 3]), + Image { + image: Arc, + flip_green: bool, + }, + /// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map + Anchor { + heights: Arc, + origin: (u32, u32), + layout: (u32, u32), + }, +} + +impl Slot { + /// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read) + fn of(inp: &Inputs, source: Option<&Source>) -> Slot { + match source { + Some(Source::Uniform(value)) => Slot::Uniform(*value), + Some(Source::Image { name, normal_format }) => match inp.images.get(name) { + Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX }, + None => Slot::Uniform([0.0; 3]), + }, + Some(Source::Anchor { anchor, .. }) => match anchor_heights(inp, *anchor) { + Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) }, + None => Slot::Uniform([0.0; 3]), + }, + _ => Slot::Uniform([0.0; 3]), + } + } + + /// Whether every UV tile block reads the same (an image or a value repeats in each) + fn same_in_every_block(&self) -> bool { + !matches!(self, Slot::Anchor { .. }) + } + + /// The slot read in the block at `origin` of a `layout` sized mesh map + fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot { + match self { + Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout }, + other => other.clone(), + } + } + + fn key(&self) -> SlotKey { + match self { + Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)), + Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green), + Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)), + } + } + + /// The slot's color at `uv`, in the file's encoding + fn color(&self, uv: [f32; 2]) -> [f32; 3] { + match self { + Slot::Uniform(value) => *value, + Slot::Image { image, .. } => { + let [red, green, blue, _] = image.sample(uv[0], uv[1]); + [red, green, blue] + } + Slot::Anchor { .. } => [0.0; 3], + } + } + + /// The slot read as a height (its gray) over a `size` block + fn heights(&self, size: (u32, u32)) -> Vec { + match self { + Slot::Anchor { heights, origin, layout } => { + (0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect() + } + _ => block_uvs(size).map(|uv| self.color(uv).iter().sum::() / 3.0).collect(), + } + } + + /// The slot read as a normal over a `size` block: its X and Y, OpenGL convention + fn normals(&self, size: (u32, u32)) -> (Vec, Vec) { + let flip_green = matches!(self, Slot::Image { flip_green: true, .. }); + block_uvs(size) + .map(|uv| { + let [red, green, _] = self.color(uv); + let y = green * 2.0 - 1.0; + (red * 2.0 - 1.0, if flip_green { -y } else { y }) + }) + .unzip() + } +} + +/// The UV of each texel's center in a `size` block, row by row +fn block_uvs((width, height): (u32, u32)) -> impl Iterator { + (0..height).flat_map(move |y| (0..width).map(move |x| [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32])) +} + +/// A slot as a cache key: an image by identity, a value by its bits +#[derive(Clone)] +enum SlotKey { + Uniform([u32; 3]), + Image(Weak, bool), + Anchor(Weak), +} + +impl PartialEq for SlotKey { + fn eq(&self, other: &SlotKey) -> bool { + match (self, other) { + (SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b, + (SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip, + (SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b), + _ => false, + } + } +} + +/// What a micro map was built from: the mesh map giving its layout, its slots, its settings' bits and its UV tile block +#[derive(Clone)] +struct Key { + map: Weak>, + height: Option, + normal: Option, + settings: Vec, + block: (u32, u32), +} + +impl PartialEq for Key { + fn eq(&self, other: &Key) -> bool { + self.map.strong_count() > 0 + && self.map.ptr_eq(&other.map) + && self.height == other.height + && self.normal == other.normal + && self.settings == other.settings + && self.block == other.block + } +} + +/// Built maps by what they were built from, most recently used last +struct Cache { + entries: Mutex)>>, +} + +impl Cache { + const fn new() -> Cache { + Cache { entries: Mutex::new(Vec::new()) } + } + + /// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work) + fn get_or_build(&self, key: Key, build: impl FnOnce() -> T) -> Arc { + let found = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.map.strong_count() > 0); + entries.iter().position(|(cached, _)| *cached == key).map(|index| { + let entry = entries.remove(index); + let built = entry.1.clone(); + entries.push(entry); + built + }) + }; + if let Some(built) = found { + return built; + } + + let built = Arc::new(build()); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, built.clone())); + let excess = entries.len().saturating_sub(CACHE_ENTRIES); + entries.drain(..excess); + built + } +} + +static CURVATURE_CACHE: Cache = Cache::new(); +static OCCLUSION_CACHE: Cache = Cache::new(); + +/// A baked map, its size and the size of one UV tile's block in it +type MapLayout = (Arc>, (u32, u32), (u32, u32)); + +/// The baked `map`'s layout (None when it isn't baked) +fn layout(inp: &Inputs, map: BakedMap) -> Option { + let data = inp.baked.maps.get(&map)?.clone(); + let size = (inp.baked.resolution, inp.baked.height(map)); + if size.0 == 0 || size.1 == 0 { + return None; + } + + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); + Some((data, size, (block.0.max(1).min(size.0), block.1.max(1).min(size.1)))) +} + +/// `per_block` run on each UV tile block of a `size` map, its results placed into one map +fn by_blocks(size: (u32, u32), block: (u32, u32), same_in_every_block: bool, per_block: impl Fn((u32, u32), (u32, u32)) -> Vec + Sync) -> Vec { + let blocks: Vec<(u32, u32)> = (0..size.1).step_by(block.1 as usize).flat_map(|y| (0..size.0).step_by(block.0 as usize).map(move |x| (x, y))).collect(); + + // Every block is a whole UV tile, so one computation serves them all unless the slots differ per block; a clipped last block differs too + let full = same_in_every_block.then(|| per_block((0, 0), block)); + let mut data = vec![0.0; (size.0 * size.1) as usize]; + for (left, top) in blocks { + let clipped = (block.0.min(size.0 - left), block.1.min(size.1 - top)); + let own = if clipped == block && full.is_some() { None } else { Some(per_block((left, top), clipped)) }; + let Some(values) = own.as_deref().or(full.as_deref()) else { continue }; + for row in 0..clipped.1 { + let source = (row * clipped.0) as usize; + let target = ((top + row) * size.0 + left) as usize; + if let (Some(target), Some(source)) = (data.get_mut(target..target + clipped.0 as usize), values.get(source..source + clipped.0 as usize)) { + target.copy_from_slice(source); + } + } + } + data +} + +impl MicroCurvature { + /// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map) + pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails) -> Option> { + let (curvature, size, block) = layout(inp, BakedMap::Curvature)?; + let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref())); + let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref())); + let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32]; + let key = Key { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, block }; + + Some(CURVATURE_CACHE.get_or_build(key, || { + let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block); + let term = by_blocks(size, block, same_in_every_block, |origin, block| { + let height = height.as_ref().map(|height| height.in_block(origin, size)); + let normal = normal.as_ref().map(|normal| normal.in_block(origin, size)); + curvature_term(micro, height.as_ref(), normal.as_ref(), block) + }); + let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect(); + MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) } + })) + } +} + +/// What the occlusion input is multiplied by: the micro height's occlusion in the baked AO map's layout (None without a baked AO map or a micro height) +pub fn micro_occlusion(inp: &Inputs, micro: &MicroDetails) -> Option> { + let (occlusion, size, block) = layout(inp, BakedMap::AmbientOcclusion)?; + let height = Slot::of(inp, micro.height.then_some(micro.height_source.as_ref())?); + let settings = vec![micro.ao_radius.to_bits(), micro.ao_depth.to_bits()]; + let key = Key { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, block }; + + Some(OCCLUSION_CACHE.get_or_build(key, || { + let data = by_blocks(size, block, height.same_in_every_block(), |origin, block| occlusion_factor(micro, &height.in_block(origin, size), block)); + LayoutMap { data, size } + })) +} + +/// The fitted constants of a curvature type: what it adds everywhere, and its gain on the height and on the normal +fn type_constants(curvature_type: MicroCurvatureType) -> (f32, f32, f32) { + match curvature_type { + MicroCurvatureType::Standard => (0.00876, 12.36, 9.49), + MicroCurvatureType::Sobel => (0.0, 5.72, 4.46), + MicroCurvatureType::Smooth => (-0.00332, 0.969, 34.2), + } +} + +/// The curvature the micro details add over one `size` UV tile block +fn curvature_term(micro: &MicroDetails, height: Option<&Slot>, normal: Option<&Slot>, size: (u32, u32)) -> Vec { + let (offset, height_gain, normal_gain) = type_constants(micro.curvature_type); + let texel_scale = size.0 as f32 / REFERENCE_TILE_TEXELS; + let mut term = vec![offset; (size.0 * size.1) as usize]; + + if let Some(height) = height { + let heights = height.heights(size); + let detail = match micro.curvature_type { + MicroCurvatureType::Smooth => smooth_detail(&heights, size, texel_scale).into_iter().map(|detail| detail * micro.height_intensity).collect(), + MicroCurvatureType::Standard | MicroCurvatureType::Sobel => { + // The height turned into a normal, then that normal's divergence + let strength = HEIGHT_NORMAL_STRENGTH * micro.height_intensity * texel_scale; + let (slope_x, slope_y) = sobel(&heights, size); + let tilted = |slope_x: f32, slope_y: f32| { + let (x, y) = (-strength * slope_x, -strength * slope_y); + let length = (x * x + y * y + 1.0).sqrt(); + (x / length, y / length) + }; + let (normal_x, normal_y): (Vec, Vec) = slope_x.par_iter().zip(slope_y.par_iter()).map(|(x, y)| tilted(*x, *y)).unzip(); + divergence(&normal_x, &normal_y, size, texel_scale) + } + }; + add_scaled(&mut term, &detail, micro.curvature_intensity * height_gain); + } + if let Some(normal) = normal { + let (normal_x, normal_y) = normal.normals(size); + add_scaled(&mut term, &divergence(&normal_x, &normal_y, size, texel_scale), micro.curvature_intensity * normal_gain); + } + term +} + +fn add_scaled(target: &mut [f32], values: &[f32], gain: f32) { + target.par_iter_mut().zip(values.par_iter()).for_each(|(target, value)| *target += value * gain); +} + +/// The Smooth type's detail: the height above its blurred copies, averaged over [`SMOOTH_SIGMAS`] +fn smooth_detail(heights: &[f32], size: (u32, u32), texel_scale: f32) -> Vec { + let mut detail = vec![0.0; heights.len()]; + for sigma in SMOOTH_SIGMAS { + let blurred = gaussian_wrapped(heights, size, sigma * texel_scale); + detail.par_iter_mut().zip(heights.par_iter().zip(blurred.par_iter())).for_each(|(detail, (height, blurred))| *detail += height - blurred); + } + let count = SMOOTH_SIGMAS.len() as f32; + detail.par_iter_mut().for_each(|detail| *detail /= count); + detail +} + +/// The divergence of the `x` and `y` fields, per texel at 2K +fn divergence(x: &[f32], y: &[f32], size: (u32, u32), texel_scale: f32) -> Vec { + let (dx, _) = sobel(x, size); + let (_, dy) = sobel(y, size); + dx.par_iter().zip(dy.par_iter()).map(|(dx, dy)| (dx + dy) * texel_scale).collect() +} + +/// The slope of `values` along X and Y per texel (3×3 Sobel), wrapping around the block like a tiling image +fn sobel(values: &[f32], (width, height): (u32, u32)) -> (Vec, Vec) { + let (width, height) = (i64::from(width.max(1)), i64::from(height.max(1))); + let at = |x: i64, y: i64| values.get((y.rem_euclid(height) * width + x.rem_euclid(width)) as usize).copied().unwrap_or(0.0); + (0..width * height) + .into_par_iter() + .map(|texel| { + let (x, y) = (texel % width, texel / width); + let column = |dx: i64| at(x + dx, y - 1) + 2.0 * at(x + dx, y) + at(x + dx, y + 1); + let row = |dy: i64| at(x - 1, y + dy) + 2.0 * at(x, y + dy) + at(x + 1, y + dy); + ((column(1) - column(-1)) / 8.0, (row(1) - row(-1)) / 8.0) + }) + .unzip() +} + +/// `values` blurred to `sigma` texels, wrapping around the block like a tiling image +fn gaussian_wrapped(values: &[f32], (width, height): (u32, u32), sigma: f32) -> Vec { + let rows = blur_lines(values, width as usize, sigma); + let columns = blur_lines(&transposed(&rows, width as usize, height as usize), height as usize, sigma); + transposed(&columns, height as usize, width as usize) +} + +/// Each `length`-long line of `values` blurred to `sigma`, wrapping around +fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { + let length = length.max(1); + let mut out = vec![0.0; values.len()]; + out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| { + if sigma < BOX_BLUR_MIN_SIGMA { + kernel_blur(line, out, sigma); + } else { + // Three box passes of radius r spread a value with variance r(r + 1) + let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize; + let mut current = line.to_vec(); + for _ in 0..3 { + box_blur(¤t, out, radius); + current.copy_from_slice(out); + } + } + }); + out +} + +/// `line` blurred into `out` by a sampled gaussian of `sigma`, wrapping around +fn kernel_blur(line: &[f32], out: &mut [f32], sigma: f32) { + let reach = (3.0 * sigma).ceil().max(1.0) as i64; + let weights: Vec = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect(); + let total: f32 = weights.iter().sum(); + let length = line.len().max(1) as i64; + for (index, value) in out.iter_mut().enumerate() { + let sum: f32 = (-reach..=reach) + .zip(&weights) + .map(|(offset, weight)| line.get((index as i64 + offset).rem_euclid(length) as usize).copied().unwrap_or(0.0) * weight) + .sum(); + *value = sum / total; + } +} + +/// `line` averaged over `radius` texels each side into `out`, wrapping around +fn box_blur(line: &[f32], out: &mut [f32], radius: usize) { + let length = line.len().max(1) as i64; + let window = (2 * radius + 1) as f32; + let at = |index: i64| line.get(index.rem_euclid(length) as usize).copied().unwrap_or(0.0); + let mut sum: f32 = (-(radius as i64)..=radius as i64).map(at).sum(); + for (index, value) in out.iter_mut().enumerate() { + *value = sum / window; + let index = index as i64; + sum += at(index + radius as i64 + 1) - at(index - radius as i64); + } +} + +fn transposed(values: &[f32], width: usize, height: usize) -> Vec { + let height = height.max(1); + (0..width * height).into_par_iter().map(|texel| values.get((texel % height) * width + texel / height).copied().unwrap_or(0.0)).collect() +} + +/// What the occlusion is multiplied by over one `size` UV tile block: the horizon the micro height raises above its slope, looked for in [`OCCLUSION_DIRECTIONS`] +fn occlusion_factor(micro: &MicroDetails, height: &Slot, size: (u32, u32)) -> Vec { + let tile_scale = size.0 as f32 / (REFERENCE_TILE_TEXELS / 2.0); + let radius_1k = OCCLUSION_RADIUS_TEXELS_1K * micro.ao_radius.powf(OCCLUSION_RADIUS_POWER); + let radius = (radius_1k * tile_scale).round() as usize; + let count = (size.0 * size.1) as usize; + if radius_1k < MIN_OCCLUSION_RADIUS_TEXELS_1K || radius < 1 { + return vec![1.0; count]; + } + + let depth = OCCLUSION_DEPTH_SCALE_1K * micro.ao_depth.powf(OCCLUSION_DEPTH_POWER) * tile_scale; + let heights = height.heights(size); + let (width, rows) = (i64::from(size.0.max(1)), i64::from(size.1.max(1))); + let at = |x: i64, y: i64| heights.get((y.rem_euclid(rows) * width + x.rem_euclid(width)) as usize).copied().unwrap_or(0.0); + let directions: Vec<(f32, f32)> = (0..OCCLUSION_DIRECTIONS) + .map(|index| std::f32::consts::TAU * index as f32 / OCCLUSION_DIRECTIONS as f32) + .map(|angle| (angle.cos(), angle.sin())) + .collect(); + // Up to OCCLUSION_STEPS distances spread over the radius + let steps: Vec = if radius <= OCCLUSION_STEPS { + (1..=radius).map(|step| step as f32).collect() + } else { + (1..=OCCLUSION_STEPS).map(|step| 1.0 + (radius - 1) as f32 * (step - 1) as f32 / (OCCLUSION_STEPS - 1) as f32).collect() + }; + let sine = |slope: f32| slope / (1.0 + slope * slope).sqrt(); + + (0..width * rows) + .into_par_iter() + .map(|texel| { + let (x, y) = (texel % width, texel / width); + let here = at(x, y); + let gradient = ((at(x + 1, y) - at(x - 1, y)) / 2.0, (at(x, y + 1) - at(x, y - 1)) / 2.0); + let occluded: f32 = directions + .iter() + .map(|(dx, dy)| { + let horizon = steps + .iter() + .map(|distance| (at(x + (dx * distance).round() as i64, y + (dy * distance).round() as i64) - here) / distance) + .fold(f32::NEG_INFINITY, f32::max); + let tangent = gradient.0 * dx + gradient.1 * dy; + (sine(horizon * depth) - sine(tangent * depth)).max(0.0) + }) + .sum(); + 1.0 - OCCLUSION_STRENGTH * occluded / OCCLUSION_DIRECTIONS as f32 + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sobel_reads_a_ramp_as_its_slope() { + let size = (8, 8); + let ramp: Vec = (0..64).map(|texel| (texel % 8) as f32 * 0.1).collect(); + let (x, y) = sobel(&ramp, size); + assert!((x[3 * 8 + 3] - 0.1).abs() < 1e-5); + assert!(y[3 * 8 + 3].abs() < 1e-5); + } + + #[test] + fn wrapped_blurs_keep_the_mean() { + let size = (32, 16); + let values: Vec = (0..32 * 16).map(|texel| ((texel * 7919) % 13) as f32).collect(); + let mean = values.iter().sum::() / values.len() as f32; + for sigma in [0.5, 1.0, 4.0] { + let blurred = gaussian_wrapped(&values, size, sigma); + assert!((blurred.iter().sum::() / blurred.len() as f32 - mean).abs() < 1e-3, "sigma {sigma}"); + } + } + + #[test] + fn a_flat_height_adds_only_the_types_offset() { + let mut micro = MicroDetails::defaults(GeneratorKind::Curvature).unwrap(); + let flat = Slot::Uniform([0.4; 3]); + for curvature_type in MicroCurvatureType::ALL { + micro.curvature_type = curvature_type; + let term = curvature_term(µ, Some(&flat), Some(&Slot::Uniform([0.5, 0.5, 1.0])), (16, 16)); + assert!(term.iter().all(|value| (value - type_constants(curvature_type).0).abs() < 1e-6), "{curvature_type:?}"); + } + } + + #[test] + fn a_flat_height_occludes_nothing() { + let micro = MicroDetails::defaults(GeneratorKind::AmbientOcclusion).unwrap(); + let factor = occlusion_factor(µ, &Slot::Uniform([0.7; 3]), (64, 64)); + assert!(factor.iter().all(|value| (value - 1.0).abs() < 1e-6)); + } +} diff --git a/crates/compose/tests/generator_micro_details.rs b/crates/compose/tests/generator_micro_details.rs new file mode 100644 index 00000000..62254619 --- /dev/null +++ b/crates/compose/tests/generator_micro_details.rs @@ -0,0 +1,211 @@ +//! A generator's micro details on a flat plane: a height bump reads as an edge on Curvature and occludes its foot on Ambient Occlusion; off or flat, they change nothing + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, + MicroCurvatureType, MicroDetails, Project, Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// Size of the bump image, and the bump's spread in its texels +const BUMP_SIZE: u32 = 64; +const BUMP_SIGMA: f32 = 4.0; + +/// How steep the bump's normal image is drawn +const NORMAL_STRENGTH: f32 = 8.0; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, + images: ImageStore, +} + +/// The bump's height at texel (`x`, `y`) of the bump image: 1 at its center, 0 far away +fn bump_height(x: f32, y: f32) -> f32 { + let center = BUMP_SIZE as f32 / 2.0; + let distance_squared = (x - center).powi(2) + (y - center).powi(2); + (-distance_squared / (2.0 * BUMP_SIGMA * BUMP_SIGMA)).exp() +} + +/// A plane with a white fill layer, flat curvature and no occlusion, and the images `bump` (a height), `bump_normal` and `flat` +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let texels = (RES * RES) as usize; + let maps = [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; texels])), (BakedMap::Curvature, Arc::new(vec![0.5; texels]))]; + let baked = BakedMaps { resolution: RES, maps: maps.into() }; + + let texel_xy = |index: u32| ((index % BUMP_SIZE) as f32 + 0.5, (index / BUMP_SIZE) as f32 + 0.5); + let height = |index: u32| { + let (x, y) = texel_xy(index); + let height = bump_height(x, y); + [height, height, height, 1.0] + }; + let normal = |index: u32| { + let (x, y) = texel_xy(index); + let slope = ((bump_height(x + 0.5, y) - bump_height(x - 0.5, y)), (bump_height(x, y + 0.5) - bump_height(x, y - 0.5))); + let (normal_x, normal_y) = (-NORMAL_STRENGTH * slope.0, -NORMAL_STRENGTH * slope.1); + let length = (normal_x * normal_x + normal_y * normal_y + 1.0).sqrt(); + [normal_x / length * 0.5 + 0.5, normal_y / length * 0.5 + 0.5, 0.5 / length + 0.5, 1.0] + }; + let image = |texel: &dyn Fn(u32) -> [f32; 4]| Arc::new(ImageRes::new(BUMP_SIZE, BUMP_SIZE, (0..BUMP_SIZE * BUMP_SIZE).map(texel).collect(), false)); + let flat = Arc::new(ImageRes::new(4, 4, vec![[0.3, 0.3, 0.3, 1.0]; 16], false)); + let images = [("bump".to_string(), image(&height)), ("bump_normal".to_string(), image(&normal)), ("flat".to_string(), flat)].into(); + Fixture { project, mesh, gbuf, layer, baked, images } +} + +/// Every texel, row by row +fn texels() -> Vec<(u32, u32)> { + (0..RES * RES).map(|index| (index % RES, index / RES)).collect() +} + +/// The texel under the bump's center +fn bump_center() -> usize { + (RES / 2 * RES + RES / 2) as usize +} + +/// The mask of `generator` alone over black at every texel +fn mask(fixture: &mut Fixture, generator: Generator) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, &texels()).unwrap() +} + +/// `kind` with micro details reading `height` (and `normal` when given), edited by `edit` +fn with_micro(kind: GeneratorKind, height: Option<&str>, normal: Option<&str>, edit: impl Fn(&mut MicroDetails)) -> Generator { + let mut micro = MicroDetails { + enabled: true, + height: height.is_some(), + normal: normal.is_some(), + height_source: height.map(Source::image), + normal_source: normal.map(Source::image), + ..MicroDetails::defaults(kind).unwrap() + }; + edit(&mut micro); + let mut generator = Generator::new(kind); + if generator.wear.is_none() && kind != GeneratorKind::FiberGlassEdgeWear && generator.section.is_none() { + generator.wear = texturecraft_core::WearParameters::defaults(kind); + } + generator.micro = Some(Box::new(micro)); + generator +} + +/// Curvature in Raw mode, so a lift and a drop both show +fn raw_curvature(mut generator: Generator) -> Generator { + generator.detail = Some(CurvatureDetail { mode: CurvatureMode::Raw, ..CurvatureDetail::default() }); + generator +} + +fn strong(micro: &mut MicroDetails) { + (micro.curvature_intensity, micro.height_intensity) = (5.0, 10.0); +} + +fn mean(values: &[f32]) -> f32 { + values.iter().sum::() / values.len() as f32 +} + +#[test] +fn micro_details_switched_off_change_nothing() { + let mut fixture = fixture(); + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::FiberGlassEdgeWear] { + let plain = mask(&mut fixture, with_micro(kind, None, None, |_| {})); + // Curvature and Ambient Occlusion switch them off whole, the wear kinds by both their images + let switch = MicroDetails::has_switch(kind); + let off = |micro: &mut MicroDetails| (micro.enabled, micro.height, micro.normal) = (!switch, switch, switch); + + let switched_off = mask(&mut fixture, with_micro(kind, Some("bump"), Some("bump_normal"), off)); + assert_eq!(plain, switched_off, "{kind:?}"); + } +} + +#[test] +fn a_micro_height_bump_reads_as_an_edge_on_curvature() { + let mut fixture = fixture(); + let off = mask(&mut fixture, Generator::new(GeneratorKind::Curvature)); + + let on = mask(&mut fixture, with_micro(GeneratorKind::Curvature, Some("bump"), None, strong)); + assert!(on[bump_center()] > off[bump_center()] + 0.01, "the bump's top is convex: {} vs {}", on[bump_center()], off[bump_center()]); + assert!((on[0] - off[0]).abs() < 1e-4, "far from the bump the surface stays flat"); +} + +#[test] +fn a_micro_normal_bump_reads_as_an_edge_on_curvature() { + let mut fixture = fixture(); + let off = mask(&mut fixture, Generator::new(GeneratorKind::Curvature)); + + let on = mask(&mut fixture, with_micro(GeneratorKind::Curvature, None, Some("bump_normal"), strong)); + assert!(on[bump_center()] > off[bump_center()] + 0.01, "{} vs {}", on[bump_center()], off[bump_center()]); +} + +#[test] +fn standard_lifts_a_flat_micro_height_and_smooth_lowers_it() { + let mut fixture = fixture(); + let typed = |curvature_type| move |micro: &mut MicroDetails| micro.curvature_type = curvature_type; + let sobel = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Sobel))))); + let off = mean(&mask(&mut fixture, raw_curvature(Generator::new(GeneratorKind::Curvature)))); + + let standard = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Standard))))); + let smooth = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Smooth))))); + assert!((sobel - off).abs() < 1e-4, "Sobel adds nothing on a flat height"); + assert!(standard > off + 1e-3 && smooth < off - 1e-4, "standard {standard}, off {off}, smooth {smooth}"); +} + +#[test] +fn a_micro_height_bump_occludes_around_it_on_ambient_occlusion() { + let mut fixture = fixture(); + let deep = |micro: &mut MicroDetails| (micro.ao_radius, micro.ao_depth) = (1.0, 1.0); + let off = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion)); + let flat = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("flat"), None, deep)); + + let on = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, deep)); + assert_eq!(off, flat, "a flat micro height occludes nothing"); + assert!(on.iter().zip(&off).all(|(on, off)| on <= off), "micro occlusion only darkens"); + assert!(mean(&on) < mean(&off) - 1e-3, "{} vs {}", mean(&on), mean(&off)); +} + +#[test] +fn a_tiny_ao_radius_occludes_nothing() { + let mut fixture = fixture(); + let off = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion)); + + let tiny = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| micro.ao_radius = 0.05)); + assert_eq!(off, tiny); +} + +#[test] +fn a_micro_height_bump_moves_the_wear_kinds_around_it() { + let mut fixture = fixture(); + for kind in [GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::FiberGlassEdgeWear] { + let off = mask(&mut fixture, with_micro(kind, None, None, |_| {})); + + let on = mask(&mut fixture, with_micro(kind, Some("bump"), None, |micro| micro.curvature_intensity = 1.0)); + let changed = on.iter().zip(&off).filter(|(on, off)| (*on - *off).abs() > 1e-3).count(); + assert!(changed > 0, "{kind:?}"); + } +} diff --git a/crates/core/src/block_scales.rs b/crates/core/src/block_scales.rs index 65b2403e..ee5269f4 100644 --- a/crates/core/src/block_scales.rs +++ b/crates/core/src/block_scales.rs @@ -30,6 +30,24 @@ impl BlockScales { 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]) } + /// Uniform bake atlas UV → working atlas UV, the inverse of [`BlockScales::bake_uv`] + pub fn working_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]; + Some([(origin[0] + local[0]) * block / working_size.0 as f32, (origin[1] + local[1]) * block / working_size.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)); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 0dbcc0d7..62629fc6 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -12,6 +12,7 @@ use crate::{ ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, }; +mod anchored_micro_detail; mod axis_blend; mod axis_layer; mod curvature_detail; @@ -22,7 +23,8 @@ mod filtering; mod generator_global; mod generator_grayscale; mod light_parameters; -mod micro_detail; +mod micro_curvature_type; +mod micro_details; mod output_resolution; mod resolution_mode; mod sampling; @@ -40,6 +42,7 @@ mod uv_transform; mod uv_wrap; mod wear_parameters; +use anchored_micro_detail::AnchoredMicroDetail; pub use axis_blend::AxisBlend; pub use axis_layer::AxisLayer; pub use curvature_detail::CurvatureDetail; @@ -50,7 +53,8 @@ pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; pub use light_parameters::LightParameters; -pub use micro_detail::MicroDetail; +pub use micro_curvature_type::MicroCurvatureType; +pub use micro_details::MicroDetails; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; @@ -1028,6 +1032,7 @@ impl GeneratorKind { } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(remote = "Self")] pub struct Generator { pub kind: GeneratorKind, /// Where the mask starts (0..1, generator specific threshold). @@ -1056,9 +1061,6 @@ pub struct Generator { /// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub inputs: BTreeMap, - /// Painted height read from an anchor point below, added as micro detail (None: baked maps only). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub micro: Option, /// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub wear: Option, @@ -1074,6 +1076,30 @@ pub struct Generator { /// The image a wear generator reads as its grunge once Use Custom Grunge is on (None: an empty slot) #[serde(default, skip_serializing_if = "Option::is_none")] pub grunge: Option, + /// The micro details of Curvature, Ambient Occlusion and the wear kinds (None: never touched, their defaults: off); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub micro: Option>, +} + +impl Serialize for Generator { + fn serialize(&self, serializer: S) -> Result { + Generator::serialize(self, serializer) + } +} + +impl<'de> Deserialize<'de> for Generator { + fn deserialize>(deserializer: D) -> Result { + let mut saved = serde_json::Value::deserialize(deserializer)?; + + // Micro detail saved before Micro Details: an anchor point's height and its amount + let anchored = saved.get_mut("micro").filter(|micro| micro.get("anchor").is_some()).map(serde_json::Value::take); + let mut generator = Generator::deserialize(saved).map_err(serde::de::Error::custom)?; + if let Some(anchored) = anchored { + let AnchoredMicroDetail { anchor, amount } = serde_json::from_value(anchored).map_err(serde::de::Error::custom)?; + generator.micro = MicroDetails::of_anchor(generator.kind, anchor, amount).map(Box::new); + } + Ok(generator) + } } impl Generator { @@ -1111,9 +1137,15 @@ impl Generator { self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) } - /// Everything the generator reads instead of its mesh maps: its inputs, then its texture and its custom grunge + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture, its custom grunge and its micro details pub fn sources(&self) -> impl Iterator { - self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()) + let micro = self.micro.iter().flat_map(|micro| micro.sources()); + self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) + } + + /// The micro details the generator computes with: switched on with an image to read (an anchor's micro detail saved on the earlier model reads too) + pub fn micro_in_use(&self) -> Option<&MicroDetails> { + self.micro.as_deref().filter(|micro| micro.in_use(self.kind)) } /// Whether the generator is on the level, softness and noise it had before the reference app's controls @@ -1148,12 +1180,12 @@ impl Generator { global: GeneratorGlobal::default(), resolution: OutputResolution::default(), inputs: BTreeMap::new(), - micro: None, wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), light: LightParameters::defaults(kind), texture: None, grunge: None, + micro: None, } } @@ -2125,10 +2157,7 @@ impl EffectKind { match self { EffectKind::Fill { source, .. } => source.reads_anchor(anchor), EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)), - EffectKind::Generator(generator) => { - generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor)) - || generator.sources().any(|source| source.reads_anchor(anchor)) - } + EffectKind::Generator(generator) => generator.sources().any(|source| source.reads_anchor(anchor)), _ => false, } } @@ -2141,19 +2170,13 @@ impl EffectKind { EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; - let mut anchors: Vec<_> = sources + sources .into_iter() .filter_map(|source| match source { Source::Anchor { anchor, channel, .. } => Some((*anchor, *channel)), _ => None, }) - .collect(); - if let EffectKind::Generator(generator) = self - && let Some(micro) = generator.micro - { - anchors.push((micro.anchor, Channel::Height)); - } - anchors + .collect() } /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input, a colour selection's ID map) @@ -2641,10 +2664,10 @@ mod tests { let reader = fill_layer.mask.as_ref().map(|mask| &mask.effects[0].kind); assert!(reader.is_some_and(|reader| reader.reads(Some(LayerId(9))) && reader.reads(None) && !reader.reads(Some(LayerId(8))))); - // A generator with micro detail reads its anchor too + // A generator whose Micro Height reads an anchor reads it too let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); - generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); + generator.micro = MicroDetails::of_anchor(GeneratorKind::Dirt, LayerId(9), 0.5).map(Box::new); assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9))) && !EffectKind::Generator(generator.clone()).reads(Some(LayerId(8)))); @@ -2654,6 +2677,29 @@ mod tests { assert!(generator_layer.reads_anchor()); } + #[test] + fn micro_detail_saved_on_an_anchor_loads_as_micro_details_reading_its_height() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + saved["micro"] = serde_json::json!({"anchor": 9, "amount": 0.25}); + + let generator: Generator = serde_json::from_value(saved.clone()).unwrap(); + let micro = generator.micro.as_deref().unwrap(); + let defaults = MicroDetails::defaults(GeneratorKind::Curvature).unwrap(); + + assert!(micro.enabled && micro.height, "{micro:?}"); + assert_eq!(micro.height_source, Some(Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() })); + assert!(micro.height_intensity < defaults.height_intensity, "a weaker amount reads a gentler height"); + assert_eq!((micro.curvature_type, micro.ao_radius, micro.normal_source.clone()), (defaults.curvature_type, defaults.ao_radius, None)); + assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9)))); + + let reloaded: Generator = serde_json::from_value(serde_json::to_value(&generator).unwrap()).unwrap(); + assert_eq!(reloaded, generator, "saved again as Micro Details"); + + saved["kind"] = serde_json::to_value(GeneratorKind::ThinAreas).unwrap(); + let without: Generator = serde_json::from_value(saved).unwrap(); + assert!(without.micro.is_none(), "a kind without micro details drops it"); + } + #[test] fn compare_masks_saved_before_sources_compare_the_mask_with_the_constant_hard() { let saved = r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#; diff --git a/crates/core/src/layer/anchored_micro_detail.rs b/crates/core/src/layer/anchored_micro_detail.rs new file mode 100644 index 00000000..0101ddfa --- /dev/null +++ b/crates/core/src/layer/anchored_micro_detail.rs @@ -0,0 +1,18 @@ +use serde::Deserialize; + +use super::LayerId; + +/// Micro detail as saved before Micro Details: the anchor point whose painted height it read, and how strongly +#[derive(Deserialize)] +pub(crate) struct AnchoredMicroDetail { + pub anchor: LayerId, + /// 0..1, 0.5 by default + #[serde(default = "AnchoredMicroDetail::default_amount")] + pub amount: f32, +} + +impl AnchoredMicroDetail { + fn default_amount() -> f32 { + 0.5 + } +} diff --git a/crates/core/src/layer/micro_curvature_type.rs b/crates/core/src/layer/micro_curvature_type.rs new file mode 100644 index 00000000..f0eba63c --- /dev/null +++ b/crates/core/src/layer/micro_curvature_type.rs @@ -0,0 +1,30 @@ +use serde::{Deserialize, Serialize}; + +/// How a generator's micro details turn the micro height into curvature +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum MicroCurvatureType { + /// The slope of the height, stronger than Sobel and lifting the whole surface slightly + Standard, + /// The slope of the height + #[default] + Sobel, + /// The height against blurred copies of itself, softer and wider + Smooth, +} + +impl MicroCurvatureType { + pub const ALL: [MicroCurvatureType; 3] = [MicroCurvatureType::Standard, MicroCurvatureType::Sobel, MicroCurvatureType::Smooth]; + + pub fn label(self) -> &'static str { + match self { + MicroCurvatureType::Standard => "Standard", + MicroCurvatureType::Sobel => "Sobel", + MicroCurvatureType::Smooth => "Smooth", + } + } + + /// The type named `name` (its label, any case) + pub fn parse(name: &str) -> Option { + MicroCurvatureType::ALL.into_iter().find(|kind| kind.label().eq_ignore_ascii_case(name)) + } +} diff --git a/crates/core/src/layer/micro_detail.rs b/crates/core/src/layer/micro_detail.rs deleted file mode 100644 index d7b13121..00000000 --- a/crates/core/src/layer/micro_detail.rs +++ /dev/null @@ -1,16 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::LayerId; - -/// Painted height read from an anchor point below a generator -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct MicroDetail { - /// The anchor point effect id - pub anchor: LayerId, - /// Strength of the height signal from 0 to 1 - pub amount: f32, -} - -impl MicroDetail { - pub const DEFAULT_AMOUNT: f32 = 0.5; -} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs new file mode 100644 index 00000000..3a090755 --- /dev/null +++ b/crates/core/src/layer/micro_details.rs @@ -0,0 +1,121 @@ +use serde::{Deserialize, Serialize}; + +use super::micro_curvature_type::MicroCurvatureType; +use super::{GeneratorKind, LayerId, Source}; +use crate::Channel; + +/// A generator's micro details: a height or normal image adding fine curvature or occlusion to its mesh maps +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MicroDetails { + /// Use Micro Details (Curvature and Ambient Occlusion; the wear kinds use them once Micro Height or Micro Normal is on) + pub enabled: bool, + /// Read the micro height image + pub height: bool, + /// Read the micro normal image + pub normal: bool, + pub curvature_type: MicroCurvatureType, + /// How strongly the micro details add to the curvature (0..5 on Curvature, 0..1 on the wear kinds) + pub curvature_intensity: f32, + /// How steep the micro height reads ([`MicroDetails::HEIGHT_INTENSITY_RANGE`]) + pub height_intensity: f32, + /// How far the micro height occludes (0..1) + pub ao_radius: f32, + /// How deep the micro height reads for occlusion (0..1) + pub ao_depth: f32, + /// The micro height image (None: an empty slot) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height_source: Option, + /// The micro normal image (None: an empty slot) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub normal_source: Option, +} + +impl MicroDetails { + pub const HEIGHT_INTENSITY_RANGE: std::ops::RangeInclusive = 0.0..=10.0; + + /// Height Details Intensity per unit of an anchor's micro detail amount (0..1): the earlier default amount, 0.5, reads at the default intensity + pub const HEIGHT_INTENSITY_PER_AMOUNT: f32 = 2.0; + + /// The micro details reading anchor point `anchor`'s height as their Micro Height at `amount` (0..1) on a `kind` generator, None for kinds without them + pub fn of_anchor(kind: GeneratorKind, anchor: LayerId, amount: f32) -> Option { + let amount = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 }; + let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; + let micro = MicroDetails { + enabled: true, + height: true, + height_intensity: amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT, + height_source: Some(source), + ..MicroDetails::defaults(kind)? + }; + Some(micro.clamped(kind)) + } + + /// The reference app's defaults for `kind`, or None for kinds without micro details + pub fn defaults(kind: GeneratorKind) -> Option { + let shared = MicroDetails { + enabled: false, + height: true, + normal: true, + curvature_type: MicroCurvatureType::Sobel, + curvature_intensity: 1.0, + height_intensity: 1.0, + ao_radius: 0.3, + ao_depth: 0.05, + height_source: None, + normal_source: None, + }; + match kind { + GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion => Some(shared), + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => { + Some(MicroDetails { height: false, normal: false, curvature_intensity: 0.5, ..shared }) + } + GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => None, + } + } + + /// Whether a generator of `kind` has the Use Micro Details switch (the wear kinds have only Micro Height and Micro Normal) + pub fn has_switch(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion) + } + + /// Whether a generator of `kind` adds micro curvature + pub fn has_curvature(kind: GeneratorKind) -> bool { + MicroDetails::defaults(kind).is_some() && kind != GeneratorKind::AmbientOcclusion + } + + /// Whether a generator of `kind` adds micro occlusion + pub fn has_occlusion(kind: GeneratorKind) -> bool { + MicroDetails::defaults(kind).is_some() && kind != GeneratorKind::Curvature + } + + /// The range of the curvature intensity on `kind` + pub fn curvature_intensity_range(kind: GeneratorKind) -> std::ops::RangeInclusive { + if kind == GeneratorKind::Curvature { 0.0..=5.0 } else { 0.0..=1.0 } + } + + /// Whether the micro details change a generator of `kind`: switched on with an image to read + pub fn in_use(&self, kind: GeneratorKind) -> bool { + (self.enabled || !MicroDetails::has_switch(kind)) && (self.height || self.normal) + } + + /// The images the micro details read: their height, then their normal + pub fn sources(&self) -> impl Iterator { + self.height_source.iter().chain(self.normal_source.as_ref()) + } + + /// Every value brought into its range, non-finite ones to the defaults of `kind` + pub fn clamped(self, kind: GeneratorKind) -> MicroDetails { + let Some(defaults) = MicroDetails::defaults(kind) else { return self }; + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + MicroDetails { + curvature_intensity: within(self.curvature_intensity, defaults.curvature_intensity, MicroDetails::curvature_intensity_range(kind)), + height_intensity: within(self.height_intensity, defaults.height_intensity, MicroDetails::HEIGHT_INTENSITY_RANGE), + ao_radius: within(self.ao_radius, defaults.ao_radius, 0.0..=1.0), + ao_depth: within(self.ao_depth, defaults.ao_depth, 0.0..=1.0), + ..self + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b8d53dd9..e68cdada 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,7 +112,7 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, diff --git a/crates/engine/src/anchored_micro_edit.rs b/crates/engine/src/anchored_micro_edit.rs new file mode 100644 index 00000000..75d2eb54 --- /dev/null +++ b/crates/engine/src/anchored_micro_edit.rs @@ -0,0 +1,71 @@ +//! `microAnchor` and `microAmount`: the earlier commands for a generator's micro detail, now its Micro Height read from an anchor point + +use serde_json::Value; +use texturecraft_core::{Channel, Generator, LayerId, MicroDetails, Source}; + +use crate::commands::bad; +use crate::mask_cmds::anchor_source; +use crate::{Result, Session}; + +/// What `microAnchor` and `microAmount` change on a generator's micro details +pub struct AnchoredMicroEdit { + /// The anchor point the Micro Height reads (`Some(None)`: `microAnchor: null` empties the slot) + anchor: Option>, + /// `microAmount`, 0..1, read as the Height Details Intensity + amount: Option, +} + +impl AnchoredMicroEdit { + /// The edit `params` ask of a generator on layer `reader` (None when they give neither key) + pub fn parse(session: &Session, command: &str, reader: LayerId, params: &Value) -> Result> { + let amount = match params.get("microAmount") { + Some(value) => { + let amount = value.as_f64().filter(|value| value.is_finite()).ok_or_else(|| bad(command, "`microAmount` must be a number 0..1"))?; + Some((amount as f32).clamp(0.0, 1.0)) + } + None => None, + }; + let anchor = match params.get("microAnchor") { + None => None, + Some(Value::Null) => Some(None), + Some(value) => { + let anchor = value.as_u64().ok_or_else(|| bad(command, "`microAnchor` must be an anchor effect id or null"))?; + + // The same rule as fills: an anchor below, in the same texture set + Some(Some(anchor_source(session, command, reader, LayerId(anchor), Channel::Height)?)) + } + }; + if anchor.is_none() && amount.is_none() { + return Ok(None); + } + + Ok(Some(AnchoredMicroEdit { anchor, amount })) + } + + /// The edit made on `generator`: an anchor switches the micro details and their Micro Height on and reads it there + pub fn apply(self, command: &str, generator: &mut Generator) -> Result<()> { + let kind = generator.kind; + let defaults = MicroDetails::defaults(kind); + match (self.anchor, &defaults) { + (Some(None), _) => { + if let Some(micro) = generator.micro.as_mut() { + micro.height_source = None; + } + } + (Some(Some(source)), Some(defaults)) => { + let micro = generator.micro.get_or_insert_with(|| Box::new(defaults.clone())); + (micro.enabled, micro.height, micro.height_source) = (true, true, Some(source)); + } + (Some(Some(_)), None) => return Err(bad(command, format!("{} has no micro details for `microAnchor`", kind.label()))), + (None, _) => {} + } + + if let Some(amount) = self.amount { + let reads_height = generator.micro.as_mut().filter(|micro| micro.height_source.is_some()); + let micro = reads_height.ok_or_else(|| bad(command, "give `microAnchor` before `microAmount`: the generator's Micro Height reads nothing"))?; + micro.height_intensity = amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT; + **micro = micro.as_ref().clone().clamped(kind); + } + Ok(()) + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index de36131e..c4ac692e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -159,13 +159,13 @@ fn generator_json(generator: &Generator) -> Value { if let Some(grunge) = &generator.grunge { out["grunge"] = source_json(grunge); } + if let Some(micro) = &generator.micro { + out["micro"] = json!(micro); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); } - if let Some(micro) = &generator.micro { - out["micro"] = json!({ "anchor": micro.anchor.0, "amount": micro.amount }); - } out } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..a9348fc1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,6 +9,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod add_mask_cmds; +mod anchored_micro_edit; pub mod bake; pub mod bake_preview; pub mod brush_preset_cmds; @@ -50,6 +51,7 @@ pub mod materialx_cmds; pub mod meshmap_cmds; mod meshmap_file_name; pub mod meshmap_import_cmds; +pub mod micro_params; mod orb_camera; pub mod orb_preview; pub mod painting; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 4369c512..3462216c 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,12 +3,14 @@ use serde_json::{Value, json}; use texturecraft_core::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, + GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, }; +use crate::anchored_micro_edit::AnchoredMicroEdit; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; +use crate::micro_params::{MICRO_HEIGHT_INPUT, MICRO_NORMAL_INPUT, micro_from, swapped_micro}; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; @@ -53,7 +55,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -98,7 +100,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture or grunge + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture, grunge, microHeight or microNormal + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null (the Micro Height reads that anchor point; null empties it), microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -691,6 +693,8 @@ pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; section_from(command, params, generator)?; + let earlier_keys: &[&str] = if WearParameters::defaults(generator.kind).is_some() { &EARLIER_WEAR_KEYS } else { &EARLIER_SECTION_KEYS }; + micro_from(command, params, generator, earlier_keys)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } @@ -780,53 +784,26 @@ fn add_anchor(session: &mut Session, params: &Value) -> Result { push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal) } -/// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer -/// `reader` (None: leave it as it is; `Some(None)`: remove it). -fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value, current: Option) -> Result>> { - let amount = match params.get("microAmount") { - Some(value) => { - Some(value.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(command, "`microAmount` must be a number 0..1"))?.clamp(0.0, 1.0) as f32) - } - None => None, - }; - let anchor = match params.get("microAnchor") { - None => current.map(|m| m.anchor), - Some(Value::Null) => return Ok(Some(None)), - Some(value) => Some(LayerId(value.as_u64().ok_or_else(|| bad(command, "`microAnchor` must be an anchor effect id or null"))?)), - }; - let Some(anchor) = anchor else { - return match amount { - Some(_) => Err(bad(command, "give `microAnchor` before `microAmount`: the generator has no micro detail")), - None => Ok(None), - }; - }; - - if params.get("microAnchor").is_none() && amount.is_none() { - return Ok(None); - } - - // The same rule as fills: an anchor below, in the same texture set - anchor_source(session, command, reader, anchor, Channel::Height)?; - let amount = amount.or(current.map(|m| m.amount)).unwrap_or(MicroDetail::DEFAULT_AMOUNT); - Ok(Some(Some(MicroDetail { anchor, amount }))) -} - /// A generator input a command names: a mesh map it reads, its texture or its custom grunge #[derive(Clone, Copy)] enum GeneratorInput { Map(BakedMap), Texture, Grunge, + MicroHeight, + MicroNormal, } /// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture` or `grunge`"))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture`, `grunge`, `microHeight` or `microNormal`"))?; let input = match name { TEXTURE_INPUT => GeneratorInput::Texture, GRUNGE_INPUT => GeneratorInput::Grunge, + MICRO_HEIGHT_INPUT => GeneratorInput::MicroHeight, + MICRO_NORMAL_INPUT => GeneratorInput::MicroNormal, _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), }; @@ -842,6 +819,9 @@ fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> R Some(Source::Image { name: image.to_string(), normal_format: Default::default() }) } (None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])), + (None, None, Some(_), false) if matches!(input, GeneratorInput::MicroNormal) => { + return Err(bad(CMD, "the micro normal reads an image or a value, not an anchor point")); + } (None, None, Some(anchor), false) => { let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height); Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?) @@ -861,8 +841,8 @@ fn add_generator(session: &mut Session, params: &Value) -> Result { generator_from("effect.add.generator", params, &mut generator)?; let selected_layer = layer_param(session, "effect.add.generator", params)?; let reader = session.doc.project.mask_owner(selected_layer); - if let Some(micro) = micro_param(session, "effect.add.generator", reader, params, None)? { - generator.micro = micro; + if let Some(edit) = AnchoredMicroEdit::parse(session, "effect.add.generator", reader, params)? { + edit.apply("effect.add.generator", &mut generator)?; } let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); push_effect(session, params, EffectKind::Generator(generator), blend) @@ -1071,7 +1051,7 @@ fn set(session: &mut Session, params: &Value) -> Result { }; let micro = match session.doc.project.effect(effect) { - Some((owner, Effect { kind: EffectKind::Generator(generator), .. })) => micro_param(session, CMD, owner, params, generator.micro)?, + Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => AnchoredMicroEdit::parse(session, CMD, owner, params)?, _ if params.get("microAnchor").is_some() || params.get("microAmount").is_some() => { return Err(bad(CMD, "`microAnchor` and `microAmount` edit generator effects only")); } @@ -1144,9 +1124,6 @@ fn set(session: &mut Session, params: &Value) -> Result { generator.inputs.retain(|map, _| kind.inputs().contains(map)); } generator_from(CMD, params, generator)?; - if let Some(micro) = micro { - generator.micro = micro; - } match input { Some((GeneratorInput::Map(map), source)) => { if !generator.inputs_in_use().contains(&map) { @@ -1161,8 +1138,22 @@ fn set(session: &mut Session, params: &Value) -> Result { Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source, // generator_from refused the grunge on kinds without wear controls and moved the generator onto them Some((GeneratorInput::Grunge, source)) => generator.grunge = source, + // generator_from refused micro details on kinds without them and created them + Some((GeneratorInput::MicroHeight, source)) => { + if let Some(micro) = generator.micro.as_mut() { + micro.height_source = source; + } + } + Some((GeneratorInput::MicroNormal, source)) => { + if let Some(micro) = generator.micro.as_mut() { + micro.normal_source = source; + } + } None => {} } + if let Some(edit) = micro { + edit.apply(CMD, generator)?; + } } _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), EffectKind::Levels(levels) => levels_from(CMD, params, levels)?, @@ -1294,6 +1285,7 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { resolution: current.resolution, inputs, grunge: current.grunge.clone().filter(|_| WearParameters::defaults(kind).is_some()), + micro: swapped_micro(current.micro.as_deref(), kind), ..Generator::new(kind) } } diff --git a/crates/engine/src/micro_params.rs b/crates/engine/src/micro_params.rs new file mode 100644 index 00000000..7e0ed083 --- /dev/null +++ b/crates/engine/src/micro_params.rs @@ -0,0 +1,91 @@ +//! The micro details controls `effect.add.generator` and `effect.set` take + +use serde_json::Value; +use texturecraft_core::{Generator, GeneratorKind, MicroCurvatureType, MicroDetails, SectionParameters, WearParameters}; + +use crate::Result; +use crate::commands::{bad, boolp, f32p, strp}; + +/// The micro details controls +pub const MICRO_KEYS: [&str; 8] = + ["useMicroDetails", "microHeight", "microNormal", "microCurvatureType", "microCurvatureIntensity", "microHeightIntensity", "microAoRadius", "microAoDepth"]; + +/// The input names of the micro height and micro normal images, beside the mesh map ids +pub const MICRO_HEIGHT_INPUT: &str = "microHeight"; +pub const MICRO_NORMAL_INPUT: &str = "microNormal"; + +/// Whether micro details control `key` changes a generator of `kind` +pub fn micro_key_applies(kind: GeneratorKind, key: &str) -> bool { + match key { + "useMicroDetails" => MicroDetails::has_switch(kind), + "microCurvatureType" | "microCurvatureIntensity" | "microHeightIntensity" => MicroDetails::has_curvature(kind), + "microAoRadius" | "microAoDepth" => MicroDetails::has_occlusion(kind), + _ => MicroDetails::defaults(kind).is_some(), + } +} + +/// The micro details controls in `params` (a micro height or normal input counts as one): they move a generator off its earlier model onto the reference's controls; `earlier_keys` are the keys that keep it there +pub fn micro_from(command: &str, params: &Value, generator: &mut Generator, earlier_keys: &[&str]) -> Result<()> { + let input_given = matches!(strp(params, "input"), Some(MICRO_HEIGHT_INPUT | MICRO_NORMAL_INPUT)); + let mut given = MICRO_KEYS.iter().filter(|key| params.get(**key).is_some()).peekable(); + if given.peek().is_none() && !input_given { + return Ok(()); + } + + let kind = generator.kind; + let Some(defaults) = MicroDetails::defaults(kind) else { + return Err(bad(command, format!("{} has no micro details: only Curvature, Ambient Occlusion and the wear kinds have them", kind.label()))); + }; + if let Some(unused) = given.find(|key| !micro_key_applies(kind, key)) { + return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); + } + if WearParameters::defaults(kind).is_some() && ["blur", "balance", "contrast"].iter().any(|key| params.get(*key).is_some()) { + return Err(bad(command, format!("{} has no global blur, balance or contrast beside its micro details", kind.label()))); + } + if earlier_keys.iter().any(|key| params.get(*key).is_some()) { + return Err(bad(command, "level, softness, noise and offset drive the earlier model: give them or the micro details, not both")); + } + + // Micro details exist on the reference's controls only + if generator.on_earlier_model() { + generator.offset = 0.0; + if let Some(wear) = WearParameters::defaults(kind) { + generator.wear = Some(wear); + } else { + let fresh = Generator::new(kind); + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale) = + (fresh.level, fresh.softness, fresh.noise_amount, fresh.noise_scale); + generator.section = SectionParameters::defaults(kind); + } + } + + let micro = generator.micro.get_or_insert_with(|| Box::new(defaults)); + for (key, value) in [("useMicroDetails", &mut micro.enabled), ("microHeight", &mut micro.height), ("microNormal", &mut micro.normal)] { + if let Some(given) = boolp(params, key) { + *value = given; + } + } + for (key, value) in [ + ("microCurvatureIntensity", &mut micro.curvature_intensity), + ("microHeightIntensity", &mut micro.height_intensity), + ("microAoRadius", &mut micro.ao_radius), + ("microAoDepth", &mut micro.ao_depth), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(value) = params.get("microCurvatureType") { + let name = value.as_str().ok_or_else(|| bad(command, "`microCurvatureType` must be a string"))?; + micro.curvature_type = MicroCurvatureType::parse(name).ok_or_else(|| bad(command, format!("unknown curvature type `{name}`")))?; + } + **micro = micro.as_ref().clone().clamped(kind); + Ok(()) +} + +/// `current`'s micro details carried onto a `kind` generator: its images stay, its controls start from `kind`'s defaults +pub fn swapped_micro(current: Option<&MicroDetails>, kind: GeneratorKind) -> Option> { + let current = current.filter(|micro| micro.sources().next().is_some())?; + let defaults = MicroDetails::defaults(kind)?; + Some(Box::new(MicroDetails { height_source: current.height_source.clone(), normal_source: current.normal_source.clone(), ..defaults })) +} diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index caba4447..f15a9ed8 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -150,35 +150,58 @@ fn anchor_points_in_masks_record_the_mask_for_layers_above() { assert!(close(center(&mut s, Channel::BaseColor), [expected; 3]), "{:?}", center(&mut s, Channel::BaseColor)); } +/// The composited base color over the whole texture set, row by row +fn base_colors(s: &mut Session) -> Vec<[f32; 3]> { + s.update(); + let composite = &s.caches[0].composite; + (0..composite.height).flat_map(|y| (0..composite.resolution).map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() +} + +fn largest_change(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { + a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max) +} + #[test] -fn generators_read_an_anchor_height_as_micro_detail() { - let mut s = session(); - let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); - let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); +fn generators_read_an_anchor_height_as_their_micro_height() { + let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + + // A checker of raised height below, recorded by an anchor point + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap(); // The anchor must be below; `microAmount` needs an anchor; ids must be numbers assert!(execute(&mut s, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"microAmount": 0.5})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": "x"})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": low})).is_err(), "not an anchor point"); + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAmount": 0.5})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": "x"})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": low})).is_err(), "not an anchor point"); - let generator = id(execute(&mut s, "effect.add.generator", &json!({"generator": "curvature", "noise": 0.0})).unwrap(), "effect"); - let plain = center(&mut s, Channel::BaseColor); + let generator = id(execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap(), "effect"); + let plain = base_colors(&mut s); execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); - let raised = center(&mut s, Channel::BaseColor); - assert!(raised[0] > plain[0] + 0.1, "{plain:?} -> {raised:?}"); + let raised = base_colors(&mut s); + assert!(largest_change(&raised, &plain) > 0.05, "the checker's raised edges read as curvature"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); - assert!(inspect.to_string().contains(&format!("\"micro\":{{\"amount\":1.0,\"anchor\":{anchor}}}")), "{inspect}"); + let inspected = inspect.to_string(); + assert!(inspected.contains("\"heightSource\"") && inspected.contains(&format!("\"anchor\":{anchor}")), "{inspect}"); - // The amount alone keeps the anchor; null removes the micro detail + // The amount alone keeps the anchor; null empties the Micro Height execute(&mut s, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); - assert!(close(center(&mut s, Channel::BaseColor), plain)); + assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "no amount, no micro height"); execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); - assert!(s.doc.project.effect(LayerId(generator)).map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.is_none())).unwrap()); + let emptied = s + .doc + .project + .effect(LayerId(generator)) + .map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.as_ref().is_some_and(|micro| micro.height_source.is_none()))); + assert_eq!(emptied, Some(true)); + assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "without an anchor, as without micro details"); assert!(execute(&mut s, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); - // A copied generator with micro detail needs the anchor below its new layer + // A copied generator reading an anchor needs the anchor below its new layer execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); execute(&mut s, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); execute(&mut s, "effect.copy", &json!({"effect": generator})).unwrap(); diff --git a/crates/engine/tests/it/generator_micro_details.rs b/crates/engine/tests/it/generator_micro_details.rs new file mode 100644 index 00000000..33e13b87 --- /dev/null +++ b/crates/engine/tests/it/generator_micro_details.rs @@ -0,0 +1,133 @@ +//! A generator's micro details through `effect.add.generator` and `effect.set`: their controls per kind, their images as the `microHeight` and `microNormal` inputs, and the kinds without them + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, LayerId, MicroCurvatureType, Source}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +/// A gray image resource, by the name it was imported under +fn gray_image(session: &mut Session) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("height.png", bytes).unwrap() +} + +#[test] +fn curvature_takes_its_micro_details_controls() { + let mut session = session(); + let params = json!({"generator": "curvature", "useMicroDetails": true, "microNormal": false, "microCurvatureType": "smooth", "microCurvatureIntensity": 4.0, "microHeightIntensity": 20.0}); + let effect = add(&mut session, params); + + let micro = generator(&session, effect).micro.unwrap(); + assert!(micro.enabled && micro.height && !micro.normal); + assert_eq!(micro.curvature_type, MicroCurvatureType::Smooth); + assert_eq!((micro.curvature_intensity, micro.height_intensity), (4.0, 10.0), "the height intensity stops at 10"); + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"micro\""), "inspect shows the micro details"); +} + +#[test] +fn each_kind_refuses_the_micro_controls_it_lacks() { + let mut session = session(); + let refused = [ + ("curvature", "microAoRadius"), + ("ambientOcclusion", "microCurvatureType"), + ("ambientOcclusion", "microHeightIntensity"), + ("edgeWear", "useMicroDetails"), + ("dirt", "useMicroDetails"), + ("position", "microHeight"), + ("worldSpaceNormals", "microNormal"), + ("direction", "microAoDepth"), + ]; + for (kind, key) in refused { + let effect = add(&mut session, json!({"generator": kind})); + let value = if key == "microCurvatureType" { json!("sobel") } else { json!(true) }; + let value = if key.starts_with("microAo") || key.ends_with("Intensity") { json!(0.5) } else { value }; + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: value})).is_err(), "{kind} {key}"); + assert_eq!(generator(&session, effect).micro, None, "{kind} {key}"); + } +} + +#[test] +fn the_wear_kinds_cap_their_curvature_intensity_at_one() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "fiberGlassEdgeWear", "microHeight": true, "microCurvatureIntensity": 3.0})); + + assert_eq!(generator(&session, effect).micro.unwrap().curvature_intensity, 1.0); +} + +#[test] +fn the_micro_images_are_inputs_and_stay_used_resources() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "ambientOcclusion", "useMicroDetails": true})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microHeight", "inputImage": name})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microNormal", "inputValue": 0.5})).unwrap(); + let micro = generator(&session, effect).micro.unwrap(); + assert_eq!(micro.height_source, Some(Source::image(name.clone()))); + assert_eq!(micro.normal_source, Some(Source::Uniform([0.5; 3]))); + assert!(generator(&session, effect).inputs.is_empty(), "micro images are not mesh map inputs"); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the micro height"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microHeight", "inputBaked": true})).unwrap(); + assert_eq!(generator(&session, effect).micro.unwrap().height_source, None, "inputBaked empties the slot"); + let anchor = json!({"effect": effect, "input": "microNormal", "inputAnchor": effect}); + assert!(execute(&mut session, "effect.set", &anchor).is_err(), "the micro normal reads no anchor point"); +} + +#[test] +fn micro_details_move_an_earlier_generator_onto_the_reference_controls() { + let mut session = session(); + let name = gray_image(&mut session); + let wear = add(&mut session, json!({"generator": "edgeWear", "level": 0.8, "offset": 0.2})); + let curvature = add(&mut session, json!({"generator": "curvature", "level": 0.8})); + assert!(generator(&session, wear).on_earlier_model() && generator(&session, curvature).on_earlier_model()); + + execute(&mut session, "effect.set", &json!({"effect": wear, "input": "microHeight", "inputImage": name})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": curvature, "useMicroDetails": true})).unwrap(); + let moved = generator(&session, wear); + assert!(moved.wear.is_some() && moved.offset == 0.0, "Metal Edge Wear on its wear controls, without the earlier offset"); + assert!(generator(&session, curvature).section.is_some(), "Curvature on its section controls"); + + let both = json!({"effect": wear, "microHeight": true, "softness": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "micro details and the earlier model at once"); + let global = json!({"effect": wear, "microHeight": true, "blur": 0.2}); + assert!(execute(&mut session, "effect.set", &global).is_err(), "the wear kinds have no global blur"); +} + +#[test] +fn swapping_kinds_keeps_the_micro_images_where_the_kind_has_micro_details() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "curvature", "useMicroDetails": true, "microCurvatureIntensity": 4.0})); + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microHeight", "inputImage": name})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "edgeWear"})).unwrap(); + let micro = generator(&session, effect).micro.unwrap(); + assert_eq!(micro.height_source, Some(Source::image(name))); + assert_eq!(micro.curvature_intensity, 0.5, "the controls start from Metal Edge Wear's defaults"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "position"})).unwrap(); + assert_eq!(generator(&session, effect).micro, None, "Position has no micro details"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index de497d5a..08d80a48 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -37,6 +37,7 @@ mod folder_contents; mod frame_selection; mod generator_custom_grunge; mod generator_inputs; +mod generator_micro_details; mod generator_sections; mod generator_swap; mod generator_texture; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index f965ca40..26170c32 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2834,24 +2834,6 @@ fn mask_anchor_enabled(app: &TextureCraftApp, anchor: LayerId) -> Option { mask.effects.iter().any(|effect| effect.id == anchor).then_some(mask.enabled) } -/// The anchor points of `anchors` as menu entries under their own heading (a note when there -/// are none); returns the one clicked. -pub(crate) fn anchor_entries(ui: &mut Ui, anchors: &[(LayerId, String)], current: Option) -> Option { - ui.separator(); - ui.label(caption(tr("Anchor points"))); - if anchors.is_empty() { - ui.label(RichText::new(tr("No anchor point below this layer")).color(Tokens::get(ui.ctx()).text_dim)); - } - - let mut picked = None; - for (anchor, label) in anchors { - if ui.selectable_label(current == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { - picked = Some(*anchor); - } - } - picked -} - pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); let label = trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 62b3d0bb..bfcf203a 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,15 +4,15 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, - SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorGrayscale, GeneratorKind, LayerId, LightParameters, OutputResolution, + ResolutionMode, SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, }; use crate::TextureCraftApp; -use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; use crate::i18n::{baked_map_label, tr, trf}; use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; -use crate::theme::{Tokens, caption}; +use crate::theme::Tokens; use crate::widgets::{combo, section, slider_edit, slider_edit_with_suffix}; /// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. @@ -58,9 +58,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer light_parameters(app, ui, id, None, defaults); } } - if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { - micro_detail_properties(app, ui, id, generator.micro, layer); - } ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.button(tr("Restore defaults")).clicked() { @@ -85,34 +82,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer } } -/// The painted height anchor and its influence on this generator -fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micro: Option, layer: LayerId) { - let tokens = Tokens::get(ui.ctx()); - ui.label(caption(tr("Micro detail"))) - .on_hover_text(tr("Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.")); - let anchors = effect_anchors_below(app, layer, LayerId(id)); - let current = match micro { - Some(detail) => anchors.iter().find(|(anchor, _)| *anchor == detail.anchor).map_or_else(|| tr("missing").to_string(), |(_, label)| label.clone()), - None => tr("None").to_string(), - }; - combo(ui, tr("Anchor point"), current, |ui| { - if ui.selectable_label(micro.is_none(), tr("None")).clicked() { - app.run("effect.set", json!({"effect": id, "microAnchor": null})); - } - if let Some(anchor) = anchor_entries(ui, &anchors, micro.map(|detail| detail.anchor)) { - app.run("effect.set", json!({"effect": id, "microAnchor": anchor.0})); - } - }); - if let Some(detail) = micro { - let mut amount = detail.amount; - if let Some(merge) = slider_edit(ui, tr("Amount"), &mut amount, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "microAmount": amount, "merge": merge})); - } - } else if anchors.is_empty() { - ui.label(RichText::new(tr("Add an anchor point to a layer below to use its height as micro detail.")).color(tokens.text_dim)); - } -} - /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -330,7 +299,6 @@ fn defaults_of(id: u64, generator: &Generator) -> Value { "resolution": format!("{:?}", defaults.resolution.mode), "customResolution": defaults.resolution.custom, "resolutionFactor": defaults.resolution.factor, - "microAnchor": null, }); // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 01bf845a..811582c8 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, SectionParameters, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -73,9 +73,6 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { let (mut harness, effect) = harness(false); let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); - if let EffectKind::Generator(generator) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind { - generator.micro = Some(MicroDetail { anchor: LayerId(999), amount: 0.8 }); - } harness.run_steps(3); harness.get_by_label("Restore defaults").scroll_to_me(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..bea73433 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -724,36 +724,6 @@ fn nested_layers_snapshot() { } /// The mask anchor and generator micro controls in the integrated properties panel -#[test] -#[ignore] -fn mask_anchor_micro_detail_snapshot() { - use serde_json::{Value, json}; - use texturecraft_engine::execute; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); - execute(&mut session, "mask.add.black", &json!({"layer": lower})).unwrap(); - execute(&mut session, "effect.add.fill", &json!({"layer": lower, "value": 0.4})).unwrap(); - let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower, "target": "mask", "name": "Wear"})).unwrap()["effect"].as_u64().unwrap(); - let upper = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); - let generator = execute(&mut session, "effect.add.generator", &json!({"layer": upper, "generator": "dirt", "microAnchor": anchor})).unwrap()["effect"] - .as_u64() - .unwrap(); - execute(&mut session, "layer.select", &json!({"layer": upper, "target": generator})).unwrap(); - - let mut harness = Harness::builder() - .with_size(egui::vec2(1600.0, 1200.0)) - .with_pixels_per_point(1.0) - .wgpu() - .build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.dock.focus(Panel::Properties); - harness.run_steps(6); - harness.get_by_label("Micro detail").scroll_to_me(); - save(&mut harness, &output_dir, "mask-anchor-micro-detail"); -} - #[test] #[ignore] fn path_tool_snapshots() { From 815bdb2e4703bcb2cfb2a3070142c5ef6dfb1d2d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:19:49 +0000 Subject: [PATCH 103/153] Generators: 3D Distance, white around a point fading over a radius A new kind with the reference's controls: Position X, Y and Z across the mesh's bounds (scaled evenly, the longest side spanning 0 to 1, as the reference's position map is), Radius, Offset, Contrast and Invert. The value falls from 1 at the point to 0 at the radius and is then slid through by a histogram scan (offset 0 all black, 1 all white; contrast 1 a hard edge); it matches the reference within 0.001 on every captured setting. It reads its Position input like Position does, has no earlier model or global controls (both refused), and swapping onto it drops the earlier offset. Commands only: the picker leaves it out until its panel is designed. --- crates/compose/src/eval.rs | 25 ++++- crates/compose/src/histogram_scan.rs | 35 +++++++ crates/compose/src/lib.rs | 2 + crates/compose/src/three_d_distance.rs | 13 +++ .../tests/generator_three_d_distance.rs | 96 +++++++++++++++++++ crates/core/src/layer.rs | 33 +++++-- crates/core/src/layer/distance_parameters.rs | 40 ++++++++ crates/core/src/layer/micro_details.rs | 6 +- crates/core/src/layer/section_parameters.rs | 7 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 48 ++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 7 +- .../tests/it/generator_three_d_distance.rs | 61 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 1 + 17 files changed, 367 insertions(+), 14 deletions(-) create mode 100644 crates/compose/src/histogram_scan.rs create mode 100644 crates/compose/src/three_d_distance.rs create mode 100644 crates/compose/tests/generator_three_d_distance.rs create mode 100644 crates/core/src/layer/distance_parameters.rs create mode 100644 crates/engine/src/distance_params.rs create mode 100644 crates/engine/tests/it/generator_three_d_distance.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2bf1cf69..29db5ca0 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -43,6 +43,7 @@ use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::texture_layer; +use crate::three_d_distance; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use crate::wear; use crate::wear_inputs::WearInputs; @@ -3406,6 +3407,10 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, maps); } + if let Some(distance) = generator.distance_controls() { + let position = self.uniform_position_input(generator); + return three_d_distance::distance_value(&distance, position); + } let coords = self.coords(); @@ -3424,8 +3429,9 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, 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, - // World Space Normals always computes with its section controls: this arm only keeps the match whole + // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, + (GeneratorKind::ThreeDDistance, _) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3466,7 +3472,12 @@ impl<'a, 'b> Texel<'a, 'b> { sections::axes_signal(normal, §ion.axes) } // Only the kinds with section controls reach here: this arm only keeps the match whole - GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => 0.0, + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance => 0.0, } } @@ -3478,6 +3489,16 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds scaled evenly: the longest side spans 0..1, the others centred on 0.5 + fn uniform_position_input(&mut self, generator: &Generator) -> Vec3 { + if let Some(source) = generator.inputs.get(&BakedMap::Position) { + return Vec3::from(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)); + } + let (low, high) = self.inp.bounds; + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + self.world().map_or(Vec3::splat(0.5), |position| (position - (low + high) * 0.5) / longest + Vec3::splat(0.5)) + } + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) fn bounds_position(&self) -> Vec3 { let (low, high) = self.inp.bounds; diff --git a/crates/compose/src/histogram_scan.rs b/crates/compose/src/histogram_scan.rs new file mode 100644 index 00000000..ca9c851c --- /dev/null +++ b/crates/compose/src/histogram_scan.rs @@ -0,0 +1,35 @@ +//! The histogram scan several generators finish with: a ramp slid through the values and narrowed by a contrast + +/// `value` scanned at `position` (0 all black, 1 all white) over a ramp `1 − contrast` wide; contrast 1 is a hard step +pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 { + let width = 1.0 - contrast.clamp(0.0, 1.0); + // The ramp's low end runs from 1 at position 0 to −width at position 1, so the ends are wholly black or white + let low = (1.0 - position.clamp(0.0, 1.0)) * (1.0 + width) - width; + if width <= f32::EPSILON { + return if value >= low { 1.0 } else { 0.0 }; + } + ((value - low) / width).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_ends_of_the_position_are_all_black_and_all_white() { + for value in [0.0, 0.3, 1.0] { + assert_eq!(histogram_scan(value, 0.0, 0.5), 0.0, "{value}"); + assert_eq!(histogram_scan(value, 1.0, 0.5), 1.0, "{value}"); + } + } + + #[test] + fn the_middle_position_keeps_mid_gray_and_contrast_narrows_around_it() { + assert!((histogram_scan(0.5, 0.5, 0.5) - 0.5).abs() < 1e-6); + assert!((histogram_scan(0.5, 0.5, 0.0) - 0.5).abs() < 1e-6); + assert!((histogram_scan(0.7, 0.5, 0.5) - 0.9).abs() < 1e-6, "a ramp half wide from 0.25"); + assert!(histogram_scan(0.6, 0.5, 0.9) > histogram_scan(0.6, 0.5, 0.5)); + assert_eq!(histogram_scan(0.51, 0.5, 1.0), 1.0); + assert_eq!(histogram_scan(0.49, 0.5, 1.0), 0.0); + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b3f52141..cf4ed85e 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -27,6 +27,7 @@ pub mod frame_placement; mod fur_lock; mod generator_maps; mod held_fields; +mod histogram_scan; mod image_identity; mod mask_gray; mod micro_details; @@ -45,6 +46,7 @@ mod soft_box; pub mod solo; pub mod store; mod texture_layer; +mod three_d_distance; pub mod thumb; pub mod tile_length; mod tile_pattern; diff --git a/crates/compose/src/three_d_distance.rs b/crates/compose/src/three_d_distance.rs new file mode 100644 index 00000000..f6f909c8 --- /dev/null +++ b/crates/compose/src/three_d_distance.rs @@ -0,0 +1,13 @@ +//! The 3D Distance generator: a gradient falling off with the distance from a point across the mesh's bounds + +use texturecraft_core::DistanceParameters; +use texturecraft_geom::glam::Vec3; + +use crate::histogram_scan::histogram_scan; + +/// The value at `position` (0..1 across the bounds, the longest side spanning 0..1): 1 at the point, 0 at the radius, then scanned by the offset and contrast +pub(crate) fn distance_value(distance: &DistanceParameters, position: Vec3) -> f32 { + let from_point = position.distance(Vec3::from(distance.point)); + let gradient = if distance.radius > 0.0 { (1.0 - from_point / distance.radius).clamp(0.0, 1.0) } else { 0.0 }; + histogram_scan(gradient, distance.offset, distance.contrast) +} diff --git a/crates/compose/tests/generator_three_d_distance.rs b/crates/compose/tests/generator_three_d_distance.rs new file mode 100644 index 00000000..6b233479 --- /dev/null +++ b/crates/compose/tests/generator_three_d_distance.rs @@ -0,0 +1,96 @@ +//! The 3D Distance generator on a sphere: white at its point, falling off over its radius, slid by its offset + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, + Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 64; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, +} + +/// A unit sphere with a white fill layer +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; (RES * RES) as usize]))].into() }; + Fixture { project, mesh, gbuf, layer, baked } +} + +/// Every covered texel and its height on the sphere +fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { + (0..RES * RES).filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos.y))).collect() +} + +/// The mask of a 3D Distance generator with `distance` alone over black at `texels` +fn mask(fixture: &mut Fixture, distance: DistanceParameters, texels: &[(u32, u32)]) -> Vec { + let generator = Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +#[test] +fn a_point_at_the_top_lights_the_top() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + + let values = mask(&mut fixture, DistanceParameters { point: [0.5, 1.0, 0.5], radius: 0.8, contrast: 0.0, ..DistanceParameters::default() }, &at); + let mean_where = |above: bool| { + let picked: Vec = texels.iter().zip(&values).filter(|((_, height), _)| (*height > 0.5) == above).map(|(_, value)| *value).collect(); + picked.iter().sum::() / picked.len() as f32 + }; + assert!(mean_where(true) > mean_where(false) + 0.3, "top {} bottom {}", mean_where(true), mean_where(false)); +} + +#[test] +fn the_offset_slides_the_mask_from_black_to_white() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let black = mask(&mut fixture, DistanceParameters { offset: 0.0, ..DistanceParameters::default() }, &at); + let white = mask(&mut fixture, DistanceParameters { offset: 1.0, ..DistanceParameters::default() }, &at); + assert!(black.iter().all(|value| *value == 0.0)); + assert!(white.iter().all(|value| *value == 1.0)); +} + +#[test] +fn a_larger_radius_reaches_further() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + let total = |values: Vec| values.iter().sum::(); + + let small = total(mask(&mut fixture, DistanceParameters { radius: 0.3, ..DistanceParameters::default() }, &at)); + let large = total(mask(&mut fixture, DistanceParameters { radius: 1.2, ..DistanceParameters::default() }, &at)); + assert!(large > small); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 62629fc6..67e57460 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -19,6 +19,7 @@ mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; +mod distance_parameters; mod filtering; mod generator_global; mod generator_grayscale; @@ -49,6 +50,7 @@ pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; +pub use distance_parameters::DistanceParameters; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; @@ -950,10 +952,12 @@ pub enum GeneratorKind { FiberGlassEdgeWear, /// The world space normal's axes combined into one gray WorldSpaceNormals, + /// White around a point across the mesh's bounds, fading with the distance from it + ThreeDDistance, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 9] = [ + pub const ALL: [GeneratorKind; 10] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -963,6 +967,7 @@ impl GeneratorKind { GeneratorKind::Direction, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::WorldSpaceNormals, + GeneratorKind::ThreeDDistance, ]; pub fn label(self) -> &'static str { match self { @@ -975,6 +980,7 @@ impl GeneratorKind { GeneratorKind::Direction => "Light", GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", GeneratorKind::WorldSpaceNormals => "World Space Normals", + GeneratorKind::ThreeDDistance => "3D Distance", } } @@ -990,12 +996,13 @@ impl GeneratorKind { GeneratorKind::Direction => "Direction", GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", + GeneratorKind::ThreeDDistance => "ThreeDDistance", } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; 3D Distance waits for its panel) pub fn in_picker(self) -> bool { - self != GeneratorKind::ThinAreas + !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance) } /// Whether the kind's result depends on its seed @@ -1010,12 +1017,17 @@ impl GeneratorKind { GeneratorKind::Curvature => &[BakedMap::Curvature], GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], - GeneratorKind::Position => &[BakedMap::Position], + GeneratorKind::Position | GeneratorKind::ThreeDDistance => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], } } + /// Whether the kind was added with the reference's controls only, so it never computes with level, softness and noise + pub fn has_no_earlier_model(self) -> bool { + matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance) + } + pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); // The labels before the reference app's names, which agents may still send @@ -1079,6 +1091,9 @@ pub struct Generator { /// The micro details of Curvature, Ambient Occlusion and the wear kinds (None: never touched, their defaults: off); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub micro: Option>, + /// The 3D Distance generator's controls (None on every other kind); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub distance: Option>, } impl Serialize for Generator { @@ -1112,7 +1127,7 @@ impl Generator { /// The global blur, balance and contrast the generator applies: none on the wear and light controls, which have no such controls pub fn applied_global(&self) -> GeneratorGlobal { - if self.wear.is_some() || self.light.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } + if self.wear.is_some() || self.light.is_some() || self.kind.has_no_earlier_model() { GeneratorGlobal::default() } else { self.global } } /// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None @@ -1120,6 +1135,11 @@ impl Generator { self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals)) } + /// The 3D Distance controls the generator computes with: its own, else the defaults on a 3D Distance generator + pub fn distance_controls(&self) -> Option { + self.distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDDistance).then(DistanceParameters::default)) + } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None pub fn detail_in_use(&self) -> Option { let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); @@ -1150,7 +1170,7 @@ impl Generator { /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { - self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear + self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && !self.kind.has_no_earlier_model() } pub fn new(kind: GeneratorKind) -> Generator { @@ -1186,6 +1206,7 @@ impl Generator { texture: None, grunge: None, micro: None, + distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), } } diff --git a/crates/core/src/layer/distance_parameters.rs b/crates/core/src/layer/distance_parameters.rs new file mode 100644 index 00000000..a392b4a0 --- /dev/null +++ b/crates/core/src/layer/distance_parameters.rs @@ -0,0 +1,40 @@ +use serde::{Deserialize, Serialize}; + +/// The 3D Distance generator's controls: white around a point across the mesh's bounds, fading to black at the radius +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DistanceParameters { + /// The point, 0..1 across the mesh's bounds on each axis (Position X, Y and Z) + pub point: [f32; 3], + /// How far the gradient reaches, in units of the bounds' longest side ([`DistanceParameters::RADIUS_RANGE`]) + pub radius: f32, + /// Slides the gradient through: 0 all black, 1 all white + pub offset: f32, + /// Narrows the gradient (0..1; 1 a hard edge) + pub contrast: f32, +} + +impl DistanceParameters { + pub const RADIUS_RANGE: std::ops::RangeInclusive = 0.0..=1.5; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> DistanceParameters { + let defaults = DistanceParameters::default(); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + DistanceParameters { + point: std::array::from_fn(|axis| within(self.point[axis], defaults.point[axis], 0.0..=1.0)), + radius: within(self.radius, defaults.radius, DistanceParameters::RADIUS_RANGE), + offset: within(self.offset, defaults.offset, 0.0..=1.0), + contrast: within(self.contrast, defaults.contrast, 0.0..=1.0), + } + } +} + +impl Default for DistanceParameters { + /// The reference app's defaults: the bounds' centre, radius 1 + fn default() -> DistanceParameters { + DistanceParameters { point: [0.5; 3], radius: 1.0, offset: 0.5, contrast: 0.5 } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 3a090755..a0cbc4ff 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -70,7 +70,11 @@ impl MicroDetails { GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => { Some(MicroDetails { height: false, normal: false, curvature_intensity: 0.5, ..shared }) } - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => None, + GeneratorKind::ThinAreas + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 583c4a99..322fd54c 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -35,7 +35,12 @@ impl SectionParameters { let defaults = SectionParameters { invert: false, blur: 0.0, balance: 0.5, contrast: 0.0, brightness: 0.0, axes: [axis(0.0), axis(1.0), axis(0.0)] }; match kind { GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals => Some(defaults), - GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => None, + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 17975266..b354a95f 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -58,7 +58,8 @@ impl WearParameters { | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::Direction - | GeneratorKind::WorldSpaceNormals => None, + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index e68cdada..bd02feff 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, + AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs new file mode 100644 index 00000000..6e16cbda --- /dev/null +++ b/crates/engine/src/distance_params.rs @@ -0,0 +1,48 @@ +//! The 3D Distance controls `effect.add.generator` and `effect.set` take + +use serde_json::Value; +use texturecraft_core::{Generator, GeneratorKind}; + +use crate::Result; +use crate::commands::{bad, f32p}; + +/// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast +pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; + +/// The controls of the earlier model and the global adjustments, which 3D Distance doesn't have +const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; + +/// The 3D Distance controls in `params`, refused on other kinds; 3D Distance refuses the earlier model's controls +pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if generator.kind != GeneratorKind::ThreeDDistance { + return match first_given(params, &DISTANCE_KEYS) { + Some(key) => Err(bad(command, format!("{} has no `{key}`: only 3D Distance has it", generator.kind.label()))), + None => Ok(()), + }; + } + if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { + return Err(bad( + command, + format!("3D Distance has no `{key}`: its controls are distanceX, distanceY, distanceZ, distanceRadius, distanceOffset and distanceContrast"), + )); + } + + let mut distance = generator.distance_controls().unwrap_or_default(); + for (axis, key) in DISTANCE_KEYS.iter().take(3).enumerate() { + if let (Some(value), Some(coordinate)) = (f32p(params, key), distance.point.get_mut(axis)) { + *coordinate = value; + } + } + for (key, value) in [("distanceRadius", &mut distance.radius), ("distanceOffset", &mut distance.offset), ("distanceContrast", &mut distance.contrast)] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.distance = Some(Box::new(distance.clamped())); + Ok(()) +} + +/// The first of `keys` that `params` gives +fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { + keys.iter().find(|key| params.get(**key).is_some()).copied() +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a9348fc1..041aca62 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,6 +17,7 @@ pub mod camera_cmds; pub mod color_selection_cmds; pub mod commands; pub mod decal_cmds; +pub mod distance_params; pub mod effect_blending_cmds; pub mod effect_clipboard; pub mod file_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 3462216c..fd9b3466 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -8,6 +8,7 @@ use texturecraft_core::{ use crate::anchored_micro_edit::AnchoredMicroEdit; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::distance_params::distance_from; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; use crate::micro_params::{MICRO_HEIGHT_INPUT, MICRO_NORMAL_INPUT, micro_from, swapped_micro}; @@ -55,7 +56,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -695,6 +696,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R section_from(command, params, generator)?; let earlier_keys: &[&str] = if WearParameters::defaults(generator.kind).is_some() { &EARLIER_WEAR_KEYS } else { &EARLIER_SECTION_KEYS }; micro_from(command, params, generator, earlier_keys)?; + distance_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } @@ -1278,7 +1280,8 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { noise_amount: current.noise_amount, noise_scale: current.noise_scale, seed: current.seed, - offset: current.offset, + // The offset belongs to the earlier model, which these kinds lack + offset: if kind.has_no_earlier_model() { 0.0 } else { current.offset }, direction: current.direction, invert: current.invert, global: current.global, diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs new file mode 100644 index 00000000..07f0bdb8 --- /dev/null +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -0,0 +1,61 @@ +//! The 3D Distance generator through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point + +use serde_json::{Value, json}; +use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +#[test] +fn three_d_distance_takes_its_controls_by_name_and_label() { + let mut session = session(); + for name in ["3dDistance", "3D Distance", "ThreeDDistance"] { + let effect = add(&mut session, json!({"generator": name, "distanceX": 0.2, "distanceRadius": 3.0, "distanceOffset": 0.7, "invert": true})); + + let made = generator(&session, effect); + assert_eq!(made.kind, GeneratorKind::ThreeDDistance, "{name}"); + let expected = DistanceParameters { point: [0.2, 0.5, 0.5], radius: 1.5, offset: 0.7, ..DistanceParameters::default() }; + assert_eq!(made.distance_controls(), Some(expected), "{name}: the radius stops at 1.5"); + assert!(made.invert && !made.on_earlier_model()); + } +} + +#[test] +fn three_d_distance_refuses_the_earlier_and_global_controls_and_others_refuse_its_own() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "3dDistance"})); + for key in ["level", "softness", "noise", "offset", "blur", "balance", "contrast"] { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.3})).is_err(), "{key}"); + } + + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "distanceRadius": 0.5})).is_err()); + assert_eq!(generator(&session, curvature).distance, None); +} + +#[test] +fn swapping_onto_three_d_distance_drops_the_earlier_offset() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "curvature", "level": 0.5, "offset": 0.4})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "3dDistance"})).unwrap(); + let swapped = generator(&session, effect); + assert_eq!(swapped.offset, 0.0); + assert_eq!(swapped.distance_controls(), Some(DistanceParameters::default())); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 08d80a48..c67529cc 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -41,6 +41,7 @@ mod generator_micro_details; mod generator_sections; mod generator_swap; mod generator_texture; +mod generator_three_d_distance; mod generator_wear; mod gradient_map; mod high_poly_missed; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index bfcf203a..22505eb3 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -95,6 +95,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::Position => (tr("A gradient across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), GeneratorKind::WorldSpaceNormals => (tr("Surfaces facing along the world's axes."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + GeneratorKind::ThreeDDistance => (tr("A gradient around a point on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), }; // Wrapped rows: a long line must not widen the panel past its edge From 0ab43ea76c8fb9b1c89f70531b0187250a33476c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:37:20 +0000 Subject: [PATCH 104/153] Generators: 3D Linear Gradient between a start and an end point A new kind with the reference's controls: 3D Position Start and End (0 to 1 across the mesh's bounds, scaled evenly like 3D Distance; bottom to top by default), Balance, Contrast and Invert. The value is how far along from the start to the end a texel lies, balanced and contrasted like the global controls; on the test gun it matches the reference within 0.001 on every captured setting, as 3D Distance does. It shares 3D Distance's command module; each refuses the other's controls, and both refuse the earlier model's and the global ones. Commands only: picking the points on the mesh and the panel come with its mock. --- crates/compose/src/eval.rs | 9 +++- crates/compose/src/three_d_distance.rs | 15 +++++- .../tests/generator_three_d_distance.rs | 29 +++++++++-- crates/core/src/layer.rs | 26 ++++++++-- .../src/layer/linear_gradient_parameters.rs | 36 +++++++++++++ crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 6 +-- crates/engine/src/distance_params.rs | 50 ++++++++++++++----- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 29 ++++++++++- crates/ui-egui/src/generator_panel.rs | 3 ++ 13 files changed, 177 insertions(+), 37 deletions(-) create mode 100644 crates/core/src/layer/linear_gradient_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 29db5ca0..39178fd9 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3411,6 +3411,10 @@ impl<'a, 'b> Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::distance_value(&distance, position); } + if let Some(gradient) = generator.linear_gradient_controls() { + let position = self.uniform_position_input(generator); + return three_d_distance::linear_gradient_value(&gradient, position); + } let coords = self.coords(); @@ -3431,7 +3435,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance, _) => 0.0, + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, _) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3477,7 +3481,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear - | GeneratorKind::ThreeDDistance => 0.0, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => 0.0, } } diff --git a/crates/compose/src/three_d_distance.rs b/crates/compose/src/three_d_distance.rs index f6f909c8..d62524d4 100644 --- a/crates/compose/src/three_d_distance.rs +++ b/crates/compose/src/three_d_distance.rs @@ -1,6 +1,6 @@ -//! The 3D Distance generator: a gradient falling off with the distance from a point across the mesh's bounds +//! The 3D Distance and 3D Linear Gradient generators: gradients around a point and between two points across the mesh's bounds -use texturecraft_core::DistanceParameters; +use texturecraft_core::{DistanceParameters, GeneratorGlobal, LinearGradientParameters}; use texturecraft_geom::glam::Vec3; use crate::histogram_scan::histogram_scan; @@ -11,3 +11,14 @@ pub(crate) fn distance_value(distance: &DistanceParameters, position: Vec3) -> f let gradient = if distance.radius > 0.0 { (1.0 - from_point / distance.radius).clamp(0.0, 1.0) } else { 0.0 }; histogram_scan(gradient, distance.offset, distance.contrast) } + +/// Shortest start-to-end span the gradient divides by +const MIN_GRADIENT_LENGTH: f32 = 1e-6; + +/// The value at `position`: how far along from the start to the end it lies (0 at the start, 1 at the end), balanced and contrasted like a generator's global controls +pub(crate) fn linear_gradient_value(gradient: &LinearGradientParameters, position: Vec3) -> f32 { + let (start, end) = (Vec3::from(gradient.start), Vec3::from(gradient.end)); + let span = end - start; + let along = if span.length_squared() > MIN_GRADIENT_LENGTH { (position - start).dot(span) / span.length_squared() } else { 0.0 }; + GeneratorGlobal { balance: gradient.balance, contrast: gradient.contrast, ..GeneratorGlobal::default() }.apply(along.clamp(0.0, 1.0)) +} diff --git a/crates/compose/tests/generator_three_d_distance.rs b/crates/compose/tests/generator_three_d_distance.rs index 6b233479..35d4aaad 100644 --- a/crates/compose/tests/generator_three_d_distance.rs +++ b/crates/compose/tests/generator_three_d_distance.rs @@ -1,11 +1,11 @@ -//! The 3D Distance generator on a sphere: white at its point, falling off over its radius, slid by its offset +//! The 3D Distance and 3D Linear Gradient generators on a sphere: white at a point falling off over a radius, and a gradient between two points use std::sync::Arc; use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, - Source, TextureSet, + BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, LinearGradientParameters, Mask, + MaskBackground, Project, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -40,7 +40,11 @@ fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { /// The mask of a 3D Distance generator with `distance` alone over black at `texels` fn mask(fixture: &mut Fixture, distance: DistanceParameters, texels: &[(u32, u32)]) -> Vec { - let generator = Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }; + generator_mask(fixture, Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }, texels) +} + +/// The mask of `generator` alone over black at `texels` +fn generator_mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); @@ -94,3 +98,20 @@ fn a_larger_radius_reaches_further() { let large = total(mask(&mut fixture, DistanceParameters { radius: 1.2, ..DistanceParameters::default() }, &at)); assert!(large > small); } + +#[test] +fn the_linear_gradient_runs_from_its_start_to_its_end() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + let gradient = + |gradient: LinearGradientParameters| Generator { linear_gradient: Some(Box::new(gradient)), ..Generator::new(GeneratorKind::ThreeDLinearGradient) }; + + let upwards = generator_mask(&mut fixture, gradient(LinearGradientParameters::default()), &at); + let downwards = + generator_mask(&mut fixture, gradient(LinearGradientParameters { start: [0.5, 1.0, 0.5], end: [0.5, 0.0, 0.5], ..Default::default() }), &at); + for (((_, height), up), down) in texels.iter().zip(&upwards).zip(&downwards) { + assert!((up - (height * 0.5 + 0.5)).abs() < 0.02, "bottom to top across the sphere's height: {up} at {height}"); + assert!((up + down - 1.0).abs() < 1e-4, "swapping the points reverses it"); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 67e57460..bdbd77c4 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -24,6 +24,7 @@ mod filtering; mod generator_global; mod generator_grayscale; mod light_parameters; +mod linear_gradient_parameters; mod micro_curvature_type; mod micro_details; mod output_resolution; @@ -55,6 +56,7 @@ pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; pub use light_parameters::LightParameters; +pub use linear_gradient_parameters::LinearGradientParameters; pub use micro_curvature_type::MicroCurvatureType; pub use micro_details::MicroDetails; pub use output_resolution::OutputResolution; @@ -954,10 +956,12 @@ pub enum GeneratorKind { WorldSpaceNormals, /// White around a point across the mesh's bounds, fading with the distance from it ThreeDDistance, + /// A gradient from a start point to an end point across the mesh's bounds + ThreeDLinearGradient, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 10] = [ + pub const ALL: [GeneratorKind; 11] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -968,6 +972,7 @@ impl GeneratorKind { GeneratorKind::FiberGlassEdgeWear, GeneratorKind::WorldSpaceNormals, GeneratorKind::ThreeDDistance, + GeneratorKind::ThreeDLinearGradient, ]; pub fn label(self) -> &'static str { match self { @@ -981,6 +986,7 @@ impl GeneratorKind { GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", GeneratorKind::WorldSpaceNormals => "World Space Normals", GeneratorKind::ThreeDDistance => "3D Distance", + GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", } } @@ -997,12 +1003,13 @@ impl GeneratorKind { GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", GeneratorKind::ThreeDDistance => "ThreeDDistance", + GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; 3D Distance waits for its panel) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the 3D kinds wait for their panels) pub fn in_picker(self) -> bool { - !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance) + !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) } /// Whether the kind's result depends on its seed @@ -1017,7 +1024,7 @@ impl GeneratorKind { GeneratorKind::Curvature => &[BakedMap::Curvature], GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], - GeneratorKind::Position | GeneratorKind::ThreeDDistance => &[BakedMap::Position], + GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], } @@ -1025,7 +1032,7 @@ impl GeneratorKind { /// Whether the kind was added with the reference's controls only, so it never computes with level, softness and noise pub fn has_no_earlier_model(self) -> bool { - matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance) + matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) } pub fn parse(s: &str) -> Option { @@ -1094,6 +1101,9 @@ pub struct Generator { /// The 3D Distance generator's controls (None on every other kind); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub distance: Option>, + /// The 3D Linear Gradient generator's controls (None on every other kind); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub linear_gradient: Option>, } impl Serialize for Generator { @@ -1140,6 +1150,11 @@ impl Generator { self.distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDDistance).then(DistanceParameters::default)) } + /// The 3D Linear Gradient controls the generator computes with: its own, else the defaults on a 3D Linear Gradient generator + pub fn linear_gradient_controls(&self) -> Option { + self.linear_gradient.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDLinearGradient).then(LinearGradientParameters::default)) + } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None pub fn detail_in_use(&self) -> Option { let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); @@ -1207,6 +1222,7 @@ impl Generator { grunge: None, micro: None, distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), + linear_gradient: (kind == GeneratorKind::ThreeDLinearGradient).then(Box::default), } } diff --git a/crates/core/src/layer/linear_gradient_parameters.rs b/crates/core/src/layer/linear_gradient_parameters.rs new file mode 100644 index 00000000..2526da80 --- /dev/null +++ b/crates/core/src/layer/linear_gradient_parameters.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; + +/// The 3D Linear Gradient generator's controls: black at the start point, white at the end point, across the mesh's bounds +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LinearGradientParameters { + /// Where the gradient is black, 0..1 across the mesh's bounds on each axis + pub start: [f32; 3], + /// Where the gradient is white + pub end: [f32; 3], + /// Shifts the gradient darker (below 0.5) or brighter (above 0.5) + pub balance: f32, + /// Narrows the gradient around its middle (0..1; 1 a hard step) + pub contrast: f32, +} + +impl LinearGradientParameters { + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> LinearGradientParameters { + let defaults = LinearGradientParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + LinearGradientParameters { + start: std::array::from_fn(|axis| unit(self.start[axis], defaults.start[axis])), + end: std::array::from_fn(|axis| unit(self.end[axis], defaults.end[axis])), + balance: unit(self.balance, defaults.balance), + contrast: unit(self.contrast, defaults.contrast), + } + } +} + +impl Default for LinearGradientParameters { + /// The reference app's defaults: bottom to top through the bounds' centre + fn default() -> LinearGradientParameters { + LinearGradientParameters { start: [0.5, 0.0, 0.5], end: [0.5, 1.0, 0.5], balance: 0.5, contrast: 0.0 } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index a0cbc4ff..377e2d22 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -74,7 +74,8 @@ impl MicroDetails { | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals - | GeneratorKind::ThreeDDistance => None, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 322fd54c..18837e45 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -40,7 +40,8 @@ impl SectionParameters { | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear - | GeneratorKind::ThreeDDistance => None, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index b354a95f..8937561c 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -59,7 +59,8 @@ impl WearParameters { | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals - | GeneratorKind::ThreeDDistance => None, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index bd02feff..0206af63 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,11 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, - OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, - hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 6e16cbda..2aa370ff 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,30 +1,36 @@ -//! The 3D Distance controls `effect.add.generator` and `effect.set` take +//! The 3D Distance and 3D Linear Gradient controls `effect.add.generator` and `effect.set` take use serde_json::Value; use texturecraft_core::{Generator, GeneratorKind}; use crate::Result; -use crate::commands::{bad, f32p}; +use crate::commands::{bad, color_param, f32p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; -/// The controls of the earlier model and the global adjustments, which 3D Distance doesn't have +/// The 3D Linear Gradient controls: its start and end points ([x, y, z] across the mesh's bounds), balance and contrast +pub const LINEAR_GRADIENT_KEYS: [&str; 4] = ["gradientStart", "gradientEnd", "gradientBalance", "gradientContrast"]; + +/// The controls of the earlier model and the global adjustments, which the 3D kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; -/// The 3D Distance controls in `params`, refused on other kinds; 3D Distance refuses the earlier model's controls +/// The 3D Distance and 3D Linear Gradient controls in `params`, each refused on other kinds; both kinds refuse the earlier model's and the global controls pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { - if generator.kind != GeneratorKind::ThreeDDistance { - return match first_given(params, &DISTANCE_KEYS) { - Some(key) => Err(bad(command, format!("{} has no `{key}`: only 3D Distance has it", generator.kind.label()))), - None => Ok(()), - }; + let kind = generator.kind; + for (keys, owner) in [(&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient)] { + if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { + return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); + } + } + if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) { + return Ok(()); } if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { - return Err(bad( - command, - format!("3D Distance has no `{key}`: its controls are distanceX, distanceY, distanceZ, distanceRadius, distanceOffset and distanceContrast"), - )); + return Err(bad(command, format!("{} has no `{key}`: it has its own controls only", kind.label()))); + } + if kind == GeneratorKind::ThreeDLinearGradient { + return linear_gradient_from(command, params, generator); } let mut distance = generator.distance_controls().unwrap_or_default(); @@ -42,6 +48,24 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - Ok(()) } +/// The 3D Linear Gradient controls in `params` (the generator is one) +fn linear_gradient_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let mut gradient = generator.linear_gradient_controls().unwrap_or_default(); + if let Some(start) = color_param(command, params, "gradientStart")? { + gradient.start = start; + } + if let Some(end) = color_param(command, params, "gradientEnd")? { + gradient.end = end; + } + for (key, value) in [("gradientBalance", &mut gradient.balance), ("gradientContrast", &mut gradient.contrast)] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.linear_gradient = Some(Box::new(gradient.clamped())); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index fd9b3466..78a407b7 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 07f0bdb8..8c5f0da5 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,7 +1,7 @@ -//! The 3D Distance generator through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point +//! The 3D Distance and 3D Linear Gradient generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point use serde_json::{Value, json}; -use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId}; +use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; use texturecraft_engine::{Session, execute}; fn session() -> Session { @@ -59,3 +59,28 @@ fn swapping_onto_three_d_distance_drops_the_earlier_offset() { assert_eq!(swapped.offset, 0.0); assert_eq!(swapped.distance_controls(), Some(DistanceParameters::default())); } + +#[test] +fn three_d_linear_gradient_takes_its_points_balance_and_contrast() { + let mut session = session(); + let params = + json!({"generator": "3D Linear Gradient", "gradientStart": [0.0, 0.5, 0.5], "gradientEnd": [1.0, 0.5, 2.0], "gradientBalance": 0.25, "invert": true}); + let effect = add(&mut session, params); + + let made = generator(&session, effect); + assert_eq!(made.kind, GeneratorKind::ThreeDLinearGradient); + let expected = LinearGradientParameters { start: [0.0, 0.5, 0.5], end: [1.0, 0.5, 1.0], balance: 0.25, contrast: 0.0 }; + assert_eq!(made.linear_gradient_controls(), Some(expected), "points stay within the bounds"); + assert!(made.invert && !made.on_earlier_model()); +} + +#[test] +fn each_3d_kind_refuses_the_others_controls() { + let mut session = session(); + let gradient = add(&mut session, json!({"generator": "3dLinearGradient"})); + let distance = add(&mut session, json!({"generator": "3dDistance"})); + + assert!(execute(&mut session, "effect.set", &json!({"effect": gradient, "distanceRadius": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": distance, "gradientBalance": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": gradient, "level": 0.5})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 22505eb3..fa9df7b1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -96,6 +96,9 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), GeneratorKind::WorldSpaceNormals => (tr("Surfaces facing along the world's axes."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), GeneratorKind::ThreeDDistance => (tr("A gradient around a point on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::ThreeDLinearGradient => { + (tr("A gradient between two points on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]) + } }; // Wrapped rows: a long line must not widen the panel past its edge From 9562b30c2b12fb338446ba4daf6f308331812270 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:05:17 +0000 Subject: [PATCH 105/153] Generators: UV Border Distance, white at the UV islands' borders fading inwards A new kind with the reference's controls: Distance (1 reaches about half a UV tile in), Smoothness, Balance, Contrast and Invert. Each covered texel's exact Euclidean distance to the nearest uncovered texel of its UV tile (the tile's edge counting as a border) sets a linear gradient; Smoothness blurs it with the empty space around the islands, softening the borders towards black; balance and contrast act like the global controls. The gradient is built once per UV layout and setting and cached. On the test gun it matches the reference within 0.002 to 0.011 mean error on every captured setting. Commands only; the picker leaves it out until its panel is designed. --- crates/compose/src/eval.rs | 11 +- crates/compose/src/generator_maps.rs | 6 +- crates/compose/src/lib.rs | 1 + crates/compose/src/uv_border_distance.rs | 217 ++++++++++++++++++ .../tests/generator_uv_border_distance.rs | 80 +++++++ crates/core/src/layer.rs | 28 ++- .../src/layer/border_distance_parameters.rs | 36 +++ crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 32 ++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 17 +- crates/ui-egui/src/generator_panel.rs | 1 + 15 files changed, 423 insertions(+), 19 deletions(-) create mode 100644 crates/compose/src/uv_border_distance.rs create mode 100644 crates/compose/tests/generator_uv_border_distance.rs create mode 100644 crates/core/src/layer/border_distance_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 39178fd9..ceeeb6a0 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -44,6 +44,7 @@ use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::texture_layer; use crate::three_d_distance; +use crate::uv_border_distance; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use crate::wear; use crate::wear_inputs::WearInputs; @@ -3411,6 +3412,11 @@ impl<'a, 'b> Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::distance_value(&distance, position); } + if let Some(border) = generator.border_distance_controls() { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); + return uv_border_distance::border_value(&border, gradient); + } if let Some(gradient) = generator.linear_gradient_controls() { let position = self.uniform_position_input(generator); return three_d_distance::linear_gradient_value(&gradient, position); @@ -3435,7 +3441,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, _) => 0.0, + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance, _) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3482,7 +3488,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => 0.0, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => 0.0, } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 6bc18477..613e7e3a 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -7,6 +7,7 @@ use texturecraft_core::{BakedMap, Generator, MicroDetails}; use crate::curvature_sizes::CurvatureSizes; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; +use crate::uv_border_distance::border_gradient; /// What a generator reads beyond its texel: built once per map and settings, shared by every tile #[derive(Clone, Default)] @@ -17,6 +18,8 @@ pub(crate) struct GeneratorMaps { pub micro_curvature: Option>, /// What its micro details multiply its occlusion by pub micro_occlusion: Option>, + /// The UV Border Distance gradient at every working texel + pub border_gradient: Option>>, } impl GeneratorMaps { @@ -29,6 +32,7 @@ impl GeneratorMaps { Some(micro) => CurvatureSizes::of_map(inp, µ.curvature, needed), None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), }; - GeneratorMaps { sizes, micro_curvature, micro_occlusion } + let border_gradient = generator.border_distance_controls().map(|border| border_gradient(inp, &border)); + GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient } } } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index cf4ed85e..24c3f9e5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -52,6 +52,7 @@ pub mod tile_length; mod tile_pattern; mod tile_random_stream; mod timber; +mod uv_border_distance; pub mod warp; mod warp_source_sample; mod warp_texel; diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs new file mode 100644 index 00000000..50033fcd --- /dev/null +++ b/crates/compose/src/uv_border_distance.rs @@ -0,0 +1,217 @@ +//! The UV Border Distance generator: how far each texel lies inside its UV island, as a gradient built once per UV layout and settings + +use std::sync::{Arc, Mutex}; + +use rayon::prelude::*; +use texturecraft_core::{BlockScales, BorderDistanceParameters, GeneratorGlobal}; + +use crate::eval::{Inputs, blur}; + +/// How far in the gradient reaches at Distance 1, in UV units (fitted: about half a UV tile) +const REACH_PER_DISTANCE: f32 = 0.4936; + +/// The blur at Smoothness 1, as a gaussian sigma in texels of a 2K UV tile (fitted) +const SMOOTHNESS_SIGMA_2K: f32 = 45.0; + +/// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// Cached gradients; one per layout and setting a stack shows at a time +const CACHE_ENTRIES: usize = 8; + +/// Texels between the samples a layout's fingerprint reads +const FINGERPRINT_STRIDE: usize = 997; + +/// What a gradient was built from: the working layout (size, coverage fingerprint, UV tile block, tile scales) and the settings' bits +#[derive(Clone, PartialEq)] +struct Key { + size: (u32, u32), + fingerprint: u64, + block: (u32, u32), + scales: BlockScales, + settings: [u32; 2], +} + +static CACHE: Mutex>)>> = Mutex::new(Vec::new()); + +/// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) +pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) -> Arc> { + let gbuf = inp.gbuf; + let size = (gbuf.width, gbuf.height); + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); + let block = (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))); + let fingerprint = gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)); + let key = Key { size, fingerprint, block, scales: inp.block_scales.clone(), settings: [border.distance.to_bits(), border.smoothness.to_bits()] }; + + let cached = { + let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.iter().find(|(cached, _)| *cached == key).map(|(_, gradient)| gradient.clone()) + }; + if let Some(gradient) = cached { + return gradient; + } + + // Built without the cache locked: the build runs parallel work + let gradient = Arc::new(build(inp, border, block)); + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(cached, _)| *cached != key); + cache.push((key, gradient.clone())); + let excess = cache.len().saturating_sub(CACHE_ENTRIES); + cache.drain(..excess); + gradient +} + +/// The value at a working texel: the gradient balanced, contrasted and inverted +pub(crate) fn border_value(border: &BorderDistanceParameters, gradient: f32) -> f32 { + GeneratorGlobal { balance: border.balance, contrast: border.contrast, ..GeneratorGlobal::default() }.apply(gradient) +} + +fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> Vec { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + + // Every covered texel's distance to the nearest uncovered one, within its UV tile + let distances = border_distances(gbuf, (width, height), block); + + let mut gradient: Vec = (0..width * height) + .into_par_iter() + .map(|texel| { + if !gbuf.covered(texel as usize) { + return 0.0; + } + let (x, y) = (texel % width, texel / width); + let tile_texels = block.0 as f32 * inp.block_scales.at(x, y); + let to_border = distances.get(texel as usize).copied().unwrap_or(0.0); + let reach = border.distance * REACH_PER_DISTANCE * tile_texels; + if reach > 0.0 { (1.0 - to_border / reach).clamp(0.0, 1.0) } else { 0.0 } + }) + .collect(); + + // Smoothness blurs the gradient with the empty space around the islands, so their borders soften towards black + let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * block.0 as f32 / REFERENCE_TILE_TEXELS; + let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize; + if radius > 0 { + blur_blocks(&mut gradient, (width, height), block, radius); + for (value, texel) in gradient.iter_mut().zip(0..) { + if !gbuf.covered(texel) { + *value = 0.0; + } + } + } + gradient +} + +/// Each texel's Euclidean distance in texels to the nearest uncovered texel of its UV tile block, the space past the block's edges counting as uncovered +fn border_distances(gbuf: &texturecraft_geom::UvGBuffer, (width, height): (u32, u32), block: (u32, u32)) -> Vec { + let mut squared = vec![0.0f32; (width * height) as usize]; + for top in (0..height).step_by(block.1 as usize) { + for left in (0..width).step_by(block.0 as usize) { + let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); + let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; + + // A ring of uncovered texels around the block, then the exact transform along rows and columns + let (padded_columns, padded_rows) = (columns + 2, rows + 2); + let mut field: Vec = (0..padded_rows) + .flat_map(|row| (0..padded_columns).map(move |column| (column, row))) + .map(|(column, row)| { + let inside = (1..=columns).contains(&column) && (1..=rows).contains(&row); + if inside && gbuf.covered(index(column - 1, row - 1)) { f32::INFINITY } else { 0.0 } + }) + .collect(); + field.par_chunks_mut(padded_columns).for_each(squared_distance_line); + let mut transposed: Vec = (0..padded_columns * padded_rows) + .map(|texel| field.get((texel % padded_rows) * padded_columns + texel / padded_rows).copied().unwrap_or(0.0)) + .collect(); + transposed.par_chunks_mut(padded_rows).for_each(squared_distance_line); + + for row in 0..rows { + for column in 0..columns { + let value = transposed.get((column + 1) * padded_rows + row + 1).copied().unwrap_or(0.0); + if let Some(target) = squared.get_mut(index(column, row)) { + *target = value; + } + } + } + } + } + squared.into_iter().map(f32::sqrt).collect() +} + +/// The squared distance transform of one line in place (Felzenszwalb and Huttenlocher's lower envelope of parabolas); `line` holds 0 at sources and infinity elsewhere +fn squared_distance_line(line: &mut [f32]) { + let length = line.len(); + let input = line.to_vec(); + let finite: Vec = (0..length).filter(|index| input.get(*index).is_some_and(|value| value.is_finite())).collect(); + if finite.is_empty() { + return; + } + + // Parabola vertices and the boundaries between them + let value_at = |index: usize| input.get(index).copied().unwrap_or(f32::INFINITY); + let intersection = |a: usize, b: usize| ((value_at(b) + (b * b) as f32) - (value_at(a) + (a * a) as f32)) / (2.0 * (b as f32 - a as f32)); + let mut vertices: Vec = Vec::with_capacity(finite.len()); + let mut boundaries: Vec = Vec::with_capacity(finite.len() + 1); + for &index in &finite { + while let (Some(&last), Some(&start)) = (vertices.last(), boundaries.last()) { + if intersection(last, index) <= start { + vertices.pop(); + boundaries.pop(); + } else { + break; + } + } + let start = vertices.last().map_or(f32::NEG_INFINITY, |&last| intersection(last, index)); + vertices.push(index); + boundaries.push(start); + } + + let mut current = 0; + for (index, value) in line.iter_mut().enumerate() { + while boundaries.get(current + 1).is_some_and(|next| *next < index as f32) { + current += 1; + } + let vertex = vertices.get(current).copied().unwrap_or(index); + let offset = index as f32 - vertex as f32; + *value = offset * offset + value_at(vertex); + } +} + +/// `data` blurred one UV tile block at a time, reading black past each block's edges +fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius: usize) { + for top in (0..height).step_by(block.1 as usize) { + for left in (0..width).step_by(block.0 as usize) { + let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); + let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; + let mut values: Vec = (0..rows) + .flat_map(|row| (0..columns).map(move |column| (column, row))) + .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) + .collect(); + blur(&mut values, columns, rows, radius); + for (offset, value) in values.into_iter().enumerate() { + if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { + *target = value; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_line_reads_the_squared_distance_to_its_nearest_source() { + let mut line = [0.0, f32::INFINITY, f32::INFINITY, f32::INFINITY, f32::INFINITY, 0.0, f32::INFINITY]; + squared_distance_line(&mut line); + assert_eq!(line, [0.0, 1.0, 4.0, 4.0, 1.0, 0.0, 1.0]); + } + + #[test] + fn a_line_without_sources_stays_unreached() { + let mut line = [f32::INFINITY; 3]; + squared_distance_line(&mut line); + assert!(line.iter().all(|value| value.is_infinite())); + } +} diff --git a/crates/compose/tests/generator_uv_border_distance.rs b/crates/compose/tests/generator_uv_border_distance.rs new file mode 100644 index 00000000..db5b5db6 --- /dev/null +++ b/crates/compose/tests/generator_uv_border_distance.rs @@ -0,0 +1,80 @@ +//! The UV Border Distance generator on a plane filling its UV tile: white at the tile's edge, fading inwards over its distance, softened by its smoothness + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BorderDistanceParameters, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, + TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 64; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, +} + +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer } +} + +/// The middle row's values, left edge to centre +fn row(fixture: &mut Fixture, border: BorderDistanceParameters) -> Vec { + let generator = Generator { border_distance: Some(Box::new(border)), ..Generator::new(GeneratorKind::UvBorderDistance) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + let texels: Vec<(u32, u32)> = (0..RES / 2).map(|x| (x, RES / 2)).collect(); + mask_at(&inputs, fixture.layer, &texels).unwrap() +} + +#[test] +fn the_border_is_white_and_the_inside_fades_to_black() { + let mut fixture = fixture(); + let values = row(&mut fixture, BorderDistanceParameters { distance: 0.5, ..BorderDistanceParameters::default() }); + + assert!(values[0] > 0.9, "the edge, a texel in: {}", values[0]); + assert!(values.windows(2).all(|pair| pair[1] <= pair[0]), "falling inwards: {values:?}"); + assert!(*values.last().unwrap() < 0.05, "half a tile in is black at distance 0.5"); +} + +#[test] +fn a_larger_distance_reaches_further_in() { + let mut fixture = fixture(); + let near = row(&mut fixture, BorderDistanceParameters { distance: 0.1, ..BorderDistanceParameters::default() }); + let far = row(&mut fixture, BorderDistanceParameters { distance: 0.6, ..BorderDistanceParameters::default() }); + + assert!(far.iter().sum::() > near.iter().sum::() + 1.0); +} + +#[test] +fn smoothness_darkens_the_edge_with_the_space_around_the_island() { + let mut fixture = fixture(); + let sharp = row(&mut fixture, BorderDistanceParameters::default()); + let smooth = row(&mut fixture, BorderDistanceParameters { smoothness: 1.0, ..BorderDistanceParameters::default() }); + + assert!(smooth[0] < sharp[0] - 0.2, "{} vs {}", smooth[0], sharp[0]); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index bdbd77c4..f19b2ec3 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -15,6 +15,7 @@ use crate::{ mod anchored_micro_detail; mod axis_blend; mod axis_layer; +mod border_distance_parameters; mod curvature_detail; mod curvature_mode; mod decal_flip; @@ -47,6 +48,7 @@ mod wear_parameters; use anchored_micro_detail::AnchoredMicroDetail; pub use axis_blend::AxisBlend; pub use axis_layer::AxisLayer; +pub use border_distance_parameters::BorderDistanceParameters; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; @@ -958,10 +960,12 @@ pub enum GeneratorKind { ThreeDDistance, /// A gradient from a start point to an end point across the mesh's bounds ThreeDLinearGradient, + /// White at the UV islands' borders, fading towards their insides + UvBorderDistance, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 11] = [ + pub const ALL: [GeneratorKind; 12] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -973,6 +977,7 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals, GeneratorKind::ThreeDDistance, GeneratorKind::ThreeDLinearGradient, + GeneratorKind::UvBorderDistance, ]; pub fn label(self) -> &'static str { match self { @@ -987,6 +992,7 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => "World Space Normals", GeneratorKind::ThreeDDistance => "3D Distance", GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", + GeneratorKind::UvBorderDistance => "UV Border Distance", } } @@ -1004,12 +1010,13 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", GeneratorKind::ThreeDDistance => "ThreeDDistance", GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", + GeneratorKind::UvBorderDistance => "UvBorderDistance", } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the 3D kinds wait for their panels) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the newest kinds wait for their panels) pub fn in_picker(self) -> bool { - !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) + !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) } /// Whether the kind's result depends on its seed @@ -1027,12 +1034,16 @@ impl GeneratorKind { GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], + GeneratorKind::UvBorderDistance => &[], } } /// Whether the kind was added with the reference's controls only, so it never computes with level, softness and noise pub fn has_no_earlier_model(self) -> bool { - matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) + matches!( + self, + GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance + ) } pub fn parse(s: &str) -> Option { @@ -1104,6 +1115,9 @@ pub struct Generator { /// The 3D Linear Gradient generator's controls (None on every other kind); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub linear_gradient: Option>, + /// The UV Border Distance generator's controls (None on every other kind); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub border_distance: Option>, } impl Serialize for Generator { @@ -1155,6 +1169,11 @@ impl Generator { self.linear_gradient.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDLinearGradient).then(LinearGradientParameters::default)) } + /// The UV Border Distance controls the generator computes with: its own, else the defaults on a UV Border Distance generator + pub fn border_distance_controls(&self) -> Option { + self.border_distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::UvBorderDistance).then(BorderDistanceParameters::default)) + } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None pub fn detail_in_use(&self) -> Option { let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); @@ -1223,6 +1242,7 @@ impl Generator { micro: None, distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), linear_gradient: (kind == GeneratorKind::ThreeDLinearGradient).then(Box::default), + border_distance: (kind == GeneratorKind::UvBorderDistance).then(Box::default), } } diff --git a/crates/core/src/layer/border_distance_parameters.rs b/crates/core/src/layer/border_distance_parameters.rs new file mode 100644 index 00000000..2d55c45b --- /dev/null +++ b/crates/core/src/layer/border_distance_parameters.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; + +/// The UV Border Distance generator's controls: white at the UV islands' borders, fading towards their insides +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BorderDistanceParameters { + /// How far in from the border the gradient reaches (0..1; 1 is half a UV tile) + pub distance: f32, + /// Softens the gradient, the empty space around the islands darkening their borders (0..1) + pub smoothness: f32, + /// Shifts the gradient darker (below 0.5) or brighter (above 0.5) + pub balance: f32, + /// Narrows the gradient around its middle (0..1; 1 a hard step) + pub contrast: f32, +} + +impl BorderDistanceParameters { + /// Every value brought into 0..1, non-finite ones to the defaults + pub fn clamped(self) -> BorderDistanceParameters { + let defaults = BorderDistanceParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + BorderDistanceParameters { + distance: unit(self.distance, defaults.distance), + smoothness: unit(self.smoothness, defaults.smoothness), + balance: unit(self.balance, defaults.balance), + contrast: unit(self.contrast, defaults.contrast), + } + } +} + +impl Default for BorderDistanceParameters { + /// The reference app's defaults + fn default() -> BorderDistanceParameters { + BorderDistanceParameters { distance: 0.1, smoothness: 0.0, balance: 0.5, contrast: 0.0 } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 377e2d22..4fdfe6f5 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -75,7 +75,8 @@ impl MicroDetails { | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => None, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 18837e45..c0c64f41 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -41,7 +41,8 @@ impl SectionParameters { | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => None, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 8937561c..4f10a9c6 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -60,7 +60,8 @@ impl WearParameters { | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => None, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 0206af63..fcbd7228 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 2aa370ff..5bab2b11 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,4 +1,4 @@ -//! The 3D Distance and 3D Linear Gradient controls `effect.add.generator` and `effect.set` take +//! The controls of 3D Distance, 3D Linear Gradient and UV Border Distance that `effect.add.generator` and `effect.set` take use serde_json::Value; use texturecraft_core::{Generator, GeneratorKind}; @@ -12,18 +12,25 @@ pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "di /// The 3D Linear Gradient controls: its start and end points ([x, y, z] across the mesh's bounds), balance and contrast pub const LINEAR_GRADIENT_KEYS: [&str; 4] = ["gradientStart", "gradientEnd", "gradientBalance", "gradientContrast"]; -/// The controls of the earlier model and the global adjustments, which the 3D kinds don't have +/// The UV Border Distance controls +pub const BORDER_DISTANCE_KEYS: [&str; 4] = ["borderDistance", "borderSmoothness", "borderBalance", "borderContrast"]; + +/// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; -/// The 3D Distance and 3D Linear Gradient controls in `params`, each refused on other kinds; both kinds refuse the earlier model's and the global controls +/// The 3D Distance, 3D Linear Gradient and UV Border Distance controls in `params`, each refused on other kinds; these kinds refuse the earlier model's and the global controls pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let kind = generator.kind; - for (keys, owner) in [(&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient)] { + for (keys, owner) in [ + (&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), + (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient), + (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), + ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); } } - if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) { + if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) { return Ok(()); } if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { @@ -32,6 +39,21 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::ThreeDLinearGradient { return linear_gradient_from(command, params, generator); } + if kind == GeneratorKind::UvBorderDistance { + let mut border = generator.border_distance_controls().unwrap_or_default(); + for (key, value) in [ + ("borderDistance", &mut border.distance), + ("borderSmoothness", &mut border.smoothness), + ("borderBalance", &mut border.balance), + ("borderContrast", &mut border.contrast), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.border_distance = Some(Box::new(border.clamped())); + return Ok(()); + } let mut distance = generator.distance_controls().unwrap_or_default(); for (axis, key) in DISTANCE_KEYS.iter().take(3).enumerate() { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 78a407b7..393e8a0b 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 8c5f0da5..a1508452 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,7 +1,7 @@ -//! The 3D Distance and 3D Linear Gradient generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point +//! The 3D Distance, 3D Linear Gradient and UV Border Distance generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point use serde_json::{Value, json}; -use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; +use texturecraft_engine::core::{BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; use texturecraft_engine::{Session, execute}; fn session() -> Session { @@ -84,3 +84,16 @@ fn each_3d_kind_refuses_the_others_controls() { assert!(execute(&mut session, "effect.set", &json!({"effect": distance, "gradientBalance": 0.5})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": gradient, "level": 0.5})).is_err()); } + +#[test] +fn uv_border_distance_takes_its_controls_and_refuses_the_others() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "UV Border Distance", "borderDistance": 0.3, "borderSmoothness": 2.0, "borderContrast": 0.4})); + + let expected = BorderDistanceParameters { distance: 0.3, smoothness: 1.0, contrast: 0.4, ..BorderDistanceParameters::default() }; + assert_eq!(generator(&session, effect).border_distance_controls(), Some(expected)); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "distanceRadius": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "softness": 0.5})).is_err()); + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "borderDistance": 0.5})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index fa9df7b1..0139894f 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -99,6 +99,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::ThreeDLinearGradient => { (tr("A gradient between two points on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]) } + GeneratorKind::UvBorderDistance => (tr("A gradient in from the UV islands' borders."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; // Wrapped rows: a long line must not widen the panel past its edge From 13062a8efdb14153e5f7d50dc13ac6e1e5a61d22 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:27:14 +0000 Subject: [PATCH 106/153] Generators: Grayscale Conversion; the kinds with only their own controls share one field Grayscale Conversion is a new kind with the reference's controls: an image (effect.set input: image; an empty slot reads black) repeated Tile times across the UV square and turned by Rotation about its centre, made gray by one of the eight conversions Use Texture already has, then Balance, Contrast and Invert like the global controls. Safe Rotation turns in quarter turns only so the image keeps tiling; that rule is inferred, as the reference captures had no image plugged in. Its image counts as a used resource. 3D Distance, 3D Linear Gradient, UV Border Distance and Grayscale Conversion now keep their controls in one boxed KindControls field (one variant per kind) instead of a field each, so a generator effect stays small as kinds are added; their behaviour is unchanged. Commands only; the picker leaves the new kinds out until their panels are designed. --- crates/compose/src/eval.rs | 36 +++++-- .../tests/generator_grayscale_conversion.rs | 102 ++++++++++++++++++ .../tests/generator_three_d_distance.rs | 12 ++- .../tests/generator_uv_border_distance.rs | 6 +- crates/core/src/layer.rs | 82 ++++++++++---- .../layer/grayscale_conversion_parameters.rs | 59 ++++++++++ crates/core/src/layer/kind_controls.rs | 44 ++++++++ crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 47 ++++++-- crates/engine/src/mask_cmds.rs | 24 ++++- .../tests/it/generator_three_d_distance.rs | 27 ++++- crates/ui-egui/src/generator_panel.rs | 1 + 15 files changed, 397 insertions(+), 54 deletions(-) create mode 100644 crates/compose/tests/generator_grayscale_conversion.rs create mode 100644 crates/core/src/layer/grayscale_conversion_parameters.rs create mode 100644 crates/core/src/layer/kind_controls.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ceeeb6a0..2d725331 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -12,11 +12,7 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, - CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, - PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, - TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -1952,6 +1948,9 @@ fn filter_region( /// What a generator's texture or custom grunge reads with nothing in its slot const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); +/// The step Safe Rotation turns a Grayscale Conversion image by, so it keeps tiling seamlessly +const QUARTER_TURN_DEGREES: f32 = 90.0; + /// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray const GENERATOR_STAGE_COMPONENTS: usize = 3; @@ -3412,6 +3411,9 @@ impl<'a, 'b> Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::distance_value(&distance, position); } + if let Some(grayscale) = generator.grayscale_controls() { + return self.grayscale_conversion(&grayscale); + } if let Some(border) = generator.border_distance_controls() { let texel = (self.y * self.inp.gbuf.width + self.x) as usize; let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); @@ -3441,7 +3443,9 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance, _) => 0.0, + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion, _) => { + 0.0 + } }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3489,7 +3493,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => 0.0, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => 0.0, } } @@ -3501,6 +3506,23 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// The Grayscale Conversion generator at this texel: its image tiled and turned about the UV square's centre, made gray, balanced and contrasted + fn grayscale_conversion(&mut self, grayscale: &GrayscaleConversionParameters) -> f32 { + let degrees = if grayscale.safe_rotation { (grayscale.rotation / QUARTER_TURN_DEGREES).round() * QUARTER_TURN_DEGREES } else { grayscale.rotation }; + let (sin, cos) = degrees.to_radians().sin_cos(); + let centred = self.coords().uv - Vec2::splat(0.5); + let at = Vec2::new(centred.x * cos - centred.y * sin, centred.x * sin + centred.y * cos) * grayscale.tile + Vec2::splat(0.5); + let rgb = match grayscale.source.as_ref().unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => self.inp.images.get(name).map_or([0.0; 3], |image| { + let [red, green, blue, _] = image.sample(at.x, at.y); + [red, green, blue] + }), + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + let gray = grayscale.grayscale.gray(rgb).clamp(0.0, 1.0); + GeneratorGlobal { balance: grayscale.balance, contrast: grayscale.contrast, ..GeneratorGlobal::default() }.apply(gray) + } + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds scaled evenly: the longest side spans 0..1, the others centred on 0.5 fn uniform_position_input(&mut self, generator: &Generator) -> Vec3 { if let Some(source) = generator.inputs.get(&BakedMap::Position) { diff --git a/crates/compose/tests/generator_grayscale_conversion.rs b/crates/compose/tests/generator_grayscale_conversion.rs new file mode 100644 index 00000000..ee3e79dd --- /dev/null +++ b/crates/compose/tests/generator_grayscale_conversion.rs @@ -0,0 +1,102 @@ +//! The Grayscale Conversion generator on a plane filling its UV tile: its image turned gray by the chosen type, tiled, turned and balanced + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Generator, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, KindControls, Layer, LayerId, LayerKind, + Mask, MaskBackground, Project, Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 64; + +/// Width of the image: its left half red, its right half blue +const IMAGE_WIDTH: u32 = 16; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + images: ImageStore, +} + +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let texel = |index: u32| if index % IMAGE_WIDTH < IMAGE_WIDTH / 2 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] }; + let image = ImageRes::new(IMAGE_WIDTH, IMAGE_WIDTH, (0..IMAGE_WIDTH * IMAGE_WIDTH).map(texel).collect(), false); + Fixture { project, mesh, gbuf, layer, images: [("split".to_string(), Arc::new(image))].into() } +} + +/// The values along a row a quarter of the way down, left to right +fn row(fixture: &mut Fixture, grayscale: GrayscaleConversionParameters) -> Vec { + let generator = Generator { + controls: Some(Box::new(KindControls::Grayscale(GrayscaleConversionParameters { source: Some(Source::image("split")), ..grayscale }))), + ..Generator::new(GeneratorKind::GrayscaleConversion) + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + let texels: Vec<(u32, u32)> = (0..RES).map(|x| (x, RES / 4)).collect(); + mask_at(&inputs, fixture.layer, &texels).unwrap() +} + +fn red_channel() -> GrayscaleConversionParameters { + GrayscaleConversionParameters { grayscale: GeneratorGrayscale::Red, ..GrayscaleConversionParameters::default() } +} + +/// How many times the row changes between dark and light +fn edges(values: &[f32]) -> usize { + values.windows(2).filter(|pair| (pair[0] > 0.5) != (pair[1] > 0.5)).count() +} + +#[test] +fn the_type_picks_what_turns_white() { + let mut fixture = fixture(); + let red = row(&mut fixture, red_channel()); + let blue = row(&mut fixture, GrayscaleConversionParameters { grayscale: GeneratorGrayscale::Blue, ..GrayscaleConversionParameters::default() }); + + assert!(red[2] > 0.9 && red[RES as usize - 3] < 0.1, "red on the left: {red:?}"); + assert!(blue[2] < 0.1 && blue[RES as usize - 3] > 0.9, "blue on the right"); +} + +#[test] +fn tile_repeats_the_image_and_a_half_turn_mirrors_it() { + let mut fixture = fixture(); + let once = row(&mut fixture, red_channel()); + let four = row(&mut fixture, GrayscaleConversionParameters { tile: 4.0, ..red_channel() }); + let turned = row(&mut fixture, GrayscaleConversionParameters { rotation: 180.0, ..red_channel() }); + + assert!(edges(&four) > edges(&once) + 4, "{} vs {}", edges(&four), edges(&once)); + assert!(turned[2] < 0.1 && turned[RES as usize - 3] > 0.9, "the red half swaps sides"); +} + +#[test] +fn safe_rotation_turns_by_quarter_turns_only() { + let mut fixture = fixture(); + let snapped = row(&mut fixture, GrayscaleConversionParameters { rotation: 170.0, ..red_channel() }); + let half = row(&mut fixture, GrayscaleConversionParameters { rotation: 180.0, ..red_channel() }); + + assert_eq!(snapped, half); +} diff --git a/crates/compose/tests/generator_three_d_distance.rs b/crates/compose/tests/generator_three_d_distance.rs index 35d4aaad..db833c3b 100644 --- a/crates/compose/tests/generator_three_d_distance.rs +++ b/crates/compose/tests/generator_three_d_distance.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, LinearGradientParameters, Mask, - MaskBackground, Project, Source, TextureSet, + BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, + LinearGradientParameters, Mask, MaskBackground, Project, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -40,7 +40,7 @@ fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { /// The mask of a 3D Distance generator with `distance` alone over black at `texels` fn mask(fixture: &mut Fixture, distance: DistanceParameters, texels: &[(u32, u32)]) -> Vec { - generator_mask(fixture, Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }, texels) + generator_mask(fixture, Generator { controls: Some(Box::new(KindControls::Distance(distance))), ..Generator::new(GeneratorKind::ThreeDDistance) }, texels) } /// The mask of `generator` alone over black at `texels` @@ -104,8 +104,10 @@ fn the_linear_gradient_runs_from_its_start_to_its_end() { let mut fixture = fixture(); let texels = covered(&fixture); let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); - let gradient = - |gradient: LinearGradientParameters| Generator { linear_gradient: Some(Box::new(gradient)), ..Generator::new(GeneratorKind::ThreeDLinearGradient) }; + let gradient = |gradient: LinearGradientParameters| Generator { + controls: Some(Box::new(KindControls::LinearGradient(gradient))), + ..Generator::new(GeneratorKind::ThreeDLinearGradient) + }; let upwards = generator_mask(&mut fixture, gradient(LinearGradientParameters::default()), &at); let downwards = diff --git a/crates/compose/tests/generator_uv_border_distance.rs b/crates/compose/tests/generator_uv_border_distance.rs index db5b5db6..4457fb8c 100644 --- a/crates/compose/tests/generator_uv_border_distance.rs +++ b/crates/compose/tests/generator_uv_border_distance.rs @@ -2,8 +2,8 @@ use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - BorderDistanceParameters, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, - TextureSet, + BorderDistanceParameters, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, + Project, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -30,7 +30,7 @@ fn fixture() -> Fixture { /// The middle row's values, left edge to centre fn row(fixture: &mut Fixture, border: BorderDistanceParameters) -> Vec { - let generator = Generator { border_distance: Some(Box::new(border)), ..Generator::new(GeneratorKind::UvBorderDistance) }; + let generator = Generator { controls: Some(Box::new(KindControls::BorderDistance(border))), ..Generator::new(GeneratorKind::UvBorderDistance) }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index f19b2ec3..f5c23e39 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -24,6 +24,8 @@ mod distance_parameters; mod filtering; mod generator_global; mod generator_grayscale; +mod grayscale_conversion_parameters; +mod kind_controls; mod light_parameters; mod linear_gradient_parameters; mod micro_curvature_type; @@ -57,6 +59,8 @@ pub use distance_parameters::DistanceParameters; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; +pub use grayscale_conversion_parameters::GrayscaleConversionParameters; +pub use kind_controls::KindControls; pub use light_parameters::LightParameters; pub use linear_gradient_parameters::LinearGradientParameters; pub use micro_curvature_type::MicroCurvatureType; @@ -962,10 +966,12 @@ pub enum GeneratorKind { ThreeDLinearGradient, /// White at the UV islands' borders, fading towards their insides UvBorderDistance, + /// An image turned gray, tiled and rotated across the UV square + GrayscaleConversion, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 12] = [ + pub const ALL: [GeneratorKind; 13] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -978,6 +984,7 @@ impl GeneratorKind { GeneratorKind::ThreeDDistance, GeneratorKind::ThreeDLinearGradient, GeneratorKind::UvBorderDistance, + GeneratorKind::GrayscaleConversion, ]; pub fn label(self) -> &'static str { match self { @@ -993,6 +1000,7 @@ impl GeneratorKind { GeneratorKind::ThreeDDistance => "3D Distance", GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", GeneratorKind::UvBorderDistance => "UV Border Distance", + GeneratorKind::GrayscaleConversion => "Grayscale Conversion", } } @@ -1011,12 +1019,20 @@ impl GeneratorKind { GeneratorKind::ThreeDDistance => "ThreeDDistance", GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", GeneratorKind::UvBorderDistance => "UvBorderDistance", + GeneratorKind::GrayscaleConversion => "GrayscaleConversion", } } /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the newest kinds wait for their panels) pub fn in_picker(self) -> bool { - !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) + !matches!( + self, + GeneratorKind::ThinAreas + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + ) } /// Whether the kind's result depends on its seed @@ -1034,7 +1050,7 @@ impl GeneratorKind { GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], - GeneratorKind::UvBorderDistance => &[], + GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion => &[], } } @@ -1042,7 +1058,11 @@ impl GeneratorKind { pub fn has_no_earlier_model(self) -> bool { matches!( self, - GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance + GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion ) } @@ -1109,15 +1129,9 @@ pub struct Generator { /// The micro details of Curvature, Ambient Occlusion and the wear kinds (None: never touched, their defaults: off); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub micro: Option>, - /// The 3D Distance generator's controls (None on every other kind); boxed, so a generator effect stays small + /// The controls of 3D Distance, 3D Linear Gradient, UV Border Distance or Grayscale Conversion (None on the other kinds); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] - pub distance: Option>, - /// The 3D Linear Gradient generator's controls (None on every other kind); boxed, so a generator effect stays small - #[serde(default, skip_serializing_if = "Option::is_none")] - pub linear_gradient: Option>, - /// The UV Border Distance generator's controls (None on every other kind); boxed, so a generator effect stays small - #[serde(default, skip_serializing_if = "Option::is_none")] - pub border_distance: Option>, + pub controls: Option>, } impl Serialize for Generator { @@ -1161,17 +1175,47 @@ impl Generator { /// The 3D Distance controls the generator computes with: its own, else the defaults on a 3D Distance generator pub fn distance_controls(&self) -> Option { - self.distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDDistance).then(DistanceParameters::default)) + match self.kind_controls() { + Some(KindControls::Distance(distance)) => Some(distance), + _ => None, + } } /// The 3D Linear Gradient controls the generator computes with: its own, else the defaults on a 3D Linear Gradient generator pub fn linear_gradient_controls(&self) -> Option { - self.linear_gradient.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDLinearGradient).then(LinearGradientParameters::default)) + match self.kind_controls() { + Some(KindControls::LinearGradient(gradient)) => Some(gradient), + _ => None, + } } /// The UV Border Distance controls the generator computes with: its own, else the defaults on a UV Border Distance generator pub fn border_distance_controls(&self) -> Option { - self.border_distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::UvBorderDistance).then(BorderDistanceParameters::default)) + match self.kind_controls() { + Some(KindControls::BorderDistance(border)) => Some(border), + _ => None, + } + } + + /// The Grayscale Conversion controls the generator computes with: its own, else the defaults on a Grayscale Conversion generator + pub fn grayscale_controls(&self) -> Option { + match self.kind_controls() { + Some(KindControls::Grayscale(grayscale)) => Some(grayscale), + _ => None, + } + } + + /// The controls of a kind with only its own controls: its saved ones when they are that kind's, else its defaults + pub fn kind_controls(&self) -> Option { + self.controls.as_deref().filter(|controls| controls.kind() == self.kind).cloned().or_else(|| KindControls::defaults(self.kind)) + } + + /// The Grayscale Conversion controls as saved, without a copy + fn grayscale_controls_ref(&self) -> Option<&GrayscaleConversionParameters> { + match self.controls.as_deref() { + Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => Some(grayscale), + _ => None, + } } /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None @@ -1191,9 +1235,9 @@ impl Generator { self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) } - /// Everything the generator reads instead of its mesh maps: its inputs, then its texture, its custom grunge and its micro details + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture, its custom grunge, its micro details and its Grayscale Conversion image pub fn sources(&self) -> impl Iterator { - let micro = self.micro.iter().flat_map(|micro| micro.sources()); + let micro = self.micro.iter().flat_map(|micro| micro.sources()).chain(self.grayscale_controls_ref().and_then(|grayscale| grayscale.source.as_ref())); self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } @@ -1240,9 +1284,7 @@ impl Generator { texture: None, grunge: None, micro: None, - distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), - linear_gradient: (kind == GeneratorKind::ThreeDLinearGradient).then(Box::default), - border_distance: (kind == GeneratorKind::UvBorderDistance).then(Box::default), + controls: KindControls::defaults(kind).map(Box::new), } } diff --git a/crates/core/src/layer/grayscale_conversion_parameters.rs b/crates/core/src/layer/grayscale_conversion_parameters.rs new file mode 100644 index 00000000..1745be39 --- /dev/null +++ b/crates/core/src/layer/grayscale_conversion_parameters.rs @@ -0,0 +1,59 @@ +use serde::{Deserialize, Serialize}; + +use super::Source; +use super::generator_grayscale::GeneratorGrayscale; + +/// The Grayscale Conversion generator's controls: an image turned gray, tiled and rotated across the UV square +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GrayscaleConversionParameters { + /// How the image's color becomes gray + pub grayscale: GeneratorGrayscale, + /// Shifts the gray darker (below 0.5) or brighter (above 0.5) + pub balance: f32, + /// Narrows the gray around its middle (0..1; 1 a hard step) + pub contrast: f32, + /// How many times the image repeats across the UV square ([`GrayscaleConversionParameters::TILE_RANGE`]) + pub tile: f32, + /// Degrees the image turns about the UV square's centre (0..360) + pub rotation: f32, + /// Turn in quarter turns only, so the image keeps tiling seamlessly + pub safe_rotation: bool, + /// The image (None: an empty slot, read black) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +impl GrayscaleConversionParameters { + pub const TILE_RANGE: std::ops::RangeInclusive = 1.0..=16.0; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> GrayscaleConversionParameters { + let defaults = GrayscaleConversionParameters::default(); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + GrayscaleConversionParameters { + balance: within(self.balance, defaults.balance, 0.0..=1.0), + contrast: within(self.contrast, defaults.contrast, 0.0..=1.0), + tile: within(self.tile, defaults.tile, GrayscaleConversionParameters::TILE_RANGE).round(), + rotation: within(self.rotation, defaults.rotation, 0.0..=360.0), + ..self + } + } +} + +impl Default for GrayscaleConversionParameters { + /// The reference app's defaults + fn default() -> GrayscaleConversionParameters { + GrayscaleConversionParameters { + grayscale: GeneratorGrayscale::Desaturation, + balance: 0.5, + contrast: 0.0, + tile: 1.0, + rotation: 0.0, + safe_rotation: true, + source: None, + } + } +} diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs new file mode 100644 index 00000000..faf0000c --- /dev/null +++ b/crates/core/src/layer/kind_controls.rs @@ -0,0 +1,44 @@ +use serde::{Deserialize, Serialize}; + +use super::{BorderDistanceParameters, DistanceParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; + +/// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum KindControls { + Distance(DistanceParameters), + LinearGradient(LinearGradientParameters), + BorderDistance(BorderDistanceParameters), + Grayscale(GrayscaleConversionParameters), +} + +impl KindControls { + /// The reference app's defaults for `kind`, or None for kinds with an earlier model or section, wear or light controls + pub fn defaults(kind: GeneratorKind) -> Option { + match kind { + GeneratorKind::ThreeDDistance => Some(KindControls::Distance(DistanceParameters::default())), + GeneratorKind::ThreeDLinearGradient => Some(KindControls::LinearGradient(LinearGradientParameters::default())), + GeneratorKind::UvBorderDistance => Some(KindControls::BorderDistance(BorderDistanceParameters::default())), + GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Curvature + | GeneratorKind::AmbientOcclusion + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::WorldSpaceNormals => None, + } + } + + /// The kind these controls belong to + pub fn kind(&self) -> GeneratorKind { + match self { + KindControls::Distance(_) => GeneratorKind::ThreeDDistance, + KindControls::LinearGradient(_) => GeneratorKind::ThreeDLinearGradient, + KindControls::BorderDistance(_) => GeneratorKind::UvBorderDistance, + KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, + } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 4fdfe6f5..8040b874 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -76,7 +76,8 @@ impl MicroDetails { | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => None, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index c0c64f41..153640f8 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -42,7 +42,8 @@ impl SectionParameters { | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => None, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 4f10a9c6..6acde341 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -61,7 +61,8 @@ impl WearParameters { | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => None, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index fcbd7228..33b70ff6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 5bab2b11..120d3d42 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,10 +1,10 @@ -//! The controls of 3D Distance, 3D Linear Gradient and UV Border Distance that `effect.add.generator` and `effect.set` take +//! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{Generator, GeneratorKind}; +use texturecraft_core::{Generator, GeneratorKind, GeneratorGrayscale, KindControls}; use crate::Result; -use crate::commands::{bad, color_param, f32p}; +use crate::commands::{bad, boolp, color_param, f32p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; @@ -15,22 +15,26 @@ pub const LINEAR_GRADIENT_KEYS: [&str; 4] = ["gradientStart", "gradientEnd", "gr /// The UV Border Distance controls pub const BORDER_DISTANCE_KEYS: [&str; 4] = ["borderDistance", "borderSmoothness", "borderBalance", "borderContrast"]; +/// The Grayscale Conversion controls (its image is the `image` input) +pub const GRAYSCALE_KEYS: [&str; 6] = ["grayscaleType", "grayscaleBalance", "grayscaleContrast", "grayscaleTile", "grayscaleRotation", "grayscaleSafeRotation"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; -/// The 3D Distance, 3D Linear Gradient and UV Border Distance controls in `params`, each refused on other kinds; these kinds refuse the earlier model's and the global controls +/// The controls of the kinds with only their own controls in `params`, each refused on other kinds; these kinds refuse the earlier model's and the global controls pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let kind = generator.kind; for (keys, owner) in [ (&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient), (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), + (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); } } - if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) { + if !kind.has_no_earlier_model() || kind == GeneratorKind::FiberGlassEdgeWear { return Ok(()); } if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { @@ -39,6 +43,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::ThreeDLinearGradient { return linear_gradient_from(command, params, generator); } + if kind == GeneratorKind::GrayscaleConversion { + return grayscale_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -51,7 +58,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - *value = given; } } - generator.border_distance = Some(Box::new(border.clamped())); + generator.controls = Some(Box::new(KindControls::BorderDistance(border.clamped()))); return Ok(()); } @@ -66,7 +73,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - *value = given; } } - generator.distance = Some(Box::new(distance.clamped())); + generator.controls = Some(Box::new(KindControls::Distance(distance.clamped()))); Ok(()) } @@ -84,7 +91,31 @@ fn linear_gradient_from(command: &str, params: &Value, generator: &mut Generator *value = given; } } - generator.linear_gradient = Some(Box::new(gradient.clamped())); + generator.controls = Some(Box::new(KindControls::LinearGradient(gradient.clamped()))); + Ok(()) +} + +/// The Grayscale Conversion controls in `params` (the generator is one) +fn grayscale_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let mut grayscale = generator.grayscale_controls().unwrap_or_default(); + if let Some(value) = params.get("grayscaleType") { + let name = value.as_str().ok_or_else(|| bad(command, "`grayscaleType` must be a string"))?; + grayscale.grayscale = GeneratorGrayscale::parse(name).ok_or_else(|| bad(command, format!("unknown grayscale type `{name}`")))?; + } + for (key, value) in [ + ("grayscaleBalance", &mut grayscale.balance), + ("grayscaleContrast", &mut grayscale.contrast), + ("grayscaleTile", &mut grayscale.tile), + ("grayscaleRotation", &mut grayscale.rotation), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(safe) = boolp(params, "grayscaleSafeRotation") { + grayscale.safe_rotation = safe; + } + generator.controls = Some(Box::new(KindControls::Grayscale(grayscale.clamped()))); Ok(()) } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 393e8a0b..3cb7a868 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,9 @@ use serde_json::{Value, json}; use texturecraft_core::{ - AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, + AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, + Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, Levels, LightParameters, Mask, MaskBackground, Procedural, ProceduralKind, Project, + Sampling, SectionParameters, Source, TextureBlend, WearParameters, }; use crate::anchored_micro_edit::AnchoredMicroEdit; @@ -56,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -101,7 +102,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture, grunge, microHeight or microNormal + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null (the Micro Height reads that anchor point; null empties it), microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), 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; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture, grunge, microHeight, microNormal or image + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null (the Micro Height reads that anchor point; null empties it), microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -510,6 +511,9 @@ const TEXTURE_KEYS: [&str; 10] = [ "textureTriplanarContrast", ]; +/// The input name of Grayscale Conversion's image, beside the mesh map ids +const GRAYSCALE_IMAGE_INPUT: &str = "image"; + /// The input name of a generator's texture, beside the mesh map ids const TEXTURE_INPUT: &str = "texture"; @@ -794,18 +798,20 @@ enum GeneratorInput { Grunge, MicroHeight, MicroNormal, + Image, } /// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture`, `grunge`, `microHeight` or `microNormal`"))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture`, `grunge`, `microHeight`, `microNormal` or `image`"))?; let input = match name { TEXTURE_INPUT => GeneratorInput::Texture, GRUNGE_INPUT => GeneratorInput::Grunge, MICRO_HEIGHT_INPUT => GeneratorInput::MicroHeight, MICRO_NORMAL_INPUT => GeneratorInput::MicroNormal, + GRAYSCALE_IMAGE_INPUT => GeneratorInput::Image, _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), }; @@ -1146,6 +1152,14 @@ fn set(session: &mut Session, params: &Value) -> Result { micro.height_source = source; } } + Some((GeneratorInput::Image, source)) => { + if generator.kind != GeneratorKind::GrayscaleConversion { + return Err(bad(CMD, "only Grayscale Conversion reads an `image` input")); + } + let mut grayscale = generator.grayscale_controls().unwrap_or_default(); + grayscale.source = source; + generator.controls = Some(Box::new(KindControls::Grayscale(grayscale))); + } Some((GeneratorInput::MicroNormal, source)) => { if let Some(micro) = generator.micro.as_mut() { micro.normal_source = source; diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index a1508452..7e7ab4ef 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,7 +1,9 @@ //! The 3D Distance, 3D Linear Gradient and UV Border Distance generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point use serde_json::{Value, json}; -use texturecraft_engine::core::{BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; +use texturecraft_engine::core::{ + BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LinearGradientParameters, Source, +}; use texturecraft_engine::{Session, execute}; fn session() -> Session { @@ -46,7 +48,7 @@ fn three_d_distance_refuses_the_earlier_and_global_controls_and_others_refuse_it let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "distanceRadius": 0.5})).is_err()); - assert_eq!(generator(&session, curvature).distance, None); + assert_eq!(generator(&session, curvature).controls, None); } #[test] @@ -97,3 +99,24 @@ fn uv_border_distance_takes_its_controls_and_refuses_the_others() { let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "borderDistance": 0.5})).is_err()); } + +#[test] +fn grayscale_conversion_takes_its_controls_and_its_image() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 50, 50, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("color.png", bytes).unwrap(); + let effect = add(&mut session, json!({"generator": "Grayscale Conversion", "grayscaleType": "red", "grayscaleTile": 3.4, "grayscaleSafeRotation": false})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "image", "inputImage": name})).unwrap(); + let grayscale = generator(&session, effect).grayscale_controls().unwrap(); + assert_eq!((grayscale.grayscale, grayscale.tile, grayscale.safe_rotation), (GeneratorGrayscale::Red, 3.0, false), "the tile is a whole count"); + assert_eq!(grayscale.source, Some(Source::image(name.clone()))); + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read"); + + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "input": "image", "inputImage": name})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "grayscaleTile": 2})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 0139894f..f7335dc8 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -100,6 +100,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { (tr("A gradient between two points on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]) } GeneratorKind::UvBorderDistance => (tr("A gradient in from the UV islands' borders."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), + GeneratorKind::GrayscaleConversion => (tr("An image turned gray."), [tr("mask"), tr("generator"), tr("grayscale"), tr("image")]), }; // Wrapped rows: a long line must not widen the panel past its edge From c2cad52627d920b66e016e0d33b655d30662934b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:49:36 +0000 Subject: [PATCH 107/153] Generators: review fixes for Micro Details and the new kinds Saved values are brought into range when read (a hand-edited project's infinite smoothness or huge AO radius no longer reaches the blurs and occlusion search), with tests. The UV Border Distance gradient is built once before tiles composite, not by every tile at once; its cache key adds the g-buffer's address and a denser coverage fingerprint, and its Smoothness blur follows each UV tile's own resolution. The micro and border caches keep at most 256 MB besides the newest entry. A generator's own controls are resolved once per plan instead of per texel; project.inspect shows them. Docs say which space the 3D kinds' points live in (the bounds scaled evenly, like the reference's position map) and that an empty micro slot reads a flat height. --- crates/compose/src/eval.rs | 51 ++++++++++++------- crates/compose/src/generator_maps.rs | 19 ++++--- crates/compose/src/micro_details.rs | 34 +++++++++++-- crates/compose/src/three_d_distance.rs | 6 +-- crates/compose/src/uv_border_distance.rs | 48 +++++++++++++---- .../compose/tests/generator_micro_details.rs | 10 ++++ .../tests/generator_uv_border_distance.rs | 10 ++++ crates/core/src/layer.rs | 7 +-- crates/core/src/layer/distance_parameters.rs | 2 +- crates/core/src/layer/kind_controls.rs | 10 ++++ .../src/layer/linear_gradient_parameters.rs | 4 +- crates/core/src/layer/micro_details.rs | 2 +- crates/engine/src/inspect.rs | 3 ++ 13 files changed, 158 insertions(+), 48 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2d725331..746c03af 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -12,7 +12,12 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, + CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, + GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, + MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, + SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, + blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -2475,8 +2480,8 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, maps); } - if let Some(distance) = generator.distance_controls() { - let position = self.uniform_position_input(generator); - return three_d_distance::distance_value(&distance, position); - } - if let Some(grayscale) = generator.grayscale_controls() { - return self.grayscale_conversion(&grayscale); - } - if let Some(border) = generator.border_distance_controls() { - let texel = (self.y * self.inp.gbuf.width + self.x) as usize; - let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); - return uv_border_distance::border_value(&border, gradient); - } - if let Some(gradient) = generator.linear_gradient_controls() { - let position = self.uniform_position_input(generator); - return three_d_distance::linear_gradient_value(&gradient, position); + // The kinds with only their own controls: resolved once per plan, not per texel + let resolved; + let controls = match maps.controls.as_deref() { + Some(controls) => Some(controls), + None => { + resolved = generator.kind_controls(); + resolved.as_ref() + } + }; + match controls { + Some(KindControls::Distance(distance)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::distance_value(distance, position); + } + Some(KindControls::LinearGradient(gradient)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::linear_gradient_value(gradient, position); + } + Some(KindControls::BorderDistance(border)) => { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); + return uv_border_distance::border_value(border, gradient); + } + Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), + None => {} } let coords = self.coords(); diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 613e7e3a..a0498c0c 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use texturecraft_core::{BakedMap, Generator, MicroDetails}; +use texturecraft_core::{BakedMap, Generator, KindControls, MicroDetails}; use crate::curvature_sizes::CurvatureSizes; use crate::eval::Inputs; @@ -20,19 +20,26 @@ pub(crate) struct GeneratorMaps { pub micro_occlusion: Option>, /// The UV Border Distance gradient at every working texel pub border_gradient: Option>>, + /// The controls of a kind with only its own controls, brought into range + pub controls: Option>, } impl GeneratorMaps { /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size) pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps { - let micro = generator.micro_in_use(); - let micro_curvature = micro.filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); - let micro_occlusion = micro.filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro)); + let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind)); + let micro_curvature = + micro.as_ref().filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); + let micro_occlusion = micro.as_ref().filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro)); let sizes = match µ_curvature { Some(micro) => CurvatureSizes::of_map(inp, µ.curvature, needed), None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), }; - let border_gradient = generator.border_distance_controls().map(|border| border_gradient(inp, &border)); - GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient } + let controls = generator.kind_controls(); + let border_gradient = match &controls { + Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), + _ => None, + }; + GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, controls: controls.map(Arc::new) } } } diff --git a/crates/compose/src/micro_details.rs b/crates/compose/src/micro_details.rs index d81fabf9..35132998 100644 --- a/crates/compose/src/micro_details.rs +++ b/crates/compose/src/micro_details.rs @@ -41,8 +41,26 @@ const OCCLUSION_DEPTH_POWER: f32 = 1.0654; /// How dark a fully occluding horizon makes the occlusion (fitted) const OCCLUSION_STRENGTH: f32 = 0.3232; -/// Cached micro maps; each entry is small next to the curvature sizes it feeds +/// Most micro maps cached, and the bytes they may hold (the newest is kept whatever its size), like the curvature sizes they feed const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; + +/// What a cached map holds, to keep the cache within [`CACHE_BYTES`] +trait CachedBytes { + fn bytes(&self) -> usize; +} + +impl CachedBytes for LayoutMap { + fn bytes(&self) -> usize { + self.data.len().saturating_mul(size_of::()) + } +} + +impl CachedBytes for MicroCurvature { + fn bytes(&self) -> usize { + self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::())) + } +} /// A map in a mesh map's layout: `size` texels, each UV tile one block pub struct LayoutMap { @@ -288,7 +306,7 @@ struct Cache { entries: Mutex)>>, } -impl Cache { +impl Cache { const fn new() -> Cache { Cache { entries: Mutex::new(Vec::new()) } } @@ -313,7 +331,17 @@ impl Cache { let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); entries.retain(|(cached, _)| *cached != key); entries.push((key, built.clone())); - let excess = entries.len().saturating_sub(CACHE_ENTRIES); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.bytes()); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); entries.drain(..excess); built } diff --git a/crates/compose/src/three_d_distance.rs b/crates/compose/src/three_d_distance.rs index d62524d4..02812e84 100644 --- a/crates/compose/src/three_d_distance.rs +++ b/crates/compose/src/three_d_distance.rs @@ -12,13 +12,13 @@ pub(crate) fn distance_value(distance: &DistanceParameters, position: Vec3) -> f histogram_scan(gradient, distance.offset, distance.contrast) } -/// Shortest start-to-end span the gradient divides by -const MIN_GRADIENT_LENGTH: f32 = 1e-6; +/// Smallest squared start-to-end span the gradient divides by +const MIN_GRADIENT_LENGTH_SQUARED: f32 = 1e-12; /// The value at `position`: how far along from the start to the end it lies (0 at the start, 1 at the end), balanced and contrasted like a generator's global controls pub(crate) fn linear_gradient_value(gradient: &LinearGradientParameters, position: Vec3) -> f32 { let (start, end) = (Vec3::from(gradient.start), Vec3::from(gradient.end)); let span = end - start; - let along = if span.length_squared() > MIN_GRADIENT_LENGTH { (position - start).dot(span) / span.length_squared() } else { 0.0 }; + let along = if span.length_squared() > MIN_GRADIENT_LENGTH_SQUARED { (position - start).dot(span) / span.length_squared() } else { 0.0 }; GeneratorGlobal { balance: gradient.balance, contrast: gradient.contrast, ..GeneratorGlobal::default() }.apply(along.clamp(0.0, 1.0)) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index 50033fcd..a18535a4 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -16,15 +16,18 @@ const SMOOTHNESS_SIGMA_2K: f32 = 45.0; /// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at const REFERENCE_TILE_TEXELS: f32 = 2048.0; -/// Cached gradients; one per layout and setting a stack shows at a time +/// Most gradients cached, and the bytes they may hold (the newest is kept whatever its size) const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; -/// Texels between the samples a layout's fingerprint reads -const FINGERPRINT_STRIDE: usize = 997; +/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile +const FINGERPRINT_STRIDE: usize = 31; /// What a gradient was built from: the working layout (size, coverage fingerprint, UV tile block, tile scales) and the settings' bits #[derive(Clone, PartialEq)] struct Key { + /// The g-buffer's triangle data by address, beside its fingerprint + layout: usize, size: (u32, u32), fingerprint: u64, block: (u32, u32), @@ -42,7 +45,14 @@ pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) - let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); let block = (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))); let fingerprint = gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)); - let key = Key { size, fingerprint, block, scales: inp.block_scales.clone(), settings: [border.distance.to_bits(), border.smoothness.to_bits()] }; + let key = Key { + layout: gbuf.tri.as_ptr() as usize, + size, + fingerprint, + block, + scales: inp.block_scales.clone(), + settings: [border.distance.to_bits(), border.smoothness.to_bits()], + }; let cached = { let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -57,7 +67,17 @@ pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); cache.retain(|(cached, _)| *cached != key); cache.push((key, gradient.clone())); - let excess = cache.len().saturating_sub(CACHE_ENTRIES); + let mut bytes = 0usize; + let keep = cache + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = cache.len().saturating_sub(keep); cache.drain(..excess); gradient } @@ -89,10 +109,12 @@ fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> .collect(); // Smoothness blurs the gradient with the empty space around the islands, so their borders soften towards black - let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * block.0 as f32 / REFERENCE_TILE_TEXELS; - let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize; - if radius > 0 { - blur_blocks(&mut gradient, (width, height), block, radius); + if border.smoothness > 0.0 { + let radius_at = |tile_texels: f32| { + let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * tile_texels / REFERENCE_TILE_TEXELS; + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize + }; + blur_blocks(&mut gradient, (width, height), block, |left, top| radius_at(block.0 as f32 * inp.block_scales.at(left, top))); for (value, texel) in gradient.iter_mut().zip(0..) { if !gbuf.covered(texel) { *value = 0.0; @@ -177,8 +199,8 @@ fn squared_distance_line(line: &mut [f32]) { } } -/// `data` blurred one UV tile block at a time, reading black past each block's edges -fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius: usize) { +/// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges +fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { for top in (0..height).step_by(block.1 as usize) { for left in (0..width).step_by(block.0 as usize) { let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); @@ -187,6 +209,10 @@ fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), .flat_map(|row| (0..columns).map(move |column| (column, row))) .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) .collect(); + let radius = radius_at(left, top); + if radius == 0 { + continue; + } blur(&mut values, columns, rows, radius); for (offset, value) in values.into_iter().enumerate() { if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { diff --git a/crates/compose/tests/generator_micro_details.rs b/crates/compose/tests/generator_micro_details.rs index 62254619..2b8001a6 100644 --- a/crates/compose/tests/generator_micro_details.rs +++ b/crates/compose/tests/generator_micro_details.rs @@ -209,3 +209,13 @@ fn a_micro_height_bump_moves_the_wear_kinds_around_it() { assert!(changed > 0, "{kind:?}"); } } + +#[test] +fn saved_micro_values_out_of_range_render_as_their_nearest_valid_ones() { + let mut fixture = fixture(); + let hostile = + mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| (micro.ao_radius, micro.ao_depth) = (1e30, f32::NAN))); + let valid = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| micro.ao_radius = 1.0)); + + assert_eq!(hostile, valid); +} diff --git a/crates/compose/tests/generator_uv_border_distance.rs b/crates/compose/tests/generator_uv_border_distance.rs index 4457fb8c..ec14c22a 100644 --- a/crates/compose/tests/generator_uv_border_distance.rs +++ b/crates/compose/tests/generator_uv_border_distance.rs @@ -78,3 +78,13 @@ fn smoothness_darkens_the_edge_with_the_space_around_the_island() { assert!(smooth[0] < sharp[0] - 0.2, "{} vs {}", smooth[0], sharp[0]); } + +#[test] +fn saved_values_out_of_range_render_as_their_nearest_valid_ones() { + let mut fixture = fixture(); + let hostile = + row(&mut fixture, BorderDistanceParameters { distance: f32::NAN, smoothness: f32::INFINITY, contrast: 7.0, ..BorderDistanceParameters::default() }); + let valid = row(&mut fixture, BorderDistanceParameters { contrast: 1.0, ..BorderDistanceParameters::default() }); + + assert_eq!(hostile, valid, "non-finite values read their defaults, others their nearest valid value"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index f5c23e39..fd0a9c1a 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1205,9 +1205,10 @@ impl Generator { } } - /// The controls of a kind with only its own controls: its saved ones when they are that kind's, else its defaults + /// The controls of a kind with only its own controls: its saved ones (brought into range) when they are that kind's, else its defaults pub fn kind_controls(&self) -> Option { - self.controls.as_deref().filter(|controls| controls.kind() == self.kind).cloned().or_else(|| KindControls::defaults(self.kind)) + let saved = self.controls.as_deref().filter(|controls| controls.kind() == self.kind).cloned().map(KindControls::clamped); + saved.or_else(|| KindControls::defaults(self.kind)) } /// The Grayscale Conversion controls as saved, without a copy @@ -1241,7 +1242,7 @@ impl Generator { self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } - /// The micro details the generator computes with: switched on with an image to read (an anchor's micro detail saved on the earlier model reads too) + /// The micro details as saved, when the generator computes with them: with a slot switched on, also on the earlier model where an anchor's micro detail saved before Micro Details reads (bring them into range before use: saved files are not trusted) pub fn micro_in_use(&self) -> Option<&MicroDetails> { self.micro.as_deref().filter(|micro| micro.in_use(self.kind)) } diff --git a/crates/core/src/layer/distance_parameters.rs b/crates/core/src/layer/distance_parameters.rs index a392b4a0..15a38371 100644 --- a/crates/core/src/layer/distance_parameters.rs +++ b/crates/core/src/layer/distance_parameters.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DistanceParameters { - /// The point, 0..1 across the mesh's bounds on each axis (Position X, Y and Z) + /// The point (Position X, Y and Z) in the mesh's bounds scaled evenly, as the reference's position map is: the longest side spans 0..1, the others are centred on 0.5 pub point: [f32; 3], /// How far the gradient reaches, in units of the bounds' longest side ([`DistanceParameters::RADIUS_RANGE`]) pub radius: f32, diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index faf0000c..abfd61b5 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -32,6 +32,16 @@ impl KindControls { } } + /// Every value brought into its range, non-finite ones to the defaults (saved files are not trusted) + pub fn clamped(self) -> KindControls { + match self { + KindControls::Distance(distance) => KindControls::Distance(distance.clamped()), + KindControls::LinearGradient(gradient) => KindControls::LinearGradient(gradient.clamped()), + KindControls::BorderDistance(border) => KindControls::BorderDistance(border.clamped()), + KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), + } + } + /// The kind these controls belong to pub fn kind(&self) -> GeneratorKind { match self { diff --git a/crates/core/src/layer/linear_gradient_parameters.rs b/crates/core/src/layer/linear_gradient_parameters.rs index 2526da80..1c100065 100644 --- a/crates/core/src/layer/linear_gradient_parameters.rs +++ b/crates/core/src/layer/linear_gradient_parameters.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LinearGradientParameters { - /// Where the gradient is black, 0..1 across the mesh's bounds on each axis + /// Where the gradient is black, in the mesh's bounds scaled evenly like 3D Distance's point (the longest side spans 0..1, the others are centred on 0.5) pub start: [f32; 3], /// Where the gradient is white pub end: [f32; 3], @@ -29,7 +29,7 @@ impl LinearGradientParameters { } impl Default for LinearGradientParameters { - /// The reference app's defaults: bottom to top through the bounds' centre + /// The reference app's defaults: from y 0 to y 1 through the bounds' centre, which spans the mesh when its longest side is vertical fn default() -> LinearGradientParameters { LinearGradientParameters { start: [0.5, 0.0, 0.5], end: [0.5, 1.0, 0.5], balance: 0.5, contrast: 0.0 } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 8040b874..dc2c5f4b 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -101,7 +101,7 @@ impl MicroDetails { if kind == GeneratorKind::Curvature { 0.0..=5.0 } else { 0.0..=1.0 } } - /// Whether the micro details change a generator of `kind`: switched on with an image to read + /// Whether the micro details change a generator of `kind`: switched on with a slot to read (an empty slot reads a flat black height, which some curvature types still lift) pub fn in_use(&self, kind: GeneratorKind) -> bool { (self.enabled || !MicroDetails::has_switch(kind)) && (self.height || self.normal) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index c4ac692e..bc0efe3c 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -162,6 +162,9 @@ fn generator_json(generator: &Generator) -> Value { if let Some(micro) = &generator.micro { out["micro"] = json!(micro); } + if let Some(controls) = &generator.controls { + out["controls"] = json!(controls); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); From f3c8103579e728d24a38c32320e8db43cc3ba743 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:10:31 +0000 Subject: [PATCH 108/153] Generators: Dripping Rust, rust grown from the occlusion and run down in drips A new kind with the reference's controls: Rust Spreading, Rust Contrast, Spreading Smoothness, Drips Intensity, Drips Smoothness, Drips Samples Amount, Position axis, Seed and Invert. Fitted to the reference: the rust rises with the occlusion, is blurred by the spreading smoothness, and each texel then takes the most rust found uphill along the chosen axis of the mesh's bounds over the samples, fading with distance (93 texels at 2K at intensity 1), blurred by the drips smoothness and scanned by spreading and contrast (spreading 0 and 1 are exactly black and white, as in the reference). The reference's grunge is not reproduced: the Dirt grunge breaks the rust up at the measured strength instead, so the look is close in level but not texel for texel (correlation 0.55 on the test gun, versus about 0.75 for the fitted model with its noise averaged out). The field is built once per layout, occlusion map and setting, with the UV Border Distance gradient's cache and blur now shared in one module. Commands only; no replaceable inputs yet (it reads the baked occlusion and the mesh's bounds whole). --- crates/compose/src/dripping_rust.rs | 162 ++++++++++++++++++ crates/compose/src/eval.rs | 43 ++++- crates/compose/src/generator_maps.rs | 9 +- crates/compose/src/lib.rs | 2 + crates/compose/src/uv_border_distance.rs | 94 +--------- crates/compose/src/working_field.rs | 127 ++++++++++++++ .../compose/tests/generator_dripping_rust.rs | 107 ++++++++++++ crates/core/src/layer.rs | 16 +- .../src/layer/dripping_rust_parameters.rs | 55 ++++++ crates/core/src/layer/kind_controls.rs | 6 +- crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 42 ++++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 20 ++- crates/ui-egui/src/generator_panel.rs | 3 + 18 files changed, 592 insertions(+), 107 deletions(-) create mode 100644 crates/compose/src/dripping_rust.rs create mode 100644 crates/compose/src/working_field.rs create mode 100644 crates/compose/tests/generator_dripping_rust.rs create mode 100644 crates/core/src/layer/dripping_rust_parameters.rs diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs new file mode 100644 index 00000000..ef3e308c --- /dev/null +++ b/crates/compose/src/dripping_rust.rs @@ -0,0 +1,162 @@ +//! The Dripping Rust generator: rust grown from the occlusion, broken up by grunge, then run down the mesh in drips; built once per layout and settings + +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearParameters}; +use texturecraft_geom::glam::Vec3; + +use crate::eval::{Inputs, texel_coords}; +use crate::histogram_scan::histogram_scan; +use crate::wear; +use crate::working_field::{FieldCache, blur_blocks}; + +/// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference) +const RUST_FLOOR: f32 = 0.315; +const RUST_GAIN: f32 = 3.19; +const RUST_OCCLUSION: f32 = 0.849; +const RUST_POWER: f32 = 2.38; + +/// How much grunge breaks the rust up: the spread of the reference's noise (measured); the pattern itself is inferred +const GRUNGE_SPREAD: f32 = 0.19; + +/// Blur sizes at Spreading Smoothness 1 and Drips Smoothness 1, as gaussian sigmas in texels of a 2K UV tile (fitted) +const SPREADING_SIGMA_2K: f32 = 47.0; +const DRIPS_SIGMA_2K: f32 = 11.5; + +/// How far a drip runs at Drips Intensity 1, in texels of a 2K UV tile, and how it fades along its length: `1 − DRIP_FADE · along^DRIP_FADE_POWER` (fitted) +const DRIP_LENGTH_2K: f32 = 90.86; +const DRIP_FADE: f32 = 0.898; +const DRIP_FADE_POWER: f32 = 0.671; + +/// The UV tile resolution the sizes above are measured at +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// Coverage below which a blurred texel has nothing to average +const MIN_COVERAGE: f32 = 1e-3; + +static CACHE: FieldCache = FieldCache::new(); + +/// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) +pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) -> Arc> { + let occlusion = inp.baked.maps.get(&BakedMap::AmbientOcclusion); + let settings = vec![ + rust.spreading_smoothness.to_bits(), + rust.drips_intensity.to_bits(), + rust.drips_smoothness.to_bits(), + rust.drips_samples, + u32::from(rust.axis), + seed, + ]; + CACHE.get_or_build(inp, &occlusion.into_iter().collect::>(), settings, |block| build(inp, rust, seed, block)) +} + +/// The value at a working texel: the rust spread and contrasted +pub(crate) fn rust_value(rust: &DrippingRustParameters, field: f32) -> f32 { + histogram_scan(field, rust.spreading, rust.contrast) +} + +fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u32)) -> Vec { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + let cover: Vec = (0..width * height).map(|texel| if gbuf.covered(texel as usize) { 1.0 } else { 0.0 }).collect(); + let tile_texels = |x: u32, y: u32| block.0 as f32 * inp.block_scales.at(x, y); + + // The rust from the occlusion, broken up by the Dirt generator's grunge + let grunge = WearParameters::defaults(GeneratorKind::Dirt); + let rust_at = |texel: u32| { + let (x, y) = (texel % width, texel / width); + let occlusion = inp.baked.sample_working(BakedMap::AmbientOcclusion, x, y, (width, height), &inp.block_scales).map_or(1.0, |value| value[0]); + let base = RUST_FLOOR + RUST_GAIN * (RUST_OCCLUSION - occlusion).max(0.0).powf(RUST_POWER); + let noise = grunge.map_or(0.0, |grunge| wear::grunge(GeneratorKind::Dirt, &grunge, seed, &texel_coords(inp, x, y))); + base + GRUNGE_SPREAD * noise + }; + let mut field: Vec = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect(); + + let sigma_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); + blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); + let mut field = drips(inp, rust, &field, (width, height), &tile_texels); + blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); + field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 }); + field +} + +/// The radius of three box passes that blur like a gaussian of `sigma`: three boxes of radius r spread a texel with variance r (r + 1) +fn box_radius(sigma: f32) -> usize { + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize +} + +/// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) { + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + let mut weights = cover.to_vec(); + blur_blocks(&mut sums, size, block, radius_at); + blur_blocks(&mut weights, size, block, radius_at); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).zip(cover.par_iter()).for_each(|((value, (sum, weight)), covered)| { + if *covered > 0.0 && *weight > MIN_COVERAGE { + *value = sum / weight; + } + }); +} + +/// Each texel takes the most rust found uphill along the drip axis, fading with how far up it lies +fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, height): (u32, u32), tile_texels: &(impl Fn(u32, u32) -> f32 + Sync)) -> Vec { + let gbuf = inp.gbuf; + if rust.drips_samples == 0 || rust.drips_intensity <= 0.0 { + return field.to_vec(); + } + + // The drip axis across the mesh's bounds at every covered texel + let (low, high) = inp.bounds; + let extent = (high - low).max(Vec3::splat(f32::EPSILON)); + let axis = usize::from(rust.axis.min(2)); + let along_axis: Vec> = (0..width * height) + .into_par_iter() + .map(|texel| gbuf.surface(inp.mesh, texel as usize).map(|surface| ((surface.pos - low) / extent).to_array()[axis])) + .collect(); + let axis_at = |x: i64, y: i64| -> Option { + if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) { + return None; + } + along_axis.get((y * i64::from(width) + x) as usize).copied().flatten() + }; + let field_at = |x: i64, y: i64| -> Option { + if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) || !gbuf.covered((y * i64::from(width) + x) as usize) { + return None; + } + field.get((y * i64::from(width) + x) as usize).copied() + }; + // Central differences, one-sided at an island's border + let slope = |before: Option, here: f32, after: Option| match (before, after) { + (Some(before), Some(after)) => (after - before) * 0.5, + (None, Some(after)) => after - here, + (Some(before), None) => here - before, + (None, None) => 0.0, + }; + + let samples = rust.drips_samples; + (0..width * height) + .into_par_iter() + .map(|texel| { + let (x, y) = (i64::from(texel % width), i64::from(texel / width)); + let here = field.get(texel as usize).copied().unwrap_or(0.0); + let Some(axis_here) = axis_at(x, y) else { return here }; + let uphill = (slope(axis_at(x - 1, y), axis_here, axis_at(x + 1, y)), slope(axis_at(x, y - 1), axis_here, axis_at(x, y + 1))); + let length = (uphill.0 * uphill.0 + uphill.1 * uphill.1).sqrt(); + if length <= f32::EPSILON { + return here; + } + + let reach = rust.drips_intensity * DRIP_LENGTH_2K * tile_texels(texel % width, texel / width) / REFERENCE_TILE_TEXELS; + (1..=samples).fold(here, |most, step| { + let along = step as f32 / samples as f32; + let distance = reach * along; + let (sample_x, sample_y) = (x as f32 + distance * uphill.0 / length, y as f32 + distance * uphill.1 / length); + match field_at(sample_x.round() as i64, sample_y.round() as i64) { + Some(value) => most.max(value * (1.0 - DRIP_FADE * along.powf(DRIP_FADE_POWER))), + None => most, + } + }) + }) + .collect() +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 746c03af..52625777 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -26,6 +26,7 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::{CurvatureSizes, LEVEL_RADII}; +use crate::dripping_rust; use crate::effect_histogram::EffectHistogram; use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; @@ -1950,6 +1951,26 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } +/// Where working texel (`x`, `y`) of `inp` is, for pattern evaluation (as [`Texel::coords`] sees it outside a fill copy) +pub(crate) fn texel_coords(inp: &Inputs, x: u32, y: u32) -> Coords { + let g = inp.gbuf; + let mut c = match g.surface(inp.mesh, (y * g.width + x) as usize) { + Some(s) => { + let (center, radius) = mesh_frame(inp.bounds); + Coords { uv: s.uv, pos: (s.pos - center) / radius, nrm: s.nrm } + } + None => Coords { uv: Vec2::new((x as f32 + 0.5) / g.width as f32, (y as f32 + 0.5) / g.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + }; + + // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile) + if let Ok(set) = inp.project.texture_set(inp.ts) + && let Some(grid) = set.tile_grid() + { + c.uv = Vec2::from(set.from_atlas(&grid, c.uv.to_array())); + } + c +} + /// What a generator's texture or custom grunge reads with nothing in its slot const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); @@ -2481,7 +2502,8 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { return uv_border_distance::border_value(border, gradient); } Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), + Some(KindControls::DrippingRust(rust)) => { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + let field = maps.rust_field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0); + return dripping_rust::rust_value(rust, field); + } None => {} } @@ -3458,9 +3485,14 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion, _) => { - 0.0 - } + ( + GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust, + _, + ) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3509,7 +3541,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => 0.0, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => 0.0, } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index a0498c0c..acced92c 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use texturecraft_core::{BakedMap, Generator, KindControls, MicroDetails}; use crate::curvature_sizes::CurvatureSizes; +use crate::dripping_rust::rust_field; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; use crate::uv_border_distance::border_gradient; @@ -20,6 +21,8 @@ pub(crate) struct GeneratorMaps { pub micro_occlusion: Option>, /// The UV Border Distance gradient at every working texel pub border_gradient: Option>>, + /// The Dripping Rust field at every working texel + pub rust_field: Option>>, /// The controls of a kind with only its own controls, brought into range pub controls: Option>, } @@ -40,6 +43,10 @@ impl GeneratorMaps { Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), _ => None, }; - GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, controls: controls.map(Arc::new) } + let rust_field = match &controls { + Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), + _ => None, + }; + GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, rust_field, controls: controls.map(Arc::new) } } } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 24c3f9e5..09ae63d8 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -14,6 +14,7 @@ mod curvature_size_level; pub mod curvature_sizes; pub mod display; mod distance_envelope; +mod dripping_rust; mod effect_histogram; pub mod environment_sh; pub mod environment_sky; @@ -59,6 +60,7 @@ mod warp_texel; mod wear; mod wear_inputs; mod wear_scan; +mod working_field; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index a18535a4..0fa3afd0 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -1,11 +1,12 @@ //! The UV Border Distance generator: how far each texel lies inside its UV island, as a gradient built once per UV layout and settings -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use rayon::prelude::*; -use texturecraft_core::{BlockScales, BorderDistanceParameters, GeneratorGlobal}; +use texturecraft_core::{BorderDistanceParameters, GeneratorGlobal}; -use crate::eval::{Inputs, blur}; +use crate::eval::Inputs; +use crate::working_field::{FieldCache, blur_blocks}; /// How far in the gradient reaches at Distance 1, in UV units (fitted: about half a UV tile) const REACH_PER_DISTANCE: f32 = 0.4936; @@ -16,70 +17,11 @@ const SMOOTHNESS_SIGMA_2K: f32 = 45.0; /// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at const REFERENCE_TILE_TEXELS: f32 = 2048.0; -/// Most gradients cached, and the bytes they may hold (the newest is kept whatever its size) -const CACHE_ENTRIES: usize = 8; -const CACHE_BYTES: usize = 256 << 20; - -/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile -const FINGERPRINT_STRIDE: usize = 31; - -/// What a gradient was built from: the working layout (size, coverage fingerprint, UV tile block, tile scales) and the settings' bits -#[derive(Clone, PartialEq)] -struct Key { - /// The g-buffer's triangle data by address, beside its fingerprint - layout: usize, - size: (u32, u32), - fingerprint: u64, - block: (u32, u32), - scales: BlockScales, - settings: [u32; 2], -} - -static CACHE: Mutex>)>> = Mutex::new(Vec::new()); +static CACHE: FieldCache = FieldCache::new(); /// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) -> Arc> { - let gbuf = inp.gbuf; - let size = (gbuf.width, gbuf.height); - let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); - let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); - let block = (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))); - let fingerprint = gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)); - let key = Key { - layout: gbuf.tri.as_ptr() as usize, - size, - fingerprint, - block, - scales: inp.block_scales.clone(), - settings: [border.distance.to_bits(), border.smoothness.to_bits()], - }; - - let cached = { - let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.iter().find(|(cached, _)| *cached == key).map(|(_, gradient)| gradient.clone()) - }; - if let Some(gradient) = cached { - return gradient; - } - - // Built without the cache locked: the build runs parallel work - let gradient = Arc::new(build(inp, border, block)); - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.retain(|(cached, _)| *cached != key); - cache.push((key, gradient.clone())); - let mut bytes = 0usize; - let keep = cache - .iter() - .rev() - .take_while(|(_, built)| { - bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); - bytes <= CACHE_BYTES - }) - .count() - .clamp(1, CACHE_ENTRIES); - let excess = cache.len().saturating_sub(keep); - cache.drain(..excess); - gradient + CACHE.get_or_build(inp, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) } /// The value at a working texel: the gradient balanced, contrasted and inverted @@ -199,30 +141,6 @@ fn squared_distance_line(line: &mut [f32]) { } } -/// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges -fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { - for top in (0..height).step_by(block.1 as usize) { - for left in (0..width).step_by(block.0 as usize) { - let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); - let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; - let mut values: Vec = (0..rows) - .flat_map(|row| (0..columns).map(move |column| (column, row))) - .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) - .collect(); - let radius = radius_at(left, top); - if radius == 0 { - continue; - } - blur(&mut values, columns, rows, radius); - for (offset, value) in values.into_iter().enumerate() { - if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { - *target = value; - } - } - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/compose/src/working_field.rs b/crates/compose/src/working_field.rs new file mode 100644 index 00000000..55c3763b --- /dev/null +++ b/crates/compose/src/working_field.rs @@ -0,0 +1,127 @@ +//! Whole-map fields some generators precompute at the working resolution (UV Border Distance, Dripping Rust), built once per layout, mesh map and settings + +use std::sync::{Arc, Mutex, Weak}; + +use texturecraft_core::BlockScales; + +use crate::eval::{Inputs, blur}; + +/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) +const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; + +/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile +const FINGERPRINT_STRIDE: usize = 31; + +/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh, the mesh maps it reads and its settings' bits +#[derive(Clone)] +struct Key { + layout: usize, + size: (u32, u32), + fingerprint: u64, + block: (u32, u32), + scales: BlockScales, + mesh: (usize, usize), + maps: Vec>>, + settings: Vec, +} + +impl PartialEq for Key { + fn eq(&self, other: &Key) -> bool { + let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); + same_maps + && self.layout == other.layout + && self.size == other.size + && self.fingerprint == other.fingerprint + && self.block == other.block + && self.scales == other.scales + && self.mesh == other.mesh + && self.settings == other.settings + } +} + +/// Built fields by what they were built from, most recently used last +pub(crate) struct FieldCache { + entries: Mutex>)>>, +} + +impl FieldCache { + pub(crate) const fn new() -> FieldCache { + FieldCache { entries: Mutex::new(Vec::new()) } + } + + /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work + pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { + let gbuf = inp.gbuf; + let block = working_block(inp); + let key = Key { + layout: gbuf.tri.as_ptr() as usize, + size: (gbuf.width, gbuf.height), + fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), + block, + scales: inp.block_scales.clone(), + mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), + maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), + settings, + }; + + let cached = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); + entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) + }; + if let Some(field) = cached { + return field; + } + + let field = Arc::new(build(block)); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, field.clone())); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); + entries.drain(..excess); + field + } +} + +/// The size of one UV tile's block in `inp`'s working atlas +pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { + let size = (inp.gbuf.width, inp.gbuf.height); + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); + (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))) +} + +/// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges +pub(crate) fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { + for top in (0..height).step_by(block.1 as usize) { + for left in (0..width).step_by(block.0 as usize) { + let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); + let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; + let mut values: Vec = (0..rows) + .flat_map(|row| (0..columns).map(move |column| (column, row))) + .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) + .collect(); + let radius = radius_at(left, top); + if radius == 0 { + continue; + } + blur(&mut values, columns, rows, radius); + for (offset, value) in values.into_iter().enumerate() { + if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { + *target = value; + } + } + } + } +} diff --git a/crates/compose/tests/generator_dripping_rust.rs b/crates/compose/tests/generator_dripping_rust.rs new file mode 100644 index 00000000..b94c323d --- /dev/null +++ b/crates/compose/tests/generator_dripping_rust.rs @@ -0,0 +1,107 @@ +//! The Dripping Rust generator on a sphere with an occluded band: rust grows in the occlusion, spreads from none to everywhere, and drips run down from it + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, DrippingRustParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, + MaskBackground, Project, Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// The occluded band's heights on the unit sphere, and its occlusion +const BAND: std::ops::Range = 0.2..0.5; +const BAND_OCCLUSION: f32 = 0.2; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, +} + +/// A unit sphere with a white fill layer, occluded only in [`BAND`] +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 48, 24); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let occlusion: Vec = (0..RES * RES) + .map(|texel| gbuf.surface(&mesh, texel as usize).map_or(1.0, |surface| if BAND.contains(&surface.pos.y) { BAND_OCCLUSION } else { 1.0 })) + .collect(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(occlusion))].into() }; + Fixture { project, mesh, gbuf, layer, baked } +} + +/// Every covered texel and its height +fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { + (0..RES * RES).filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos.y))).collect() +} + +fn mask(fixture: &mut Fixture, rust: DrippingRustParameters, texels: &[(u32, u32)]) -> Vec { + let generator = Generator { controls: Some(Box::new(KindControls::DrippingRust(rust))), ..Generator::new(GeneratorKind::DrippingRust) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// The mean of `values` over the texels whose height lies in `heights` +fn mean_within(texels: &[((u32, u32), f32)], values: &[f32], heights: std::ops::Range) -> f32 { + let picked: Vec = texels.iter().zip(values).filter(|((_, height), _)| heights.contains(height)).map(|(_, value)| *value).collect(); + picked.iter().sum::() / picked.len().max(1) as f32 +} + +#[test] +fn spreading_runs_from_none_to_everywhere() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let none = mask(&mut fixture, DrippingRustParameters { spreading: 0.0, ..DrippingRustParameters::default() }, &at); + let all = mask(&mut fixture, DrippingRustParameters { spreading: 1.0, ..DrippingRustParameters::default() }, &at); + assert!(none.iter().all(|value| *value == 0.0)); + assert!(all.iter().all(|value| *value == 1.0)); +} + +#[test] +fn the_occluded_band_rusts_most() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + + let values = mask(&mut fixture, DrippingRustParameters { drips_intensity: 0.0, ..DrippingRustParameters::default() }, &at); + assert!(mean_within(&texels, &values, BAND) > mean_within(&texels, &values, -1.0..-0.2) + 0.3); +} + +#[test] +fn drips_only_add_rust_and_run_down_from_the_band() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + let rust = DrippingRustParameters { contrast: 0.0, drips_smoothness: 0.0, ..DrippingRustParameters::default() }; + + let dry = mask(&mut fixture, DrippingRustParameters { drips_intensity: 0.0, ..rust }, &at); + let dripping = mask(&mut fixture, DrippingRustParameters { drips_intensity: 1.0, ..rust }, &at); + assert!(dripping.iter().zip(&dry).all(|(wet, dry)| wet >= dry), "a drip takes the most rust above, never less than its own"); + let gain = |heights: std::ops::Range| mean_within(&texels, &dripping, heights.clone()) - mean_within(&texels, &dry, heights); + assert!(gain(0.05..0.2) > gain(0.5..0.65) + 0.05, "below the band {} above it {}", gain(0.05..0.2), gain(0.5..0.65)); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index fd0a9c1a..6844d9c0 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -21,6 +21,7 @@ mod curvature_mode; mod decal_flip; mod decal_symmetry; mod distance_parameters; +mod dripping_rust_parameters; mod filtering; mod generator_global; mod generator_grayscale; @@ -56,6 +57,7 @@ pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use distance_parameters::DistanceParameters; +pub use dripping_rust_parameters::DrippingRustParameters; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; @@ -968,10 +970,12 @@ pub enum GeneratorKind { UvBorderDistance, /// An image turned gray, tiled and rotated across the UV square GrayscaleConversion, + /// Rust in the occluded areas, running down the mesh in drips + DrippingRust, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 13] = [ + pub const ALL: [GeneratorKind; 14] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -985,6 +989,7 @@ impl GeneratorKind { GeneratorKind::ThreeDLinearGradient, GeneratorKind::UvBorderDistance, GeneratorKind::GrayscaleConversion, + GeneratorKind::DrippingRust, ]; pub fn label(self) -> &'static str { match self { @@ -1001,6 +1006,7 @@ impl GeneratorKind { GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", GeneratorKind::UvBorderDistance => "UV Border Distance", GeneratorKind::GrayscaleConversion => "Grayscale Conversion", + GeneratorKind::DrippingRust => "Dripping Rust", } } @@ -1020,6 +1026,7 @@ impl GeneratorKind { GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", GeneratorKind::UvBorderDistance => "UvBorderDistance", GeneratorKind::GrayscaleConversion => "GrayscaleConversion", + GeneratorKind::DrippingRust => "DrippingRust", } } @@ -1032,12 +1039,13 @@ impl GeneratorKind { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust ) } /// Whether the kind's result depends on its seed pub fn includes_randomness(self) -> bool { - matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear) + matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust) } /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. @@ -1050,7 +1058,8 @@ impl GeneratorKind { GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], - GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion => &[], + // Dripping Rust reads the baked occlusion and the mesh's bounds whole, so no input replaces them yet + GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust => &[], } } @@ -1063,6 +1072,7 @@ impl GeneratorKind { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust ) } diff --git a/crates/core/src/layer/dripping_rust_parameters.rs b/crates/core/src/layer/dripping_rust_parameters.rs new file mode 100644 index 00000000..879044ed --- /dev/null +++ b/crates/core/src/layer/dripping_rust_parameters.rs @@ -0,0 +1,55 @@ +use serde::{Deserialize, Serialize}; + +/// The Dripping Rust generator's controls: rust in the occluded areas, running down in drips +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DrippingRustParameters { + /// How far the rust spreads: 0 none, 1 everywhere + pub spreading: f32, + /// How hard the rust's edge is (0..1; 1 a hard step) + pub contrast: f32, + /// Softens the rust before it drips (0..1) + pub spreading_smoothness: f32, + /// How far the drips run (0..1) + pub drips_intensity: f32, + /// Softens the drips (0..1) + pub drips_smoothness: f32, + /// How many steps each drip is drawn with ([`DrippingRustParameters::MAX_SAMPLES`] at most) + pub drips_samples: u32, + /// The axis of the mesh's bounds the drips run down: 0 X, 1 Y, 2 Z + pub axis: u8, +} + +impl DrippingRustParameters { + pub const MAX_SAMPLES: u32 = 32; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> DrippingRustParameters { + let defaults = DrippingRustParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + DrippingRustParameters { + spreading: unit(self.spreading, defaults.spreading), + contrast: unit(self.contrast, defaults.contrast), + spreading_smoothness: unit(self.spreading_smoothness, defaults.spreading_smoothness), + drips_intensity: unit(self.drips_intensity, defaults.drips_intensity), + drips_smoothness: unit(self.drips_smoothness, defaults.drips_smoothness), + drips_samples: self.drips_samples.min(DrippingRustParameters::MAX_SAMPLES), + axis: self.axis.min(2), + } + } +} + +impl Default for DrippingRustParameters { + /// The reference app's defaults + fn default() -> DrippingRustParameters { + DrippingRustParameters { + spreading: 0.5, + contrast: 0.5, + spreading_smoothness: 0.0, + drips_intensity: 0.1, + drips_smoothness: 0.05, + drips_samples: 32, + axis: 1, + } + } +} diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index abfd61b5..83b820cd 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; -use super::{BorderDistanceParameters, DistanceParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; +use super::{BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; /// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -10,6 +10,7 @@ pub enum KindControls { LinearGradient(LinearGradientParameters), BorderDistance(BorderDistanceParameters), Grayscale(GrayscaleConversionParameters), + DrippingRust(DrippingRustParameters), } impl KindControls { @@ -20,6 +21,7 @@ impl KindControls { GeneratorKind::ThreeDLinearGradient => Some(KindControls::LinearGradient(LinearGradientParameters::default())), GeneratorKind::UvBorderDistance => Some(KindControls::BorderDistance(BorderDistanceParameters::default())), GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), + GeneratorKind::DrippingRust => Some(KindControls::DrippingRust(DrippingRustParameters::default())), GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas @@ -39,6 +41,7 @@ impl KindControls { KindControls::LinearGradient(gradient) => KindControls::LinearGradient(gradient.clamped()), KindControls::BorderDistance(border) => KindControls::BorderDistance(border.clamped()), KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), + KindControls::DrippingRust(rust) => KindControls::DrippingRust(rust.clamped()), } } @@ -49,6 +52,7 @@ impl KindControls { KindControls::LinearGradient(_) => GeneratorKind::ThreeDLinearGradient, KindControls::BorderDistance(_) => GeneratorKind::UvBorderDistance, KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, + KindControls::DrippingRust(_) => GeneratorKind::DrippingRust, } } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index dc2c5f4b..63ed7115 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -77,7 +77,8 @@ impl MicroDetails { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => None, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 153640f8..375534b9 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -43,7 +43,8 @@ impl SectionParameters { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => None, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 6acde341..32d478c5 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -62,7 +62,8 @@ impl WearParameters { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => None, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 33b70ff6..09320d73 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 120d3d42..0c67f2a0 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,10 +1,10 @@ //! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{Generator, GeneratorKind, GeneratorGrayscale, KindControls}; +use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls}; use crate::Result; -use crate::commands::{bad, boolp, color_param, f32p}; +use crate::commands::{bad, boolp, color_param, f32p, u64p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; @@ -18,6 +18,10 @@ pub const BORDER_DISTANCE_KEYS: [&str; 4] = ["borderDistance", "borderSmoothness /// The Grayscale Conversion controls (its image is the `image` input) pub const GRAYSCALE_KEYS: [&str; 6] = ["grayscaleType", "grayscaleBalance", "grayscaleContrast", "grayscaleTile", "grayscaleRotation", "grayscaleSafeRotation"]; +/// The Dripping Rust controls (it also takes the seed and invert) +pub const DRIPPING_RUST_KEYS: [&str; 7] = + ["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; @@ -29,6 +33,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient), (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), + (&DRIPPING_RUST_KEYS[..], GeneratorKind::DrippingRust), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); @@ -46,6 +51,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::GrayscaleConversion { return grayscale_from(command, params, generator); } + if kind == GeneratorKind::DrippingRust { + return dripping_rust_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -119,6 +127,36 @@ fn grayscale_from(command: &str, params: &Value, generator: &mut Generator) -> R Ok(()) } +/// The Dripping Rust controls in `params` (the generator is one) +fn dripping_rust_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let Some(KindControls::DrippingRust(mut rust)) = generator.kind_controls() else { return Ok(()) }; + for (key, value) in [ + ("rustSpreading", &mut rust.spreading), + ("rustContrast", &mut rust.contrast), + ("spreadingSmoothness", &mut rust.spreading_smoothness), + ("dripsIntensity", &mut rust.drips_intensity), + ("dripsSmoothness", &mut rust.drips_smoothness), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(samples) = u64p(params, "dripsSamples") { + rust.drips_samples = samples.min(u64::from(DrippingRustParameters::MAX_SAMPLES)) as u32; + } + if let Some(value) = params.get("dripsAxis") { + let name = value.as_str().ok_or_else(|| bad(command, "`dripsAxis` must be x, y or z"))?; + rust.axis = match name.to_ascii_lowercase().as_str() { + "x" => 0, + "y" => 1, + "z" => 2, + _ => return Err(bad(command, format!("unknown axis `{name}`: x, y or z"))), + }; + } + generator.controls = Some(Box::new(KindControls::DrippingRust(rust.clamped()))); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 3cb7a868..95811f45 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 7e7ab4ef..c9e63424 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,8 +1,8 @@ -//! The 3D Distance, 3D Linear Gradient and UV Border Distance generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point +//! The generators with only their own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion, Dripping Rust) through `effect.add.generator` and `effect.set`: their controls and the controls they lack use serde_json::{Value, json}; use texturecraft_engine::core::{ - BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LinearGradientParameters, Source, + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, }; use texturecraft_engine::{Session, execute}; @@ -120,3 +120,19 @@ fn grayscale_conversion_takes_its_controls_and_its_image() { assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "input": "image", "inputImage": name})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "grayscaleTile": 2})).is_err()); } + +#[test] +fn dripping_rust_takes_its_controls_its_seed_and_its_axis() { + let mut session = session(); + let params = json!({"generator": "Dripping Rust", "rustSpreading": 0.7, "dripsIntensity": 0.4, "dripsSamples": 99, "dripsAxis": "X", "seed": 3}); + let effect = add(&mut session, params); + + let made = generator(&session, effect); + let expected = DrippingRustParameters { spreading: 0.7, drips_intensity: 0.4, drips_samples: 32, axis: 0, ..DrippingRustParameters::default() }; + assert_eq!(made.kind_controls(), Some(KindControls::DrippingRust(expected)), "samples stop at 32"); + assert_eq!(made.seed, 3); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "dripsAxis": "w"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "level": 0.2})).is_err()); + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "rustSpreading": 0.2})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index f7335dc8..01eee8de 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -101,6 +101,9 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { } GeneratorKind::UvBorderDistance => (tr("A gradient in from the UV islands' borders."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), GeneratorKind::GrayscaleConversion => (tr("An image turned gray."), [tr("mask"), tr("generator"), tr("grayscale"), tr("image")]), + GeneratorKind::DrippingRust => { + (tr("Rust in occluded areas, running down in drips."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) + } }; // Wrapped rows: a long line must not widen the panel past its edge From 59fd1bc705f5a373a61bbafcea2fc94aecaf5c98 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:14:23 +0000 Subject: [PATCH 109/153] Polygon fill: the triangle grouping moves to geom, for generators to share TrianglePartition and the UV edge key (with its corner grid) move from the engine into texturecraft-geom unchanged, beside the mesh they group, with a uv_islands constructor polygon fill now uses for its UV island mode. The compositor can then group texels by UV island for the UV island generators without depending on the engine. --- crates/engine/src/lib.rs | 1 - crates/engine/src/polygon_fill.rs | 23 ++------------ crates/engine/src/polygon_fill_drag.rs | 2 +- crates/engine/src/polygon_fill_mirror.rs | 2 +- crates/geom/src/lib.rs | 2 ++ .../src/triangle_partition.rs | 30 +++++++++++++++++-- 6 files changed, 34 insertions(+), 26 deletions(-) rename crates/{engine => geom}/src/triangle_partition.rs (78%) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 041aca62..336ba602 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -86,7 +86,6 @@ mod tile_transform_params; mod tool_availability; pub mod tool_cmds; pub mod tool_settings; -mod triangle_partition; mod uv_stroke_state; mod uv_symmetry; pub mod uv_tile_cmds; diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index 3292c61b..4f65c090 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -5,18 +5,15 @@ use std::collections::{BTreeSet, HashSet}; use texturecraft_compose::MaskGray; use texturecraft_geom::glam::Vec2; -use texturecraft_geom::{Mesh, NO_TRI}; +use texturecraft_geom::triangle_partition::CORNER_GRID_STEPS; +use texturecraft_geom::{Mesh, NO_TRI, TrianglePartition}; use texturecraft_paint::{EyeDepth, fill_triangles, screen_point}; use crate::fill_mode::FillMode; use crate::polygon_fill_drag::PolygonFillDrag; 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; - 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 { @@ -178,7 +175,7 @@ impl Session { 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::UvIsland => TrianglePartition::uv_islands(&self.mesh, material), FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges), } } @@ -298,12 +295,6 @@ fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range { first..end.max(first) } -/// 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)?]) -} - /// 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); @@ -318,14 +309,6 @@ fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { .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)); diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs index 09c20905..39c64507 100644 --- a/crates/engine/src/polygon_fill_drag.rs +++ b/crates/engine/src/polygon_fill_drag.rs @@ -9,7 +9,7 @@ use texturecraft_paint::EyeDepth; use texturecraft_texel::TileImage; use crate::session::{Document, StackTarget}; -use crate::triangle_partition::TrianglePartition; +use texturecraft_geom::TrianglePartition; /// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends pub(crate) struct PolygonFillDrag { diff --git a/crates/engine/src/polygon_fill_mirror.rs b/crates/engine/src/polygon_fill_mirror.rs index 945d15bb..fd362ff2 100644 --- a/crates/engine/src/polygon_fill_mirror.rs +++ b/crates/engine/src/polygon_fill_mirror.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeSet, HashSet}; use texturecraft_geom::glam::Mat3; use crate::session::Session; -use crate::triangle_partition::TrianglePartition; +use texturecraft_geom::TrianglePartition; /// How far a mirrored face centre may be from the surface and still count as on it, as a fraction of the mesh's bounding-box diagonal const MIRROR_TOLERANCE: f32 = 1e-3; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3ca0f8ed..eb71f854 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,6 +11,7 @@ pub mod camera; pub mod gbuffer; pub mod mesh; pub mod primitives; +pub mod triangle_partition; pub mod unwrap; pub use bvh::{Bvh, Hit}; @@ -18,6 +19,7 @@ pub use camera::{OrbitCamera, Ray}; pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at}; pub use glam; pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; +pub use triangle_partition::TrianglePartition; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum GeomError { diff --git a/crates/engine/src/triangle_partition.rs b/crates/geom/src/triangle_partition.rs similarity index 78% rename from crates/engine/src/triangle_partition.rs rename to crates/geom/src/triangle_partition.rs index d6ad31cb..ab578c2c 100644 --- a/crates/engine/src/triangle_partition.rs +++ b/crates/geom/src/triangle_partition.rs @@ -1,9 +1,14 @@ -//! Triangles of one material grouped into the pieces polygon fill selects and fills. +//! Triangles of one material grouped into pieces joined across shared edges: the UV islands, polygons or connected meshes polygon fill selects and the UV island generators colour use std::collections::HashMap; use std::hash::Hash; -use texturecraft_geom::Mesh; +use glam::Vec2; + +use crate::Mesh; + +/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner +pub const CORNER_GRID_STEPS: f32 = 1e5; /// A material's triangles split into groups joined across shared edges pub struct TrianglePartition { @@ -58,15 +63,34 @@ impl TrianglePartition { self.group_of.get(&triangle).copied() } + /// `material`'s UV islands: triangles joined where they share an edge in UV space + pub fn uv_islands(mesh: &Mesh, material: usize) -> TrianglePartition { + TrianglePartition::new(mesh, material, uv_edges) + } + /// 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) } } +/// 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)?]) +} + +/// `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 +pub 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() +} + #[cfg(test)] mod tests { - use texturecraft_geom::primitives; + use crate::primitives; use super::*; From 44a8af0943dce788dfd14e8fd2423667b1fc957a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:24:31 +0000 Subject: [PATCH 110/153] Generators: UV Random Color, one random value per UV island MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new kind with the reference's controls: Seed and Color Source Mode (Random, or Custom Gradient with its colors). Each UV island (triangles joined across shared UV edges, as polygon fill groups them) gets a seeded random color, or the gradient's color at a random point, and the mask reads the mean of its channels. The reference's random numbers are its own, so islands differ in value but not in kind: on the test gun every island is one flat value in both, with island means spread alike (0.52 ± 0.16 against the reference's 0.50 ± 0.15). As a mask it is gray; a colored fill would need generators in content stacks. Generator maps now hold one whole-map field for UV Border Distance, Dripping Rust and UV Random Color. Commands only. --- crates/compose/src/eval.rs | 28 ++--- crates/compose/src/generator_maps.rs | 15 ++- crates/compose/src/lib.rs | 1 + crates/compose/src/uv_islands.rs | 48 +++++++++ .../tests/generator_uv_random_color.rs | 102 ++++++++++++++++++ crates/core/src/layer.rs | 18 +++- crates/core/src/layer/kind_controls.rs | 9 +- crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- .../src/layer/uv_random_color_parameters.rs | 29 +++++ crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 30 +++++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 14 ++- crates/ui-egui/src/generator_panel.rs | 1 + 16 files changed, 274 insertions(+), 34 deletions(-) create mode 100644 crates/compose/src/uv_islands.rs create mode 100644 crates/compose/tests/generator_uv_random_color.rs create mode 100644 crates/core/src/layer/uv_random_color_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52625777..b719fe21 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2502,7 +2502,8 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::linear_gradient_value(gradient, position); } - Some(KindControls::BorderDistance(border)) => { - let texel = (self.y * self.inp.gbuf.width + self.x) as usize; - let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); - return uv_border_distance::border_value(border, gradient); - } + Some(KindControls::BorderDistance(border)) => return uv_border_distance::border_value(border, self.field_value(maps)), Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), - Some(KindControls::DrippingRust(rust)) => { - let texel = (self.y * self.inp.gbuf.width + self.x) as usize; - let field = maps.rust_field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0); - return dripping_rust::rust_value(rust, field); - } + Some(KindControls::DrippingRust(rust)) => return dripping_rust::rust_value(rust, self.field_value(maps)), + Some(KindControls::UvRandomColor(_)) => return self.field_value(maps), None => {} } @@ -3490,7 +3484,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor, _, ) => 0.0, }; @@ -3542,7 +3537,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => 0.0, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => 0.0, } } @@ -3554,6 +3550,12 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// A generator's whole-map field at this texel (0 without one) + fn field_value(&self, maps: &GeneratorMaps) -> f32 { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + maps.field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0) + } + /// The Grayscale Conversion generator at this texel: its image tiled and turned about the UV square's centre, made gray, balanced and contrasted fn grayscale_conversion(&mut self, grayscale: &GrayscaleConversionParameters) -> f32 { let degrees = if grayscale.safe_rotation { (grayscale.rotation / QUARTER_TURN_DEGREES).round() * QUARTER_TURN_DEGREES } else { grayscale.rotation }; diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index acced92c..6206889d 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -9,6 +9,7 @@ use crate::dripping_rust::rust_field; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; use crate::uv_border_distance::border_gradient; +use crate::uv_islands::random_color_field; /// What a generator reads beyond its texel: built once per map and settings, shared by every tile #[derive(Clone, Default)] @@ -19,10 +20,8 @@ pub(crate) struct GeneratorMaps { pub micro_curvature: Option>, /// What its micro details multiply its occlusion by pub micro_occlusion: Option>, - /// The UV Border Distance gradient at every working texel - pub border_gradient: Option>>, - /// The Dripping Rust field at every working texel - pub rust_field: Option>>, + /// The whole-map field of UV Border Distance, Dripping Rust or UV Random Color at every working texel + pub field: Option>>, /// The controls of a kind with only its own controls, brought into range pub controls: Option>, } @@ -39,14 +38,12 @@ impl GeneratorMaps { None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), }; let controls = generator.kind_controls(); - let border_gradient = match &controls { + let field = match &controls { Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), - _ => None, - }; - let rust_field = match &controls { Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), + Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)), _ => None, }; - GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, rust_field, controls: controls.map(Arc::new) } + GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) } } } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 09ae63d8..eb85e0ae 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -54,6 +54,7 @@ mod tile_pattern; mod tile_random_stream; mod timber; mod uv_border_distance; +mod uv_islands; pub mod warp; mod warp_source_sample; mod warp_texel; diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs new file mode 100644 index 00000000..400afeae --- /dev/null +++ b/crates/compose/src/uv_islands.rs @@ -0,0 +1,48 @@ +//! The UV island generators: a value per UV island at every working texel, built once per layout and settings + +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{UvRandomColorParameters, gradient}; +use texturecraft_geom::TrianglePartition; +use texturecraft_texel::noise::cell_hash; + +use crate::eval::Inputs; +use crate::working_field::FieldCache; + +static CACHE: FieldCache = FieldCache::new(); + +/// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) +pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { + let mut settings = vec![seed, u32::from(random.custom_gradient)]; + settings.extend(random.gradient.iter().flat_map(|color| color.map(f32::to_bits))); + CACHE.get_or_build(inp, &[], settings, |_| { + let island_values = island_values(inp, |island| random_gray(random, seed, island)); + let gbuf = inp.gbuf; + gbuf.tri.par_iter().map(|triangle| island_values.get(triangle).copied().unwrap_or(0.0)).collect() + }) +} + +/// The value `value_of` gives each UV island, by triangle +fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> std::collections::HashMap { + let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); + let islands = TrianglePartition::uv_islands(inp.mesh, material); + islands + .groups + .iter() + .enumerate() + .flat_map(|(island, triangles)| triangles.iter().map(move |triangle| (*triangle, island as u32))) + .map(|(triangle, island)| (triangle, value_of(island))) + .collect() +} + +/// An island's gray: the mean of a random color's channels, or of the gradient's color at a random point +fn random_gray(random: &UvRandomColorParameters, seed: u32, island: u32) -> f32 { + let island = island as i32; + let color = if random.custom_gradient { + gradient(&random.gradient, cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) + } else { + std::array::from_fn(|channel| cell_hash(island, channel as i32 + 1, 0, seed)) + }; + color.iter().sum::() / 3.0 +} diff --git a/crates/compose/tests/generator_uv_random_color.rs b/crates/compose/tests/generator_uv_random_color.rs new file mode 100644 index 00000000..529bc354 --- /dev/null +++ b/crates/compose/tests/generator_uv_random_color.rs @@ -0,0 +1,102 @@ +//! The UV Random Color generator on a cube: one value per UV island, reshuffled by the seed, or picked along a gradient + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, TextureSet, + UvRandomColorParameters, +}; +use texturecraft_geom::{Mesh, TrianglePartition, UvGBuffer, primitives}; + +const RES: u32 = 128; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, +} + +fn fixture() -> Fixture { + let mesh = primitives::cube(1.0); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:cube"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer } +} + +/// Every covered texel and its UV island +fn covered(fixture: &Fixture) -> Vec<((u32, u32), usize)> { + let islands = TrianglePartition::uv_islands(&fixture.mesh, 0); + (0..RES * RES) + .filter_map(|index| { + let triangle = *fixture.gbuf.tri.get(index as usize)?; + islands.index_of(triangle).map(|island| ((index % RES, index / RES), island)) + }) + .collect() +} + +fn mask(fixture: &mut Fixture, random: UvRandomColorParameters, seed: u32, texels: &[(u32, u32)]) -> Vec { + let generator = Generator { controls: Some(Box::new(KindControls::UvRandomColor(random))), seed, ..Generator::new(GeneratorKind::UvRandomColor) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// Each island's values, by island +fn by_island(texels: &[((u32, u32), usize)], values: &[f32]) -> std::collections::BTreeMap> { + let mut islands = std::collections::BTreeMap::>::new(); + for ((_, island), value) in texels.iter().zip(values) { + islands.entry(*island).or_default().push(*value); + } + islands +} + +#[test] +fn each_island_is_one_value_and_the_islands_differ() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + + let islands = by_island(&texels, &mask(&mut fixture, UvRandomColorParameters::default(), 0, &at)); + assert!(islands.len() > 1, "the cube has several UV islands"); + assert!(islands.values().all(|values| values.iter().all(|value| (value - values[0]).abs() < 1e-6))); + let firsts: Vec = islands.values().map(|values| values[0]).collect(); + assert!(firsts.iter().any(|value| (value - firsts[0]).abs() > 0.01)); +} + +#[test] +fn the_seed_reshuffles_the_values() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let first = mask(&mut fixture, UvRandomColorParameters::default(), 0, &at); + let second = mask(&mut fixture, UvRandomColorParameters::default(), 2, &at); + assert_ne!(first, second); +} + +#[test] +fn a_one_color_gradient_colors_every_island_alike() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let values = mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]] }, 0, &at); + assert!(values.iter().all(|value| (value - 0.2).abs() < 1e-5), "the mean of its channels"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 6844d9c0..d74cfbf8 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -44,6 +44,7 @@ mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_random_color_parameters; mod uv_transform; mod uv_wrap; mod wear_parameters; @@ -80,6 +81,7 @@ pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_random_color_parameters::UvRandomColorParameters; pub use uv_transform::UvTransform; pub use uv_wrap::UvWrap; pub use wear_parameters::WearParameters; @@ -972,10 +974,12 @@ pub enum GeneratorKind { GrayscaleConversion, /// Rust in the occluded areas, running down the mesh in drips DrippingRust, + /// One random value per UV island + UvRandomColor, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 14] = [ + pub const ALL: [GeneratorKind; 15] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -990,6 +994,7 @@ impl GeneratorKind { GeneratorKind::UvBorderDistance, GeneratorKind::GrayscaleConversion, GeneratorKind::DrippingRust, + GeneratorKind::UvRandomColor, ]; pub fn label(self) -> &'static str { match self { @@ -1007,6 +1012,7 @@ impl GeneratorKind { GeneratorKind::UvBorderDistance => "UV Border Distance", GeneratorKind::GrayscaleConversion => "Grayscale Conversion", GeneratorKind::DrippingRust => "Dripping Rust", + GeneratorKind::UvRandomColor => "UV Random Color", } } @@ -1027,6 +1033,7 @@ impl GeneratorKind { GeneratorKind::UvBorderDistance => "UvBorderDistance", GeneratorKind::GrayscaleConversion => "GrayscaleConversion", GeneratorKind::DrippingRust => "DrippingRust", + GeneratorKind::UvRandomColor => "UvRandomColor", } } @@ -1040,12 +1047,16 @@ impl GeneratorKind { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor ) } /// Whether the kind's result depends on its seed pub fn includes_randomness(self) -> bool { - matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust) + matches!( + self, + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + ) } /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. @@ -1059,7 +1070,7 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], // Dripping Rust reads the baked occlusion and the mesh's bounds whole, so no input replaces them yet - GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust => &[], + GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor => &[], } } @@ -1073,6 +1084,7 @@ impl GeneratorKind { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor ) } diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index 83b820cd..76292879 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -1,6 +1,9 @@ use serde::{Deserialize, Serialize}; -use super::{BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; +use super::{ + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters, + UvRandomColorParameters, +}; /// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -11,6 +14,7 @@ pub enum KindControls { BorderDistance(BorderDistanceParameters), Grayscale(GrayscaleConversionParameters), DrippingRust(DrippingRustParameters), + UvRandomColor(UvRandomColorParameters), } impl KindControls { @@ -22,6 +26,7 @@ impl KindControls { GeneratorKind::UvBorderDistance => Some(KindControls::BorderDistance(BorderDistanceParameters::default())), GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), GeneratorKind::DrippingRust => Some(KindControls::DrippingRust(DrippingRustParameters::default())), + GeneratorKind::UvRandomColor => Some(KindControls::UvRandomColor(UvRandomColorParameters::default())), GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas @@ -42,6 +47,7 @@ impl KindControls { KindControls::BorderDistance(border) => KindControls::BorderDistance(border.clamped()), KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), KindControls::DrippingRust(rust) => KindControls::DrippingRust(rust.clamped()), + KindControls::UvRandomColor(random) => KindControls::UvRandomColor(random.clamped()), } } @@ -53,6 +59,7 @@ impl KindControls { KindControls::BorderDistance(_) => GeneratorKind::UvBorderDistance, KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, KindControls::DrippingRust(_) => GeneratorKind::DrippingRust, + KindControls::UvRandomColor(_) => GeneratorKind::UvRandomColor, } } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 63ed7115..ed99f19c 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -78,7 +78,8 @@ impl MicroDetails { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => None, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 375534b9..8c1a6744 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -44,7 +44,8 @@ impl SectionParameters { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => None, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => None, } } diff --git a/crates/core/src/layer/uv_random_color_parameters.rs b/crates/core/src/layer/uv_random_color_parameters.rs new file mode 100644 index 00000000..156a1be0 --- /dev/null +++ b/crates/core/src/layer/uv_random_color_parameters.rs @@ -0,0 +1,29 @@ +use serde::{Deserialize, Serialize}; + +/// The UV Random Color generator's controls: one random value per UV island, picked at random or along a gradient +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UvRandomColorParameters { + /// Pick each island's color along [`UvRandomColorParameters::gradient`] instead of at random + pub custom_gradient: bool, + /// The gradient's colors, evenly spaced (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) + pub gradient: Vec<[f32; 3]>, +} + +impl UvRandomColorParameters { + pub const MAX_GRADIENT_COLORS: usize = 16; + + /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one + pub fn clamped(self) -> UvRandomColorParameters { + let unit = |value: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; + let gradient: Vec<[f32; 3]> = self.gradient.into_iter().take(UvRandomColorParameters::MAX_GRADIENT_COLORS).map(|color| color.map(unit)).collect(); + UvRandomColorParameters { gradient: if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }, ..self } + } +} + +impl Default for UvRandomColorParameters { + /// Random colors; the gradient black to white + fn default() -> UvRandomColorParameters { + UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]] } + } +} diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 32d478c5..ab081fed 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -63,7 +63,8 @@ impl WearParameters { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => None, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 09320d73..03c5f7ba 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvRandomColorParameters, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 0c67f2a0..1de81fae 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,10 +1,10 @@ //! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls}; +use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls, UvRandomColorParameters}; use crate::Result; -use crate::commands::{bad, boolp, color_param, f32p, u64p}; +use crate::commands::{bad, boolp, color_of, color_param, f32p, u64p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; @@ -22,6 +22,9 @@ pub const GRAYSCALE_KEYS: [&str; 6] = ["grayscaleType", "grayscaleBalance", "gra pub const DRIPPING_RUST_KEYS: [&str; 7] = ["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"]; +/// The UV Random Color controls (it also takes the seed) +pub const UV_RANDOM_COLOR_KEYS: [&str; 2] = ["colorSourceMode", "gradientColors"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; @@ -34,6 +37,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), (&DRIPPING_RUST_KEYS[..], GeneratorKind::DrippingRust), + (&UV_RANDOM_COLOR_KEYS[..], GeneratorKind::UvRandomColor), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); @@ -54,6 +58,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::DrippingRust { return dripping_rust_from(command, params, generator); } + if kind == GeneratorKind::UvRandomColor { + return uv_random_color_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -157,6 +164,25 @@ fn dripping_rust_from(command: &str, params: &Value, generator: &mut Generator) Ok(()) } +/// The UV Random Color controls in `params` (the generator is one) +fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let Some(KindControls::UvRandomColor(mut random)) = generator.kind_controls() else { return Ok(()) }; + if let Some(value) = params.get("colorSourceMode") { + random.custom_gradient = match value.as_str().map(str::to_ascii_lowercase).as_deref() { + Some("random") => false, + Some("customgradient" | "custom gradient" | "gradient") => true, + _ => return Err(bad(command, "`colorSourceMode` must be random or customGradient")), + }; + } + if let Some(value) = params.get("gradientColors") { + let invalid = || bad(command, "`gradientColors` takes 1 to 16 colors, each [r, g, b] or \"#rrggbb\""); + let items = value.as_array().filter(|items| (1..=UvRandomColorParameters::MAX_GRADIENT_COLORS).contains(&items.len())).ok_or_else(invalid)?; + random.gradient = items.iter().map(|item| color_of(item).ok_or_else(invalid)).collect::>()?; + } + generator.controls = Some(Box::new(KindControls::UvRandomColor(random.clamped()))); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 95811f45..9dc863d9 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index c9e63424..732c5a28 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use texturecraft_engine::core::{ - BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, UvRandomColorParameters, }; use texturecraft_engine::{Session, execute}; @@ -136,3 +136,15 @@ fn dripping_rust_takes_its_controls_its_seed_and_its_axis() { let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "rustSpreading": 0.2})).is_err()); } + +#[test] +fn uv_random_color_takes_its_mode_and_gradient() { + let mut session = session(); + let params = json!({"generator": "UV Random Color", "colorSourceMode": "customGradient", "gradientColors": [[2.0, 0.5, 0.0], "#000000"]}); + let effect = add(&mut session, params); + + let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]] }; + assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvRandomColor(expected)), "colors stay within 0..1"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": []})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "colorSourceMode": "fancy"})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 01eee8de..51c9d7e9 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -104,6 +104,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::DrippingRust => { (tr("Rust in occluded areas, running down in drips."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) } + GeneratorKind::UvRandomColor => (tr("A random value per UV island."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; // Wrapped rows: a long line must not widen the panel past its edge From f3d5cbe40c5ad549f5af2ad7a92bac9c21486146 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:07:20 +0000 Subject: [PATCH 111/153] Generators: UV Checker, a checker and grid over each UV tile with the islands' borders A new kind with the reference's controls: Seed, Checker Color Mode (Uniform, or Random per UV island), Checker Color, Checker Grid Tile, Checker Grid Opacity, UV Borders Color and UV Borders Width. Fitted to the reference's color captures: four checker squares per grid tile, dark squares a shade of the light color; minor grid lines every quarter square and major ones on the square edges, each layer laid over the last at the grid opacity; texels within the border width (0.2 is 3 texels at 2K) of an island's edge take the border color; random mode gives each island its own light color; the mask reads the mean of the sRGB-encoded channels, as the reference does. On the test gun 99.9% of texels match the reference within 1/255, at the default and with the grid off (the rest lie on seams where two islands touch in UV, which coverage alone can't tell apart). Lines and borders test a texel's whole footprint, so they stay visible below 2K. Commands only. --- crates/compose/src/eval.rs | 14 +- crates/compose/src/generator_maps.rs | 5 +- crates/compose/src/uv_border_distance.rs | 2 +- crates/compose/src/uv_islands.rs | 127 +++++++++++++++++- crates/compose/tests/generator_uv_checker.rs | 76 +++++++++++ crates/core/src/layer.rs | 24 +++- crates/core/src/layer/kind_controls.rs | 6 +- crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- .../core/src/layer/uv_checker_parameters.rs | 51 +++++++ crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 8 +- crates/engine/src/distance_params.rs | 37 ++++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 16 ++- crates/ui-egui/src/generator_panel.rs | 1 + 16 files changed, 354 insertions(+), 24 deletions(-) create mode 100644 crates/compose/tests/generator_uv_checker.rs create mode 100644 crates/core/src/layer/uv_checker_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b719fe21..06f95001 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2502,8 +2502,10 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { Some(KindControls::BorderDistance(border)) => return uv_border_distance::border_value(border, self.field_value(maps)), Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), Some(KindControls::DrippingRust(rust)) => return dripping_rust::rust_value(rust, self.field_value(maps)), - Some(KindControls::UvRandomColor(_)) => return self.field_value(maps), + Some(KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) => return self.field_value(maps), None => {} } @@ -3485,7 +3487,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker, _, ) => 0.0, }; @@ -3538,7 +3541,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => 0.0, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 6206889d..151ae176 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -9,7 +9,7 @@ use crate::dripping_rust::rust_field; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; use crate::uv_border_distance::border_gradient; -use crate::uv_islands::random_color_field; +use crate::uv_islands::{checker_field, random_color_field}; /// What a generator reads beyond its texel: built once per map and settings, shared by every tile #[derive(Clone, Default)] @@ -20,7 +20,7 @@ pub(crate) struct GeneratorMaps { pub micro_curvature: Option>, /// What its micro details multiply its occlusion by pub micro_occlusion: Option>, - /// The whole-map field of UV Border Distance, Dripping Rust or UV Random Color at every working texel + /// The whole-map field of UV Border Distance, Dripping Rust, UV Random Color or UV Checker at every working texel pub field: Option>>, /// The controls of a kind with only its own controls, brought into range pub controls: Option>, @@ -42,6 +42,7 @@ impl GeneratorMaps { Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)), + Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, checker, generator.seed)), _ => None, }; GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index 0fa3afd0..c4d1af41 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -67,7 +67,7 @@ fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> } /// Each texel's Euclidean distance in texels to the nearest uncovered texel of its UV tile block, the space past the block's edges counting as uncovered -fn border_distances(gbuf: &texturecraft_geom::UvGBuffer, (width, height): (u32, u32), block: (u32, u32)) -> Vec { +pub(crate) fn border_distances(gbuf: &texturecraft_geom::UvGBuffer, (width, height): (u32, u32), block: (u32, u32)) -> Vec { let mut squared = vec![0.0f32; (width * height) as usize]; for top in (0..height).step_by(block.1 as usize) { for left in (0..width).step_by(block.0 as usize) { diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 400afeae..25a23d10 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -1,13 +1,16 @@ -//! The UV island generators: a value per UV island at every working texel, built once per layout and settings +//! The UV island generators (UV Random Color, UV Checker) at every working texel, built once per layout and settings +use std::collections::HashMap; use std::sync::Arc; use rayon::prelude::*; -use texturecraft_core::{UvRandomColorParameters, gradient}; -use texturecraft_geom::TrianglePartition; +use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters, gradient}; +use texturecraft_geom::{NO_TRI, TrianglePartition}; +use texturecraft_texel::linear_to_srgb; use texturecraft_texel::noise::cell_hash; -use crate::eval::Inputs; +use crate::eval::{Inputs, texel_coords}; +use crate::uv_border_distance::border_distances; use crate::working_field::FieldCache; static CACHE: FieldCache = FieldCache::new(); @@ -24,7 +27,7 @@ pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, } /// The value `value_of` gives each UV island, by triangle -fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> std::collections::HashMap { +fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> HashMap { let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); let islands = TrianglePartition::uv_islands(inp.mesh, material); islands @@ -46,3 +49,117 @@ fn random_gray(random: &UvRandomColorParameters, seed: u32, island: u32) -> f32 }; color.iter().sum::() / 3.0 } + +/// Checker squares across one grid tile, and grid lines across one square (fitted) +const SQUARES_PER_GRID_TILE: f32 = 4.0; +const MINOR_LINES_PER_SQUARE: f32 = 4.0; + +/// The dark squares are the light color times this, on its sRGB-encoded values (fitted) +const DARK_SQUARE_SHADE: f32 = 0.7128; + +/// What a full-opacity minor and major grid line multiply the color by (fitted) +const MINOR_LINE_SHADE: f32 = 0.8465; +const MAJOR_LINE_SHADE: f32 = 0.4230; + +/// Texels of a 2K UV tile a grid line lies within of its square's edge, and the border's width per unit of UV Borders Width (fitted: 0.2 is 3 texels) +const LINE_HALF_WIDTH_2K: f32 = 1.0; +const BORDER_TEXELS_PER_WIDTH_2K: f32 = 15.0; + +/// The UV tile resolution the sizes above are measured at +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// The saturation and value random island colors are picked within (measured) +const RANDOM_SATURATION: std::ops::RangeInclusive = 0.06..=0.57; +const RANDOM_VALUE: std::ops::RangeInclusive = 0.42..=0.80; + +/// UV Checker at every working texel of `inp`: the gray of its color, the mean of the sRGB-encoded channels as the reference reads it (0 outside the islands) +pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u32) -> Arc> { + let mut settings = vec![seed, u32::from(checker.random_colors), checker.grid_tile, checker.grid_opacity.to_bits(), checker.border_width.to_bits()]; + settings.extend(checker.checker_color.iter().chain(&checker.border_color).map(|value| value.to_bits())); + CACHE.get_or_build(inp, &[], settings, |block| { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + let island_colors = if checker.random_colors { island_colors(inp, seed) } else { HashMap::new() }; + let distances = border_distances(gbuf, (width, height), block); + let light = checker.checker_color.map(linear_to_srgb); + let border = checker.border_color.map(linear_to_srgb); + + (0..width * height) + .into_par_iter() + .map(|texel| { + let Some(triangle) = gbuf.tri.get(texel as usize).copied().filter(|triangle| *triangle != NO_TRI) else { return 0.0 }; + let (x, y) = (texel % width, texel / width); + let texels_2k = REFERENCE_TILE_TEXELS / (block.0 as f32 * inp.block_scales.at(x, y)); + // Measured from the texel's 2K sub-texel nearest the border, so a coarser texel still shows the border it holds + let to_border = distances.get(texel as usize).copied().unwrap_or(0.0) * texels_2k - (texels_2k - 1.0).max(0.0); + let color = if checker.border_width > 0.0 && to_border <= checker.border_width * BORDER_TEXELS_PER_WIDTH_2K { + border + } else { + let uv = texel_coords(inp, x, y).uv; + let light = island_colors.get(&triangle).copied().unwrap_or(light); + let at = (uv.x.rem_euclid(1.0) * REFERENCE_TILE_TEXELS, uv.y.rem_euclid(1.0) * REFERENCE_TILE_TEXELS); + checker_color(checker, light, at, texels_2k) + }; + color.iter().sum::() / 3.0 + }) + .collect() + }) +} + +/// The checker's sRGB-encoded color at (`x`, `y`) in texels of a 2K UV tile (row 0 at the top) for a texel `texels_2k` of them wide, with `light` its light squares +fn checker_color(checker: &UvCheckerParameters, light: [f32; 3], (x, y): (f32, f32), texels_2k: f32) -> [f32; 3] { + let square = REFERENCE_TILE_TEXELS / (SQUARES_PER_GRID_TILE * checker.grid_tile.max(1) as f32); + let is_light = ((x / square).floor() + (y / square).floor()).rem_euclid(2.0) >= 1.0; + let base = if is_light { light } else { light.map(|channel| channel * DARK_SQUARE_SHADE) }; + + // Line layers in the reference's order, each laid over the last at the grid's opacity + let minor = square / MINOR_LINES_PER_SQUARE; + // A texel is on a line when its footprint overlaps the line's band, so lines stay visible on coarser texels + let reach = LINE_HALF_WIDTH_2K + (texels_2k - 1.0).max(0.0) * 0.5; + let on_line = |position: f32, period: f32| (position - (position / period).round() * period).abs() < reach; + let layers = [ + (on_line(y, minor) && !on_line(y, square), MINOR_LINE_SHADE), + (on_line(x, minor) && !on_line(x, square), MINOR_LINE_SHADE), + (on_line(y, square), MAJOR_LINE_SHADE), + (on_line(x, square), MAJOR_LINE_SHADE), + ]; + let opacity = checker.grid_opacity.clamp(0.0, 1.0); + let shade = layers.iter().filter(|(on, _)| *on).fold(1.0, |shade, (_, line)| shade + (line - shade) * opacity); + base.map(|channel| channel * shade) +} + +/// A random light sRGB-encoded color per UV island, by triangle +fn island_colors(inp: &Inputs, seed: u32) -> HashMap { + let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); + let islands = TrianglePartition::uv_islands(inp.mesh, material); + islands + .groups + .iter() + .enumerate() + .flat_map(|(island, triangles)| { + let island = island as i32; + let within = |range: &std::ops::RangeInclusive, random: f32| range.start() + (range.end() - range.start()) * random; + let color = hsv_to_rgb( + cell_hash(island, 0, 1, seed), + within(&RANDOM_SATURATION, cell_hash(island, 1, 1, seed)), + within(&RANDOM_VALUE, cell_hash(island, 2, 1, seed)), + ); + triangles.iter().map(move |triangle| (*triangle, color)) + }) + .collect() +} + +/// A color from its hue (in turns), saturation and value +fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> [f32; 3] { + let sector = hue.rem_euclid(1.0) * 6.0; + let fraction = sector - sector.floor(); + let (low, falling, rising) = (value * (1.0 - saturation), value * (1.0 - saturation * fraction), value * (1.0 - saturation * (1.0 - fraction))); + match sector.floor() as u32 { + 0 => [value, rising, low], + 1 => [falling, value, low], + 2 => [low, value, rising], + 3 => [low, falling, value], + 4 => [rising, low, value], + _ => [value, low, falling], + } +} diff --git a/crates/compose/tests/generator_uv_checker.rs b/crates/compose/tests/generator_uv_checker.rs new file mode 100644 index 00000000..549abc29 --- /dev/null +++ b/crates/compose/tests/generator_uv_checker.rs @@ -0,0 +1,76 @@ +//! The UV Checker generator on a plane filling its UV tile: a checker with grid lines, its border along the tile's edge + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, TextureSet, + UvCheckerParameters, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 256; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, +} + +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer } +} + +/// The middle row, left to right +fn row(fixture: &mut Fixture, checker: UvCheckerParameters) -> Vec { + let generator = Generator { controls: Some(Box::new(KindControls::UvChecker(checker))), ..Generator::new(GeneratorKind::UvChecker) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + let texels: Vec<(u32, u32)> = (0..RES).map(|x| (x, RES / 2 + 3)).collect(); + mask_at(&inputs, fixture.layer, &texels).unwrap() +} + +/// The distinct values of `values`, to 0.01 +fn tones(values: &[f32]) -> std::collections::BTreeSet { + values.iter().map(|value| (value * 100.0).round() as u32).collect() +} + +#[test] +fn without_grid_lines_the_checker_has_two_tones_and_a_border() { + let mut fixture = fixture(); + let values = row(&mut fixture, UvCheckerParameters { grid_opacity: 0.0, grid_tile: 1, ..UvCheckerParameters::default() }); + + assert_eq!(tones(&values[8..RES as usize - 8]).len(), 2, "two checker tones inside: {:?}", tones(&values)); + assert!((values[0] - 1.0 / 3.0).abs() < 0.01, "the red border reads a third: {}", values[0]); +} + +#[test] +fn grid_lines_only_darken() { + let mut fixture = fixture(); + let plain = row(&mut fixture, UvCheckerParameters { grid_opacity: 0.0, ..UvCheckerParameters::default() }); + let lined = row(&mut fixture, UvCheckerParameters::default()); + + assert!(lined.iter().zip(&plain).all(|(lined, plain)| lined <= plain)); + assert!(lined.iter().zip(&plain).any(|(lined, plain)| lined < plain)); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index d74cfbf8..ccbf8ed9 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -44,6 +44,7 @@ mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_checker_parameters; mod uv_random_color_parameters; mod uv_transform; mod uv_wrap; @@ -81,6 +82,7 @@ pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_checker_parameters::UvCheckerParameters; pub use uv_random_color_parameters::UvRandomColorParameters; pub use uv_transform::UvTransform; pub use uv_wrap::UvWrap; @@ -976,10 +978,12 @@ pub enum GeneratorKind { DrippingRust, /// One random value per UV island UvRandomColor, + /// A checker and grid over each UV tile with the UV islands' borders drawn in, for checking a layout + UvChecker, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 15] = [ + pub const ALL: [GeneratorKind; 16] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -995,6 +999,7 @@ impl GeneratorKind { GeneratorKind::GrayscaleConversion, GeneratorKind::DrippingRust, GeneratorKind::UvRandomColor, + GeneratorKind::UvChecker, ]; pub fn label(self) -> &'static str { match self { @@ -1013,6 +1018,7 @@ impl GeneratorKind { GeneratorKind::GrayscaleConversion => "Grayscale Conversion", GeneratorKind::DrippingRust => "Dripping Rust", GeneratorKind::UvRandomColor => "UV Random Color", + GeneratorKind::UvChecker => "UV Checker", } } @@ -1034,6 +1040,7 @@ impl GeneratorKind { GeneratorKind::GrayscaleConversion => "GrayscaleConversion", GeneratorKind::DrippingRust => "DrippingRust", GeneratorKind::UvRandomColor => "UvRandomColor", + GeneratorKind::UvChecker => "UvChecker", } } @@ -1048,6 +1055,7 @@ impl GeneratorKind { | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker ) } @@ -1055,7 +1063,12 @@ impl GeneratorKind { pub fn includes_randomness(self) -> bool { matches!( self, - GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker ) } @@ -1070,7 +1083,11 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], // Dripping Rust reads the baked occlusion and the mesh's bounds whole, so no input replaces them yet - GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor => &[], + GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => &[], } } @@ -1085,6 +1102,7 @@ impl GeneratorKind { | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker ) } diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index 76292879..eab247d5 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; use super::{ BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters, - UvRandomColorParameters, + UvCheckerParameters, UvRandomColorParameters, }; /// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind @@ -15,6 +15,7 @@ pub enum KindControls { Grayscale(GrayscaleConversionParameters), DrippingRust(DrippingRustParameters), UvRandomColor(UvRandomColorParameters), + UvChecker(UvCheckerParameters), } impl KindControls { @@ -27,6 +28,7 @@ impl KindControls { GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), GeneratorKind::DrippingRust => Some(KindControls::DrippingRust(DrippingRustParameters::default())), GeneratorKind::UvRandomColor => Some(KindControls::UvRandomColor(UvRandomColorParameters::default())), + GeneratorKind::UvChecker => Some(KindControls::UvChecker(UvCheckerParameters::default())), GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas @@ -48,6 +50,7 @@ impl KindControls { KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), KindControls::DrippingRust(rust) => KindControls::DrippingRust(rust.clamped()), KindControls::UvRandomColor(random) => KindControls::UvRandomColor(random.clamped()), + KindControls::UvChecker(checker) => KindControls::UvChecker(checker.clamped()), } } @@ -60,6 +63,7 @@ impl KindControls { KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, KindControls::DrippingRust(_) => GeneratorKind::DrippingRust, KindControls::UvRandomColor(_) => GeneratorKind::UvRandomColor, + KindControls::UvChecker(_) => GeneratorKind::UvChecker, } } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index ed99f19c..186f3af4 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -79,7 +79,8 @@ impl MicroDetails { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => None, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 8c1a6744..7ea25d60 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -45,7 +45,8 @@ impl SectionParameters { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => None, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => None, } } diff --git a/crates/core/src/layer/uv_checker_parameters.rs b/crates/core/src/layer/uv_checker_parameters.rs new file mode 100644 index 00000000..2a15020b --- /dev/null +++ b/crates/core/src/layer/uv_checker_parameters.rs @@ -0,0 +1,51 @@ +use serde::{Deserialize, Serialize}; + +/// The UV Checker generator's controls: a checker with a grid laid over each UV tile, the UV islands' borders drawn in a color +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UvCheckerParameters { + /// A random light color per UV island instead of the checker color + pub random_colors: bool, + /// The checker's light squares (linear RGB); the dark ones are a shade of it + pub checker_color: [f32; 3], + /// Grid tiles across the UV tile, each four checker squares wide ([`UvCheckerParameters::GRID_TILE_RANGE`]) + pub grid_tile: u32, + /// How strongly the grid lines darken the checker (0..1) + pub grid_opacity: f32, + /// The color of the UV islands' borders (linear RGB) + pub border_color: [f32; 3], + /// How wide the borders are (0..1; 0.2 is 3 texels of a 2K UV tile) + pub border_width: f32, +} + +impl UvCheckerParameters { + pub const GRID_TILE_RANGE: std::ops::RangeInclusive = 1..=24; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> UvCheckerParameters { + let defaults = UvCheckerParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + UvCheckerParameters { + checker_color: std::array::from_fn(|channel| unit(self.checker_color[channel], defaults.checker_color[channel])), + grid_tile: self.grid_tile.clamp(*UvCheckerParameters::GRID_TILE_RANGE.start(), *UvCheckerParameters::GRID_TILE_RANGE.end()), + grid_opacity: unit(self.grid_opacity, defaults.grid_opacity), + border_color: std::array::from_fn(|channel| unit(self.border_color[channel], defaults.border_color[channel])), + border_width: unit(self.border_width, defaults.border_width), + ..self + } + } +} + +impl Default for UvCheckerParameters { + /// The reference app's defaults: a light cyan checker (#5BDDFF), red borders + fn default() -> UvCheckerParameters { + UvCheckerParameters { + random_colors: false, + checker_color: [0.104_616, 0.723_055, 1.0], + grid_tile: 16, + grid_opacity: 0.5, + border_color: [1.0, 0.0, 0.0], + border_width: 0.2, + } + } +} diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index ab081fed..1d7e1718 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -64,7 +64,8 @@ impl WearParameters { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => None, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 03c5f7ba..0662670a 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,13 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvRandomColorParameters, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, + DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, + GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, + LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, + Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, + TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvCheckerParameters, UvRandomColorParameters, UvTransform, + UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 1de81fae..7b620be0 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,7 +1,7 @@ //! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls, UvRandomColorParameters}; +use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls, UvCheckerParameters, UvRandomColorParameters}; use crate::Result; use crate::commands::{bad, boolp, color_of, color_param, f32p, u64p}; @@ -25,6 +25,9 @@ pub const DRIPPING_RUST_KEYS: [&str; 7] = /// The UV Random Color controls (it also takes the seed) pub const UV_RANDOM_COLOR_KEYS: [&str; 2] = ["colorSourceMode", "gradientColors"]; +/// The UV Checker controls (it also takes the seed) +pub const UV_CHECKER_KEYS: [&str; 6] = ["checkerColorMode", "checkerColor", "checkerGridTile", "checkerGridOpacity", "uvBordersColor", "uvBordersWidth"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; @@ -38,6 +41,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), (&DRIPPING_RUST_KEYS[..], GeneratorKind::DrippingRust), (&UV_RANDOM_COLOR_KEYS[..], GeneratorKind::UvRandomColor), + (&UV_CHECKER_KEYS[..], GeneratorKind::UvChecker), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); @@ -61,6 +65,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::UvRandomColor { return uv_random_color_from(command, params, generator); } + if kind == GeneratorKind::UvChecker { + return uv_checker_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -183,6 +190,34 @@ fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator Ok(()) } +/// The UV Checker controls in `params` (the generator is one) +fn uv_checker_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let Some(KindControls::UvChecker(mut checker)) = generator.kind_controls() else { return Ok(()) }; + if let Some(value) = params.get("checkerColorMode") { + checker.random_colors = match value.as_str().map(str::to_ascii_lowercase).as_deref() { + Some("uniform") => false, + Some("random") => true, + _ => return Err(bad(command, "`checkerColorMode` must be uniform or random")), + }; + } + if let Some(color) = color_param(command, params, "checkerColor")? { + checker.checker_color = color; + } + if let Some(color) = color_param(command, params, "uvBordersColor")? { + checker.border_color = color; + } + if let Some(tile) = u64p(params, "checkerGridTile") { + checker.grid_tile = tile.min(u64::from(*UvCheckerParameters::GRID_TILE_RANGE.end())) as u32; + } + for (key, value) in [("checkerGridOpacity", &mut checker.grid_opacity), ("uvBordersWidth", &mut checker.border_width)] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.controls = Some(Box::new(KindControls::UvChecker(checker.clamped()))); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9dc863d9..77341832 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 732c5a28..c4f7b3ed 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -2,7 +2,8 @@ use serde_json::{Value, json}; use texturecraft_engine::core::{ - BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, UvRandomColorParameters, + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, + LinearGradientParameters, Source, UvCheckerParameters, UvRandomColorParameters, }; use texturecraft_engine::{Session, execute}; @@ -148,3 +149,16 @@ fn uv_random_color_takes_its_mode_and_gradient() { assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": []})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "colorSourceMode": "fancy"})).is_err()); } + +#[test] +fn uv_checker_takes_its_controls() { + let mut session = session(); + let params = + json!({"generator": "UV Checker", "checkerColorMode": "random", "checkerGridTile": 40, "checkerGridOpacity": 0.25, "uvBordersColor": [0.0, 1.0, 0.0]}); + let effect = add(&mut session, params); + + let expected = + UvCheckerParameters { random_colors: true, grid_tile: 24, grid_opacity: 0.25, border_color: [0.0, 1.0, 0.0], ..UvCheckerParameters::default() }; + assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvChecker(expected)), "the grid tile stops at 24"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "checkerColorMode": "plaid"})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 51c9d7e9..cee102fa 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -105,6 +105,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { (tr("Rust in occluded areas, running down in drips."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) } GeneratorKind::UvRandomColor => (tr("A random value per UV island."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), + GeneratorKind::UvChecker => (tr("A checker over the UV layout."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; // Wrapped rows: a long line must not widen the panel past its edge From 90d1c3e7389f33e8b6f759510f8c53c972382046 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:32 +0000 Subject: [PATCH 112/153] Generators: every generator panel on the property sheet, as the approved mockups --- crates/engine/src/orb_preview.rs | 7 +- crates/ui-egui/src/dock.rs | 2 +- crates/ui-egui/src/fill_material_panel.rs | 4 +- crates/ui-egui/src/fill_symmetry_panel.rs | 4 +- crates/ui-egui/src/generator_input_card.rs | 129 +++ crates/ui-egui/src/generator_input_slot.rs | 63 ++ crates/ui-egui/src/generator_panel.rs | 831 +++--------------- crates/ui-egui/src/generator_params.rs | 182 ++++ crates/ui-egui/src/generator_section_rows.rs | 189 ++++ crates/ui-egui/src/generator_slot.rs | 28 +- crates/ui-egui/src/generator_wear_rows.rs | 158 ++++ crates/ui-egui/src/lib.rs | 6 +- crates/ui-egui/src/preview_request.rs | 4 + .../ui-egui/src/property_sheet/axis_rows.rs | 40 +- crates/ui-egui/src/property_sheet/group.rs | 17 + crates/ui-egui/src/property_sheet/mod.rs | 3 + .../src/property_sheet/size_columns.rs | 73 ++ .../property_sheet/size_columns_response.rs | 9 + crates/ui-egui/src/property_sheet/slider.rs | 39 +- .../src/property_sheet/stack_slider.rs | 3 + .../src/property_sheet/switch_control.rs | 2 +- crates/ui-egui/src/resource_slot.rs | 68 -- crates/ui-egui/src/shelf.rs | 2 +- crates/ui-egui/src/shelf_preview.rs | 19 +- crates/ui-egui/src/thumbs.rs | 5 + .../ui-egui/tests/it/curvature_generator.rs | 11 +- crates/ui-egui/tests/it/effect_sliders.rs | 54 +- crates/ui-egui/tests/it/generator_panel.rs | 242 ++--- 28 files changed, 1245 insertions(+), 949 deletions(-) create mode 100644 crates/ui-egui/src/generator_input_card.rs create mode 100644 crates/ui-egui/src/generator_input_slot.rs create mode 100644 crates/ui-egui/src/generator_params.rs create mode 100644 crates/ui-egui/src/generator_section_rows.rs create mode 100644 crates/ui-egui/src/generator_wear_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/size_columns.rs create mode 100644 crates/ui-egui/src/property_sheet/size_columns_response.rs delete mode 100644 crates/ui-egui/src/resource_slot.rs diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index a0b701a4..4d5d3c70 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -86,13 +86,18 @@ impl OrbPreview { /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { + self.generator_of(Generator::new(kind), size) + } + + /// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone) + pub fn generator_of(&mut self, generator: Generator, size: usize) -> Option>> { if !valid_size(size) { return None; } // Each generator goes on the bare shape, not over the previous mask (self.session.doc, self.session.selected) = self.bare.clone(); - let effects = vec![(EffectKind::Generator(Generator::new(kind)), BlendMode::Normal)]; + let effects = vec![(EffectKind::Generator(generator), BlendMode::Normal)]; let mask = smart_masks::build_mask(&mut self.session.doc.project, MaskBackground::Black, effects); self.session.doc.project.layer_mut(self.layer).ok()?.mask = Some(mask); self.mask_pixels(size) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 26170c32..82b01579 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -3050,7 +3050,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe // Property sheets keep the panel's own edges; only the rows not yet laid out by one get the legacy margin match &effect.kind { - EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), + EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 1d5b0f9a..b294da01 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -138,7 +138,7 @@ fn resolution_json(resolution: CookResolution) -> Value { } /// The size of the texture set being painted, `fallback` when none is -fn texture_set_size(app: &TextureCraftApp, fallback: u32) -> u32 { +pub(crate) fn texture_set_size(app: &TextureCraftApp, fallback: u32) -> u32 { app.session.doc.project.texture_set(app.session.ts()).map_or(fallback, |texture_set| texture_set.resolution) } @@ -484,7 +484,7 @@ fn procedural_rows( } /// The Resolution band's reading of a pattern's saved output resolution: a size of its own is Fixed, any other follows the texture set -fn band_size(resolution: OutputResolution, texture_set: u32) -> CookResolution { +pub(crate) fn band_size(resolution: OutputResolution, texture_set: u32) -> CookResolution { match resolution.mode { ResolutionMode::Custom => CookResolution::Fixed(resolution.output_size(texture_set, texture_set)), _ => CookResolution::Relative(resolution.factor), diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs index 58579240..b306c05e 100644 --- a/crates/ui-egui/src/fill_symmetry_panel.rs +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -90,8 +90,8 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr let (mut count_value, mut span_value) = (count as f32, symmetry.span); let mut sliders = [ - StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" }, - StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" }, + StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "", dial: false }, + StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°", dial: false }, ]; let [count_edit, span_edit] = sheet.picture_sliders(&picture, &mut sliders); diff --git a/crates/ui-egui/src/generator_input_card.rs b/crates/ui-egui/src/generator_input_card.rs new file mode 100644 index 00000000..2cc9c41f --- /dev/null +++ b/crates/ui-egui/src/generator_input_card.rs @@ -0,0 +1,129 @@ +//! A generator's image input as a slot: what it reads, a picker to replace it with a value, an anchor point or an image, and the way back + +use egui::{Painter, Rect}; +use serde_json::json; +use texturecraft_engine::core::{LayerId, Source}; + +use crate::TextureCraftApp; +use crate::dock::{anchor_label, anchors_below, image_drop, mesh_map_color}; +use crate::fill_material_panel::{source_choice, source_tabs}; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::PropertySheet; +use crate::resource_picker; +use crate::source_choice::SourceChoice; +use crate::theme::Tokens; + +/// Glyph size on a slot picture standing for an anchor point +const GLYPH_SIZE: f32 = 12.0; + +/// The slot of input `slot` of generator effect `id` on `layer`, holding `source`: a card of its own, or a row of the card open now when `in_card` +pub(crate) fn input_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), slot: GeneratorInputSlot, source: Option<&Source>, in_card: bool) { + let tokens = Tokens::get(sheet.ui.ctx()); + let input = slot.id(); + let line = match (source, slot) { + (None, GeneratorInputSlot::Map(map)) => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + (None, _) => tr("Empty").to_string(), + (Some(Source::Uniform(_)), _) => tr("Uniform value").to_string(), + (Some(Source::Image { name, .. }), _) => trf("Image: {name}", &[("name", name)]), + (Some(Source::Anchor { anchor, channel, .. }), _) => anchor_label(app, *anchor, *channel), + (Some(Source::Procedural { .. }), _) => tr("Procedural").to_string(), + }; + + let image = match source { + Some(Source::Image { name, .. }) => app.session.images.get(name).map(|image| app.thumbs.image(sheet.ui.ctx(), name, image)), + _ => None, + }; + let baked = match slot { + GeneratorInputSlot::Map(map) => app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)), + _ => false, + }; + let picture = |painter: &Painter, rect: Rect| { + let gray = |value: f32| egui::Color32::from_gray((value.clamp(0.0, 1.0) * 255.0).round() as u8); + match (source, slot) { + (Some(Source::Image { .. }), _) => match &image { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, 0.0, tokens.button); + } + }, + (Some(Source::Uniform(value)), _) => { + painter.rect_filled(rect, 0.0, gray(value[0])); + } + (Some(Source::Anchor { .. } | Source::Procedural { .. }), _) => { + painter.rect_filled(rect, 0.0, tokens.button); + let glyph = egui_phosphor::regular::ANCHOR; + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(GLYPH_SIZE), tokens.text_dim); + } + (None, GeneratorInputSlot::Map(map)) => { + painter.rect_filled(rect, 0.0, if baked { mesh_map_color(map) } else { tokens.button }); + } + (None, _) => { + painter.rect_filled(rect, 0.0, tokens.button); + } + } + }; + + // A mesh map input goes back to its map with ⟲; an image slot empties with × + let map_slot = matches!(slot, GeneratorInputSlot::Map(_)); + let response = match (in_card, map_slot) { + (true, _) => sheet.slot_in_card(&picture, slot.title(), &line, source.is_some()), + (false, true) => sheet.slot(&picture, slot.title(), &line, None, false, source.is_some()), + (false, false) => sheet.slot(&picture, slot.title(), &line, None, source.is_some(), false), + }; + if response.clear || response.reset { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + if let Some(name) = image_drop(sheet.ui, &response.pick) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + + let popup = sheet.ui.make_persistent_id(("generator_input", id, input)); + if response.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = source.map(|source| source_choice(&app.session, source)); + let tabs = || { + let anchors = if slot.takes_anchor() { anchors_below(&app.session.doc.project, layer) } else { Vec::new() }; + let mut tabs = source_tabs(&app.session, &anchors, tokens.button, false); + + // A generator's inputs read images, values and anchor points, never a procedural + for tab in &mut tabs { + for group in &mut tab.groups { + group.items.retain(|item| !matches!(item.id, SourceChoice::Procedural(_))); + } + tab.groups.retain(|group| !group.items.is_empty()); + } + tabs.retain(|tab| !tab.groups.is_empty()); + tabs + }; + let picked = resource_picker::show(&response.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); + match picked.filter(|choice| Some(choice) != current.as_ref()) { + Some(SourceChoice::Uniform) => { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": slot.neutral()})); + } + Some(SourceChoice::Image(name)) => { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + Some(SourceChoice::Anchor(anchor)) => { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + Some(SourceChoice::Import) => crate::menus::invoke(app, sheet.ui.ctx(), "resource.import"), + Some(SourceChoice::Procedural(_) | SourceChoice::Alpha(_)) | None => {} + } + + if let Some(Source::Uniform(value)) = source { + let mut gray = value[0]; + let edit = sheet.ramp(tr("Value"), &mut gray, 0.0..=1.0); + if edit.invert { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": 1.0 - gray})); + } else if let Some(merge) = edit.changed { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": gray, "merge": merge})); + } + } + if !in_card { + sheet.close_card(); + } +} diff --git a/crates/ui-egui/src/generator_input_slot.rs b/crates/ui-egui/src/generator_input_slot.rs new file mode 100644 index 00000000..0e145a6f --- /dev/null +++ b/crates/ui-egui/src/generator_input_slot.rs @@ -0,0 +1,63 @@ +//! What one image input of a generator replaces or holds + +use texturecraft_engine::core::{BakedMap, Generator, Source}; + +use crate::i18n::{baked_map_label, tr}; + +/// An image input of a generator: a mesh map it reads, or one of the images its switches add +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum GeneratorInputSlot { + Map(BakedMap), + Texture, + Grunge, + MicroHeight, + MicroNormal, +} + +impl GeneratorInputSlot { + /// The input's name in `effect.set` + pub(crate) fn id(self) -> &'static str { + match self { + GeneratorInputSlot::Map(map) => map.id(), + GeneratorInputSlot::Texture => "texture", + GeneratorInputSlot::Grunge => "grunge", + GeneratorInputSlot::MicroHeight => texturecraft_engine::micro_params::MICRO_HEIGHT_INPUT, + GeneratorInputSlot::MicroNormal => texturecraft_engine::micro_params::MICRO_NORMAL_INPUT, + } + } + + pub(crate) fn title(self) -> &'static str { + match self { + GeneratorInputSlot::Map(map) => tr(baked_map_label(map)), + GeneratorInputSlot::Texture => tr("Texture"), + GeneratorInputSlot::Grunge => tr("Custom Grunge"), + GeneratorInputSlot::MicroHeight => tr("Micro Height"), + GeneratorInputSlot::MicroNormal => tr("Micro Normal"), + } + } + + /// The value a slot set to a uniform value starts at + pub(crate) fn neutral(self) -> f32 { + match self { + GeneratorInputSlot::Map(map) => map.neutral()[0], + GeneratorInputSlot::MicroHeight | GeneratorInputSlot::MicroNormal => 0.5, + GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge => 0.0, + } + } + + /// Whether it may read an anchor point (the engine computes the micro normal from an image or a value only) + pub(crate) fn takes_anchor(self) -> bool { + self != GeneratorInputSlot::MicroNormal + } + + /// What it holds on `generator`: None reads the mesh map, or leaves an image slot empty + pub(crate) fn source(self, generator: &Generator) -> Option<&Source> { + match self { + GeneratorInputSlot::Map(map) => generator.inputs.get(&map), + GeneratorInputSlot::Texture => generator.texture.as_ref().and_then(|texture| texture.source.as_ref()), + GeneratorInputSlot::Grunge => generator.grunge.as_ref(), + GeneratorInputSlot::MicroHeight => generator.micro.as_ref().and_then(|micro| micro.height_source.as_ref()), + GeneratorInputSlot::MicroNormal => generator.micro.as_ref().and_then(|micro| micro.normal_source.as_ref()), + } + } +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index cee102fa..98d060ee 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -1,90 +1,143 @@ -//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs. +//! A generator effect's properties, laid out like the reference app's: its slot, Parameters, Image inputs, Resolution, Attributes -use egui::{RichText, Ui}; -use egui_phosphor::regular as ic; -use serde_json::{Value, json}; -use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorGrayscale, GeneratorKind, LayerId, LightParameters, OutputResolution, - ResolutionMode, SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, -}; +use egui::{Painter, Rect, TextureHandle}; +use serde_json::json; +use texturecraft_engine::core::{CookResolution, Generator, GeneratorKind, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters}; use crate::TextureCraftApp; -use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; -use crate::i18n::{baked_map_label, tr, trf}; -use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; +use crate::fill_material_panel::{band_size, texture_set_size}; +use crate::generator_input_card::input_card; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::generator_params::{defaults_of, differs_from_defaults}; +use crate::generator_section_rows::{global_rows, ramp_rows, section_rows, texture_card}; +use crate::generator_wear_rows::{light_rows, micro_switch_card, wear_rows}; +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; -use crate::widgets::{combo, section, slider_edit, slider_edit_with_suffix}; -/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. -const INPUT_TILE_SIZE: f32 = 32.0; -const INPUT_TILE_ROUNDING: f32 = 2.0; -const INPUT_TILE_ICON_SIZE: f32 = 16.0; +/// The width the preview's orb is rendered at, in pixels: sharp at twice the preview's size +const PREVIEW_ORB_PX: usize = 256; -/// Width of a False/True button, so the buttons line up under each other -const TOGGLE_WIDTH: f32 = 136.0; +/// The texture set size a project without one is shown against +const FALLBACK_TEXTURE_SET_SIZE: u32 = 2048; -/// Edge of a light angle's dial, the width of its needle and the radius of its hub -const DIAL_SIZE: f32 = 36.0; -const DIAL_NEEDLE_WIDTH: f32 = 2.0; -const DIAL_HUB_RADIUS: f32 = 2.0; +/// How soon a picture still rendering is looked for again +const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); -/// Closest to a dial's centre a pointer still turns it, so the angle is defined -const DIAL_DEAD_ZONE: f32 = 1.0; +/// The settings of generator effect `id` on `layer` +pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, layer: LayerId, id: u64, generator: &Generator) { + PropertySheet::show(ui, ("generator_sheet", id), |sheet| { + sheet.section(tr("Generator"), false); + slot_card(app, sheet, id, generator); -/// The settings of generator effect `id`. -pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { - let tokens = Tokens::get(ui.ctx()); - crate::generator_slot::show(app, ui, id, generator); + let band = sheet.band(tr("Parameters"), true, Some(differs_from_defaults(generator)), None); + if band.reset { + app.run("effect.set", defaults_of(id, generator)); + } + if band.open { + parameters(app, sheet, (layer, id), generator); + } - section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); - section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); - section(ui, "generator_parameters", tr("Parameters"), true, |ui| { - if let Some(defaults) = WearParameters::defaults(generator.kind) { - // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them - wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); - } else if let Some(light) = generator.light { - light_parameters(app, ui, id, Some(generator.invert), light); - } else { - global_adjustments(app, ui, id, generator); - if generator.on_earlier_model() { - ramp_parameters(app, ui, id, generator); - } - // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them - if let Some(defaults) = SectionParameters::defaults(generator.kind) { - section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); - texture_parameters(app, ui, id, generator.texture.as_deref().cloned().unwrap_or_default()); - } - if let Some(defaults) = LightParameters::defaults(generator.kind) { - light_parameters(app, ui, id, None, defaults); + let inputs = generator.inputs_in_use(); + if !inputs.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&inputs.len().to_string())).open { + for map in inputs { + let slot = GeneratorInputSlot::Map(*map); + input_card(app, sheet, (layer, id), slot, slot.source(generator), false); } } - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Restore defaults")).clicked() { - app.run("effect.set", defaults_of(id, generator)); - } - }); - }); + + let texture_set = texture_set_size(app, FALLBACK_TEXTURE_SET_SIZE); + if let Some(picked) = crate::resolution_band::resolution_band(sheet, band_size(generator.resolution, texture_set), texture_set) { + let size = match picked { + CookResolution::Relative(factor) => json!({"resolution": format!("{:?}", ResolutionMode::Auto), "resolutionFactor": factor}), + CookResolution::Fixed(size) => json!({"resolution": format!("{:?}", ResolutionMode::Custom), "customResolution": size, "resolutionFactor": 0}), + }; + app.run("effect.set", crate::generator_params::merged(json!({"effect": id}), size)); + } + + if sheet.band(tr("Attributes"), false, None, None).open { + attributes(sheet, generator.kind); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + sheet.caption(tr("Bake mesh maps (Ctrl+Shift+B) for curvature, AO and thickness based generators.")); + } }); - let texture = generator.texture.as_ref().filter(|texture| texture.enabled && SectionParameters::defaults(generator.kind).is_some()); - if !generator.inputs_in_use().is_empty() || texture.is_some() { - section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { - if let Some(texture) = texture { - input_slot(app, ui, (layer, id), InputSlot::Texture, texture.source.as_ref(), false); - } - for map in generator.inputs_in_use() { - input_slot(app, ui, (layer, id), InputSlot::Map(*map), generator.inputs.get(map), generator.detail_in_use().is_some()); - } - }); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps for curvature, AO and thickness based generators."))).color(tokens.warning)); +} + +/// The card naming the generator: its orb and name; a click opens the generator picker +fn slot_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator) { + let ctx = sheet.ui.ctx().clone(); + let thumbnail = app.thumbs.generator(&ctx, generator.kind); + let tokens = Tokens::get(&ctx); + let picture = |painter: &Painter, rect: Rect| orb(painter, rect, thumbnail.as_ref(), &tokens, &ctx); + let slot = sheet.slot(&picture, tr(generator.kind.label()), tr("Generator"), None, false, false); + sheet.close_card(); + crate::generator_slot::picker(app, &slot.pick, id, generator.kind); +} + +/// An orb picture in `rect`, a placeholder while it renders +fn orb(painter: &Painter, rect: Rect, texture: Option<&TextureHandle>, tokens: &Tokens, ctx: &egui::Context) { + match texture { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, 0.0, tokens.button); + ctx.request_repaint_after(PICTURE_POLL); + } } } -/// What a generator kind makes, its category and its tags (read only). -fn attributes(ui: &mut Ui, kind: GeneratorKind) { - let tokens = Tokens::get(ui.ctx()); +/// The Parameters band's rows: the kind's own controls, else the global block and the earlier model's ramp +fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), generator: &Generator) { + let ctx = sheet.ui.ctx().clone(); + let tokens = Tokens::get(&ctx); + let kind = generator.kind; + + // The Curvature size under the pointer shows alone in the preview: the columns are drawn after it, so it is kept from the frame before + let solo_id = sheet.ui.make_persistent_id(("generator_solo", id)); + let mut solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); + let preview = match (kind, generator.detail_in_use()) { + (GeneratorKind::Curvature, Some(detail)) => ShelfPreview::Curvature { mode: detail.mode, solo }, + _ => ShelfPreview::Generator(kind), + }; + let texture = app.thumbs.generator_picture(&ctx, preview, PREVIEW_ORB_PX); + + // A size shows the whole preview until its own render arrives + let texture = texture.or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); + let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); + + if let Some(defaults) = WearParameters::defaults(kind) { + // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them + wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), &picture); + return; + } + if let Some(light) = generator.light { + light_rows(app, sheet, id, Some(generator.invert), light, &picture); + return; + } + + global_rows(app, sheet, id, generator, &picture); + if generator.on_earlier_model() { + ramp_rows(app, sheet, id, generator); + } + + // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them + if let Some(defaults) = SectionParameters::defaults(kind) { + solo = None; + section_rows(app, sheet, id, generator, generator.section_controls().unwrap_or(defaults), &mut solo); + texture_card(app, sheet, (layer, id), generator.texture.as_deref().cloned().unwrap_or_default()); + micro_switch_card(app, sheet, (layer, id), generator); + sheet.ui.data_mut(|data| data.insert_temp(solo_id, solo)); + } + if let Some(defaults) = LightParameters::defaults(kind) { + light_rows(app, sheet, id, None, defaults, &picture); + } +} + +/// What a generator kind makes, its category and its tags (read only) +fn attributes(sheet: &mut PropertySheet<'_>, kind: GeneratorKind) { let (description, tags) = match kind { GeneratorKind::EdgeWear => (tr("Worn metal edges, scratched."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), GeneratorKind::FiberGlassEdgeWear => (tr("Worn fibreglass edges."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), @@ -107,637 +160,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::UvRandomColor => (tr("A random value per UV island."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), GeneratorKind::UvChecker => (tr("A checker over the UV layout."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; - - // Wrapped rows: a long line must not widen the panel past its edge - let tags = tags.join(", "); - for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] { - ui.horizontal_top(|ui| { - ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); - ui.add(egui::Label::new(value).wrap()); - }); - } -} - -/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to. -fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) { - let tokens = Tokens::get(ui.ctx()); - combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| { - for mode in ResolutionMode::ALL { - if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() { - app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")})); - } - } - }) - .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); - if resolution.mode == ResolutionMode::Custom { - combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| { - for size in OutputResolution::CUSTOM_SIZES { - if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() { - app.run("effect.set", json!({"effect": id, "customResolution": size})); - } - } - }); - } - combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| { - for factor in OutputResolution::FACTORS { - if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() { - app.run("effect.set", json!({"effect": id, "resolutionFactor": factor})); - } - } - }) - .on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up.")); - - let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return }; - - let (smallest, largest) = texture_set - .uv_tiles - .iter() - .map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution)) - .fold((u32::MAX, 0), |(smallest, largest), size| (smallest.min(size), largest.max(size))); - let (smallest, largest) = if largest == 0 { - let size = resolution.output_size(texture_set.resolution, texture_set.resolution); - (size, size) - } else { - (smallest, largest) - }; - let size_label = if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") }; - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label)); - }) - .response - .on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution.")); -} - -/// Global invert, blur, balance and contrast: what every generator applies to its finished value. -fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let (mut invert, mut global) = (generator.invert, generator.global); - let invert_edit = true_false(ui, tr("Global invert"), &mut invert).then_some(false); - let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); - let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); - let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); - if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) { - app.run( - "effect.set", - json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), - ); - } -} - -/// The wear controls of generator effect `id` in the reference app's order, showing `wear` -fn wear_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, wear: WearParameters) { - seed_row(app, ui, id, generator.seed); - let mut invert = generator.invert; - if true_false(ui, tr("Invert"), &mut invert) { - app.run("effect.set", json!({"effect": id, "invert": invert})); - } - - let dirt = generator.kind == GeneratorKind::Dirt; - let (level_label, contrast_label) = if dirt { (tr("Dirt level"), tr("Dirt contrast")) } else { (tr("Wear level"), tr("Wear contrast")) }; - let mut edited = wear; - let mut edit = slider_edit(ui, level_label, &mut edited.level, 0.0..=1.0, 2); - edit = edit.or(slider_edit(ui, contrast_label, &mut edited.contrast, 0.0..=1.0, 2)); - let triplanar_edit = true_false(ui, tr("Use triplanar"), &mut edited.triplanar).then_some(false); - edit = edit.or(triplanar_edit).or(slider_edit(ui, tr("Triplanar blending contrast"), &mut edited.triplanar_contrast, 0.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Grunge amount"), &mut edited.grunge_amount, 0.0..=1.0, 2)); - if generator.kind != GeneratorKind::FiberGlassEdgeWear { - edit = edit.or(slider_edit(ui, tr("Grunge scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); - } - if dirt { - edit = edit.or(slider_edit(ui, tr("Edges masking"), &mut edited.edges_masking, 0.0..=1.0, 2)); - } else { - edit = edit.or(slider_edit(ui, tr("Edges smoothness"), &mut edited.edges_smoothness, WearParameters::EDGES_SMOOTHNESS_RANGE, 2)); - edit = edit.or(slider_edit(ui, tr("Ambient occlusion masking"), &mut edited.ao_masking, 0.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Curvature weight"), &mut edited.curvature_weight, 0.0..=1.0, 2)); - } - - if let Some(merge) = edit { - let mut params = wear_params(generator.kind, &edited); - params["effect"] = json!(id); - params["merge"] = json!(merge); - app.run("effect.set", params); - } -} - -/// The `effect.set` params that set every wear control a generator of `kind` has to `wear` -fn wear_params(kind: GeneratorKind, wear: &WearParameters) -> Value { - let mut params = json!({ - "wearLevel": wear.level, - "wearContrast": wear.contrast, - "grungeAmount": wear.grunge_amount, - "grungeScale": wear.grunge_scale, - "triplanar": wear.triplanar, - "triplanarContrast": wear.triplanar_contrast, - "edgesSmoothness": wear.edges_smoothness, - "aoMasking": wear.ao_masking, - "curvatureWeight": wear.curvature_weight, - "edgesMasking": wear.edges_masking, - }); - if let Some(params) = params.as_object_mut() { - params.retain(|key, _| texturecraft_engine::mask_cmds::wear_key_applies(kind, key)); - } - params -} - -/// An on/off control as the reference app draws it: the name, then a full-width button reading False or True; returns whether it was clicked -fn true_false(ui: &mut Ui, label: &str, value: &mut bool) -> bool { - let mut clicked = false; - ui.horizontal(|ui| { - ui.label(label); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let text = if *value { tr("True") } else { tr("False") }; - if ui.add_sized([TOGGLE_WIDTH, ui.spacing().interact_size.y], egui::Button::new(text)).clicked() { - *value = !*value; - clicked = true; - } - }); - }); - clicked -} - -/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. -fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = - (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); - 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 offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); - if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) { - app.run( - "effect.set", - json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), - ); - } - seed_row(app, ui, id, generator.seed); -} - -/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference. -fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { - let typing_id = ui.make_persistent_id(("generator_seed_typing", id)); - let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); - ui.horizontal(|ui| { - ui.label(tr("Seed")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { - typing = !typing; - } - if typing { - let mut typed = seed; - let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); - if field.changed() { - // The later changes of one drag continue its first undo step - let merge = field.dragged() && !field.drag_started(); - app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge})); - } - } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() { - app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)})); - } - }); - }); - ui.data_mut(|data| data.insert_temp(typing_id, typing)); -} - -/// The `effect.set` params that put generator effect `id` back to the defaults of its kind. -fn defaults_of(id: u64, generator: &Generator) -> Value { - let kind = generator.kind; - let defaults = Generator::new(kind); - let params = json!({ - "effect": id, - "seed": defaults.seed, - "invert": defaults.invert, - "resolution": format!("{:?}", defaults.resolution.mode), - "customResolution": defaults.resolution.custom, - "resolutionFactor": defaults.resolution.factor, - }); - - // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model - let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); - let own = match (&defaults.wear, &defaults.section, &defaults.light) { - (Some(wear), _, _) => wear_params(kind, wear), - (None, _, Some(light)) => light_params(light), - // The texture's controls only once it has them: its image stays in its slot - (None, Some(section), None) if generator.texture.is_some() => { - merged(merged(section_params(kind, section), global), texture_params(&TextureLayer::default())) - } - (None, Some(section), None) => merged(section_params(kind, section), global), - (None, None, None) => json!({ - "level": defaults.level, - "softness": defaults.softness, - "noise": defaults.noise_amount, - "noiseScale": defaults.noise_scale, - "offset": defaults.offset, - "direction": defaults.direction, - "blur": defaults.global.blur, - "balance": defaults.global.balance, - "contrast": defaults.global.contrast, - }), - }; - let mut params = merged(params, own); - if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { - params["mode"] = json!(format!("{:?}", detail.mode)); - params["sizes"] = json!(detail.weights); - } - params -} - -/// The keys of `extra` added to the object `params` -fn merged(mut params: Value, extra: Value) -> Value { - if let (Some(params), Value::Object(extra)) = (params.as_object_mut(), extra) { - params.extend(extra); - } - params -} - -/// The section controls of generator effect `id` under the kind's own heading, showing `shown` -fn section_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, shown: SectionParameters) { - let kind = generator.kind; - let title = match kind { - GeneratorKind::Curvature => tr("Curvature"), - GeneratorKind::AmbientOcclusion => tr("Ambient occlusion"), - GeneratorKind::Position => tr("Position"), - _ => tr("World space normal"), - }; - section(ui, "generator_section", title, true, |ui| { - let mut edited = shown; - let mut edit = true_false(ui, tr("Invert"), &mut edited.invert).then_some(false); - if kind == GeneratorKind::Curvature { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); - } - if SectionParameters::has_blur(kind) { - edit = edit.or(slider_edit(ui, tr("Blur"), &mut edited.blur, SectionParameters::BLUR_RANGE, 2)); - } - if SectionParameters::has_balance(kind) { - edit = edit.or(slider_edit(ui, tr("Balance"), &mut edited.balance, 0.0..=1.0, 2)); - } - edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); - if SectionParameters::has_brightness(kind) { - edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, SectionParameters::BRIGHTNESS_RANGE, 2)); - } - if SectionParameters::has_axes(kind) { - let titles = [tr("Right to left"), tr("Top to bottom"), tr("Front to back")]; - for (index, (axis, title)) in edited.axes.iter_mut().zip(titles).enumerate() { - // Each axis's dropdown needs its own id: the dropdown's id comes from its label - ui.push_id(("generator_axis", index), |ui| { - section(ui, "generator_axis", title, true, |ui| { - edit = edit.or(true_false(ui, tr("Invert"), &mut axis.invert).then_some(false)); - combo(ui, tr("Blending mode"), axis_blend_label(axis.blend), |ui| { - for blend in AxisBlend::ALL { - if ui.selectable_label(blend == axis.blend, axis_blend_label(blend)).clicked() { - axis.blend = blend; - edit = Some(false); - } - } - }); - }); - edit = edit.or(slider_edit(ui, title, &mut axis.weight, 0.0..=1.0, 2)); - }); - } - } - if let Some(merge) = edit { - app.run("effect.set", merged(json!({"effect": id, "merge": merge}), section_params(kind, &edited))); - } - }); -} - -/// The `effect.set` params that set every section control a generator of `kind` has to `section` -fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { - let mut params = json!({ - "sectionInvert": section.invert, - "sectionBlur": section.blur, - "sectionBalance": section.balance, - "sectionContrast": section.contrast, - "sectionBrightness": section.brightness, - }); - if let Some(params) = params.as_object_mut() { - for (name, axis) in ["rightLeft", "topBottom", "frontBack"].into_iter().zip(§ion.axes) { - params.insert(format!("{name}Invert"), json!(axis.invert)); - params.insert(format!("{name}Blend"), json!(axis.blend.id())); - params.insert(format!("{name}Weight"), json!(axis.weight)); - } - params.retain(|key, _| texturecraft_engine::mask_cmds::section_key_applies(kind, key)); - } - params -} - -/// The translated name of axis blending mode `blend` -/// Use Texture and, once it is on, the texture's controls and its opacity -fn texture_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, shown: TextureLayer) { - let mut edited = shown; - let mut edit = true_false(ui, tr("Use texture"), &mut edited.enabled).then_some(false); - if edited.enabled { - section(ui, "generator_texture", tr("Texture"), true, |ui| { - edit = edit.or(true_false(ui, tr("Invert"), &mut edited.invert).then_some(false)); - combo(ui, tr("Grayscale conversion"), tr(edited.grayscale.label()), |ui| { - for mode in GeneratorGrayscale::ALL { - if ui.selectable_label(mode == edited.grayscale, tr(mode.label())).clicked() { - edited.grayscale = mode; - edit = Some(false); - } - } - }); - combo(ui, tr("Blending mode"), tr(edited.blend.label()), |ui| { - for blend in TextureBlend::ALL { - if ui.selectable_label(blend == edited.blend, tr(blend.label())).clicked() { - edited.blend = blend; - edit = Some(false); - } - } - }); - edit = edit.or(slider_edit(ui, tr("Scale"), &mut edited.scale, TextureLayer::SCALE_RANGE, 2)); - edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, -1.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, -1.0..=1.0, 2)); - edit = edit.or(true_false(ui, tr("Triplanar"), &mut edited.triplanar).then_some(false)); - edit = edit.or(slider_edit(ui, tr("Triplanar contrast"), &mut edited.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE, 2)); - }); - edit = edit.or(slider_edit(ui, tr("Texture opacity"), &mut edited.opacity, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", merged(json!({"effect": id, "merge": merge}), texture_params(&edited))); - } -} - -/// The texture controls as `effect.set` keys (its image is the `texture` input) -fn texture_params(texture: &TextureLayer) -> Value { - json!({ - "useTexture": texture.enabled, - "textureOpacity": texture.opacity, - "textureInvert": texture.invert, - "textureGrayscale": texture.grayscale.id(), - "textureBlend": texture.blend.id(), - "textureScale": texture.scale, - "textureContrast": texture.contrast, - "textureBrightness": texture.brightness, - "textureTriplanar": texture.triplanar, - "textureTriplanarContrast": texture.triplanar_contrast, - }) -} - -fn axis_blend_label(blend: AxisBlend) -> &'static str { - match blend { - AxisBlend::Normal => tr("Normal"), - AxisBlend::Add => tr("Linear Dodge (Add)"), - AxisBlend::Subtract => tr("Subtract"), - AxisBlend::Multiply => tr("Multiply"), - AxisBlend::AddSub => tr("Add/Sub"), - AxisBlend::Max => tr("Max (Lighten)"), - } -} - -/// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) -fn light_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, invert: Option, shown: LightParameters) { - if let Some(mut invert) = invert - && true_false(ui, tr("Invert"), &mut invert) - { - app.run("effect.set", json!({"effect": id, "invert": invert})); - } - let mut edited = shown; - let mut edit = angle_row(ui, "generator_light_horizontal", tr("Horizontal angle"), &mut edited.horizontal); - edit = edit.or(angle_row(ui, "generator_light_vertical", tr("Vertical angle"), &mut edited.vertical)); - edit = edit.or(slider_edit(ui, tr("Highlight glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); - edit = edit.or(slider_edit(ui, tr("Highlight level"), &mut edited.highlight_level, 0.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Light attenuation"), &mut edited.attenuation, 0.0..=1.0, 2)); - if let Some(merge) = edit { - app.run("effect.set", merged(json!({"effect": id, "merge": merge}), light_params(&edited))); - } -} - -/// The `effect.set` params that set every light control to `light` -fn light_params(light: &LightParameters) -> Value { - json!({ - "lightHorizontal": light.horizontal, - "lightVertical": light.vertical, - "highlightGlossiness": light.glossiness, - "highlightLevel": light.highlight_level, - "lightAttenuation": light.attenuation, - }) -} - -/// A light angle in degrees: its name, then a dial beside an Angle slider; `Some(merge)` when either changes it -fn angle_row(ui: &mut Ui, id: &str, label: &str, degrees: &mut f32) -> Option { - ui.label(label); - ui.push_id(id, |ui| { - ui.horizontal(|ui| { - let dial = angle_dial(ui, label, degrees); - let slider = ui.vertical(|ui| slider_edit_with_suffix(ui, tr("Angle"), degrees, LightParameters::ANGLE_RANGE, 0, "°")).inner; - dial.or(slider) - }) - .inner - }) - .inner -} - -/// A round dial whose needle points at `degrees` (0 on the left, clockwise, as in the reference); dragging it turns it, `Some(merge)` like [`slider_edit`] -fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(egui::vec2(DIAL_SIZE, DIAL_SIZE), egui::Sense::click_and_drag()); - let mut edit = None; - if (response.dragged() || response.clicked()) - && let Some(pointer) = response.interact_pointer_pos() - { - let offset = pointer - rect.center(); - let turned = (-offset.y).atan2(-offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); - if offset.length() > DIAL_DEAD_ZONE && (turned - *degrees).abs() > f32::EPSILON { - *degrees = turned; - // Later frames of one drag share its undo step - edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); - } - } - if response.drag_stopped() || response.clicked() { - ui.data_mut(|data| data.remove_temp::(response.id)); - } - let shown = *degrees; - response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(shown), label)); - - let painter = ui.painter(); - // The rim's stroke stays inside the dial - let radius = (DIAL_SIZE - DIAL_NEEDLE_WIDTH) * 0.5; - painter.circle(rect.center(), radius, tokens.field, egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.button_border)); - let (sin, cos) = degrees.to_radians().sin_cos(); - let tip = rect.center() + egui::vec2(-cos, -sin) * radius; - painter.line_segment([rect.center(), tip], egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.accent)); - painter.circle_filled(rect.center(), DIAL_HUB_RADIUS, tokens.text); - edit -} - -/// 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 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:?}")})); - } - } - }); - - let names = [tr("Sharp"), tr("Fine"), tr("Soft"), tr("Medium"), tr("Large"), tr("Big"), tr("Huge")]; - let mut weights = shown.weights; - let mut edit = None; - for (weight, name) in weights.iter_mut().zip(names) { - edit = edit.or(slider_edit(ui, name, weight, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); - } -} - -/// 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("Dual"), - CurvatureMode::Raw => tr("Unprocessed"), - } -} - -/// What an image input slot of a generator replaces: a mesh map it reads, or its texture -#[derive(Clone, Copy)] -enum InputSlot { - Map(BakedMap), - Texture, -} - -impl InputSlot { - /// The input's name in `effect.set` - fn id(self) -> &'static str { - match self { - InputSlot::Map(map) => map.id(), - InputSlot::Texture => "texture", - } - } - - fn title(self) -> &'static str { - match self { - InputSlot::Map(map) => tr(baked_map_label(map)), - InputSlot::Texture => tr("Texture"), - } - } - - /// The value a slot set to a uniform value starts at - fn neutral(self) -> f32 { - match self { - InputSlot::Map(map) => map.neutral()[0], - InputSlot::Texture => 0.0, - } - } -} - -/// One image input: what it reads now, a menu to replace it with a value, an anchor point or an image, and a button to empty it -fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), slot: InputSlot, source: Option<&Source>, detail_sizes: bool) { - let tokens = Tokens::get(ui.ctx()); - let input = slot.id(); - let current = match (source, slot) { - (None, InputSlot::Map(map)) => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), - (None, InputSlot::Texture) | (Some(Source::Uniform(_)), _) => tr("Uniform value").to_string(), - (Some(Source::Image { name, .. }), _) => trf("Image: {name}", &[("name", name)]), - (Some(Source::Anchor { anchor, channel, .. }), _) => anchor_label(app, *anchor, *channel), - (Some(Source::Procedural { .. }), _) => tr("Procedural").to_string(), - }; - let empty_hint = match slot { - InputSlot::Map(_) => tr("Read the mesh map again"), - InputSlot::Texture => tr("Empty the slot"), - }; - let group = ui.group(|ui| { - ui.horizontal(|ui| { - input_tile(app, ui, slot, source); - ui.vertical(|ui| { - ui.label(RichText::new(slot.title()).strong()); - ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); - }); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if source.is_some() && ui.button(ic::X).on_hover_text(empty_hint).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); - } - }); - }); - // Each input's menu needs its own id: the dropdown's id comes from its label - ui.push_id(input, |ui| { - combo(ui, tr("Source"), current.clone(), |ui| { - let anchors = anchors_below(&app.session.doc.project, layer); - if let InputSlot::Map(_) = slot - && ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() - { - app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); - } - let uniform = matches!(source, Some(Source::Uniform(_))) || (source.is_none() && matches!(slot, InputSlot::Texture)); - if ui.selectable_label(uniform, tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": slot.neutral()})); - } - for (anchor, label) in &anchors { - if ui - .selectable_label( - matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), - trf("Anchor: {name}", &[("name", label)]), - ) - .clicked() - { - app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); - } - } - if let Some(name) = image_menu(app, ui) { - app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); - } - }) - }); - let uniform = match (source, slot) { - (Some(Source::Uniform(value)), _) => Some(value[0]), - (None, InputSlot::Texture) => Some(slot.neutral()), - _ => None, - }; - if let Some(mut value) = uniform - && let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) - { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); - } - let replaced_curvature = matches!(slot, InputSlot::Map(BakedMap::Curvature)) && source.is_some_and(|source| !matches!(source, Source::Uniform(_))); - if detail_sizes && replaced_curvature { - ui.label( - RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) - .size(NOTE_FONT_SIZE) - .color(tokens.text_dim), - ); - } - }); - if let Some(name) = image_drop(ui, &group.response) { - app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); - } -} - -/// The picture beside an image input: its image, its value as gray, an icon for an anchor or a procedural, else its mesh map's color (black for an empty texture) -fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, slot: InputSlot, source: Option<&Source>) { - let tokens = Tokens::get(ui.ctx()); - let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); - let painter = ui.painter(); - let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); - let gray = |value: f32| egui::Color32::from_gray((value.clamp(0.0, 1.0) * 255.0).round() as u8); - match (source, slot) { - (Some(Source::Image { name, .. }), _) => match app.session.images.get(name) { - Some(image) => { - let texture = app.thumbs.image(ui.ctx(), name, image); - painter.image(texture.id(), rect, whole, egui::Color32::WHITE); - } - None => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); - } - }, - (Some(Source::Uniform(value)), _) => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(value[0])); - } - (Some(Source::Anchor { .. } | Source::Procedural { .. }), _) => { - let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; - painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); - painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); - } - (None, InputSlot::Texture) => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(slot.neutral())); - } - (None, InputSlot::Map(map)) => { - let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); - painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); - } - } - painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside); + sheet.attribute_text(tr("Description"), description); + sheet.attribute(tr("Category"), tr("Generators")); + sheet.attribute(tr("Tags"), &tags.join(", ")); } diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs new file mode 100644 index 00000000..96fc1980 --- /dev/null +++ b/crates/ui-egui/src/generator_params.rs @@ -0,0 +1,182 @@ +//! The `effect.set` keys of a generator's controls, as its panel sends them + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Generator, GeneratorKind, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; +use texturecraft_engine::mask_cmds::{section_key_applies, wear_key_applies}; +use texturecraft_engine::micro_params::micro_key_applies; + +/// The keys of `extra` added to the object `params` +pub(crate) fn merged(mut params: Value, extra: Value) -> Value { + if let (Some(params), Value::Object(extra)) = (params.as_object_mut(), extra) { + params.extend(extra); + } + params +} + +/// Every wear control a generator of `kind` has, set to `wear` +pub(crate) fn wear_params(kind: GeneratorKind, wear: &WearParameters) -> Value { + let mut params = json!({ + "wearLevel": wear.level, + "wearContrast": wear.contrast, + "grungeAmount": wear.grunge_amount, + "grungeScale": wear.grunge_scale, + "triplanar": wear.triplanar, + "triplanarContrast": wear.triplanar_contrast, + "edgesSmoothness": wear.edges_smoothness, + "aoMasking": wear.ao_masking, + "curvatureWeight": wear.curvature_weight, + "edgesMasking": wear.edges_masking, + "useCustomGrunge": wear.custom_grunge, + }); + if let Some(params) = params.as_object_mut() { + params.retain(|key, _| wear_key_applies(kind, key)); + } + params +} + +/// Every section control a generator of `kind` has, set to `section` +pub(crate) fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { + let mut params = json!({ + "sectionInvert": section.invert, + "sectionBlur": section.blur, + "sectionBalance": section.balance, + "sectionContrast": section.contrast, + "sectionBrightness": section.brightness, + }); + if let Some(params) = params.as_object_mut() { + for (name, axis) in ["rightLeft", "topBottom", "frontBack"].into_iter().zip(§ion.axes) { + params.insert(format!("{name}Invert"), json!(axis.invert)); + params.insert(format!("{name}Blend"), json!(axis.blend.id())); + params.insert(format!("{name}Weight"), json!(axis.weight)); + } + params.retain(|key, _| section_key_applies(kind, key)); + } + params +} + +/// The texture's controls (its image is the `texture` input) +pub(crate) fn texture_params(texture: &TextureLayer) -> Value { + json!({ + "useTexture": texture.enabled, + "textureOpacity": texture.opacity, + "textureInvert": texture.invert, + "textureGrayscale": texture.grayscale.id(), + "textureBlend": texture.blend.id(), + "textureScale": texture.scale, + "textureContrast": texture.contrast, + "textureBrightness": texture.brightness, + "textureTriplanar": texture.triplanar, + "textureTriplanarContrast": texture.triplanar_contrast, + }) +} + +/// Every light control, set to `light` +pub(crate) fn light_params(light: &LightParameters) -> Value { + json!({ + "lightHorizontal": light.horizontal, + "lightVertical": light.vertical, + "highlightGlossiness": light.glossiness, + "highlightLevel": light.highlight_level, + "lightAttenuation": light.attenuation, + }) +} + +/// Every micro details control a generator of `kind` has, set to `micro` (its images are the `microHeight` and `microNormal` inputs) +pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { + let mut params = json!({ + "useMicroDetails": micro.enabled, + "microHeight": micro.height, + "microNormal": micro.normal, + "microCurvatureType": micro.curvature_type.label(), + "microCurvatureIntensity": micro.curvature_intensity, + "microHeightIntensity": micro.height_intensity, + "microAoRadius": micro.ao_radius, + "microAoDepth": micro.ao_depth, + }); + if let Some(params) = params.as_object_mut() { + params.retain(|key, _| micro_key_applies(kind, key)); + } + params +} + +/// The `effect.set` params that put generator effect `id` back to the defaults of its kind; its images stay in their slots +pub(crate) fn defaults_of(id: u64, generator: &Generator) -> Value { + let kind = generator.kind; + let defaults = Generator::new(kind); + let params = json!({ + "effect": id, + "seed": defaults.seed, + "invert": defaults.invert, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + + // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model + let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); + let own = match (&defaults.wear, &defaults.section, &defaults.light) { + (Some(wear), _, _) => wear_params(kind, wear), + (None, _, Some(light)) => light_params(light), + // The texture's controls only once it has them: its image stays in its slot + (None, Some(section), None) if generator.texture.is_some() => { + merged(merged(section_params(kind, section), global), texture_params(&TextureLayer::default())) + } + (None, Some(section), None) => merged(section_params(kind, section), global), + (None, None, None) => json!({ + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + "direction": defaults.direction, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, + }), + }; + let mut params = merged(params, own); + if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { + params["mode"] = json!(format!("{:?}", detail.mode)); + params["sizes"] = json!(detail.weights); + } + + // Micro details only once it has them, as the texture's + if generator.micro.is_some() + && let Some(micro) = MicroDetails::defaults(kind) + { + params = merged(params, micro_params(kind, µ)); + } + params +} + +/// Whether Restore defaults would change generator `generator`: its controls differ from its kind's, images and resolution aside +pub(crate) fn differs_from_defaults(generator: &Generator) -> bool { + let mut restored = Generator::new(generator.kind); + restored.resolution = generator.resolution; + restored.inputs = generator.inputs.clone(); + restored.grunge = generator.grunge.clone(); + if let Some(texture) = &generator.texture { + restored.texture = Some(Box::new(TextureLayer { source: texture.source.clone(), ..TextureLayer::default() })); + } + if let Some(micro) = &generator.micro + && let Some(defaults) = MicroDetails::defaults(generator.kind) + { + restored.micro = Some(Box::new(MicroDetails { height_source: micro.height_source.clone(), normal_source: micro.normal_source.clone(), ..defaults })); + } + restored.controls = generator.controls.clone(); + + // Saved before the wear, section or light controls: the earlier model's own values count + if generator.wear.is_none() { + restored.wear = None; + } + if generator.section.is_none() { + restored.section = None; + } + if generator.light.is_none() { + restored.light = None; + } + if generator.detail.is_none() { + restored.detail = None; + } + restored != *generator +} diff --git a/crates/ui-egui/src/generator_section_rows.rs b/crates/ui-egui/src/generator_section_rows.rs new file mode 100644 index 00000000..0e7533a8 --- /dev/null +++ b/crates/ui-egui/src/generator_section_rows.rs @@ -0,0 +1,189 @@ +//! The Parameters rows of Curvature, Ambient Occlusion, Position and World Space Normals: the global block, the kind's own card, its axes, Use Texture; and the earlier model's ramp + +use egui::{Painter, Rect}; +use serde_json::json; +use texturecraft_engine::core::{ + AxisBlend, CurvatureDetail, CurvatureMode, Generator, GeneratorGrayscale, GeneratorKind, LayerId, SectionParameters, TextureBlend, TextureLayer, +}; + +use crate::TextureCraftApp; +use crate::generator_input_card::input_card; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::generator_params::{merged, section_params, texture_params}; +use crate::i18n::tr; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::theme::AXIS_COLORS; + +/// A 0..1 setting in the stack beside the preview +fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } +} + +/// Global Invert, then the preview beside Global Blur, Balance and Contrast: what every generator applies to its finished value +pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, picture: &dyn Fn(&Painter, Rect)) { + let (mut invert, mut global) = (generator.invert, generator.global); + let invert_edit = sheet.toggle(tr("Global Invert"), &mut invert).then_some(false); + let mut stack = + [stacked(tr("Global Blur"), &mut global.blur), stacked(tr("Global Balance"), &mut global.balance), stacked(tr("Global Contrast"), &mut global.contrast)]; + let stack_edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); + if let Some(merge) = invert_edit.or(stack_edit) { + app.run( + "effect.set", + json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), + ); + } +} + +/// The kind's own card (Curvature's mode and sizes in it), then one card per axis, showing `shown`; `solo` keeps the Curvature size under the pointer for the preview +pub(crate) fn section_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, shown: SectionParameters, solo: &mut Option) { + let kind = generator.kind; + let title = match kind { + GeneratorKind::Curvature => tr("Curvature"), + GeneratorKind::AmbientOcclusion => tr("Ambient Occlusion"), + GeneratorKind::Position => tr("Position Gradient"), + _ => tr("World Space Normal"), + }; + let mut edited = shown; + let mut edit = None; + if sheet.card(title, Some(true)) { + edit = sheet.toggle(tr("Invert"), &mut edited.invert).then_some(false); + if kind == GeneratorKind::Curvature { + *solo = curvature_detail_rows(app, sheet, id, generator.detail.as_ref()); + } + if SectionParameters::has_blur(kind) { + edit = edit.or(sheet.slider(tr("Blur"), &mut edited.blur, SectionParameters::BLUR_RANGE, 2)); + } + if SectionParameters::has_balance(kind) { + edit = edit.or(sheet.slider(tr("Balance"), &mut edited.balance, 0.0..=1.0, 2)); + } + edit = edit.or(sheet.slider(tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + if SectionParameters::has_brightness(kind) { + edit = edit.or(sheet.signed_slider(tr("Brightness"), &mut edited.brightness, SectionParameters::BRIGHTNESS_RANGE, 2)); + } + } + sheet.close_card(); + + if SectionParameters::has_axes(kind) { + let axes = [("X", tr("Right to Left")), ("Y", tr("Top To Bottom")), ("Z", tr("Front to Back"))]; + for ((axis, (letter, name)), tint) in edited.axes.iter_mut().zip(axes).zip(AXIS_COLORS) { + edit = edit.or(sheet.axis_card((letter, tint), name, &mut axis.weight, 0.0..=1.0, 2)); + edit = edit.or(sheet.toggle(tr("Invert"), &mut axis.invert).then_some(false)); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), axis.blend, &AxisBlend::ALL, |blend| axis_blend_label(blend).to_string(), None) { + axis.blend = picked; + edit = Some(false); + } + sheet.close_card(); + } + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), section_params(kind, &edited))); + } +} + +/// Curvature's Mode, each mode pictured, and its detail sizes as columns (`detail` None: saved before detail sizes); returns the size under the pointer +fn curvature_detail_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, detail: Option<&CurvatureDetail>) -> Option { + let shown = detail.cloned().unwrap_or_default(); + let ctx = sheet.ui.ctx().clone(); + let pictures: Vec<_> = CurvatureMode::ALL + .into_iter() + .map(|mode| (mode, app.thumbs.generator_picture(&ctx, crate::shelf_preview::ShelfPreview::Curvature { mode, solo: None }, MODE_PICTURE_PX))) + .collect(); + let draw = |painter: &Painter, rect: Rect, mode: CurvatureMode| { + if let Some((_, Some(texture))) = pictures.iter().find(|(shown, _)| *shown == mode) { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + }; + let name = |mode: CurvatureMode| curvature_mode_label(mode).to_string(); + if let (Some(mode), _) = sheet.dropdown(tr("Mode"), shown.mode, &CurvatureMode::ALL, name, Some(&draw)) { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + + let names = [tr("Sharp"), tr("Fine"), tr("Soft"), tr("Medium"), tr("Large"), tr("Big"), tr("Huge")]; + let mut weights = shown.weights; + let columns = sheet.size_columns(&names, &mut weights); + if let Some((_, merge)) = columns.edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + columns.hovered +} + +/// The width a Mode picture is rendered at, in pixels: sharp at twice the dropdown's picture +const MODE_PICTURE_PX: usize = 48; + +/// Use Texture's switch card: while on, the texture's slot and controls +pub(crate) fn texture_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), shown: TextureLayer) { + let mut edited = shown.clone(); + let mut edit = sheet.switch_card(tr("Use Texture"), &mut edited.enabled).then_some(false); + if edited.enabled { + input_card(app, sheet, (layer, id), GeneratorInputSlot::Texture, shown.source.as_ref(), true); + edit = edit.or(sheet.toggle(tr("Invert"), &mut edited.invert).then_some(false)); + let grayscale = |mode: GeneratorGrayscale| tr(mode.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Grayscale Conversion"), edited.grayscale, &GeneratorGrayscale::ALL, grayscale, None) { + edited.grayscale = picked; + edit = Some(false); + } + let blend = |blend: TextureBlend| tr(blend.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), edited.blend, &TextureBlend::ALL, blend, None) { + edited.blend = picked; + edit = Some(false); + } + edit = edit.or(sheet.slider(tr("Scale"), &mut edited.scale, TextureLayer::SCALE_RANGE, 2)); + edit = edit.or(sheet.signed_slider(tr("Contrast"), &mut edited.contrast, -1.0..=1.0, 2)); + edit = edit.or(sheet.signed_slider(tr("Brightness"), &mut edited.brightness, -1.0..=1.0, 2)); + edit = edit.or(sheet.toggle(tr("Triplanar"), &mut edited.triplanar).then_some(false)); + if edited.triplanar { + edit = edit.or(sheet.slider(tr("Triplanar Contrast"), &mut edited.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE, 2)); + } + edit = edit.or(sheet.slider(tr("Texture Opacity"), &mut edited.opacity, 0.0..=1.0, 2)); + } + sheet.close_card(); + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), texture_params(&edited))); + } +} + +/// The earlier model's ramp: where it starts, how soft it is, the noise breaking it up, its offset and its seed +pub(crate) fn ramp_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator) { + let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); + let mut edit = sheet.slider(tr("Level"), &mut level, 0.0..=1.0, 2); + edit = edit.or(sheet.slider(tr("Softness"), &mut softness, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("Noise Amount"), &mut noise, 0.0..=Generator::MAX_NOISE_AMOUNT, 2)); + edit = edit.or(sheet.slider(tr("Noise Scale"), &mut noise_scale, EARLIER_NOISE_SCALE, 1)); + edit = edit.or(sheet.signed_slider(tr("Offset"), &mut offset, -1.0..=1.0, 2)); + if let Some(merge) = edit { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), + ); + } + let mut seed = generator.seed; + if sheet.seed(tr("Seed"), &mut seed) { + app.run("effect.set", json!({"effect": id, "seed": seed})); + } +} + +/// What the earlier model's Noise Scale slider spans: the noise sizes it was tuned over +const EARLIER_NOISE_SCALE: std::ops::RangeInclusive = 0.1..=64.0; + +/// The translated name of axis blending mode `blend` +fn axis_blend_label(blend: AxisBlend) -> &'static str { + match blend { + AxisBlend::Normal => tr("Normal"), + AxisBlend::Add => tr("Linear Dodge (Add)"), + AxisBlend::Subtract => tr("Subtract"), + AxisBlend::Multiply => tr("Multiply"), + AxisBlend::AddSub => tr("Add/Sub"), + AxisBlend::Max => tr("Max (Lighten)"), + } +} + +/// 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("Dual"), + CurvatureMode::Raw => tr("Unprocessed"), + } +} diff --git a/crates/ui-egui/src/generator_slot.rs b/crates/ui-egui/src/generator_slot.rs index 99c19557..4d396b4d 100644 --- a/crates/ui-egui/src/generator_slot.rs +++ b/crates/ui-egui/src/generator_slot.rs @@ -1,9 +1,8 @@ -//! The generator slot atop a generator's properties: its orb and name, opening a picker that swaps its kind +//! The generator picker a generator's slot card opens: picking a kind swaps the generator to it -use egui::{Sense, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::{Generator, GeneratorKind}; +use texturecraft_engine::core::GeneratorKind; use crate::TextureCraftApp; use crate::i18n::tr; @@ -11,27 +10,16 @@ use crate::picker_group::PickerGroup; use crate::picker_tab::PickerTab; use crate::resource_picker; use crate::resource_picker_item::ResourcePickerItem; -use crate::resource_slot::{ResourceSlot, SLOT_HEIGHT}; use crate::tile_picture::TilePicture; -/// The slot of generator effect `effect`: a pick runs `effect.set {generator}` -pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, generator: &Generator) { - let ctx = ui.ctx().clone(); - let current = generator.kind; - let thumbnail = app.thumbs.generator(&ctx, current); - let name = tr(current.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)); - let popup = ui.make_persistent_id(("generator_picker", effect)); - if response.clicked() { +/// The picker of generator effect `effect` (a `current` generator) under its slot `pick`: a pick runs `effect.set {generator}` +pub(crate) fn picker(app: &mut TextureCraftApp, pick: &egui::Response, effect: u64, current: GeneratorKind) { + let ctx = pick.ctx.clone(); + let popup = pick.id.with(("generator_picker", effect)); + if pick.clicked() { resource_picker::toggle(&ctx, popup); } - let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); - let slot = ResourceSlot { highlighted, focused: response.has_focus(), thumbnail: thumbnail.as_ref(), caption: tr("Generator"), name }; - slot.paint(ui, rect); - let tabs = || { let mut items: Vec> = GeneratorKind::ALL .into_iter() @@ -43,7 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, generato items.sort_by_cached_key(|item| item.label.to_lowercase()); vec![PickerTab { icon: ic::SPARKLE, name: tr("Generators"), groups: vec![PickerGroup { header: None, items }] }] }; - let picked = resource_picker::show(&response, popup, &mut app.thumbs, Some(¤t), true, tabs); + let picked = resource_picker::show(pick, popup, &mut app.thumbs, Some(¤t), true, tabs); if let Some(kind) = picked.filter(|kind| *kind != current) { app.run("effect.set", json!({"effect": effect, "generator": kind.id()})); } diff --git a/crates/ui-egui/src/generator_wear_rows.rs b/crates/ui-egui/src/generator_wear_rows.rs new file mode 100644 index 00000000..09273f0b --- /dev/null +++ b/crates/ui-egui/src/generator_wear_rows.rs @@ -0,0 +1,158 @@ +//! The Parameters rows of the wear kinds and the Light generator, and the Micro Details rows they share with Curvature and Ambient Occlusion + +use egui::{Painter, Rect}; +use serde_json::json; +use texturecraft_engine::core::{Generator, GeneratorKind, LayerId, LightParameters, MicroCurvatureType, MicroDetails, WearParameters}; + +use crate::TextureCraftApp; +use crate::generator_input_card::input_card; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::generator_params::{light_params, merged, micro_params, wear_params}; +use crate::i18n::tr; +use crate::property_sheet::{PropertySheet, StackSlider}; + +/// A 0..1 setting in the stack beside the preview +fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } +} + +/// The wear controls of generator effect `id` on `layer` in the reference's order, showing `wear`; `picture` draws the preview +pub(crate) fn wear_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + (layer, id): (LayerId, u64), + generator: &Generator, + wear: WearParameters, + picture: &dyn Fn(&Painter, Rect), +) { + let kind = generator.kind; + let mut seed = generator.seed; + if sheet.seed(tr("Seed"), &mut seed) { + app.run("effect.set", json!({"effect": id, "seed": seed})); + } + let mut invert = generator.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + + let dirt = kind == GeneratorKind::Dirt; + let (level_label, contrast_label) = if dirt { (tr("Dirt Level"), tr("Dirt Contrast")) } else { (tr("Wear Level"), tr("Wear Contrast")) }; + let mut edited = wear; + let mut stack = [ + stacked(level_label, &mut edited.level), + stacked(contrast_label, &mut edited.contrast), + stacked(tr("Grunge Amount"), &mut edited.grunge_amount), + ]; + let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); + if kind != GeneratorKind::FiberGlassEdgeWear { + edit = edit.or(sheet.slider(tr("Grunge Scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); + } + if dirt { + edit = edit.or(sheet.slider(tr("Edges Masking"), &mut edited.edges_masking, 0.0..=1.0, 2)); + } else { + edit = edit.or(sheet.slider(tr("Edges Smoothness"), &mut edited.edges_smoothness, WearParameters::EDGES_SMOOTHNESS_RANGE, 2)); + edit = edit.or(sheet.slider(tr("Ambient Occlusion Masking"), &mut edited.ao_masking, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("Curvature Weight"), &mut edited.curvature_weight, 0.0..=1.0, 2)); + } + + if sheet.switch_card(tr("Use Triplanar"), &mut edited.triplanar) { + edit = Some(false); + } + if edited.triplanar { + edit = edit.or(sheet.slider(tr("Triplanar Blending Contrast"), &mut edited.triplanar_contrast, 0.0..=1.0, 2)); + } + sheet.close_card(); + + if sheet.switch_card(tr("Use Custom Grunge"), &mut edited.custom_grunge) { + edit = Some(false); + } + if edited.custom_grunge { + input_card(app, sheet, (layer, id), GeneratorInputSlot::Grunge, generator.grunge.as_ref(), true); + } + sheet.close_card(); + + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), wear_params(kind, &edited))); + } + + if sheet.card(tr("Micro Details"), Some(false)) { + micro_rows(app, sheet, (layer, id), generator); + } + sheet.close_card(); +} + +/// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) +pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, invert: Option, shown: LightParameters, picture: &dyn Fn(&Painter, Rect)) { + if let Some(mut invert) = invert + && sheet.toggle(tr("Invert"), &mut invert) + { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + + let mut edited = shown; + let angle = |label, value| StackSlider { label, value, range: LightParameters::ANGLE_RANGE, typed: LightParameters::ANGLE_RANGE, decimals: 0, suffix: "°", dial: true }; + let mut stack = [ + angle(tr("Horizontal Angle"), &mut edited.horizontal), + angle(tr("Vertical Angle"), &mut edited.vertical), + stacked(tr("Light Attenuation"), &mut edited.attenuation), + ]; + let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); + edit = edit.or(sheet.slider(tr("Highlight Glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); + edit = edit.or(sheet.slider(tr("Highlight Level"), &mut edited.highlight_level, 0.0..=1.0, 2)); + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), light_params(&edited))); + } +} + +/// Curvature's and Ambient Occlusion's Use Micro Details: its switch card, holding the micro details rows while on +pub(crate) fn micro_switch_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), generator: &Generator) { + let Some(defaults) = MicroDetails::defaults(generator.kind) else { return }; + + let mut on = generator.micro.as_ref().map_or(defaults.enabled, |micro| micro.enabled); + if sheet.switch_card(tr("Use Micro Details"), &mut on) { + app.run("effect.set", json!({"effect": id, "useMicroDetails": on})); + } + if on { + micro_rows(app, sheet, (layer, id), generator); + } + sheet.close_card(); +} + +/// The micro details rows of generator effect `id`, inside the card open now: each image's switch with its slot while on, then the kind's settings +fn micro_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), generator: &Generator) { + let kind = generator.kind; + let Some(defaults) = MicroDetails::defaults(kind) else { return }; + + let shown = generator.micro.as_deref().cloned().unwrap_or(defaults); + let mut edited = shown.clone(); + let mut edit = None; + if sheet.toggle(tr("Micro Height"), &mut edited.height) { + edit = Some(false); + } + if edited.height { + input_card(app, sheet, (layer, id), GeneratorInputSlot::MicroHeight, shown.height_source.as_ref(), true); + } + if sheet.toggle(tr("Micro Normal"), &mut edited.normal) { + edit = Some(false); + } + if edited.normal { + input_card(app, sheet, (layer, id), GeneratorInputSlot::MicroNormal, shown.normal_source.as_ref(), true); + } + if MicroDetails::has_curvature(kind) { + let name = |kind: MicroCurvatureType| tr(kind.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Curvature Type"), edited.curvature_type, &MicroCurvatureType::ALL, name, None) { + edited.curvature_type = picked; + edit = Some(false); + } + let range = MicroDetails::curvature_intensity_range(kind); + edit = edit.or(sheet.slider(tr("Curvature Intensity"), &mut edited.curvature_intensity, range, 2)); + edit = edit.or(sheet.slider(tr("Height Details Intensity"), &mut edited.height_intensity, MicroDetails::HEIGHT_INTENSITY_RANGE, 2)); + } + if MicroDetails::has_occlusion(kind) { + edit = edit.or(sheet.slider(tr("AO Radius"), &mut edited.ao_radius, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("AO Depth"), &mut edited.ao_depth, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), micro_params(kind, &edited))); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a8e83fce..d626d5c3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -44,8 +44,13 @@ mod filter_transform_rows; mod folder_properties; pub mod fonts; mod frame_gizmo; +mod generator_input_card; +mod generator_input_slot; mod generator_panel; +mod generator_params; +mod generator_section_rows; mod generator_slot; +mod generator_wear_rows; pub mod gpu; mod gray_slider; mod grid_tile; @@ -125,7 +130,6 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; -mod resource_slot; mod round_gizmo; mod running_bake; pub mod saved_search; diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 71c925ea..f1d78d74 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -25,6 +25,10 @@ impl PreviewRequest { match &self.preview { ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), ShelfPreview::Generator(kind) => Some(mask_preview_image(self.size_px, &shape.get()?.generator(*kind, self.size_px)?)), + ShelfPreview::Curvature { mode, solo } => { + let generator = ShelfPreview::curvature_generator(*mode, *solo); + Some(mask_preview_image(self.size_px, &shape.get()?.generator_of(generator, 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/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index 5a0f6a22..f16db1b3 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -5,7 +5,7 @@ use std::ops::RangeInclusive; use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::row::SECTION_CAPTION_CENTER; -use super::slider::KNOB_RADIUS; +use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS}; use super::switch_control::PILL_SIZE; use super::track::Track; use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; @@ -31,6 +31,15 @@ const STACK_CAPTION_LINE: f32 = 18.0; const STACK_PART_LINE: f32 = 22.0; const STACK_GAP: f32 = 6.0; +/// An axis card's air above its name row, the edge of its letter chip, the air from the chip to the name, and its full-width track's line +const AXIS_CARD_TOP: f32 = 4.0; +const AXIS_CHIP_SIZE: f32 = 18.0; +const AXIS_CHIP_TO_NAME: f32 = 8.0; +const AXIS_TRACK_LINE: f32 = 20.0; + +/// The letter on an axis chip: dark on every axis color, in every theme +const AXIS_CHIP_LETTER: Color32 = Color32::from_rgb(20, 20, 24); + /// The picture's top below the block's (the first caption's letters), how much shorter it is than the stack, and its air before the controls column const PICTURE_TOP: f32 = 4.0; const PICTURE_SHORTER: f32 = 10.0; @@ -97,6 +106,28 @@ impl PropertySheet<'_> { edit } + /// A card for one axis: its letter on a chip in `tint`, the bold name and the value, then a full-width slider filled in `tint`; the axis's other rows follow, then [`Self::close_card`] + pub(crate) fn axis_card(&mut self, (letter, tint): (&str, Color32), name: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + self.open_card(); + self.scope = self.named_id("axis_card", name); + self.space(AXIS_CARD_TOP); + let head = self.take(super::ROW_HEIGHT); + let center_y = head.center().y; + let chip = Rect::from_center_size(pos2(self.left + AXIS_CHIP_SIZE / 2.0, center_y), vec2(AXIS_CHIP_SIZE, AXIS_CHIP_SIZE)); + let painter = self.ui.painter(); + painter.rect_filled(chip, egui::CornerRadius::same(super::CONTROL_RADIUS), tint); + painter.text(chip.center(), Align2::CENTER_CENTER, letter, semibold(SMALL_TEXT_SIZE), AXIS_CHIP_LETTER); + painter.text(pos2(chip.right() + AXIS_CHIP_TO_NAME, center_y), Align2::LEFT_CENTER, name, semibold(TEXT_SIZE), self.tokens.text); + + let id = self.next_id(); + let typed = self.value_field(id, name, center_y, *value, &range, decimals, ""); + let track_y = self.take(AXIS_TRACK_LINE).center().y; + let track = Track { start: self.left + KNOB_RADIUS, end: self.right - KNOB_RADIUS, center_y: track_y, zero: None, ramp: false }; + let dragged = self.track_filled(id, name, &track, value, &range, tint); + self.drawn(track_y + KNOB_RADIUS); + Self::apply_typed(value, typed, dragged) + } + /// Draw a picture beside captioned sliders and report the edit on each slider. pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>; N]) -> [Option; N] { let count = sliders.len().max(1) as f32; @@ -117,7 +148,12 @@ impl PropertySheet<'_> { self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; let id = self.next_id(); - let track = Track { start: x0 + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; + let end = if slider.dial { dial_x - DIAL_RADIUS - DIAL_AIR } else { self.track_end() }; + let track = Track { start: x0 + KNOB_RADIUS, end, center_y, zero: None, ramp: false }; + if slider.dial { + self.paint_dial(pos2(dial_x, center_y), *slider.value); + } let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); *edit = Self::apply_typed(slider.value, typed, dragged); diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index 7a3085bf..d7d30e03 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -2,6 +2,7 @@ use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2} use egui_phosphor::regular as ic; use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; +use super::switch_control::PILL_SIZE; use super::{BandResponse, GROUP_GAP, PropertySheet, ROW_HEIGHT, TEXT_SIZE, open_card::OpenCard}; use crate::theme::semibold; @@ -173,6 +174,22 @@ impl PropertySheet<'_> { open } + /// A card headed by its on/off switch: the bold name, the switch at the right edge; its settings follow while on, then [`Self::close_card`]. Returns whether the switch was clicked + pub(crate) fn switch_card(&mut self, title: &str, on: &mut bool) -> bool { + self.open_card(); + self.scope = self.named_id("card", title); + let rect = self.take(CARD_NAME_CENTER + ROW_HEIGHT / 2.0); + let center_y = rect.top() + CARD_NAME_CENTER; + let hit = Rect::from_x_y_ranges(self.left..=self.right, (center_y - CARD_HIT_HALF_HEIGHT)..=(center_y + CARD_HIT_HALF_HEIGHT)); + let clicked = self.toggle_hit(hit, title, on); + + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + self.pill(pos2(self.right - PILL_SIZE.x / 2.0, center_y), *on, true); + self.drawn(center_y + TITLE_HALF_LINE); + clicked + } + /// A sub-group inside the held card: its bold name on a hairline (no card in a card), a caret when it folds fn inner_caption(&mut self, title: &str, foldable: Option) -> bool { self.space(INNER_CAPTION_AIR); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 62c81046..0a890707 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -37,6 +37,8 @@ mod section_tabs; #[path = "property_sheet.rs"] mod sheet; mod sheet_measure; +mod size_columns; +mod size_columns_response; mod slider; mod slot; mod slot_response; @@ -66,6 +68,7 @@ pub(crate) use section_tabs::{ full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box, }; pub(crate) use sheet::PropertySheet; +pub(crate) use size_columns_response::SizeColumnsResponse; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; diff --git a/crates/ui-egui/src/property_sheet/size_columns.rs b/crates/ui-egui/src/property_sheet/size_columns.rs new file mode 100644 index 00000000..da810113 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/size_columns.rs @@ -0,0 +1,73 @@ +//! A row of vertical sliders across the panel, one per size, each with its value above and its name below (Curvature's detail sizes) + +use egui::{Align2, CornerRadius, Rect, Sense, Stroke, WidgetInfo, pos2}; + +use super::slider::{KNOB_RADIUS, KNOB_STROKE}; +use super::{PropertySheet, SMALL_TEXT_SIZE, SizeColumnsResponse}; +use crate::theme::semibold; + +/// A column's value line above its track, the track's length, and its name line under it +const VALUE_LINE: f32 = 20.0; +const COLUMN_TRACK: f32 = 72.0; +const NAME_LINE: f32 = 22.0; + +/// How far a hovered column's face reaches past its value and name lines, and the air between neighbouring faces +const FACE_OVERHANG: f32 = 4.0; +const FACE_AIR: f32 = 2.0; + +/// Width of a column's track and fill +const COLUMN_TRACK_WIDTH: f32 = 2.0; + +impl PropertySheet<'_> { + /// One 0..1 vertical slider per name in `values`, side by side across the panel + pub(crate) fn size_columns(&mut self, names: &[&str], values: &mut [f32]) -> SizeColumnsResponse { + let block = self.take(VALUE_LINE + COLUMN_TRACK + NAME_LINE); + let pitch = (self.right - self.left) / names.len().max(1) as f32; + let (track_top, track_bottom) = (block.top() + VALUE_LINE, block.top() + VALUE_LINE + COLUMN_TRACK); + let tokens = self.tokens; + let mut response = SizeColumnsResponse::default(); + for (index, (name, value)) in names.iter().zip(values.iter_mut()).enumerate() { + let x = self.left + pitch * (index as f32 + 0.5); + let column = Rect::from_min_max(pos2(x - pitch / 2.0, block.top()), pos2(x + pitch / 2.0, block.bottom())); + let id = self.next_id(); + let hit = self.ui.interact(column, id, Sense::click_and_drag()); + hit.widget_info(|| WidgetInfo::slider(true, f64::from(*value), *name)); + + let mut moved = false; + if (hit.dragged() || hit.drag_stopped() || hit.clicked()) + && let Some(pointer) = hit.interact_pointer_pos() + { + let picked = (1.0 - (pointer.y - track_top) / COLUMN_TRACK).clamp(0.0, 1.0); + if picked != *value { + *value = picked; + moved = true; + } + } + if let Some(merge) = crate::widgets::press_edit(self.ui, id, moved) { + response.edit = Some((index, merge)); + } + let hovered = hit.hovered() || hit.dragged(); + if hovered { + response.hovered = Some(index); + } + + let painter = self.ui.painter(); + if hovered { + let face = Rect::from_min_max(pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG)); + painter.rect(face, CornerRadius::same(super::CONTROL_RADIUS), tokens.row_hover, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + } + painter.text(pos2(x, block.top() + VALUE_LINE / 2.0), Align2::CENTER_CENTER, format!("{value:.2}"), semibold(SMALL_TEXT_SIZE), tokens.text); + painter.line_segment([pos2(x, track_top), pos2(x, track_bottom)], Stroke::new(COLUMN_TRACK_WIDTH, tokens.button_border)); + let knob_y = track_bottom - value.clamp(0.0, 1.0) * COLUMN_TRACK; + painter.line_segment([pos2(x, knob_y), pos2(x, track_bottom)], Stroke::new(COLUMN_TRACK_WIDTH, tokens.accent)); + let outline = if hovered { tokens.accent } else { tokens.text }; + painter.circle(pos2(x, knob_y), KNOB_RADIUS, tokens.panel, Stroke::new(KNOB_STROKE, outline)); + let (font, color) = if hovered { (semibold(SMALL_TEXT_SIZE), tokens.text) } else { (egui::FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) }; + painter.text(pos2(x, track_bottom + NAME_LINE / 2.0), Align2::CENTER_CENTER, *name, font, color); + self.paint_control_focus(&hit); + } + + self.drawn(block.bottom()); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/size_columns_response.rs b/crates/ui-egui/src/property_sheet/size_columns_response.rs new file mode 100644 index 00000000..2ea0031c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/size_columns_response.rs @@ -0,0 +1,9 @@ +/// What a row of size columns did this frame +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct SizeColumnsResponse { + /// The column edited and whether the edit continues the previous undo step + pub(crate) edit: Option<(usize, bool)>, + + /// The column under the pointer or being dragged + pub(crate) hovered: Option, +} diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 98ef953d..6cf51d26 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -13,7 +13,7 @@ use crate::theme::semibold; pub(super) const KNOB_RADIUS: f32 = 5.0; /// Width of a slider's knob outline -const KNOB_STROKE: f32 = 1.5; +pub(super) const KNOB_STROKE: f32 = 1.5; /// Width of a slider's track const TRACK_WIDTH: f32 = 2.0; @@ -22,13 +22,13 @@ const TRACK_WIDTH: f32 = 2.0; const ZERO_TICK_HALF: f32 = 4.0; /// Radius of an angle row's dial -const DIAL_RADIUS: f32 = 8.0; +pub(super) const DIAL_RADIUS: f32 = 8.0; /// The quarter turn back from the screen's 0 rad (pointing right) that points the dial's hand straight up at 0° const DIAL_ZERO_DEGREES: f32 = 90.0; /// Air between the dial and the value, and between the track's end and the dial -const DIAL_AIR: f32 = 6.0; +pub(super) const DIAL_AIR: f32 = 6.0; /// Air between a tinted slider's track end and its right-hand color name const TINT_WORD_AIR: f32 = 8.0; @@ -128,18 +128,23 @@ impl PropertySheet<'_> { let name = lead.text(); let dragged = self.track(id, name, &track, degrees, &range); - let tokens = self.tokens; - let painter = self.ui.painter(); - painter.circle_stroke(pos2(dial_x, center_y), DIAL_RADIUS, Stroke::new(KNOB_STROKE, tokens.button_border)); - let turn = (*degrees - DIAL_ZERO_DEGREES).to_radians(); - let hand = pos2(dial_x + DIAL_RADIUS * turn.cos(), center_y + DIAL_RADIUS * turn.sin()); - painter.line_segment([pos2(dial_x, center_y), hand], Stroke::new(TRACK_WIDTH, tokens.text)); + self.paint_dial(pos2(dial_x, center_y), *degrees); let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); Self::apply_typed(degrees, typed, dragged) } + /// The small dial of an angle row centred on `center`, its hand at `degrees` + pub(super) fn paint_dial(&self, center: egui::Pos2, degrees: f32) { + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.circle_stroke(center, DIAL_RADIUS, Stroke::new(KNOB_STROKE, tokens.button_border)); + let turn = (degrees - DIAL_ZERO_DEGREES).to_radians(); + let hand = pos2(center.x + DIAL_RADIUS * turn.cos(), center.y + DIAL_RADIUS * turn.sin()); + painter.line_segment([center, hand], Stroke::new(TRACK_WIDTH, tokens.text)); + } + /// A slider with a small dropdown chip before its value (Intensity's divider); returns the edit and the chip pub(crate) fn slider_with_chip( &mut self, @@ -187,6 +192,20 @@ impl PropertySheet<'_> { /// Paints a track with its knob and moves `value` while it is clicked or dragged pub(super) fn track(&mut self, id: Id, label: impl std::fmt::Display, track: &Track, value: &mut f32, range: &RangeInclusive) -> Option { + let fill = self.tokens.accent; + self.track_filled(id, label, track, value, range, fill) + } + + /// [`Self::track`] whose fill is `fill` (an axis card's in its axis color) + pub(super) fn track_filled( + &mut self, + id: Id, + label: impl std::fmt::Display, + track: &Track, + value: &mut f32, + range: &RangeInclusive, + fill: Color32, + ) -> Option { let (minimum, maximum) = (*range.start(), *range.end()); let span = (maximum - minimum).max(f32::EPSILON); let length = (track.end - track.start).max(1.0); @@ -218,7 +237,7 @@ impl PropertySheet<'_> { let painter = self.ui.painter(); if !track.ramp { painter.line_segment([pos2(track.start, track.center_y), pos2(track.end, track.center_y)], Stroke::new(TRACK_WIDTH, tokens.button_border)); - painter.line_segment([pos2(zero_x.min(knob_x), track.center_y), pos2(zero_x.max(knob_x), track.center_y)], Stroke::new(TRACK_WIDTH, tokens.accent)); + painter.line_segment([pos2(zero_x.min(knob_x), track.center_y), pos2(zero_x.max(knob_x), track.center_y)], Stroke::new(TRACK_WIDTH, fill)); } if track.zero.is_some() { let tick = [pos2(zero_x, track.center_y - ZERO_TICK_HALF), pos2(zero_x, track.center_y + ZERO_TICK_HALF)]; diff --git a/crates/ui-egui/src/property_sheet/stack_slider.rs b/crates/ui-egui/src/property_sheet/stack_slider.rs index b68c602d..9297e9b9 100644 --- a/crates/ui-egui/src/property_sheet/stack_slider.rs +++ b/crates/ui-egui/src/property_sheet/stack_slider.rs @@ -17,4 +17,7 @@ pub(crate) struct StackSlider<'a> { /// A unit after the value ("°") pub(crate) suffix: &'a str, + + /// An angle: a small dial before its value, as an angle row has + pub(crate) dial: bool, } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 7443f9f4..8f700a6d 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -234,7 +234,7 @@ impl PropertySheet<'_> { } /// A toggle's clickable area: a click flips `on`; returns whether it was clicked - fn toggle_hit(&mut self, hit: Rect, label: &str, on: &mut bool) -> bool { + pub(super) fn toggle_hit(&mut self, hit: Rect, label: &str, on: &mut bool) -> bool { let id = self.next_id(); let response = self.ui.interact(hit, id, Sense::click()); if response.clicked() { diff --git a/crates/ui-egui/src/resource_slot.rs b/crates/ui-egui/src/resource_slot.rs deleted file mode 100644 index e814dd27..00000000 --- a/crates/ui-egui/src/resource_slot.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! The box atop an effect's properties that names its resource and opens a picker: thumbnail, a caption over the name, a caret - -use egui::{Align2, FontId, Rect, Stroke, Ui, pos2, vec2}; -use egui_phosphor::regular as ic; - -use crate::theme::Tokens; -use crate::widgets::elided; - -/// The slot's height in points -pub(crate) 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; -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; -/// Gap between the slot and its keyboard focus outline -const FOCUS_MARGIN: f32 = 2.0; - -/// What the slot shows and how: highlighted while hovered or its picker is open, outlined while focused -pub(crate) struct ResourceSlot<'a> { - pub highlighted: bool, - pub focused: bool, - pub thumbnail: Option<&'a egui::TextureHandle>, - pub caption: &'a str, - pub name: &'a str, -} - -impl ResourceSlot<'_> { - /// Paints the slot into `rect` - pub(crate) fn paint(&self, ui: &Ui, rect: Rect) { - let tk = Tokens::get(ui.ctx()); - let painter = ui.painter(); - let (fill, border) = if self.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 self.focused { - painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); - } - - if let Some(texture) = self.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); - } - - // 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 = [(self.caption, CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (self.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 self.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/src/shelf.rs b/crates/ui-egui/src/shelf.rs index bc34317f..dc64aaae 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,7 +646,7 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::SmartMaterial(_)); + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | 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 diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 20491e3a..744c3795 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::compose::ImageStore; -use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; +use texturecraft_engine::core::{CurvatureMode, Generator, GeneratorKind, ProceduralKind}; use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; @@ -30,6 +30,8 @@ pub enum ShelfPreview { SmartMask(&'static str), /// A mask generator at its defaults, rendered like a smart mask on the worker's baked orb Generator(GeneratorKind), + /// A Curvature generator in `mode`, with only detail size `solo` (finest first) when given, rendered like [`ShelfPreview::Generator`] + Curvature { mode: CurvatureMode, solo: Option }, /// A library filter on a sample material on a sphere Filter(&'static str), /// A procedural pattern as a grayscale swatch @@ -47,6 +49,18 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// The Curvature generator [`ShelfPreview::Curvature`] renders + pub fn curvature_generator(mode: CurvatureMode, solo: Option) -> Generator { + let mut generator = Generator::new(GeneratorKind::Curvature); + let mut detail = generator.detail.take().unwrap_or_default(); + detail.mode = mode; + if let Some(solo) = solo { + detail.weights = std::array::from_fn(|size| if size == solo { 1.0 } else { 0.0 }); + } + generator.detail = Some(detail); + generator + } + /// Resolve a saved brush's image alpha while the project images are available pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { let settings = read_saved_brush(path); @@ -75,6 +89,7 @@ impl ShelfPreview { ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Generator(kind) => format!("generator:{kind:?}"), + ShelfPreview::Curvature { mode, solo } => format!("curvature:{mode:?}:{solo:?}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), @@ -90,7 +105,7 @@ impl ShelfPreview { pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::SmartMaterial(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | 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)), diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index e847359e..569443c6 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -300,6 +300,11 @@ impl Thumbs { self.worker_rendered(ctx, ShelfPreview::Generator(kind), SPHERE_PX, false) } + /// A generator orb (`preview` a [`ShelfPreview::Generator`] or [`ShelfPreview::Curvature`]) rendered `size_px` wide, kept like a thumbnail; None until the worker returns it + pub fn generator_picture(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + self.worker_rendered(ctx, preview, size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX), false) + } + /// 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) diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index aae768dc..67ed3eca 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -37,9 +37,9 @@ fn mode_label(mode: CurvatureMode) -> &'static str { } fn select_mode(harness: &mut Harness<'_, TextureCraftApp>, current: CurvatureMode, next: CurvatureMode) { - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(mode_label(current))).unwrap().click(); + harness.get_by_role_and_label(Role::ComboBox, mode_label(current)).click(); harness.run_steps(2); - harness.get_by_label(mode_label(next)).click(); + harness.get_by_role_and_label(Role::ListBoxOption, mode_label(next)).click(); harness.run_steps(4); } @@ -54,11 +54,10 @@ fn mode_and_detail_controls_apply_and_undo() { assert_eq!(detail(&harness).mode, CurvatureMode::Cavities); let previous = detail(&harness); let history = harness.state().session.history_labels().len(); - harness.get_by_label("Large").scroll_to_me(); + harness.get_by_role_and_label(Role::Slider, "Large").scroll_to_me(); harness.run_steps(3); - let label = harness.get_by_label("Large").rect(); - let start = egui::pos2(label.left() + 20.0, label.bottom() + 10.0); - let end = start + egui::vec2(100.0, 0.0); + let column = harness.get_by_role_and_label(Role::Slider, "Large").rect(); + let (start, end) = (egui::pos2(column.center().x, column.bottom() - 30.0), egui::pos2(column.center().x, column.top() + 24.0)); harness.drag_at(start); harness.run_steps(2); harness.hover_at(end); diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index 30e53995..a191e641 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -38,10 +38,14 @@ fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { } } -/// The track under the slider labelled `label` (the row below the label). +/// The track of the slider labelled `label` fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { - let label_rect = harness.get_by_label(label).rect(); - egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0)) + harness.get_by_role_and_label(Role::Slider, label).rect() +} + +/// The point `share` of the way along `track` +fn along(track: egui::Rect, share: f32) -> egui::Pos2 { + egui::pos2(track.left() + track.width() * share, track.center().y) } #[test] @@ -49,12 +53,12 @@ fn dragging_a_slider_applies_it() { let (mut harness, effect) = selected_generator(); assert_eq!(balance(&harness, effect), 0.5); - let track_rect = track(&harness, "Global balance"); - harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + let track_rect = track(&harness, "Global Balance"); + harness.drag_at(along(track_rect, 0.98)); harness.run_steps(2); - harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.hover_at(along(track_rect, 0.08)); harness.run_steps(2); - harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.drop_at(along(track_rect, 0.08)); harness.run_steps(3); assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); @@ -71,19 +75,19 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { }; let steps = harness.state().session.history_labels().len(); let track_rect = track(&harness, "Level"); - let point_at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y); - harness.drag_at(point_at(10.0)); + let point_at = |share: f32| along(track_rect, share); + harness.drag_at(point_at(0.05)); harness.run_steps(2); let mut last = 0.0; - for x in [60.0, 160.0] { - harness.hover_at(point_at(x)); + for share in [0.3, 0.8] { + harness.hover_at(point_at(share)); harness.run_steps(2); assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); last = level(&harness); } - harness.drop_at(point_at(160.0)); + harness.drop_at(point_at(0.8)); harness.run_steps(3); assert_eq!(level(&harness), last); @@ -93,8 +97,8 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { #[test] fn clicking_a_slider_track_applies_it() { let (mut harness, effect) = selected_generator(); - let track_rect = track(&harness, "Global balance"); - let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y); + let track_rect = track(&harness, "Global Balance"); + let at = along(track_rect, 0.08); harness.drag_at(at); harness.drop_at(at); harness.run_steps(3); @@ -104,20 +108,22 @@ fn clicking_a_slider_track_applies_it() { /// The number field in the row of the slider labelled `label` fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = harness.get_by_label(label).rect().center().y; + let row = track(harness, label).center().y; harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person. +/// Click the balance's value to type in it and press `keys`, then type `text`, one key per frame like a person. fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { - number_field(harness, "Global balance").focus(); + harness.get_by_label("Global Balance value").click(); + harness.run_steps(2); + number_field(harness, "Global Balance").focus(); harness.run_steps(2); for key in keys { harness.key_press(*key); harness.run_steps(1); } for character in text.chars() { - number_field(harness, "Global balance").type_text(&character.to_string()); + number_field(harness, "Global Balance").type_text(&character.to_string()); harness.run_steps(1); } } @@ -140,12 +146,12 @@ fn a_value_typed_in_the_number_field_applies() { fn a_track_drag_drops_text_typed_in_the_number_field() { let (mut harness, effect) = selected_generator(); type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5"); - let track_rect = track(&harness, "Global balance"); - harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + let track_rect = track(&harness, "Global Balance"); + harness.drag_at(along(track_rect, 0.98)); harness.run_steps(2); - harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.hover_at(along(track_rect, 0.08)); harness.run_steps(2); - harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.drop_at(along(track_rect, 0.08)); harness.run_steps(2); let dragged = balance(&harness, effect); assert!(dragged < 0.25, "the drag applies: {dragged}"); @@ -175,8 +181,8 @@ fn leaving_the_number_field_unchanged_keeps_the_value() { type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); - assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); - assert!(number_field(&harness, "Global balance").is_focused()); + assert_eq!(number_field(&harness, "Global Balance").value().as_deref(), Some("0.39")); + assert!(number_field(&harness, "Global Balance").is_focused()); harness.key_press(egui::Key::Escape); harness.run_steps(3); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 811582c8..78fc0d9c 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -2,7 +2,7 @@ use egui::Role; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; @@ -42,13 +42,14 @@ fn generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generat } } -/// Drags the track under slider `label` to the right. +/// Drags slider `label` from near its left end to the right fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { - harness.get_by_label(label).scroll_to_me(); + harness.get_by_role_and_label(Role::Slider, label).scroll_to_me(); harness.run_steps(3); - let rect = harness.get_by_label(label).rect(); - let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0); - let end = start + egui::vec2(120.0, 0.0); + let rect = harness.get_by_role_and_label(Role::Slider, label).rect(); + let start = egui::pos2(rect.left() + 12.0, rect.center().y); + // Three quarters along: off a 0.5 default, which a drag ending mid-track would land back on + let end = egui::pos2(rect.left() + rect.width() * 0.75, rect.center().y); harness.drag_at(start); harness.run_steps(2); harness.hover_at(end); @@ -57,11 +58,31 @@ fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.run_steps(3); } +/// A press and release at `at` +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + harness.drag_at(at); + harness.run_steps(1); + harness.drop_at(at); + harness.run_steps(3); +} + +/// Clicks the one live control named `label` with `role` (the panel's Restore defaults and a slot's share a name) +fn click_live(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + let live = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role_and_label(role, label).find(|node| !node.accesskit_node().is_disabled()).expect("a live control").rect() + }; + let rect = live(harness); + harness.hover_at(rect.center()); + harness.run_steps(2); + let at = live(harness).center(); + click_at(harness, at); +} + #[test] fn global_blur_applies_as_one_undo_step() { let (mut harness, effect) = harness(false); let history = harness.state().session.history_labels().len(); - drag_slider(&mut harness, "Global blur"); + drag_slider(&mut harness, "Global Blur"); assert!(generator(&harness, effect).global.blur > 0.0); assert_eq!(harness.state().session.history_labels().len(), history + 1); harness.state_mut().session.undo().unwrap(); @@ -71,15 +92,12 @@ fn global_blur_applies_as_one_undo_step() { #[test] fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { let (mut harness, effect) = harness(false); + assert!(harness.get_by_role_and_label(Role::Button, "Restore defaults").accesskit_node().is_disabled(), "at its defaults it does nothing"); let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); - harness.run_steps(3); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); - harness.run_steps(3); + click_live(&mut harness, Role::Button, "Restore defaults"); assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); } @@ -102,7 +120,7 @@ fn a_wear_control_moves_an_earlier_wear_generator_onto_the_wear_controls() { let (mut harness, effect) = harness_with(false, json!({"generator": "edgeWear", "level": 0.4})); assert_eq!(generator(&harness, effect).wear, None, "level keeps it on the earlier model"); - drag_slider(&mut harness, "Wear level"); + drag_slider(&mut harness, "Wear Level"); let wear = generator(&harness, effect).wear.expect("on the wear controls now"); let defaults = WearParameters::defaults(GeneratorKind::EdgeWear).unwrap(); @@ -113,29 +131,31 @@ fn a_wear_control_moves_an_earlier_wear_generator_onto_the_wear_controls() { #[test] fn restore_defaults_keeps_a_wear_generator_on_its_wear_controls() { let (mut harness, effect) = harness_with(false, json!({"generator": "dirt", "grungeAmount": 0.9, "seed": 3})); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); - harness.run_steps(3); + click_live(&mut harness, Role::Button, "Restore defaults"); assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Dirt)); } +/// The slot reading `value`: an image input's card +fn slot_reading<'a>(harness: &'a Harness<'_, TextureCraftApp>, value: &str) -> egui_kittest::Node<'a> { + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(value)).expect("a slot reading it") +} + #[test] fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { let (mut harness, effect) = harness(false); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me(); + harness.get_by_role_and_label(Role::Button, "Image inputs").click(); harness.run_steps(3); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click(); + slot_reading(&harness, "Mesh map: Curvature").scroll_to_me(); + harness.run_steps(3); + slot_reading(&harness, "Mesh map: Curvature").click(); harness.run_steps(2); - harness.get_by_label("Uniform value").click(); + harness.get_by_role_and_label(Role::ListBoxOption, "Uniform value").click(); harness.run_steps(3); assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_)))); + assert!(slot_reading(&harness, "Uniform value").rect().is_positive()); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); - harness.run_steps(2); - harness.get_by_label("Mesh map").click(); - harness.run_steps(3); - assert!(generator(&harness, effect).inputs.is_empty()); + click_live(&mut harness, Role::Button, "Restore defaults"); + assert!(generator(&harness, effect).inputs.is_empty(), "the slot's reset reads the mesh map again"); } /// How many nodes carry `label` @@ -146,14 +166,14 @@ fn count(harness: &Harness<'_, TextureCraftApp>, label: &str) -> usize { #[test] fn each_kind_shows_its_section_rows_and_no_earlier_ones() { let rows = [ - ("curvature", &["Sharp", "Huge", "Brightness", "Global contrast"][..], &["Balance", "Blending mode", "Level"][..]), - ("ambientOcclusion", &["Blur", "Balance", "Global contrast"][..], &["Brightness", "Blending mode", "Level"][..]), - ("position", &["Balance", "Brightness", "Right to left", "Front to back"][..], &["Blur", "Level", "Sharp"][..]), - ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top to bottom"][..], &["Level", "Softness"][..]), + ("curvature", &["Sharp", "Huge", "Brightness", "Global Contrast"][..], &["Balance", "Blending Mode", "Level"][..]), + ("ambientOcclusion", &["Blur", "Balance", "Global Contrast"][..], &["Brightness", "Blending Mode", "Level"][..]), + ("position", &["Balance", "Brightness", "Right to Left", "Front to Back"][..], &["Blur", "Level", "Sharp"][..]), + ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top To Bottom"][..], &["Level", "Softness"][..]), ( "direction", - &["Horizontal angle", "Vertical angle", "Highlight glossiness", "Highlight level", "Light attenuation"][..], - &["Global blur", "Level"][..], + &["Horizontal Angle", "Vertical Angle", "Highlight Glossiness", "Highlight Level", "Light Attenuation"][..], + &["Global Blur", "Level"][..], ), ]; for (kind, shown, hidden) in rows { @@ -167,35 +187,23 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { } let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); - assert_eq!(count(&harness, "Blending mode"), 3); - for axis in ["Right to left", "Top to bottom", "Front to back"] { - assert_eq!(count(&harness, axis), 2, "{axis}: a section heading and its weight slider"); - } - let (harness, _) = harness_with(false, json!({"generator": "direction"})); - assert_eq!(count(&harness, "Angle"), 2, "an Angle slider beside each dial"); + assert_eq!(harness.get_all_by_role_and_label(Role::ComboBox, "Linear Dodge (Add)").count(), 3, "a blending mode per axis"); let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); } -/// The blending mode dropdown in the Front to back section: the first dropdown below its heading, the topmost "Front to back" -fn front_to_back_dropdown<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let heading = harness.query_all_by_label("Front to back").map(|node| node.rect().top()).fold(f32::INFINITY, f32::min); - let below = harness.get_all_by_role(Role::ComboBox).filter(|node| node.rect().top() > heading); - below.min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() -} - #[test] fn each_axis_has_its_own_blending_mode_dropdown() { let (mut harness, effect) = harness_with(false, json!({"generator": "worldSpaceNormals"})); - let added = |harness: &Harness<'_, TextureCraftApp>| { - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).count() + let lowest = |harness: &Harness<'_, TextureCraftApp>| { + let dropdowns = harness.get_all_by_role_and_label(Role::ComboBox, "Linear Dodge (Add)"); + dropdowns.max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().rect() }; - assert_eq!(added(&harness), 3); - front_to_back_dropdown(&harness).scroll_to_me(); + harness.get_by_role_and_label(Role::Slider, "Front to Back").scroll_to_me(); harness.run_steps(3); - front_to_back_dropdown(&harness).click(); - harness.run_steps(2); - harness.get_by_label("Multiply").click(); + let at = lowest(&harness).center(); + click_at(&mut harness, at); + harness.get_by_role_and_label(Role::ListBoxOption, "Multiply").click(); harness.run_steps(3); let axes = generator(&harness, effect).section.unwrap().axes; @@ -217,30 +225,57 @@ fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { } #[test] -fn the_light_dial_turns_towards_the_pointer() { - let (mut harness, effect) = harness_with(false, json!({"generator": "direction"})); - harness.get_by_role_and_label(Role::Slider, "Horizontal angle").scroll_to_me(); +fn a_curvature_size_column_sets_its_size_alone_in_one_step() { + let (mut harness, effect) = harness(false); + let before = generator(&harness, effect).detail.unwrap().weights; + let history = harness.state().session.history_labels().len(); + harness.get_by_role_and_label(Role::Slider, "Huge").scroll_to_me(); harness.run_steps(3); - let rect = harness.get_by_role_and_label(Role::Slider, "Horizontal angle").rect(); - let left = egui::pos2(rect.left() + 2.0, rect.center().y); - harness.drag_at(left); + let column = harness.get_by_role_and_label(Role::Slider, "Huge").rect(); + let (low, high) = (egui::pos2(column.center().x, column.bottom() - 30.0), egui::pos2(column.center().x, column.top() + 24.0)); + harness.drag_at(low); harness.run_steps(2); - harness.drop_at(left); + harness.hover_at(high); + harness.run_steps(2); + harness.drop_at(high); harness.run_steps(3); - let horizontal = generator(&harness, effect).light.unwrap().horizontal; - assert!(!(1.0..=359.0).contains(&horizontal), "0 is on the left, as in the reference: {horizontal}"); + + let after = generator(&harness, effect).detail.unwrap().weights; + let last = before.len() - 1; + assert!(after[last] > before[last], "dragged up, Huge rose: {} -> {}", before[last], after[last]); + assert_eq!(after[..last], before[..last], "the other sizes kept theirs"); + assert_eq!(harness.state().session.history_labels().len(), history + 1); } #[test] fn restore_defaults_puts_a_light_back_on_its_defaults() { let (mut harness, effect) = harness_with(false, json!({"generator": "direction", "lightHorizontal": 10.0, "highlightLevel": 0.7, "invert": true})); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); - harness.run_steps(3); + click_live(&mut harness, Role::Button, "Restore defaults"); assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Direction)); } +#[test] +fn micro_details_show_their_settings_once_switched_on() { + let (mut harness, effect) = harness_with(false, json!({"generator": "ambientOcclusion"})); + assert_eq!(count(&harness, "AO Radius"), 0, "they wait for Use Micro Details"); + harness.get_by_role_and_label(Role::CheckBox, "Use Micro Details").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Use Micro Details").click(); + harness.run_steps(3); + assert!(generator(&harness, effect).micro.is_some_and(|micro| micro.enabled)); + for label in ["Micro Height", "Micro Normal", "AO Radius", "AO Depth"] { + assert!(count(&harness, label) > 0, "{label}"); + } + assert_eq!(count(&harness, "Curvature Type"), 0, "Ambient Occlusion's micro details have no curvature"); + + let (mut harness, _) = harness_with(false, json!({"generator": "dirt", "microHeight": true})); + harness.get_by_role_and_label(Role::Button, "Micro Details").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Micro Details").click(); + harness.run_steps(3); + assert!(slot_reading(&harness, "Empty").rect().is_positive(), "Micro Height on: its slot, empty"); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -251,7 +286,7 @@ fn generator_panel_snapshots() { harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap(); for section in ["Attributes", "Resolution"] { - harness.get_by_label(section).click(); + harness.get_by_role_and_label(Role::Button, section).click(); harness.run_steps(3); } harness.run_steps(6); @@ -276,66 +311,65 @@ fn generator_panel_snapshots() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn wear_panel_snapshots() { +fn full_set_panel_snapshots() { let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); - for kind in ["edgeWear", "dirt", "fiberGlassEdgeWear"] { - let (mut harness, _) = harness_with(true, json!({"generator": kind})); - harness.run_steps(12); - harness.render().unwrap().save(directory.join(format!("wear-panel-{kind}.png"))).unwrap(); - } -} + let kinds = ["edgeWear", "fiberGlassEdgeWear", "dirt", "direction", "curvature", "ambientOcclusion", "position", "worldSpaceNormals"]; + for kind in kinds { + let (mut harness, _) = harness_with(true, json!({"generator": kind, "seed": 12})); + if kind == "dirt" { + harness.get_by_role_and_label(Role::Button, "Micro Details").click(); + } -#[test] -#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn section_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); - std::fs::create_dir_all(&directory).unwrap(); - for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals", "direction"] { - let (mut harness, _) = harness_with(true, json!({"generator": kind})); - harness.run_steps(12); - harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); + // The orbs render on the preview worker + for _ in 0..40 { + harness.run_steps(4); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-{kind}-{name}.png"))).unwrap(); + } } } #[test] fn use_texture_shows_the_texture_rows_and_its_slot() { let (harness, _) = harness_with(false, json!({"generator": "position"})); - assert_eq!(count(&harness, "Use texture"), 1); - for label in ["Grayscale conversion", "Texture opacity", "Triplanar contrast", "Texture"] { - assert_eq!(count(&harness, label), 0, "{label} waits for Use texture"); + assert_eq!(harness.get_all_by_role_and_label(Role::CheckBox, "Use Texture").count(), 1); + let dropdowns = |harness: &Harness<'_, TextureCraftApp>| harness.get_all_by_role(Role::ComboBox).count(); + let closed = dropdowns(&harness); + for label in ["Texture Opacity", "Texture"] { + assert_eq!(count(&harness, label), 0, "{label} waits for Use Texture"); } let (harness, _) = harness_with(false, json!({"generator": "position", "useTexture": true})); - for label in ["Grayscale conversion", "Texture opacity", "Triplanar", "Triplanar contrast", "Scale"] { - assert_eq!(count(&harness, label), 1, "{label}"); + for label in ["Texture Opacity", "Triplanar", "Scale"] { + assert!(count(&harness, label) > 0, "{label}"); } - assert_eq!(count(&harness, "Texture"), 2, "the Texture section and the Texture slot in Image inputs"); - assert_eq!(count(&harness, "Blending mode"), 4, "the texture's beside the three axes'"); + assert_eq!(count(&harness, "Triplanar Contrast"), 0, "it waits for Triplanar"); + assert!(harness.get_by_role_and_label(Role::ComboBox, "Texture").rect().is_positive(), "the texture's slot in its card"); + assert_eq!(dropdowns(&harness), closed + 3, "the texture's slot, Grayscale Conversion and Blending Mode"); let (harness, _) = harness_with(false, json!({"generator": "dirt"})); - assert_eq!(count(&harness, "Use texture"), 0, "wear generators have no texture"); + assert_eq!(count(&harness, "Use Texture"), 0, "wear generators have no texture"); } #[test] -fn the_texture_slot_reads_a_uniform_value_until_it_is_given_one() { +fn the_texture_slot_takes_a_uniform_value_and_empties_again() { let (mut harness, effect) = harness_with(false, json!({"generator": "ambientOcclusion", "useTexture": true})); - let slot = |harness: &Harness<'_, TextureCraftApp>| { - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Uniform value")).count() - }; - assert_eq!(slot(&harness), 1, "an empty texture slot is a uniform value"); - assert_eq!(count(&harness, "Value"), 1, "with its value slider"); - - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me(); + slot_reading(&harness, "Empty").scroll_to_me(); harness.run_steps(3); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + slot_reading(&harness, "Empty").click(); harness.run_steps(2); - assert_eq!(count(&harness, "Mesh map"), 0, "the texture has no mesh map to go back to"); - // The slot's heading also reads "Uniform value": the menu entry is the button - harness.get_by_role_and_label(Role::Button, "Uniform value").click(); + harness.get_by_role_and_label(Role::ListBoxOption, "Uniform value").click(); harness.run_steps(3); - let texture = generator(&harness, effect).texture.unwrap(); - assert_eq!(texture.source, Some(Source::Uniform([0.0; 3]))); + assert!(matches!(generator(&harness, effect).texture.unwrap().source, Some(Source::Uniform(_)))); + assert!(count(&harness, "Value") > 0, "with its value"); + + click_live(&mut harness, Role::Button, "Clear"); + assert_eq!(generator(&harness, effect).texture.unwrap().source, None); } #[test] @@ -345,7 +379,7 @@ fn texture_panel_snapshots() { std::fs::create_dir_all(&directory).unwrap(); for kind in ["position", "ambientOcclusion"] { let (mut harness, _) = harness_with(true, json!({"generator": kind, "useTexture": true, "textureOpacity": 0.6, "textureBlend": "normal"})); - harness.get_by_label("Use texture").scroll_to_me(); + harness.get_by_role_and_label(Role::CheckBox, "Use Texture").scroll_to_me(); harness.run_steps(12); for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; From b40f743878fc3b79474ba218e8fedde985b5abfc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:32 +0000 Subject: [PATCH 113/153] Generators: the seven new kinds in the picker with their panels, gradient stop places for UV Random Color and picking a point on the mesh --- crates/compose/src/uv_islands.rs | 8 +- .../tests/generator_uv_random_color.rs | 21 +- crates/core/src/layer.rs | 14 +- .../src/layer/uv_random_color_parameters.rs | 60 +++- crates/engine/src/commands.rs | 1 + crates/engine/src/distance_params.rs | 16 +- crates/engine/src/generator_pick.rs | 66 ++++ crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 4 +- crates/engine/src/orb_preview.rs | 13 +- .../tests/it/generator_three_d_distance.rs | 59 +++- crates/ui-egui/src/fill_symmetry_panel.rs | 10 +- crates/ui-egui/src/generator_input_card.rs | 9 +- crates/ui-egui/src/generator_input_slot.rs | 13 +- crates/ui-egui/src/generator_kind_rows.rs | 289 ++++++++++++++++++ crates/ui-egui/src/generator_panel.rs | 20 +- crates/ui-egui/src/generator_params.rs | 85 +++++- crates/ui-egui/src/generator_point_pick.rs | 30 ++ crates/ui-egui/src/generator_section_rows.rs | 16 +- crates/ui-egui/src/generator_wear_rows.rs | 26 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus.rs | 7 + crates/ui-egui/src/properties_popup.rs | 1 + .../ui-egui/src/property_sheet/axis_rows.rs | 9 +- .../src/property_sheet/number_field.rs | 40 ++- .../src/property_sheet/size_columns.rs | 13 +- crates/ui-egui/src/shelf.rs | 3 +- crates/ui-egui/src/viewport.rs | 22 +- crates/ui-egui/tests/it/generator_panel.rs | 106 ++++++- 29 files changed, 904 insertions(+), 60 deletions(-) create mode 100644 crates/engine/src/generator_pick.rs create mode 100644 crates/ui-egui/src/generator_kind_rows.rs create mode 100644 crates/ui-egui/src/generator_point_pick.rs diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 25a23d10..124ece1b 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::sync::Arc; use rayon::prelude::*; -use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters, gradient}; +use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters}; use texturecraft_geom::{NO_TRI, TrianglePartition}; use texturecraft_texel::linear_to_srgb; use texturecraft_texel::noise::cell_hash; @@ -18,7 +18,9 @@ static CACHE: FieldCache = FieldCache::new(); /// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(random.custom_gradient)]; - settings.extend(random.gradient.iter().flat_map(|color| color.map(f32::to_bits))); + settings.push(random.used_colors().len() as u32); + settings.extend(random.used_colors().iter().flat_map(|color| color.map(f32::to_bits))); + settings.extend(random.positions.iter().map(|position| position.to_bits())); CACHE.get_or_build(inp, &[], settings, |_| { let island_values = island_values(inp, |island| random_gray(random, seed, island)); let gbuf = inp.gbuf; @@ -43,7 +45,7 @@ fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> HashMap f32 { let island = island as i32; let color = if random.custom_gradient { - gradient(&random.gradient, cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) + random.at(cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) } else { std::array::from_fn(|channel| cell_hash(island, channel as i32 + 1, 0, seed)) }; diff --git a/crates/compose/tests/generator_uv_random_color.rs b/crates/compose/tests/generator_uv_random_color.rs index 529bc354..a546c627 100644 --- a/crates/compose/tests/generator_uv_random_color.rs +++ b/crates/compose/tests/generator_uv_random_color.rs @@ -97,6 +97,25 @@ fn a_one_color_gradient_colors_every_island_alike() { let mut fixture = fixture(); let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); - let values = mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]] }, 0, &at); + let values = + mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]], ..UvRandomColorParameters::default() }, 0, &at); assert!(values.iter().all(|value| (value - 0.2).abs() < 1e-5), "the mean of its channels"); } + +#[test] +fn moving_a_gradient_stop_brightens_the_islands() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + let black_to_white = |positions: Vec| UvRandomColorParameters { + custom_gradient: true, + gradient: vec![[0.0; 3], [1.0; 3]], + positions, + ..UvRandomColorParameters::default() + }; + + let even = mask(&mut fixture, black_to_white(Vec::new()), 0, &at); + let white_early = mask(&mut fixture, black_to_white(vec![0.0, 0.2]), 0, &at); + let mean = |values: &[f32]| values.iter().sum::() / values.len().max(1) as f32; + assert!(mean(&white_early) > mean(&even), "white reached sooner along the gradient: brighter islands"); + assert!(white_early.iter().zip(&even).all(|(early, even)| early >= even), "no island darker"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ccbf8ed9..bc82c7b7 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1044,19 +1044,9 @@ impl GeneratorKind { } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the newest kinds wait for their panels) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks) pub fn in_picker(self) -> bool { - !matches!( - self, - GeneratorKind::ThinAreas - | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor - | GeneratorKind::UvChecker - ) + self != GeneratorKind::ThinAreas } /// Whether the kind's result depends on its seed diff --git a/crates/core/src/layer/uv_random_color_parameters.rs b/crates/core/src/layer/uv_random_color_parameters.rs index 156a1be0..07b73e13 100644 --- a/crates/core/src/layer/uv_random_color_parameters.rs +++ b/crates/core/src/layer/uv_random_color_parameters.rs @@ -6,24 +6,74 @@ use serde::{Deserialize, Serialize}; pub struct UvRandomColorParameters { /// Pick each island's color along [`UvRandomColorParameters::gradient`] instead of at random pub custom_gradient: bool, - /// The gradient's colors, evenly spaced (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) + /// The gradient's colors (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) pub gradient: Vec<[f32; 3]>, + /// Each color's place on the gradient (0..1); colors past the end are evenly spaced (projects saved before have none) + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub positions: Vec, + /// How many of the colors the gradient uses (all of them where None): the rest are kept for when the count grows again + #[serde(default, skip_serializing_if = "Option::is_none")] + pub quantity: Option, } impl UvRandomColorParameters { pub const MAX_GRADIENT_COLORS: usize = 16; - /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one + /// The fewest colors the gradient's count goes down to + pub const MIN_QUANTITY: u8 = 2; + + /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one; places into 0..1, one per color at most pub fn clamped(self) -> UvRandomColorParameters { let unit = |value: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; let gradient: Vec<[f32; 3]> = self.gradient.into_iter().take(UvRandomColorParameters::MAX_GRADIENT_COLORS).map(|color| color.map(unit)).collect(); - UvRandomColorParameters { gradient: if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }, ..self } + let gradient = if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }; + let positions = self.positions.into_iter().take(gradient.len()).map(unit).collect(); + let quantity = self.quantity.map(|count| count.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8)); + UvRandomColorParameters { gradient, positions, quantity, ..self } + } + + /// The colors the gradient uses: the first [`UvRandomColorParameters::quantity`] of them (all of them where it has none) + pub fn used_colors(&self) -> &[[f32; 3]] { + let used = self.quantity.map_or(self.gradient.len(), usize::from).min(self.gradient.len()); + self.gradient.get(..used).unwrap_or(&self.gradient) + } + + /// Each used color's place on the gradient, evenly spaced where it has none + pub fn used_positions(&self) -> Vec { + let used = self.used_colors().len(); + let last = used.saturating_sub(1).max(1) as f32; + (0..used).map(|index| self.positions.get(index).copied().unwrap_or(index as f32 / last)).collect() + } + + /// The gradient's color at `t` (linear blend) + pub fn at(&self, t: f32) -> Option<[f32; 3]> { + let colors = self.used_colors(); + + // An evenly spaced gradient (projects saved before) takes the path it took then, so it renders bit for bit as before + if self.positions.is_empty() { super::gradient(colors, t) } else { crate::gradient_input::ramp(colors, &self.positions, true, t) } + } + + /// Use the first `wanted` colors: an evenly spaced gradient keeps its places from now on, and each added color starts at 1 as the gradient's color there + pub fn set_quantity(&mut self, wanted: u8) { + let wanted = wanted.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8); + // The used colors without a place keep the even place the gradient gave them; hidden colors keep theirs + let even = self.used_positions(); + let placed = self.positions.len(); + self.positions.extend(even.into_iter().skip(placed)); + let fill = self.at(1.0).unwrap_or([1.0; 3]); + let wanted_len = usize::from(wanted); + if self.gradient.len() < wanted_len { + self.gradient.resize(wanted_len, fill); + } + if self.positions.len() < wanted_len { + self.positions.resize(wanted_len, 1.0); + } + self.quantity = Some(wanted); } } impl Default for UvRandomColorParameters { - /// Random colors; the gradient black to white fn default() -> UvRandomColorParameters { - UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]] } + UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]], positions: Vec::new(), quantity: None } } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..49cead62 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -117,6 +117,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::generator_pick::specs()); v.extend(crate::mask_export::specs()); v.extend(crate::add_mask_cmds::specs()); v.extend(crate::color_selection_cmds::specs()); diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 7b620be0..172a1cf2 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -23,7 +23,7 @@ pub const DRIPPING_RUST_KEYS: [&str; 7] = ["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"]; /// The UV Random Color controls (it also takes the seed) -pub const UV_RANDOM_COLOR_KEYS: [&str; 2] = ["colorSourceMode", "gradientColors"]; +pub const UV_RANDOM_COLOR_KEYS: [&str; 4] = ["colorSourceMode", "gradientColors", "gradientPositions", "gradientQuantity"]; /// The UV Checker controls (it also takes the seed) pub const UV_CHECKER_KEYS: [&str; 6] = ["checkerColorMode", "checkerColor", "checkerGridTile", "checkerGridOpacity", "uvBordersColor", "uvBordersWidth"]; @@ -185,6 +185,20 @@ fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator let invalid = || bad(command, "`gradientColors` takes 1 to 16 colors, each [r, g, b] or \"#rrggbb\""); let items = value.as_array().filter(|items| (1..=UvRandomColorParameters::MAX_GRADIENT_COLORS).contains(&items.len())).ok_or_else(invalid)?; random.gradient = items.iter().map(|item| color_of(item).ok_or_else(invalid)).collect::>()?; + + // The colors given are the whole gradient: a count after them hides some again + random.quantity = None; + } + if let Some(value) = params.get("gradientPositions") { + let invalid = || bad(command, "`gradientPositions` must be numbers in 0..1, at most one per color"); + let places = value.as_array().filter(|places| places.len() <= random.gradient.len()).ok_or_else(invalid)?; + random.positions = places.iter().map(|place| place.as_f64().map(|place| place as f32).ok_or_else(invalid)).collect::>()?; + } + if params.get("gradientQuantity").is_some() { + let range = UvRandomColorParameters::MIN_QUANTITY..=UvRandomColorParameters::MAX_GRADIENT_COLORS as u8; + let wanted = u64p(params, "gradientQuantity").and_then(|count| u8::try_from(count).ok()).filter(|count| range.contains(count)); + let wanted = wanted.ok_or_else(|| bad(command, format!("`gradientQuantity` must be a whole number from {} to {}", range.start(), range.end())))?; + random.set_quantity(wanted); } generator.controls = Some(Box::new(KindControls::UvRandomColor(random.clamped()))); Ok(()) diff --git a/crates/engine/src/generator_pick.rs b/crates/engine/src/generator_pick.rs new file mode 100644 index 00000000..b6195451 --- /dev/null +++ b/crates/engine/src/generator_pick.rs @@ -0,0 +1,66 @@ +//! `effect.generator.pickPoint`: a 3D Distance or 3D Linear Gradient point set from where the mesh is under a viewport point + +use serde_json::{Value, json}; +use texturecraft_core::{EffectKind, GeneratorKind, LayerId}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::commands::{CommandSpec, bad, f32p, has_layer, strp, u64p}; +use crate::tool_cmds::viewport_of; +use crate::{Result, Session, cmd}; + +const CMD: &str = "effect.generator.pickPoint"; + +/// The least extent the mesh's bounds count with, so a flat mesh still places a point (the compositor's own floor) +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + +pub fn specs() -> Vec { + vec![cmd!( + "effect.generator.pickPoint", + "Pick generator point on mesh", + [], + None, + "{effect, point?: distance|start|end (default distance on 3dDistance, start on 3dLinearGradient), x?, y?: viewport pixels (default its centre), viewport?: [w, h]} sets a 3D Distance or 3D Linear Gradient point to the mesh under that pixel, across the mesh's bounds as the generator reads it; returns the point", + has_layer, + pick_point + )] +} + +fn pick_point(session: &mut Session, params: &Value) -> Result { + let effect = u64p(params, "effect").ok_or_else(|| bad(CMD, "`effect` is required"))?; + let kind = match session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => generator.kind, + Some(_) => return Err(bad(CMD, format!("effect {effect} is not a generator"))), + None => return Err(bad(CMD, format!("no effect {effect}"))), + }; + let point = strp(params, "point").map(str::to_ascii_lowercase); + let key = match (kind, point.as_deref()) { + (GeneratorKind::ThreeDDistance, None | Some("distance")) => "distance", + (GeneratorKind::ThreeDLinearGradient, None | Some("start")) => "gradientStart", + (GeneratorKind::ThreeDLinearGradient, Some("end")) => "gradientEnd", + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, Some(other)) => { + return Err(bad(CMD, format!("{} has no point `{other}`", kind.label()))); + } + _ => return Err(bad(CMD, format!("{} has no point to pick: only 3D Distance and 3D Linear Gradient have one", kind.label()))), + }; + + let viewport = viewport_of(session, params); + let screen = match (f32p(params, "x"), f32p(params, "y")) { + (Some(x), Some(y)) => Vec2::new(x, y), + _ => viewport * 0.5, + }; + let hit = session.pick(screen, viewport).ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; + let picked = across_bounds(hit.pos, session.mesh.bounds()).to_array().map(|coordinate| coordinate.clamp(0.0, 1.0)); + + let edit = match key { + "distance" => json!({"effect": effect, "distanceX": picked[0], "distanceY": picked[1], "distanceZ": picked[2]}), + _ => json!({"effect": effect, key: picked}), + }; + crate::mask_cmds::set(session, &edit)?; + Ok(json!({"effect": effect, "point": picked})) +} + +/// `position` across `bounds` as the 3D generators read the mesh: scaled evenly by the longest side, centred on 0.5 +pub fn across_bounds(position: Vec3, (low, high): (Vec3, Vec3)) -> Vec3 { + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + (position - (low + high) * 0.5) / longest + Vec3::splat(0.5) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 336ba602..82d395ce 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod filter_about; pub mod filter_lib; pub mod folder_cmds; mod frame_target; +pub mod generator_pick; pub mod id_mask_view; pub mod inspect; pub mod instance_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 77341832..e7ef1e7a 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...], gradientPositions?: [0..1 per color], gradientQuantity?: 2..16 (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -1016,7 +1016,7 @@ fn histogram(s: &mut Session, p: &Value) -> Result { } /// Edit visibility, blending, name, effect parameters, or a filter's type -fn set(session: &mut Session, params: &Value) -> Result { +pub(crate) fn set(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.set"; let effect = effect_id(session, params, CMD)?; let blend = blend_param(CMD, params, "blend")?; diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index 4d5d3c70..6d03ef36 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -4,7 +4,10 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, LayerId, MaskBackground}; +use texturecraft_core::{ + BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, KindControls, LayerId, MaskBackground, Procedural, + ProceduralKind, Source, +}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::primitives; use texturecraft_texel::TILE; @@ -86,7 +89,13 @@ impl OrbPreview { /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { - self.generator_of(Generator::new(kind), size) + let mut generator = Generator::new(kind); + + // Grayscale Conversion grays the image it is given: its picture grays clouds, as it starts with none + if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut() { + grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); + } + self.generator_of(generator, size) } /// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone) diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index c4f7b3ed..735bef45 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -144,12 +144,46 @@ fn uv_random_color_takes_its_mode_and_gradient() { let params = json!({"generator": "UV Random Color", "colorSourceMode": "customGradient", "gradientColors": [[2.0, 0.5, 0.0], "#000000"]}); let effect = add(&mut session, params); - let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]] }; + let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]], ..UvRandomColorParameters::default() }; assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvRandomColor(expected)), "colors stay within 0..1"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": []})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "colorSourceMode": "fancy"})).is_err()); } +#[test] +fn uv_random_color_gradient_takes_places_and_a_count() { + let mut session = session(); + let params = json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]}); + let effect = add(&mut session, params); + let random = |session: &Session| match generator(session, effect).kind_controls() { + Some(KindControls::UvRandomColor(random)) => random, + other => panic!("not UV Random Color controls: {other:?}"), + }; + + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientPositions": [0.25, 0.75]})).unwrap(); + assert_eq!(random(&session).at(0.5), Some([0.5; 3]), "halfway between the two places"); + assert_eq!(random(&session).at(0.1), Some([0.0; 3]), "before the first place: the first color"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 3})).unwrap(); + assert_eq!(random(&session).used_colors().len(), 3); + assert_eq!(random(&session).used_positions(), vec![0.25, 0.75, 1.0], "an added color starts at the end"); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0]]})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 2})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 3})).unwrap(); + assert_eq!(random(&session).used_colors()[2], [1.0, 0.0, 0.0], "a hidden color comes back as it was"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 17})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientPositions": [0.0, 0.1, 0.2, 0.3]})).is_err()); +} + +#[test] +fn uv_random_color_saved_without_places_loads_evenly_spaced() { + let saved: UvRandomColorParameters = + serde_json::from_value(json!({"customGradient": true, "gradient": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]})).unwrap(); + assert_eq!(saved.used_positions(), vec![0.0, 0.5, 1.0]); + assert_eq!(saved.at(0.5), Some([1.0; 3])); +} + #[test] fn uv_checker_takes_its_controls() { let mut session = session(); @@ -162,3 +196,26 @@ fn uv_checker_takes_its_controls() { assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvChecker(expected)), "the grid tile stops at 24"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "checkerColorMode": "plaid"})).is_err()); } + +#[test] +fn picking_on_the_mesh_sets_the_point() { + let mut session = session(); + let distance = add(&mut session, json!({"generator": "3dDistance", "distanceX": 0.0, "distanceY": 0.0, "distanceZ": 0.0})); + let picked = execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance})).unwrap(); + let point = generator(&session, distance).distance_controls().unwrap().point; + assert_eq!(json!(point), picked["point"], "the point is where the mesh is under the viewport's centre"); + assert_ne!(point, [0.0; 3]); + + let gradient = add(&mut session, json!({"generator": "3dLinearGradient"})); + let before = generator(&session, gradient).linear_gradient_controls().unwrap(); + execute(&mut session, "effect.generator.pickPoint", &json!({"effect": gradient, "point": "end"})).unwrap(); + let after = generator(&session, gradient).linear_gradient_controls().unwrap(); + assert_eq!(after.start, before.start, "picking the end leaves the start"); + assert_eq!(json!(after.end), picked["point"], "the same pixel gives the same point"); + + let missed = json!({"effect": distance, "x": 0.0, "y": 0.0, "viewport": [512, 512]}); + assert!(execute(&mut session, "effect.generator.pickPoint", &missed).is_err(), "a corner off the mesh picks nothing"); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance, "point": "end"})).is_err()); + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": curvature})).is_err()); +} diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs index b306c05e..a2796f79 100644 --- a/crates/ui-egui/src/fill_symmetry_panel.rs +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -91,7 +91,15 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr let mut sliders = [ StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "", dial: false }, - StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°", dial: false }, + StackSlider { + label: tr("Angle span"), + value: &mut span_value, + range: FillSymmetry::SPANS, + typed: FillSymmetry::SPANS, + decimals: 0, + suffix: "°", + dial: false, + }, ]; let [count_edit, span_edit] = sheet.picture_sliders(&picture, &mut sliders); diff --git a/crates/ui-egui/src/generator_input_card.rs b/crates/ui-egui/src/generator_input_card.rs index 2cc9c41f..b63012ce 100644 --- a/crates/ui-egui/src/generator_input_card.rs +++ b/crates/ui-egui/src/generator_input_card.rs @@ -18,7 +18,14 @@ use crate::theme::Tokens; const GLYPH_SIZE: f32 = 12.0; /// The slot of input `slot` of generator effect `id` on `layer`, holding `source`: a card of its own, or a row of the card open now when `in_card` -pub(crate) fn input_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), slot: GeneratorInputSlot, source: Option<&Source>, in_card: bool) { +pub(crate) fn input_card( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + (layer, id): (LayerId, u64), + slot: GeneratorInputSlot, + source: Option<&Source>, + in_card: bool, +) { let tokens = Tokens::get(sheet.ui.ctx()); let input = slot.id(); let line = match (source, slot) { diff --git a/crates/ui-egui/src/generator_input_slot.rs b/crates/ui-egui/src/generator_input_slot.rs index 0e145a6f..4027cb4f 100644 --- a/crates/ui-egui/src/generator_input_slot.rs +++ b/crates/ui-egui/src/generator_input_slot.rs @@ -1,6 +1,6 @@ //! What one image input of a generator replaces or holds -use texturecraft_engine::core::{BakedMap, Generator, Source}; +use texturecraft_engine::core::{BakedMap, Generator, KindControls, Source}; use crate::i18n::{baked_map_label, tr}; @@ -12,6 +12,9 @@ pub(crate) enum GeneratorInputSlot { Grunge, MicroHeight, MicroNormal, + + /// Grayscale Conversion's image + Image, } impl GeneratorInputSlot { @@ -23,6 +26,7 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => "grunge", GeneratorInputSlot::MicroHeight => texturecraft_engine::micro_params::MICRO_HEIGHT_INPUT, GeneratorInputSlot::MicroNormal => texturecraft_engine::micro_params::MICRO_NORMAL_INPUT, + GeneratorInputSlot::Image => "image", } } @@ -33,6 +37,7 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => tr("Custom Grunge"), GeneratorInputSlot::MicroHeight => tr("Micro Height"), GeneratorInputSlot::MicroNormal => tr("Micro Normal"), + GeneratorInputSlot::Image => tr("Input Image"), } } @@ -41,7 +46,7 @@ impl GeneratorInputSlot { match self { GeneratorInputSlot::Map(map) => map.neutral()[0], GeneratorInputSlot::MicroHeight | GeneratorInputSlot::MicroNormal => 0.5, - GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge => 0.0, + GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge | GeneratorInputSlot::Image => 0.0, } } @@ -58,6 +63,10 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => generator.grunge.as_ref(), GeneratorInputSlot::MicroHeight => generator.micro.as_ref().and_then(|micro| micro.height_source.as_ref()), GeneratorInputSlot::MicroNormal => generator.micro.as_ref().and_then(|micro| micro.normal_source.as_ref()), + GeneratorInputSlot::Image => match generator.controls.as_deref() { + Some(KindControls::Grayscale(grayscale)) => grayscale.source.as_ref(), + _ => None, + }, } } } diff --git a/crates/ui-egui/src/generator_kind_rows.rs b/crates/ui-egui/src/generator_kind_rows.rs new file mode 100644 index 00000000..8b3e8960 --- /dev/null +++ b/crates/ui-egui/src/generator_kind_rows.rs @@ -0,0 +1,289 @@ +//! The Parameters rows of the kinds with only their own controls: 3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion, Dripping Rust, UV Random Color and UV Checker + +use egui::{Painter, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, Generator, GeneratorGrayscale, GrayscaleConversionParameters, KindControls, + LinearGradientParameters, UvCheckerParameters, UvRandomColorParameters, +}; + +use crate::TextureCraftApp; +use crate::fill_material_panel::take_color_pick; +use crate::generator_params::{DRIPS_AXES, kind_params, merged}; +use crate::generator_point_pick::PointPick; +use crate::i18n::{tr, trf}; +use crate::property_sheet::{NumberField, PropertySheet, StackSlider}; +use crate::theme::AXIS_COLORS; + +/// A 0..1 setting in the stack beside the preview +fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } +} + +/// A whole-number setting in the stack beside the preview +fn stacked_whole<'a>(label: &'a str, value: &'a mut f32, range: std::ops::RangeInclusive) -> StackSlider<'a> { + StackSlider { label, value, range: range.clone(), typed: range, decimals: 0, suffix: "", dial: false } +} + +/// The first edit of a stack beside the preview +fn first_edit(edits: [Option; N]) -> Option { + edits.into_iter().flatten().next() +} + +/// The rows of generator effect `id`, whose own controls are `controls`; `picture` draws the preview +pub(crate) fn kind_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + generator: &Generator, + controls: KindControls, + picture: &dyn Fn(&Painter, Rect), +) { + if generator.kind.includes_randomness() { + let mut seed = generator.seed; + if sheet.seed(tr("Seed"), &mut seed) { + app.run("effect.set", json!({"effect": id, "seed": seed})); + } + } + + // UV Random Color and UV Checker make colors: Invert is the reference's on the grayscale kinds only + if !matches!(controls, KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) { + let mut invert = generator.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + } + + let edit = match controls { + KindControls::Distance(distance) => distance_rows(sheet, id, distance, picture), + KindControls::LinearGradient(gradient) => linear_gradient_rows(sheet, id, gradient, picture), + KindControls::BorderDistance(border) => border_rows(sheet, border, picture), + KindControls::Grayscale(grayscale) => grayscale_rows(sheet, grayscale, picture), + KindControls::DrippingRust(rust) => rust_rows(sheet, rust, picture), + KindControls::UvRandomColor(random) => random_color_rows(app, sheet, id, random), + KindControls::UvChecker(checker) => checker_rows(app, sheet, checker, picture), + }; + if let Some((merge, edited)) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), edited)); + } +} + +/// An edit: whether it continues the last undo step, and the controls to send +type KindEdit = Option<(bool, Value)>; + +/// The controls `controls` to send when `merge` says one was edited +fn sent(merge: Option, controls: KindControls) -> KindEdit { + merge.map(|merge| (merge, kind_params(&controls))) +} + +/// A point's X, Y and Z (across the mesh's evenly scaled bounds) with its pick-on-mesh button; returns its edit +fn point_row(sheet: &mut PropertySheet<'_>, label: &str, point: &mut [f32; 3], pick: PointPick) -> Option { + let mut fields: Vec = ["X", "Y", "Z"] + .into_iter() + .zip(AXIS_COLORS) + .zip(point.iter()) + .map(|((tag, color), value)| NumberField { tag, tag_color: Some(color), value: *value, speed: POINT_DRAG_SPEED, decimals: 2, suffix: "" }) + .collect(); + let ctx = sheet.ui.ctx().clone(); + let armed = crate::generator_point_pick::armed(&ctx) == Some(pick); + let (edited, clicked) = sheet.point_fields(label, &mut fields, armed); + if clicked { + crate::generator_point_pick::toggle(&ctx, pick); + } + let (index, merge) = edited?; + let (field, coordinate) = (fields.get(index)?, point.get_mut(index)?); + *coordinate = field.value.clamp(0.0, 1.0); + Some(merge) +} + +/// Change of a point's coordinate per pixel dragged +const POINT_DRAG_SPEED: f32 = 0.005; + +/// 3D Distance: Radius, Offset and Contrast beside the preview, then its point +fn distance_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: DistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let radius = StackSlider { + label: tr("Radius"), + value: &mut edited.radius, + range: DistanceParameters::RADIUS_RANGE, + typed: DistanceParameters::RADIUS_RANGE, + decimals: 2, + suffix: "", + dial: false, + }; + let mut stack = [radius, stacked(tr("Offset"), &mut edited.offset), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(point_row(sheet, tr("3D Position"), &mut edited.point, PointPick { effect: id, point: "distance" })); + sent(edit, KindControls::Distance(edited)) +} + +/// 3D Linear Gradient: Balance and Contrast beside the preview, then its start and end +fn linear_gradient_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: LinearGradientParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = [stacked(tr("Balance"), &mut edited.balance), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(point_row(sheet, tr("3D Position Start"), &mut edited.start, PointPick { effect: id, point: "start" })); + edit = edit.or(point_row(sheet, tr("3D Position End"), &mut edited.end, PointPick { effect: id, point: "end" })); + sent(edit, KindControls::LinearGradient(edited)) +} + +/// UV Border Distance: Distance, Smoothness and Balance beside the preview, then Contrast +fn border_rows(sheet: &mut PropertySheet<'_>, shown: BorderDistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = + [stacked(tr("Distance"), &mut edited.distance), stacked(tr("Smoothness"), &mut edited.smoothness), stacked(tr("Balance"), &mut edited.balance)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(sheet.slider(tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + sent(edit, KindControls::BorderDistance(edited)) +} + +/// Grayscale Conversion: its type, Balance, Contrast and Tile beside the preview, then Rotation and Safe Rotation (its image is in Image inputs) +fn grayscale_rows(sheet: &mut PropertySheet<'_>, shown: GrayscaleConversionParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut edit = None; + let name = |grayscale: GeneratorGrayscale| tr(grayscale.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Grayscale Type"), edited.grayscale, &GeneratorGrayscale::ALL, name, None) { + edited.grayscale = picked; + edit = Some(false); + } + let mut stack = [ + stacked(tr("Balance"), &mut edited.balance), + stacked(tr("Contrast"), &mut edited.contrast), + stacked_whole(tr("Tile"), &mut edited.tile, GrayscaleConversionParameters::TILE_RANGE), + ]; + edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); + edited.tile = edited.tile.round(); + edit = edit.or(sheet.angle(tr("Rotation"), &mut edited.rotation, 0.0..=360.0)); + if sheet.toggle(tr("Safe Rotation"), &mut edited.safe_rotation) { + edit = Some(false); + } + sent(edit, KindControls::Grayscale(edited)) +} + +/// Dripping Rust: Rust Spreading, Rust Contrast and Spreading Smoothness beside the preview, then the drips and the axis they run along +fn rust_rows(sheet: &mut PropertySheet<'_>, shown: DrippingRustParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = [ + stacked(tr("Rust Spreading"), &mut edited.spreading), + stacked(tr("Rust Contrast"), &mut edited.contrast), + stacked(tr("Spreading Smoothness"), &mut edited.spreading_smoothness), + ]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(sheet.slider(tr("Drips Intensity"), &mut edited.drips_intensity, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("Drips Smoothness"), &mut edited.drips_smoothness, 0.0..=1.0, 2)); + let mut samples = edited.drips_samples as f32; + if let Some(merge) = sheet.slider(tr("Drips Samples Amount"), &mut samples, 0.0..=DrippingRustParameters::MAX_SAMPLES as f32, 0) { + edited.drips_samples = samples.round() as u32; + edit = edit.or(Some(merge)); + } + let axes = [tr("X - Red Channel"), tr("Y - Green Channel"), tr("Z - Blue Channel")]; + let name = |axis: u8| axes.get(usize::from(axis)).copied().unwrap_or_default().to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Position Axis"), edited.axis, &[0, 1, 2], name, None) { + edited.axis = picked; + edit = Some(false); + } + debug_assert_eq!(DRIPS_AXES.len(), axes.len()); + sent(edit, KindControls::DrippingRust(edited)) +} + +/// UV Random Color: where its colors come from; a custom gradient shows the gradient editor (as the Gradient filter's) +fn random_color_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, shown: UvRandomColorParameters) -> KindEdit { + let mut edited = shown.clone(); + let mode = usize::from(edited.custom_gradient); + if let Some(picked) = sheet.switch(tr("Color Source Mode"), &[tr("Random"), tr("Custom Gradient")], mode) { + edited.custom_gradient = picked == 1; + return sent(Some(false), KindControls::UvRandomColor(edited)); + } + if !edited.custom_gradient { + return None; + } + + let used = shown.used_colors().to_vec(); + let mut places = shown.used_positions(); + if let Some(drag) = sheet.gradient_ramp(&used, &places, &|t| shown.at(t).unwrap_or([0.0; 3])) { + if let Some(place) = places.get_mut(drag.index) { + *place = drag.position; + } + return Some((drag.merge, gradient_places(&shown, &places))); + } + + let mut quantity = used.len() as f32; + let range = f32::from(UvRandomColorParameters::MIN_QUANTITY)..=UvRandomColorParameters::MAX_GRADIENT_COLORS as f32; + let slid = sheet.slider(tr("Color Quantity"), &mut quantity, range, 0).is_some(); + + // A press's first whole-number change starts its undo step: changes that round to the count it has apply nothing + let press = sheet.ui.make_persistent_id(("uv_random_color_quantity", id)); + let quantity = quantity.round(); + if let Some(merge) = crate::widgets::press_edit(sheet.ui, press, slid && quantity as usize != used.len()) { + return Some((merge, json!({"gradientQuantity": quantity}))); + } + + let mut edit = None; + for (index, color) in used.iter().enumerate() { + let label = trf("Color {number}", &[("number", &(index + 1))]); + let mut place = places.get(index).copied().unwrap_or(0.0); + let (pick, moved) = sheet.color_stop(&label, *color, &mut place, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + if let Some(slot) = edited.gradient.get_mut(index) { + *slot = picked; + } + edit = Some((pick.merge, gradient_colors(&edited))); + } + if let Some(merge) = moved { + if let Some(slot) = places.get_mut(index) { + *slot = place; + } + edit = Some((merge, gradient_places(&shown, &places))); + } + } + edit +} + +/// The colors of `random` to send: all of them, then its count again (the colors reset it) +fn gradient_colors(random: &UvRandomColorParameters) -> Value { + let mut params = json!({"gradientColors": random.gradient}); + if let Some(quantity) = random.quantity { + params["gradientQuantity"] = json!(quantity); + } + params +} + +/// The places to send: `used` (the used colors' places) and the hidden colors' own +fn gradient_places(random: &UvRandomColorParameters, used: &[f32]) -> Value { + let hidden = random.positions.iter().skip(used.len()).copied(); + json!({"gradientPositions": used.iter().copied().chain(hidden).collect::>()}) +} + +/// UV Checker: its color mode with the uniform color, Checker Grid Tile, Checker Grid Opacity and UV Borders Width beside the preview, then UV Borders Color +fn checker_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, shown: UvCheckerParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut edit = None; + if let Some(picked) = sheet.switch(tr("Checker Color Mode"), &[tr("Uniform"), tr("Random")], usize::from(edited.random_colors)) { + edited.random_colors = picked == 1; + edit = Some(false); + } + if !edited.random_colors { + let pick = sheet.color_bar_led(tr("Checker Color"), edited.checker_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + edited.checker_color = picked; + edit = Some(pick.merge); + } + } + + let mut tile = edited.grid_tile as f32; + let tiles = *UvCheckerParameters::GRID_TILE_RANGE.start() as f32..=*UvCheckerParameters::GRID_TILE_RANGE.end() as f32; + let mut stack = [ + stacked_whole(tr("Checker Grid Tile"), &mut tile, tiles), + stacked(tr("Checker Grid Opacity"), &mut edited.grid_opacity), + stacked(tr("UV Borders Width"), &mut edited.border_width), + ]; + edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); + edited.grid_tile = tile.round() as u32; + + let pick = sheet.color_bar_led(tr("UV Borders Color"), edited.border_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + edited.border_color = picked; + edit = Some(pick.merge); + } + sent(edit, KindControls::UvChecker(edited)) +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 98d060ee..4f6661da 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -2,7 +2,9 @@ use egui::{Painter, Rect, TextureHandle}; use serde_json::json; -use texturecraft_engine::core::{CookResolution, Generator, GeneratorKind, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters}; +use texturecraft_engine::core::{ + CookResolution, Generator, GeneratorKind, KindControls, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters, +}; use crate::TextureCraftApp; use crate::fill_material_panel::{band_size, texture_set_size}; @@ -39,10 +41,14 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, parameters(app, sheet, (layer, id), generator); } - let inputs = generator.inputs_in_use(); - if !inputs.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&inputs.len().to_string())).open { - for map in inputs { - let slot = GeneratorInputSlot::Map(*map); + // The kinds with only their own controls show the images the reference lets them take: Grayscale Conversion's own + let slots: Vec = match generator.kind_controls() { + Some(KindControls::Grayscale(_)) => vec![GeneratorInputSlot::Image], + Some(_) => Vec::new(), + None => generator.inputs_in_use().iter().map(|map| GeneratorInputSlot::Map(*map)).collect(), + }; + if !slots.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&slots.len().to_string())).open { + for slot in slots { input_card(app, sheet, (layer, id), slot, slot.source(generator), false); } } @@ -108,6 +114,10 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, let texture = texture.or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); + if let Some(controls) = generator.kind_controls() { + crate::generator_kind_rows::kind_rows(app, sheet, id, generator, controls, &picture); + return; + } if let Some(defaults) = WearParameters::defaults(kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), &picture); diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs index 96fc1980..00fd88d2 100644 --- a/crates/ui-egui/src/generator_params.rs +++ b/crates/ui-egui/src/generator_params.rs @@ -1,7 +1,7 @@ //! The `effect.set` keys of a generator's controls, as its panel sends them use serde_json::{Value, json}; -use texturecraft_engine::core::{Generator, GeneratorKind, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; +use texturecraft_engine::core::{Generator, GeneratorKind, KindControls, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; use texturecraft_engine::mask_cmds::{section_key_applies, wear_key_applies}; use texturecraft_engine::micro_params::micro_key_applies; @@ -81,6 +81,73 @@ pub(crate) fn light_params(light: &LightParameters) -> Value { }) } +/// Every control of a kind with only its own controls, set to `controls` (Grayscale Conversion's image is its `image` input, kept apart) +pub(crate) fn kind_params(controls: &KindControls) -> Value { + match controls { + KindControls::Distance(distance) => json!({ + "distanceX": distance.point[0], + "distanceY": distance.point[1], + "distanceZ": distance.point[2], + "distanceRadius": distance.radius, + "distanceOffset": distance.offset, + "distanceContrast": distance.contrast, + }), + KindControls::LinearGradient(gradient) => json!({ + "gradientStart": gradient.start, + "gradientEnd": gradient.end, + "gradientBalance": gradient.balance, + "gradientContrast": gradient.contrast, + }), + KindControls::BorderDistance(border) => json!({ + "borderDistance": border.distance, + "borderSmoothness": border.smoothness, + "borderBalance": border.balance, + "borderContrast": border.contrast, + }), + KindControls::Grayscale(grayscale) => json!({ + "grayscaleType": grayscale.grayscale.id(), + "grayscaleBalance": grayscale.balance, + "grayscaleContrast": grayscale.contrast, + "grayscaleTile": grayscale.tile, + "grayscaleRotation": grayscale.rotation, + "grayscaleSafeRotation": grayscale.safe_rotation, + }), + KindControls::DrippingRust(rust) => json!({ + "rustSpreading": rust.spreading, + "rustContrast": rust.contrast, + "spreadingSmoothness": rust.spreading_smoothness, + "dripsIntensity": rust.drips_intensity, + "dripsSmoothness": rust.drips_smoothness, + "dripsSamples": rust.drips_samples, + "dripsAxis": DRIPS_AXES.get(usize::from(rust.axis)).copied().unwrap_or("y"), + }), + KindControls::UvRandomColor(random) => { + let mut params = json!({ + "colorSourceMode": if random.custom_gradient { "customGradient" } else { "random" }, + "gradientColors": random.gradient, + "gradientPositions": random.positions, + }); + + // The colors reset the count to all of them: one kept hides the rest again + if let Some(quantity) = random.quantity { + params["gradientQuantity"] = json!(quantity); + } + params + } + KindControls::UvChecker(checker) => json!({ + "checkerColorMode": if checker.random_colors { "random" } else { "uniform" }, + "checkerColor": checker.checker_color, + "checkerGridTile": checker.grid_tile, + "checkerGridOpacity": checker.grid_opacity, + "uvBordersColor": checker.border_color, + "uvBordersWidth": checker.border_width, + }), + } +} + +/// Dripping Rust's `dripsAxis` names, by axis +pub(crate) const DRIPS_AXES: [&str; 3] = ["x", "y", "z"]; + /// Every micro details control a generator of `kind` has, set to `micro` (its images are the `microHeight` and `microNormal` inputs) pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { let mut params = json!({ @@ -111,6 +178,9 @@ pub(crate) fn defaults_of(id: u64, generator: &Generator) -> Value { "customResolution": defaults.resolution.custom, "resolutionFactor": defaults.resolution.factor, }); + if let Some(controls) = &defaults.controls { + return merged(params, kind_params(controls)); + } // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); @@ -163,7 +233,18 @@ pub(crate) fn differs_from_defaults(generator: &Generator) -> bool { { restored.micro = Some(Box::new(MicroDetails { height_source: micro.height_source.clone(), normal_source: micro.normal_source.clone(), ..defaults })); } - restored.controls = generator.controls.clone(); + + // Grayscale Conversion's image stays in its slot + restored.controls = match (restored.controls.as_deref(), generator.controls.as_deref()) { + (_, None) => None, + (Some(KindControls::Grayscale(defaults)), Some(KindControls::Grayscale(saved))) => { + Some(Box::new(KindControls::Grayscale(texturecraft_engine::core::GrayscaleConversionParameters { + source: saved.source.clone(), + ..defaults.clone() + }))) + } + (defaults, _) => defaults.cloned().map(Box::new), + }; // Saved before the wear, section or light controls: the earlier model's own values count if generator.wear.is_none() { diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs new file mode 100644 index 00000000..72712c84 --- /dev/null +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -0,0 +1,30 @@ +//! Picking a 3D generator's point on the mesh: its crosshair button arms it, the next click in the 3D view sets the point, Esc or the button again cancels + +/// Which point of which generator effect the next click in the 3D view sets +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PointPick { + pub(crate) effect: u64, + + /// `effect.generator.pickPoint`'s point: distance, start or end + pub(crate) point: &'static str, +} + +/// Where the armed pick is kept: a transient UI mode, like the depth of field's focus pick +fn pick_id() -> egui::Id { + egui::Id::unique("tc_generator_point_pick") +} + +/// The point the next click in the 3D view sets, if one is armed +pub(crate) fn armed(ctx: &egui::Context) -> Option { + ctx.data(|data| data.get_temp::>(pick_id())).flatten() +} + +/// Arms `pick`, or disarms it when it is the one armed +pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { + let next = if armed(ctx) == Some(pick) { None } else { Some(pick) }; + set(ctx, next); +} + +pub(crate) fn set(ctx: &egui::Context, pick: Option) { + ctx.data_mut(|data| data.insert_temp(pick_id(), pick)); +} diff --git a/crates/ui-egui/src/generator_section_rows.rs b/crates/ui-egui/src/generator_section_rows.rs index 0e7533a8..38377af0 100644 --- a/crates/ui-egui/src/generator_section_rows.rs +++ b/crates/ui-egui/src/generator_section_rows.rs @@ -23,8 +23,11 @@ fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, picture: &dyn Fn(&Painter, Rect)) { let (mut invert, mut global) = (generator.invert, generator.global); let invert_edit = sheet.toggle(tr("Global Invert"), &mut invert).then_some(false); - let mut stack = - [stacked(tr("Global Blur"), &mut global.blur), stacked(tr("Global Balance"), &mut global.balance), stacked(tr("Global Contrast"), &mut global.contrast)]; + let mut stack = [ + stacked(tr("Global Blur"), &mut global.blur), + stacked(tr("Global Balance"), &mut global.balance), + stacked(tr("Global Contrast"), &mut global.contrast), + ]; let stack_edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if let Some(merge) = invert_edit.or(stack_edit) { app.run( @@ -35,7 +38,14 @@ pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<' } /// The kind's own card (Curvature's mode and sizes in it), then one card per axis, showing `shown`; `solo` keeps the Curvature size under the pointer for the preview -pub(crate) fn section_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, shown: SectionParameters, solo: &mut Option) { +pub(crate) fn section_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + generator: &Generator, + shown: SectionParameters, + solo: &mut Option, +) { let kind = generator.kind; let title = match kind { GeneratorKind::Curvature => tr("Curvature"), diff --git a/crates/ui-egui/src/generator_wear_rows.rs b/crates/ui-egui/src/generator_wear_rows.rs index 09273f0b..c103ab72 100644 --- a/crates/ui-egui/src/generator_wear_rows.rs +++ b/crates/ui-egui/src/generator_wear_rows.rs @@ -38,11 +38,8 @@ pub(crate) fn wear_rows( let dirt = kind == GeneratorKind::Dirt; let (level_label, contrast_label) = if dirt { (tr("Dirt Level"), tr("Dirt Contrast")) } else { (tr("Wear Level"), tr("Wear Contrast")) }; let mut edited = wear; - let mut stack = [ - stacked(level_label, &mut edited.level), - stacked(contrast_label, &mut edited.contrast), - stacked(tr("Grunge Amount"), &mut edited.grunge_amount), - ]; + let mut stack = + [stacked(level_label, &mut edited.level), stacked(contrast_label, &mut edited.contrast), stacked(tr("Grunge Amount"), &mut edited.grunge_amount)]; let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if kind != GeneratorKind::FiberGlassEdgeWear { edit = edit.or(sheet.slider(tr("Grunge Scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); @@ -82,7 +79,14 @@ pub(crate) fn wear_rows( } /// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) -pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, invert: Option, shown: LightParameters, picture: &dyn Fn(&Painter, Rect)) { +pub(crate) fn light_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + invert: Option, + shown: LightParameters, + picture: &dyn Fn(&Painter, Rect), +) { if let Some(mut invert) = invert && sheet.toggle(tr("Invert"), &mut invert) { @@ -90,7 +94,15 @@ pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_ } let mut edited = shown; - let angle = |label, value| StackSlider { label, value, range: LightParameters::ANGLE_RANGE, typed: LightParameters::ANGLE_RANGE, decimals: 0, suffix: "°", dial: true }; + let angle = |label, value| StackSlider { + label, + value, + range: LightParameters::ANGLE_RANGE, + typed: LightParameters::ANGLE_RANGE, + decimals: 0, + suffix: "°", + dial: true, + }; let mut stack = [ angle(tr("Horizontal Angle"), &mut edited.horizontal), angle(tr("Vertical Angle"), &mut edited.vertical), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d626d5c3..f13365a8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -46,8 +46,10 @@ pub mod fonts; mod frame_gizmo; mod generator_input_card; mod generator_input_slot; +mod generator_kind_rows; mod generator_panel; mod generator_params; +mod generator_point_pick; mod generator_section_rows; mod generator_slot; mod generator_wear_rows; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..3782cf3b 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -473,6 +473,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Let the innermost popup consume Escape before cancelling the active tool let popup_open = egui::Popup::is_any_open(ctx); + let point_pick_armed = crate::generator_point_pick::armed(ctx).is_some(); + let mut cancel_point_pick = false; let picker_open = crate::color_picker::open_window(ctx).is_some(); let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); @@ -528,6 +530,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; + } else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { + cancel_point_pick = true; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { @@ -543,6 +547,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { commands }); + if cancel_point_pick { + crate::generator_point_pick::set(ctx, None); + } for id in &commands_to_invoke { if matches!(id.as_str(), "layer.copy" | "layer.cut") diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index bde4267b..291d50d9 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -38,6 +38,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: && app.moving_on_model.is_none() && !gesture_key_held && !crate::viewport::focus_picking(ui.ctx()) + && crate::generator_point_pick::armed(ui.ctx()).is_none() && ui.input(|input| input.modifiers.is_none()); if !free || !response.clicked_by(PointerButton::Secondary) { diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index f16db1b3..c534afc3 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -107,7 +107,14 @@ impl PropertySheet<'_> { } /// A card for one axis: its letter on a chip in `tint`, the bold name and the value, then a full-width slider filled in `tint`; the axis's other rows follow, then [`Self::close_card`] - pub(crate) fn axis_card(&mut self, (letter, tint): (&str, Color32), name: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + pub(crate) fn axis_card( + &mut self, + (letter, tint): (&str, Color32), + name: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + ) -> Option { self.open_card(); self.scope = self.named_id("axis_card", name); self.space(AXIS_CARD_TOP); diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 2e352d98..2e321496 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -51,9 +51,25 @@ impl PropertySheet<'_> { pub(crate) fn number_fields(&mut self, label: &str, fields: &mut [NumberField], link: Option<&mut bool>, keep_link_slot: bool) -> Option<(usize, bool)> { let (control, center_y) = self.row(label); let slot = if link.is_some() || keep_link_slot { LINK_SLOT } else { 0.0 }; + let edited = self.fields_in(control, slot, label, fields); + if let Some(linked) = link { + self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); + } + edited + } + + /// A point in 3D: `label` on its own line, then its fields across the card and the pick-on-mesh button in the link slot, lit while `picking`; returns the edited index with whether it continues a drag, and whether the button was clicked + pub(crate) fn point_fields(&mut self, label: &str, fields: &mut [NumberField], picking: bool) -> (Option<(usize, bool)>, bool) { + let (control, center_y) = self.row_with(super::RowLead::Label { text: label, stack: true }); + let edited = self.fields_in(control, LINK_SLOT, label, fields); + let clicked = self.pick_button(pos2(self.right - LINK_SIZE / 2.0, center_y), label, picking); + (edited, clicked) + } + + /// `fields` side by side across `control`, leaving `slot` at its end + fn fields_in(&mut self, control: Rect, slot: f32, label: &str, fields: &mut [NumberField]) -> Option<(usize, bool)> { let count = fields.len().max(1) as f32; let width = (control.width() - slot - (count - 1.0) * FIELD_GAP) / count; - let mut edited = None; for (index, field) in fields.iter_mut().enumerate() { let left = control.left() + index as f32 * (width + FIELD_GAP); @@ -62,13 +78,27 @@ impl PropertySheet<'_> { edited = Some((index, edited.is_none_or(|(_, previous_merge)| previous_merge) && merge)); } } - - if let Some(linked) = link { - self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); - } edited } + /// The button that arms picking the point of row `label` on the mesh; returns whether it was clicked + fn pick_button(&mut self, center: egui::Pos2, label: &str, picking: bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.named_id("pick_on_mesh", label); + let response = self.ui.interact(rect, id, Sense::click()); + let name = crate::i18n::trf("Pick {name} on the mesh", &[("name", &label)]); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, picking, &name)); + let response = self.tip(response, crate::i18n::tr("Pick on the mesh")); + + let tokens = self.tokens; + let (fill, border) = if picking { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + painter.text(rect.center(), Align2::CENTER_CENTER, ic::CROSSHAIR_SIMPLE, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&response); + response.clicked() + } + /// The link that keeps two values together; returns whether it was clicked pub(super) fn link_button(&mut self, center: egui::Pos2, linked: &mut bool) -> bool { let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); diff --git a/crates/ui-egui/src/property_sheet/size_columns.rs b/crates/ui-egui/src/property_sheet/size_columns.rs index da810113..ec6dd9d7 100644 --- a/crates/ui-egui/src/property_sheet/size_columns.rs +++ b/crates/ui-egui/src/property_sheet/size_columns.rs @@ -53,8 +53,17 @@ impl PropertySheet<'_> { let painter = self.ui.painter(); if hovered { - let face = Rect::from_min_max(pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG)); - painter.rect(face, CornerRadius::same(super::CONTROL_RADIUS), tokens.row_hover, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let face = Rect::from_min_max( + pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), + pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG), + ); + painter.rect( + face, + CornerRadius::same(super::CONTROL_RADIUS), + tokens.row_hover, + Stroke::new(1.0, tokens.field_border), + egui::StrokeKind::Inside, + ); } painter.text(pos2(x, block.top() + VALUE_LINE / 2.0), Align2::CENTER_CENTER, format!("{value:.2}"), semibold(SMALL_TEXT_SIZE), tokens.text); painter.line_segment([pos2(x, track_top), pos2(x, track_bottom)], Stroke::new(COLUMN_TRACK_WIDTH, tokens.button_border)); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index dc64aaae..ba44649f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,7 +646,8 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); + let on_the_orb = + matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | 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 diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..473eaf29 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -864,9 +864,27 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } + // A 3D generator's armed point pick: a click sets the point there instead of painting + let point_pick = crate::generator_point_pick::armed(ui.ctx()); + if let Some(pick) = point_pick { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() + { + let (at, viewport) = (local(pointer), app.session.viewport); + let params = json!({"effect": pick.effect, "point": pick.point, "x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]}); + + // A click off the mesh keeps it armed for the next + if app.run("effect.generator.pickPoint", params).is_some() { + crate::generator_point_pick::set(ui.ctx(), None); + } + } + } + // Depth of field focus pick: a click focuses there instead of painting - let focus_pick = focus_picking(ui.ctx()); - if focus_pick { + let focus_pick = focus_picking(ui.ctx()) || point_pick.is_some(); + if focus_picking(ui.ctx()) { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt && response.clicked_by(PointerButton::Primary) diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 78fc0d9c..e191d8b0 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; -use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, KindControls, LayerId, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -388,3 +388,107 @@ fn texture_panel_snapshots() { } } } + +/// Whether control `label` with `role` shows on +fn is_on(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { + harness.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn a_point_pick_waits_for_the_view_until_escape() { + let (mut harness, _) = harness_with(false, json!({"generator": "3dLinearGradient"})); + let (start, end) = ("Pick 3D Position Start on the mesh", "Pick 3D Position End on the mesh"); + assert!(!is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end)); + + click_live(&mut harness, Role::Button, end); + assert!(is_on(&harness, Role::Button, end), "armed: the next click in the view sets the end"); + assert!(!is_on(&harness, Role::Button, start), "only the point picked waits"); + + click_live(&mut harness, Role::Button, start); + assert!(is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end), "arming the start hands the wait over"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert!(!is_on(&harness, Role::Button, start), "Esc cancels the pick"); +} + +#[test] +fn a_gradient_color_place_moves_its_stop_in_one_step() { + let added = + json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[0.0, 0.0, 0.0], [0.8, 0.3, 0.1], [1.0, 1.0, 1.0]]}); + let (mut harness, effect) = harness_with(false, added); + let places = |harness: &Harness<'_, TextureCraftApp>| match generator(harness, effect).kind_controls() { + Some(KindControls::UvRandomColor(random)) => random.used_positions(), + other => panic!("not UV Random Color controls: {other:?}"), + }; + let before = places(&harness); + + // Color 2's own track, after its marker on the ramp + let rect = harness.get_all_by_role_and_label(Role::Slider, "Color 2").last().expect("Color 2's place").rect(); + let (from, to) = (egui::pos2(rect.left() + 4.0, rect.center().y), egui::pos2(rect.right() - 4.0, rect.center().y)); + harness.drag_at(from); + harness.run_steps(2); + harness.hover_at(to); + harness.run_steps(2); + harness.drop_at(to); + harness.run_steps(3); + + let after = places(&harness); + assert!(after[1] > before[1], "Color 2 moved right along the gradient"); + assert_eq!((after[0], after[2]), (before[0], before[2]), "the other colors keep their places"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(places(&harness), before, "one undo step puts it back"); +} + +#[test] +fn the_color_rows_follow_the_color_mode() { + let (mut harness, _) = harness_with(false, json!({"generator": "uvChecker"})); + assert_eq!(count(&harness, "Checker Color"), 1, "uniform: its color shows"); + click_live(&mut harness, Role::RadioButton, "Random"); + assert_eq!(count(&harness, "Checker Color"), 0, "random colors: no color to pick"); + assert_eq!(count(&harness, "UV Borders Color"), 1, "the borders keep theirs"); + + let (mut harness, _) = harness_with(false, json!({"generator": "uvRandomColor"})); + assert_eq!(count(&harness, "Color 1"), 0, "random: no gradient"); + harness.get_by_role_and_label(Role::ComboBox, "Random").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::ListBoxOption, "Custom Gradient").click(); + harness.run_steps(3); + assert!(count(&harness, "Color 1") > 0 && count(&harness, "Color 2") > 0, "a custom gradient shows its colors"); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn new_kind_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let gradient = json!([[0.02, 0.02, 0.02], [0.6, 0.12, 0.03], [0.8, 0.8, 0.8]]); + let kinds = [ + ("3dDistance", json!({})), + ("3dLinearGradient", json!({})), + ("uvBorderDistance", json!({})), + ("grayscaleConversion", json!({})), + ("drippingRust", json!({})), + ("uvRandomColor", json!({"colorSourceMode": "customGradient", "gradientColors": gradient, "gradientPositions": [0.0, 0.45, 1.0]})), + ("uvChecker", json!({})), + ]; + for (kind, extra) in kinds { + let mut added = json!({"generator": kind}); + added.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let (mut harness, _) = harness_with(true, added); + if kind == "grayscaleConversion" { + harness.get_by_role_and_label(Role::Button, "Image inputs").click(); + } + + // The orbs render on the preview worker + for _ in 0..40 { + harness.run_steps(4); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-{kind}-{name}.png"))).unwrap(); + } + } +} From 494403237903360a338b9bae7c55ba2cf739b9c2 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:47:05 +0000 Subject: [PATCH 114/153] Property sheet: Escape cancels a typed value even where a shortcut takes the key; a press on the track drops the value typed in its row --- crates/ui-egui/src/property_sheet/number_field.rs | 2 +- crates/ui-egui/src/property_sheet/slider.rs | 7 ++++++- crates/ui-egui/src/property_sheet/slot.rs | 2 +- crates/ui-egui/src/property_sheet/value_text.rs | 15 +++++++++++++++ 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 2e321496..36c484ad 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -154,7 +154,7 @@ impl PropertySheet<'_> { let untouched = self.end_typing(typing_id, &draft); let text = draft.text.trim(); - if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + if self.escape_pressed() { return None; } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 6cf51d26..8e43a01e 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -216,6 +216,11 @@ impl PropertySheet<'_> { let response = self.ui.interact(hit, id, Sense::click_and_drag()); response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + // A press on the track drops what was typed in its value: the track's value is the one wanted + if response.is_pointer_button_down_on() { + self.drop_typing(id.with((self.id, "typed"))); + } + let mut moved = false; if (response.dragged() || response.drag_stopped() || response.clicked()) && let Some(pointer) = response.interact_pointer_pos() @@ -336,7 +341,7 @@ impl PropertySheet<'_> { let untouched = self.end_typing(field_id, &draft); let typed_text = draft.text.trim(); - if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + if self.escape_pressed() { return None; } diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index b3b36a4c..90d2111b 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -248,7 +248,7 @@ impl PropertySheet<'_> { if let Ok(typed) = draft.text.trim().parse::() && !untouched && typed != *seed - && !self.ui.input(|input| input.key_pressed(egui::Key::Escape)) + && !self.escape_pressed() { *seed = typed; changed = true; diff --git a/crates/ui-egui/src/property_sheet/value_text.rs b/crates/ui-egui/src/property_sheet/value_text.rs index a569f284..fc83f749 100644 --- a/crates/ui-egui/src/property_sheet/value_text.rs +++ b/crates/ui-egui/src/property_sheet/value_text.rs @@ -45,6 +45,21 @@ impl super::PropertySheet<'_> { draft.original.trim() == draft.text.trim() } + /// Whether Escape was pressed this frame, even where a shortcut took it before the field lost its focus to it + pub(super) fn escape_pressed(&self) -> bool { + self.ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))) + } + + /// Drops the draft of field `field_id`, if it is being typed in, without applying it + pub(super) fn drop_typing(&self, field_id: Id) { + if self.typing_draft(field_id).is_some() { + self.ui.memory_mut(|memory| { + memory.caches.cache::().set(field_id, None); + memory.surrender_focus(field_id); + }); + } + } + /// Shows an edit in place of the displayed value, without shifting the sheet's rows pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, field_id: Id, draft: &mut ValueTextDraft) -> egui::Response { let font = semibold(super::TEXT_SIZE); From cb0a6f8a28174dd08674356749182a7fad16094a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:33 +0000 Subject: [PATCH 115/153] Generators: names and comments to the review guidelines; the bake hint without a hardcoded shortcut --- crates/compose/src/eval.rs | 14 +++--- crates/core/src/layer.rs | 11 +++-- crates/engine/src/orb_preview.rs | 3 +- crates/engine/tests/it/content_effects.rs | 60 +++++++++++------------ crates/ui-egui/src/generator_panel.rs | 2 +- 5 files changed, 45 insertions(+), 45 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 06f95001..648a98fa 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1953,22 +1953,22 @@ fn filter_region( /// Where working texel (`x`, `y`) of `inp` is, for pattern evaluation (as [`Texel::coords`] sees it outside a fill copy) pub(crate) fn texel_coords(inp: &Inputs, x: u32, y: u32) -> Coords { - let g = inp.gbuf; - let mut c = match g.surface(inp.mesh, (y * g.width + x) as usize) { - Some(s) => { + let gbuf = inp.gbuf; + let mut coords = match gbuf.surface(inp.mesh, (y * gbuf.width + x) as usize) { + Some(surface) => { let (center, radius) = mesh_frame(inp.bounds); - Coords { uv: s.uv, pos: (s.pos - center) / radius, nrm: s.nrm } + Coords { uv: surface.uv, pos: (surface.pos - center) / radius, nrm: surface.nrm } } - None => Coords { uv: Vec2::new((x as f32 + 0.5) / g.width as f32, (y as f32 + 0.5) / g.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + None => Coords { uv: Vec2::new((x as f32 + 0.5) / gbuf.width as f32, (y as f32 + 0.5) / gbuf.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, }; // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile) if let Ok(set) = inp.project.texture_set(inp.ts) && let Some(grid) = set.tile_grid() { - c.uv = Vec2::from(set.from_atlas(&grid, c.uv.to_array())); + coords.uv = Vec2::from(set.from_atlas(&grid, coords.uv.to_array())); } - c + coords } /// What a generator's texture or custom grunge reads with nothing in its slot diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index bc82c7b7..62db399d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1096,8 +1096,8 @@ impl GeneratorKind { ) } - pub fn parse(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); + pub fn parse(name: &str) -> Option { + let normalised = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); // The labels before the reference app's names, which agents may still send let earlier = |kind: GeneratorKind| match kind { GeneratorKind::EdgeWear => Some("Mask Editor: Edge wear"), @@ -1105,9 +1105,10 @@ impl GeneratorKind { GeneratorKind::Direction => Some("Light / direction"), _ => None, }; - GeneratorKind::ALL - .into_iter() - .find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s) || earlier(*k).is_some_and(|label| norm(label) == norm(s))) + GeneratorKind::ALL.into_iter().find(|kind| { + let wanted = normalised(name); + normalised(kind.id()) == wanted || normalised(kind.label()) == wanted || earlier(*kind).is_some_and(|label| normalised(label) == wanted) + }) } } diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index 6d03ef36..c392dc4c 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -86,8 +86,7 @@ impl OrbPreview { self.mask_pixels(size) } - /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape - /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, None outside the shape (and for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]) pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { let mut generator = Generator::new(kind); diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index f15a9ed8..b8770541 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -163,52 +163,52 @@ fn largest_change(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { #[test] fn generators_read_an_anchor_height_as_their_micro_height() { - let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); // A checker of raised height below, recorded by an anchor point - let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap(), "layer"); - execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap(); - execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); - let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); - let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); - execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap(); + let low = id(execute(&mut session, "layer.add.fill", &json!({"height": 1.0})).unwrap(), "layer"); + execute(&mut session, "mask.add.black", &json!({"layer": low})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); + let top = id(execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap(); // The anchor must be below; `microAmount` needs an anchor; ids must be numbers - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAmount": 0.5})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": "x"})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": low})).is_err(), "not an anchor point"); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": top, "microAmount": 0.5})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": top, "microAnchor": "x"})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": top, "microAnchor": low})).is_err(), "not an anchor point"); - let generator = id(execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap(), "effect"); - let plain = base_colors(&mut s); - execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); - let raised = base_colors(&mut s); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap(), "effect"); + let plain = base_colors(&mut session); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); + let raised = base_colors(&mut session); assert!(largest_change(&raised, &plain) > 0.05, "the checker's raised edges read as curvature"); - let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let inspect = execute(&mut session, "project.inspect", &Value::Null).unwrap(); let inspected = inspect.to_string(); assert!(inspected.contains("\"heightSource\"") && inspected.contains(&format!("\"anchor\":{anchor}")), "{inspect}"); // The amount alone keeps the anchor; null empties the Micro Height - execute(&mut s, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); - assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "no amount, no micro height"); - execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); - let emptied = s + execute(&mut session, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); + assert!(largest_change(&base_colors(&mut session), &plain) < 1e-3, "no amount, no micro height"); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); + let emptied = session .doc .project .effect(LayerId(generator)) - .map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.as_ref().is_some_and(|micro| micro.height_source.is_none()))); + .map(|(_, effect)| matches!(&effect.kind, EffectKind::Generator(made) if made.micro.as_ref().is_some_and(|micro| micro.height_source.is_none()))); assert_eq!(emptied, Some(true)); - assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "without an anchor, as without micro details"); - assert!(execute(&mut s, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); + assert!(largest_change(&base_colors(&mut session), &plain) < 1e-3, "without an anchor, as without micro details"); + assert!(execute(&mut session, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); // A copied generator reading an anchor needs the anchor below its new layer - execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); - execute(&mut s, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); - execute(&mut s, "effect.copy", &json!({"effect": generator})).unwrap(); - execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); - assert!(execute(&mut s, "effect.paste", &json!({"target": "mask"})).is_err()); - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.doc.project, s.doc.project); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); + execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut session, "effect.paste", &json!({"target": "mask"})).is_err()); + let back = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, session.doc.project); } #[test] diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 4f6661da..bc7297cf 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -66,7 +66,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, attributes(sheet, generator.kind); } if !app.session.doc.baked.contains_key(&app.session.ts()) { - sheet.caption(tr("Bake mesh maps (Ctrl+Shift+B) for curvature, AO and thickness based generators.")); + sheet.caption(tr("Bake mesh maps for curvature, AO and thickness based generators.")); } }); } From 1ed1f5ca5d13f60b4b4191a6c3a81406bc82e7d4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:31:47 +0000 Subject: [PATCH 116/153] Generators: review fixes (one type per file, a stale point pick drops, an image still loading blends black on both render paths, inspect reports the new controls) --- crates/compose/src/dripping_rust.rs | 17 +- crates/compose/src/eval.rs | 7 +- crates/compose/src/field_cache.rs | 66 ++++ crates/compose/src/field_cache_key.rs | 30 ++ crates/compose/src/grunge_pattern.rs | 37 +++ crates/compose/src/lib.rs | 4 + .../compose/src/micro_details/anchor_entry.rs | 15 + .../src/micro_details/anchor_heights.rs | 24 ++ crates/compose/src/micro_details/cache_key.rs | 24 ++ .../compose/src/micro_details/cached_bytes.rs | 4 + .../compose/src/micro_details/layout_map.rs | 26 ++ .../compose/src/micro_details/micro_cache.rs | 51 +++ .../src/micro_details/micro_curvature.rs | 47 +++ .../mod.rs} | 308 ++---------------- crates/compose/src/micro_details/slot.rs | 98 ++++++ crates/compose/src/micro_details/slot_key.rs | 23 ++ crates/compose/src/sections.rs | 4 + crates/compose/src/slot_placement.rs | 7 + crates/compose/src/texture_layer.rs | 10 +- crates/compose/src/uv_border_distance.rs | 11 +- crates/compose/src/uv_islands.rs | 15 +- crates/compose/src/wear.rs | 43 +-- crates/compose/src/working_field.rs | 98 +----- crates/compose/tests/generator_texture.rs | 12 + crates/core/src/layer.rs | 3 +- crates/engine/src/generator_input.rs | 12 + crates/engine/src/generator_pick.rs | 3 +- crates/engine/src/inspect.rs | 9 + crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 21 +- crates/ui-egui/src/generator_kind_rows.rs | 39 +-- crates/ui-egui/src/generator_params.rs | 5 +- crates/ui-egui/src/generator_point_pick.rs | 10 + crates/ui-egui/src/generator_section_rows.rs | 11 +- crates/ui-egui/src/generator_wear_rows.rs | 14 +- .../src/property_sheet/stack_slider.rs | 12 + crates/ui-egui/src/viewport.rs | 2 +- crates/ui-egui/src/widgets.rs | 31 +- crates/ui-egui/tests/it/effect_sliders.rs | 13 +- crates/ui-egui/tests/it/generator_panel.rs | 28 +- crates/ui-egui/tests/ui_snapshots.rs | 1 - 41 files changed, 659 insertions(+), 537 deletions(-) create mode 100644 crates/compose/src/field_cache.rs create mode 100644 crates/compose/src/field_cache_key.rs create mode 100644 crates/compose/src/grunge_pattern.rs create mode 100644 crates/compose/src/micro_details/anchor_entry.rs create mode 100644 crates/compose/src/micro_details/anchor_heights.rs create mode 100644 crates/compose/src/micro_details/cache_key.rs create mode 100644 crates/compose/src/micro_details/cached_bytes.rs create mode 100644 crates/compose/src/micro_details/layout_map.rs create mode 100644 crates/compose/src/micro_details/micro_cache.rs create mode 100644 crates/compose/src/micro_details/micro_curvature.rs rename crates/compose/src/{micro_details.rs => micro_details/mod.rs} (62%) create mode 100644 crates/compose/src/micro_details/slot.rs create mode 100644 crates/compose/src/micro_details/slot_key.rs create mode 100644 crates/compose/src/slot_placement.rs create mode 100644 crates/engine/src/generator_input.rs diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index ef3e308c..4b5f84d5 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -7,9 +7,10 @@ use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearPar use texturecraft_geom::glam::Vec3; use crate::eval::{Inputs, texel_coords}; +use crate::field_cache::FieldCache; use crate::histogram_scan::histogram_scan; use crate::wear; -use crate::working_field::{FieldCache, blur_blocks}; +use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius}; /// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference) const RUST_FLOOR: f32 = 0.315; @@ -29,9 +30,6 @@ const DRIP_LENGTH_2K: f32 = 90.86; const DRIP_FADE: f32 = 0.898; const DRIP_FADE_POWER: f32 = 0.671; -/// The UV tile resolution the sizes above are measured at -const REFERENCE_TILE_TEXELS: f32 = 2048.0; - /// Coverage below which a blurred texel has nothing to average const MIN_COVERAGE: f32 = 1e-3; @@ -73,19 +71,14 @@ fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u3 }; let mut field: Vec = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect(); - let sigma_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); - blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); + let radius_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); let mut field = drips(inp, rust, &field, (width, height), &tile_texels); - blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 }); field } -/// The radius of three box passes that blur like a gaussian of `sigma`: three boxes of radius r spread a texel with variance r (r + 1) -fn box_radius(sigma: f32) -> usize { - (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize -} - /// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) { let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 648a98fa..a98e07a9 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3638,9 +3638,10 @@ impl<'a, 'b> Texel<'a, 'b> { fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { let ramp = self.generator_ramp(generator, maps); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); - let textured = match (generator.texture_in_use(), self.generator_texture(generator)) { - (Some(texture), Some(gray)) => texture_layer::blended_over(texture, adjusted, gray), - _ => adjusted, + // An image still loading reads black, as it does where blur or resolution compute the generator over a region + let textured = match generator.texture_in_use() { + Some(texture) => texture_layer::blended_over(texture, adjusted, self.generator_texture(generator).unwrap_or(0.0)), + None => adjusted, }; finish_generator(generator, textured) } diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs new file mode 100644 index 00000000..910ce75c --- /dev/null +++ b/crates/compose/src/field_cache.rs @@ -0,0 +1,66 @@ +use std::sync::{Arc, Mutex}; + +use crate::eval::Inputs; +use crate::field_cache_key::FieldCacheKey; +use crate::working_field::working_block; + +/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) +const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; + +/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile +const FINGERPRINT_STRIDE: usize = 31; + +/// Built fields by what they were built from, most recently used last +pub(crate) struct FieldCache { + entries: Mutex>)>>, +} + +impl FieldCache { + pub(crate) const fn new() -> FieldCache { + FieldCache { entries: Mutex::new(Vec::new()) } + } + + /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work + pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { + let gbuf = inp.gbuf; + let block = working_block(inp); + let key = FieldCacheKey { + layout: gbuf.tri.as_ptr() as usize, + size: (gbuf.width, gbuf.height), + fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), + block, + scales: inp.block_scales.clone(), + mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len(), inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), + maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), + settings, + }; + + let cached = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); + entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) + }; + if let Some(field) = cached { + return field; + } + + let field = Arc::new(build(block)); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, field.clone())); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); + entries.drain(..excess); + field + } +} diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs new file mode 100644 index 00000000..fa84471e --- /dev/null +++ b/crates/compose/src/field_cache_key.rs @@ -0,0 +1,30 @@ +use std::sync::Weak; + +use texturecraft_core::BlockScales; + +/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits +#[derive(Clone)] +pub(crate) struct FieldCacheKey { + pub(crate) layout: usize, + pub(crate) size: (u32, u32), + pub(crate) fingerprint: u64, + pub(crate) block: (u32, u32), + pub(crate) scales: BlockScales, + pub(crate) mesh: (usize, usize, usize, usize), + pub(crate) maps: Vec>>, + pub(crate) settings: Vec, +} + +impl PartialEq for FieldCacheKey { + fn eq(&self, other: &FieldCacheKey) -> bool { + let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); + same_maps + && self.layout == other.layout + && self.size == other.size + && self.fingerprint == other.fingerprint + && self.block == other.block + && self.scales == other.scales + && self.mesh == other.mesh + && self.settings == other.settings + } +} diff --git a/crates/compose/src/grunge_pattern.rs b/crates/compose/src/grunge_pattern.rs new file mode 100644 index 00000000..5005bb73 --- /dev/null +++ b/crates/compose/src/grunge_pattern.rs @@ -0,0 +1,37 @@ +use texturecraft_core::{GeneratorKind, ProceduralKind}; + +/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`) +pub(crate) struct GrungePattern { + pub(crate) kind: ProceduralKind, + pub(crate) repeats_per_scale: f32, + pub(crate) rotation: f32, + /// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change + pub(crate) breakup: Option<(ProceduralKind, f32)>, + pub(crate) mean: f32, + pub(crate) spread: f32, + /// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner) + pub(crate) custom_gain: f32, +} + +/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt +pub(crate) const EDGE_WEAR_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 }; +pub(crate) const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { + kind: ProceduralKind::Weave, + repeats_per_scale: 16.0, + rotation: 45.0, + breakup: Some((ProceduralKind::Grunge, 4.0)), + mean: 0.539, + spread: 0.198, + custom_gain: 1.9, +}; +pub(crate) const DIRT_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 }; + +pub(crate) fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern { + match kind { + GeneratorKind::Dirt => &DIRT_GRUNGE, + GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, + _ => &EDGE_WEAR_GRUNGE, + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index eb85e0ae..e7d72fe8 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -20,6 +20,8 @@ pub mod environment_sh; pub mod environment_sky; pub mod eval; mod fabric; +mod field_cache; +mod field_cache_key; pub mod fill_copies; pub mod fill_copy; mod fill_depth; @@ -27,6 +29,7 @@ mod fill_place; pub mod frame_placement; mod fur_lock; mod generator_maps; +mod grunge_pattern; mod held_fields; mod histogram_scan; mod image_identity; @@ -43,6 +46,7 @@ pub mod projector_view; mod sections; mod shape_distance; mod slope_texel; +mod slot_placement; mod soft_box; pub mod solo; pub mod store; diff --git a/crates/compose/src/micro_details/anchor_entry.rs b/crates/compose/src/micro_details/anchor_entry.rs new file mode 100644 index 00000000..c530cb85 --- /dev/null +++ b/crates/compose/src/micro_details/anchor_entry.rs @@ -0,0 +1,15 @@ +use std::sync::{Arc, Weak}; + +use texturecraft_core::LayerId; + +use super::anchor_heights::AnchorHeights; +use crate::below::StackKey; + +/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key +pub(super) struct AnchorEntry { + pub(super) baked: Weak>, + pub(super) texture_set: usize, + pub(super) anchor: LayerId, + pub(super) stack: StackKey, + pub(super) heights: Arc, +} diff --git a/crates/compose/src/micro_details/anchor_heights.rs b/crates/compose/src/micro_details/anchor_heights.rs new file mode 100644 index 00000000..0a8b5c18 --- /dev/null +++ b/crates/compose/src/micro_details/anchor_heights.rs @@ -0,0 +1,24 @@ +use texturecraft_core::BlockScales; + +/// An anchor point's height over the whole texture set, in the working atlas's layout +pub struct AnchorHeights { + data: Vec, + working_size: (u32, u32), + scales: BlockScales, +} + +impl AnchorHeights { + pub fn new(data: Vec, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights { + AnchorHeights { data, working_size, scales } + } + + /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) + pub(super) fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { + let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; + let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 }; + + let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1)); + let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1)); + self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0) + } +} diff --git a/crates/compose/src/micro_details/cache_key.rs b/crates/compose/src/micro_details/cache_key.rs new file mode 100644 index 00000000..ee0b6bc2 --- /dev/null +++ b/crates/compose/src/micro_details/cache_key.rs @@ -0,0 +1,24 @@ +use std::sync::Weak; + +use super::slot_key::SlotKey; + +/// What a micro map was built from: the mesh map giving its layout, its slots, its settings' bits and its UV tile block +#[derive(Clone)] +pub(super) struct CacheKey { + pub(super) map: Weak>, + pub(super) height: Option, + pub(super) normal: Option, + pub(super) settings: Vec, + pub(super) block: (u32, u32), +} + +impl PartialEq for CacheKey { + fn eq(&self, other: &CacheKey) -> bool { + self.map.strong_count() > 0 + && self.map.ptr_eq(&other.map) + && self.height == other.height + && self.normal == other.normal + && self.settings == other.settings + && self.block == other.block + } +} diff --git a/crates/compose/src/micro_details/cached_bytes.rs b/crates/compose/src/micro_details/cached_bytes.rs new file mode 100644 index 00000000..46847139 --- /dev/null +++ b/crates/compose/src/micro_details/cached_bytes.rs @@ -0,0 +1,4 @@ +/// What a cached map holds, to keep the cache within [`CACHE_BYTES`](super::CACHE_BYTES) +pub(super) trait CachedBytes { + fn bytes(&self) -> usize; +} diff --git a/crates/compose/src/micro_details/layout_map.rs b/crates/compose/src/micro_details/layout_map.rs new file mode 100644 index 00000000..477129b1 --- /dev/null +++ b/crates/compose/src/micro_details/layout_map.rs @@ -0,0 +1,26 @@ +use texturecraft_core::BlockScales; + +use super::cached_bytes::CachedBytes; + +/// A map in a mesh map's layout: `size` texels, each UV tile one block +pub struct LayoutMap { + pub(super) data: Vec, + pub(super) size: (u32, u32), +} + +impl LayoutMap { + /// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout) + pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option { + let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = scales.bake_uv(uv, working_size)?; + let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1)); + let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1)); + self.data.get((row * self.size.0 + column) as usize).copied() + } +} + +impl CachedBytes for LayoutMap { + fn bytes(&self) -> usize { + self.data.len().saturating_mul(size_of::()) + } +} diff --git a/crates/compose/src/micro_details/micro_cache.rs b/crates/compose/src/micro_details/micro_cache.rs new file mode 100644 index 00000000..4aea74e7 --- /dev/null +++ b/crates/compose/src/micro_details/micro_cache.rs @@ -0,0 +1,51 @@ +use std::sync::{Arc, Mutex}; + +use super::cache_key::CacheKey; +use super::cached_bytes::CachedBytes; +use super::{CACHE_BYTES, CACHE_ENTRIES}; + +/// Built maps by what they were built from, most recently used last +pub(super) struct MicroCache { + entries: Mutex)>>, +} + +impl MicroCache { + pub(super) const fn new() -> MicroCache { + MicroCache { entries: Mutex::new(Vec::new()) } + } + + /// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work) + pub(super) fn get_or_build(&self, key: CacheKey, build: impl FnOnce() -> T) -> Arc { + let found = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.map.strong_count() > 0); + entries.iter().position(|(cached, _)| *cached == key).map(|index| { + let entry = entries.remove(index); + let built = entry.1.clone(); + entries.push(entry); + built + }) + }; + if let Some(built) = found { + return built; + } + + let built = Arc::new(build()); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, built.clone())); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.bytes()); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); + entries.drain(..excess); + built + } +} diff --git a/crates/compose/src/micro_details/micro_curvature.rs b/crates/compose/src/micro_details/micro_curvature.rs new file mode 100644 index 00000000..2ffd1bff --- /dev/null +++ b/crates/compose/src/micro_details/micro_curvature.rs @@ -0,0 +1,47 @@ +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, GeneratorKind, MicroDetails}; + +use super::cache_key::CacheKey; +use super::cached_bytes::CachedBytes; +use super::layout_map::LayoutMap; +use super::slot::Slot; +use super::{CURVATURE_CACHE, by_blocks, curvature_term, layout}; +use crate::eval::Inputs; + +/// The curvature a generator's micro details add +pub struct MicroCurvature { + /// What they add to the curvature input + pub term: LayoutMap, + /// The baked curvature with the term added, which the detail sizes blur + pub curvature: Arc>, +} + +impl MicroCurvature { + /// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map) + pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails) -> Option> { + let (curvature, size, block) = layout(inp, BakedMap::Curvature)?; + let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref())); + let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref())); + let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32]; + let key = CacheKey { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, block }; + + Some(CURVATURE_CACHE.get_or_build(key, || { + let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block); + let term = by_blocks(size, block, same_in_every_block, |origin, block| { + let height = height.as_ref().map(|height| height.in_block(origin, size)); + let normal = normal.as_ref().map(|normal| normal.in_block(origin, size)); + curvature_term(micro, height.as_ref(), normal.as_ref(), block) + }); + let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect(); + MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) } + })) + } +} + +impl CachedBytes for MicroCurvature { + fn bytes(&self) -> usize { + self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::())) + } +} diff --git a/crates/compose/src/micro_details.rs b/crates/compose/src/micro_details/mod.rs similarity index 62% rename from crates/compose/src/micro_details.rs rename to crates/compose/src/micro_details/mod.rs index 35132998..cc4bf6e4 100644 --- a/crates/compose/src/micro_details.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -1,13 +1,29 @@ //! A generator's micro details: the curvature and occlusion its micro height (an image or an anchor point's height) and normal image add to its mesh maps, built once per map, image and settings +mod anchor_entry; +mod anchor_heights; +mod cache_key; +mod cached_bytes; +mod layout_map; +mod micro_cache; +mod micro_curvature; +mod slot; +mod slot_key; + use std::sync::{Arc, Mutex, Weak}; +use anchor_entry::AnchorEntry; +pub use anchor_heights::AnchorHeights; +use cache_key::CacheKey; +pub use layout_map::LayoutMap; +use micro_cache::MicroCache; +pub use micro_curvature::MicroCurvature; use rayon::prelude::*; -use texturecraft_core::{BakedMap, BlockScales, GeneratorKind, LayerId, MicroCurvatureType, MicroDetails, NormalFormat, Source}; +use slot::Slot; +use texturecraft_core::{BakedMap, LayerId, MicroCurvatureType, MicroDetails}; use crate::below::StackKey; -use crate::eval::Inputs; -use crate::store::ImageRes; +use crate::eval::{BLUR_BOX_PASSES, Inputs}; /// The resolution of a UV tile the reference's micro details were measured at: derivatives and radii are per texel at this size const REFERENCE_TILE_TEXELS: f32 = 2048.0; @@ -21,6 +37,9 @@ const SMOOTH_SIGMAS: [f32; 7] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]; /// Below this sigma a blur is an explicit kernel; wider ones are three box passes const BOX_BLUR_MIN_SIGMA: f32 = 2.0; +/// How many sigmas the sampled kernel reaches each side +const KERNEL_REACH_SIGMAS: f32 = 3.0; + /// Directions the occlusion looks along const OCCLUSION_DIRECTIONS: usize = 16; @@ -45,80 +64,6 @@ const OCCLUSION_STRENGTH: f32 = 0.3232; const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; -/// What a cached map holds, to keep the cache within [`CACHE_BYTES`] -trait CachedBytes { - fn bytes(&self) -> usize; -} - -impl CachedBytes for LayoutMap { - fn bytes(&self) -> usize { - self.data.len().saturating_mul(size_of::()) - } -} - -impl CachedBytes for MicroCurvature { - fn bytes(&self) -> usize { - self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::())) - } -} - -/// A map in a mesh map's layout: `size` texels, each UV tile one block -pub struct LayoutMap { - data: Vec, - size: (u32, u32), -} - -impl LayoutMap { - /// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout) - pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option { - let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32]; - let baked_uv = scales.bake_uv(uv, working_size)?; - let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1)); - let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1)); - self.data.get((row * self.size.0 + column) as usize).copied() - } -} - -/// The curvature a generator's micro details add -pub struct MicroCurvature { - /// What they add to the curvature input - pub term: LayoutMap, - /// The baked curvature with the term added, which the detail sizes blur - pub curvature: Arc>, -} - -/// An anchor point's height over the whole texture set, in the working atlas's layout -pub struct AnchorHeights { - data: Vec, - working_size: (u32, u32), - scales: BlockScales, -} - -impl AnchorHeights { - pub fn new(data: Vec, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights { - AnchorHeights { data, working_size, scales } - } - - /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) - fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { - let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; - let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 }; - - let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1)); - let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1)); - self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0) - } -} - -/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key -struct AnchorEntry { - baked: Weak>, - texture_set: usize, - anchor: LayerId, - stack: StackKey, - heights: Arc, -} - /// The anchor heights prepared last, one per mesh maps, texture set and anchor static ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); @@ -167,188 +112,13 @@ fn anchor_heights(inp: &Inputs, anchor: LayerId) -> Option> { entries.iter().find(|entry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor).map(|entry| entry.heights.clone()) } -/// What a micro details slot reads -#[derive(Clone)] -enum Slot { - Uniform([f32; 3]), - Image { - image: Arc, - flip_green: bool, - }, - /// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map - Anchor { - heights: Arc, - origin: (u32, u32), - layout: (u32, u32), - }, -} - -impl Slot { - /// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read) - fn of(inp: &Inputs, source: Option<&Source>) -> Slot { - match source { - Some(Source::Uniform(value)) => Slot::Uniform(*value), - Some(Source::Image { name, normal_format }) => match inp.images.get(name) { - Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX }, - None => Slot::Uniform([0.0; 3]), - }, - Some(Source::Anchor { anchor, .. }) => match anchor_heights(inp, *anchor) { - Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) }, - None => Slot::Uniform([0.0; 3]), - }, - _ => Slot::Uniform([0.0; 3]), - } - } - - /// Whether every UV tile block reads the same (an image or a value repeats in each) - fn same_in_every_block(&self) -> bool { - !matches!(self, Slot::Anchor { .. }) - } - - /// The slot read in the block at `origin` of a `layout` sized mesh map - fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot { - match self { - Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout }, - other => other.clone(), - } - } - - fn key(&self) -> SlotKey { - match self { - Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)), - Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green), - Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)), - } - } - - /// The slot's color at `uv`, in the file's encoding - fn color(&self, uv: [f32; 2]) -> [f32; 3] { - match self { - Slot::Uniform(value) => *value, - Slot::Image { image, .. } => { - let [red, green, blue, _] = image.sample(uv[0], uv[1]); - [red, green, blue] - } - Slot::Anchor { .. } => [0.0; 3], - } - } - - /// The slot read as a height (its gray) over a `size` block - fn heights(&self, size: (u32, u32)) -> Vec { - match self { - Slot::Anchor { heights, origin, layout } => { - (0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect() - } - _ => block_uvs(size).map(|uv| self.color(uv).iter().sum::() / 3.0).collect(), - } - } - - /// The slot read as a normal over a `size` block: its X and Y, OpenGL convention - fn normals(&self, size: (u32, u32)) -> (Vec, Vec) { - let flip_green = matches!(self, Slot::Image { flip_green: true, .. }); - block_uvs(size) - .map(|uv| { - let [red, green, _] = self.color(uv); - let y = green * 2.0 - 1.0; - (red * 2.0 - 1.0, if flip_green { -y } else { y }) - }) - .unzip() - } -} - /// The UV of each texel's center in a `size` block, row by row fn block_uvs((width, height): (u32, u32)) -> impl Iterator { (0..height).flat_map(move |y| (0..width).map(move |x| [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32])) } -/// A slot as a cache key: an image by identity, a value by its bits -#[derive(Clone)] -enum SlotKey { - Uniform([u32; 3]), - Image(Weak, bool), - Anchor(Weak), -} - -impl PartialEq for SlotKey { - fn eq(&self, other: &SlotKey) -> bool { - match (self, other) { - (SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b, - (SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip, - (SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b), - _ => false, - } - } -} - -/// What a micro map was built from: the mesh map giving its layout, its slots, its settings' bits and its UV tile block -#[derive(Clone)] -struct Key { - map: Weak>, - height: Option, - normal: Option, - settings: Vec, - block: (u32, u32), -} - -impl PartialEq for Key { - fn eq(&self, other: &Key) -> bool { - self.map.strong_count() > 0 - && self.map.ptr_eq(&other.map) - && self.height == other.height - && self.normal == other.normal - && self.settings == other.settings - && self.block == other.block - } -} - -/// Built maps by what they were built from, most recently used last -struct Cache { - entries: Mutex)>>, -} - -impl Cache { - const fn new() -> Cache { - Cache { entries: Mutex::new(Vec::new()) } - } - - /// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work) - fn get_or_build(&self, key: Key, build: impl FnOnce() -> T) -> Arc { - let found = { - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.map.strong_count() > 0); - entries.iter().position(|(cached, _)| *cached == key).map(|index| { - let entry = entries.remove(index); - let built = entry.1.clone(); - entries.push(entry); - built - }) - }; - if let Some(built) = found { - return built; - } - - let built = Arc::new(build()); - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(cached, _)| *cached != key); - entries.push((key, built.clone())); - let mut bytes = 0usize; - let keep = entries - .iter() - .rev() - .take_while(|(_, built)| { - bytes = bytes.saturating_add(built.bytes()); - bytes <= CACHE_BYTES - }) - .count() - .clamp(1, CACHE_ENTRIES); - let excess = entries.len().saturating_sub(keep); - entries.drain(..excess); - built - } -} - -static CURVATURE_CACHE: Cache = Cache::new(); -static OCCLUSION_CACHE: Cache = Cache::new(); +static CURVATURE_CACHE: MicroCache = MicroCache::new(); +static OCCLUSION_CACHE: MicroCache = MicroCache::new(); /// A baked map, its size and the size of one UV tile's block in it type MapLayout = (Arc>, (u32, u32), (u32, u32)); @@ -388,34 +158,12 @@ fn by_blocks(size: (u32, u32), block: (u32, u32), same_in_every_block: bool, per data } -impl MicroCurvature { - /// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map) - pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails) -> Option> { - let (curvature, size, block) = layout(inp, BakedMap::Curvature)?; - let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref())); - let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref())); - let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32]; - let key = Key { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, block }; - - Some(CURVATURE_CACHE.get_or_build(key, || { - let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block); - let term = by_blocks(size, block, same_in_every_block, |origin, block| { - let height = height.as_ref().map(|height| height.in_block(origin, size)); - let normal = normal.as_ref().map(|normal| normal.in_block(origin, size)); - curvature_term(micro, height.as_ref(), normal.as_ref(), block) - }); - let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect(); - MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) } - })) - } -} - /// What the occlusion input is multiplied by: the micro height's occlusion in the baked AO map's layout (None without a baked AO map or a micro height) pub fn micro_occlusion(inp: &Inputs, micro: &MicroDetails) -> Option> { let (occlusion, size, block) = layout(inp, BakedMap::AmbientOcclusion)?; let height = Slot::of(inp, micro.height.then_some(micro.height_source.as_ref())?); let settings = vec![micro.ao_radius.to_bits(), micro.ao_depth.to_bits()]; - let key = Key { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, block }; + let key = CacheKey { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, block }; Some(OCCLUSION_CACHE.get_or_build(key, || { let data = by_blocks(size, block, height.same_in_every_block(), |origin, block| occlusion_factor(micro, &height.in_block(origin, size), block)); @@ -520,7 +268,7 @@ fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { // Three box passes of radius r spread a value with variance r(r + 1) let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize; let mut current = line.to_vec(); - for _ in 0..3 { + for _ in 0..BLUR_BOX_PASSES { box_blur(¤t, out, radius); current.copy_from_slice(out); } @@ -531,7 +279,7 @@ fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { /// `line` blurred into `out` by a sampled gaussian of `sigma`, wrapping around fn kernel_blur(line: &[f32], out: &mut [f32], sigma: f32) { - let reach = (3.0 * sigma).ceil().max(1.0) as i64; + let reach = (KERNEL_REACH_SIGMAS * sigma).ceil().max(1.0) as i64; let weights: Vec = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect(); let total: f32 = weights.iter().sum(); let length = line.len().max(1) as i64; @@ -612,6 +360,8 @@ fn occlusion_factor(micro: &MicroDetails, height: &Slot, size: (u32, u32)) -> Ve #[cfg(test)] mod tests { + use texturecraft_core::GeneratorKind; + use super::*; #[test] diff --git a/crates/compose/src/micro_details/slot.rs b/crates/compose/src/micro_details/slot.rs new file mode 100644 index 00000000..1c5f8c62 --- /dev/null +++ b/crates/compose/src/micro_details/slot.rs @@ -0,0 +1,98 @@ +use std::sync::Arc; + +use texturecraft_core::{NormalFormat, Source}; + +use super::anchor_heights::AnchorHeights; +use super::slot_key::SlotKey; +use super::{anchor_heights, block_uvs}; +use crate::eval::Inputs; +use crate::store::ImageRes; + +/// What a micro details slot reads +#[derive(Clone)] +pub(super) enum Slot { + Uniform([f32; 3]), + Image { + image: Arc, + flip_green: bool, + }, + /// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map + Anchor { + heights: Arc, + origin: (u32, u32), + layout: (u32, u32), + }, +} + +impl Slot { + /// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read) + pub(super) fn of(inp: &Inputs, source: Option<&Source>) -> Slot { + match source { + Some(Source::Uniform(value)) => Slot::Uniform(*value), + Some(Source::Image { name, normal_format }) => match inp.images.get(name) { + Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX }, + None => Slot::Uniform([0.0; 3]), + }, + Some(Source::Anchor { anchor, .. }) => match anchor_heights(inp, *anchor) { + Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) }, + None => Slot::Uniform([0.0; 3]), + }, + _ => Slot::Uniform([0.0; 3]), + } + } + + /// Whether every UV tile block reads the same (an image or a value repeats in each) + pub(super) fn same_in_every_block(&self) -> bool { + !matches!(self, Slot::Anchor { .. }) + } + + /// The slot read in the block at `origin` of a `layout` sized mesh map + pub(super) fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot { + match self { + Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout }, + other => other.clone(), + } + } + + pub(super) fn key(&self) -> SlotKey { + match self { + Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)), + Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green), + Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)), + } + } + + /// The slot's color at `uv`, in the file's encoding + pub(super) fn color(&self, uv: [f32; 2]) -> [f32; 3] { + match self { + Slot::Uniform(value) => *value, + Slot::Image { image, .. } => { + let [red, green, blue, _] = image.sample(uv[0], uv[1]); + [red, green, blue] + } + Slot::Anchor { .. } => [0.0; 3], + } + } + + /// The slot read as a height (its gray) over a `size` block + pub(super) fn heights(&self, size: (u32, u32)) -> Vec { + match self { + Slot::Anchor { heights, origin, layout } => { + (0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect() + } + _ => block_uvs(size).map(|uv| self.color(uv).iter().sum::() / 3.0).collect(), + } + } + + /// The slot read as a normal over a `size` block: its X and Y, OpenGL convention + pub(super) fn normals(&self, size: (u32, u32)) -> (Vec, Vec) { + let flip_green = matches!(self, Slot::Image { flip_green: true, .. }); + block_uvs(size) + .map(|uv| { + let [red, green, _] = self.color(uv); + let y = green * 2.0 - 1.0; + (red * 2.0 - 1.0, if flip_green { -y } else { y }) + }) + .unzip() + } +} diff --git a/crates/compose/src/micro_details/slot_key.rs b/crates/compose/src/micro_details/slot_key.rs new file mode 100644 index 00000000..fdd853e3 --- /dev/null +++ b/crates/compose/src/micro_details/slot_key.rs @@ -0,0 +1,23 @@ +use std::sync::Weak; + +use super::anchor_heights::AnchorHeights; +use crate::store::ImageRes; + +/// A slot as a cache key: an image by identity, a value by its bits +#[derive(Clone)] +pub(super) enum SlotKey { + Uniform([u32; 3]), + Image(Weak, bool), + Anchor(Weak), +} + +impl PartialEq for SlotKey { + fn eq(&self, other: &SlotKey) -> bool { + match (self, other) { + (SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b, + (SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip, + (SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b), + _ => false, + } + } +} diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index bee4012d..76e4d2a6 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -31,6 +31,7 @@ pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 { if axis.weight <= 0.0 { return base; } + let layer = if axis.invert { 1.0 - channels[index] } else { channels[index] }; (base + (blended(axis.blend, base, layer) - base) * axis.weight).clamp(0.0, 1.0) }) @@ -81,11 +82,14 @@ pub(crate) fn adjusted(kind: GeneratorKind, section: &SectionParameters, signal: value.powf(BALANCE_POWER_BASE.powf(2.0 * balance - 1.0)) }; } + value = contrasted(value, section.contrast.clamp(0.0, 1.0)); + if SectionParameters::has_brightness(kind) { let brightness = section.brightness.clamp(*SectionParameters::BRIGHTNESS_RANGE.start(), *SectionParameters::BRIGHTNESS_RANGE.end()); value = if brightness > 0.0 { value + brightness * (1.0 - value) } else { value * (1.0 + brightness) }; } + if section.invert { 1.0 - value } else { value } } diff --git a/crates/compose/src/slot_placement.rs b/crates/compose/src/slot_placement.rs new file mode 100644 index 00000000..69af657b --- /dev/null +++ b/crates/compose/src/slot_placement.rs @@ -0,0 +1,7 @@ +/// Where a generator's image slot is read: `scale` times across the UV square (or the mesh's bounds, triplanar), plus `offset` +pub(crate) struct SlotPlacement { + pub scale: f32, + pub offset: f32, + /// How sharply the three projections meet, or None to read in UV + pub triplanar_contrast: Option, +} diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs index e9042d05..02cf6769 100644 --- a/crates/compose/src/texture_layer.rs +++ b/crates/compose/src/texture_layer.rs @@ -3,20 +3,14 @@ use texturecraft_core::{TextureBlend, TextureLayer}; use texturecraft_geom::glam::{Vec2, Vec3}; +pub(crate) use crate::slot_placement::SlotPlacement; + /// Exponent of the triplanar weights per unit of `1 / (1 − triplanar contrast)`: contrast 0 weighs the axes by the normal itself, 0.5 by its cube const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58; /// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly const MIN_NORMAL_COMPONENT: f32 = 1e-6; -/// Where a generator's image slot is read: `scale` times across the UV square (or the mesh's bounds, triplanar), plus `offset` -pub(crate) struct SlotPlacement { - pub scale: f32, - pub offset: f32, - /// How sharply the three projections meet, or None to read in UV - pub triplanar_contrast: Option, -} - /// The texture is scaled about the centre of the UV square (or of the mesh's bounds) pub(crate) fn texture_placement(texture: &TextureLayer) -> SlotPlacement { SlotPlacement { scale: texture.scale, offset: 0.5 * (1.0 - texture.scale), triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index c4d1af41..b324e4ac 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -6,7 +6,8 @@ use rayon::prelude::*; use texturecraft_core::{BorderDistanceParameters, GeneratorGlobal}; use crate::eval::Inputs; -use crate::working_field::{FieldCache, blur_blocks}; +use crate::field_cache::FieldCache; +use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius}; /// How far in the gradient reaches at Distance 1, in UV units (fitted: about half a UV tile) const REACH_PER_DISTANCE: f32 = 0.4936; @@ -14,9 +15,6 @@ const REACH_PER_DISTANCE: f32 = 0.4936; /// The blur at Smoothness 1, as a gaussian sigma in texels of a 2K UV tile (fitted) const SMOOTHNESS_SIGMA_2K: f32 = 45.0; -/// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at -const REFERENCE_TILE_TEXELS: f32 = 2048.0; - static CACHE: FieldCache = FieldCache::new(); /// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) @@ -52,10 +50,7 @@ fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> // Smoothness blurs the gradient with the empty space around the islands, so their borders soften towards black if border.smoothness > 0.0 { - let radius_at = |tile_texels: f32| { - let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * tile_texels / REFERENCE_TILE_TEXELS; - (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize - }; + let radius_at = |tile_texels: f32| box_radius(border.smoothness * SMOOTHNESS_SIGMA_2K * tile_texels / REFERENCE_TILE_TEXELS); blur_blocks(&mut gradient, (width, height), block, |left, top| radius_at(block.0 as f32 * inp.block_scales.at(left, top))); for (value, texel) in gradient.iter_mut().zip(0..) { if !gbuf.covered(texel) { diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 124ece1b..6ce27082 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -10,8 +10,9 @@ use texturecraft_texel::linear_to_srgb; use texturecraft_texel::noise::cell_hash; use crate::eval::{Inputs, texel_coords}; +use crate::field_cache::FieldCache; use crate::uv_border_distance::border_distances; -use crate::working_field::FieldCache; +use crate::working_field::REFERENCE_TILE_TEXELS; static CACHE: FieldCache = FieldCache::new(); @@ -67,9 +68,6 @@ const MAJOR_LINE_SHADE: f32 = 0.4230; const LINE_HALF_WIDTH_2K: f32 = 1.0; const BORDER_TEXELS_PER_WIDTH_2K: f32 = 15.0; -/// The UV tile resolution the sizes above are measured at -const REFERENCE_TILE_TEXELS: f32 = 2048.0; - /// The saturation and value random island colors are picked within (measured) const RANDOM_SATURATION: std::ops::RangeInclusive = 0.06..=0.57; const RANDOM_VALUE: std::ops::RangeInclusive = 0.42..=0.80; @@ -93,7 +91,7 @@ pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u let (x, y) = (texel % width, texel / width); let texels_2k = REFERENCE_TILE_TEXELS / (block.0 as f32 * inp.block_scales.at(x, y)); // Measured from the texel's 2K sub-texel nearest the border, so a coarser texel still shows the border it holds - let to_border = distances.get(texel as usize).copied().unwrap_or(0.0) * texels_2k - (texels_2k - 1.0).max(0.0); + let to_border = distances.get(texel as usize).copied().unwrap_or(0.0) * texels_2k - footprint_beyond_one(texels_2k); let color = if checker.border_width > 0.0 && to_border <= checker.border_width * BORDER_TEXELS_PER_WIDTH_2K { border } else { @@ -108,6 +106,11 @@ pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u }) } +/// How many 2K texels a working texel `texels_2k` of them wide covers beyond the one at its centre +fn footprint_beyond_one(texels_2k: f32) -> f32 { + (texels_2k - 1.0).max(0.0) +} + /// The checker's sRGB-encoded color at (`x`, `y`) in texels of a 2K UV tile (row 0 at the top) for a texel `texels_2k` of them wide, with `light` its light squares fn checker_color(checker: &UvCheckerParameters, light: [f32; 3], (x, y): (f32, f32), texels_2k: f32) -> [f32; 3] { let square = REFERENCE_TILE_TEXELS / (SQUARES_PER_GRID_TILE * checker.grid_tile.max(1) as f32); @@ -117,7 +120,7 @@ fn checker_color(checker: &UvCheckerParameters, light: [f32; 3], (x, y): (f32, f // Line layers in the reference's order, each laid over the last at the grid's opacity let minor = square / MINOR_LINES_PER_SQUARE; // A texel is on a line when its footprint overlaps the line's band, so lines stay visible on coarser texels - let reach = LINE_HALF_WIDTH_2K + (texels_2k - 1.0).max(0.0) * 0.5; + let reach = LINE_HALF_WIDTH_2K + footprint_beyond_one(texels_2k) / 2.0; let on_line = |position: f32, period: f32| (position - (position / period).round() * period).abs() < reach; let layers = [ (on_line(y, minor) && !on_line(y, square), MINOR_LINE_SHADE), diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 864ae755..14903b8f 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -1,12 +1,11 @@ //! The wear generators' value at a texel (Metal Edge Wear, Fiber Glass Edge Wear, Dirt), fitted to the reference app's observed results -use texturecraft_core::{GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; +use texturecraft_core::{GeneratorKind, Procedural, Projection, WearParameters}; use crate::curvature_sizes::LEVEL_RADII; - +use crate::grunge_pattern::grunge_pattern; use crate::pattern::{Coords, procedural}; -use crate::texture_layer::SlotPlacement; - +use crate::slot_placement::SlotPlacement; use crate::wear_inputs::WearInputs; use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; @@ -21,33 +20,6 @@ const SMOOTHED_SHARE: f32 = 0.5; /// Dirt reads its edges and cavities slightly softened, sigma in texels at 2K const DIRT_CURVATURE_SIGMA: f32 = 1.49; -/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`) -struct GrungePattern { - kind: ProceduralKind, - repeats_per_scale: f32, - rotation: f32, - /// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change - breakup: Option<(ProceduralKind, f32)>, - mean: f32, - spread: f32, - /// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner) - custom_gain: f32, -} - -/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt -const EDGE_WEAR_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 }; -const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { - kind: ProceduralKind::Weave, - repeats_per_scale: 16.0, - rotation: 45.0, - breakup: Some((ProceduralKind::Grunge, 4.0)), - mean: 0.539, - spread: 0.198, - custom_gain: 1.9, -}; -const DIRT_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 }; /// How much a breakup pattern varies the grunge's strength (0 none, 1 down to nothing) const BREAKUP_DEPTH: f32 = 0.6; @@ -69,14 +41,6 @@ pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { } } -fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern { - match kind { - GeneratorKind::Dirt => &DIRT_GRUNGE, - GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, - _ => &EDGE_WEAR_GRUNGE, - } -} - fn triplanar_sharpness(wear: &WearParameters) -> f32 { TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast } @@ -195,6 +159,7 @@ mod tests { use texturecraft_geom::glam::{Vec2, Vec3}; use super::*; + use crate::grunge_pattern::{DIRT_GRUNGE, EDGE_WEAR_GRUNGE, FIBER_GLASS_GRUNGE}; fn inputs(curvature: f32, occlusion: f32) -> WearInputs { WearInputs { curvature, blurred_curvature: curvature, occlusion, grunge: 0.0 } diff --git a/crates/compose/src/working_field.rs b/crates/compose/src/working_field.rs index 55c3763b..5c4e9c49 100644 --- a/crates/compose/src/working_field.rs +++ b/crates/compose/src/working_field.rs @@ -1,98 +1,9 @@ //! Whole-map fields some generators precompute at the working resolution (UV Border Distance, Dripping Rust), built once per layout, mesh map and settings -use std::sync::{Arc, Mutex, Weak}; - -use texturecraft_core::BlockScales; - use crate::eval::{Inputs, blur}; -/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) -const CACHE_ENTRIES: usize = 8; -const CACHE_BYTES: usize = 256 << 20; - -/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile -const FINGERPRINT_STRIDE: usize = 31; - -/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh, the mesh maps it reads and its settings' bits -#[derive(Clone)] -struct Key { - layout: usize, - size: (u32, u32), - fingerprint: u64, - block: (u32, u32), - scales: BlockScales, - mesh: (usize, usize), - maps: Vec>>, - settings: Vec, -} - -impl PartialEq for Key { - fn eq(&self, other: &Key) -> bool { - let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); - same_maps - && self.layout == other.layout - && self.size == other.size - && self.fingerprint == other.fingerprint - && self.block == other.block - && self.scales == other.scales - && self.mesh == other.mesh - && self.settings == other.settings - } -} - -/// Built fields by what they were built from, most recently used last -pub(crate) struct FieldCache { - entries: Mutex>)>>, -} - -impl FieldCache { - pub(crate) const fn new() -> FieldCache { - FieldCache { entries: Mutex::new(Vec::new()) } - } - - /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work - pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { - let gbuf = inp.gbuf; - let block = working_block(inp); - let key = Key { - layout: gbuf.tri.as_ptr() as usize, - size: (gbuf.width, gbuf.height), - fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), - block, - scales: inp.block_scales.clone(), - mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), - maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), - settings, - }; - - let cached = { - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); - entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) - }; - if let Some(field) = cached { - return field; - } - - let field = Arc::new(build(block)); - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(cached, _)| *cached != key); - entries.push((key, field.clone())); - let mut bytes = 0usize; - let keep = entries - .iter() - .rev() - .take_while(|(_, built)| { - bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); - bytes <= CACHE_BYTES - }) - .count() - .clamp(1, CACHE_ENTRIES); - let excess = entries.len().saturating_sub(keep); - entries.drain(..excess); - field - } -} +/// The resolution of a UV tile the generators' fitted sizes are measured at +pub(crate) const REFERENCE_TILE_TEXELS: f32 = 2048.0; /// The size of one UV tile's block in `inp`'s working atlas pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { @@ -102,6 +13,11 @@ pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))) } +/// The box radius whose repeated passes approximate a Gaussian of `sigma` +pub(crate) fn box_radius(sigma: f32) -> usize { + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize +} + /// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges pub(crate) fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { for top in (0..height).step_by(block.1 as usize) { diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs index b9bd92ea..3dcc0d46 100644 --- a/crates/compose/tests/generator_texture.rs +++ b/crates/compose/tests/generator_texture.rs @@ -160,6 +160,18 @@ fn overlay_with_a_mid_gray_texture_doubles_a_dark_signal_times_the_gray() { assert_all(&mask(&mut fixture, generator, &texels), OCCLUSION + (overlay - OCCLUSION) * 0.5, "overlay at half opacity"); } +#[test] +fn an_image_not_loaded_blends_black_with_or_without_a_blur() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let loading = occlusion_with("not loaded yet", TextureLayer { opacity: 0.5, ..replacing() }); + assert_all(&mask(&mut fixture, loading.clone(), &texels), OCCLUSION * 0.5, "per texel"); + + let mut blurred = loading; + blurred.global.blur = 0.5; + assert_all(&mask(&mut fixture, blurred, &texels), OCCLUSION * 0.5, "over a region, as the blur computes it"); +} + #[test] fn the_texture_blends_after_the_section_controls_and_before_the_global_ones() { let mut fixture = fixture([0.6; 3]); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 62db399d..2e4371b5 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1098,6 +1098,8 @@ impl GeneratorKind { pub fn parse(name: &str) -> Option { let normalised = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); + let wanted = normalised(name); + // The labels before the reference app's names, which agents may still send let earlier = |kind: GeneratorKind| match kind { GeneratorKind::EdgeWear => Some("Mask Editor: Edge wear"), @@ -1106,7 +1108,6 @@ impl GeneratorKind { _ => None, }; GeneratorKind::ALL.into_iter().find(|kind| { - let wanted = normalised(name); normalised(kind.id()) == wanted || normalised(kind.label()) == wanted || earlier(*kind).is_some_and(|label| normalised(label) == wanted) }) } diff --git a/crates/engine/src/generator_input.rs b/crates/engine/src/generator_input.rs new file mode 100644 index 00000000..4a5c65e0 --- /dev/null +++ b/crates/engine/src/generator_input.rs @@ -0,0 +1,12 @@ +use texturecraft_core::BakedMap; + +/// A generator input a command names: a mesh map it reads, its texture or its custom grunge +#[derive(Clone, Copy)] +pub(crate) enum GeneratorInput { + Map(BakedMap), + Texture, + Grunge, + MicroHeight, + MicroNormal, + Image, +} diff --git a/crates/engine/src/generator_pick.rs b/crates/engine/src/generator_pick.rs index b6195451..b0e9ea0f 100644 --- a/crates/engine/src/generator_pick.rs +++ b/crates/engine/src/generator_pick.rs @@ -46,7 +46,8 @@ fn pick_point(session: &mut Session, params: &Value) -> Result { let viewport = viewport_of(session, params); let screen = match (f32p(params, "x"), f32p(params, "y")) { (Some(x), Some(y)) => Vec2::new(x, y), - _ => viewport * 0.5, + (None, None) => viewport * 0.5, + _ => return Err(bad(CMD, "give both `x` and `y`, or neither for the viewport's centre")), }; let hit = session.pick(screen, viewport).ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; let picked = across_bounds(hit.pos, session.mesh.bounds()).to_array().map(|coordinate| coordinate.clamp(0.0, 1.0)); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index bc0efe3c..14863420 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -153,6 +153,15 @@ fn generator_json(generator: &Generator) -> Value { if !generator.inputs.is_empty() { out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::>().into(); } + if let Some(wear) = &generator.wear { + out["wear"] = json!(wear); + } + if let Some(section) = &generator.section { + out["section"] = json!(section); + } + if let Some(light) = &generator.light { + out["light"] = json!(light); + } if let Some(texture) = &generator.texture { out["texture"] = json!(texture); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 82d395ce..cb0519b8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod filter_about; pub mod filter_lib; pub mod folder_cmds; mod frame_target; +mod generator_input; pub mod generator_pick; pub mod id_mask_view; pub mod inspect; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e7ef1e7a..a746f431 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -10,6 +10,7 @@ use texturecraft_core::{ use crate::anchored_micro_edit::AnchoredMicroEdit; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::distance_params::distance_from; +use crate::generator_input::GeneratorInput; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; use crate::micro_params::{MICRO_HEIGHT_INPUT, MICRO_NORMAL_INPUT, micro_from, swapped_micro}; @@ -391,7 +392,6 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { push_effect(session, params, EffectKind::Fill { source, projection, sampling }, blend) } -/// Apply `params` to `generator`, using `command` in errors /// The parameters that drive the wear generators' earlier model const EARLIER_WEAR_KEYS: [&str; 7] = ["level", "softness", "noise", "noiseScale", "offset", "mode", "sizes"]; @@ -550,6 +550,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res None => Ok(()), }; } + if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) { return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); } @@ -576,10 +577,12 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res generator.light = None; return Ok(()); } + let on_light = generator.light.is_some() || (light_defaults.is_some() && !new_keys.is_empty()); if on_light && GLOBAL_KEYS.iter().any(|key| params.get(*key).is_some()) { return Err(bad(command, "Light has no global blur, balance or contrast on its light controls")); } + if new_keys.is_empty() { return Ok(()); } @@ -594,6 +597,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res generator.global = defaults.global; } } + if let Some(defaults) = light_defaults { let light = generator.light.get_or_insert(defaults); for (key, value) in [ @@ -623,9 +627,11 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res *value = given; } } + if let Some(invert) = boolp(params, "sectionInvert") { section.invert = invert; } + for (axis, name) in section.axes.iter_mut().zip(AXIS_NAMES) { if let Some(invert) = boolp(params, &format!("{name}Invert")) { axis.invert = invert; @@ -639,6 +645,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res axis.blend = AxisBlend::parse(blend_name).ok_or_else(|| bad(command, format!("unknown blending mode `{blend_name}`")))?; } } + generator.section = Some(section.clamped(kind)); texture_from(command, params, generator) } @@ -695,6 +702,7 @@ pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { } } +/// Apply `params` to `generator`, using `command` in errors fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; section_from(command, params, generator)?; @@ -790,17 +798,6 @@ fn add_anchor(session: &mut Session, params: &Value) -> Result { push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal) } -/// A generator input a command names: a mesh map it reads, its texture or its custom grunge -#[derive(Clone, Copy)] -enum GeneratorInput { - Map(BakedMap), - Texture, - Grunge, - MicroHeight, - MicroNormal, - Image, -} - /// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; diff --git a/crates/ui-egui/src/generator_kind_rows.rs b/crates/ui-egui/src/generator_kind_rows.rs index 8b3e8960..e6df474c 100644 --- a/crates/ui-egui/src/generator_kind_rows.rs +++ b/crates/ui-egui/src/generator_kind_rows.rs @@ -15,16 +15,6 @@ use crate::i18n::{tr, trf}; use crate::property_sheet::{NumberField, PropertySheet, StackSlider}; use crate::theme::AXIS_COLORS; -/// A 0..1 setting in the stack beside the preview -fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { - StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } -} - -/// A whole-number setting in the stack beside the preview -fn stacked_whole<'a>(label: &'a str, value: &'a mut f32, range: std::ops::RangeInclusive) -> StackSlider<'a> { - StackSlider { label, value, range: range.clone(), typed: range, decimals: 0, suffix: "", dial: false } -} - /// The first edit of a stack beside the preview fn first_edit(edits: [Option; N]) -> Option { edits.into_iter().flatten().next() @@ -111,7 +101,7 @@ fn distance_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: DistanceParamete suffix: "", dial: false, }; - let mut stack = [radius, stacked(tr("Offset"), &mut edited.offset), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut stack = [radius, StackSlider::unit(tr("Offset"), &mut edited.offset), StackSlider::unit(tr("Contrast"), &mut edited.contrast)]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(point_row(sheet, tr("3D Position"), &mut edited.point, PointPick { effect: id, point: "distance" })); sent(edit, KindControls::Distance(edited)) @@ -120,7 +110,7 @@ fn distance_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: DistanceParamete /// 3D Linear Gradient: Balance and Contrast beside the preview, then its start and end fn linear_gradient_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: LinearGradientParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { let mut edited = shown; - let mut stack = [stacked(tr("Balance"), &mut edited.balance), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut stack = [StackSlider::unit(tr("Balance"), &mut edited.balance), StackSlider::unit(tr("Contrast"), &mut edited.contrast)]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(point_row(sheet, tr("3D Position Start"), &mut edited.start, PointPick { effect: id, point: "start" })); edit = edit.or(point_row(sheet, tr("3D Position End"), &mut edited.end, PointPick { effect: id, point: "end" })); @@ -130,8 +120,11 @@ fn linear_gradient_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: LinearGra /// UV Border Distance: Distance, Smoothness and Balance beside the preview, then Contrast fn border_rows(sheet: &mut PropertySheet<'_>, shown: BorderDistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { let mut edited = shown; - let mut stack = - [stacked(tr("Distance"), &mut edited.distance), stacked(tr("Smoothness"), &mut edited.smoothness), stacked(tr("Balance"), &mut edited.balance)]; + let mut stack = [ + StackSlider::unit(tr("Distance"), &mut edited.distance), + StackSlider::unit(tr("Smoothness"), &mut edited.smoothness), + StackSlider::unit(tr("Balance"), &mut edited.balance), + ]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(sheet.slider(tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); sent(edit, KindControls::BorderDistance(edited)) @@ -147,9 +140,9 @@ fn grayscale_rows(sheet: &mut PropertySheet<'_>, shown: GrayscaleConversionParam edit = Some(false); } let mut stack = [ - stacked(tr("Balance"), &mut edited.balance), - stacked(tr("Contrast"), &mut edited.contrast), - stacked_whole(tr("Tile"), &mut edited.tile, GrayscaleConversionParameters::TILE_RANGE), + StackSlider::unit(tr("Balance"), &mut edited.balance), + StackSlider::unit(tr("Contrast"), &mut edited.contrast), + StackSlider::whole(tr("Tile"), &mut edited.tile, GrayscaleConversionParameters::TILE_RANGE), ]; edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); edited.tile = edited.tile.round(); @@ -164,9 +157,9 @@ fn grayscale_rows(sheet: &mut PropertySheet<'_>, shown: GrayscaleConversionParam fn rust_rows(sheet: &mut PropertySheet<'_>, shown: DrippingRustParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { let mut edited = shown; let mut stack = [ - stacked(tr("Rust Spreading"), &mut edited.spreading), - stacked(tr("Rust Contrast"), &mut edited.contrast), - stacked(tr("Spreading Smoothness"), &mut edited.spreading_smoothness), + StackSlider::unit(tr("Rust Spreading"), &mut edited.spreading), + StackSlider::unit(tr("Rust Contrast"), &mut edited.contrast), + StackSlider::unit(tr("Spreading Smoothness"), &mut edited.spreading_smoothness), ]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(sheet.slider(tr("Drips Intensity"), &mut edited.drips_intensity, 0.0..=1.0, 2)); @@ -273,9 +266,9 @@ fn checker_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, shown: let mut tile = edited.grid_tile as f32; let tiles = *UvCheckerParameters::GRID_TILE_RANGE.start() as f32..=*UvCheckerParameters::GRID_TILE_RANGE.end() as f32; let mut stack = [ - stacked_whole(tr("Checker Grid Tile"), &mut tile, tiles), - stacked(tr("Checker Grid Opacity"), &mut edited.grid_opacity), - stacked(tr("UV Borders Width"), &mut edited.border_width), + StackSlider::whole(tr("Checker Grid Tile"), &mut tile, tiles), + StackSlider::unit(tr("Checker Grid Opacity"), &mut edited.grid_opacity), + StackSlider::unit(tr("UV Borders Width"), &mut edited.border_width), ]; edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); edited.grid_tile = tile.round() as u32; diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs index 00fd88d2..879efecc 100644 --- a/crates/ui-egui/src/generator_params.rs +++ b/crates/ui-egui/src/generator_params.rs @@ -119,7 +119,7 @@ pub(crate) fn kind_params(controls: &KindControls) -> Value { "dripsIntensity": rust.drips_intensity, "dripsSmoothness": rust.drips_smoothness, "dripsSamples": rust.drips_samples, - "dripsAxis": DRIPS_AXES.get(usize::from(rust.axis)).copied().unwrap_or("y"), + "dripsAxis": DRIPS_AXES.get(usize::from(rust.axis)).copied().unwrap_or(DEFAULT_DRIPS_AXIS), }), KindControls::UvRandomColor(random) => { let mut params = json!({ @@ -148,6 +148,9 @@ pub(crate) fn kind_params(controls: &KindControls) -> Value { /// Dripping Rust's `dripsAxis` names, by axis pub(crate) const DRIPS_AXES: [&str; 3] = ["x", "y", "z"]; +/// The axis drips run along when a saved one is out of range: down Y, as new ones do +const DEFAULT_DRIPS_AXIS: &str = "y"; + /// Every micro details control a generator of `kind` has, set to `micro` (its images are the `microHeight` and `microNormal` inputs) pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { let mut params = json!({ diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs index 72712c84..4fd3d591 100644 --- a/crates/ui-egui/src/generator_point_pick.rs +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -25,6 +25,16 @@ pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { set(ctx, next); } +/// The armed pick while its effect is still the selected one; a pick whose effect was deselected or deleted is dropped +pub(crate) fn armed_on(ctx: &egui::Context, session: &texturecraft_engine::Session) -> Option { + let armed = armed(ctx)?; + if session.target == texturecraft_engine::StackTarget::Effect(texturecraft_engine::core::LayerId(armed.effect)) { + return Some(armed); + } + set(ctx, None); + None +} + pub(crate) fn set(ctx: &egui::Context, pick: Option) { ctx.data_mut(|data| data.insert_temp(pick_id(), pick)); } diff --git a/crates/ui-egui/src/generator_section_rows.rs b/crates/ui-egui/src/generator_section_rows.rs index 38377af0..40c58353 100644 --- a/crates/ui-egui/src/generator_section_rows.rs +++ b/crates/ui-egui/src/generator_section_rows.rs @@ -14,19 +14,14 @@ use crate::i18n::tr; use crate::property_sheet::{PropertySheet, StackSlider}; use crate::theme::AXIS_COLORS; -/// A 0..1 setting in the stack beside the preview -fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { - StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } -} - /// Global Invert, then the preview beside Global Blur, Balance and Contrast: what every generator applies to its finished value pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, picture: &dyn Fn(&Painter, Rect)) { let (mut invert, mut global) = (generator.invert, generator.global); let invert_edit = sheet.toggle(tr("Global Invert"), &mut invert).then_some(false); let mut stack = [ - stacked(tr("Global Blur"), &mut global.blur), - stacked(tr("Global Balance"), &mut global.balance), - stacked(tr("Global Contrast"), &mut global.contrast), + StackSlider::unit(tr("Global Blur"), &mut global.blur), + StackSlider::unit(tr("Global Balance"), &mut global.balance), + StackSlider::unit(tr("Global Contrast"), &mut global.contrast), ]; let stack_edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if let Some(merge) = invert_edit.or(stack_edit) { diff --git a/crates/ui-egui/src/generator_wear_rows.rs b/crates/ui-egui/src/generator_wear_rows.rs index c103ab72..3d7d15c6 100644 --- a/crates/ui-egui/src/generator_wear_rows.rs +++ b/crates/ui-egui/src/generator_wear_rows.rs @@ -11,11 +11,6 @@ use crate::generator_params::{light_params, merged, micro_params, wear_params}; use crate::i18n::tr; use crate::property_sheet::{PropertySheet, StackSlider}; -/// A 0..1 setting in the stack beside the preview -fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { - StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } -} - /// The wear controls of generator effect `id` on `layer` in the reference's order, showing `wear`; `picture` draws the preview pub(crate) fn wear_rows( app: &mut TextureCraftApp, @@ -38,8 +33,11 @@ pub(crate) fn wear_rows( let dirt = kind == GeneratorKind::Dirt; let (level_label, contrast_label) = if dirt { (tr("Dirt Level"), tr("Dirt Contrast")) } else { (tr("Wear Level"), tr("Wear Contrast")) }; let mut edited = wear; - let mut stack = - [stacked(level_label, &mut edited.level), stacked(contrast_label, &mut edited.contrast), stacked(tr("Grunge Amount"), &mut edited.grunge_amount)]; + let mut stack = [ + StackSlider::unit(level_label, &mut edited.level), + StackSlider::unit(contrast_label, &mut edited.contrast), + StackSlider::unit(tr("Grunge Amount"), &mut edited.grunge_amount), + ]; let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if kind != GeneratorKind::FiberGlassEdgeWear { edit = edit.or(sheet.slider(tr("Grunge Scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); @@ -106,7 +104,7 @@ pub(crate) fn light_rows( let mut stack = [ angle(tr("Horizontal Angle"), &mut edited.horizontal), angle(tr("Vertical Angle"), &mut edited.vertical), - stacked(tr("Light Attenuation"), &mut edited.attenuation), + StackSlider::unit(tr("Light Attenuation"), &mut edited.attenuation), ]; let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); edit = edit.or(sheet.slider(tr("Highlight Glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); diff --git a/crates/ui-egui/src/property_sheet/stack_slider.rs b/crates/ui-egui/src/property_sheet/stack_slider.rs index 9297e9b9..f14da76e 100644 --- a/crates/ui-egui/src/property_sheet/stack_slider.rs +++ b/crates/ui-egui/src/property_sheet/stack_slider.rs @@ -21,3 +21,15 @@ pub(crate) struct StackSlider<'a> { /// An angle: a small dial before its value, as an angle row has pub(crate) dial: bool, } + +impl<'a> StackSlider<'a> { + /// A 0..1 setting with two decimals + pub(crate) fn unit(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } + } + + /// A whole-number setting across `range` + pub(crate) fn whole(label: &'a str, value: &'a mut f32, range: RangeInclusive) -> StackSlider<'a> { + StackSlider { label, value, range: range.clone(), typed: range, decimals: 0, suffix: "", dial: false } + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 473eaf29..92c07e7e 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -865,7 +865,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // A 3D generator's armed point pick: a click sets the point there instead of painting - let point_pick = crate::generator_point_pick::armed(ui.ctx()); + let point_pick = crate::generator_point_pick::armed_on(ui.ctx(), &app.session); if let Some(pick) = point_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 809fc048..126f7be5 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -19,7 +19,7 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { - slider_inner(ui, label, value, range, decimals, "").0 + slider_inner(ui, label, value, range, decimals).0 } /// For an editor `id` drawn every frame: `Some(merge)` when it `changed`, merge true for a press's later changes (one undo step per drag; typing never merges) @@ -57,12 +57,7 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { /// true for the later changes of one drag, so the edit that applies them (with the command's /// `merge` param) continues the drag's first undo step. pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> Option { - slider_inner(ui, label, value, range, decimals, "").1 -} - -/// [`slider_edit`] showing `suffix` after the value (a unit such as °), which a typed value may leave out -pub fn slider_edit_with_suffix(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> Option { - slider_inner(ui, label, value, range, decimals, suffix).1 + slider_inner(ui, label, value, range, decimals).1 } /// Least width of a slider's value field, wide enough for a short number @@ -80,24 +75,12 @@ const SLIDER_KNOB_RADIUS: f32 = 4.5; /// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { - suffixed_value_header(ui, label, value, range, decimals, "") -} - -/// [`value_header`] showing `suffix` after the value, which a typed value may leave out -fn suffixed_value_header( - ui: &mut Ui, - label: &str, - value: &mut f32, - range: std::ops::RangeInclusive, - decimals: usize, - suffix: &str, -) -> (egui::Id, Option) { let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() - .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}{suffix}"), font.clone(), tokens.text).size().x) + .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) .fold(SLIDER_VALUE_MIN_WIDTH, f32::max); let mut edit = None; let field = ui @@ -105,7 +88,7 @@ fn suffixed_value_header( ui.label(RichText::new(label).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - let shown = format!("{value:.decimals$}{suffix}"); + let shown = format!("{value:.decimals$}"); // Keep unfinished input while the document value is re-read each frame let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); @@ -128,7 +111,7 @@ fn suffixed_value_header( if response.lost_focus() && !escape && text != shown - && let Ok(parsed) = text.trim().strip_suffix(suffix).unwrap_or(text.trim()).trim_end().parse::() + && let Ok(parsed) = text.trim().parse::() && parsed.is_finite() && parsed.clamp(minimum, maximum) != *value { @@ -144,10 +127,10 @@ fn suffixed_value_header( (field, edit) } -fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> (Response, Option) { +fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { let (minimum, maximum) = (*range.start(), *range.end()); let width = ui.available_width(); - let (field, mut edit) = suffixed_value_header(ui, label, value, range, decimals, suffix); + let (field, mut edit) = value_header(ui, label, value, range, decimals); let (rect, mut response) = ui.allocate_exact_size(vec2(width, SLIDER_TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index a191e641..edce0259 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -1,4 +1,4 @@ -//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all). +//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all) use egui::accesskit::Role; use egui_kittest::Harness; @@ -64,8 +64,7 @@ fn dragging_a_slider_applies_it() { assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); } -/// A generator slider applies while it is dragged (the texture follows the pointer), and the -/// whole drag is one undo step. +/// A generator slider applies while it is dragged (the texture follows the pointer), and the whole drag is one undo step #[test] fn dragging_a_generator_slider_applies_live_as_one_undo_step() { let (mut harness, effect) = selected_generator(); @@ -112,7 +111,7 @@ fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> e harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Click the balance's value to type in it and press `keys`, then type `text`, one key per frame like a person. +/// Click the balance's value to type in it and press `keys`, then type `text`, one key per frame like a person fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { harness.get_by_label("Global Balance value").click(); harness.run_steps(2); @@ -140,8 +139,7 @@ fn a_value_typed_in_the_number_field_applies() { assert_eq!(harness.state().session.history_labels().len(), steps + 1); } -/// Dragging the track while the number field has focus drops what was typed there: leaving the -/// field afterwards does not undo the drag. +/// Dragging the track while the value is being typed drops what was typed: leaving the field afterwards does not undo the drag #[test] fn a_track_drag_drops_text_typed_in_the_number_field() { let (mut harness, effect) = selected_generator(); @@ -165,8 +163,7 @@ fn a_track_drag_drops_text_typed_in_the_number_field() { assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); } -/// Leaving the number field without typing, or with Escape, keeps the value (not the rounded -/// text the field shows) and makes no undo step. +/// Leaving the value without typing, or with Escape, keeps it (not the rounded text shown) and makes no undo step #[test] fn leaving_the_number_field_unchanged_keeps_the_value() { let (mut harness, effect) = selected_generator(); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index e191d8b0..0c673fce 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -1,4 +1,4 @@ -//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator. +//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator use egui::Role; use egui_kittest::Harness; @@ -10,7 +10,7 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::theme::Brightness; -/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. +/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { harness_with(render, json!({"generator": "curvature"})) } @@ -394,9 +394,22 @@ fn is_on(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> boo harness.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) } +#[test] +fn restore_defaults_puts_a_kind_with_its_own_controls_back() { + let added = json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]], "gradientPositions": [0.0, 0.3, 1.0], "seed": 4}); + let (mut harness, effect) = harness_with(false, added); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "gradientQuantity": 2})).unwrap(); + harness.run_steps(3); + + click_live(&mut harness, Role::Button, "Restore defaults"); + + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::UvRandomColor), "colors, places and count back to the kind's"); + assert!(harness.get_by_role_and_label(Role::Button, "Restore defaults").accesskit_node().is_disabled(), "nothing left to restore"); +} + #[test] fn a_point_pick_waits_for_the_view_until_escape() { - let (mut harness, _) = harness_with(false, json!({"generator": "3dLinearGradient"})); + let (mut harness, effect) = harness_with(false, json!({"generator": "3dLinearGradient"})); let (start, end) = ("Pick 3D Position Start on the mesh", "Pick 3D Position End on the mesh"); assert!(!is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end)); @@ -410,6 +423,15 @@ fn a_point_pick_waits_for_the_view_until_escape() { harness.key_press(egui::Key::Escape); harness.run_steps(3); assert!(!is_on(&harness, Role::Button, start), "Esc cancels the pick"); + + // Selecting something else drops the pick: coming back finds it disarmed + click_live(&mut harness, Role::Button, end); + let layer = harness.state().session.doc.project.effect(effect).unwrap().0; + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap(); + harness.run_steps(3); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + harness.run_steps(3); + assert!(!is_on(&harness, Role::Button, end), "a pick left behind is dropped"); } #[test] diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index bea73433..dcc4fee8 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -723,7 +723,6 @@ fn nested_layers_snapshot() { save(&mut harness, &output_dir, "panel-layers-narrow-nested"); } -/// The mask anchor and generator micro controls in the integrated properties panel #[test] #[ignore] fn path_tool_snapshots() { From 9519f35873d6b0a8cb436d278fff027ed845f606 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:37:03 +0000 Subject: [PATCH 117/153] Generators: second review round (one box radius formula, named cache key fields, tests for inspect and a half-given pick pixel) --- crates/compose/src/eval.rs | 4 +++- crates/compose/src/field_cache.rs | 3 ++- crates/compose/src/field_cache_key.rs | 7 +++++-- crates/compose/src/micro_details/mod.rs | 4 +--- crates/compose/src/sections.rs | 4 +--- crates/compose/src/working_field.rs | 2 +- crates/engine/tests/it/generator_sections.rs | 13 +++++++++++++ .../engine/tests/it/generator_three_d_distance.rs | 1 + crates/ui-egui/src/generator_point_pick.rs | 11 +++++++---- crates/ui-egui/tests/it/generator_panel.rs | 3 +++ 10 files changed, 37 insertions(+), 15 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a98e07a9..a1a58358 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3634,15 +3634,17 @@ impl<'a, 'b> Texel<'a, 'b> { Some(((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32)) } - /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]) fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { let ramp = self.generator_ramp(generator, maps); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + // An image still loading reads black, as it does where blur or resolution compute the generator over a region let textured = match generator.texture_in_use() { Some(texture) => texture_layer::blended_over(texture, adjusted, self.generator_texture(generator).unwrap_or(0.0)), None => adjusted, }; + finish_generator(generator, textured) } diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 910ce75c..1458cb3f 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -31,7 +31,8 @@ impl FieldCache { fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), block, scales: inp.block_scales.clone(), - mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len(), inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), + positions: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), + uvs: (inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), settings, }; diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs index fa84471e..d29d80f5 100644 --- a/crates/compose/src/field_cache_key.rs +++ b/crates/compose/src/field_cache_key.rs @@ -10,7 +10,9 @@ pub(crate) struct FieldCacheKey { pub(crate) fingerprint: u64, pub(crate) block: (u32, u32), pub(crate) scales: BlockScales, - pub(crate) mesh: (usize, usize, usize, usize), + /// The mesh's positions and UVs, each by address and length: a UV edit changes island fields + pub(crate) positions: (usize, usize), + pub(crate) uvs: (usize, usize), pub(crate) maps: Vec>>, pub(crate) settings: Vec, } @@ -24,7 +26,8 @@ impl PartialEq for FieldCacheKey { && self.fingerprint == other.fingerprint && self.block == other.block && self.scales == other.scales - && self.mesh == other.mesh + && self.positions == other.positions + && self.uvs == other.uvs && self.settings == other.settings } } diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index cc4bf6e4..ca5fa213 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -24,9 +24,7 @@ use texturecraft_core::{BakedMap, LayerId, MicroCurvatureType, MicroDetails}; use crate::below::StackKey; use crate::eval::{BLUR_BOX_PASSES, Inputs}; - -/// The resolution of a UV tile the reference's micro details were measured at: derivatives and radii are per texel at this size -const REFERENCE_TILE_TEXELS: f32 = 2048.0; +use crate::working_field::REFERENCE_TILE_TEXELS; /// How steeply the micro height tilts the normal it is turned into, per unit of Height Details Intensity (fitted) const HEIGHT_NORMAL_STRENGTH: f32 = 5.9; diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index 76e4d2a6..297a086a 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -66,9 +66,7 @@ pub(crate) fn generator_blur_sigma(generator: &Generator) -> f32 { /// The radius of the three box passes that blur like the section blur at `resolution` texels per side pub(crate) fn blur_radius_at(kind: GeneratorKind, section: &SectionParameters, resolution: u32) -> usize { let sigma = blur_sigma(kind, section) * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION; - - // Three boxes of radius r spread a texel with variance r (r + 1) - (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize + crate::working_field::box_radius(sigma) } /// `signal` after the section's balance, contrast, brightness and invert, as far as a generator of `kind` has them diff --git a/crates/compose/src/working_field.rs b/crates/compose/src/working_field.rs index 5c4e9c49..246e95b0 100644 --- a/crates/compose/src/working_field.rs +++ b/crates/compose/src/working_field.rs @@ -13,7 +13,7 @@ pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))) } -/// The box radius whose repeated passes approximate a Gaussian of `sigma` +/// The radius of three box passes that blur like a gaussian of `sigma`: three boxes of radius r spread a texel with variance r (r + 1) pub(crate) fn box_radius(sigma: f32) -> usize { (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index ed9276f0..29311091 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -154,3 +154,16 @@ fn the_offset_belongs_to_the_earlier_model() { assert!(execute(&mut session, "effect.set", &both).is_err(), "{kind}: offset and the reference controls at once are refused"); } } + +#[test] +fn inspect_reports_the_reference_controls_set() { + let mut session = session(); + add(&mut session, json!({"generator": "position", "sectionContrast": 0.25})); + add(&mut session, json!({"generator": "direction", "lightHorizontal": 90.0})); + add(&mut session, json!({"generator": "dirt", "wearLevel": 0.125})); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + for (key, value) in [("section", "\"contrast\":0.25"), ("light", "\"horizontal\":90.0"), ("wear", "\"level\":0.125")] { + assert!(inspected.contains(&format!("\"{key}\"")) && inspected.contains(value), "{key} with {value} in {inspected}"); + } +} diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 735bef45..7866b622 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -215,6 +215,7 @@ fn picking_on_the_mesh_sets_the_point() { let missed = json!({"effect": distance, "x": 0.0, "y": 0.0, "viewport": [512, 512]}); assert!(execute(&mut session, "effect.generator.pickPoint", &missed).is_err(), "a corner off the mesh picks nothing"); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance, "x": 10.0})).is_err(), "a pixel needs both coordinates"); assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance, "point": "end"})).is_err()); let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": curvature})).is_err()); diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs index 4fd3d591..4b876e78 100644 --- a/crates/ui-egui/src/generator_point_pick.rs +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -1,5 +1,8 @@ //! Picking a 3D generator's point on the mesh: its crosshair button arms it, the next click in the 3D view sets the point, Esc or the button again cancels +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, StackTarget}; + /// Which point of which generator effect the next click in the 3D view sets #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct PointPick { @@ -26,10 +29,10 @@ pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { } /// The armed pick while its effect is still the selected one; a pick whose effect was deselected or deleted is dropped -pub(crate) fn armed_on(ctx: &egui::Context, session: &texturecraft_engine::Session) -> Option { - let armed = armed(ctx)?; - if session.target == texturecraft_engine::StackTarget::Effect(texturecraft_engine::core::LayerId(armed.effect)) { - return Some(armed); +pub(crate) fn armed_on(ctx: &egui::Context, session: &Session) -> Option { + let pick = armed(ctx)?; + if session.target == StackTarget::Effect(LayerId(pick.effect)) { + return Some(pick); } set(ctx, None); None diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 0c673fce..5d2e24b1 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -427,10 +427,13 @@ fn a_point_pick_waits_for_the_view_until_escape() { // Selecting something else drops the pick: coming back finds it disarmed click_live(&mut harness, Role::Button, end); let layer = harness.state().session.doc.project.effect(effect).unwrap().0; + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap(); harness.run_steps(3); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); harness.run_steps(3); + assert!(!is_on(&harness, Role::Button, end), "a pick left behind is dropped"); } From 0402ba32a5a9ba6b46fa0f2bc58f0fe79cb477ec Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:49:45 +0000 Subject: [PATCH 118/153] Generators: the panel's preview shows the generator as set, rendered one at a time while its settings change --- crates/engine/src/orb_preview.rs | 36 ++++++++++++++++++----- crates/ui-egui/src/generator_panel.rs | 16 ++++++---- crates/ui-egui/src/preview_request.rs | 3 ++ crates/ui-egui/src/preview_worker.rs | 15 +++++++++- crates/ui-egui/src/shelf.rs | 10 +++++-- crates/ui-egui/src/shelf_preview.rs | 34 +++++++++++++++++++++- crates/ui-egui/src/thumbs.rs | 42 +++++++++++++++++++++++++++ 7 files changed, 139 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index c392dc4c..e40366e1 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -2,8 +2,10 @@ //! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde_json::json; +use texturecraft_compose::ImageRes; use texturecraft_core::{ BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, KindControls, LayerId, MaskBackground, Procedural, ProceduralKind, Source, @@ -14,6 +16,7 @@ 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; @@ -51,6 +54,16 @@ pub struct OrbPreview { cameras: Vec, } +/// `generator` with clouds in Grayscale Conversion's empty image slot: it grays the image it is given, and its picture would be black without one +fn with_sample_image(mut generator: Generator) -> Generator { + if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut() + && grayscale.source.is_none() + { + grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); + } + generator +} + impl OrbPreview { /// Bake the orb once (previews of any size reuse it) pub fn new() -> Result { @@ -88,13 +101,7 @@ impl OrbPreview { /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, None outside the shape (and for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]) pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { - let mut generator = Generator::new(kind); - - // Grayscale Conversion grays the image it is given: its picture grays clouds, as it starts with none - if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut() { - grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); - } - self.generator_of(generator, size) + self.generator_of(with_sample_image(Generator::new(kind)), size) } /// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone) @@ -111,6 +118,21 @@ impl OrbPreview { self.mask_pixels(size) } + /// [`Self::generator_of`] with `images` (the images the generator reads, by name) loaded for this render only + pub fn generator_reading(&mut self, generator: Generator, images: &[(String, Arc)], size: usize) -> Option>> { + let replaced: Vec<_> = images.iter().map(|(name, image)| (name.clone(), self.session.images.insert(name.clone(), image.clone()))).collect(); + let pixels = self.generator_of(with_sample_image(generator), size); + + // The orb's own images come back: the next preview reads only what it brings + for (name, previous) in replaced { + match previous { + Some(previous) => self.session.images.insert(name, previous), + None => self.session.images.remove(&name), + }; + } + pixels + } + /// Row-major `size²` pixels of the preview layer's current mask, with None outside the shape fn mask_pixels(&mut self, size: usize) -> Option>> { let camera = camera_for(&mut self.cameras, &self.session, size)?; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index bc7297cf..270ff5e1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -104,14 +104,18 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, // The Curvature size under the pointer shows alone in the preview: the columns are drawn after it, so it is kept from the frame before let solo_id = sheet.ui.make_persistent_id(("generator_solo", id)); let mut solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); - let preview = match (kind, generator.detail_in_use()) { - (GeneratorKind::Curvature, Some(detail)) => ShelfPreview::Curvature { mode: detail.mode, solo }, - _ => ShelfPreview::Generator(kind), + let solo_texture = match (kind, generator.detail_in_use(), solo) { + (GeneratorKind::Curvature, Some(detail), Some(size)) => { + app.thumbs.generator_picture(&ctx, ShelfPreview::Curvature { mode: detail.mode, solo: Some(size) }, PREVIEW_ORB_PX) + } + _ => None, }; - let texture = app.thumbs.generator_picture(&ctx, preview, PREVIEW_ORB_PX); - // A size shows the whole preview until its own render arrives - let texture = texture.or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); + // The preview shows the generator as set; a size shows the whole preview until its own render arrives, and the kind at its defaults shows until the first render + let set = ShelfPreview::generator_set(generator, &app.session.images); + let texture = solo_texture + .or_else(|| app.thumbs.generator_set_picture(&ctx, id, set, PREVIEW_ORB_PX)) + .or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); if let Some(controls) = generator.kind_controls() { diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index f1d78d74..2da02d5c 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -29,6 +29,9 @@ impl PreviewRequest { let generator = ShelfPreview::curvature_generator(*mode, *solo); Some(mask_preview_image(self.size_px, &shape.get()?.generator_of(generator, self.size_px)?)) } + ShelfPreview::GeneratorSet { generator, images } => { + Some(mask_preview_image(self.size_px, &shape.get()?.generator_reading(generator.as_ref().clone(), images, 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 57879c71..9bc7fb79 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -156,7 +156,7 @@ mod tests { use std::collections::HashMap; use std::time::{Duration, Instant}; - use texturecraft_engine::core::GeneratorKind; + use texturecraft_engine::core::{Generator, GeneratorKind}; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -187,6 +187,19 @@ mod tests { } } + #[test] + fn a_generator_as_set_renders_its_settings() { + let mut shape = OrbShape::default(); + let render = |shape: &mut OrbShape, generator: Generator| { + let preview = ShelfPreview::GeneratorSet { generator: Box::new(generator), images: Vec::new() }; + PreviewRequest { key: String::new(), preview, size_px: 16, hover: false }.render(shape).expect("an orb picture") + }; + + let plain = render(&mut shape, Generator::new(GeneratorKind::Dirt)); + let inverted = render(&mut shape, Generator { invert: true, ..Generator::new(GeneratorKind::Dirt) }); + assert_ne!(plain.pixels, inverted.pixels, "the picture follows the generator's settings"); + } + #[test] fn requests_are_answered_and_unknown_assets_get_none() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index ba44649f..2fa13ce5 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,8 +646,14 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = - matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); + let on_the_orb = matches!( + &preview, + ShelfPreview::SmartMask(_) + | ShelfPreview::Generator(_) + | ShelfPreview::Curvature { .. } + | ShelfPreview::GeneratorSet { .. } + | 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 diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 744c3795..30f0884d 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -32,6 +32,8 @@ pub enum ShelfPreview { Generator(GeneratorKind), /// A Curvature generator in `mode`, with only detail size `solo` (finest first) when given, rendered like [`ShelfPreview::Generator`] Curvature { mode: CurvatureMode, solo: Option }, + /// A generator as set, reading `images` (its image inputs by name), rendered like [`ShelfPreview::Generator`] + GeneratorSet { generator: Box, images: Vec<(String, Arc)> }, /// A library filter on a sample material on a sphere Filter(&'static str), /// A procedural pattern as a grayscale swatch @@ -61,6 +63,18 @@ impl ShelfPreview { generator } + /// `generator` as set, with the images it reads from `store` + pub fn generator_set(generator: &Generator, store: &ImageStore) -> ShelfPreview { + let images = generator + .sources() + .filter_map(|source| match source { + texturecraft_engine::core::Source::Image { name, .. } => store.get(name).map(|image| (name.clone(), image.clone())), + _ => None, + }) + .collect(); + ShelfPreview::GeneratorSet { generator: Box::new(generator.clone()), images } + } + /// Resolve a saved brush's image alpha while the project images are available pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { let settings = read_saved_brush(path); @@ -90,6 +104,7 @@ impl ShelfPreview { ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Generator(kind) => format!("generator:{kind:?}"), ShelfPreview::Curvature { mode, solo } => format!("curvature:{mode:?}:{solo:?}"), + ShelfPreview::GeneratorSet { generator, images } => format!("generator-set:{:016x}", settings_hash(generator, images)), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), @@ -105,7 +120,11 @@ impl ShelfPreview { pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_) => None, + ShelfPreview::SmartMask(_) + | ShelfPreview::Generator(_) + | ShelfPreview::Curvature { .. } + | ShelfPreview::GeneratorSet { .. } + | 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)), @@ -228,3 +247,16 @@ mod tests { assert!(missing.image(64).is_none()); } } + +/// What a generator preview depends on: its settings and which images it reads +fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u64 { + use std::hash::{Hash, Hasher}; + + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + serde_json::to_string(generator).unwrap_or_default().hash(&mut hasher); + for (name, image) in images { + name.hash(&mut hasher); + Arc::as_ptr(image).hash(&mut hasher); + } + hasher.finish() +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 569443c6..82755d8b 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -64,6 +64,8 @@ pub struct Thumbs { big_shown: VecDeque, /// The frame that last took in the worker's results received_in_pass: u64, + /// Per generator panel: the picture of its settings being rendered, and the last one finished (shown meanwhile) + set_pictures: HashMap, Option)>, } impl Thumbs { @@ -305,6 +307,29 @@ impl Thumbs { self.worker_rendered(ctx, preview, size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX), false) } + /// Generator `effect`'s picture as set (`preview` a [`ShelfPreview::GeneratorSet`]): one render at a time, the last finished one shown while the next renders, so a drag renders only as fast as the worker keeps up + pub fn generator_set_picture(&mut self, ctx: &egui::Context, effect: u64, preview: ShelfPreview, size_px: usize) -> Option { + self.receive(ctx); + let size_px = size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX); + let key = self.worker_key(&preview, size_px); + let (in_flight, last) = self.set_pictures.get(&effect).cloned().unwrap_or_default(); + + // The picture in flight landed: it is the latest shown + let last = match in_flight.as_ref().map(|key| self.rendered.get(key)) { + Some(Some(WorkerPreview::Ready(texture))) => Some(texture.clone()), + _ => last, + }; + let busy = in_flight.as_ref().is_some_and(|key| matches!(self.rendered.get(key), Some(WorkerPreview::Rendering))); + let shown = match self.ready(&key) { + Some(texture) => Some(texture), + None if busy => last.clone(), + None => self.big(ctx, preview, size_px).or_else(|| last.clone()), + }; + let in_flight = if busy { in_flight } else { Some(key) }; + self.set_pictures.insert(effect, (in_flight, shown.clone().or(last))); + shown + } + /// 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) @@ -466,11 +491,28 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use texturecraft_engine::compose::BakedMaps; + use texturecraft_engine::core::Generator; use crate::orb_shape::OrbShape; static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + #[test] + fn a_generator_picture_shows_the_last_one_while_the_next_renders() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let set = |invert| ShelfPreview::GeneratorSet { generator: Box::new(Generator { invert, ..Generator::new(GeneratorKind::Dirt) }), images: Vec::new() }; + let last = ctx.load_texture("last", ColorImage::filled([1, 1], Color32::RED), TextureOptions::LINEAR); + let rendering = thumbs.worker_key(&set(false), 8); + thumbs.rendered.insert(rendering.clone(), WorkerPreview::Rendering); + thumbs.set_pictures.insert(1, (Some(rendering), Some(last.clone()))); + + let shown = thumbs.generator_set_picture(&ctx, 1, set(true), 8); + + assert_eq!(shown.map(|texture| texture.id()), Some(last.id()), "the last picture stays up"); + assert!(!thumbs.rendered.contains_key(&thumbs.worker_key(&set(true), 8)), "the newer settings wait for the render in flight"); + } + #[test] fn saved_brush_refresh_discards_old_worker_result() { let ctx = egui::Context::default(); From 21b5180dc2199bf65a8234532b0e44f51a2bebda Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:14:07 +0000 Subject: [PATCH 119/153] Generators: Use Texture goes along when the kind changes between the four kinds that have it --- crates/engine/src/mask_cmds.rs | 1 + crates/engine/tests/it/generator_swap.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index a746f431..0d139bf4 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -1299,6 +1299,7 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { resolution: current.resolution, inputs, grunge: current.grunge.clone().filter(|_| WearParameters::defaults(kind).is_some()), + texture: current.texture.clone().filter(|_| SectionParameters::defaults(kind).is_some()), micro: swapped_micro(current.micro.as_deref(), kind), ..Generator::new(kind) } diff --git a/crates/engine/tests/it/generator_swap.rs b/crates/engine/tests/it/generator_swap.rs index a91790d0..24f88b5b 100644 --- a/crates/engine/tests/it/generator_swap.rs +++ b/crates/engine/tests/it/generator_swap.rs @@ -63,3 +63,23 @@ fn only_generator_effects_take_a_generator_kind() { assert!(execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "nope"})).is_err()); assert!(matches!(effect_kind(&session, filter), EffectKind::Filter(_)), "a refused swap changes nothing"); } + +#[test] +fn use_texture_goes_along_between_the_kinds_that_have_it() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let added = json!({"generator": "curvature", "useTexture": true, "textureOpacity": 0.75, "textureScale": 2.0}); + let effect = execute(&mut session, "effect.add.generator", &added).unwrap()["effect"].as_u64().unwrap(); + let texture = |session: &Session| match effect_kind(session, effect) { + EffectKind::Generator(generator) => generator.texture.map(|texture| (texture.enabled, texture.opacity, texture.scale)), + other => panic!("not a generator: {other:?}"), + }; + let before = texture(&session); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "ambientOcclusion"})).unwrap(); + assert_eq!(texture(&session), before, "Ambient Occlusion has Use Texture too"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "dirt"})).unwrap(); + assert_eq!(texture(&session), None, "Dirt has none"); +} From cc9b981112cb2d7d1439bebfab1eea7e3e5cd18c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:15:29 +0000 Subject: [PATCH 120/153] Shelf preview: the settings hash before the tests --- crates/ui-egui/src/shelf_preview.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 30f0884d..f6bad1cb 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -171,6 +171,19 @@ pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option { None } +/// What a generator preview depends on: its settings and which images it reads +fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u64 { + use std::hash::{Hash, Hasher}; + + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + serde_json::to_string(generator).unwrap_or_default().hash(&mut hasher); + for (name, image) in images { + name.hash(&mut hasher); + Arc::as_ptr(image).hash(&mut hasher); + } + hasher.finish() +} + #[cfg(test)] mod tests { use texturecraft_engine::filter_lib::FILTERS; @@ -247,16 +260,3 @@ mod tests { assert!(missing.image(64).is_none()); } } - -/// What a generator preview depends on: its settings and which images it reads -fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u64 { - use std::hash::{Hash, Hasher}; - - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - serde_json::to_string(generator).unwrap_or_default().hash(&mut hasher); - for (name, image) in images { - name.hash(&mut hasher); - Arc::as_ptr(image).hash(&mut hasher); - } - hasher.finish() -} From 3f72b65487c795467466d456363c7fd90f642c71 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:41:50 +0000 Subject: [PATCH 121/153] Bake mode pass 2: settings sync between texture sets, undoable high polys loaded on a worker, automatic cage, panels in the reference's layout --- crates/bake/src/cage.rs | 3 + crates/bake/src/cage/fitted_cage.rs | 169 +++++++ crates/bake/src/cage/high_poly_reach.rs | 2 +- crates/bake/src/cage/name_keys.rs | 38 ++ crates/bake/src/cage/ray_frame.rs | 22 +- crates/bake/src/cage/ray_start.rs | 12 + crates/bake/src/cage/vertex_reach.rs | 5 +- crates/bake/src/lib.rs | 6 +- crates/bake/src/map/bake_context.rs | 19 +- crates/bake/src/map/transfer.rs | 2 + crates/bake/src/test/cage_shell.rs | 6 + crates/bake/src/test/fitted_cage.rs | 150 ++++++ crates/bake/src/tests.rs | 3 + crates/core/src/bake.rs | 4 + crates/core/src/bake/bake_settings.rs | 17 +- crates/core/src/bake/bake_sync.rs | 40 ++ crates/core/src/bake/bake_sync_group.rs | 8 + crates/core/src/bake/cage_type.rs | 2 + crates/core/src/bake/common_bake_settings.rs | 4 +- crates/core/src/bake/mesh_map_settings.rs | 16 + crates/core/src/lib.rs | 10 +- crates/core/src/project.rs | 13 +- crates/core/tests/bake_settings.rs | 8 +- crates/engine/src/bake/bake_checks.rs | 2 +- crates/engine/src/bake/bake_mesh.rs | 2 + crates/engine/src/bake/bake_meshes.rs | 3 +- crates/engine/src/bake/high_poly_load.rs | 75 +++ crates/engine/src/bake/mesh_map_command.rs | 176 ++++--- crates/engine/src/bake/mod.rs | 4 + crates/engine/src/bake/model_patch.rs | 3 +- crates/engine/src/bake/sync_command.rs | 268 ++++++++++ crates/engine/src/file_cmds.rs | 41 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/material_lib.rs | 22 +- crates/engine/src/session.rs | 19 +- crates/engine/src/smart_masks.rs | 3 + crates/engine/tests/it/bake.rs | 73 ++- crates/ui-egui/src/bake_job.rs | 4 + crates/ui-egui/src/bake_mode/bake_checks.rs | 2 +- crates/ui-egui/src/bake_mode/breadcrumb.rs | 96 +++- .../ui-egui/src/bake_mode/common_settings.rs | 412 +++++++-------- crates/ui-egui/src/bake_mode/controls.rs | 111 ++--- crates/ui-egui/src/bake_mode/glyph_look.rs | 9 + crates/ui-egui/src/bake_mode/map_settings.rs | 195 +++++--- .../ui-egui/src/bake_mode/map_thumbnails.rs | 69 +++ .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 317 ++++++++++-- crates/ui-egui/src/bake_mode/mod.rs | 37 +- crates/ui-egui/src/bake_mode/set_picker.rs | 290 +++++++++++ .../src/bake_mode/set_picker_purpose.rs | 10 + .../ui-egui/src/bake_mode/set_picker_row.rs | 7 + .../ui-egui/src/bake_scene/bake_scene_link.rs | 2 +- .../ui-egui/src/bake_scene/cage_shell_key.rs | 33 +- crates/ui-egui/src/bake_scene/reach_link.rs | 18 +- crates/ui-egui/src/docking.rs | 4 +- crates/ui-egui/src/high_poly_job.rs | 79 +++ crates/ui-egui/src/lib.rs | 47 +- crates/ui-egui/src/property_sheet/choice.rs | 3 +- .../ui-egui/src/property_sheet/file_list.rs | 152 ++++++ .../src/property_sheet/file_list_add.rs | 6 + .../src/property_sheet/file_list_response.rs | 6 + crates/ui-egui/src/property_sheet/file_row.rs | 7 + .../src/property_sheet/fold_section.rs | 7 + crates/ui-egui/src/property_sheet/mod.rs | 11 + .../src/property_sheet/property_sheet.rs | 3 + crates/ui-egui/src/property_sheet/slider.rs | 6 +- .../src/property_sheet/stacked_rows.rs | 471 ++++++++++++++++++ crates/ui-egui/src/updates_ui.rs | 2 +- crates/ui-egui/src/viewport.rs | 20 +- crates/ui-egui/src/web_files.rs | 19 +- crates/ui-egui/tests/bake_preview.rs | 20 + crates/ui-egui/tests/it/bake_job_mesh.rs | 2 +- crates/ui-egui/tests/it/bake_map_rows.rs | 70 +++ crates/ui-egui/tests/it/bake_mode.rs | 112 +++-- crates/ui-egui/tests/it/bake_presets.rs | 2 + crates/ui-egui/tests/it/bake_reset_menus.rs | 84 ++++ crates/ui-egui/tests/it/bake_sync.rs | 111 +++++ crates/ui-egui/tests/it/high_poly_loading.rs | 97 ++++ crates/ui-egui/tests/it/main.rs | 4 + crates/ui-egui/tests/it/skew_paint.rs | 14 +- crates/ui-egui/tests/ui_snapshots.rs | 2 +- docs/control-protocol.md | 15 +- 81 files changed, 3571 insertions(+), 669 deletions(-) create mode 100644 crates/bake/src/cage/fitted_cage.rs create mode 100644 crates/bake/src/cage/name_keys.rs create mode 100644 crates/bake/src/test/fitted_cage.rs create mode 100644 crates/core/src/bake/bake_sync.rs create mode 100644 crates/core/src/bake/bake_sync_group.rs create mode 100644 crates/engine/src/bake/high_poly_load.rs create mode 100644 crates/engine/src/bake/sync_command.rs create mode 100644 crates/ui-egui/src/bake_mode/glyph_look.rs create mode 100644 crates/ui-egui/src/bake_mode/map_thumbnails.rs create mode 100644 crates/ui-egui/src/bake_mode/set_picker.rs create mode 100644 crates/ui-egui/src/bake_mode/set_picker_purpose.rs create mode 100644 crates/ui-egui/src/bake_mode/set_picker_row.rs create mode 100644 crates/ui-egui/src/high_poly_job.rs create mode 100644 crates/ui-egui/src/property_sheet/file_list.rs create mode 100644 crates/ui-egui/src/property_sheet/file_list_add.rs create mode 100644 crates/ui-egui/src/property_sheet/file_list_response.rs create mode 100644 crates/ui-egui/src/property_sheet/file_row.rs create mode 100644 crates/ui-egui/src/property_sheet/fold_section.rs create mode 100644 crates/ui-egui/src/property_sheet/stacked_rows.rs create mode 100644 crates/ui-egui/tests/it/bake_map_rows.rs create mode 100644 crates/ui-egui/tests/it/bake_reset_menus.rs create mode 100644 crates/ui-egui/tests/it/bake_sync.rs create mode 100644 crates/ui-egui/tests/it/high_poly_loading.rs diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs index d2c7d7f3..d2c8a592 100644 --- a/crates/bake/src/cage.rs +++ b/crates/bake/src/cage.rs @@ -1,7 +1,9 @@ //! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws mod cage_shell; +mod fitted_cage; mod high_poly_reach; +mod name_keys; mod ray_frame; mod ray_start; mod vertex_reach; @@ -9,6 +11,7 @@ mod vertex_reach; #[cfg(test)] pub(crate) use cage_shell::CORNERS; pub use cage_shell::CageShell; +pub(crate) use fitted_cage::FittedCage; pub use high_poly_reach::HighPolyReach; pub(crate) use ray_frame::RayFrame; pub use ray_start::RayStart; diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs new file mode 100644 index 00000000..088dae2f --- /dev/null +++ b/crates/bake/src/cage/fitted_cage.rs @@ -0,0 +1,169 @@ +use super::name_keys::NameKeys; +use crate::map::interpolate; +use crate::{BakeRequest, HighPoly, MeshExtent}; +use rayon::prelude::*; +use std::collections::VecDeque; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// How much farther than the high poly the cage reaches, as a fraction of the fitted distance: the fit reads both meshes at their vertices only. Tuned with [`MARGIN_PER_DIAGONAL`] on two production meshes: the tightest pair whose rays miss no more texels than the default distances do +const MARGIN_PER_DISTANCE: f32 = 0.5; + +/// The least the cage reaches each way, as a fraction of the mesh diagonal, so a high poly lying on the low poly is still inside +const MARGIN_PER_DIAGONAL: f32 = 4e-3; + +/// How many times farther than the nearest high-poly point a low-poly vertex's ray may find the high poly: beyond it (a surface more than about 75 degrees off the ray) the ray has left the vertex's own part +const MAX_RAY_PER_NEAREST_DISTANCE: f32 = 4.0; + +/// The automatic cage: how far the transfer rays start in front of each low-poly vertex and how far they run behind it, fitted to the high poly +pub(crate) struct FittedCage { + /// (front, rear) in world units per low-poly vertex; `None` on parts no high poly is near + distances: Vec>, +} + +impl FittedCage { + /// Fit the cage of `request`'s low poly around `high` along `ray_normals`: each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { + let low = request.mesh; + let keys = NameKeys::of(request, high); + let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; + let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + let mut reach: Vec> = vec![None; welded_count]; + let mut widen = |vertex: usize, height: f32| { + if let Some(distances) = reach.get_mut(welded(vertex)) { + let (front, rear) = distances.unwrap_or((0.0, 0.0)); + *distances = Some((front.max(height), rear.max(-height))); + } + }; + + for (vertex, height) in heights_at_low_vertices(low, high, ray_normals, &keys, extent.diagonal).into_iter().enumerate() { + if let Some(height) = height { + widen(vertex, height); + } + } + for (triangle, height) in heights_of_high_vertices(request, high, ray_normals, &keys).into_iter().flatten() { + for corner in low.tri(triangle).into_iter().flatten() { + widen(corner, height); + } + } + spread_to_neighbours(&mut reach, low.indices.as_chunks::<3>().0.iter().map(|corners| corners.map(|corner| welded(corner as usize)))); + + let floor = MARGIN_PER_DIAGONAL * extent.diagonal; + let padded = |distance: f32| distance * (1.0 + MARGIN_PER_DISTANCE) + floor; + let distances = + (0..low.positions.len()).map(|vertex| reach.get(welded(vertex)).copied().flatten().map(|(front, rear)| (padded(front), padded(rear)))).collect(); + + FittedCage { distances } + } + + /// The (front, rear) distances at `barycentric` of triangle `triangle` of the low poly `low` the cage was fitted to; `None` where the high poly reaches no corner + pub(crate) fn distances(&self, low: &Mesh, triangle: u32, barycentric: [f32; 2]) -> Option<(f32, f32)> { + let corners = low.tri(triangle as usize)?; + let [first, second, third] = [0, 1, 2].map(|corner| self.distances.get(corners[corner]).copied().flatten()); + let ((first_front, first_rear), (second_front, second_rear), (third_front, third_rear)) = (first?, second?, third?); + let [second_weight, third_weight] = barycentric; + let first_weight = 1.0 - second_weight - third_weight; + + Some(( + first_front * first_weight + second_front * second_weight + third_front * third_weight, + first_rear * first_weight + second_rear * second_weight + third_rear * third_weight, + )) + } +} + +/// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead +fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { + low.positions + .par_iter() + .zip(ray_normals) + .enumerate() + .map(|(vertex, (&position, &up))| { + let low_key = keys.low_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(low_key, keys.high_triangles.get(triangle as usize)); + let nearest = high.bvh.nearest(position, max_distance, &rays_reach)?; + let nearest_position = interpolate(high.mesh, &high.mesh.positions, nearest.tri, [nearest.u, nearest.v])?; + let ray_limit = nearest.t * MAX_RAY_PER_NEAREST_DISTANCE + MARGIN_PER_DIAGONAL * max_distance; + let distance = |direction: Vec3| high.bvh.closest_filtered(position, direction, ray_limit, &rays_reach).map(|hit| hit.t); + + Some(match (distance(up), distance(-up)) { + (Some(front), Some(rear)) if front <= rear => front, + (Some(front), None) => front, + (_, Some(rear)) => -rear, + (None, None) => (nearest_position - position).dot(up), + }) + }) + .collect() +} + +/// Per high-poly vertex, its nearest low-poly triangle and its height over it along the ray normal there +fn heights_of_high_vertices(request: &BakeRequest, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys) -> Vec> { + let low = request.mesh; + high.mesh + .positions + .par_iter() + .enumerate() + .map(|(vertex, &high_position)| { + let high_key = keys.high_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(keys.low_triangles.get(triangle as usize), high_key); + let nearest = request.bvh.nearest(high_position, f32::INFINITY, &rays_reach)?; + let barycentric = [nearest.u, nearest.v]; + let low_position = interpolate(low, &low.positions, nearest.tri, barycentric)?; + let up = interpolate(low, ray_normals, nearest.tri, barycentric)?.try_normalize()?; + Some((nearest.tri as usize, (high_position - low_position).dot(up))) + }) + .collect() +} + +/// Give each vertex without distances the largest of its nearest fitted neighbours', walking outward along the edges of `triangles` +fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterator) { + let mut neighbours = vec![Vec::new(); reach.len()]; + for corners in triangles { + for (corner, next) in [(0, 1), (1, 2), (2, 0)] { + if let (true, Some(list)) = (corners[next] < reach.len(), neighbours.get_mut(corners[corner])) { + list.push(corners[next]); + } + if let (true, Some(list)) = (corners[corner] < reach.len(), neighbours.get_mut(corners[next])) { + list.push(corners[corner]); + } + } + } + + // Steps from the nearest fitted vertex; a vertex only takes distances from vertices one step nearer + let mut steps: Vec> = reach.iter().map(|distances| distances.map(|_| 0)).collect(); + let mut queue: VecDeque = (0..reach.len()).filter(|vertex| reach[*vertex].is_some()).collect(); + while let Some(vertex) = queue.pop_front() { + let (Some((front, rear)), Some(step)) = (reach[vertex], steps[vertex]) else { continue }; + + for &neighbour in &neighbours[vertex] { + match steps[neighbour] { + None => { + steps[neighbour] = Some(step + 1); + reach[neighbour] = Some((front, rear)); + queue.push_back(neighbour); + } + Some(neighbour_step) if neighbour_step == step + 1 => { + let (neighbour_front, neighbour_rear) = reach[neighbour].unwrap_or((0.0, 0.0)); + reach[neighbour] = Some((neighbour_front.max(front), neighbour_rear.max(rear))); + } + Some(_) => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::spread_to_neighbours; + + #[test] + fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { + // A strip of triangles 0-1-2, 1-2-3, 2-3-4: vertices 0 and 4 are fitted + let mut reach = vec![Some((1.0, 0.5)), None, None, None, Some((3.0, 0.25))]; + + spread_to_neighbours(&mut reach, [[0, 1, 2], [1, 2, 3], [2, 3, 4]].into_iter()); + + assert_eq!(reach[1], Some((1.0, 0.5)), "one step from vertex 0 only"); + assert_eq!(reach[3], Some((3.0, 0.25)), "one step from vertex 4 only"); + assert_eq!(reach[2], Some((3.0, 0.5)), "one step from both: the larger of each"); + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index 2f461343..b227ca06 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -75,7 +75,7 @@ impl HighPolyReach { } /// Each vertex's mesh-name key, from the first triangle that uses it -fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { +pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { diff --git a/crates/bake/src/cage/name_keys.rs b/crates/bake/src/cage/name_keys.rs new file mode 100644 index 00000000..077cd826 --- /dev/null +++ b/crates/bake/src/cage/name_keys.rs @@ -0,0 +1,38 @@ +use super::high_poly_reach::vertex_keys; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly}; +use texturecraft_core::MeshMatchMode; + +/// The mesh-name keys of a bake's low and high poly, per triangle and per vertex; all empty when every ray may hit every part +#[derive(Default)] +pub(super) struct NameKeys { + pub(super) low_triangles: Vec, + pub(super) low_vertices: Vec, + pub(super) high_triangles: Vec, + pub(super) high_vertices: Vec, +} + +impl NameKeys { + /// The keys `request` bakes with against `high`: filled only when it matches by mesh name + pub(super) fn of(request: &BakeRequest, high: HighPoly) -> NameKeys { + match request.settings.high_poly.match_mode { + MeshMatchMode::Always => NameKeys::default(), + MeshMatchMode::ByMeshName => { + let (low_triangles, high_triangles) = transfer_keys(request); + NameKeys { + low_vertices: vertex_keys(request.mesh, &low_triangles), + high_vertices: vertex_keys(high.mesh, &high_triangles), + low_triangles, + high_triangles, + } + } + } + } + + /// Whether a ray from the low-poly part keyed `low_key` may hit the high-poly part keyed `high_key`; a missing key is a part any ray may hit + pub(super) fn matches(low_key: Option<&u32>, high_key: Option<&u32>) -> bool { + let low_key = low_key.copied().unwrap_or(ANY); + low_key == ANY || low_key == high_key.copied().unwrap_or(ANY) + } +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs index e8692cf2..590e52e1 100644 --- a/crates/bake/src/cage/ray_frame.rs +++ b/crates/bake/src/cage/ray_frame.rs @@ -1,4 +1,4 @@ -use super::RayStart; +use super::{FittedCage, RayStart}; use crate::MeshExtent; use crate::map::{interpolate, welded}; use crate::skew::PreparedSkew; @@ -7,11 +7,12 @@ 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 +/// What decides where transfer rays start: the cage mesh, the automatic cage's fitted distances, or the averaged normals, skew and painted cage amount pub(crate) struct RayFrame<'a> { mesh: &'a Mesh, ray_normals: Vec, cage: Option<&'a Mesh>, + fitted: Option, skew: Option>, cage_paint: Option<&'a BakePaintMap>, /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead @@ -23,18 +24,24 @@ pub(crate) struct RayFrame<'a> { 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() { + + // The automatic cage is one closed shell, so its rays always follow the averaged normals + let automatic_high = request.high.filter(|_| settings.cage.kind == CageType::Automatic); + let (ray_normals, fitted) = match (settings.cage.average_normals || automatic_high.is_some()) && 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() + let ray_normals: Vec = welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect(); + let fitted = automatic_high.map(|high| FittedCage::new(request, high, &welded_indices, &ray_normals, extent)); + (ray_normals, fitted) } - false => Vec::new(), + false => (Vec::new(), None), }; Ok(RayFrame { mesh: request.mesh, ray_normals, cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + fitted, 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(), @@ -54,6 +61,11 @@ impl<'a> RayFrame<'a> { } let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let fitted_distances = self.fitted.as_ref().and_then(|fitted| fitted.distances(self.mesh, surface.tri, barycentric)); + if let Some((front, rear)) = fitted_distances { + return RayStart::Fitted { up: averaged_normal, front, rear }; + } + let up = match &self.skew { Some(skew) => skew.correct(self.mesh, surface, averaged_normal), None => averaged_normal, diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs index c0c3923a..8c21bb9b 100644 --- a/crates/bake/src/cage/ray_start.rs +++ b/crates/bake/src/cage/ray_start.rs @@ -7,6 +7,8 @@ pub enum RayStart { CageMesh(Vec3), /// Out along `up` by the frontal distance times `scale` (the painted cage amount) Distance { up: Vec3, scale: f32 }, + /// Out along `up` by `front` world units and reaching `rear` past the low-poly point: the automatic cage's own distances + Fitted { up: Vec3, front: f32, rear: f32 }, } impl RayStart { @@ -15,6 +17,16 @@ impl RayStart { match *self { RayStart::CageMesh(offset) => position - offset, RayStart::Distance { up, scale } => position + up * frontal * scale, + RayStart::Fitted { up, front, .. } => position + up * front, + } + } + + /// The ray's direction, how far it runs to the low-poly point and how far past it, at `frontal` and `rear` world units of the distance settings + pub fn span(&self, frontal: f32, rear: f32) -> (Vec3, f32, f32) { + match *self { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length(), rear), + RayStart::Distance { up, scale } => (-up, frontal * scale, rear), + RayStart::Fitted { up, front, rear: fitted_rear } => (-up, front, fitted_rear), } } } diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs index 34adea92..2c6df8e8 100644 --- a/crates/bake/src/cage/vertex_reach.rs +++ b/crates/bake/src/cage/vertex_reach.rs @@ -17,10 +17,7 @@ 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 (direction, front, rear) = self.start.span(frontal, rear); 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 1d99ab36..8b55546e 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -349,6 +349,7 @@ fn bake_rows( .collect() }) .collect(); + let row_offsets: Vec = samples_by_row .iter() .scan(0, |sample_count, row| { @@ -362,11 +363,12 @@ fn bake_rows( true => { let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?; - hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() + hits.into_par_iter().zip(&rays).zip(frontal_distances).map(|((hit, ray), front)| context.transfer(hit, front, ray.max_distance)).collect() } false => Vec::new(), }; let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref); + let curvature = match context.traces_curvature() { true => { let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row @@ -379,6 +381,7 @@ fn bake_rows( } false => Vec::new(), }; + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { true => samples_by_row .par_iter() @@ -388,6 +391,7 @@ fn bake_rows( .collect(), false => Vec::new(), }; + // Share occlusion results when the bent-normal ray settings match let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao); let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect(); diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index bbeb623e..8dce2df9 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,7 +1,7 @@ use super::curvature::Curvature; use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::cage::{RayFrame, RayStart}; +use crate::cage::RayFrame; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; @@ -12,6 +12,9 @@ use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; +/// Height relative to the rays divides by the ray's length; this keeps a zero-length ray from dividing by zero +const SHORTEST_RAY: f32 = 1e-20; + pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, @@ -109,21 +112,19 @@ impl<'a> BakeContext<'a> { pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { 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 (direction, front, rear) = start.span(self.frontal, self.rear); let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY), }; - (Ray { origin, direction, max_distance: front + self.rear, key }, front) + (Ray { origin, direction, max_distance: front + rear, key }, front) } - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + /// What the transfer ray that ran `front` to the low poly and `ray_length` in all brought back from the high poly + pub(crate) fn transfer(&self, hit: Option, front: f32, ray_length: f32) -> Option { let (high, hit) = (self.high.as_ref()?, hit?); let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; - Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front }) + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front, ray_length }) } pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { @@ -245,7 +246,7 @@ impl<'a> BakeContext<'a> { let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances; [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| { let height = hit.front - hit.t; - if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height } + if relative_to_rays { (0.5 + height / hit.ray_length.max(SHORTEST_RAY)).clamp(0.0, 1.0) } else { height } }); 3] } BakedMap::Opacity if missed => [0.0; 3], diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs index c1200053..46c67f28 100644 --- a/crates/bake/src/map/transfer.rs +++ b/crates/bake/src/map/transfer.rs @@ -5,4 +5,6 @@ pub(crate) struct Transfer { pub(super) bary: [f32; 2], pub(super) t: f32, pub(super) front: f32, + /// The whole ray, from the cage to its rear end + pub(super) ray_length: f32, } diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 40edd3b8..f0ce2600 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -60,6 +60,12 @@ fn the_cage_corners_are_the_bake_ray_origins() { face_normals }; assert_cage_matches_the_ray_origins(&request(&face_normals)); + let automatic = { + let mut automatic = bake_settings.clone(); + automatic.cage.kind = CageType::Automatic; + automatic + }; + assert_cage_matches_the_ray_origins(&request(&automatic)); } #[test] diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs new file mode 100644 index 00000000..3aa96e6b --- /dev/null +++ b/crates/bake/src/test/fitted_cage.rs @@ -0,0 +1,150 @@ +use super::{covered_values, settings, transfer}; +use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::{BakeSettings, BakedMap, CageType}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives}; + +/// A distance setting far larger than any fitted distance in these tests, to tell the two apart +const UNFITTED_DISTANCE: f32 = 0.5; + +/// Settings baking `maps` with the automatic cage, and distance settings no fitted cage comes near +fn automatic(maps: &[BakedMap]) -> BakeSettings { + let mut bake_settings = settings(32, maps); + bake_settings.cage.kind = CageType::Automatic; + bake_settings.cage.relative_to_bounding_box = false; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (UNFITTED_DISTANCE, UNFITTED_DISTANCE); + bake_settings +} + +/// How far each corner of the automatic cage of the flat `low` around `high` rises above it, with the corner's low-poly position +fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(Vec3, f32)> { + let (low_bvh, high_bvh) = (Bvh::new(low), Bvh::new(high)); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &low_bvh, + material: 0, + settings: bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let corners = shell.corners(bake_settings.cage.max_frontal); + shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() +} + +#[test] +fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { + let low = primitives::cube(1.0); + let high = primitives::sphere(0.8, 32, 16); + let opacity_of = |bake_settings: &BakeSettings| -> Vec { + let output = transfer(&low, &high, None, bake_settings).unwrap(); + covered_values(&low, &output, BakedMap::Opacity).into_iter().map(|(_, opacity)| opacity).collect() + }; + + let distance_based = opacity_of(&settings(32, &[BakedMap::Opacity])); + assert!(distance_based.contains(&0.0), "the sphere is beyond the default distances at the middle of each face"); + + let mut bake_settings = settings(32, &[BakedMap::Opacity]); + bake_settings.cage.kind = CageType::Automatic; + let fitted = opacity_of(&bake_settings); + assert!(fitted.iter().all(|opacity| *opacity == 1.0), "every ray of the automatic cage finds the sphere"); + + // The triangles at the sphere's poles have no area, so a pole vertex has no side to face the ray with + bake_settings.high_poly.ignore_backface = false; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + for vertex in 0..high.positions.len() { + assert_eq!(reach.missed(vertex, 0.0, 0.0), Some(false), "high-poly vertex {vertex} is inside the cage whatever the distance settings"); + } +} + +#[test] +fn the_automatic_cage_stays_low_where_the_high_poly_is_low() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.2; + const RAISED_FROM_X: f32 = 0.25; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(1.0, 40); + for position in &mut high.positions { + position.y = if position.x > RAISED_FROM_X { RAISED_HEIGHT } else { LOW_HEIGHT }; + } + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + for (position, height) in heights { + if position.x < 0.0 { + assert!((LOW_HEIGHT..RAISED_HEIGHT / 2.0).contains(&height), "the cage at {position} hugs the low part: {height}"); + } else if position.x > RAISED_FROM_X + 0.125 { + assert!((RAISED_HEIGHT..RAISED_HEIGHT * 2.0).contains(&height), "the cage at {position} clears the raised part: {height}"); + } + } +} + +#[test] +fn a_ray_that_only_finds_a_far_surface_takes_the_nearest_surface_height_instead() { + const PATCH_HEIGHT: f32 = 0.02; + const CEILING_HEIGHT: f32 = 1.0; + // A low-plane vertex beside the patch's edge: the patch is its nearest high poly, the ceiling is straight above it + const BESIDE_PATCH: Vec3 = Vec3::new(0.125, 0.0, 0.0); + // Far enough that the ceiling's own corners are nearest to the low plane's border, not to the vertex tested + const CEILING_REACH: f32 = 1000.0; + // The ceiling starts just past the patch's edge (x = 0), the patch covers the low plane's other half + const CEILING_FROM_X: f32 = 0.05; + const PATCH_SIZE: f32 = 0.5; + const SAME_POSITION: f32 = 1e-4; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(PATCH_SIZE, 1); + for position in &mut high.positions { + *position = Vec3::new(position.x - PATCH_SIZE / 2.0, PATCH_HEIGHT, position.z); + } + let ceiling = Mesh::from_parts( + vec![ + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, -CEILING_REACH), + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, CEILING_REACH), + Vec3::new(CEILING_REACH, CEILING_HEIGHT, 0.0), + ], + None, + vec![Default::default(); 3], + vec![0, 1, 2], + "ceiling", + ) + .unwrap(); + high.append(&ceiling); + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + let (_, height) = heights.iter().find(|(position, _)| position.distance(BESIDE_PATCH) < SAME_POSITION).unwrap(); + assert!(*height < CEILING_HEIGHT / 2.0, "the cage beside the patch stays near the patch, not the ceiling: {height}"); +} + +#[test] +fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { + let mut low = primitives::plane(1.0, 2); + let mut high = primitives::plane(1.0, 2); + low.submeshes[0].name = "panel_low".into(); + high.submeshes[0].name = "door_high".into(); + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index eaa64cf2..7d94031e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -20,6 +20,9 @@ mod bent_normal_space; #[path = "test/cage_shell.rs"] mod cage_shell; +#[path = "test/fitted_cage.rs"] +mod fitted_cage; + #[path = "test/high_poly_reach.rs"] mod high_poly_reach; diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index 4b21a20d..a40f5ab0 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -7,6 +7,8 @@ mod bake_antialiasing; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_sync; +mod bake_sync_group; mod mesh_match_mode; mod skew_correction_method; pub use bake_paint_target::BakePaintTarget; @@ -45,6 +47,8 @@ pub use backface_mode::BackfaceMode; pub use bake_antialiasing::BakeAntialiasing; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_sync::BakeSync; +pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; pub use bent_normal_settings::BentNormalSettings; pub use cage_settings::CageSettings; diff --git a/crates/core/src/bake/bake_settings.rs b/crates/core/src/bake/bake_settings.rs index 8d121419..87962b5c 100644 --- a/crates/core/src/bake/bake_settings.rs +++ b/crates/core/src/bake/bake_settings.rs @@ -1,4 +1,4 @@ -use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; +use super::{BakeSync, BakeSyncGroup, CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; use serde::{Deserialize, Serialize}; /// Persisted clean-room bake settings, grouped by the controls they belong to @@ -10,6 +10,8 @@ pub struct BakeSettings { pub cage: CageSettings, pub skew: SkewSettings, pub maps: MeshMapSettings, + /// What this texture set shares with the others + pub sync: BakeSync, } impl BakeSettings { @@ -17,4 +19,17 @@ impl BakeSettings { pub fn skew_applies(&self) -> bool { !self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals } + + /// Take `group`'s settings from `source`, keeping whether this set is baked and which maps it bakes + pub fn copy_group(&mut self, source: &BakeSettings, group: BakeSyncGroup) { + match group { + BakeSyncGroup::Common => { + self.common = CommonBakeSettings { is_enabled: self.common.is_enabled, ..source.common }; + self.high_poly = source.high_poly.clone(); + self.cage = source.cage; + self.skew = source.skew; + } + BakeSyncGroup::Map(map) => self.maps.copy_parameters(map, &source.maps), + } + } } diff --git a/crates/core/src/bake/bake_sync.rs b/crates/core/src/bake/bake_sync.rs new file mode 100644 index 00000000..e53a4def --- /dev/null +++ b/crates/core/src/bake/bake_sync.rs @@ -0,0 +1,40 @@ +use super::{BakeSyncGroup, BakedMap}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Which of a texture set's bake settings it shares with every other texture set sharing them; all are shared at first, as in the reference +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeSync { + /// Shares Common Settings: output, high poly, cage and skew correction + pub common: bool, + /// The map types whose settings it shares + pub maps: BTreeSet, +} + +impl Default for BakeSync { + fn default() -> Self { + Self { common: true, maps: BakedMap::ALL.into_iter().collect() } + } +} + +impl BakeSync { + pub fn shares(&self, group: BakeSyncGroup) -> bool { + match group { + BakeSyncGroup::Common => self.common, + BakeSyncGroup::Map(map) => self.maps.contains(&map), + } + } + + pub fn set_shares(&mut self, group: BakeSyncGroup, shares: bool) { + match group { + BakeSyncGroup::Common => self.common = shares, + BakeSyncGroup::Map(map) if shares => { + self.maps.insert(map); + } + BakeSyncGroup::Map(map) => { + self.maps.remove(&map); + } + } + } +} diff --git a/crates/core/src/bake/bake_sync_group.rs b/crates/core/src/bake/bake_sync_group.rs new file mode 100644 index 00000000..c9007dbf --- /dev/null +++ b/crates/core/src/bake/bake_sync_group.rs @@ -0,0 +1,8 @@ +use super::BakedMap; + +/// A part of the bake settings texture sets can share: Common Settings, or one map type's settings +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum BakeSyncGroup { + Common, + Map(BakedMap), +} diff --git a/crates/core/src/bake/cage_type.rs b/crates/core/src/bake/cage_type.rs index 1985055f..a894235c 100644 --- a/crates/core/src/bake/cage_type.rs +++ b/crates/core/src/bake/cage_type.rs @@ -4,5 +4,7 @@ use serde::{Deserialize, Serialize}; pub enum CageType { #[default] DistanceBased, + /// Distances fitted to the high poly at every low-poly vertex + Automatic, CustomFile, } diff --git a/crates/core/src/bake/common_bake_settings.rs b/crates/core/src/bake/common_bake_settings.rs index 3f743fff..a39ef77f 100644 --- a/crates/core/src/bake/common_bake_settings.rs +++ b/crates/core/src/bake/common_bake_settings.rs @@ -21,8 +21,8 @@ impl Default for CommonBakeSettings { resolution: BakeResolution::R2048, resolution_height: None, antialiasing: BakeAntialiasing::None, - dilation: 1, - apply_diffusion: true, + dilation: 32, + apply_diffusion: false, } } } diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index c0a38673..281d5c98 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -68,6 +68,22 @@ impl MeshMapSettings { *enabled = is_enabled; } + /// Take `map`'s parameters from `source`, keeping whether it is checked + pub fn copy_parameters(&mut self, map: BakedMap, source: &MeshMapSettings) { + match map { + BakedMap::Normal => self.normal.parameters = source.normal.parameters, + BakedMap::WorldNormal => self.world_normal.parameters = source.world_normal.parameters, + BakedMap::Id => self.id.parameters = source.id.parameters, + BakedMap::AmbientOcclusion => self.ao.parameters = source.ao.parameters, + BakedMap::Curvature => self.curvature.parameters = source.curvature.parameters, + BakedMap::Position => self.position.parameters = source.position.parameters, + BakedMap::Thickness => self.thickness.parameters = source.thickness.parameters, + BakedMap::Height => self.height.parameters = source.height.parameters, + BakedMap::BentNormal => self.bent_normal.parameters = source.bent_normal.parameters, + BakedMap::Opacity => self.opacity.parameters = source.opacity.parameters, + } + } + pub fn enabled(&self) -> impl Iterator { BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 88ee96d1..bd89a2a8 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -80,11 +80,11 @@ pub const FULL_TURN_DEGREES: f32 = 360.0; pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ - AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, - BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, - HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, - NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, - SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync, + BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, + HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, + MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, + SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, }; pub use bevel::Bevel; pub use bevel_blur::BevelBlur; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 649f4f6d..6bcf92e4 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -478,6 +478,17 @@ impl Project { self.texture_sets.get_mut(ts).ok_or(CoreError::NoTextureSet(ts)) } + /// The texture sets an edit of `group` on texture set `active` reaches: every set sharing `group` with it, or `active` alone + pub fn bake_synced_sets(&self, active: usize, group: BakeSyncGroup) -> Vec { + match self.texture_sets.get(active) { + Some(set) if set.bake.sync.shares(group) => { + self.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.sync.shares(group)).map(|(index, _)| index).collect() + } + Some(_) => vec![active], + None => Vec::new(), + } + } + pub fn layer(&self, id: LayerId) -> Result<&Layer> { self.layers.get(&id).ok_or(CoreError::NoLayer(id)) } diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 1616604f..80fda4b8 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -13,10 +13,11 @@ fn reference_defaults_cover_common_and_per_map_settings() { let mut thickness_rays = rays.clone(); thickness_rays["max_distance"] = json!(0.1); let mut expected = json!({ - "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 1, "apply_diffusion": true}, + "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 32, "apply_diffusion": false}, "high_poly": {"match_mode": "Always", "use_low_as_high": false, "ignore_backface": true, "low_suffix": "_low", "high_suffix": "_high", "ignore_backface_suffix": "_ignorebf"}, "cage": {"kind": "DistanceBased", "max_frontal": 0.01, "max_rear": 0.01, "relative_to_bounding_box": true, "average_normals": true}, "skew": {"method": "MeshNormalsBased", "edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5}, + "sync": {"common": true, "maps": ["Normal", "WorldNormal", "Id", "AmbientOcclusion", "Curvature", "Position", "Thickness", "Height", "BentNormal", "Opacity"]}, "id": {"source": "MaterialColor", "generator": "HueShift"}, "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, "curvature": { @@ -81,7 +82,7 @@ fn all_dropdowns_store_enum_choices() { assert_choices(&[bake::SkewCorrectionMethod::MeshNormalsBased, bake::SkewCorrectionMethod::FaceNormalsBased]); assert_choices(&bake::BakeResolution::ALL); assert_choices(&bake::BakeAntialiasing::ALL); - assert_choices(&[bake::CageType::DistanceBased, bake::CageType::CustomFile]); + assert_choices(&[bake::CageType::DistanceBased, bake::CageType::Automatic, bake::CageType::CustomFile]); assert_choices(&[bake::CurvatureMethod::NormalMap, bake::CurvatureMethod::Mesh]); assert_choices(&[ bake::IdColorSource::VertexColor, @@ -126,7 +127,8 @@ fn nested_settings_round_trip_per_texture_set() { settings.common.resolution = bake::BakeResolution::R16; settings.common.resolution_height = Some(bake::BakeResolution::R8192); settings.common.antialiasing = bake::BakeAntialiasing::Subsampling8x8; - settings.common.apply_diffusion = false; + settings.common.apply_diffusion = true; + settings.sync.set_shares(bake::BakeSyncGroup::Map(bake::BakedMap::Height), false); settings.high_poly.ignore_backface_suffix = "_two_sided".into(); settings.cage.kind = bake::CageType::CustomFile; settings.skew.edge_protection = true; diff --git a/crates/engine/src/bake/bake_checks.rs b/crates/engine/src/bake/bake_checks.rs index 3ea93729..f25ed63c 100644 --- a/crates/engine/src/bake/bake_checks.rs +++ b/crates/engine/src/bake/bake_checks.rs @@ -39,7 +39,7 @@ impl Session { pub fn bake_name_pairs(&self, texture_set: usize) -> Result>> { let set = self.doc.project.texture_set(texture_set)?; let settings = &set.bake.high_poly; - let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); + let high = self.doc.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings))) } diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index 0d4d5ffe..bcdb2bcc 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -6,6 +6,8 @@ use texturecraft_geom::{BaseColor, Mesh}; #[derive(Clone, Debug)] pub struct BakeMesh { pub name: String, + /// The folder the file was read from, when it was picked from disk this session (projects don't keep it) + pub folder: Option, pub bytes: Arc>, pub mesh: Arc, pub base_color: Vec>>, diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs index da0e4a97..b609e106 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -2,8 +2,7 @@ use super::{BakeMesh, MergedHigh}; use std::sync::{Arc, OnceLock}; use texturecraft_geom::{Bvh, Mesh}; -/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the -/// undo history. +/// The high-definition meshes and the cage; undo and redo restore them with the document #[derive(Clone, Debug, Default)] pub struct BakeMeshes { pub(crate) low_base_color: OnceLock>, diff --git a/crates/engine/src/bake/high_poly_load.rs b/crates/engine/src/bake/high_poly_load.rs new file mode 100644 index 00000000..7a69d30e --- /dev/null +++ b/crates/engine/src/bake/high_poly_load.rs @@ -0,0 +1,75 @@ +use std::sync::Arc; + +use texturecraft_formats::MeshFile; + +use super::mesh_map_command::{ADD_HIGH_POLY_LABEL, parse_mesh, unique_name}; +use super::{BakeMesh, BakeMeshes, MergedHigh}; +use crate::{Result, Session}; + +/// A high poly file parsed and merged with the meshes it joins, which a worker thread can prepare while the session stays in use +pub struct HighPolyLoad { + /// The name the file was picked by, before it was made unique in the list + file_name: String, + added: BakeMesh, + /// The list the mesh joined, with it at the end + high: Vec, + /// `high` as bakes see it + merged: Option, + /// Files the mesh refers to that could not be read, as messages for the log + warnings: Vec, +} + +impl HighPolyLoad { + /// Parse `file` and merge it with the high polys of `meshes` + pub fn prepare(meshes: &BakeMeshes, file: MeshFile) -> Result { + let mut added = parse_mesh(&file.name, file.bytes)?; + let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect(); + added.name = unique_name(&file.name, &taken); + + let mut joined = BakeMeshes { high: meshes.high.clone(), ..Default::default() }; + joined.high.push(added.clone()); + joined.rebuild(); + Ok(Self { file_name: file.name, added, high: joined.high, merged: joined.merged, warnings: file.warnings }) + } + + /// Read the mesh file at `path`, then [`HighPolyLoad::prepare`] it + #[cfg(not(target_arch = "wasm32"))] + pub fn read(meshes: &BakeMeshes, path: &str) -> Result { + Self::prepare(meshes, crate::file_cmds::read_mesh("bake.highPoly.add", path)?) + } + + /// Whether `current` is still the list this mesh was merged into + fn joins(&self, current: &[BakeMesh]) -> bool { + let joined = &self.high[..self.high.len() - 1]; + joined.len() == current.len() + && joined.iter().zip(current).all(|(joined, current)| joined.name == current.name && Arc::ptr_eq(&joined.mesh, ¤t.mesh)) + } +} + +impl Session { + /// Add a prepared high poly as one undo step; every texture set then bakes from the high polys. Returns its name + pub fn apply_high_poly_load(&mut self, load: HighPolyLoad) -> String { + let before = self.doc.clone(); + let meshes = &mut self.doc.bake_meshes; + let mut added = load.added.clone(); + if load.joins(&meshes.high) { + meshes.high = load.high; + meshes.merged = load.merged; + } else { + // The list changed while the file loaded, so the mesh joins the list as it is now + let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect(); + added.name = unique_name(&load.file_name, &taken); + meshes.high.push(added.clone()); + meshes.rebuild(); + } + + let textures = added.base_color.iter().flatten().filter(|color| !color.texels.is_empty()).count(); + self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", added.name, added.mesh.triangle_count())); + self.log.warnings("Baker", load.warnings); + for set in &mut self.doc.project.texture_sets { + set.bake.high_poly.use_low_as_high = false; + } + self.push_history(ADD_HIGH_POLY_LABEL, before); + added.name + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef27ea3..6bb70d19 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -9,19 +9,26 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; -use super::{BakeCageInputs, MergedHigh}; +use super::{BakeCageInputs, HighPolyLoad, MergedHigh}; use crate::{BakeMesh, BakeTask, StreamedBake}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ - BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, 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}; +/// Undo step names of the bake mesh edits +pub(super) const ADD_HIGH_POLY_LABEL: &str = "Add high poly mesh"; +const REMOVE_HIGH_POLY_LABEL: &str = "Remove high poly mesh"; +const SET_CAGE_LABEL: &str = "Load cage mesh"; +const REMOVE_CAGE_LABEL: &str = "Remove cage mesh"; + pub(super) fn specs() -> Vec { vec![ cmd!( @@ -55,8 +62,11 @@ pub(super) fn specs() -> Vec { cmd!("bake.highPoly.list", "List high definition meshes", [], None, "{}", always, |s, _| Ok(meshes_json(s))), cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set), cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| { - s.bake_meshes.cage = None; - s.modified = true; + if s.doc.bake_meshes.cage.is_some() { + let before = s.doc.clone(); + s.doc.bake_meshes.cage = None; + s.push_history(REMOVE_CAGE_LABEL, before); + } Ok(meshes_json(s)) }), ] @@ -86,8 +96,8 @@ fn chosen_tracer(installed: Option<&Arc>, enabled: bool) -> Option String { +/// A mesh file name made unique among `taken` (and safe as a project file entry) +pub(super) fn unique_name(file_name: &str, taken: &[&str]) -> String { let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh"); let base = texturecraft_formats::sanitize_resource_name(leaf); let mut name = base.clone(); @@ -99,10 +109,11 @@ fn unique_name(file_name: &str, taken: &[&str]) -> String { name } -fn parse_mesh(file_name: &str, bytes: Vec) -> Result { +pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { let h = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let base_color = h.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); - Ok(BakeMesh { name: file_name.to_string(), bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color }) + let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty()); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color }) } impl Session { @@ -114,8 +125,9 @@ impl Session { 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()) { - self.bake_meshes + let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) { + self.doc + .bake_meshes .low_base_color .get_or_init(|| match &self.mesh_source { Some((extension, bytes)) => texturecraft_formats::import_high_poly_bytes(&format!("mesh.{extension}"), bytes) @@ -179,7 +191,7 @@ impl Session { /// 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() }) + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.doc.bake_meshes.merged.clone() }) } /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage @@ -189,7 +201,7 @@ impl Session { return Ok(None); } - let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + let cage = self.doc.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; Ok(Some(cage.mesh.clone())) } @@ -260,37 +272,38 @@ impl Session { Ok(tracer) } - /// Add a high-definition mesh from file bytes (the web picker, the desktop dialog and - /// `bake.highPoly.add`); every texture set then bakes from the high polys. Returns its name. + /// Add a high-definition mesh from file bytes as one undo step; every texture set then bakes from the high polys. Returns its name pub fn add_high_poly_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - let mut m = parse_mesh(file_name, bytes)?; - let taken: Vec<&str> = self.bake_meshes.high.iter().map(|h| h.name.as_str()).collect(); - m.name = unique_name(file_name, &taken); - let textures = m.base_color.iter().flatten().filter(|c| !c.texels.is_empty()).count(); - self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", m.name, m.mesh.triangle_count())); - let name = m.name.clone(); - self.bake_meshes.high.push(m); - self.bake_meshes.rebuild(); - for set in &mut self.doc.project.texture_sets { - set.bake.high_poly.use_low_as_high = false; - } - self.modified = true; - Ok(name) + let file = texturecraft_formats::MeshFile { name: file_name.to_string(), bytes, warnings: Vec::new() }; + let load = HighPolyLoad::prepare(&self.doc.bake_meshes, file)?; + Ok(self.apply_high_poly_load(load)) } - /// Remove high-definition mesh `index`. + /// Remove high-definition mesh `index` as one undo step pub fn remove_high_poly(&mut self, index: usize) -> Result { - if index >= self.bake_meshes.high.len() { + if index >= self.doc.bake_meshes.high.len() { return Err(EngineError::Other(format!("no high poly mesh {index}"))); } - let removed = self.bake_meshes.high.remove(index); - self.bake_meshes.rebuild(); - self.modified = true; + + let before = self.doc.clone(); + let removed = self.doc.bake_meshes.high.remove(index); + self.doc.bake_meshes.rebuild(); + self.push_history(REMOVE_HIGH_POLY_LABEL, before); Ok(removed) } - /// Use a cage mesh (same triangles as the low poly) from file bytes. + /// Use a cage mesh (same triangles as the low poly) from file bytes as one undo step. Returns its name pub fn set_cage_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + let cage = self.cage_from_bytes(file_name, bytes)?; + let name = cage.name.clone(); + let before = self.doc.clone(); + self.doc.bake_meshes.cage = Some(cage); + self.push_history(SET_CAGE_LABEL, before); + Ok(name) + } + + /// Parse a cage mesh file, refusing one whose triangles are not the low poly's + fn cage_from_bytes(&self, file_name: &str, bytes: Vec) -> Result { let mut m = parse_mesh(file_name, bytes)?; if m.mesh.triangle_count() != self.mesh.triangle_count() { return Err(EngineError::Other(format!( @@ -301,33 +314,36 @@ impl Session { } m.name = unique_name(file_name, &[]); m.base_color.clear(); - let name = m.name.clone(); - self.bake_meshes.cage = Some(m); - self.modified = true; - Ok(name) + Ok(m) } - /// Add mesh file `f` as a high-definition mesh, or set it as the cage, logging what it could - /// not fold in. Replies like `bake.highPoly.add` / `bake.cage.set`: `{name, meshes}`. + /// Add mesh file `f` as a high poly or the cage, logging what it could not fold in; replies `{name, meshes}` like `bake.highPoly.add` / `bake.cage.set` pub fn add_bake_mesh(&mut self, f: texturecraft_formats::MeshFile, cage: bool) -> Result { - let name = if cage { self.set_cage_bytes(&f.name, f.bytes)? } else { self.add_high_poly_bytes(&f.name, f.bytes)? }; - self.log.warnings("Baker", f.warnings); + let name = if cage { + let name = self.set_cage_bytes(&f.name, f.bytes)?; + self.log.warnings("Baker", f.warnings); + name + } else { + let load = HighPolyLoad::prepare(&self.doc.bake_meshes, f)?; + self.apply_high_poly_load(load) + }; Ok(json!({ "name": name, "meshes": meshes_json(self) })) } - /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped. + /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped pub(crate) fn load_bake_meshes(&mut self, high: Vec, cage: Option) { for (name, bytes) in high { match parse_mesh(&name, bytes) { - Ok(m) => self.bake_meshes.high.push(m), + Ok(m) => self.doc.bake_meshes.high.push(m), Err(e) => self.log.warn("Baker", format!("skipped high poly mesh: {e}")), } } - self.bake_meshes.rebuild(); - if let Some((name, bytes)) = cage - && let Err(e) = self.set_cage_bytes(&name, bytes) - { - self.log.warn("Baker", format!("skipped cage mesh: {e}")); + self.doc.bake_meshes.rebuild(); + if let Some((name, bytes)) = cage { + match self.cage_from_bytes(&name, bytes) { + Ok(cage) => self.doc.bake_meshes.cage = Some(cage), + Err(e) => self.log.warn("Baker", format!("skipped cage mesh: {e}")), + } } } @@ -356,10 +372,10 @@ impl Session { .collect() } - /// The bake meshes for a project file: (high polys, cage). + /// The bake meshes for a project file: (high polys, cage) pub(crate) fn saved_bake_meshes(&self) -> (Vec, Option) { let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone()); - (self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry)) + (self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry)) } } @@ -367,7 +383,7 @@ impl Session { pub fn meshes_json(s: &Session) -> Value { let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::>() }); let painted = |target| s.doc.bake_paint.get(&(s.ts(), target)).map(|map| json!({ "width": map.width, "height": map.height })); - json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| { + json!({ "highPoly": s.doc.bake_meshes.high.iter().map(one).collect::>(), "cage": s.doc.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| { let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0 }; json!({"textureSet": texture_set, "target": target, "width": map.width, "height": map.height, "paintedTexels": map.values.iter().filter(|value| **value != default).count()}) }).collect::>() }) @@ -390,14 +406,17 @@ fn high_add(s: &mut Session, p: &Value) -> Result { fn high_remove(s: &mut Session, p: &Value) -> Result { if boolp(p, "all") == Some(true) { - s.bake_meshes.high.clear(); - s.bake_meshes.rebuild(); - s.modified = true; + if !s.doc.bake_meshes.high.is_empty() { + let before = s.doc.clone(); + s.doc.bake_meshes.high.clear(); + s.doc.bake_meshes.rebuild(); + s.push_history(REMOVE_HIGH_POLY_LABEL, before); + } return Ok(meshes_json(s)); } let index = match (u64p(p, "index"), strp(p, "name")) { (Some(i), _) => usize::try_from(i).unwrap_or(usize::MAX), - (None, Some(n)) => s.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, + (None, Some(n)) => s.doc.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, (None, None) => return Err(bad("bake.highPoly.remove", "`index`, `name` or `all` is required")), }; s.remove_high_poly(index)?; @@ -408,8 +427,8 @@ fn cage_set(s: &mut Session, p: &Value) -> Result { s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true) } -/// Texture sets named by `ts` (default: the active one). -fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { +/// Texture sets named by `ts` (default: the active one) +pub(super) fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { let n = s.set_count(); let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}"))); match p.get("ts") { @@ -465,8 +484,9 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> if let Some(model) = params.get("model") { let replacement: BakeSettings = serde_json::from_value(model.clone()).map_err(|error| bad(command, error.to_string()))?; validate_model_settings(&replacement, command, boolp(params, "preset") == Some(true), None)?; - let is_enabled = settings.common.is_enabled; - *settings = replacement; + let (is_enabled, sync) = (settings.common.is_enabled, std::mem::take(&mut settings.sync)); + // Sync membership is not a setting: only `bake.sync` changes it + *settings = BakeSettings { sync, ..replacement }; if boolp(params, "preserveEnabled") == Some(true) { settings.common.is_enabled = is_enabled; } @@ -708,19 +728,37 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< } fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { - let next = updated_settings(session, params, command)?; - let sets = next.iter().map(|(index, _)| *index).collect(); - if next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)) { - session.edit("Bake Settings", |session| { - for (index, settings) in next { - session.doc.project.texture_set_mut(index)?.bake = settings; - } - Ok(()) - })?; - } + let targets = updated_settings(session, params, command)?; + let sets = targets.iter().map(|(index, _)| *index).collect(); + let next = with_sync_partners(&session.doc.project, targets, command)?; + + super::sync_command::store(session, "Bake Settings", next)?; Ok(sets) } +/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group +fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { + let mut next: BTreeMap = BTreeMap::new(); + for (target, settings) in &targets { + let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue }; + let Some(changed) = model_patch::changed_fields(&json!(before), &json!(settings)) else { continue }; + + let groups = std::iter::once(BakeSyncGroup::Common).chain(BakedMap::ALL.map(BakeSyncGroup::Map)); + for group in groups { + for partner in project.bake_synced_sets(*target, group).into_iter().filter(|partner| partner != target) { + let Some(set) = project.texture_sets.get(partner) else { continue }; + let entry = next.entry(partner).or_insert_with(|| set.bake.clone()); + let mut model = json!(entry); + model_patch::apply_patch(&mut model, &changed, command)?; + let patched: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; + entry.copy_group(&patched, group); + } + } + } + next.extend(targets); + Ok(next.into_iter().collect()) +} + fn settings(session: &mut Session, params: &Value) -> Result { let sets = set_settings(session, params, "bake.settings")?; let result: Vec = sets diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index ef9dc935..1be548db 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -5,6 +5,7 @@ mod bake_checks; mod bake_mesh; mod bake_meshes; mod bake_task; +mod high_poly_load; mod high_poly_missed; mod layout; mod merged_high; @@ -14,12 +15,14 @@ mod paint_command; mod preserve_tiles; mod streamed_bake; mod streamed_map; +mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; +pub use high_poly_load::HighPolyLoad; pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed}; pub use merged_high::MergedHigh; pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params}; @@ -36,5 +39,6 @@ pub(crate) fn specs() -> Vec { let mut commands = mesh_map_command::specs(); commands.extend(paint_command::specs()); commands.extend(tile_command::specs()); + commands.extend(sync_command::specs()); commands } diff --git a/crates/engine/src/bake/model_patch.rs b/crates/engine/src/bake/model_patch.rs index 871d7dc8..6532f914 100644 --- a/crates/engine/src/bake/model_patch.rs +++ b/crates/engine/src/bake/model_patch.rs @@ -9,7 +9,8 @@ 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 { +/// The fields of `after` that differ from `before`, nested as a `bake.settings` patch; `None` when nothing changed +pub(super) fn changed_fields(before: &Value, after: &Value) -> Option { if before == after { return None; } diff --git a/crates/engine/src/bake/sync_command.rs b/crates/engine/src/bake/sync_command.rs new file mode 100644 index 00000000..e244e507 --- /dev/null +++ b/crates/engine/src/bake/sync_command.rs @@ -0,0 +1,268 @@ +//! Sharing bake settings between texture sets: live sync groups, and one-off copies from the bake menus + +use serde_json::{Value, json}; +use texturecraft_core::{BakeSettings, BakeSyncGroup, BakedMap}; + +use super::mesh_map_command::sets_param; +use crate::commands::{CommandSpec, always, bad, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "bake.sync", + "Sync bake settings", + [], + None, + "{group: \"common\"|map id, ts: index|[indices]|\"all\"} → {group, ts}; exactly these texture sets share the group's settings from now on, and the ones added take the settings the group shares", + always, + sync + ), + cmd!( + "bake.copy", + "Copy bake settings", + [], + None, + "{what: \"settings\"|\"checked\"|\"check\", map?: id, from?: index (default: the active set), ts: index|[indices]|\"all\"} → {ts}; settings: every setting and which maps are checked, or with map that map's settings; checked: which maps are checked; check: check map. Settings also reach the sets sharing a group with a target, whose checkboxes stay their own", + always, + copy + ), + ] +} + +fn group_param(params: &Value, command: &str) -> Result { + match strp(params, "group") { + Some("common") => Ok(BakeSyncGroup::Common), + Some(id) => BakedMap::parse(id).map(BakeSyncGroup::Map).ok_or_else(|| bad(command, format!("unknown group {id}"))), + None => Err(bad(command, "`group` must be \"common\" or a mesh map id")), + } +} + +fn group_id(group: BakeSyncGroup) -> &'static str { + match group { + BakeSyncGroup::Common => "common", + BakeSyncGroup::Map(map) => map.id(), + } +} + +fn sync(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.sync"; + let group = group_param(params, COMMAND)?; + let members = sets_param(session, COMMAND, params)?; + let sets = &session.doc.project.texture_sets; + + // Additions take the settings of a set that already shares them; with none left, of the active set when it joins, else of the first + let staying = members.iter().copied().find(|index| sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); + let active = session.ts(); + let source = staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()); + let source = source.and_then(|index| sets.get(index)).map(|set| set.bake.clone()); + + let next: Vec<(usize, BakeSettings)> = sets + .iter() + .enumerate() + .map(|(index, set)| { + let mut settings = set.bake.clone(); + let joins = members.contains(&index); + if let Some(source) = source.as_ref().filter(|_| joins && !settings.sync.shares(group)) { + settings.copy_group(source, group); + } + settings.sync.set_shares(group, joins); + (index, settings) + }) + .collect(); + store(session, "Sync bake settings", next)?; + Ok(json!({ "group": group_id(group), "ts": members })) +} + +fn copy(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.copy"; + let map = strp(params, "map").map(|id| BakedMap::parse(id).ok_or_else(|| bad(COMMAND, format!("unknown mesh map {id}")))).transpose()?; + let from = match u64p(params, "from") { + Some(index) => usize::try_from(index).map_err(|_| bad(COMMAND, "invalid `from`"))?, + None => session.ts(), + }; + let source = session.doc.project.texture_set(from)?.bake.clone(); + let targets = sets_param(session, COMMAND, params)?; + let maps: Vec = map.map_or_else(|| BakedMap::ALL.to_vec(), |map| vec![map]); + + let mut next: Vec = session.doc.project.texture_sets.iter().map(|set| set.bake.clone()).collect(); + let project = &session.doc.project; + // Every target together with the sets sharing `group` with it, so a sync group never drifts apart + let reached = |group: BakeSyncGroup| -> Vec { + let mut reached: Vec = targets.iter().flat_map(|target| project.bake_synced_sets(*target, group)).collect(); + reached.sort_unstable(); + reached.dedup(); + reached + }; + match strp(params, "what") { + Some("settings") => { + let groups = map.map_or_else( + || std::iter::once(BakeSyncGroup::Common).chain(maps.iter().map(|map| BakeSyncGroup::Map(*map))).collect(), + |map| vec![BakeSyncGroup::Map(map)], + ); + for group in groups { + for index in reached(group) { + if let Some(settings) = next.get_mut(index) { + settings.copy_group(&source, group); + } + } + } + if map.is_none() { + for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| targets.contains(index)) { + for map in BakedMap::ALL { + settings.maps.set_enabled(map, source.maps.is_enabled(map)); + } + } + } + } + Some(what @ ("checked" | "check")) => { + if what == "check" && map.is_none() { + return Err(bad(COMMAND, "`check` needs a `map`")); + } + for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| targets.contains(index)) { + for map in &maps { + settings.maps.set_enabled(*map, what == "check" || source.maps.is_enabled(*map)); + } + } + } + _ => return Err(bad(COMMAND, "`what` must be settings, checked or check")), + } + + store(session, "Copy bake settings", next.into_iter().enumerate().collect())?; + Ok(json!({ "ts": targets })) +} + +/// Write each set's `next` bake settings as one undo step labelled `label`; nothing when none changed +pub(super) fn store(session: &mut Session, label: &str, next: Vec<(usize, BakeSettings)>) -> Result<()> { + let changed = + |session: &Session| next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)); + if !changed(session) { + return Ok(()); + } + + session.edit(label, |session| { + for (index, settings) in next { + session.doc.project.texture_set_mut(index)?.bake = settings; + } + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{execute, sample_session}; + use texturecraft_core::BakeSettings; + + fn session() -> Session { + let session = sample_session(128, 32).unwrap(); + assert_eq!(session.set_count(), 2); + session + } + + fn bake(session: &Session, index: usize) -> &BakeSettings { + &session.doc.project.texture_sets[index].bake + } + + #[test] + fn projects_saved_before_sync_share_everything() { + let settings: BakeSettings = serde_json::from_value(json!({ "common": { "dilation": 4 } })).unwrap(); + assert!(settings.sync.common); + assert!(BakedMap::ALL.iter().all(|map| settings.sync.shares(BakeSyncGroup::Map(*map)))); + } + + #[test] + fn a_set_left_out_of_common_sync_keeps_its_own_common_settings() { + let mut session = session(); + assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0, 1]); + + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap(); + assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0]); + assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Common), [1]); + assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Map(BakedMap::Normal)), [0, 1], "map sync is separate"); + + let reached = session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common); + execute(&mut session, "bake.settings", &json!({ "ts": reached, "patch": { "common": { "dilation": 7 } } })).unwrap(); + assert_eq!((bake(&session, 0).common.dilation, bake(&session, 1).common.dilation), (7, 32)); + } + + #[test] + fn a_set_joining_a_group_takes_its_settings_and_keeps_its_own_inclusion() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 3; + session.doc.project.texture_sets[1].bake.common.is_enabled = false; + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[1].bake.common.dilation = 5; + + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": "all" })).unwrap(); + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": "all" })).unwrap(); + assert_eq!(bake(&session, 1).maps.ao.parameters, bake(&session, 0).maps.ao.parameters); + assert_eq!(bake(&session, 1).common.dilation, bake(&session, 0).common.dilation); + assert!(!bake(&session, 1).common.is_enabled, "whether the set bakes is its own"); + + session.undo().unwrap(); + assert_eq!(bake(&session, 1).common.dilation, 5, "one undo per sync"); + } + + #[test] + fn copies_check_maps_and_carry_settings_without_linking() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "height", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[0].bake.maps.height.parameters.scaling_divisor = 9.0; + + execute(&mut session, "bake.copy", &json!({ "what": "check", "map": "height", "ts": "all" })).unwrap(); + assert!(bake(&session, 0).maps.height.is_enabled && bake(&session, 1).maps.height.is_enabled); + + execute(&mut session, "bake.copy", &json!({ "what": "settings", "map": "height", "from": 0, "ts": [1] })).unwrap(); + assert_eq!(bake(&session, 1).maps.height.parameters.scaling_divisor, 9.0); + assert!(!bake(&session, 1).sync.shares(BakeSyncGroup::Map(BakedMap::Height)), "a copy does not link"); + + session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); + execute(&mut session, "bake.copy", &json!({ "what": "checked", "from": 0, "ts": [1] })).unwrap(); + assert_eq!(bake(&session, 1).maps.enabled().collect::>(), [BakedMap::Normal]); + } + + #[test] + fn a_copy_reaches_the_sets_sharing_the_group_with_its_target() { + let mut session = session(); + let third = session.doc.project.texture_sets[1].clone(); + session.doc.project.texture_sets.push(third); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0, 1] })).unwrap(); + session.doc.project.texture_sets[2].bake.maps.ao.parameters.rays.rays = 3; + let height_checked = !bake(&session, 0).maps.is_enabled(BakedMap::Height); + session.doc.project.texture_sets[2].bake.maps.set_enabled(BakedMap::Height, height_checked); + + execute(&mut session, "bake.copy", &json!({ "what": "settings", "from": 2, "ts": [0] })).unwrap(); + assert_eq!((bake(&session, 0).maps.ao.parameters.rays.rays, bake(&session, 1).maps.ao.parameters.rays.rays), (3, 3), "set 1 shares AO with set 0"); + assert!(!bake(&session, 2).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion))); + assert_eq!(bake(&session, 0).maps.is_enabled(BakedMap::Height), height_checked, "every setting includes which maps are checked"); + assert_ne!(bake(&session, 1).maps.is_enabled(BakedMap::Height), height_checked, "the set sharing a group keeps its own checkboxes"); + } + + #[test] + fn loading_a_preset_on_one_set_keeps_its_sync_groups_and_reaches_the_sets_sharing_them() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [1] })).unwrap(); + let mut preset = bake(&session, 0).clone(); + preset.common.dilation = 9; + preset.maps.ao.parameters.rays.rays = 5; + preset.sync = Default::default(); + + let params = json!({ "ts": 0, "model": preset, "preserveEnabled": true, "preset": true }); + execute(&mut session, "bake.settings", ¶ms).unwrap(); + assert!(!bake(&session, 0).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion)), "a preset is settings, not membership"); + assert_eq!(bake(&session, 1).common.dilation, 9, "set 1 shares Common Settings with set 0"); + assert_ne!(bake(&session, 1).maps.ao.parameters.rays.rays, 5, "set 1 no longer shares AO with set 0"); + } + + #[test] + fn a_change_to_one_group_leaves_the_other_groups_of_the_sets_sharing_it_alone() { + let mut session = session(); + session.doc.project.texture_sets[1].bake.common.dilation = 3; + + execute(&mut session, "bake.settings", &json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 6 } } } } } })).unwrap(); + assert_eq!(bake(&session, 1).maps.ao.parameters.rays.rays, 6); + assert_eq!(bake(&session, 1).common.dilation, 3); + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 006bb979..59eaf446 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -209,8 +209,12 @@ impl Session { check_materials(&pf.project, &mesh)?; let source = pf.mesh.clone(); let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect(); - let mut s = - Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; + + let mut s = Session::new( + Document { bake_meshes: Default::default(), bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, + mesh, + source, + )?; s.sync_images(); s.load_bake_meshes(pf.high_poly, pf.cage); @@ -608,10 +612,7 @@ impl Session { Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file()) } - /// Replace the mesh with `file` (or re-read the project's own copy) and keep the project: - /// texture sets map by material index. Nothing changes unless the new mesh fits the project. - /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies - /// like `file.reimportMesh`: `{preserved?}`. + /// Replace the mesh with `file` (or re-read the project's own copy), keeping the project when the new mesh fits it; `preserve_strokes` moves painted pixels with the surface; replies `{preserved?}` pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { let (mesh, source, warnings, mesh_file) = match file { Some(f) => { @@ -625,27 +626,29 @@ impl Session { None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")), }, }; + check_materials(&self.doc.project, &mesh)?; let mut doc = self.doc.clone(); if let Some((ext, _)) = &source { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; } + let mut next = Session::new(doc, mesh, source)?; next.log.warnings("Importer", warnings); next.path = self.path.clone(); next.sync_images(); // The cage uses triangle indices and barycentrics, so it needs identical geometry - next.bake_meshes = self.bake_meshes.clone(); - next.bake_meshes.low_base_color = Default::default(); - if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { - next.bake_meshes.cage = None; + next.doc.bake_meshes.low_base_color = Default::default(); + if next.doc.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { + next.doc.bake_meshes.cage = None; next.log.warn("Project", "the cage mesh was dropped: the low-poly mesh changed"); } if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { next.log.warn("Project", "the skew map is laid over the old UV layout; check it in Bake mode"); } + next.modified = true; next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); @@ -1486,19 +1489,21 @@ f 1/1 2/2 3/3 std::fs::create_dir_all(&dir).unwrap(); let a = dir.join("a.obj"); std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); - // Same triangle count, other vertices. + // Same triangle count, other vertices let b = dir.join("b.obj"); std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); - let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; - s.bake_meshes.cage = Some(cage); - let _ = s.bake_meshes.low_base_color.set(Err("old".into())); - // The same mesh again keeps the cage but not the cached colours. + let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.doc.bake_meshes.cage = Some(cage); + let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); + + // The same mesh again keeps the cage but not the cached colours crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); - assert!(s.bake_meshes.cage.is_some()); - assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + assert!(s.doc.bake_meshes.cage.is_some()); + assert!(s.doc.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); - assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + assert!(s.doc.bake_meshes.cage.is_none(), "the cage was made for another mesh"); std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..7ac866b0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -90,7 +90,7 @@ pub mod uv_tile_cmds; pub mod view_cmds; pub mod warp_cmds; -pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; +pub use bake::{BakeMesh, BakeMeshes, BakeTask, HighPolyLoad, StreamedBake, StreamedMap}; pub use bake_preview::{BakePreview, PreviewShow}; pub use commands::{CommandSpec, check_enabled, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 678d7bb7..ac0b8636 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -70,7 +70,14 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); project.texture_sets.push(set); - Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() } + Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project, + pixels: PixelStore::default(), + baked: BTreeMap::new(), + resources: BTreeMap::new(), + } } impl Session { @@ -129,12 +136,22 @@ impl Session { .first() .and_then(|t| t.stack.last().copied()) .ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?; + let resources: BTreeMap>> = project_file.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); - let source = Document { bake_paint: BTreeMap::new(), project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), resources }; + let source = Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project: project_file.project, + pixels: project_file.pixels, + baked: BTreeMap::new(), + resources, + }; + let id = self.edit("Add smart material", |s| { for (name, bytes) in &source.resources { s.doc.resources.entry(name.clone()).or_insert_with(|| Arc::clone(bytes)); } + let ts = s.ts(); let sel = s.selected_layer(); let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group()); @@ -144,6 +161,7 @@ impl Session { s.target = StackTarget::Content; Ok(id) })?; + self.sync_images(); Ok(id) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..cb69ffb3 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -31,6 +31,8 @@ pub struct Document { pub bake_paint: BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc>, /// Imported image resources by name: original file bytes. pub resources: BTreeMap>>, + /// High-definition meshes and cage for baking (saved inside the project) + pub bake_meshes: crate::BakeMeshes, } /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). @@ -426,8 +428,6 @@ pub struct Session { pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Vec)>, - /// High-definition meshes and cage for baking (saved inside the project). - pub bake_meshes: crate::BakeMeshes, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -525,7 +525,6 @@ impl Session { mesh, bvh: Arc::new(bvh), mesh_source, - bake_meshes: Default::default(), caches, undo: Vec::new(), redo: Vec::new(), @@ -604,8 +603,7 @@ impl Session { Session::new_project_tiled(name, mesh, mesh_ref, mesh_source, resolution, None) } - /// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` for every - /// set, `Some(false)` for none, `None` for the sets whose UVs leave tile 1001. + /// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` every set, `Some(false)` none, `None` the sets whose UVs leave tile 1001 pub fn new_project_tiled( name: &str, mesh: Mesh, @@ -628,11 +626,20 @@ impl Session { ts.stack.push(id); project.texture_sets.push(ts); } + let mut s = Session::new( - Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, + Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project, + pixels: PixelStore::default(), + baked: BTreeMap::new(), + resources: BTreeMap::new(), + }, mesh, mesh_source, )?; + s.log.append(log); Ok(s) } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 8c7a2791..13479df9 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -223,14 +223,17 @@ impl Session { .and_then(|root| pf.project.layers.get(&root)) .and_then(|l| l.mask.clone()) .ok_or_else(|| EngineError::Other("the smart mask file has no mask".into()))?; + let resources: BTreeMap>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); let src = crate::session::Document { + bake_meshes: Default::default(), bake_paint: BTreeMap::new(), project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: BTreeMap::new(), }; + let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); self.edit(&format!("Apply smart mask {label}"), |s| { let (ts, _, _) = s.doc.project.locate(layer).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 4c5314ad..09b9eca6 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -65,15 +65,15 @@ fn high_poly_meshes_drive_the_bake_and_round_trip() { // Save and reopen: meshes, cage and settings come back let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); - let names = |session: &Session| session.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect::>(); + let names = |session: &Session| session.doc.bake_meshes.high.iter().map(|high| (high.name.clone(), high.mesh.triangle_count())).collect::>(); assert_eq!(names(&reloaded), names(&session)); - assert_eq!(reloaded.bake_meshes.cage.as_ref().map(|c| c.name.as_str()), Some("cage.obj")); + assert_eq!(reloaded.doc.bake_meshes.cage.as_ref().map(|cage| cage.name.as_str()), Some("cage.obj")); assert_eq!(reloaded.doc.project.texture_sets[0].bake, session.doc.project.texture_sets[0].bake); execute(&mut session, "bake.highPoly.remove", &json!({ "name": "hp_high.obj" })).unwrap(); - assert!(session.bake_meshes.high.is_empty()); + assert!(session.doc.bake_meshes.high.is_empty()); execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); - assert!(session.bake_meshes.cage.is_none()); + assert!(session.doc.bake_meshes.cage.is_none()); // Without high polys the bake falls back to the low poly execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"] })).unwrap(); @@ -81,6 +81,63 @@ fn high_poly_meshes_drive_the_bake_and_round_trip() { let _ = std::fs::remove_dir_all(std::path::Path::new(&high).parent().unwrap()); } +#[test] +fn high_poly_and_cage_edits_are_undo_steps() { + let mut session = plane_session(); + execute(&mut session, "bake.settings", &json!({ "ts": "all", "useLowAsHigh": true })).unwrap(); + let low = session.mesh.as_ref().clone(); + let high_names = |session: &Session| session.doc.bake_meshes.high.iter().map(|high| high.name.clone()).collect::>(); + let merged_triangles = |session: &Session| session.doc.bake_meshes.merged_high().map(|merged| merged.mesh.triangle_count()); + + session.add_high_poly_bytes("part_high.obj", obj(&low, 0.002, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + assert_eq!(session.undo_label(), Some("Add high poly mesh")); + assert!(!session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high); + + session.undo().unwrap(); + assert!(high_names(&session).is_empty(), "undo takes the high poly out"); + assert_eq!(merged_triangles(&session), None, "bakes no longer see it"); + assert!(session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high, "the setting the add changed comes back"); + + session.redo().unwrap(); + assert_eq!(high_names(&session), ["part_high.obj"]); + assert_eq!(merged_triangles(&session), Some(low.triangle_count())); + + execute(&mut session, "bake.highPoly.remove", &json!({ "index": 0 })).unwrap(); + session.undo().unwrap(); + assert_eq!(high_names(&session), ["part_high.obj"], "undo brings a removed high poly back"); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + session.undo().unwrap(); + assert_eq!(merged_triangles(&session), Some(low.triangle_count())); + + session.set_cage_bytes("cage.obj", obj(&low, 0.05, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + session.undo().unwrap(); + assert!(session.doc.bake_meshes.cage.is_none(), "undo takes the cage out"); + session.redo().unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + session.undo().unwrap(); + assert_eq!(session.doc.bake_meshes.cage.as_ref().map(|cage| cage.name.as_str()), Some("cage.obj"), "undo brings a removed cage back"); + + let steps = session.history_labels().len(); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + assert_eq!(session.history_labels().len(), steps + 2, "removing nothing adds no step"); +} + +#[test] +fn opening_a_project_with_bake_meshes_adds_no_undo_step() { + let mut session = plane_session(); + let low = session.mesh.as_ref().clone(); + session.add_high_poly_bytes("part_high.obj", obj(&low, 0.002, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + session.set_cage_bytes("cage.obj", obj(&low, 0.05, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert!(reloaded.doc.bake_meshes.cage.is_some() && reloaded.doc.bake_meshes.merged_high().is_some()); + assert!(reloaded.history_labels().is_empty()); + assert!(!reloaded.modified, "a project just opened has nothing to save"); +} + #[test] fn malformed_high_poly_input_errors_cleanly() { let mut session = plane_session(); @@ -94,7 +151,7 @@ fn malformed_high_poly_input_errors_cleanly() { assert!(execute(&mut session, "bake.highPoly.add", &json!({ "path": "/definitely/missing.obj" })).is_err()); assert!(execute(&mut session, "bake.highPoly.remove", &json!({ "index": 3 })).is_err()); assert!(execute(&mut session, "bake.highPoly.remove", &Value::Null).is_err()); - assert!(session.bake_meshes.high.is_empty() && session.bake_meshes.cage.is_none()); + assert!(session.doc.bake_meshes.high.is_empty() && session.doc.bake_meshes.cage.is_none()); assert_eq!(session.doc.project, before, "failed imports preserve project settings"); } @@ -380,7 +437,7 @@ fn opacity_samples_a_textured_gltf_high_poly() { // The textures come back with the project let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); - assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color); + assert_eq!(reloaded.doc.bake_meshes.high[0].base_color, session.doc.bake_meshes.high[0].base_color); } /// USDZ opacity uses the UsdPreviewSurface texture alpha @@ -441,7 +498,7 @@ fn opacity_samples_textures_next_to_a_high_poly() { // The project holds the folded file: the textures come back without the folder let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); - assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color, "{file}"); + assert_eq!(reloaded.doc.bake_meshes.high[0].base_color, session.doc.bake_meshes.high[0].base_color, "{file}"); } // A missing image is named in the log; the high poly still loads, untextured @@ -685,7 +742,7 @@ fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap(); assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh"); - assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert_eq!(s.doc.bake_meshes.high.len(), 1, "the high poly stays"); assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays"); assert!(s.modified, "the project differs from the saved one"); assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index 4b60f6f0..97dd4610 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -1,3 +1,5 @@ +use texturecraft_engine::core::BakedMap; + use crate::RunningBake; /// A background bake of one or more texture sets. @@ -7,4 +9,6 @@ pub struct BakeJob { pub total: usize, /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. pub mesh_id: u64, + /// The one map to bake (a row's quick bake) instead of the checked ones + pub only: Option, } diff --git a/crates/ui-egui/src/bake_mode/bake_checks.rs b/crates/ui-egui/src/bake_mode/bake_checks.rs index 36b91298..4245a5a1 100644 --- a/crates/ui-egui/src/bake_mode/bake_checks.rs +++ b/crates/ui-egui/src/bake_mode/bake_checks.rs @@ -50,7 +50,7 @@ pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc, Arc>)>(id)) && cached_key == key && cached_high.ptr_eq(&high) diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs index 14dc7fd5..2ece6800 100644 --- a/crates/ui-egui/src/bake_mode/breadcrumb.rs +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -1,35 +1,89 @@ -use egui::{RichText, Ui}; +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; 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}; +use crate::theme::{Tokens, semibold}; -/// 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) { +/// The breadcrumb's line and the air under its hairline +const LINE_HEIGHT: f32 = 32.0; +const AIR_BELOW: f32 = 10.0; + +/// A caret's click square, and the air between a caret and its name +const CARET_BOX: f32 = 18.0; +const CARET_TO_NAME: f32 = 4.0; + +/// Air between the set's name and the next caret +const NAME_TO_CARET: f32 = 8.0; + +/// Size of the carets and of the reset glyph +const CARET_SIZE: f32 = 12.0; +const RESET_SIZE: f32 = 14.0; +const RESET_BOX: f32 = 20.0; + +/// Size of the names +const NAME_SIZE: f32 = 12.0; + +/// › texture set › map above Mesh Map Settings, each caret a menu to switch it, with ⟲ (Restore Defaults) at the right when the map has parameters; returns whether ⟲ was clicked +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, restorable: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); 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(); + let (line, _) = ui.allocate_exact_size(vec2(ui.available_width(), LINE_HEIGHT), Sense::hover()); + let center_y = line.center().y; + let painter = ui.painter().clone(); - 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)); + let mut x = line.left(); + let set_caret = caret(ui, &painter, &tokens, x, center_y, "texture_set_caret", tr("Switch Texture Set")); + x += CARET_BOX + CARET_TO_NAME; + let set_name = set_names.get(active_set).map_or("", String::as_str); + let set_galley = painter.layout_no_wrap(set_name.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let set_width = set_galley.size().x; + painter.galley(pos2(x, center_y - set_galley.size().y / 2.0), set_galley, tokens.text); + x += set_width + NAME_TO_CARET; + let map_caret = caret(ui, &painter, &tokens, x, center_y, "map_caret", tr("Switch Mesh Map")); + x += CARET_BOX + CARET_TO_NAME; + painter.text(pos2(x, center_y), Align2::LEFT_CENTER, tr(baked_map_label(selected)), semibold(NAME_SIZE), tokens.text_strong); - 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(); - } + egui::Popup::menu(&set_caret).show(|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.label(RichText::new(tr(baked_map_label(selected))).strong()); + } }); + egui::Popup::menu(&map_caret).show(|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); + } + } + }); + + let mut restore = false; + if restorable { + let rect = Rect::from_center_size(pos2(line.right() - RESET_BOX / 2.0, center_y), vec2(RESET_BOX, RESET_BOX)); + let response = ui.interact(rect, ui.scope_id().with("restore_defaults"), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, true, tr("Restore Defaults"))); + let response = response.on_hover_text(tr("Restore Defaults")); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_SIZE), color); + restore = response.clicked(); + } + + painter.line_segment([pos2(line.left(), line.bottom()), pos2(line.right(), line.bottom())], Stroke::new(1.0, tokens.separator)); + ui.add_space(AIR_BELOW); + restore +} + +/// A caret at `left` that opens a menu, answering as `label` +fn caret(ui: &mut Ui, painter: &egui::Painter, tokens: &Tokens, left: f32, center_y: f32, salt: &str, label: &str) -> egui::Response { + let rect = Rect::from_min_size(pos2(left, center_y - CARET_BOX / 2.0), vec2(CARET_BOX, CARET_BOX)); + let response = ui.interact(rect, ui.scope_id().with(salt), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, true, label)); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, icon::CARET_RIGHT, FontId::proportional(CARET_SIZE), color); + response } diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index 1953d2d3..aca0ed1d 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -1,139 +1,161 @@ -use super::controls::{choice, hint, integer, number, section, text_input}; +use super::controls::{choice, integer, number, section, text_input}; use crate::TextureCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; -use crate::widgets::icon_button; -use egui::Ui; +use crate::i18n::{tr, trf}; +use crate::property_sheet::{FileListAdd, FileRow, PropertySheet}; use egui_phosphor::regular as icon; use serde_json::{Map, Value, json}; use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -/// How many rows the high poly list box is tall -const HIGH_POLY_LIST_ROWS: f32 = 5.0; +/// The high poly list is never shorter than this many rows, so it reads as a list while empty +const HIGH_POLY_LIST_MIN_ROWS: usize = 2; -/// Space between the panel's sections, in points -const SECTION_GAP: f32 = 8.0; +/// The Cage and Skew Correction ⟲ menus' items, in their order: reset the parameters, clear the paint strokes, both +const RESET_PARAMETERS: usize = 0; +const CLEAR_STROKES: usize = 1; +const RESET_AND_CLEAR: usize = 2; + +/// The cage list holds one file, so one row shows while it is empty +const CAGE_LIST_MIN_ROWS: usize = 1; + +/// Largest cage distance the sliders offer, and their decimals (relative to the bounding box, the reference's range) +const MAX_CAGE_DISTANCE: f32 = 0.05; +const CAGE_DISTANCE_DECIMALS: usize = 4; + +/// A paint brush's first value: half the frontal distance for the cage, full correction for skew +const CAGE_BRUSH_VALUE: f32 = 0.5; +const SKEW_BRUSH_VALUE: f32 = 1.0; + +/// The paint brush's radius range, in UV units +const BRUSH_RADIUS: std::ops::RangeInclusive = 0.002..=0.2; /// Widest dilation the slider offers, in texels (the bake settings command accepts the same) const MAX_DILATION_WIDTH: u32 = 128; -/// The output and high-poly sections, then cage and skew, greyed with the reason when they can't apply -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { +/// The Common Settings, Cage and Skew Correction sections, cage and skew greyed with the reason when they can't apply +pub(super) fn show(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, 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; - if section(ui, tr("Common Parameters"), |ui| { - output_size(ui, &mut settings.common); - choice( - ui, - tr("Antialiasing"), - &mut settings.common.antialiasing, - &[ - (BakeAntialiasing::None, tr("None")), - (BakeAntialiasing::Subsampling2x2, tr("Subsampling 2x2")), - (BakeAntialiasing::Subsampling4x4, tr("Subsampling 4x4")), - (BakeAntialiasing::Subsampling8x8, tr("Subsampling 8x8")), - ], - ); - integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); - 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); - } - }); + let has_high = !app.session.doc.bake_meshes.high.is_empty(); + let common_reset = section(sheet, tr("Common Settings"), &[], |sheet| { + sheet.sub_header(tr("Output Settings"), |sheet| { + output_size(sheet, &mut settings.common); + let antialiasing = BakeAntialiasing::ALL.map(|option| (option, antialiasing_label(option))); + choice(sheet, tr("Antialiasing"), &mut settings.common.antialiasing, &antialiasing); + integer(sheet, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); + sheet.check(tr("Apply Diffusion"), &mut settings.common.apply_diffusion); + }); + sheet.sub_header(tr("High-Poly Parameters"), |sheet| { + sheet.check(tr("Use Low Poly Mesh as High Poly Mesh"), &mut settings.high_poly.use_low_as_high); + high_poly_scene(app, sheet); - // Without a high poly the reference shows everything that needs one greyed, not hidden - let has_high = !app.session.bake_meshes.high.is_empty(); - ui.add_space(SECTION_GAP); - ui.push_id("high_poly", |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_scene(app, ui); - ui.add_enabled_ui(has_high, |ui| { - ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); + // Without a high poly the reference shows everything that needs one greyed, not hidden + sheet.greyed(has_high, Some(tr("These settings apply once a high poly mesh is loaded.")), |sheet| { + sheet.check(tr("Ignore Backface"), &mut settings.high_poly.ignore_backface); choice( - ui, + sheet, tr("Match"), &mut settings.high_poly.match_mode, &[(MeshMatchMode::Always, tr("Always")), (MeshMatchMode::ByMeshName, tr("By Mesh Name"))], ); - text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); - text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); - text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); + text_input(sheet, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); + text_input(sheet, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); + text_input(sheet, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); }); - }) { - settings.high_poly = Default::default(); - reset.insert("high_poly".into(), json!(settings.high_poly)); + }); + }); + if common_reset.is_some() { + // Restoring keeps whether the texture set is included in the bake + settings.common = CommonBakeSettings { is_enabled: settings.common.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); + settings.high_poly = Default::default(); + reset.insert("high_poly".into(), json!(settings.high_poly)); + } + + let mut menu = [""; 3]; + (menu[RESET_PARAMETERS], menu[CLEAR_STROKES], menu[RESET_AND_CLEAR]) = + (tr("Reset Cage Parameters"), tr("Clear All Cage Paint Strokes"), tr("Reset and Clear All")); + let cage_reset = section(sheet, tr("Cage"), &menu, |sheet| { + // The cage steers rays toward a separate high poly, so it has nothing to do without one + let cage_applies = has_high && !settings.high_poly.use_low_as_high; + let reason = if has_high { + tr("The cage is not used while the low poly mesh is used as the high poly mesh.") + } else { + tr("The cage applies once a high poly mesh is loaded.") + }; + sheet.greyed(cage_applies, Some(reason), |sheet| { + choice( + sheet, + tr("Cage Type"), + &mut settings.cage.kind, + &[ + (CageType::DistanceBased, tr("Distance-Based")), + (CageType::Automatic, tr("Automatic (Experimental)")), + (CageType::CustomFile, tr("Custom File")), + ], + ); + if settings.cage.kind == CageType::DistanceBased { + paint_button(app, sheet, BakePaintTarget::Cage); + sheet.indented(|sheet| { + number(sheet, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=MAX_CAGE_DISTANCE, CAGE_DISTANCE_DECIMALS); + number(sheet, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=MAX_CAGE_DISTANCE, CAGE_DISTANCE_DECIMALS); + sheet.check(tr("Relative to Bounding Box"), &mut settings.cage.relative_to_bounding_box); + sheet.check(tr("Average Normals"), &mut settings.cage.average_normals); + }); + } + }); + + // A loaded cage stays listed and removable while the cage can't apply, so a saved one can still be dropped + if settings.cage.kind == CageType::CustomFile { + cage_file(app, sheet, cage_applies); } }); - - ui.add_space(SECTION_GAP); - ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), |ui| { - // The cage steers rays toward a separate high poly, so it has nothing to do without one - let cage_applies = has_high && !settings.high_poly.use_low_as_high; - if !has_high { - hint(ui, tr("The cage applies once a high poly mesh is loaded.")); - } else if !cage_applies { - hint(ui, tr("The cage is not used while the low poly mesh is used as the high poly mesh.")); - } - ui.add_enabled_ui(cage_applies, |ui| { - choice( - ui, - tr("Cage Type"), - &mut settings.cage.kind, - &[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))], - ); - if settings.cage.kind == CageType::DistanceBased { - paint_brush(app, ui, BakePaintTarget::Cage); - number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); - number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); - ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); - ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); - } - }); - if settings.cage.kind == CageType::CustomFile { - cage_file(app, ui, cage_applies); - } - }) { + if let Some(item) = cage_reset { + if matches!(item, RESET_PARAMETERS | RESET_AND_CLEAR) { settings.cage = Default::default(); reset.insert("cage".into(), json!(settings.cage)); } - }); + if matches!(item, CLEAR_STROKES | RESET_AND_CLEAR) { + app.run("bake.cage.reset", json!({})); + } + } - // Shown greyed when it can't apply, as the reference does, with the reason on top + // Shown greyed when it can't apply, as the reference does, with the reason on hover let skew_applies = has_high && settings.skew_applies(); - ui.add_space(SECTION_GAP); - ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), |ui| { - if !skew_applies { - hint(ui, skew_unavailable_reason(settings, has_high)); - } - ui.add_enabled_ui(skew_applies, |ui| { - choice( - ui, - tr("Skew Correction Method"), - &mut settings.skew.method, - &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], - ); - paint_brush(app, ui, BakePaintTarget::Skew); - ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); - number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); - number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + let mut menu = [""; 3]; + (menu[RESET_PARAMETERS], menu[CLEAR_STROKES], menu[RESET_AND_CLEAR]) = + (tr("Reset Skew Correction Parameters"), tr("Clear All Skew Paint Strokes"), tr("Reset and Clear All")); + let skew_reset = section(sheet, tr("Skew Correction"), &menu, |sheet| { + sheet.greyed(skew_applies, Some(skew_unavailable_reason(settings, has_high)), |sheet| { + paint_button(app, sheet, BakePaintTarget::Skew); + sheet.check(tr("Edge Protection"), &mut settings.skew.edge_protection); + sheet.greyed(settings.skew.edge_protection, None, |sheet| { + sheet.indented(|sheet| { + number(sheet, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); + number(sheet, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + }); }); - }) { + choice( + sheet, + tr("Skew Correction Method"), + &mut settings.skew.method, + &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], + ); + }); + }); + if let Some(item) = skew_reset { + if matches!(item, RESET_PARAMETERS | RESET_AND_CLEAR) { settings.skew = Default::default(); reset.insert("skew".into(), json!(settings.skew)); } - }); + if matches!(item, CLEAR_STROKES | RESET_AND_CLEAR) { + app.run("bake.skew.clear", json!({})); + } + } (!reset.is_empty()).then_some(Value::Object(reset)) } @@ -146,130 +168,122 @@ fn skew_unavailable_reason(settings: &BakeSettings, has_high: bool) -> &'static tr("Skew Correction is not available while the low poly mesh is used as the high poly mesh.") } else if settings.cage.kind == CageType::CustomFile { tr("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself.") + } else if settings.cage.kind == CageType::Automatic { + tr("Skew Correction needs a distance-based cage: the automatic cage is fitted to the high poly as it is.") } else { tr("Skew Correction needs Average Normals turned on in the cage settings.") } } -fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { - ui.label(tr("Output Size")); - ui.horizontal(|ui| { - 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 { - ui.selectable_value(value, resolution, resolution.pixels().to_string()); - } - }); - }; - - resolution(ui, "output_width", &mut settings.resolution); - let locked = settings.resolution_height.is_none(); - let mut height = settings.resolution_height.unwrap_or(settings.resolution); - ui.add_enabled_ui(!locked, |ui| resolution(ui, "output_height", &mut height)); - 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, button_size).clicked() { - settings.resolution_height = if locked { Some(settings.resolution) } else { None }; - } - }); +/// How the Antialiasing dropdown names `antialiasing` +pub(super) fn antialiasing_label(antialiasing: BakeAntialiasing) -> &'static str { + match antialiasing { + BakeAntialiasing::None => tr("None"), + BakeAntialiasing::Subsampling2x2 => tr("Subsampling 2x2"), + BakeAntialiasing::Subsampling4x4 => tr("Subsampling 4x4"), + BakeAntialiasing::Subsampling8x8 => tr("Subsampling 8x8"), + } } -/// The high poly meshes as a list box, with + to add some and − to remove the selected one -fn high_poly_scene(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); - let names: Vec = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); - let selected_id = ui.make_persistent_id("high_poly_selected"); - let mut selected = ui.data(|data| data.get_temp::(selected_id)).filter(|index| *index < names.len()); +/// The smallest output size offered, as in the reference; a project saved with a smaller one keeps it +const SMALLEST_OUTPUT_SIZE: u32 = 32; - ui.label(tr("High Poly Scene")); - let (mut add, mut remove) = (false, false); - ui.horizontal_top(|ui| { - let button_size = ui.spacing().interact_size.y; - let list_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); - let list_height = HIGH_POLY_LIST_ROWS * ui.spacing().interact_size.y; - egui::Frame::NONE.fill(tokens.field).stroke(egui::Stroke::new(1.0, tokens.field_border)).corner_radius(tokens.cr()).show(ui, |ui| { - ui.set_min_size(egui::vec2(list_width, list_height)); - ui.set_max_width(list_width); - egui::ScrollArea::both().id_salt("high_poly_list").max_height(list_height).auto_shrink([false; 2]).show(ui, |ui| { - for (index, name) in names.iter().enumerate() { - if ui.selectable_label(selected == Some(index), name).on_hover_text(name).clicked() { - selected = Some(index); - } - } - }); - }); - ui.vertical(|ui| { - add = icon_button(ui, icon::PLUS, tr("Add High-Poly Meshes"), false, button_size).clicked(); - remove = ui.add_enabled_ui(selected.is_some(), |ui| icon_button(ui, icon::MINUS, tr("Remove"), false, button_size)).inner.clicked(); - }); - }); +/// Width, the link, then the height it ties to the width, as in the reference +fn output_size(sheet: &mut PropertySheet<'_>, settings: &mut CommonBakeSettings) { + let sizes: Vec = BakeResolution::ALL.into_iter().filter(|resolution| resolution.pixels() >= SMALLEST_OUTPUT_SIZE).collect(); + let mut linked = settings.resolution_height.is_none(); + let height = settings.resolution_height.unwrap_or(settings.resolution); + let picked = sheet.dropdown_pair_above( + tr("Output Size"), + [settings.resolution, height], + &sizes, + |size| size.pixels().to_string(), + &mut linked, + tr("Lock Output Size"), + ); + match picked { + Some((0, size)) => settings.resolution = size, + Some((_, size)) => settings.resolution_height = Some(size), + None => {} + } + if linked { + settings.resolution_height = None; + } else if settings.resolution_height.is_none() { + settings.resolution_height = Some(settings.resolution); + } +} - if let (true, Some(index)) = (remove, selected) { +/// The high poly meshes, one row each with × to remove it, and + beside them to add some; files still loading show greyed +fn high_poly_scene(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let loading: Vec = app.high_poly_job.iter().flat_map(|job| job.file_names()).map(|name| trf("Loading {name}...", &[("name", &name)])).collect(); + let meshes = &app.session.doc.bake_meshes.high; + let rows: Vec> = meshes + .iter() + .map(|mesh| FileRow { name: &mesh.name, folder: mesh.folder.as_deref(), loading: false }) + .chain(loading.iter().map(|name| FileRow { name, folder: None, loading: true })) + .collect(); + let answer = sheet.file_list( + tr("High Poly Scene"), + &rows, + HIGH_POLY_LIST_MIN_ROWS, + FileListAdd { glyph: icon::PLUS, label: tr("Add High-Poly Meshes"), enabled: true }, + tr("Remove"), + ); + if let Some(index) = answer.removed { app.run("bake.highPoly.remove", json!({ "index": index })); - selected = None; } - ui.data_mut(|data| { - if let Some(index) = selected { - data.insert_temp(selected_id, index); - } else { - data.remove_temp::(selected_id); - } - }); - if add { - crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false); + if answer.add { + crate::web_files::import_bake_mesh(app, &sheet.ui.ctx().clone(), false); } } -/// The cage file row; while the cage can't `apply` only removing a loaded one stays available, so a saved cage can still be dropped -fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui, apply: bool) { - ui.add_enabled(apply, egui::Label::new(tr("Cage Scene"))); - let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); - ui.horizontal(|ui| { - 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_enabled_ui(apply, |ui| { - 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, 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, button_size).clicked() { - app.run("bake.cage.clear", json!({})); - } - }); +/// The cage file's row, with the folder button that loads one while the cage `applies` +fn cage_file(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, applies: bool) { + let cage = app.session.doc.bake_meshes.cage.as_ref(); + let rows: Vec> = cage.iter().map(|mesh| FileRow { name: &mesh.name, folder: mesh.folder.as_deref(), loading: false }).collect(); + let answer = sheet.file_list( + tr("Cage Scene"), + &rows, + CAGE_LIST_MIN_ROWS, + FileListAdd { glyph: icon::FOLDER_OPEN, label: tr("Load Cage"), enabled: applies }, + tr("Remove Cage"), + ); + if answer.removed.is_some() { + app.run("bake.cage.clear", json!({})); + } + if answer.add { + crate::web_files::import_bake_mesh(app, &sheet.ui.ctx().clone(), true); + } } -fn paint_brush(app: &mut TextureCraftApp, ui: &mut Ui, target: BakePaintTarget) { - let (label, clear_label, clear_command) = match target { - BakePaintTarget::Cage => ("Paint Cage", "Reset Painted Cage", "bake.cage.reset"), - BakePaintTarget::Skew => ("Paint Skew Correction", "Remove Skew Correction", "bake.skew.clear"), +/// "Paint Cage" or "Paint Skew Correction", held down as "Stop Painting" while that brush is on, with the brush sliders under it +fn paint_button(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, target: BakePaintTarget) { + let label = match target { + BakePaintTarget::Cage => tr("Paint Cage"), + BakePaintTarget::Skew => tr("Paint Skew Correction"), }; let mut brush = app.ui.bake_paint_brush; let active = brush.on && brush.target == target; - if ui.add(egui::Button::new(tr(label)).selected(active)).clicked() { + let (glyph, text) = if active { (icon::PROHIBIT, tr("Stop Painting")) } else { (icon::PENCIL_SIMPLE, label) }; + if sheet.wide_button(glyph, text, active).clicked() { brush.on = !active; if brush.target != target { brush.value = match target { - BakePaintTarget::Cage => 0.5, - BakePaintTarget::Skew => 1.0, + BakePaintTarget::Cage => CAGE_BRUSH_VALUE, + BakePaintTarget::Skew => SKEW_BRUSH_VALUE, }; } brush.target = target; } if brush.on && brush.target == target { - number(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3); - number(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2); - number(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); + sheet.indented(|sheet| { + number(sheet, tr("Radius"), &mut brush.radius, BRUSH_RADIUS, 3); + number(sheet, tr("Value"), &mut brush.value, 0.0..=1.0, 2); + number(sheet, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); + }); if app.ui.layout == crate::state::ViewLayout::Only3D { app.ui.layout = crate::state::ViewLayout::Split; } } app.ui.bake_paint_brush = brush; - if app.session.doc.bake_paint.contains_key(&(app.session.ts(), target)) && ui.button(tr(clear_label)).clicked() { - app.run(clear_command, json!({})); - } } diff --git a/crates/ui-egui/src/bake_mode/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs index f260bf7c..a8c78922 100644 --- a/crates/ui-egui/src/bake_mode/controls.rs +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -1,88 +1,55 @@ -use crate::i18n::tr; -use crate::theme::{Tokens, caption}; -use egui::collapsing_header::CollapsingState; -use egui::{RichText, Ui}; +//! The bake panels' settings on the property sheet: labels above full-width controls, as the reference's bake panels lay them out -/// 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 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); - 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 - }); +use crate::property_sheet::PropertySheet; - let response = ui.interact(header.response.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(header.inner, egui::Label::new(chevron).selectable(false)); -} - -/// 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); - section_header(ui, title, &mut collapsing_state); - - collapsing_state - .show_body_unindented(ui, |ui| { - egui::Frame::NONE - .inner_margin(egui::Margin::same(8)) - .show(ui, |ui| { - contents(ui); - ui.add_space(6.0); - ui.button(tr("Restore Defaults")).clicked() - }) - .inner - }) - .is_some_and(|response| response.inner) -} - -pub(super) fn choice(ui: &mut Ui, label: &str, value: &mut T, options: &[(T, &str)]) { - let caption = ui.label(label); - let selected = options.iter().find(|(option, _)| option == value).map_or("", |(_, label)| *label); - egui::ComboBox::from_id_salt(label) - .width(ui.available_width()) - .selected_text(selected) - .show_ui(ui, |ui| { - for (option, label) in options { - ui.selectable_value(value, *option, *label); +/// A folding section with `contents` under its caption; its reset glyph resets at once, or opens `reset_menu` when not empty. Returns the reset choice: `Some(0)` for a plain reset, else the chosen item of `reset_menu` (from 0) +pub(super) fn section(sheet: &mut PropertySheet<'_>, title: &str, reset_menu: &[&str], contents: impl FnOnce(&mut PropertySheet<'_>)) -> Option { + let section = sheet.fold_section(title, true); + let mut chosen = None; + if reset_menu.is_empty() { + chosen = section.reset.clicked().then_some(0); + } else { + // Hanging left from the glyph at the panel's right edge, so it stays inside the panel + egui::Popup::menu(§ion.reset).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + for (index, item) in reset_menu.iter().enumerate() { + if ui.button(*item).clicked() { + chosen = Some(index); + } } - }) - .response - .labelled_by(caption.id); + }); + } + if section.open { + contents(sheet); + } + chosen } -pub(super) fn number(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) { - let response = crate::widgets::slider(ui, label, value, range.clone(), decimals); - if response.changed() && (response.dragged() || response.clicked()) { +/// A dropdown of `options`, each with its shown name +pub(super) fn choice(sheet: &mut PropertySheet<'_>, label: &str, value: &mut T, options: &[(T, &str)]) { + let values: Vec = options.iter().map(|(option, _)| *option).collect(); + let name = |option: T| options.iter().find(|(candidate, _)| *candidate == option).map_or("", |(_, name)| *name).to_owned(); + if let Some(picked) = sheet.dropdown_above(label, *value, &values, name) { + *value = picked; + } +} + +/// A slider whose dragged values keep `decimals` places +pub(super) fn number(sheet: &mut PropertySheet<'_>, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) { + if sheet.slider_above(label, value, range.clone(), decimals).is_some() { let scale = 10_f32.powi(decimals as i32); *value = ((*value * scale).round() / scale).clamp(*range.start(), *range.end()); } } -pub(super) fn integer(ui: &mut Ui, label: &str, value: &mut u32, range: std::ops::RangeInclusive) { +/// A slider of whole numbers +pub(super) fn integer(sheet: &mut PropertySheet<'_>, label: &str, value: &mut u32, range: std::ops::RangeInclusive) { let mut number_value = *value as f32; - let response = crate::widgets::slider(ui, label, &mut number_value, *range.start() as f32..=*range.end() as f32, 0); - if response.changed() { + if sheet.slider_above(label, &mut number_value, *range.start() as f32..=*range.end() as f32, 0).is_some() { *value = (number_value.round() as u32).clamp(*range.start(), *range.end()); } } -pub(super) fn text_input(ui: &mut Ui, label: &str, value: &mut String) { - ui.label(label); - ui.add(egui::TextEdit::singleline(value).desired_width(ui.available_width())); -} - -pub(super) fn hint(ui: &mut Ui, text: &str) { - ui.label(RichText::new(text).color(Tokens::get(ui.ctx()).text_dim).size(11.0)); +/// A one-line text field +pub(super) fn text_input(sheet: &mut PropertySheet<'_>, label: &str, value: &mut String) { + sheet.text_field_above(label, value); } diff --git a/crates/ui-egui/src/bake_mode/glyph_look.rs b/crates/ui-egui/src/bake_mode/glyph_look.rs new file mode 100644 index 00000000..db9f8bc6 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/glyph_look.rs @@ -0,0 +1,9 @@ +/// How a baker row's glyph button shows its state +#[derive(Clone, Copy, PartialEq)] +pub(super) enum GlyphLook { + Plain, + /// Bright: what it stands for is on (the set shares these settings) + Lit, + /// Held down in a box: the view it toggles is showing + Pressed, +} diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index 5168d341..7283d254 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,6 +1,6 @@ -use super::controls::{choice, hint, integer, number}; +use super::controls::{choice, integer, number}; use crate::i18n::tr; -use egui::Ui; +use crate::property_sheet::PropertySheet; use serde::Serialize; use serde_json::{Value, json}; use texturecraft_engine::core::{ @@ -9,89 +9,110 @@ use texturecraft_engine::core::{ 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) -> Option { +/// Most secondary rays a slider offers, as the reference's does (the bake settings command accepts the same) +const MAX_SECONDARY_RAYS: u32 = 256; + +/// Smallest distance, radius or divisor a slider offers: the bake settings command's lower limit +const SHORTEST_DISTANCE: f32 = 0.00001; + +/// Whether `map` has parameters (and so a Restore Defaults) +pub(super) fn has_parameters(map: BakedMap) -> bool { + !matches!(map, BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity) +} + +/// Draw `map`'s parameters; `restore` sets them back to the defaults. Maps without parameters say so +pub(super) fn show(sheet: &mut PropertySheet<'_>, map: BakedMap, settings: &mut MeshMapSettings, restore: bool) -> Option { match map { BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { - hint(ui, tr("No Parameters")); + sheet.dim_line(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), + BakedMap::Id => parameters(sheet, "id", &mut settings.id.parameters, restore, id), + BakedMap::AmbientOcclusion => parameters(sheet, "ao", &mut settings.ao.parameters, restore, ambient_occlusion), + BakedMap::Curvature => parameters(sheet, "curvature", &mut settings.curvature.parameters, restore, curvature), + BakedMap::Position => parameters(sheet, "position", &mut settings.position.parameters, restore, position), + BakedMap::Thickness => parameters(sheet, "thickness", &mut settings.thickness.parameters, restore, thickness), + BakedMap::Height => parameters(sheet, "height", &mut settings.height.parameters, restore, height), + BakedMap::BentNormal => parameters(sheet, "bent_normal", &mut settings.bent_normal.parameters, restore, bent_normal), } } -/// A map's controls, then a right-aligned Restore Defaults that resets only its parameters -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() { +/// A map's controls; on `restore` only its parameters go back to the defaults +fn parameters( + sheet: &mut PropertySheet<'_>, + map_key: &str, + parameters: &mut T, + restore: bool, + controls: impl FnOnce(&mut PropertySheet<'_>, &mut T), +) -> Option { + controls(sheet, parameters); + if restore { *parameters = T::default(); return Some(json!({"maps": {map_key: {"parameters": parameters}}})); } None } -fn id(ui: &mut Ui, settings: &mut IdSettings) { +/// Settings that belong to the one above: indented under it, greyed while it rules them out +fn dependent(sheet: &mut PropertySheet<'_>, applies: bool, body: impl FnOnce(&mut PropertySheet<'_>)) { + sheet.greyed(applies, None, |sheet| sheet.indented(body)); +} + +fn id(sheet: &mut PropertySheet<'_>, settings: &mut IdSettings) { choice( - ui, + sheet, tr("Color Source"), &mut settings.source, &[ (IdColorSource::VertexColor, tr("Vertex Color")), (IdColorSource::MaterialColor, tr("Material Color")), (IdColorSource::FileId, tr("File ID")), - (IdColorSource::MeshId, tr("Mesh ID")), + (IdColorSource::MeshId, tr("Mesh ID / Polygroup")), (IdColorSource::Submesh, tr("Submesh")), ], ); - if matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh) { + // Dependent controls show greyed and indented, never hidden, as in the reference + let generates_colors = matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh); + dependent(sheet, generates_colors, |sheet| { choice( - ui, + sheet, tr("Color Generator"), &mut settings.generator, &[(IdColorGenerator::Random, tr("Random")), (IdColorGenerator::HueShift, tr("Hue Shift")), (IdColorGenerator::Grayscale, tr("Grayscale"))], ); - } + }); } -fn rays(ui: &mut Ui, settings: &mut RaySettings) { - integer(ui, tr("Secondary Rays"), &mut settings.rays, 1..=256); - number(ui, tr("Min Occluder Distance"), &mut settings.min_distance, 0.00001..=1.0, 5); - number(ui, tr("Max Occluder Distance"), &mut settings.max_distance, 0.00001..=if settings.relative_to_bounding_box { 1.0 } else { 10.0 }, 5); - if ui.checkbox(&mut settings.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && settings.relative_to_bounding_box { +fn rays(sheet: &mut PropertySheet<'_>, settings: &mut RaySettings) { + integer(sheet, tr("Secondary Rays"), &mut settings.rays, 1..=MAX_SECONDARY_RAYS); + number(sheet, tr("Min Occluder Distance"), &mut settings.min_distance, SHORTEST_DISTANCE..=1.0, 5); + number(sheet, tr("Max Occluder Distance"), &mut settings.max_distance, SHORTEST_DISTANCE..=if settings.relative_to_bounding_box { 1.0 } else { 10.0 }, 5); + if sheet.check(tr("Relative to Bounding Box"), &mut settings.relative_to_bounding_box) && settings.relative_to_bounding_box { settings.max_distance = settings.max_distance.min(1.0); } - number(ui, tr("Spread Angle"), &mut settings.spread, 0.0..=180.0, 0); - choice(ui, tr("Distribution"), &mut settings.distribution, &[(RayDistribution::Uniform, tr("Uniform")), (RayDistribution::Cosine, tr("Cosine"))]); + number(sheet, tr("Spread Angle"), &mut settings.spread, 0.0..=180.0, 0); + choice(sheet, tr("Distribution"), &mut settings.distribution, &[(RayDistribution::Uniform, tr("Uniform")), (RayDistribution::Cosine, tr("Cosine"))]); } -fn backface(ui: &mut Ui, settings: &mut BackfaceMode) { +fn backface(sheet: &mut PropertySheet<'_>, settings: &mut BackfaceMode) { choice( - ui, + sheet, tr("Ignore Backface"), settings, &[(BackfaceMode::Never, tr("Never")), (BackfaceMode::Always, tr("Always")), (BackfaceMode::ByMeshName, tr("By Mesh Name"))], ); } -fn occlusion(ui: &mut Ui, label: &str, settings: &mut SelfOcclusion) { - choice(ui, label, settings, &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only Same Mesh Name"))]); +fn occlusion(sheet: &mut PropertySheet<'_>, label: &str, settings: &mut SelfOcclusion) { + choice(sheet, label, settings, &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only Same Mesh Name"))]); } -fn ambient_occlusion(ui: &mut Ui, settings: &mut AmbientOcclusionSettings) { - rays(ui, &mut settings.rays); - backface(ui, &mut settings.ignore_backface); - occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +fn ambient_occlusion(sheet: &mut PropertySheet<'_>, settings: &mut AmbientOcclusionSettings) { + rays(sheet, &mut settings.rays); + backface(sheet, &mut settings.ignore_backface); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); choice( - ui, + sheet, tr("Attenuation"), &mut settings.attenuation, &[ @@ -100,94 +121,104 @@ fn ambient_occlusion(ui: &mut Ui, settings: &mut AmbientOcclusionSettings) { (AmbientOcclusionAttenuation::Linear, tr("Linear")), ], ); - ui.checkbox(&mut settings.ground_plane.enabled, tr("Ground Plane")); - if settings.ground_plane.enabled { - number(ui, tr("Ground Plane Offset"), &mut settings.ground_plane.offset, 0.0..=100.0, 2); - } + sheet.check(tr("Ground Plane"), &mut settings.ground_plane.enabled); + dependent(sheet, settings.ground_plane.enabled, |sheet| number(sheet, tr("Ground Plane Offset"), &mut settings.ground_plane.offset, 0.0..=100.0, 2)); } -fn curvature(ui: &mut Ui, settings: &mut CurvatureSettings) { +fn curvature(sheet: &mut PropertySheet<'_>, settings: &mut CurvatureSettings) { choice( - ui, + sheet, tr("Method"), &mut settings.method, - &[(CurvatureMethod::NormalMap, tr("Generate from Normal Map")), (CurvatureMethod::Mesh, tr("Generate from Mesh"))], + &[(CurvatureMethod::Mesh, tr("Generate from Mesh")), (CurvatureMethod::NormalMap, tr("Generate from Normal Map"))], ); match settings.method { CurvatureMethod::NormalMap => { - number(ui, tr("Details"), &mut settings.normal_map.details, 0.0..=1.0, 2); - ui.checkbox(&mut settings.normal_map.enable_seams, tr("Enable Seams")); - if settings.normal_map.enable_seams { - number(ui, tr("Seams Intensity"), &mut settings.normal_map.seams_intensity, 0.0..=1.0, 2); - } + number(sheet, tr("Details"), &mut settings.normal_map.details, 0.0..=1.0, 2); + sheet.check(tr("Enable Seams"), &mut settings.normal_map.enable_seams); + let seams = settings.normal_map.enable_seams; + dependent(sheet, seams, |sheet| number(sheet, tr("Seams Intensity"), &mut settings.normal_map.seams_intensity, 0.0..=1.0, 2)); } CurvatureMethod::Mesh => { let mesh = &mut settings.mesh; - integer(ui, tr("Secondary Rays"), &mut mesh.rays, 1..=256); - number(ui, tr("Sampling Radius"), &mut mesh.sampling_radius, 0.00001..=if mesh.relative_to_bounding_box { 10.0 } else { 1.0 }, 5); - if ui.checkbox(&mut mesh.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && !mesh.relative_to_bounding_box { + integer(sheet, tr("Secondary Rays"), &mut mesh.rays, 1..=MAX_SECONDARY_RAYS); + number(sheet, tr("Sampling Radius"), &mut mesh.sampling_radius, SHORTEST_DISTANCE..=if mesh.relative_to_bounding_box { 10.0 } else { 1.0 }, 5); + if sheet.check(tr("Relative to Bounding Box"), &mut mesh.relative_to_bounding_box) && !mesh.relative_to_bounding_box { mesh.sampling_radius = mesh.sampling_radius.min(1.0); } - occlusion(ui, tr("Self Intersection"), &mut mesh.self_intersection); - ui.checkbox(&mut mesh.auto_tonemapping, tr("Auto Tonemapping")); - if !mesh.auto_tonemapping { - number(ui, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); - number(ui, tr("Value Bounds Max"), &mut mesh.value_max, -10.0..=10.0, 2); - } + occlusion(sheet, tr("Self Intersection"), &mut mesh.self_intersection); + sheet.check(tr("Auto Tonemapping (per UV Tile)"), &mut mesh.auto_tonemapping); + dependent(sheet, !mesh.auto_tonemapping, |sheet| { + number(sheet, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); + number(sheet, tr("Value Bounds Max"), &mut mesh.value_max, -10.0..=10.0, 2); + }); } } } -fn position(ui: &mut Ui, settings: &mut PositionSettings) { - choice(ui, tr("Axis"), &mut settings.axis, &[(PositionAxis::All, tr("All")), (PositionAxis::X, "X"), (PositionAxis::Y, "Y"), (PositionAxis::Z, "Z")]); +fn position(sheet: &mut PropertySheet<'_>, settings: &mut PositionSettings) { + // The reference splits the axis into a Mode and an Axis that applies only to One Axis + let mut one_axis = settings.axis != PositionAxis::All; + choice(sheet, tr("Mode"), &mut one_axis, &[(false, tr("All Axis")), (true, tr("One Axis"))]); + if one_axis && settings.axis == PositionAxis::All { + settings.axis = PositionAxis::X; + } else if !one_axis { + settings.axis = PositionAxis::All; + } + dependent(sheet, one_axis, |sheet| { + let mut axis = if one_axis { settings.axis } else { PositionAxis::X }; + choice(sheet, tr("Axis"), &mut axis, &[(PositionAxis::X, "X"), (PositionAxis::Y, "Y"), (PositionAxis::Z, "Z")]); + if one_axis { + settings.axis = axis; + } + }); choice( - ui, + sheet, tr("Normalization Type"), &mut settings.normalization, &[(PositionMode::BoundingBox, tr("BBox")), (PositionMode::BoundingSphere, tr("BSphere")), (PositionMode::None, tr("None"))], ); choice( - ui, + sheet, tr("Normalization Scale"), &mut settings.scale, &[(PositionNormalizationScale::PerMaterial, tr("Per Material")), (PositionNormalizationScale::FullScene, tr("Full Scene"))], ); } -fn thickness(ui: &mut Ui, settings: &mut ThicknessSettings) { - rays(ui, &mut settings.rays); - occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +fn thickness(sheet: &mut PropertySheet<'_>, settings: &mut ThicknessSettings) { + rays(sheet, &mut settings.rays); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); choice( - ui, + sheet, tr("Normalization"), &mut settings.normalization, &[ (ThicknessNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), - (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max (per UV Tile)")), (ThicknessNormalization::None, tr("None")), ], ); } -fn height(ui: &mut Ui, settings: &mut HeightSettings) { +fn height(sheet: &mut PropertySheet<'_>, settings: &mut HeightSettings) { choice( - ui, + sheet, tr("Normalization"), &mut settings.normalization, &[ (HeightNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), - (HeightNormalization::RelativeToLowMesh, tr("Relative to Low Mesh")), - (HeightNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (HeightNormalization::RelativeToLowMesh, tr("Relative to Low Mesh (per UV Tile)")), + (HeightNormalization::RelativeToMinMax, tr("Relative to Min/Max (per UV Tile)")), (HeightNormalization::Manual, tr("Manual")), ], ); - if settings.normalization == HeightNormalization::Manual { - number(ui, tr("Scaling Divisor"), &mut settings.scaling_divisor, 0.00001..=100.0, 5); - } + let manual = settings.normalization == HeightNormalization::Manual; + dependent(sheet, manual, |sheet| number(sheet, tr("Scaling Divisor"), &mut settings.scaling_divisor, SHORTEST_DISTANCE..=100.0, 5)); } -fn bent_normal(ui: &mut Ui, settings: &mut BentNormalSettings) { - rays(ui, &mut settings.rays); - backface(ui, &mut settings.ignore_backface); - occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +fn bent_normal(sheet: &mut PropertySheet<'_>, settings: &mut BentNormalSettings) { + rays(sheet, &mut settings.rays); + backface(sheet, &mut settings.ignore_backface); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); } diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs new file mode 100644 index 00000000..433cbb98 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -0,0 +1,69 @@ +use std::collections::BTreeMap; +use std::sync::{Arc, Weak}; + +use egui::{ColorImage, TextureHandle, TextureOptions}; +use texturecraft_engine::Session; +use texturecraft_engine::core::BakedMap; + +/// Side of a thumbnail's texture, in pixels (twice the row's square, for high-density screens) +const THUMBNAIL_PIXELS: u32 = 44; + +/// A thumbnail's texture, with the baked data and the working size it was drawn from +type Thumbnail = (Weak>, (u32, u32), TextureHandle); + +/// The Mesh Map Bakers rows' thumbnails of the baked maps, redrawn when a map is baked again +#[derive(Default)] +pub struct MapThumbnails { + textures: BTreeMap<(usize, BakedMap), Thumbnail>, +} + +impl MapThumbnails { + /// The thumbnail of `map` as texture set `texture_set` has it baked (a running bake's finished maps included), `None` before it is baked + pub fn texture(&mut self, context: &egui::Context, session: &Session, texture_set: usize, map: BakedMap) -> Option { + let key = (texture_set, map); + let baked = session.bake_preview_baked(texture_set).filter(|preview| preview.maps.contains_key(&map)).or_else(|| session.doc.baked.get(&texture_set)); + let (Some(data), Some(cache)) = (baked.and_then(|baked| baked.maps.get(&map)), session.caches.get(texture_set)) else { + self.textures.remove(&key); + return None; + }; + + if let Some((drawn_from, working_size, texture)) = self.textures.get(&key) + && drawn_from.ptr_eq(&Arc::downgrade(data)) + && *working_size == cache.size + { + return Some(texture.clone()); + } + + let rgba = texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, THUMBNAIL_PIXELS, cache.size, &cache.composite.block_scales); + let side = THUMBNAIL_PIXELS as usize; + let image = ColorImage::from_rgba_unmultiplied([side, side], &rgba); + let texture = context.load_texture(format!("bake_map_{texture_set}_{}", map.id()), image, TextureOptions::LINEAR); + self.textures.insert(key, (Arc::downgrade(data), cache.size, texture.clone())); + Some(texture) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_thumbnail_is_kept_until_its_map_is_baked_again() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let context = egui::Context::default(); + let mut thumbnails = MapThumbnails::default(); + let map = *session.doc.baked[&0].maps.keys().next().expect("the sample has a baked map"); + + let first = thumbnails.texture(&context, &session, 0, map).expect("a baked map has a thumbnail"); + assert_eq!(first.size(), [THUMBNAIL_PIXELS as usize; 2]); + assert_eq!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "the same bake reuses its texture"); + + let baked = session.doc.baked.get_mut(&0).unwrap(); + let rebaked = baked.maps[&map].as_ref().clone(); + baked.maps.insert(map, Arc::new(rebaked)); + assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "a new bake is drawn again"); + + session.doc.baked.get_mut(&0).unwrap().maps.remove(&map); + assert!(thumbnails.texture(&context, &session, 0, map).is_none(), "a map not baked has none"); + } +} diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 059af550..4fbe3505 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,45 +1,112 @@ -use egui::{Align, Layout, RichText, Sense, Stroke, Ui, UiBuilder, vec2}; +use egui::{Align, CornerRadius, FontId, Layout, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; -use texturecraft_engine::core::{BakeSettings, BakedMap}; +use texturecraft_engine::ViewMode; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use super::glyph_look::GlyphLook; +use super::set_picker::SetPicker; +use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; use crate::docking::Panel; use crate::i18n::{baked_map_label, tr, trf}; -use crate::theme::Tokens; +use crate::property_sheet::{CHECK_SIZE, paint_check}; +use crate::theme::{Tokens, semibold}; -/// 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 +/// The presets menu's least width, and its name field's, room for a typical preset name +const PRESETS_MENU_MIN_WIDTH: f32 = 220.0; +const PRESET_NAME_FIELD_WIDTH: f32 = 130.0; + +/// How far past its box a row's check takes clicks, so it is easy to hit +const CHECK_HIT_AIR: f32 = 3.0; + +/// Height of the header's buttons, the air inside them beside their words, and between the glyph and the words +const HEADER_BUTTON_HEIGHT: f32 = 24.0; +const HEADER_BUTTON_PADDING: f32 = 10.0; +const HEADER_GLYPH_GAP: f32 = 6.0; +/// Air above the header and between its buttons +const HEADER_AIR: f32 = 6.0; +const HEADER_GAP: f32 = 6.0; +/// Height of one baker row, and of the Check All row +const ROW_HEIGHT: f32 = 28.0; +/// Inset of a row's check from its left edge const ROW_INSET: f32 = 6.0; +/// Side of a row's map thumbnail, and the air on its sides +const THUMBNAIL_SIZE: f32 = 22.0; +const THUMBNAIL_AIR: f32 = 9.0; +/// Side of a row's icon buttons and of the list menu button +const ROW_BUTTON_SIZE: f32 = 20.0; +/// Size of a row's glyphs +const ROW_GLYPH_SIZE: f32 = 14.0; +/// Size of the map names +const NAME_SIZE: f32 = 12.0; +/// Corner radius of a row's face and of a held-down glyph's box +const ROW_RADIUS: u8 = 4; +/// Opacity of a hovered row's face, against the selected row's full one +const HOVER_FACE_OPACITY: f32 = 0.5; +/// Air above and below the hairline under Check All +const RULE_AIR: f32 = 4.0; -/// The Common Settings button, Check All, and one row per map (checkbox enables, click selects) +/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, 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); - } + let several_sets = app.session.doc.project.texture_sets.len() > 1; + ui.add_space(HEADER_AIR); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = HEADER_GAP; + if header_button(ui, icon::GEAR, tr("Common Settings")).clicked() { + app.ui.dock.focus(Panel::CommonSettings); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if several_sets { + let shares = settings.sync.shares(BakeSyncGroup::Common); + let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; + let (slot, _) = ui.allocate_exact_size(vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE), Sense::hover()); + if glyph_button(ui, slot, icon::LINK, tr("Synchronize Common Settings"), look).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Sync(BakeSyncGroup::Common)); + } + } + presets_menu(app, ui, settings); + }); + }); - presets_menu(app, ui, settings); + SetPicker::show(app, &ui.ctx().clone()); - ui.add_space(4.0); - check_all(ui, settings); - ui.separator(); + ui.add_space(RULE_AIR); + check_all_row(app, ui, settings); + ui.add_space(RULE_AIR); + let rule = ui.available_rect_before_wrap(); + ui.painter().hline(rule.x_range(), rule.top(), Stroke::new(1.0, Tokens::get(ui.ctx()).separator)); + ui.add_space(RULE_AIR); let selected = super::selected_map(app.ui.selected_baked_map, settings); + let check_drag_id = ui.scope_id().with("check_drag"); + let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(ui, map, settings, map == selected)).inner { + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } } + + // Kept through the frame of the release, so the click that ends a drag does not toggle its last checkbox back + let is_held = ui.input(|input| input.pointer.primary_down()); + ui.data_mut(|data| { + if let Some(value) = check_drag.filter(|_| is_held) { + data.insert_temp(check_drag_id, value); + } else { + data.remove_temp::(check_drag_id); + } + }); } /// The Presets menu: save the active set's settings under a name, load or delete a saved one, copy to all sets fn presets_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &BakeSettings) { - ui.menu_button(format!("{} {}", icon::SLIDERS_HORIZONTAL, tr("Presets")), |ui| { - ui.set_min_width(220.0); + let (slot, _) = ui.allocate_exact_size(vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE), Sense::hover()); + let button = glyph_button(ui, slot, icon::SLIDERS_HORIZONTAL, tr("Presets"), GlyphLook::Plain); + egui::Popup::menu(&button).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + ui.set_min_width(PRESETS_MENU_MIN_WIDTH); ui.horizontal(|ui| { - let name_edit = egui::TextEdit::singleline(&mut app.ui.bake_preset_name).hint_text(tr("Preset name")).desired_width(130.0); + let name_edit = egui::TextEdit::singleline(&mut app.ui.bake_preset_name).hint_text(tr("Preset name")).desired_width(PRESET_NAME_FIELD_WIDTH); let enter = ui.add(name_edit).lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); let can_save = !app.ui.bake_preset_name.trim().is_empty(); if (ui.add_enabled(can_save, egui::Button::new(tr("Save Preset"))).clicked() || (enter && can_save)) @@ -90,45 +157,209 @@ fn presets_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &BakeSettings) }); } -/// Enable every map, or disable them all when every map is already enabled -fn check_all(ui: &mut Ui, settings: &mut BakeSettings) { +/// Check All (mixed while only some maps are checked; a click checks them all, or unchecks them when all are) with the ≡ menu at the right +fn check_all_row(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + let tokens = Tokens::get(ui.ctx()); 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; + let all_enabled = enabled_count == BakedMap::ALL.len(); + let state = match enabled_count { + 0 => Some(false), + _ if all_enabled => Some(true), + _ => None, + }; - if ui.add(egui::Checkbox::new(&mut all_enabled, tr("Check All")).indeterminate(some_enabled)).changed() { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let label = tr("Check All"); + let galley = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + let hit = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(check.right() + THUMBNAIL_AIR + galley.size().x, rect.bottom())); + let response = ui.interact(hit, ui.scope_id().with("check_all"), Sense::click()); + response.widget_info(|| match state { + Some(on) => egui::WidgetInfo::selected(egui::Role::CheckBox, true, on, label), + None => egui::WidgetInfo::labeled(egui::Role::CheckBox, true, label), + }); + paint_check(ui.painter(), &tokens, check, state, response.hovered()); + ui.painter().galley(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - galley.size().y / 2.0), galley, tokens.text); + if response.clicked() { for map in BakedMap::ALL { - settings.maps.set_enabled(map, all_enabled); + settings.maps.set_enabled(map, !all_enabled); } } + + let menu = Rect::from_center_size(pos2(rect.right() - ROW_BUTTON_SIZE / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + let mut menu_ui = ui.new_child(UiBuilder::new().max_rect(menu)); + list_menu(app, &mut menu_ui, settings); +} + +/// The ≡ menu beside Check All: check states, and copying them or every setting to other texture sets +fn list_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + let button = glyph_button(ui, ui.max_rect(), icon::LIST, tr("Mesh Map Bakers Menu"), GlyphLook::Plain); + egui::Popup::menu(&button).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + if ui.button(tr("Check All Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, true)); + } + if ui.button(tr("Uncheck All Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, false)); + } + if ui.button(tr("Invert Checked Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, !settings.maps.is_enabled(map))); + } + copy_items(app, ui, "checked", None, [tr("Apply Checked to More Texture Sets..."), tr("Apply Checked to All Texture Sets")]); + ui.separator(); + copy_items(app, ui, "settings", None, [tr("Sync All Settings to More Texture Sets..."), tr("Sync All Settings to All Texture Sets")]); + }); +} + +/// A copy's two menu items: "...more Texture Sets..." opens the set picker, "...all Texture Sets" copies to every set +fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, what: &'static str, map: Option, [more, all]: [&str; 2]) { + // With one texture set there is nothing to copy to + let several_sets = app.session.doc.project.texture_sets.len() > 1; + if ui.add_enabled(several_sets, egui::Button::new(more)).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Copy { what, map }); + } + if ui.add_enabled(several_sets, egui::Button::new(all)).clicked() { + let from = app.session.ts(); + app.run("bake.copy", json!({ "what": what, "map": map.map(BakedMap::id), "from": from, "ts": "all" })); + } } -/// 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 { +/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses); returns whether the row itself was clicked +fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option) -> bool { + let several_sets = app.session.doc.project.texture_sets.len() > 1; 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(); + // The selected row is brighter and its name bold: no outline, no accent + let hovered = ui.rect_contains_pointer(rect); 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); + ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover); + } else if hovered { + ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover.gamma_multiply(HOVER_FACE_OPACITY)); } + // Added after the row's own response, so the check and icons take the clicks over it + let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + let checkbox = ui.interact(check.expand(CHECK_HIT_AIR), ui.scope_id().with("include"), Sense::click()).on_hover_text(tr("Include in Bake")); + checkbox.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, settings.maps.is_enabled(map), name)); + let is_dragged_over = drag_check(ui, &checkbox, rect, settings.maps.is_enabled(map), check_drag); + if let Some(value) = check_drag.filter(|_| is_dragged_over) { + settings.maps.set_enabled(map, value); + } else if checkbox.clicked() && check_drag.is_none() { + settings.maps.set_enabled(map, !settings.maps.is_enabled(map)); + } + paint_check(ui.painter(), &tokens, check, Some(settings.maps.is_enabled(map)), checkbox.hovered()); + + let texture = app.bake_map_thumbnails.texture(ui.ctx(), &app.session, app.session.ts(), map); + let thumbnail_rect = Rect::from_min_size(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - THUMBNAIL_SIZE / 2.0), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + thumbnail(ui, thumbnail_rect, texture.as_ref()); + + // Icons right to left, only on the hovered or selected row + let mut icons_left = rect.right(); + if is_selected || hovered { + let mut next_icon = || { + let slot = + Rect::from_center_size(pos2(icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + icons_left = slot.left() - ROW_INSET / 2.0; + slot + }; + if several_sets { + let shares = settings.sync.shares(BakeSyncGroup::Map(map)); + let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; + if glyph_button(ui, next_icon(), icon::LINK, &trf("Synchronize {map} Settings", &[("map", &name)]), look).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); + } + } + let baking = app.bake_progress().is_some(); + let bolt = next_icon(); + let bolt_label = trf("Bake {map} Only", &[("map", &name)]); + if ui.add_enabled_ui(!baking, |ui| glyph_button(ui, bolt, icon::LIGHTNING, &bolt_label, GlyphLook::Plain)).inner.clicked() { + let active = app.session.ts(); + app.start_bake_of(vec![active], Some(map)); + } + let shown = app.session.view == ViewMode::MeshMap(map); + let look = if shown { GlyphLook::Pressed } else { GlyphLook::Plain }; + if glyph_button(ui, next_icon(), icon::EYE, &trf("Show {map} in the Viewport", &[("map", &name)]), look).clicked() { + let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) }; + app.run("viewport.view", json!({ "mode": mode })); + } + } + + let name_left = thumbnail_rect.right() + THUMBNAIL_AIR; + let font = if is_selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + let color = if is_selected { tokens.text_strong } else { tokens.text }; + let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), font, color); + job.wrap = egui::text::TextWrapping::truncate_at_width((icons_left - name_left).max(0.0)); + let galley = ui.painter().layout_job(job); + // The full name on hover only when the row cuts it short + let response = if galley.elided { response.on_hover_text(name) } else { response }; + ui.painter().galley(pos2(name_left, rect.center().y - galley.size().y / 2.0), galley, color); + + response.context_menu(|ui| { + let labels = |more: &str, all: &str| [trf(more, &[("map", &name)]), trf(all, &[("map", &name)])]; + let [check_more, check_all] = labels("Check {map} for More Texture Sets...", "Check {map} for All Texture Sets"); + copy_items(app, ui, "check", Some(map), [&check_more, &check_all]); + ui.separator(); + let [apply_more, apply_all] = labels("Apply {map} Settings to More Texture Sets...", "Apply {map} Settings to All Texture Sets"); + copy_items(app, ui, "settings", Some(map), [&apply_more, &apply_all]); + ui.separator(); + if ui.add_enabled(several_sets, egui::Button::new(tr("Sync Settings..."))).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); + } + }); response.clicked() } + +/// Start a checkbox drag at a press on `checkbox`; returns whether a drag is in this row's checkbox column now (the whole row height counts) +fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option) -> bool { + if check_drag.is_none() && checkbox.is_pointer_button_down_on() { + *check_drag = Some(!is_enabled); + } + check_drag.is_some() && ui.rect_contains_pointer(Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range())) +} + +/// The baked map's thumbnail in `rect`; before it is baked, an empty square crossed by a diagonal +fn thumbnail(ui: &Ui, rect: Rect, texture: Option<&egui::TextureHandle>) { + let tokens = Tokens::get(ui.ctx()); + let stroke = Stroke::new(1.0, tokens.text_dim); + match texture { + Some(texture) => { + egui::Image::new(texture).paint_at(ui, rect); + } + None => { + ui.painter().line_segment([rect.left_bottom(), rect.right_top()], stroke); + ui.painter().rect_stroke(rect, 0.0, stroke, egui::StrokeKind::Inside); + } + } +} + +/// A glyph in `rect` that answers clicks as `label`, its tooltip +fn glyph_button(ui: &mut Ui, rect: Rect, glyph: &str, label: &str, look: GlyphLook) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(label), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), look != GlyphLook::Plain, label)); + let response = response.on_hover_text(label); + if look == GlyphLook::Pressed { + ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), tokens.separator, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside); + } + let color = if look == GlyphLook::Plain && !response.hovered() { tokens.text_dim } else { tokens.text_strong }; + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, glyph, FontId::proportional(ROW_GLYPH_SIZE), color); + response +} + +/// One of the header's bordered buttons, sized to its glyph and words +fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let icon = ui.painter().layout_no_wrap(glyph.to_owned(), FontId::proportional(ROW_GLYPH_SIZE), tokens.text); + let words = ui.painter().layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let width = 2.0 * HEADER_BUTTON_PADDING + icon.size().x + HEADER_GLYPH_GAP + words.size().x; + let (rect, response) = ui.allocate_exact_size(vec2(width, HEADER_BUTTON_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), fill, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside); + let x = rect.left() + HEADER_BUTTON_PADDING; + ui.painter().galley(pos2(x, rect.center().y - icon.size().y / 2.0), icon.clone(), tokens.text); + ui.painter().galley(pos2(x + icon.size().x + HEADER_GLYPH_GAP, rect.center().y - words.size().y / 2.0), words, tokens.text); + response +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 2ae7f095..a4bf439f 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -6,6 +6,7 @@ mod bake_visualization_panel; mod bake_visualization_toggles; mod breadcrumb; mod common_settings; +mod glyph_look; mod section_opening; pub(crate) use bake_checks::bake_warnings; pub use bake_paint_brush::BakePaintBrush; @@ -13,19 +14,31 @@ pub(crate) use bake_visualization_panel::bake_visualization_panel; pub use bake_visualization_toggles::BakeVisualizationToggles; mod controls; mod map_settings; +mod map_thumbnails; mod mesh_map_bakers; +pub use map_thumbnails::MapThumbnails; +mod set_picker; +mod set_picker_purpose; +mod set_picker_row; use egui::{Ui, vec2}; use egui_phosphor::regular as icon; use serde_json::{Value, json}; +use texturecraft_engine::Session; use texturecraft_engine::bake::settings_patch; -use texturecraft_engine::core::{BakeSettings, BakedMap}; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap, CageType}; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; +use crate::property_sheet::PropertySheet; use crate::state::Mode; use crate::widgets::{icon_button, primary_button}; +/// Whether the high poly shows its matching error for `session`'s selected texture set: the automatic cage has no distances to fall short, as in the reference +pub(crate) fn matching_error_applies(session: &Session) -> bool { + session.doc.project.texture_sets.get(session.ts()).is_none_or(|set| set.bake.cage.kind != CageType::Automatic) +} + 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() { @@ -156,20 +169,30 @@ 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 + let restore = ui.horizontal(|ui| { + ui.add_space(crate::property_sheet::SIDE_PADDING_POINTS); + ui.vertical(|ui| { + ui.set_width(ui.available_width() - crate::property_sheet::SIDE_PADDING_POINTS); + breadcrumb::show(app, ui, selected, map_settings::has_parameters(selected)) + }) + .inner + }); + let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Map(selected))); + edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| { + PropertySheet::show(ui, ("mesh_map_settings_sheet", selected), |sheet| map_settings::show(sheet, selected, &mut settings.maps, restore.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); + let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Common)); + edit_settings(app, ui, "bake_common_settings", texture_sets, |app, ui, settings| { + PropertySheet::show(ui, "bake_common_sheet", |sheet| common_settings::show(app, sheet, settings)) + }); } /// The map whose settings show: the chosen one, else the first enabled map, else Normal -fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { +pub(super) fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) } diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs new file mode 100644 index 00000000..fc27b9e9 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -0,0 +1,290 @@ +//! The dialog that picks texture sets: which ones share settings, or which ones a copy goes to + +use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as icon; +use serde_json::{Value, json}; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; + +use super::common_settings::antialiasing_label; +use super::set_picker_purpose::SetPickerPurpose; +use super::set_picker_row::SetPickerRow; +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::PropertySheet; +use crate::theme::{Tokens, semibold}; + +/// Width of the dialog, in points +const DIALOG_WIDTH: f32 = 420.0; + +/// The title bar: its height, the gear's and the title's left edges, and the glyph and title sizes +const TITLE_BAR_HEIGHT: f32 = 30.0; +const TITLE_GEAR_CENTER: f32 = 19.0; +const TITLE_TEXT_LEFT: f32 = 34.0; +const TITLE_GLYPH_SIZE: f32 = 14.0; +const TITLE_TEXT_SIZE: f32 = 12.0; + +/// Air under the title bar and above the buttons, and around the dialog's edge +const BODY_AIR: f32 = 12.0; +const BUTTONS_AIR: f32 = 18.0; +const EDGE_AIR: f32 = 12.0; + +/// OK and Cancel: their size, the air between them, their corners +const BUTTON_SIZE: egui::Vec2 = vec2(88.0, 24.0); +const BUTTON_GAP: f32 = 8.0; +const DIALOG_RADIUS: u8 = 4; + +/// An open picker: what it is for, and per texture set whether it is ticked +#[derive(Clone, Debug)] +pub(super) struct SetPicker { + purpose: SetPickerPurpose, + chosen: Vec, +} + +impl SetPicker { + fn id() -> egui::Id { + egui::Id::unique("bake_set_picker") + } + + /// Open the picker for `purpose`; a sync picker starts with the sets sharing the group ticked, a copy picker with none + pub(super) fn open(app: &TextureCraftApp, ctx: &egui::Context, purpose: SetPickerPurpose) { + let chosen = app + .session + .doc + .project + .texture_sets + .iter() + .map(|set| match purpose { + SetPickerPurpose::Sync(group) => set.bake.sync.shares(group), + SetPickerPurpose::Copy { .. } => false, + }) + .collect(); + ctx.data_mut(|data| data.insert_temp(Self::id(), SetPicker { purpose, chosen })); + } + + /// The open picker, if any; OK runs its command + pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { return }; + + let rows = picker.rows(app); + let active = app.session.ts(); + let tokens = Tokens::get(ctx); + let frame = egui::Frame::new() + .fill(tokens.panel) + .stroke(Stroke::new(1.0, tokens.button_border)) + .corner_radius(CornerRadius::same(DIALOG_RADIUS)) + .inner_margin(0); + let modal = egui::Modal::new(Self::id().with("modal")).frame(frame).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let closed = title_bar(ui, &tokens, &picker.title()); + ui.add_space(BODY_AIR); + PropertySheet::show(ui, "bake_set_picker_sheet", |sheet| picker.list(sheet, &rows)); + ui.add_space(BUTTONS_AIR); + let (ok, cancel) = buttons(ui, &tokens); + ui.add_space(EDGE_AIR); + (ok, cancel || closed) + }); + + let (ok, cancel) = modal.inner; + if ok { + picker.apply(app, active); + } + if ok || cancel || modal.should_close() { + ctx.data_mut(|data| data.remove::(Self::id())); + } else { + ctx.data_mut(|data| data.insert_temp(Self::id(), picker)); + } + } + + /// The listed sets + fn rows(&self, app: &TextureCraftApp) -> Vec { + let project = &app.session.doc.project; + let active = app.session.ts(); + let source = match self.purpose { + // New additions take on the settings already shared, or the active set's when none are + SetPickerPurpose::Sync(group) => project.texture_sets.iter().find(|set| set.bake.sync.shares(group)).or(project.texture_sets.get(active)), + SetPickerPurpose::Copy { .. } => None, + }; + project + .texture_sets + .iter() + .enumerate() + // A copy goes from the active set, so it isn't listed + .filter(|(index, _)| matches!(self.purpose, SetPickerPurpose::Sync(_)) || *index != active) + .map(|(index, set)| { + let note = match (self.purpose, source) { + (SetPickerPurpose::Sync(group), Some(source)) if !set.bake.sync.shares(group) => differing_values(&set.bake, &source.bake, group), + _ => None, + }; + SetPickerRow { index, name: set.name.clone(), note } + }) + .collect() + } + + fn title(&self) -> String { + match self.purpose { + SetPickerPurpose::Sync(group) => trf("{settings} Sync", &[("settings", &group_label(group))]), + SetPickerPurpose::Copy { what: "checked", .. } => tr("Apply Checked to More Texture Sets").to_owned(), + SetPickerPurpose::Copy { what: "check", map: Some(map) } => trf("Check {map} for More Texture Sets", &[("map", &tr(baked_map_label(map)))]), + SetPickerPurpose::Copy { map: Some(map), .. } => trf("Apply {map} Settings to More Texture Sets", &[("map", &tr(baked_map_label(map)))]), + SetPickerPurpose::Copy { .. } => tr("Sync All Settings to More Texture Sets").to_owned(), + } + } + + /// The master check and one check per listed set, indented under it + fn list(&mut self, sheet: &mut PropertySheet<'_>, rows: &[SetPickerRow]) { + let ticked = rows.iter().filter(|row| self.chosen.get(row.index).copied().unwrap_or(false)).count(); + let all_ticked = ticked == rows.len(); + let label = if all_ticked { tr("Deselect All") } else { tr("Select All") }; + let state = if ticked == 0 { Some(false) } else { all_ticked.then_some(true) }; + if sheet.check_mixed(label, state).clicked() { + for row in rows { + if let Some(chosen) = self.chosen.get_mut(row.index) { + *chosen = !all_ticked; + } + } + } + sheet.indented(|sheet| { + for row in rows { + let Some(chosen) = self.chosen.get_mut(row.index) else { continue }; + if sheet.check_noted(&row.name, Some(*chosen), row.note.as_deref()).clicked() { + *chosen = !*chosen; + } + } + }); + } + + fn apply(&self, app: &mut TextureCraftApp, active: usize) { + let ticked: Vec = self.chosen.iter().enumerate().filter(|(_, chosen)| **chosen).map(|(index, _)| index).collect(); + match self.purpose { + SetPickerPurpose::Sync(group) => { + app.run("bake.sync", json!({ "group": group_id(group), "ts": ticked })); + } + SetPickerPurpose::Copy { what, map } if !ticked.is_empty() => { + app.run("bake.copy", json!({ "what": what, "map": map.map(BakedMap::id), "from": active, "ts": ticked })); + } + SetPickerPurpose::Copy { .. } => {} + } + } +} + +/// The group as the `bake.sync` command names it +pub(super) fn group_id(group: BakeSyncGroup) -> &'static str { + match group { + BakeSyncGroup::Common => "common", + BakeSyncGroup::Map(map) => map.id(), + } +} + +fn group_label(group: BakeSyncGroup) -> String { + match group { + BakeSyncGroup::Common => tr("Common Settings").to_owned(), + BakeSyncGroup::Map(map) => trf("{map} Settings", &[("map", &tr(baked_map_label(map)))]), + } +} + +/// The title bar: gear, title, and × at the right; returns whether × was clicked +fn title_bar(ui: &mut Ui, tokens: &Tokens, title: &str) -> bool { + let (bar, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, TITLE_BAR_HEIGHT), Sense::hover()); + let top = CornerRadius { nw: DIALOG_RADIUS, ne: DIALOG_RADIUS, sw: 0, se: 0 }; + ui.painter().rect_filled(bar, top, tokens.chrome); + let center_y = bar.center().y; + ui.painter().text(pos2(bar.left() + TITLE_GEAR_CENTER, center_y), Align2::CENTER_CENTER, icon::GEAR, FontId::proportional(TITLE_GLYPH_SIZE), tokens.text); + let text = Rect::from_min_max(pos2(bar.left() + TITLE_TEXT_LEFT, bar.top()), pos2(bar.right() - TITLE_BAR_HEIGHT, bar.bottom())); + let label = egui::Label::new(RichText::new(title).font(semibold(TITLE_TEXT_SIZE)).color(tokens.text_strong)).truncate(); + ui.scope_builder(egui::UiBuilder::new().max_rect(text).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| ui.add(label)); + + let close = Rect::from_center_size(pos2(bar.right() - TITLE_BAR_HEIGHT / 2.0, center_y), vec2(TITLE_BAR_HEIGHT, TITLE_BAR_HEIGHT)); + let response = ui.interact(close, ui.scope_id().with("close"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Close"))); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(close.center(), Align2::CENTER_CENTER, icon::X, FontId::proportional(TITLE_TEXT_SIZE), color); + response.clicked() +} + +/// OK then Cancel at the right, both neutral; returns (OK, Cancel) clicked +fn buttons(ui: &mut Ui, tokens: &Tokens) -> (bool, bool) { + let (row, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, BUTTON_SIZE.y), Sense::hover()); + let cancel = Rect::from_min_size(pos2(row.right() - EDGE_AIR - BUTTON_SIZE.x, row.top()), BUTTON_SIZE); + let ok = cancel.translate(vec2(-(BUTTON_SIZE.x + BUTTON_GAP), 0.0)); + (dialog_button(ui, tokens, ok, tr("OK")), dialog_button(ui, tokens, cancel, tr("Cancel"))) +} + +fn dialog_button(ui: &mut Ui, tokens: &Tokens, rect: Rect, text: &str) -> bool { + let response = ui.interact(rect, ui.scope_id().with(text), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(DIALOG_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, FontId::proportional(TITLE_TEXT_SIZE), tokens.text); + response.clicked() +} + +/// What `set` holds in `group` that differs from `source`, dim beside it: output size and antialiasing by value, the rest counted +fn differing_values(set: &BakeSettings, source: &BakeSettings, group: BakeSyncGroup) -> Option { + let mut taken = set.clone(); + taken.copy_group(source, group); + let mut patch = settings_patch(set, &taken); + let mut values = Vec::new(); + if let Some(common) = patch.get_mut("common").and_then(Value::as_object_mut) { + let resolution = common.remove("resolution").is_some(); + let height = common.remove("resolution_height").is_some(); + if resolution || height { + values.push(match set.common.output_size() { + (width, height) if width == height => width.to_string(), + (width, height) => format!("{width} × {height}"), + }); + } + if common.remove("antialiasing").is_some() { + values.push(tr(antialiasing_label(set.common.antialiasing)).to_owned()); + } + } + let rest = leaf_count(&patch); + match (values.is_empty(), rest) { + (true, 0) => None, + (true, 1) => Some(tr("1 differing setting").to_owned()), + (true, count) => Some(trf("{count} differing settings", &[("count", &count.to_string())])), + (false, 0) => Some(values.join(" · ")), + (false, count) => Some(trf("{values} · {count} more", &[("values", &values.join(" · ")), ("count", &count.to_string())])), + } +} + +/// How many plain values a settings patch changes +fn leaf_count(patch: &Value) -> usize { + match patch { + Value::Object(fields) => fields.values().map(leaf_count).sum(), + _ => 1, + } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap}; + + use super::differing_values; + + #[test] + fn a_set_shows_its_own_size_and_antialiasing_and_counts_the_rest() { + let source = BakeSettings::default(); + let mut set = BakeSettings::default(); + set.common.resolution = BakeResolution::R1024; + set.common.antialiasing = BakeAntialiasing::Subsampling4x4; + set.common.dilation = 8; + set.high_poly.ignore_backface = !source.high_poly.ignore_backface; + + let note = differing_values(&set, &source, BakeSyncGroup::Common); + + assert_eq!(note.as_deref(), Some("1024 · Subsampling 4x4 · 2 more")); + } + + #[test] + fn a_set_matching_the_group_shows_nothing_and_other_groups_are_not_compared() { + let source = BakeSettings::default(); + let mut set = BakeSettings::default(); + set.common.is_enabled = false; + set.maps.ao.parameters.rays.rays = 16; + + assert_eq!(differing_values(&set, &source, BakeSyncGroup::Common), None); + assert_eq!(differing_values(&set, &source, BakeSyncGroup::Map(BakedMap::AmbientOcclusion)).as_deref(), Some("1 differing setting")); + } +} diff --git a/crates/ui-egui/src/bake_mode/set_picker_purpose.rs b/crates/ui-egui/src/bake_mode/set_picker_purpose.rs new file mode 100644 index 00000000..f2b21b50 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker_purpose.rs @@ -0,0 +1,10 @@ +use texturecraft_engine::core::{BakeSyncGroup, BakedMap}; + +/// What a texture set picker does with the sets chosen in it +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SetPickerPurpose { + /// Exactly the chosen sets share the group's settings + Sync(BakeSyncGroup), + /// Copy from the active set to the chosen ones: `what` as the `bake.copy` command takes it, for one map or for all + Copy { what: &'static str, map: Option }, +} diff --git a/crates/ui-egui/src/bake_mode/set_picker_row.rs b/crates/ui-egui/src/bake_mode/set_picker_row.rs new file mode 100644 index 00000000..e7f18f6c --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker_row.rs @@ -0,0 +1,7 @@ +/// One texture set listed in the set picker +pub(super) struct SetPickerRow { + pub(super) index: usize, + pub(super) name: String, + /// For a set not yet sharing a sync group, the values it would give up + pub(super) note: Option, +} 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 766a43c2..751aed00 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -52,7 +52,7 @@ impl BakeSceneLink { let Some(visualization) = visualization else { return }; if visualization.high_poly.shown { - let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let high = session.doc.bake_meshes.merged_high().map(|high| high.mesh.clone()); let handle = SharedHandle::of(high.as_ref()); if handle != self.high { self.high = handle; diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs index 44e17eca..126c7f06 100644 --- a/crates/ui-egui/src/bake_scene/cage_shell_key.rs +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -2,12 +2,12 @@ use std::collections::BTreeMap; use texturecraft_engine::Session; use texturecraft_engine::bake::BakePaintMap; -use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::core::{BakePaintTarget, CageType, HighPolySettings, 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 +/// Everything a texture set's cage shell and ray reach are built from except the distances, which only move its corners #[derive(Clone, Debug, PartialEq)] pub(super) struct CageShellKey { mesh_id: u64, @@ -19,7 +19,8 @@ pub(super) struct CageShellKey { cage_kind: CageType, relative_to_bounding_box: bool, average_normals: bool, - use_low_as_high: bool, + /// Whether the set has a cage at all, the name matching the automatic cage fits by and the backfaces the reach leaves out + high_poly: HighPolySettings, skew: SkewSettings, /// The painted skew and cage maps paint: [SharedHandle; 2], @@ -31,17 +32,37 @@ impl CageShellKey { 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)), + high: SharedHandle::of(session.doc.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.doc.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, + high_poly: set.bake.high_poly.clone(), skew: set.bake.skew, paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], }) } } + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::MeshMatchMode; + use texturecraft_engine::geom::primitives; + + #[test] + fn the_key_changes_with_the_name_matching_the_automatic_cage_is_fitted_by() { + let mut session = Session::new_project("Cage", primitives::plane(1.0, 1), "plane", None, 128).unwrap(); + let before = CageShellKey::of(&session, 0); + + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let by_name = CageShellKey::of(&session, 0); + session.doc.project.texture_sets[0].bake.high_poly.high_suffix = "_hp".into(); + + assert_ne!(before, by_name); + assert_ne!(by_name, CageShellKey::of(&session, 0)); + } +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs index f94ed3d5..3996a25b 100644 --- a/crates/ui-egui/src/bake_scene/reach_link.rs +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -2,7 +2,6 @@ use std::sync::mpsc::{Receiver, TryRecvError}; use texturecraft_engine::Session; use texturecraft_engine::bake::{HighPolyReach, high_poly_missed}; -use texturecraft_engine::core::HighPolySettings; use super::cage_shell_key::CageShellKey; use crate::gpu::SceneSync; @@ -13,8 +12,8 @@ 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>, + /// Each set's ray inputs, and the id of the high poly, the reach was started for + keys: Vec>, high_id: u64, job: Option>>>, reach: Vec>, @@ -56,14 +55,7 @@ impl ReachLink { } 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(); + let keys: Vec> = (0..set_count).map(|texture_set| CageShellKey::of(session, texture_set)).collect(); if keys != self.keys || high_id != self.high_id { // The GPU keeps displayed colors; stale CPU arrays need not overlap the rebuild @@ -87,7 +79,7 @@ impl ReachLink { return; } - let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + let Some(vertex_count) = session.doc.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; out.bake_high_missed = Some((self.high_id, high_poly_missed(&self.reach, &shown.0, only_set, vertex_count))); self.shown = Some(shown); @@ -164,7 +156,7 @@ mod tests { link.sync(&session, 2, None, &mut out); let (high_id, missed) = out.bake_high_missed.unwrap(); assert_eq!(high_id, 2); - assert_eq!(missed, vec![0.0; session.bake_meshes.merged_high().unwrap().mesh.positions.len()]); + assert_eq!(missed, vec![0.0; session.doc.bake_meshes.merged_high().unwrap().mesh.positions.len()]); assert!(link.reach[0].is_none(), "the latest setting bakes without a high poly"); } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 761928ec..c900230b 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -262,8 +262,8 @@ pub(crate) const TAB_HEIGHT: f32 = 30.0; /// Width of the bake layout's texture set and mesh map bakers column in points: the reference's scaled to our larger font const BAKERS_COLUMN_WIDTH: f32 = 232.0; -/// Width of the bake layout's common and mesh map settings column, in points -const SETTINGS_COLUMN_WIDTH: f32 = 330.0; +/// Width of the bake layout's common and mesh map settings column, in points: both tab names fit beside the × +const SETTINGS_COLUMN_WIDTH: f32 = 380.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 diff --git a/crates/ui-egui/src/high_poly_job.rs b/crates/ui-egui/src/high_poly_job.rs new file mode 100644 index 00000000..37ac21df --- /dev/null +++ b/crates/ui-egui/src/high_poly_job.rs @@ -0,0 +1,79 @@ +use std::collections::VecDeque; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use texturecraft_engine::{EngineError, HighPolyLoad, Result}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; + +/// How often the app looks for the worker's answer while a file loads +const POLL_INTERVAL: Duration = Duration::from_millis(30); + +/// High poly files loading on a worker thread, one after the other, so a large mesh does not freeze the app +pub struct HighPolyJob { + /// The file being loaded + pub current: String, + /// The worker's answer for `current` + answer: Receiver>, + /// The files still to load, in order + pub queue: VecDeque, + /// The project the files are for: they are dropped once another project is open + project: u64, +} + +impl HighPolyJob { + /// The names of the files being loaded and waiting, without their folders + pub fn file_names(&self) -> impl Iterator { + std::iter::once(&self.current).chain(&self.queue).map(|path| std::path::Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path)) + } +} + +impl TextureCraftApp { + /// Add the mesh files at `paths` as high polys, read and parsed on a worker thread + #[cfg(not(target_arch = "wasm32"))] + pub fn load_high_polys(&mut self, paths: impl IntoIterator) { + let mut paths: VecDeque = paths.into_iter().collect(); + match &mut self.high_poly_job { + Some(job) if job.project == self.session.project_id => job.queue.append(&mut paths), + _ => self.load_next_high_poly(paths), + } + } + + /// Start loading the first of `queue`, on top of the high polys the session has now + #[cfg(not(target_arch = "wasm32"))] + fn load_next_high_poly(&mut self, mut queue: VecDeque) { + self.high_poly_job = queue.pop_front().map(|current| { + let (meshes, path) = (self.session.doc.bake_meshes.clone(), current.clone()); + let answer = crate::spawn_worker("texturecraft-high-poly", move || HighPolyLoad::read(&meshes, &path)); + HighPolyJob { current, answer, queue, project: self.session.project_id } + }); + } + + /// Add a loaded high poly to the session and start on the next file; drop them all once another project is open + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn poll_high_poly_job(&mut self, context: &egui::Context) { + let Some(job) = &self.high_poly_job else { return }; + if job.project != self.session.project_id { + self.high_poly_job = None; + self.toast(tr("The project changed while the high polys loaded, so they were not added"), true); + return; + } + + context.request_repaint_after(POLL_INTERVAL); + let loaded = match job.answer.try_recv() { + Ok(loaded) => loaded, + Err(TryRecvError::Empty) => return, + Err(TryRecvError::Disconnected) => Err(EngineError::Other(tr("The mesh loading worker stopped").into())), + }; + let Some(job) = self.high_poly_job.take() else { return }; + + match loaded { + Ok(load) => { + self.session.apply_high_poly_load(load); + } + Err(error) => self.toast(trf("Couldn't import {name}: {error}", &[("name", &job.current), ("error", &error.to_string())]), true), + } + self.load_next_high_poly(job.queue); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..a24b9d6d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -48,6 +48,7 @@ mod generator_panel; pub mod gpu; mod gray_slider; mod grid_tile; +mod high_poly_job; mod histogram_cache; pub mod i18n; pub mod id_color_pick; @@ -182,6 +183,7 @@ use texturecraft_engine::bake::Progress; pub use bake_job::BakeJob; pub use control::ControlRequest; +pub use high_poly_job::HighPolyJob; pub use running_bake::RunningBake; pub use state::UiState; @@ -264,12 +266,16 @@ pub struct TextureCraftApp { /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, + /// High poly files being loaded for the bake + pub high_poly_job: Option, pub link_cooks: Vec, #[cfg(not(target_arch = "wasm32"))] link_imports: Vec, pub thumbs: thumbs::Thumbs, /// The Layers panel's thumbnails and folded groups. pub layer_panel: layer_panel::LayerPanel, + /// The Mesh Map Bakers rows' thumbnails + pub(crate) bake_map_thumbnails: bake_mode::MapThumbnails, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -405,11 +411,13 @@ impl TextureCraftApp { bake_report: Default::default(), pbr_import: None, resize: None, + high_poly_job: None, link_cooks: Vec::new(), #[cfg(not(target_arch = "wasm32"))] link_imports: Vec::new(), thumbs: thumbs::Thumbs::default(), layer_panel: layer_panel::LayerPanel::default(), + bake_map_thumbnails: bake_mode::MapThumbnails::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, @@ -599,9 +607,13 @@ impl TextureCraftApp { self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); } - /// Start baking texture sets in the background, one after another. Invalid set indices - /// show an error without starting a preview or queuing any work. + /// Bake texture sets in the background, one after another; invalid set indices show an error without starting anything pub fn start_bake(&mut self, sets: Vec) { + self.start_bake_of(sets, None); + } + + /// Bake `sets`: only map `only` when given, else each set's checked maps + pub fn start_bake_of(&mut self, sets: Vec, only: Option) { if self.bake.is_some() || sets.is_empty() { return; } @@ -609,14 +621,19 @@ impl TextureCraftApp { // Restore the picker's view before the preview starts following baked maps id_color_pick::IdColorPick::end(self); - if let Err(error) = self.session.bake_preview_begin_for(&sets) { - self.toast(error.to_string(), true); - return; + match only { + Some(map) => self.session.bake_preview_begin(sets.iter().map(|set| (*set, vec![map])).collect()), + None => { + if let Err(error) = self.session.bake_preview_begin_for(&sets) { + self.toast(error.to_string(), true); + return; + } + } } let total = sets.len(); self.bake_report = bake_report::BakeReport::started(self.last_time); - self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -713,8 +730,7 @@ impl TextureCraftApp { } } - /// Show at most one streamed map per frame, then apply the set as one undo step after - /// its map channel closes. Closing the preview alone does not stop the background bake. + /// Show at most one streamed map per frame, then apply the set as one undo step once its map channel closes; closing the preview alone does not stop the bake fn poll_bake(&mut self, ctx: &egui::Context) { // Leaving Bake mode puts the view mode back; the bake goes on if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { @@ -736,7 +752,7 @@ impl TextureCraftApp { return; } - ctx.request_repaint_after(std::time::Duration::from_millis(50)); + ctx.request_repaint_after(BAKE_POLL_INTERVAL); if let Some(running) = &job.current { let set_index = running.set_index; @@ -787,9 +803,15 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); + let only = job.only; + self.session.bake_preview_set_current(set_index); match self.session.bake_task(set_index) { - Ok(task) => { + Ok(mut task) => { + if let Some(map) = only { + task.settings.maps.select([map]); + } + let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); @@ -1015,6 +1037,9 @@ struct CameraGlide { const GLIDE_SECONDS: f64 = 0.35; +/// How often a running bake is checked for finished maps: often enough that each shows within a few frames +const BAKE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50); + /// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames) const FRAME_AVERAGE_KEEP: f32 = 0.9; /// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason @@ -1107,6 +1132,8 @@ impl eframe::App for TextureCraftApp { } self.poll_bake(ctx); self.poll_resize(ctx); + #[cfg(not(target_arch = "wasm32"))] + self.poll_high_poly_job(ctx); self.poll_link_cooks(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_link_imports(ctx); diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs index 5917a337..122857cb 100644 --- a/crates/ui-egui/src/property_sheet/choice.rs +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -159,7 +159,8 @@ impl PropertySheet<'_> { pub(super) fn dropdown_button_led(&mut self, rect: Rect, value: &str, lead: impl FnOnce(&Painter) -> f32) -> Response { let id = self.next_id(); let response = self.ui.interact(rect, id, Sense::click()); - response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, true, value)); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, enabled, value)); let tokens = self.tokens; let painter = self.ui.painter(); painter.rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), if response.hovered() { tokens.row_hover } else { tokens.button }); diff --git a/crates/ui-egui/src/property_sheet/file_list.rs b/crates/ui-egui/src/property_sheet/file_list.rs new file mode 100644 index 00000000..69a34386 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list.rs @@ -0,0 +1,152 @@ +//! A list of loaded files under its label, one row per file, with its add button beside it + +use egui::{Align2, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::FileListAdd; +use super::stacked_rows::{LABEL_LINE, STACK_ROW_AIR}; +use super::{CONTROL_RADIUS, FileListResponse, FileRow, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// One file's row, and the list's inner margin above and below its rows +const FILE_ROW_HEIGHT: f32 = 40.0; +const LIST_MARGIN: f32 = 2.0; + +/// The add button's square and the room it takes beside the list +const ADD_BUTTON_SIZE: f32 = 28.0; +const ADD_BUTTON_ROOM: f32 = 34.0; + +/// Where a row's cube sits, where its words start, and its × from the list's right edge +const CUBE_CENTER: f32 = 16.0; +const CUBE_SIZE: f32 = 14.0; +const NAME_LEFT: f32 = 32.0; +const REMOVE_INSET: f32 = 14.0; +const REMOVE_SIZE: f32 = 12.0; +const REMOVE_BOX: f32 = 18.0; + +/// The name's and the folder's centres from the row's top, when the row shows both +const NAME_CENTER: f32 = 13.0; +const FOLDER_CENTER: f32 = 28.0; + +/// The hairline between rows stops this far from the list's sides +const DIVIDER_INSET: f32 = 8.0; + +/// Size of the add button's glyph +const ADD_GLYPH_SIZE: f32 = 14.0; + +/// What stands for the folders left out of a shortened path +const ELLIPSIS: &str = "…"; + +impl PropertySheet<'_> { + /// `rows` in a box at least `min_rows` tall, with the `add` button beside it; each loaded file's × (`remove_label`) asks to remove it + pub(crate) fn file_list(&mut self, label: &str, rows: &[FileRow<'_>], min_rows: usize, add: FileListAdd<'_>, remove_label: &str) -> FileListResponse { + let line = self.take(LABEL_LINE); + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, line.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text); + + let height = rows.len().max(min_rows) as f32 * FILE_ROW_HEIGHT + 2.0 * LIST_MARGIN; + let area = self.take(height); + let list = Rect::from_min_max(pos2(self.left, area.top()), pos2(self.right - ADD_BUTTON_ROOM, area.bottom())); + let list_id = self.next_id(); + let list_response = self.ui.interact(list, list_id, Sense::hover()); + let enabled = self.ui.is_enabled(); + list_response.widget_info(|| WidgetInfo::labeled(egui::Role::List, enabled, label)); + self.ui.painter().rect(list, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + + let mut answer = FileListResponse::default(); + for (index, row) in rows.iter().enumerate() { + let top = list.top() + LIST_MARGIN + index as f32 * FILE_ROW_HEIGHT; + let rect = Rect::from_min_max(pos2(list.left(), top), pos2(list.right(), top + FILE_ROW_HEIGHT)); + if index > 0 { + let divider = [pos2(list.left() + DIVIDER_INSET, top), pos2(list.right() - DIVIDER_INSET, top)]; + self.ui.painter().line_segment(divider, Stroke::new(1.0, tokens.separator)); + } + if self.file_row(rect, row, remove_label) { + answer.removed = Some(index); + } + } + + let add_rect = Rect::from_min_size(pos2(self.right - ADD_BUTTON_SIZE, area.top()), vec2(ADD_BUTTON_SIZE, ADD_BUTTON_SIZE)); + let add_id = self.next_id(); + let can_add = add.enabled && enabled; + let add_response = self.ui.interact(add_rect, add_id, if can_add { Sense::click() } else { Sense::hover() }); + add_response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, can_add, add.label)); + let add_response = self.tip(add_response, add.label); + let fill = if can_add && add_response.hovered() { tokens.row_hover } else { tokens.button }; + let glyph_color = if can_add { tokens.text } else { tokens.text_dim }; + let painter = self.ui.painter(); + painter.rect(add_rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + painter.text(add_rect.center(), Align2::CENTER_CENTER, add.glyph, FontId::proportional(ADD_GLYPH_SIZE), glyph_color); + self.paint_control_focus(&add_response); + answer.add = can_add && add_response.clicked(); + + self.drawn(area.bottom()); + self.space(2.0 * STACK_ROW_AIR); + answer + } + + /// One file's row in `rect`; returns whether its × was clicked + fn file_row(&mut self, rect: Rect, row: &FileRow<'_>, remove_label: &str) -> bool { + let tokens = self.tokens; + let words_right = rect.right() - REMOVE_INSET - REMOVE_BOX / 2.0; + let name_color = if row.loading { tokens.text_dim } else { tokens.text }; + let name_font = if row.loading { FontId::proportional(TEXT_SIZE) } else { semibold(TEXT_SIZE) }; + let name_y = if row.folder.is_some() { rect.top() + NAME_CENTER } else { rect.center().y }; + let painter = self.ui.painter().clone(); + painter.text(pos2(rect.left() + CUBE_CENTER, rect.center().y), Align2::CENTER_CENTER, ic::CUBE, FontId::proportional(CUBE_SIZE), tokens.text_dim); + let mut job = egui::text::LayoutJob::simple_singleline(row.name.to_owned(), name_font, name_color); + job.wrap = egui::text::TextWrapping::truncate_at_width((words_right - rect.left() - NAME_LEFT).max(0.0)); + let name = painter.layout_job(job); + painter.galley(pos2(rect.left() + NAME_LEFT, name_y - name.size().y / 2.0), name, name_color); + if let Some(folder) = row.folder { + let shown = shortened_folder(&painter, folder, words_right - rect.left() - NAME_LEFT); + painter.text( + pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER), + Align2::LEFT_CENTER, + shown, + FontId::proportional(SMALL_TEXT_SIZE), + tokens.text_dim, + ); + } + + let words = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(words_right, rect.bottom())); + let words_id = self.next_id(); + let words_response = self.ui.interact(words, words_id, Sense::hover()); + let enabled = self.ui.is_enabled() && !row.loading; + words_response.widget_info(|| WidgetInfo::labeled(egui::Role::ListItem, enabled, row.name)); + let full = match row.folder { + Some(folder) => format!("{}\n{folder}", row.name), + None => row.name.to_owned(), + }; + self.tip(words_response, &full); + if row.loading { + return false; + } + + let remove = Rect::from_center_size(pos2(rect.right() - REMOVE_INSET, rect.center().y), vec2(REMOVE_BOX, REMOVE_BOX)); + let id = self.next_id(); + let response = self.ui.interact(remove, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, self.ui.is_enabled(), remove_label)); + let response = self.tip(response, remove_label); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(remove.center(), Align2::CENTER_CENTER, ic::X, FontId::proportional(REMOVE_SIZE), color); + self.paint_control_focus(&response); + response.clicked() + } +} + +/// `folder` with folders after its first one left out, from the second on, until it fits in `room` +fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String { + let fits = |text: &str| painter.layout_no_wrap(text.to_owned(), FontId::proportional(SMALL_TEXT_SIZE), egui::Color32::WHITE).size().x <= room; + let mut parts: Vec<&str> = folder.split(['/', '\\']).collect(); + let mut shown = parts.join("/"); + while !fits(&shown) && parts.len() > 2 { + if parts[1] == ELLIPSIS { + parts.remove(2); + } else { + parts[1] = ELLIPSIS; + } + shown = parts.join("/"); + } + shown +} diff --git a/crates/ui-egui/src/property_sheet/file_list_add.rs b/crates/ui-egui/src/property_sheet/file_list_add.rs new file mode 100644 index 00000000..f790083e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list_add.rs @@ -0,0 +1,6 @@ +/// A file list's add button: its glyph, its label (also its tooltip) and whether it can add now +pub(crate) struct FileListAdd<'a> { + pub(crate) glyph: &'a str, + pub(crate) label: &'a str, + pub(crate) enabled: bool, +} diff --git a/crates/ui-egui/src/property_sheet/file_list_response.rs b/crates/ui-egui/src/property_sheet/file_list_response.rs new file mode 100644 index 00000000..e0b24c24 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list_response.rs @@ -0,0 +1,6 @@ +/// What a file list answered: its add button clicked, or a file's × clicked +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct FileListResponse { + pub(crate) add: bool, + pub(crate) removed: Option, +} diff --git a/crates/ui-egui/src/property_sheet/file_row.rs b/crates/ui-egui/src/property_sheet/file_row.rs new file mode 100644 index 00000000..1d7bf0c0 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_row.rs @@ -0,0 +1,7 @@ +/// One file of a file list: its name, the folder it was read from when known, and whether it is still loading +#[derive(Clone, Copy)] +pub(crate) struct FileRow<'a> { + pub(crate) name: &'a str, + pub(crate) folder: Option<&'a str>, + pub(crate) loading: bool, +} diff --git a/crates/ui-egui/src/property_sheet/fold_section.rs b/crates/ui-egui/src/property_sheet/fold_section.rs new file mode 100644 index 00000000..7f8e1d3d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/fold_section.rs @@ -0,0 +1,7 @@ +use egui::Response; + +/// What a folding section's caption answered: whether its rows show, and its reset glyph +pub(crate) struct FoldSection { + pub(crate) open: bool, + pub(crate) reset: Response, +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 62c81046..852d4673 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -13,6 +13,11 @@ mod compare_row; mod compare_row_response; mod eye_toggle; mod factor_slider; +mod file_list; +mod file_list_add; +mod file_list_response; +mod file_row; +mod fold_section; mod gradient_rows; mod group; mod hold_pad; @@ -42,6 +47,7 @@ mod slot; mod slot_response; mod source_card; mod stack_slider; +mod stacked_rows; mod switch_control; mod tooltip; mod track; @@ -55,6 +61,10 @@ pub(crate) use action_row_response::ActionRowResponse; pub(crate) use band_response::BandResponse; pub(crate) use button_icon::ButtonIcon; pub(crate) use compare_row_response::CompareRowResponse; +pub(crate) use file_list_add::FileListAdd; +pub(crate) use file_list_response::FileListResponse; +pub(crate) use file_row::FileRow; +pub(crate) use fold_section::FoldSection; pub(crate) use id_color_row_response::IdColorRowResponse; pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; @@ -68,6 +78,7 @@ pub(crate) use section_tabs::{ pub(crate) use sheet::PropertySheet; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; +pub(crate) use stacked_rows::{CHECK_SIZE, paint_check}; /// Side padding: every row starts and ends this far inside the panel pub(crate) const SIDE_PADDING_POINTS: f32 = 12.0; diff --git a/crates/ui-egui/src/property_sheet/property_sheet.rs b/crates/ui-egui/src/property_sheet/property_sheet.rs index 6d26f207..e1e5b1b6 100644 --- a/crates/ui-egui/src/property_sheet/property_sheet.rs +++ b/crates/ui-egui/src/property_sheet/property_sheet.rs @@ -27,6 +27,8 @@ pub(crate) struct PropertySheet<'u> { pub(super) sections: Vec<(String, f32)>, pub(super) info: Option<&'u str>, pub(super) held: bool, + /// Sub-headers so far in the current folding section: a later one takes air above it + pub(super) sub_headers: usize, } impl<'u> PropertySheet<'u> { @@ -53,6 +55,7 @@ impl<'u> PropertySheet<'u> { sections: Vec::new(), info: None, held: false, + sub_headers: 0, ui, }; let result = body(&mut sheet); diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 98ef953d..9770d2c5 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -195,7 +195,8 @@ impl PropertySheet<'_> { pos2(track.end + KNOB_RADIUS, track.center_y + ROW_HIT_HALF_HEIGHT), ); let response = self.ui.interact(hit, id, Sense::click_and_drag()); - response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::slider(enabled, f64::from(*value), &label)); let mut moved = false; if (response.dragged() || response.drag_stopped() || response.clicked()) @@ -294,7 +295,8 @@ impl PropertySheet<'_> { let Some(mut draft) = editing else { self.skip_typing_edit(); let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); - response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, enabled, crate::i18n::trf("{label} value", &[("label", label)]))); self.ui.painter().text(pos2(right, center_y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); if response.hovered() { diff --git a/crates/ui-egui/src/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs new file mode 100644 index 00000000..88aad56b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -0,0 +1,471 @@ +//! Rows with their label above a full-width control, as the bake panels lay them out: folding sections, bold sub-headers, checks, and controls that grey out with a reason + +use std::ops::RangeInclusive; + +use egui::{Align2, CornerRadius, FontId, Rect, Response, Sense, Stroke, StrokeKind, UiBuilder, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::choice::ChoicePicture; +use super::number_field::shown_number; +use super::slider::KNOB_RADIUS; +use super::track::Track; +use super::value_text::ValueText; +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, FoldSection, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Height of a label's line above its control, and its text's centre in it +pub(super) const LABEL_LINE: f32 = 18.0; +const LABEL_CENTER: f32 = 9.0; + +/// Air under a control before the next setting; full-width buttons and lists take it above and twice below, so two filled boxes never touch +pub(super) const STACK_ROW_AIR: f32 = 6.0; + +/// A slider's track line under its label, and its centre in it +const TRACK_LINE: f32 = 16.0; +const TRACK_CENTER: f32 = 8.0; + +/// A check's line, its box and the air from the box to its label +const CHECK_LINE: f32 = 20.0; +pub(crate) const CHECK_SIZE: f32 = 13.0; +const CHECK_RADIUS: u8 = 2; +const CHECK_TO_LABEL: f32 = 9.0; + +/// The tick's three points across a check's box, as fractions of its side (from the reference's tick) +const TICK_POINTS: [(f32, f32); 3] = [(0.25, 0.52), (0.43, 0.7), (0.75, 0.3)]; +const TICK_WIDTH: f32 = 1.7; + +/// Half the length of a mixed check's dash, and its thickness +const DASH_HALF: f32 = 3.0; +const DASH_WIDTH: f32 = 2.0; + +/// Air above a later section's hairline and from it to the caption +const FOLD_AIR_ABOVE: f32 = 8.0; +const FOLD_RULE_TO_CAPTION: f32 = 10.0; + +/// Air above the first section's caption +const FOLD_FIRST_AIR: f32 = 10.0; + +/// A section caption's line, the air under it, and where its chevron and caption sit +const FOLD_CAPTION_LINE: f32 = 20.0; +const FOLD_CAPTION_AIR: f32 = 10.0; +const FOLD_CHEVRON_CENTER: f32 = 5.0; +const FOLD_CAPTION_LEFT: f32 = 18.0; + +/// The reset glyph's size and its centre's distance from the right edge +const FOLD_RESET_SIZE: f32 = 14.0; +const FOLD_RESET_INSET: f32 = 6.0; +const FOLD_RESET_BOX: f32 = 20.0; + +/// Air above a later sub-header, its line, and the air under it +const SUB_HEADER_AIR: f32 = 6.0; +const SUB_HEADER_LINE: f32 = 18.0; +const SUB_HEADER_GAP: f32 = 4.0; + +/// How far a sub-header's rows, and settings that belong to the one above, sit in from the left +const STACK_INDENT: f32 = 12.0; + +/// Opacity of a greyed setting, on top of egui's disabled fade: 0.4 in all, the locked bake mock's 60 % blend toward the panel +const GREYED_EXTRA_OPACITY: f32 = 0.8; + +/// A full-width button's glyph size and the air between it and its words +const WIDE_BUTTON_ICON_SIZE: f32 = 13.0; +const WIDE_BUTTON_ICON_GAP: f32 = 8.0; + +/// Width of the link between two paired dropdowns, and the air on its sides +const PAIR_LINK_WIDTH: f32 = 26.0; +const PAIR_LINK_AIR: f32 = 4.0; + +/// Values with more places than this drop their trailing zeros +const SHORT_DECIMALS: usize = 2; + +/// Air before a field's text +const FIELD_TEXT_INSET: i8 = 8; + +impl PropertySheet<'_> { + /// A section that folds: chevron and CAPS caption left, its reset glyph right, a hairline above a later one; the click on the caption line folds it + pub(crate) fn fold_section(&mut self, title: &str, default_open: bool) -> FoldSection { + self.close_card(); + if self.empty { + self.space(FOLD_FIRST_AIR); + } else { + self.space(FOLD_AIR_ABOVE); + let y = self.cursor_y(); + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.space(FOLD_RULE_TO_CAPTION); + } + + let section = self.id.with(("fold_section", title)); + self.scope = section; + self.band_scope = section; + let line = self.take(FOLD_CAPTION_LINE); + let center_y = line.center().y; + let reset_rect = Rect::from_center_size(pos2(self.right - FOLD_RESET_INSET, center_y), vec2(FOLD_RESET_BOX, FOLD_RESET_BOX)); + let header = Rect::from_min_max(pos2(self.left, line.top()), pos2(reset_rect.left(), line.bottom())); + + let mut open = self.ui.data(|data| data.get_temp::(section)).unwrap_or(default_open); + let fold = self.ui.interact(header, section.with("fold"), Sense::click()); + if fold.clicked() { + open = !open; + self.ui.data_mut(|data| data.insert_temp(section, open)); + } + let enabled = self.ui.is_enabled(); + fold.widget_info(|| WidgetInfo::selected(egui::Role::Button, enabled, open, title)); + + // Added after the caption's response, so the glyph takes the clicks over it + let reset = self.ui.interact(reset_rect, section.with("reset"), Sense::click()); + let reset_label = crate::i18n::trf("Reset {section}", &[("section", &title)]); + reset.widget_info(|| WidgetInfo::labeled(egui::Role::Button, enabled, &reset_label)); + let reset = self.tip(reset, &reset_label); + + let tokens = self.tokens; + let painter = self.ui.painter(); + let chevron = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + painter.text(pos2(self.left + FOLD_CHEVRON_CENTER, center_y), Align2::CENTER_CENTER, chevron, FontId::proportional(ICON_SIZE), tokens.text); + painter.text(pos2(self.left + FOLD_CAPTION_LEFT, center_y), Align2::LEFT_CENTER, title.to_uppercase(), semibold(SMALL_TEXT_SIZE), tokens.text); + let reset_color = if reset.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(reset_rect.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(FOLD_RESET_SIZE), reset_color); + self.paint_control_focus(&fold); + self.paint_control_focus(&reset); + self.drawn(line.bottom()); + if open { + self.space(FOLD_CAPTION_AIR); + } + self.sub_headers = 0; + FoldSection { open, reset } + } + + /// A bold sub-header; its rows follow one [`STACK_INDENT`] in, inside `body` + pub(crate) fn sub_header(&mut self, title: &str, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + if self.sub_headers > 0 { + self.space(SUB_HEADER_AIR); + } + self.sub_headers += 1; + let line = self.take(SUB_HEADER_LINE); + let text = self.tokens.text_strong; + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), text); + self.drawn(line.bottom()); + self.space(SUB_HEADER_GAP); + self.indented(body) + } + + /// `body`'s rows one [`STACK_INDENT`] in from the left + pub(crate) fn indented(&mut self, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let left = self.left; + self.left += STACK_INDENT; + let result = body(self); + self.left = left; + result + } + + /// `body`'s rows, greyed and inert unless `enabled`; hovering them shows `reason` (which also names them for assistive tech). Inside a greyed part they grey no further + pub(crate) fn greyed(&mut self, enabled: bool, reason: Option<&str>, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let already_greyed = !self.ui.is_enabled(); + let top = self.cursor_y(); + let builder = UiBuilder::new().max_rect(self.ui.available_rect_before_wrap()).layout(*self.ui.layout()); + let mut child = self.ui.new_child(builder); + if !enabled && !already_greyed { + child.disable(); + child.multiply_opacity(GREYED_EXTRA_OPACITY); + } + + let mut sheet = PropertySheet { + tokens: self.tokens, + id: self.id, + scope: self.scope, + band_scope: self.band_scope, + named: std::mem::take(&mut self.named), + left: self.left, + right: self.right, + used: self.used, + seen: self.seen, + card: self.card.take(), + air_at: self.air_at, + drawn_bottom: self.drawn_bottom, + empty: self.empty, + sections: std::mem::take(&mut self.sections), + info: None, + held: self.held, + sub_headers: self.sub_headers, + ui: &mut child, + }; + let result = body(&mut sheet); + let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, .. } = sheet; + (self.named, self.seen, self.card, self.air_at, self.drawn_bottom, self.empty, self.sections) = + (named, seen, card, air_at, drawn_bottom, empty, sections); + (self.held, self.sub_headers, self.scope, self.band_scope) = (held, sub_headers, scope, band_scope); + + let bottom = child.min_rect().bottom().max(top); + let region = Rect::from_min_max(pos2(self.left, top), pos2(self.right, bottom)); + self.ui.advance_cursor_after_rect(Rect::from_min_max(pos2(child.min_rect().left(), top), pos2(child.min_rect().right(), bottom))); + if let (false, false, Some(reason)) = (enabled, already_greyed, reason) { + let response = self.ui.interact(region, self.id.with(("greyed", top as i32)), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, reason)); + + // At the pointer: the region is tall, so a tip at its edge would land far from what was hovered + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(egui::PopupAnchor::Pointer); + tooltip.show(|ui| ui.label(reason)); + } + result + } + + /// A label on its own line above its control + fn label_line(&mut self, label: &str) -> Rect { + let line = self.take(LABEL_LINE); + let text = self.tokens.text; + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), text); + line + } + + /// A full-width control's box under its label, and the air after it + fn control_line(&mut self) -> Rect { + let line = self.take(CONTROL_HEIGHT); + self.drawn(line.bottom()); + let rect = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + self.space(STACK_ROW_AIR); + rect + } + + /// A dropdown under its label; returns the picked option + pub(crate) fn dropdown_above(&mut self, label: &str, current: T, options: &[T], name: impl Fn(T) -> String) -> Option { + self.label_line(label); + let button = self.control_line(); + let response = self.dropdown_button(button, &name(current), None::); + named_choice(self.ui, &response, label, &name(current)); + self.hanging_list(&response, current, options, &name, None::>).0 + } + + /// Two dropdowns under one label with a link between them; while `linked` the second follows the first and shows greyed. Returns which one picked what + pub(crate) fn dropdown_pair_above( + &mut self, + label: &str, + values: [T; 2], + options: &[T], + name: impl Fn(T) -> String, + linked: &mut bool, + link_label: &str, + ) -> Option<(usize, T)> { + self.label_line(label); + let line = self.control_line(); + let half = (line.width() - PAIR_LINK_WIDTH - 2.0 * PAIR_LINK_AIR) / 2.0; + let first = Rect::from_min_size(line.min, vec2(half, CONTROL_HEIGHT)); + let link = Rect::from_min_size(pos2(first.right() + PAIR_LINK_AIR, line.top()), vec2(PAIR_LINK_WIDTH, CONTROL_HEIGHT)); + let second = Rect::from_min_max(pos2(link.right() + PAIR_LINK_AIR, line.top()), line.max); + + let first_response = self.dropdown_button(first, &name(values[0]), None::); + named_choice(self.ui, &first_response, label, &name(values[0])); + let mut picked = self.hanging_list(&first_response, values[0], options, &name, None::>).0.map(|value| (0, value)); + + let link_id = self.next_id(); + let link_response = self.ui.interact(link, link_id, Sense::click()); + let enabled = self.ui.is_enabled(); + link_response.widget_info(|| WidgetInfo::selected(egui::Role::CheckBox, enabled, *linked, link_label)); + let link_response = self.tip(link_response, link_label); + if link_response.clicked() { + *linked = !*linked; + } + let tokens = self.tokens; + + // Held down: the hairline grey, neutral in every accent (tool_active takes the accent's tint) + let fill = if *linked { + tokens.separator + } else if link_response.hovered() { + tokens.row_hover + } else { + tokens.button + }; + let painter = self.ui.painter(); + painter.rect(link, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + let glyph = if *linked { ic::LINK_SIMPLE_HORIZONTAL } else { ic::LINK_SIMPLE_HORIZONTAL_BREAK }; + painter.text(link.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&link_response); + + let follows = *linked; + let second_value = if follows { values[0] } else { values[1] }; + let mut second_ui = self.ui.new_child(UiBuilder::new().max_rect(second)); + if follows { + second_ui.disable(); + } + let mut second_sheet = PropertySheet { + tokens, + id: self.id, + scope: self.scope, + band_scope: self.band_scope, + named: Vec::new(), + left: second.left(), + right: second.right(), + used: self.used, + seen: self.seen, + card: None, + air_at: None, + drawn_bottom: self.drawn_bottom, + empty: false, + sections: Vec::new(), + info: None, + held: false, + sub_headers: 0, + ui: &mut second_ui, + }; + let second_response = second_sheet.dropdown_button(second, &name(second_value), None::); + named_choice(second_sheet.ui, &second_response, label, &name(second_value)); + if let Some(value) = second_sheet.hanging_list(&second_response, second_value, options, &name, None::>).0 { + picked = Some((1, value)); + } + picked + } + + /// A slider under its label, its value at the label line's right end; `Some(merge)` when `value` changed, `merge` true for a drag's later steps + pub(crate) fn slider_above(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + let line = self.label_line(label); + let id = self.named_id("slider_above", label); + let shown = shown_number(*value, decimals); + + // Fine-grained values read as the reference's do, without trailing zeros ("0.01", "1"); short ones keep their places ("0.50") + let shown = if decimals > SHORT_DECIMALS && shown.contains('.') { shown.trim_end_matches('0').trim_end_matches('.').to_owned() } else { shown }; + let width = self.text_width(&shown, semibold(TEXT_SIZE)).max(super::VALUE_MIN_WIDTH); + let value_text = ValueText { label: &label, right: self.right, width, center_y: line.top() + LABEL_CENTER, shown: &shown, suffix: "" }; + let typed = self.value_text_field(id, value_text, *value, &range, decimals); + + let track_line = self.take(TRACK_LINE); + let center_y = track_line.top() + TRACK_CENTER; + let track = Track { start: self.left + KNOB_RADIUS, end: self.right - KNOB_RADIUS, center_y, zero: (*range.start() < 0.0).then_some(0.0), ramp: false }; + let dragged = self.track(id, label, &track, value, &range); + self.drawn(center_y + KNOB_RADIUS); + self.space(STACK_ROW_AIR); + Self::apply_typed(value, typed, dragged) + } + + /// A check with its label after it; returns whether it was clicked (`on` already flipped) + pub(crate) fn check(&mut self, label: &str, on: &mut bool) -> bool { + let clicked = self.check_mixed(label, Some(*on)).clicked(); + if clicked { + *on = !*on; + } + clicked + } + + /// A check that may show mixed (`None`, a dash) for several states at once; the caller flips what it stands for on a click + pub(crate) fn check_mixed(&mut self, label: &str, state: Option) -> Response { + self.check_noted(label, state, None) + } + + /// `check_mixed` with a dim `note` at the row's right end, such as the values a set would give up + pub(crate) fn check_noted(&mut self, label: &str, state: Option, note: Option<&str>) -> Response { + let line = self.take(CHECK_LINE); + let center_y = line.center().y; + let text = self.ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), self.tokens.text); + let hit = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.left + CHECK_SIZE + CHECK_TO_LABEL + text.size().x, line.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| match state { + Some(on) => WidgetInfo::selected(egui::Role::CheckBox, enabled, on, label), + None => WidgetInfo::labeled(egui::Role::CheckBox, enabled, label), + }); + + let check = Rect::from_min_size(pos2(self.left, center_y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + paint_check(self.ui.painter(), &self.tokens, check, state, response.hovered()); + self.ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, self.tokens.text); + if let Some(note) = note { + self.ui.painter().text(pos2(self.right, center_y), Align2::RIGHT_CENTER, note, FontId::proportional(SMALL_TEXT_SIZE), self.tokens.text_dim); + } + self.paint_control_focus(&response); + self.drawn(line.bottom()); + self.space(STACK_ROW_AIR); + response + } + + /// A one-line text field under its label; returns whether `text` changed + pub(crate) fn text_field_above(&mut self, label: &str, text: &mut String) -> bool { + self.label_line(label); + let line = self.take(CONTROL_HEIGHT); + let field = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + let id = self.named_id("text_field_above", label); + let typing = self.ui.memory(|memory| memory.has_focus(id)); + let tokens = self.tokens; + let outline = Stroke::new(1.0, if typing { tokens.accent } else { tokens.field_border }); + self.ui.painter().rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, outline, StrokeKind::Inside); + let edit = egui::TextEdit::singleline(text) + .id(id) + .font(FontId::proportional(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET, 0))) + .align(Align2::LEFT_CENTER); + let response = self.ui.put(field.shrink(1.0), edit); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::TextInput, enabled, label)); + self.drawn(field.bottom()); + self.space(STACK_ROW_AIR); + response.changed() + } + + /// A full-width button with air above and twice below; `pressed` shows it held down (a toggle that is on) + pub(crate) fn wide_button(&mut self, glyph: &str, text: &str, pressed: bool) -> Response { + self.space(STACK_ROW_AIR); + let line = self.take(CONTROL_HEIGHT); + let button = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + let id = self.next_id(); + let response = self.ui.interact(button, id, Sense::click()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::selected(egui::Role::Button, enabled, pressed, text)); + + let tokens = self.tokens; + // Held down: the hairline grey, as the paired dropdowns' link + let fill = match (pressed, response.hovered()) { + (true, _) => tokens.separator, + (false, true) => tokens.row_hover, + (false, false) => tokens.button, + }; + let painter = self.ui.painter(); + painter.rect(button, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + let icon = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(WIDE_BUTTON_ICON_SIZE), tokens.text); + let words = painter.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text); + let x = button.center().x - (icon.size().x + WIDE_BUTTON_ICON_GAP + words.size().x) / 2.0; + let center_y = button.center().y; + painter.galley(pos2(x, center_y - icon.size().y / 2.0), icon.clone(), tokens.text); + painter.galley(pos2(x + icon.size().x + WIDE_BUTTON_ICON_GAP, center_y - words.size().y / 2.0), words, tokens.text); + self.paint_control_focus(&response); + self.drawn(button.bottom()); + self.space(2.0 * STACK_ROW_AIR); + response + } + + /// A dim line of its own, such as a map's "No Parameters" + pub(crate) fn dim_line(&mut self, text: &str) { + let line = self.take(LABEL_LINE); + let dim = self.tokens.text_dim; + let id = self.next_id(); + let response = self.ui.interact(line, id, Sense::hover()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, enabled, text)); + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, text, FontId::proportional(TEXT_SIZE), dim); + self.drawn(line.bottom()); + } +} + +/// A check's box in `rect`: on = dim fill and a tick in the panel's colour, mixed (`None`) = a dash, off = the row colour with a field's border +pub(crate) fn paint_check(painter: &egui::Painter, tokens: &crate::theme::Tokens, rect: Rect, state: Option, hovered: bool) { + if state == Some(false) { + let border = if hovered { tokens.button_border } else { tokens.field_border }; + painter.rect(rect, CornerRadius::same(CHECK_RADIUS), tokens.row, Stroke::new(1.0, border), StrokeKind::Inside); + return; + } + + let fill = if hovered { tokens.text } else { tokens.text_dim }; + painter.rect_filled(rect, CornerRadius::same(CHECK_RADIUS), fill); + if state.is_none() { + let y = rect.center().y; + painter.line_segment([pos2(rect.center().x - DASH_HALF, y), pos2(rect.center().x + DASH_HALF, y)], Stroke::new(DASH_WIDTH, tokens.panel)); + return; + } + let points = TICK_POINTS.map(|(x, y)| pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height())); + painter.line(points.to_vec(), Stroke::new(TICK_WIDTH, tokens.panel)); +} + +/// Names a dropdown for assistive tech by its setting (`label`), its value the choice it shows +fn named_choice(ui: &egui::Ui, response: &Response, label: &str, value: &str) { + ui.ctx().accesskit_node_builder(response.id, |node| { + node.set_label(label); + node.set_value(value); + }); +} diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 26e6d85a..2b8530ec 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -253,7 +253,7 @@ mod tests { assert!(!safe_to_close(h.state()), "unsaved changes"); h.state_mut().session.modified = false; - h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..c101e8e2 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -65,7 +65,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; let bake_painting = mode == crate::state::Mode::Baking && app.ui.bake_paint_brush.on - && !app.session.bake_meshes.high.is_empty() + && !app.session.doc.bake_meshes.high.is_empty() && app.session.doc.project.texture_sets.get(app.session.ts()).is_some_and(|texture_set| { let settings = &texture_set.bake; match app.ui.bake_paint_brush.target { @@ -1117,7 +1117,9 @@ fn bake_visualization(app: &TextureCraftApp) -> Option, Pick)>) } } -/// Bake mode: add high-definition meshes (or load the cage) with the native file dialog. The -/// meshes load on a later frame, when the dialog answers. +/// Bake mode: add high polys (they load on a worker) or load the cage with the native file dialog, once it answers #[cfg(not(target_arch = "wasm32"))] pub fn import_bake_mesh(app: &mut TextureCraftApp, _ctx: &egui::Context, cage: bool) { use crate::file_dialogs::{Bound, FileDialog}; let dialog = if cage { FileDialog::open() } else { FileDialog::open_many() }; app.ask_file(dialog.filter(tr("Meshes"), &MESH_EXTENSIONS), Bound::Project, move |app, paths| { - for p in paths { - let cmd = if cage { "bake.cage.set" } else { "bake.highPoly.add" }; - app.run(cmd, serde_json::json!({ "path": p.display().to_string() })); + let mut paths = paths.iter().map(|path| path.display().to_string()); + if !cage { + app.load_high_polys(paths); + } else if let Some(path) = paths.next() { + app.run("bake.cage.set", serde_json::json!({ "path": path })); } }); } @@ -507,8 +508,8 @@ mod tests { vec![("high.obj".into(), cage.clone(), Pick::HighPoly(old_project_id)), ("cage.obj".into(), cage, Pick::Cage(old_project_id))], ); - assert!(harness.state().session.bake_meshes.high.is_empty()); - assert!(harness.state().session.bake_meshes.cage.is_none()); + assert!(harness.state().session.doc.bake_meshes.high.is_empty()); + assert!(harness.state().session.doc.bake_meshes.cage.is_none()); assert!(!harness.state().session.modified); assert_eq!(harness.state().toasts.iter().filter(|toast| toast.error).count(), 2); @@ -521,8 +522,8 @@ mod tests { vec![("high.obj".into(), mesh.clone(), Pick::HighPoly(project_id)), ("cage.obj".into(), mesh, Pick::Cage(project_id))], ); - assert_eq!(harness.state().session.bake_meshes.high.len(), 1); - assert!(harness.state().session.bake_meshes.cage.is_some()); + assert_eq!(harness.state().session.doc.bake_meshes.high.len(), 1); + assert!(harness.state().session.doc.bake_meshes.cage.is_some()); } #[test] diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 1703abde..d0b0fcb7 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -130,6 +130,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { queue: Vec::new(), total: 1, mesh_id, + only: None, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), @@ -184,3 +185,22 @@ fn an_invalid_set_does_not_start_a_partial_bake_or_change_the_view() { assert_eq!(app.session.history_labels().len(), history_steps); assert!(app.toasts.iter().any(|toast| toast.error && toast.text.contains(&expected_error))); } + +#[test] +fn a_rows_quick_bake_bakes_that_map_alone_and_keeps_the_others() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + let before = harness.state().session.doc.baked[&0].maps.clone(); + + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([]); + harness.state_mut().start_bake_of(vec![0], Some(MAPS[1])); + assert_eq!(harness.state().session.view, ViewMode::MeshMap(MAPS[1]), "the preview shows the one map"); + run_to_the_end(&mut harness); + + let after = &harness.state().session.doc.baked[&0].maps; + assert_eq!(after.keys().collect::>(), before.keys().collect::>(), "the other maps stay"); + for map in MAPS { + assert_eq!(!std::sync::Arc::ptr_eq(&after[&map], &before[&map]), map == MAPS[1], "{map:?}"); + } +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 60f6f03e..b634a9c5 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -22,7 +22,7 @@ fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, Textu std::mem::forget(maps_tx); let running = RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; - h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); + h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id, only: None }); (h, progress) } diff --git a/crates/ui-egui/tests/it/bake_map_rows.rs b/crates/ui-egui/tests/it/bake_map_rows.rs new file mode 100644 index 00000000..ce17536c --- /dev/null +++ b/crates/ui-egui/tests/it/bake_map_rows.rs @@ -0,0 +1,70 @@ +//! The Mesh Map Bakers rows: a drag down the checkboxes gives each the state the first one took + +use egui::{Event, Modifiers, PointerButton, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::BakedMap; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// The rows the drag crosses, from the press to the release +const DRAGGED: [(BakedMap, &str); 3] = [(BakedMap::Normal, "Normal"), (BakedMap::WorldNormal, "World Space Normal"), (BakedMap::Id, "ID")]; + +/// A bake-mode app with Mesh Map Bakers in front and every map checked +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].bake.maps.select(BakedMap::ALL); + 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::MeshMapBakers); + harness.run_steps(3); + harness +} + +fn checkbox_center(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Pos2 { + harness.get_by_role_and_label(Role::CheckBox, name).rect().center() +} + +fn enabled(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let maps = &harness.state().session.doc.project.texture_sets[0].bake.maps; + BakedMap::ALL.into_iter().filter(|map| maps.is_enabled(*map)).collect() +} + +#[test] +fn a_drag_down_the_checkboxes_unchecks_every_row_it_crosses() { + let mut harness = harness(); + let [from, through, to] = DRAGGED.map(|(_, name)| checkbox_center(&harness, name)); + + 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 position in [through, to] { + harness.hover_at(position); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|map| DRAGGED.iter().all(|(dragged, _)| dragged != map)).collect(); + assert_eq!(enabled(&harness), expected, "the three rows are unchecked, the release does not check the last one again"); +} + +#[test] +fn a_click_on_one_checkbox_still_toggles_only_that_row() { + let mut harness = harness(); + let (map, name) = DRAGGED[1]; + let at = checkbox_center(&harness, name); + + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|other| *other != map).collect(); + assert_eq!(enabled(&harness), expected); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index b2603842..2339512d 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -1,6 +1,6 @@ use egui::Role; use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::kittest::{NodeT, Queryable, by}; use texturecraft_engine::core::{BakeResolution, BakeSettings, BakedMap, CageType, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -45,9 +45,14 @@ 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() +/// Type `text` as the value of the slider labelled `label`: a click on its value turns it into a field with the value selected +fn type_slider_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { + harness.get_by_role_and_label(Role::Label, &format!("{label} value")).click(); + harness.run_steps(2); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text(text.into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); } #[test] @@ -99,7 +104,7 @@ fn common_settings_edits_update_all_sets_and_keep_their_map_selection() { let mut expected = before.clone(); for texture_set in &mut expected.texture_sets { - texture_set.bake.common.apply_diffusion = false; + texture_set.bake.common.apply_diffusion = true; } assert_eq!(harness.state().session.doc.project, expected); @@ -129,14 +134,7 @@ fn secondary_rays_edit_from_another_set_updates_all_sets() { 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); + type_slider_value(&mut harness, "Secondary Rays", "128"); let session = &harness.state().session; assert_eq!(session.ts(), 1); @@ -333,12 +331,14 @@ fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() { 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.get_by_role_and_label(Role::Button, "Reset Common Settings").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; + // The section holds the High-Poly Parameters too, so its reset covers them + expected.texture_sets[1].bake.high_poly = Default::default(); let session = &mut harness.state_mut().session; assert_eq!(session.doc.project, expected); session.undo().unwrap(); @@ -385,10 +385,10 @@ fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_heig assert!(harness.query_by_label("Normalization").is_none()); 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()); + assert!(harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); click(&mut harness, "Normalization"); click(&mut harness, "Manual"); - harness.get_by_label("Scaling Divisor"); + assert!(!harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); click_checkbox(&mut harness, "Height"); @@ -396,7 +396,7 @@ fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_heig 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()); + assert!(harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); click_checkbox(&mut harness, "Height"); assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); } @@ -417,7 +417,8 @@ fn clicking_a_row_shows_that_maps_settings_without_changing_what_bakes() { assert!(harness.query_by_label("Attenuation").is_none()); assert_eq!(enabled_maps(&harness), before); - click(&mut harness, &format!("{} Common Settings", egui_phosphor::regular::GEAR)); + harness.get_by_role_and_label(Role::Button, "Common Settings").click(); + harness.run_steps(3); assert!(harness.state().ui.dock.is_visible(Panel::CommonSettings)); assert_eq!(enabled_maps(&harness), before); } @@ -437,9 +438,7 @@ fn the_breadcrumb_switches_the_shown_map() { 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.get_by_label("Switch Mesh Map").click(); harness.run_steps(3); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); @@ -452,19 +451,21 @@ fn the_breadcrumb_switches_the_shown_map() { } #[test] -fn curvature_controls_follow_the_method_and_notes_visibility_rules() { +fn curvature_controls_follow_the_method_and_grey_out_by_their_switches() { let mut harness = harness(Some(BakedMap::Curvature)); 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()); + for bound in ["Value Bounds Min", "Value Bounds Max"] { + assert!(harness.get_by_label(bound).accesskit_node().is_disabled(), "{bound} is greyed while tonemapping is automatic"); + } - click(&mut harness, "Auto Tonemapping"); - harness.get_by_label("Value Bounds Min"); - harness.get_by_label("Value Bounds Max"); + click(&mut harness, "Auto Tonemapping (per UV Tile)"); + for bound in ["Value Bounds Min", "Value Bounds Max"] { + assert!(!harness.get_by_label(bound).accesskit_node().is_disabled()); + } assert!(!curvature(&harness).mesh.auto_tonemapping); click(&mut harness, "Method"); @@ -473,9 +474,9 @@ fn curvature_controls_follow_the_method_and_notes_visibility_rules() { assert!(harness.query_by_label("Sampling Radius").is_none()); harness.get_by_label("Details"); - harness.get_by_label("Seams Intensity"); + assert!(!harness.get_by_label("Seams Intensity").accesskit_node().is_disabled()); click(&mut harness, "Enable Seams"); - assert!(harness.query_by_label("Seams Intensity").is_none()); + assert!(harness.get_by_label("Seams Intensity").accesskit_node().is_disabled()); } #[test] @@ -490,13 +491,12 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { } harness.get_by_label("The cage applies once a high poly mesh is loaded."); harness.get_by_label("Skew Correction applies once a high poly mesh is loaded."); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "nothing selected to remove"); 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); assert!(!harness.get_by_label("Max Frontal Distance").accesskit_node().is_disabled()); assert!(harness.query_by_label("The cage applies once a high poly mesh is loaded.").is_none()); - harness.get_by_label("Skew Correction"); + harness.get_by_role_and_label(Role::Button, "Reset Skew Correction"); harness.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; harness.run_steps(3); assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); @@ -505,12 +505,25 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { harness.run_steps(3); harness.get_by_label("Skew Correction is not available while the low poly mesh is used as the high poly mesh."); harness.get_by_label("The cage is not used while the low poly mesh is used as the high poly mesh."); - assert!(harness.get_by_label("Paint Cage").accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); + assert!(harness.get(by().label_contains("Paint Cage")).accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; (settings.cage.average_normals, settings.high_poly.use_low_as_high) = (true, false); harness.run_steps(3); assert!(!harness.get_by_label("Edge Protection").accesskit_node().is_disabled()); + click(&mut harness, "Cage Type"); + click(&mut harness, "Automatic (Experimental)"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::Automatic); + for distance_based_only in ["Max Frontal Distance", "Average Normals"] { + assert!(harness.query_by_label(distance_based_only).is_none(), "the automatic cage has no {distance_based_only}"); + } + assert!(harness.query(by().label_contains("Paint Cage")).is_none(), "the automatic cage is not painted"); + assert!( + harness.get_by_role_and_label(Role::CheckBox, "Matching Error").accesskit_node().is_disabled(), + "greyed with the automatic cage, as in the reference" + ); + harness.get_by_label("Skew Correction needs a distance-based cage: the automatic cage is fitted to the high poly as it is."); + 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); @@ -518,14 +531,20 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { assert!(harness.query_by_label("Max Frontal Distance").is_none()); assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); harness.get_by_label("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself."); + harness.get_by_label("Load Cage"); +} - 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)); - } +#[test] +fn output_sizes_run_from_32_to_8192_as_in_the_reference() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_value("64").next().unwrap().click(); + harness.run_steps(3); + for offered in ["32", "8192"] { + harness.get_by_label(offered); } + assert!(harness.query_by_label("16").is_none()); } #[test] @@ -535,7 +554,8 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { let session = &mut harness.state_mut().session; 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(); let mesh = session.mesh.clone(); - session.bake_meshes.cage = Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), bytes: Default::default(), mesh, base_color: Vec::new() }); + session.doc.bake_meshes.cage = + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); let settings = &mut session.doc.project.texture_sets[0].bake; (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); harness.run_steps(3); @@ -543,12 +563,15 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { assert!(harness.get_by_label("Load Cage").accesskit_node().is_disabled(), "the cage does not apply"); assert!(!harness.get_by_label("Remove Cage").accesskit_node().is_disabled()); click(&mut harness, "Remove Cage"); - assert!(harness.state().session.bake_meshes.cage.is_none()); + assert!(harness.state().session.doc.bake_meshes.cage.is_none()); } #[test] fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() { let mut harness = harness(None); + // Mesh Map Settings in front would show its map's preview instead of the material + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(2); assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode starts on the neutral material"); harness.get_by_value("Neutral Material").click(); harness.run_steps(3); @@ -582,14 +605,13 @@ fn the_high_poly_scene_is_a_list_with_add_and_remove() { harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); harness.get_by_label("Add High-Poly Meshes"); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "− waits for a selection"); + harness.get_by_label("Gunhigh.obj"); - harness.get_by_label("Gunhigh.obj").click(); - harness.run_steps(3); + // Each file's row has its own × harness.get_by_label("Remove").click(); harness.run_steps(3); - assert!(harness.state().session.bake_meshes.high.is_empty()); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled()); + assert!(harness.state().session.doc.bake_meshes.high.is_empty()); + assert!(harness.query_by_label("Remove").is_none()); } #[test] diff --git a/crates/ui-egui/tests/it/bake_presets.rs b/crates/ui-egui/tests/it/bake_presets.rs index 5adef4ea..2eeb3da2 100644 --- a/crates/ui-egui/tests/it/bake_presets.rs +++ b/crates/ui-egui/tests/it/bake_presets.rs @@ -56,6 +56,8 @@ fn a_saved_preset_loads_back_into_the_active_set_as_one_undo_step() { assert!(harness.state().ui.bake_preset_name.is_empty(), "the name field is cleared"); harness.state_mut().session.doc.project.texture_sets[0].bake.common.antialiasing = BakeAntialiasing::None; + // The sets share Common Settings at first, and a set sharing them takes what the active set loads + harness.state_mut().run("bake.sync", json!({ "group": "common", "ts": [0] })); let steps = harness.state().session.history_labels().len(); open_menu(&mut harness); click(&mut harness, "Final"); diff --git a/crates/ui-egui/tests/it/bake_reset_menus.rs b/crates/ui-egui/tests/it/bake_reset_menus.rs new file mode 100644 index 00000000..4c5c579c --- /dev/null +++ b/crates/ui-egui/tests/it/bake_reset_menus.rs @@ -0,0 +1,84 @@ +//! The Cage and Skew Correction ⟲ menus: reset the parameters, clear the paint strokes, or both + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakePaintTarget, BakeSettings}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// Bake mode with a high poly, Common Settings in front, a painted stroke on `target` and its section's settings changed +fn harness(target: BakePaintTarget) -> 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(); + 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::CommonSettings); + + let command = match target { + BakePaintTarget::Cage => "bake.cage.paint", + BakePaintTarget::Skew => "bake.skew.paint", + }; + harness.state_mut().run(command, json!({ "points": [[0.5, 0.5]] })); + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + (settings.cage.max_frontal, settings.skew.edge_distance) = (CHANGED_CAGE_DISTANCE, CHANGED_EDGE_DISTANCE); + harness.run_steps(3); + harness +} + +/// Values other than the defaults (0.01 and 0.15), inside their sliders' ranges +const CHANGED_CAGE_DISTANCE: f32 = 0.03; +const CHANGED_EDGE_DISTANCE: f32 = 0.5; + +/// Open `section`'s ⟲ menu and pick `item` +fn pick(harness: &mut Harness<'static, TextureCraftApp>, section: &str, item: &str) { + // The Baking Visualization panel has its own Cage section in the 3D view, right of Common Settings + let label = format!("Reset {section}"); + let buttons = harness.get_all_by_role_and_label(Role::Button, &label); + buttons.min_by(|first, second| first.rect().left().total_cmp(&second.rect().left())).unwrap().click(); + harness.run_steps(3); + harness.get_by_label(item).click(); + harness.run_steps(3); +} + +/// Whether the first set still has its `target` strokes, and whether its section's parameters are the defaults +fn state(harness: &Harness<'static, TextureCraftApp>, target: BakePaintTarget) -> (bool, bool) { + let session = &harness.state().session; + let settings = &session.doc.project.texture_sets[0].bake; + let defaults = BakeSettings::default(); + let painted = session.doc.bake_paint.contains_key(&(0, target)); + let reset = match target { + BakePaintTarget::Cage => settings.cage == defaults.cage, + BakePaintTarget::Skew => settings.skew == defaults.skew, + }; + (painted, reset) +} + +#[test] +fn each_cage_reset_item_resets_the_parameters_clears_the_strokes_or_both() { + let items = [("Reset Cage Parameters", (true, true)), ("Clear All Cage Paint Strokes", (false, false)), ("Reset and Clear All", (false, true))]; + for (item, expected) in items { + let mut harness = harness(BakePaintTarget::Cage); + assert_eq!(state(&harness, BakePaintTarget::Cage), (true, false), "painted, parameters changed"); + + pick(&mut harness, "Cage", item); + + assert_eq!(state(&harness, BakePaintTarget::Cage), expected, "{item}: (strokes kept, parameters reset)"); + } +} + +#[test] +fn each_skew_reset_item_resets_the_parameters_clears_the_strokes_or_both() { + let items = [("Reset Skew Correction Parameters", (true, true)), ("Clear All Skew Paint Strokes", (false, false)), ("Reset and Clear All", (false, true))]; + for (item, expected) in items { + let mut harness = harness(BakePaintTarget::Skew); + assert_eq!(state(&harness, BakePaintTarget::Skew), (true, false), "painted, parameters changed"); + + pick(&mut harness, "Skew Correction", item); + + assert_eq!(state(&harness, BakePaintTarget::Skew), expected, "{item}: (strokes kept, parameters reset)"); + } +} diff --git a/crates/ui-egui/tests/it/bake_sync.rs b/crates/ui-egui/tests/it/bake_sync.rs new file mode 100644 index 00000000..43661323 --- /dev/null +++ b/crates/ui-egui/tests/it/bake_sync.rs @@ -0,0 +1,111 @@ +//! Sharing bake settings between texture sets from the Mesh Map Bakers panel + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakeSyncGroup, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// A bake-mode app on the two-set sample with Mesh Map Bakers in front +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for set in &mut session.doc.project.texture_sets { + set.bake = Default::default(); + set.bake.common.resolution = BakeResolution::R64; + } + 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::MeshMapBakers); + harness.run_steps(3); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).click(); + harness.run_steps(3); +} + +fn second_name(harness: &Harness<'_, TextureCraftApp>) -> String { + harness.state().session.doc.project.texture_sets[1].name.clone() +} + +#[test] +fn the_common_settings_sync_dialog_takes_a_set_out_of_the_group() { + let mut harness = harness(); + click(&mut harness, "Synchronize Common Settings"); + harness.get_by_label("Common Settings Sync"); + harness.get_by_role_and_label(Role::CheckBox, "Deselect All"); + + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Select All"); + click(&mut harness, "OK"); + + let project = &harness.state().session.doc.project; + assert!(harness.query_by_label("Common Settings Sync").is_none()); + assert!(!project.texture_sets[1].bake.sync.common); + assert_eq!(project.bake_synced_sets(0, BakeSyncGroup::Common), [0]); + assert_eq!(project.bake_synced_sets(1, BakeSyncGroup::Map(BakedMap::Normal)), [0, 1], "map sync stays"); +} + +#[test] +fn cancel_leaves_the_group_as_it_was() { + let mut harness = harness(); + click(&mut harness, "Synchronize Common Settings"); + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + click(&mut harness, "Cancel"); + assert!(harness.state().session.doc.project.texture_sets[1].bake.sync.common); +} + +#[test] +fn common_settings_edits_reach_only_the_sets_sharing_them() { + let mut harness = harness(); + harness.state_mut().session.doc.project.texture_sets[1].bake.sync.common = false; + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Apply Diffusion").click(); + harness.run_steps(3); + + let sets = &harness.state().session.doc.project.texture_sets; + assert_ne!(sets[0].bake.common.apply_diffusion, sets[1].bake.common.apply_diffusion); +} + +#[test] +fn the_list_menu_applies_the_checked_maps_to_all_sets() { + let mut harness = harness(); + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal, BakedMap::Height]); + harness.run_steps(3); + click(&mut harness, "Mesh Map Bakers Menu"); + click(&mut harness, "Apply Checked to All Texture Sets"); + let enabled: Vec = harness.state().session.doc.project.texture_sets[1].bake.maps.enabled().collect(); + assert_eq!(enabled, [BakedMap::Normal, BakedMap::Height]); +} + +#[test] +fn a_rows_menu_checks_the_map_for_sets_picked_in_the_dialog() { + let mut harness = harness(); + for set in &mut harness.state_mut().session.doc.project.texture_sets { + set.bake.maps.select([]); + } + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Height").click_secondary(); + harness.run_steps(3); + click(&mut harness, "Check Height for More Texture Sets..."); + harness.get_by_label("Check Height for More Texture Sets"); + + let first = harness.state().session.doc.project.texture_sets[0].name.clone(); + assert!(harness.query_by_role_and_label(Role::CheckBox, &first).is_none(), "the active set is the source, not a target"); + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + click(&mut harness, "OK"); + + let sets = &harness.state().session.doc.project.texture_sets; + assert!(!sets[0].bake.maps.height.is_enabled && sets[1].bake.maps.height.is_enabled); +} diff --git a/crates/ui-egui/tests/it/high_poly_loading.rs b/crates/ui-egui/tests/it/high_poly_loading.rs new file mode 100644 index 00000000..4808c98c --- /dev/null +++ b/crates/ui-egui/tests/it/high_poly_loading.rs @@ -0,0 +1,97 @@ +//! Bake mode: high poly files load on a worker thread, and the list names them while they do + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// A triangle the importer accepts as a high poly +const TRIANGLE_OBJ: &str = "o Part_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"; +/// Longest the test waits for the worker +const LOAD_TIMEOUT: Duration = Duration::from_secs(60); + +/// A bake-mode app with Common Settings in front +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).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); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness +} + +fn high_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.bake_meshes.high.iter().map(|high| high.name.clone()).collect() +} + +fn run_until_loaded(harness: &mut Harness<'_, TextureCraftApp>) { + let started = Instant::now(); + while harness.state().high_poly_job.is_some() { + assert!(started.elapsed() < LOAD_TIMEOUT, "the high polys never finished loading"); + std::thread::sleep(Duration::from_millis(5)); + harness.run_steps(1); + } +} + +#[test] +fn picked_high_polys_load_in_the_background_and_each_is_an_undo_step() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-loading-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let paths: Vec = ["first.obj", "second.obj"].map(|name| folder.join(name).display().to_string()).into(); + for path in &paths { + std::fs::write(path, TRIANGLE_OBJ).unwrap(); + } + let missing = folder.join("missing.obj").display().to_string(); + + let mut harness = harness(); + let steps = harness.state().session.history_labels().len(); + harness.state_mut().load_high_polys([paths[0].clone(), missing, paths[1].clone()]); + assert!(high_names(&harness).is_empty(), "the call returns before a file is read"); + assert_eq!(harness.state().high_poly_job.as_ref().unwrap().file_names().collect::>(), ["first.obj", "missing.obj", "second.obj"]); + harness.run_steps(1); + harness.get_by_label("Loading second.obj..."); + + run_until_loaded(&mut harness); + harness.run_steps(2); + assert_eq!(high_names(&harness), ["first.obj", "second.obj"], "the unreadable file is skipped and the rest load in order"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2); + assert!(harness.state().toasts.iter().any(|toast| toast.text.contains("missing.obj")), "the unreadable file is reported"); + assert!(harness.query_by_label("Loading second.obj...").is_none()); + assert_eq!(harness.state().session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2); + + harness.state_mut().run("edit.undo", serde_json::Value::Null); + assert_eq!(high_names(&harness), ["first.obj"]); + let _ = std::fs::remove_dir_all(folder); +} + +#[test] +fn high_polys_still_loading_when_another_project_opens_are_not_added_to_it() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-moved-on-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("part.obj").display().to_string(); + std::fs::write(&path, TRIANGLE_OBJ).unwrap(); + + let mut harness = harness(); + harness.state_mut().load_high_polys([path.clone(), path]); + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + run_until_loaded(&mut harness); + + assert!(high_names(&harness).is_empty()); + assert!(harness.state().toasts.iter().any(|toast| toast.text.contains("not added"))); + let _ = std::fs::remove_dir_all(folder); +} + +#[test] +fn a_high_poly_that_finishes_after_the_list_changed_joins_the_list_as_it_is() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let file = |name: &str| texturecraft_engine::formats::MeshFile { name: name.into(), bytes: TRIANGLE_OBJ.as_bytes().to_vec(), warnings: Vec::new() }; + let load = texturecraft_engine::HighPolyLoad::prepare(&session.doc.bake_meshes, file("part.obj")).unwrap(); + + session.add_high_poly_bytes("part.obj", TRIANGLE_OBJ.as_bytes().to_vec()).unwrap(); + assert_eq!(session.apply_high_poly_load(load), "2_part.obj", "the name is made unique against the list of now"); + assert_eq!(session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2, "both meshes bake"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 831a009a..a99ef8bf 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -4,8 +4,11 @@ mod alpha_parameters; mod anchor_point; mod bake_job_mesh; +mod bake_map_rows; mod bake_mode; mod bake_presets; +mod bake_reset_menus; +mod bake_sync; mod brush_drag; mod brush_section_reset; mod camera_views; @@ -40,6 +43,7 @@ mod folder_properties; mod frame_selection; mod generator_panel; mod help_menu_664; +mod high_poly_loading; mod history_panel; mod import_resources; mod inactive_set_hint; diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index dd3b5d02..0c76f5ad 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -2,7 +2,7 @@ //! brush controls are in Common Settings. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{Queryable, by}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; @@ -26,7 +26,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { #[test] fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let mut h = harness(); - h.get_by_label("Skew Correction"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset Skew Correction"); assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on); // Off: a drag in the view paints nothing @@ -37,9 +37,9 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { assert!(h.state().session.doc.bake_paint.is_empty(), "the brush is off"); // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke - h.get_by_label("Paint Skew Correction").scroll_to_me(); + h.get(by().label_contains("Paint Skew Correction")).scroll_to_me(); h.run_steps(3); - h.get_by_label("Paint Skew Correction").click(); + h.get(by().label_contains("Paint Skew Correction")).click(); h.run_steps(3); assert!(h.state().ui.bake_paint_brush.on); h.get_by_label("Radius"); @@ -53,10 +53,10 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let painted = map.values.iter().filter(|v| **v > 0.5).count(); assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); - // Removing it from the panel clears the map - h.get_by_label("Remove Skew Correction").scroll_to_me(); + // The section's reset menu clears the map + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset Skew Correction").click(); h.run_steps(3); - h.get_by_label("Remove Skew Correction").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Clear All Skew Paint Strokes").click(); h.run_steps(3); assert!(h.state().session.doc.bake_paint.is_empty()); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..3e2696f5 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -441,7 +441,7 @@ fn window_snapshots() { save(&mut harness, &output_dir, "bake-curvature-mesh"); select_map(&mut harness, "Height"); save(&mut harness, &output_dir, "bake-height-manual"); - harness.state_mut().session.bake_meshes.high.clear(); + harness.state_mut().session.doc.bake_meshes.high.clear(); harness.state_mut().ui.mode = Mode::Painting; save(&mut harness, &output_dir, "painting-restored"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..11ce0f09 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -135,9 +135,18 @@ alone) and `alphaInvert` (swaps paint and no paint inside the stamp square). The procedural, library and imported alphas alike and are returned by `tool.brush` with the other values. The alpha's rotation is the brush `angle`. -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 mode applies an edit in Common Settings or Mesh Map Settings to the texture sets sharing that +group's settings: Common Settings, and each map's settings, are shared by any set of texture sets +(at first every set shares them). Each set keeps its own enabled mesh-map checkboxes and Include in +Bake flag. An edit reaches the sets sharing its group with only the fields it changed, so values +that differ elsewhere stay; Restore Defaults resets the whole parameter section across those sets. + +`bake.sync {group: "common" | , ts: [indices] | "all"}` makes exactly these sets share the +group from now on; sets joining take the settings the group shares. `bake.copy {what: "settings" | +"checked" | "check", map?, from?, ts}` copies once: every setting with which maps are checked (or +one map's settings), which maps are checked, or checks one map; settings also reach the sets sharing a group with a target, while +checkboxes stay per set. Each is one +undo step. `bake.settings` with `model` keeps each set's sync membership. `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 From 623bd9008d1c8d8cebd50af4c586b6030f7b1a69 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:41:50 +0000 Subject: [PATCH 122/153] Bake mode pass 2: map preview on the model while a map's settings show --- crates/engine/src/bake_preview.rs | 2 +- .../src/bake_mode/bake_visualization_panel.rs | 60 +++- .../bake_mode/bake_visualization_toggles.rs | 14 + crates/ui-egui/src/bake_mode/live_preview.rs | 325 ++++++++++++++++++ .../src/bake_mode/live_preview_target.rs | 8 + .../ui-egui/src/bake_mode/map_preview_fold.rs | 69 ++++ crates/ui-egui/src/bake_mode/mod.rs | 25 +- crates/ui-egui/src/bake_mode/preview_input.rs | 19 + .../ui-egui/src/bake_mode/running_preview.rs | 18 + crates/ui-egui/src/lib.rs | 13 +- crates/ui-egui/tests/it/bake_live_preview.rs | 168 +++++++++ crates/ui-egui/tests/it/main.rs | 1 + 12 files changed, 709 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/bake_mode/live_preview.rs create mode 100644 crates/ui-egui/src/bake_mode/live_preview_target.rs create mode 100644 crates/ui-egui/src/bake_mode/map_preview_fold.rs create mode 100644 crates/ui-egui/src/bake_mode/preview_input.rs create mode 100644 crates/ui-egui/src/bake_mode/running_preview.rs create mode 100644 crates/ui-egui/tests/it/bake_live_preview.rs diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 4898ae1a..6886535d 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Bake preview", [], None, - "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)", + "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. In Bake mode the app's map preview also shows here while Mesh Map Settings is in front. With neither {active: false} (setting `show` is then an error)", always, preview )] diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs index 5c4d02cc..4907928f 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -1,9 +1,11 @@ use egui::collapsing_header::CollapsingState; use egui::{Rect, Ui, vec2}; use egui_phosphor::regular as icon; +use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_render::BakeOverlay; use super::BakeVisualizationToggles; +use super::map_preview_fold::MapPreviewFold; use super::section_opening::SectionOpening; use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; @@ -25,6 +27,10 @@ const ROW_BUTTON_SIZE: f32 = 18.0; /// Width of an overlay's color swatch const SWATCH_WIDTH: f32 = 44.0; +/// The map preview's sizes and how the list names them +const PREVIEW_SIZES: [(BakeResolution, &str); 4] = + [(BakeResolution::R128, "128"), (BakeResolution::R256, "256"), (BakeResolution::R512, "512"), (BakeResolution::R1024, "1K")]; + /// The neutral material's quality steps: samples per pixel and their names const QUALITIES: [(u32, &str); 6] = [ (4, n_("Very Low (4 spp)")), @@ -37,6 +43,8 @@ const QUALITIES: [(u32, &str); 6] = [ /// 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 matching_error_applies = super::matching_error_applies(&app.session); + let (shown, selected) = (app.live_preview.shown(), super::live_preview::map_settings_shown(app).map(|target| target.map)); let toggles = &mut app.ui.bake_visualization; let tokens = Tokens::get(ui.ctx()); egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( @@ -52,14 +60,14 @@ pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: collapsing_state.toggle(ui); } - collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles)); + collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles, matching_error_applies, shown, selected)); }); }, ); } -/// The panel's sections below its header -fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { +/// The panel's sections below its header; the Matching Error row greys unless `matching_error_applies` +fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, matching_error_applies: bool, shown: Option, selected: Option) { ui.horizontal(|ui| { ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -72,7 +80,7 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { let meshes_editable = !toggles.hide_baking_meshes; if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| { overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh); - overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error); + ui.add_enabled_ui(matching_error_applies, |ui| overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error)); }) { toggles.reset_high_poly(); } @@ -100,6 +108,42 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { }) { toggles.reset_project_mesh(); } + + map_preview_section(ui, toggles, shown, selected); +} + +/// The Map Preview section: whether the selected map shows on the model, and the size it bakes at; it opens by itself while a preview shows +fn map_preview_section(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, shown: Option, selected: Option) { + let fold_id = ui.make_persistent_id("map_preview_fold"); + let mut fold: MapPreviewFold = ui.ctx().data(|data| data.get_temp(fold_id)).unwrap_or_default(); + let section = section_id(ui, "map_preview"); + let mut state = CollapsingState::load_with_default_open(ui.ctx(), section, false); + if let Some(open) = fold.follow(shown, selected, !toggles.map_preview) { + state.set_open(open); + state.store(ui.ctx()); + } + let open_before = state.is_open(); + + let reset = collapsible(ui, "map_preview", tr("Map Preview"), SectionOpening::Closed, true, true, |ui| { + ui.checkbox(&mut toggles.map_preview, tr("Preview the Selected Map")); + ui.add_enabled_ui(toggles.map_preview, |ui| { + let size = &mut toggles.map_preview_size; + let selected = PREVIEW_SIZES.iter().find(|(option, _)| option == size).map_or("", |(_, name)| *name); + combo(ui, tr("Resolution"), selected, |ui| { + for (option, name) in PREVIEW_SIZES { + ui.selectable_value(size, option, name); + } + }); + }); + }); + let open_after = CollapsingState::load_with_default_open(ui.ctx(), section, false).is_open(); + if open_after != open_before { + fold.toggled(open_after); + } + ui.ctx().data_mut(|data| data.insert_temp(fold_id, fold)); + if reset { + toggles.reset_map_preview(); + } } /// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal @@ -126,8 +170,7 @@ fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { /// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); - let mut collapsing_state = - CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), section_id(ui, id), opening == SectionOpening::Open); let (header, reset) = ui .horizontal(|ui| { ui.set_min_height(EYE_BUTTON_SIZE); @@ -157,6 +200,11 @@ fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, rese reset.is_some_and(|reset| reset.clicked()) } +/// The id a section keeps its open state under +fn section_id(ui: &Ui, id: &str) -> egui::Id { + ui.make_persistent_id(("baking_visualization_section", id)) +} + /// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs index bb99e09b..d638da81 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use texturecraft_engine::core::BakeResolution; use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial}; /// Opacity of the cage's surface and wireframe until changed @@ -20,6 +21,10 @@ pub struct BakeVisualizationToggles { /// Show the project mesh with [`Self::neutral`] instead of its painted material pub neutral_shown: bool, pub neutral: NeutralMaterial, + /// Show the selected map on the model while Mesh Map Settings shows its settings + pub map_preview: bool, + /// The size the map preview bakes at once a change settles + pub map_preview_size: BakeResolution, } impl Default for BakeVisualizationToggles { @@ -37,6 +42,9 @@ impl Default for BakeVisualizationToggles { project_mesh: shown(parts.low_poly), neutral_shown: true, neutral: NeutralMaterial::default(), + // Web builds bake on the UI thread, so the preview there is opt-in + map_preview: !cfg!(target_arch = "wasm32"), + map_preview_size: BakeResolution::R256, } } } @@ -85,6 +93,12 @@ impl BakeVisualizationToggles { self.missing_seams = Self::default().missing_seams; } + /// Put the Map Preview section back to its defaults + pub fn reset_map_preview(&mut self) { + let defaults = Self::default(); + (self.map_preview, self.map_preview_size) = (defaults.map_preview, defaults.map_preview_size); + } + /// Put the Project Mesh section back to its defaults pub fn reset_project_mesh(&mut self) { let defaults = Self::default(); diff --git a/crates/ui-egui/src/bake_mode/live_preview.rs b/crates/ui-egui/src/bake_mode/live_preview.rs new file mode 100644 index 00000000..4c358962 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/live_preview.rs @@ -0,0 +1,325 @@ +//! The map preview: while Mesh Map Settings shows a map's settings, the 3D view shows that map on the model, re-baked small on a worker as the settings change + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::sync::mpsc::TryRecvError; + +use texturecraft_engine::StreamedMap; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeResolution, BakedMap}; + +use super::live_preview_target::LivePreviewTarget; +use super::preview_input::PreviewInput; +use super::running_preview::RunningPreview; +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::state::Mode; + +/// Sizes a dragged slider's previews step through, smallest first +const DRAG_SIZES: [BakeResolution; 5] = [BakeResolution::R64, BakeResolution::R128, BakeResolution::R256, BakeResolution::R512, BakeResolution::R1024]; + +/// A drag preview this quick bakes one size up next time +const DRAG_STEP_UP_SECONDS: f64 = 0.07; + +/// A drag preview this slow bakes one size down next time +const DRAG_STEP_DOWN_SECONDS: f64 = 0.14; + +/// How often the view looks for a finished preview: about one frame at 60 Hz, so it shows at once +const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16); + +/// The map preview's state: what it shows, what its picture was made from (and the session revision and size it was last checked at), the bake running for it, the drag change waiting for it, whether a drag still needs the full-size bake, whether its last bake could not start, and each map's drag size on this machine +#[derive(Default)] +pub(crate) struct LivePreview { + shown: Option, + made_from: Option, + checked_at: Option<(u64, BakeResolution)>, + cannot_bake: bool, + running: Option, + drag_waiting: bool, + refine_on_release: bool, + drag_sizes: BTreeMap, +} + +impl LivePreview { + /// The map the preview shows now, if any + pub(crate) fn shown(&self) -> Option { + self.shown.map(|target| target.map) + } + + /// Stop the preview and give the 3D view back; a real bake calls this before it takes the view + pub(crate) fn release(&mut self, session: &mut texturecraft_engine::Session) { + self.cancel(); + self.refine_on_release = false; + self.made_from = None; + self.checked_at = None; + self.cannot_bake = false; + if self.shown.take().is_some() { + session.bake_preview_end(); + } + } + + fn cancel(&mut self) { + self.drag_waiting = false; + if let Some(running) = self.running.take() { + running.progress.cancel.store(true, Ordering::Relaxed); + } + } + + /// The size `map` bakes at while a slider drags: it starts small, follows how fast this machine bakes it, and never passes `chosen` + fn drag_size(&self, map: BakedMap, chosen: BakeResolution) -> BakeResolution { + let learned = self.drag_sizes.get(&map).copied().unwrap_or_else(|| first_drag_size(map)); + if learned.pixels() > chosen.pixels() { chosen } else { learned } + } + + /// A drag preview of `map` at `size` took `seconds`: step its drag size up or down one size, never past `chosen` + fn learn_drag_size(&mut self, map: BakedMap, size: BakeResolution, seconds: f64, chosen: BakeResolution) { + let Some(index) = DRAG_SIZES.iter().position(|step| *step == size) else { return }; + + let next = if seconds < DRAG_STEP_UP_SECONDS { + DRAG_SIZES.get(index + 1).copied().filter(|bigger| bigger.pixels() <= chosen.pixels()).unwrap_or(size) + } else if seconds > DRAG_STEP_DOWN_SECONDS { + index.checked_sub(1).and_then(|smaller| DRAG_SIZES.get(smaller).copied()).unwrap_or(size) + } else { + size + }; + self.drag_sizes.insert(map, next); + } +} + +/// The texture set and the map whose settings a Mesh Map Settings panel in front shows, in Bake mode +pub(crate) fn map_settings_shown(app: &TextureCraftApp) -> Option { + let set = app.session.ts(); + let settings = &app.session.doc.project.texture_sets.get(set)?.bake; + let shows = app.ui.mode == Mode::Baking && app.ui.dock.is_visible(Panel::MeshMapSettings); + shows.then(|| LivePreviewTarget { set, map: super::selected_map(app.ui.selected_baked_map, settings) }) +} + +/// What the preview should show: the map whose settings show, while the preview is on and no real bake runs +fn wanted(app: &TextureCraftApp) -> Option { + map_settings_shown(app).filter(|_| app.ui.bake_visualization.map_preview && app.bake.is_none()) +} + +/// A slider dragged in Mesh Map Settings changed a setting: a running drag bake finishes and shows before the newest value bakes, so pictures keep coming while the slider moves +pub(crate) fn slider_dragged(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(target) = app.live_preview.shown else { return }; + + app.live_preview.refine_on_release = true; + + // Web builds bake on the UI thread, so they wait for the release; a set that can't bake waits too + if cfg!(target_arch = "wasm32") || app.live_preview.cannot_bake { + return; + } + + if app.live_preview.running.as_ref().is_some_and(|running| running.dragging) { + app.live_preview.drag_waiting = true; + } else { + let size = app.live_preview.drag_size(target.map, app.ui.bake_visualization.map_preview_size); + start(app, ctx, target, size, true); + } +} + +/// Once a frame: follow what the preview should show, bake again when its picture is out of date, and take a finished bake +pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + // A new session (a project opened, the mesh replaced) has no preview layer: start over + if app.live_preview.shown.is_some() && !app.session.bake_preview_active() { + app.live_preview.release(&mut app.session); + } + + let wanted = wanted(app); + if wanted != app.live_preview.shown { + app.live_preview.release(&mut app.session); + if let Some(target) = wanted { + show(app, ctx, target); + } + } + + // After a drag, and whenever what the picture was made from changes (undo, a synced set, automation, the chosen size, the meshes) + if let Some(target) = app.live_preview.shown { + let released = app.live_preview.refine_on_release && ctx.dragged_id().is_none(); + let chosen = app.ui.bake_visualization.map_preview_size; + + // Only after an edit or a new size: comparing the inputs copies the settings + let check = (app.session.revision, chosen); + let unchecked = app.live_preview.checked_at != Some(check); + let out_of_date = unchecked && !app.live_preview.refine_on_release && app.live_preview.made_from != input(app, target, chosen); + if unchecked && !app.live_preview.refine_on_release { + app.live_preview.checked_at = Some(check); + } + if released || out_of_date { + app.live_preview.refine_on_release = false; + start(app, ctx, target, chosen, false); + } + } + + take_finished(app, ctx); +} + +/// Show a finished preview bake, learn the drag size from it, and start the drag change that waited for it; a failed one goes to the Log +fn take_finished(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(running) = &app.live_preview.running else { return }; + + ctx.request_repaint_after(POLL_INTERVAL); + let finished = match running.receiver.try_recv() { + Err(TryRecvError::Empty) => return, + Ok(finished) => finished, + Err(TryRecvError::Disconnected) => Err(texturecraft_engine::EngineError::Other(tr("The map preview worker stopped").into())), + }; + let Some(running) = app.live_preview.running.take() else { return }; + + // A failure keeps the old picture and says why + let mut output = match finished { + Ok(output) => output, + Err(error) => { + let map = tr(baked_map_label(running.target.map)); + app.session.log.warn("Baker", trf("The {map} preview failed: {error}", &[("map", &map), ("error", &error.to_string())])); + app.live_preview.drag_waiting = false; + return; + } + }; + + if running.dragging { + let seconds = ctx.input(|input| input.time) - running.started; + app.live_preview.learn_drag_size(running.target.map, running.size, seconds, app.ui.bake_visualization.map_preview_size); + } + if let Some(data) = output.maps.remove(&running.target.map) { + let streamed = StreamedMap { map: running.target.map, index: 0, total: 1, resolution: output.resolution, height: output.height, data: Arc::new(data) }; + app.session.bake_preview_map(running.target.set, streamed); + } + + // The newest drag change waited for this picture + if std::mem::take(&mut app.live_preview.drag_waiting) && app.live_preview.refine_on_release { + let size = app.live_preview.drag_size(running.target.map, app.ui.bake_visualization.map_preview_size); + start(app, ctx, running.target, size, true); + } +} + +/// Start showing `target`: the map's last real bake at once when there is one (it may predate the settings), then a preview bake at the chosen size +fn show(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget) { + app.session.bake_preview_begin(vec![(target.set, vec![target.map])]); + app.live_preview.shown = Some(target); + + let baked = app.session.baked(target.set).and_then(|baked| baked.maps.get(&target.map).map(|data| (baked.resolution, data.clone()))); + if let Some((resolution, data)) = baked { + let height = (data.len() / target.map.components()).checked_div(resolution as usize).unwrap_or(0) as u32; + app.session.bake_preview_map(target.set, StreamedMap { map: target.map, index: 0, total: 1, resolution, height, data }); + } + start(app, ctx, target, app.ui.bake_visualization.map_preview_size, false); +} + +/// What a preview of `target` at `size` would be made from now +fn input(app: &TextureCraftApp, target: LivePreviewTarget, size: BakeResolution) -> Option { + let set = app.session.doc.project.texture_sets.get(target.set)?; + let meshes = &app.session.doc.bake_meshes; + let painted = app.session.doc.bake_paint.iter().filter(|((index, _), _)| *index == target.set).map(|(_, map)| Arc::as_ptr(map) as usize).collect(); + + Some(PreviewInput { + settings: set.bake.clone(), + mesh_id: app.session.mesh_id, + uv_tiles: set.uv_tiles.clone(), + excluded_tiles: set.bake_excluded_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + high_polys: meshes.high.iter().map(|mesh| Arc::as_ptr(&mesh.mesh) as usize).collect(), + cage: meshes.cage.as_ref().map(|cage| Arc::as_ptr(&cage.mesh) as usize), + painted, + size, + }) +} + +/// Bake `target`'s map alone at `size` on the preview pool (`dragging`: for a slider still moving), cancelling the preview bake still running +fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget, size: BakeResolution, dragging: bool) { + app.live_preview.cancel(); + app.live_preview.made_from = input(app, target, size); + let mut task = match app.session.bake_task(target.set) { + Ok(task) => task, + Err(error) => { + // Once, not on every change while it stays unbakeable + if !app.live_preview.cannot_bake { + let map = tr(baked_map_label(target.map)); + app.session.log.warn("Baker", trf("The {map} preview can't bake: {error}", &[("map", &map), ("error", &error.to_string())])); + } + app.live_preview.cannot_bake = true; + return; + } + }; + app.live_preview.cannot_bake = false; + + task.settings.maps.select([target.map]); + let own = task.settings.common.resolution; + let size = if own.pixels() < size.pixels() { own } else { size }; + task.settings.common.resolution = size; + task.settings.common.resolution_height = None; + + let progress = Arc::new(Progress::new()); + let worker_progress = progress.clone(); + + // Queued on the preview pool's own threads: starting a new thread per change can stall the UI while a bake allocates + let receiver = match preview_pool() { + Some(pool) => { + let (sender, receiver) = std::sync::mpsc::channel(); + pool.spawn(move || { + let _ = sender.send(task.run(&worker_progress)); + }); + receiver + } + None => crate::spawn_worker("texturecraft-map-preview", move || task.run(&worker_progress)), + }; + let started = ctx.input(|input| input.time); + app.live_preview.running = Some(RunningPreview { target, size, started, dragging, progress, receiver }); +} + +/// A dragged slider's first preview size before this machine's speed is known: 64 for the ray-traced bakers (well over 100 ms at 128 on a 4-core machine), else 128 +fn first_drag_size(map: BakedMap) -> BakeResolution { + match map { + BakedMap::AmbientOcclusion | BakedMap::Thickness | BakedMap::BentNormal | BakedMap::Curvature => BakeResolution::R64, + _ => BakeResolution::R128, + } +} + +/// The preview bakes' own thread pool, a thread short of the cores, so the UI's parallel work never waits behind a preview; None where no pool can start +#[cfg(not(target_arch = "wasm32"))] +fn preview_pool() -> Option<&'static rayon::ThreadPool> { + static POOL: std::sync::OnceLock> = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::thread::available_parallelism().map_or(1, |cores| cores.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|index| format!("texturecraft-map-preview-{index}")).build(); + if let Err(error) = &pool { + log::warn!("map previews share the global thread pool: {error}"); + } + pool.ok() + }) + .as_ref() +} + +/// Web builds have no threads: the preview bakes on the UI thread +#[cfg(target_arch = "wasm32")] +fn preview_pool() -> Option<&'static rayon::ThreadPool> { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_drag_size_steps_up_while_fast_down_while_slow_and_never_past_the_chosen_size() { + let mut preview = LivePreview::default(); + let map = BakedMap::AmbientOcclusion; + let largest = BakeResolution::R1024; + let start = preview.drag_size(map, largest); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest); + let bigger = preview.drag_size(map, largest); + assert!(bigger.pixels() > start.pixels(), "a quick bake steps up"); + + preview.learn_drag_size(map, bigger, DRAG_STEP_DOWN_SECONDS * 2.0, largest); + assert_eq!(preview.drag_size(map, largest), start, "a slow bake steps back down"); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, start); + assert_eq!(preview.drag_size(map, largest), start, "never steps past the chosen size"); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest); + assert_eq!(preview.drag_size(map, start), start, "a smaller chosen size caps what was learned"); + } +} diff --git a/crates/ui-egui/src/bake_mode/live_preview_target.rs b/crates/ui-egui/src/bake_mode/live_preview_target.rs new file mode 100644 index 00000000..17e88085 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/live_preview_target.rs @@ -0,0 +1,8 @@ +use texturecraft_engine::core::BakedMap; + +/// One map of one texture set, as the map preview shows it +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct LivePreviewTarget { + pub(crate) set: usize, + pub(crate) map: BakedMap, +} diff --git a/crates/ui-egui/src/bake_mode/map_preview_fold.rs b/crates/ui-egui/src/bake_mode/map_preview_fold.rs new file mode 100644 index 00000000..04fa8732 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_preview_fold.rs @@ -0,0 +1,69 @@ +use texturecraft_engine::core::BakedMap; + +/// The Map Preview section's fold: it opens while a preview shows and folds when the preview goes away; folded by hand on a map, it stays folded until another map is picked +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct MapPreviewFold { + /// The map the preview showed last frame + pub(super) shown: Option, + /// The map the user folded the section on while its preview showed + pub(super) folded_for: Option, +} + +impl MapPreviewFold { + /// Whether the section should open (Some(true)) or fold (Some(false)) this frame, or stay as it is; `selected` is the map whose settings show, `switched_off` whether the preview is turned off + pub(super) fn follow(&mut self, shown: Option, selected: Option, switched_off: bool) -> Option { + // Only another map ends it; no map at all (Common Settings in front) keeps it + if selected.is_some() && selected != self.folded_for { + self.folded_for = None; + } + if shown == self.shown { + return None; + } + + self.shown = shown; + match shown { + Some(map) => (self.folded_for != Some(map)).then_some(true), + // Turning the preview off from inside the section leaves it open until the user moves on + None => (!(switched_off && selected.is_some())).then_some(false), + } + } + + /// The user folded or opened the section by hand + pub(super) fn toggled(&mut self, open: bool) { + self.folded_for = if open { None } else { self.shown }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_section_opens_with_a_preview_and_folds_when_it_goes() { + let mut fold = MapPreviewFold::default(); + + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), Some(true)); + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "no change, no move"); + assert_eq!(fold.follow(None, None, false), Some(false)); + } + + #[test] + fn folded_by_hand_it_stays_folded_until_another_map_is_picked() { + let mut fold = MapPreviewFold::default(); + fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false); + + fold.toggled(false); + fold.follow(None, None, false); + + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "same map: stays folded"); + assert_eq!(fold.follow(Some(BakedMap::Curvature), Some(BakedMap::Curvature), false), Some(true)); + } + + #[test] + fn switching_the_preview_off_leaves_the_section_open() { + let mut fold = MapPreviewFold::default(); + fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false); + + assert_eq!(fold.follow(None, Some(BakedMap::AmbientOcclusion), true), None); + } +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index a4bf439f..4c3d0e61 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -7,6 +7,12 @@ mod bake_visualization_toggles; mod breadcrumb; mod common_settings; mod glyph_look; +mod live_preview; +mod live_preview_target; +mod map_preview_fold; +mod preview_input; +mod running_preview; +pub(crate) use live_preview::LivePreview; mod section_opening; pub(crate) use bake_checks::bake_warnings; pub use bake_paint_brush::BakePaintBrush; @@ -178,9 +184,19 @@ pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { .inner }); let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Map(selected))); - edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| { + let changed = edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| { PropertySheet::show(ui, ("mesh_map_settings_sheet", selected), |sheet| map_settings::show(sheet, selected, &mut settings.maps, restore.inner)) }); + // Other changes reach the preview through its check of what its picture was made from + if changed && ui.ctx().dragged_id().is_some() { + let ctx = ui.ctx().clone(); + live_preview::slider_dragged(app, &ctx); + } +} + +/// Once a frame: the map preview follows the selected map and takes its finished bakes +pub(crate) fn poll_live_preview(app: &mut TextureCraftApp, ctx: &egui::Context) { + live_preview::poll(app, ctx); } /// The Common Settings panel: output, high poly, cage and skew settings @@ -203,14 +219,14 @@ fn edit_settings( scroll_id: &str, texture_sets: Value, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option, -) { +) -> bool { 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 Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return false }; 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; + return false; } let mut patch = settings_patch(&before, &settings); @@ -218,6 +234,7 @@ fn edit_settings( fields.extend(reset); } app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); + true } /// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material diff --git a/crates/ui-egui/src/bake_mode/preview_input.rs b/crates/ui-egui/src/bake_mode/preview_input.rs new file mode 100644 index 00000000..08b8a704 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/preview_input.rs @@ -0,0 +1,19 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_engine::core::{BakeResolution, BakeSettings}; + +/// What a map preview picture is made from, everything its bake reads: when any of it changes, the picture is out of date +#[derive(Clone, Debug, PartialEq)] +pub(super) struct PreviewInput { + pub(super) settings: BakeSettings, + pub(super) mesh_id: u64, + /// The set's UV tiles, the ones left out of the bake, and their resolutions + pub(super) uv_tiles: Vec, + pub(super) excluded_tiles: BTreeSet, + pub(super) tile_resolutions: BTreeMap, + /// The high polys', the cage's and the set's painted maps' shared buffers: a file loaded again under the same name is another buffer + pub(super) high_polys: Vec, + pub(super) cage: Option, + pub(super) painted: Vec, + pub(super) size: BakeResolution, +} diff --git a/crates/ui-egui/src/bake_mode/running_preview.rs b/crates/ui-egui/src/bake_mode/running_preview.rs new file mode 100644 index 00000000..38064540 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/running_preview.rs @@ -0,0 +1,18 @@ +use std::sync::Arc; +use std::sync::mpsc::Receiver; + +use texturecraft_engine::Result; +use texturecraft_engine::bake::{BakeOutput, Progress}; +use texturecraft_engine::core::BakeResolution; + +use super::live_preview_target::LivePreviewTarget; + +/// A map preview bake on its worker: its size, when it started (app time) and whether a dragged slider asked for it +pub(super) struct RunningPreview { + pub(super) target: LivePreviewTarget, + pub(super) size: BakeResolution, + pub(super) started: f64, + pub(super) dragging: bool, + pub(super) progress: Arc, + pub(super) receiver: Receiver>, +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a24b9d6d..c1dcf34e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -276,6 +276,8 @@ pub struct TextureCraftApp { pub layer_panel: layer_panel::LayerPanel, /// The Mesh Map Bakers rows' thumbnails pub(crate) bake_map_thumbnails: bake_mode::MapThumbnails, + /// The map preview: the selected map on the model while Mesh Map Settings shows it + pub(crate) live_preview: bake_mode::LivePreview, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -418,6 +420,7 @@ impl TextureCraftApp { thumbs: thumbs::Thumbs::default(), layer_panel: layer_panel::LayerPanel::default(), bake_map_thumbnails: bake_mode::MapThumbnails::default(), + live_preview: bake_mode::LivePreview::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, @@ -618,6 +621,9 @@ impl TextureCraftApp { return; } + // The bake takes the 3D view over from the map preview + self.live_preview.release(&mut self.session); + // Restore the picker's view before the preview starts following baked maps id_color_pick::IdColorPick::end(self); @@ -738,8 +744,10 @@ impl TextureCraftApp { } let Some(job) = self.bake.as_mut() else { - // A preview whose bake is gone must not keep the view - self.session.bake_preview_end(); + // A preview whose bake is gone must not keep the view; the map preview keeps its own + if self.live_preview.shown().is_none() { + self.session.bake_preview_end(); + } return; }; @@ -1131,6 +1139,7 @@ impl eframe::App for TextureCraftApp { } } self.poll_bake(ctx); + bake_mode::poll_live_preview(self, ctx); self.poll_resize(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_high_poly_job(ctx); diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs new file mode 100644 index 00000000..5944e3ce --- /dev/null +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -0,0 +1,168 @@ +//! The map preview: the selected map's settings show it on the model, small while a slider is dragged + +use egui::{Event, Modifiers, PointerButton, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// How long a steady drag may take to bring its first new pictures, on a slow machine +const MOVING_DRAG_LIMIT: std::time::Duration = std::time::Duration::from_secs(20); + +/// Bake mode on the sample with Ambient Occlusion's settings in front +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].bake = Default::default(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R1024; + // No earlier bake to start the preview from: its first picture is a preview bake at the chosen size + session.doc.baked.clear(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R256; + harness.run_steps(4); + harness.get(egui_kittest::kittest::by().role(Role::Button).label("Ambient Occlusion")).click(); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); + harness.run_steps(3); + harness +} + +/// The size of the picture the preview shows for the first set, once it is `wanted` (the worker gets a few seconds) +fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option { + for _ in 0..600 { + harness.run_steps(1); + let shown = + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution)); + if shown.is_some_and(&wanted) { + return shown; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + None +} + +#[test] +fn the_selected_map_shows_on_the_model_and_common_settings_hide_it_at_once() { + let mut harness = harness(); + + let shown = wait_for_preview(&mut harness, |_| true); + assert!(shown.is_some(), "selecting a map's settings shows it"); + assert_eq!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion)); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(1); + assert!(!harness.state().session.bake_preview_active(), "no lingering picture"); + assert_ne!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion)); +} + +#[test] +fn a_dragged_slider_previews_smaller_than_the_picture_it_settles_on() { + let mut harness = harness(); + let settled = wait_for_preview(&mut harness, |_| true).unwrap(); + let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect(); + let (from, to) = (track.center(), track.left_center() + egui::vec2(track.width() * 0.1, 0.0)); + + 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); + let dragged = wait_for_preview(&mut harness, |size| size < settled); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + let released = wait_for_preview(&mut harness, |size| size == settled); + + assert!(dragged.is_some(), "while dragging the preview bakes smaller"); + assert!(released.is_some(), "the release refines it to the chosen size"); +} + +#[test] +fn switching_the_preview_off_hides_it() { + let mut harness = harness(); + wait_for_preview(&mut harness, |_| true); + + harness.state_mut().ui.bake_visualization.map_preview = false; + harness.run_steps(1); + + assert!(!harness.state().session.bake_preview_active()); +} + +#[test] +fn pictures_keep_coming_while_the_slider_is_still_moving() { + let mut harness = harness(); + // Many rays: each preview bake takes several frames, as on a real mesh + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays = 256; + wait_for_preview(&mut harness, |_| true); + let track = harness.get_by_role_and_label(Role::Slider, "Spread Angle").rect(); + let from = track.left_center() + egui::vec2(track.width() * 0.05, 0.0); + let picture = |harness: &Harness<'static, TextureCraftApp>| { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned()) + }; + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + // Holding the last picture keeps a new one from reusing its address + let mut last = picture(&harness); + let mut pictures = 0; + let started = std::time::Instant::now(); + for step in 0.. { + if pictures > 2 || started.elapsed() > MOVING_DRAG_LIMIT { + break; + } + + // Every frame moves the slider, as a steady drag does + harness.hover_at(from + egui::vec2(track.width() * 0.002 * (step % 200) as f32, 0.0)); + harness.run_steps(1); + let now = picture(&harness); + if now.as_ref().map(std::sync::Arc::as_ptr) != last.as_ref().map(std::sync::Arc::as_ptr) { + pictures += 1; + last = now; + } + } + + assert!(pictures > 2, "new pictures arrive while the slider never stops"); +} + +#[test] +fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() { + let mut harness = harness(); + let first = wait_for_preview(&mut harness, |_| true).unwrap(); + let picture = |harness: &Harness<'static, TextureCraftApp>| { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned()) + }; + + harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R128; + let resized = wait_for_preview(&mut harness, |size| size < first); + assert!(resized.is_some(), "a smaller resolution bakes a smaller picture"); + + // A change that doesn't come from the panel: a script, an undo or a synced set + let before = picture(&harness); + harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } })); + let mut changed = false; + for _ in 0..600 { + harness.run_steps(1); + if picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) { + changed = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(changed, "the settings change brings a new picture"); + + // The same file loaded again: same name, new geometry + for (index, bytes) in [b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".as_slice(), b"v 0 0 0\nv 2 0 0\nv 0 2 0\nf 1 2 3\n".as_slice()].into_iter().enumerate() { + let session = &mut harness.state_mut().session; + if index > 0 { + session.remove_high_poly(0).unwrap(); + } + session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); + let before = picture(&harness); + let reloaded = (0..600).any(|_| { + harness.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) + }); + assert!(reloaded, "high poly load {index} brings a new picture"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index a99ef8bf..06e50b3c 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -4,6 +4,7 @@ mod alpha_parameters; mod anchor_point; mod bake_job_mesh; +mod bake_live_preview; mod bake_map_rows; mod bake_mode; mod bake_presets; From e8473240fd388617f6d55ac44a73a34cc21cf75a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 21:12:52 +0100 Subject: [PATCH 123/153] Output templates: Import and Export reachable from the keyboard, two tooltip fixes The Presets row gets a Template actions button (three dots) that opens a menu with Import and Export of the selected template. It is focusable, opens with Import focused and closes after an action, so no pointer is needed. The row's right-click menu keeps both entries. An inverted empty swatch names the colour it writes after inversion, and the disabled Separate R, G and B item says R, G and B must read the same map and be inverted alike. --- crates/ui-egui/src/export_templates.rs | 66 +++++++++++++++------ crates/ui-egui/tests/it/output_templates.rs | 41 ++++++++++++- docs/ui-parity.md | 8 ++- 3 files changed, 94 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index de25013f..beaf660f 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -424,6 +424,11 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { act = Some(ListAction::Duplicate(sel.clone())); } + + // TextureCraft's template files: a focusable menu, as the row's right click is pointer only + let actions = icon_button_without_tooltip(ui, ic::DOTS_THREE, tr("Template actions"), false, ICON_POINTS); + let opened_now = actions.clicked(); + egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); }); }); ui.add_space(2.0); @@ -465,12 +470,7 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti // TextureCraft's template files, after the reference's entries ui.separator(); - if ui.button(tr("Import a template (.json)")).clicked() { - act = Some(ListAction::Import); - } - if *name == sel && ui.button(tr("Export the selected template (.json)")).clicked() { - act = Some(ListAction::Export); - } + template_file_items(ui, &mut act, *name == sel, false); }); } } @@ -479,6 +479,24 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti act } +/// Import, and Export of the selected template when `with_export`; `focus_first` moves the keyboard +/// focus to Import so a menu opened from the keyboard can be used without the pointer. A key press +/// does not close a menu like a click does, so the menu closes itself +fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: bool, focus_first: bool) { + let import = ui.button(tr("Import a template (.json)")); + if focus_first { + import.request_focus(); + } + if import.clicked() { + *act = Some(ListAction::Import); + ui.close(); + } + if with_export && ui.button(tr("Export the selected template (.json)")).clicked() { + *act = Some(ListAction::Export); + ui.close(); + } +} + /// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in /// the accent colour fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { @@ -1198,13 +1216,21 @@ fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) - } } -/// A swatch's tooltip: "Empty (writes black)" ("Empty (writes white)" for alpha) when empty, -/// else ", "; another constant (TextureCraft's own) gives its value -fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> String { +/// A swatch's tooltip: "Empty (writes black)" ("Empty (writes white)" for alpha) when empty, the +/// other way round when the swatch is inverted, else ", "; another constant +/// (TextureCraft's own) gives its value +fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget, inverted: bool) -> String { let alpha = target == ChannelTarget::One(Dest::A); + let cleared = if alpha { CLEARED_ALPHA } else { CLEARED_VALUE }; + let written = if inverted { 1.0 - cleared } else { cleared }; match source { - SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Empty (writes white)").to_string(), - SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Empty (writes black)").to_string(), + SourceRef::Constant(value) if (*value - cleared).abs() < f32::EPSILON => { + if written > 0.5 { + tr("Empty (writes white)").to_string() + } else { + tr("Empty (writes black)").to_string() + } + } SourceRef::Constant(value) => trf("Constant {value}", &[("value", &format!("{value:.2}"))]), _ => { let name = map_lists::name_of(source).map_or_else(String::new, |name| tr(name).to_string()); @@ -1250,7 +1276,7 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo let label = target_label(target); let inverted = target.dests().iter().all(|dest| map.inverted.contains(dest)); - let tooltip = swatch_tooltip(map, &source, target); + let tooltip = swatch_tooltip(map, &source, target, inverted); let mut name = trf("{channel}: {tooltip}", &[("channel", &label), ("tooltip", &tooltip)]); if inverted { name = trf("{swatch}, inverted", &[("swatch", &name)]); @@ -1284,7 +1310,7 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo let mut checked = shows_split; let can_toggle = !shows_split || rgb_one_map(map); let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Separate R, G and B"))); - let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to join them")); + let item = item.on_disabled_hover_text(tr("R, G and B can only be joined when they read the same map and are inverted alike")); if item.changed() { changed |= split_or_collapse(map, split, shows_split); } @@ -1639,8 +1665,14 @@ mod tests { let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); assert_eq!(map.channels, cleared); assert!(map.inverted.is_empty(), "a cleared channel writes its default, not its inverse"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Empty (writes black)"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Empty (writes white)"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb, false), "Empty (writes black)"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A), false), "Empty (writes white)"); + assert_eq!( + swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb, true), + "Empty (writes white)", + "inverted, the empty colour writes its inverse" + ); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A), true), "Empty (writes black)"); } #[test] @@ -1661,11 +1693,11 @@ mod tests { apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::AllRgb); assert!(rgb_spread(&map)); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, RGB"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb, false), "Base color, RGB"); apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::Component(0)); assert_eq!(swatch_targets(&map, false), vec![ChannelTarget::Rgb], "R of one map in R, G and B stays one swatch"); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, red channel"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb, false), "Base color, red channel"); } #[test] diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index c063ca31..1cdba31a 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -8,6 +8,7 @@ use serde_json::json; use texturecraft_engine::core::Channel; use texturecraft_engine::formats::{Dest, SourceRef}; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; use texturecraft_ui_egui::state::{MapExport, SetExport}; #[path = "output_template/template_library.rs"] @@ -375,6 +376,44 @@ fn the_presets_row_holds_copy_minus_and_plus_without_tooltips() { assert!(h.query_by_label("Export the selected template (.json)").is_some()); } +/// Press `key` with no pointer event +fn press(h: &mut Harness<'_, TextureCraftApp>, key: egui::Key) { + h.key_press(key); + h.run_steps(4); +} + +#[test] +fn import_and_export_are_reachable_from_the_keyboard_alone() { + let library = TemplateLibrary::new("keyboard-actions"); + let mut h = harness(&library); + let file = library.0.join("exported_template.json"); + let answer = file.clone(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + let templates_before = h.state().session.export_presets.list.len(); + + // The actions menu is a named button the keyboard focus reaches + h.get_by_role_and_label(egui::Role::Button, "Template actions").focus(); + h.run_steps(2); + press(&mut h, egui::Key::Enter); + let import = h.get_by_label("Import a template (.json)"); + assert!(import.accesskit_node().is_focused(), "the menu opens with Import focused"); + + press(&mut h, egui::Key::Tab); + assert!(h.get_by_label("Export the selected template (.json)").accesskit_node().is_focused(), "Tab moves on to Export"); + press(&mut h, egui::Key::Enter); + assert!(std::fs::read_to_string(&file).unwrap().contains("\"Mine\""), "Export wrote the selected template"); + + assert!(h.query_by_label("Import a template (.json)").is_none(), "the menu closes after the action"); + + h.get_by_role_and_label(egui::Role::Button, "Template actions").focus(); + h.run_steps(2); + press(&mut h, egui::Key::Enter); + press(&mut h, egui::Key::Enter); + h.run_steps(4); + assert_eq!(h.state().session.export_presets.list.len(), templates_before + 1, "Import added the exported template"); + assert!(h.state().toasts.iter().any(|toast| toast.text.starts_with("Imported template"))); +} + #[test] fn the_map_lists_stand_in_three_panes_with_their_groups_and_names() { let library = TemplateLibrary::new("panes"); @@ -523,7 +562,7 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv invert.click(); h.run_steps(4); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); - assert!(h.query_all_by_label("G: Empty (writes black), inverted").next().is_some(), "the swatch says it is inverted"); + assert!(h.query_all_by_label("G: Empty (writes white), inverted").next().is_some(), "the swatch says it is inverted"); } #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bba5be33..1e45c49d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -353,20 +353,22 @@ that numbers hide once a tile is under 40 points on screen. ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". Create names new rows "Gray", "RGB" and "RGBA" after "$mesh_$textureSet_", so the texture sets of one export do not write the same file, with "_1", "_2" when taken. An - empty swatch's tooltip reads "Empty (writes black)" ("Empty (writes white)" for A), a filled one + empty swatch's tooltip reads "Empty (writes black)" ("Empty (writes white)" for A, the other + way round when the swatch is inverted), a filled one ", ", e.g. "Base color, red channel" or "Metallic, gray value". Dropping a map on a swatch asks "Which part of ?": a gray map offers *Gray value* and *Alpha channel*, a colour map *Gray value*, *Red channel*, *Green channel*, *Blue channel* and *Alpha channel*, on the RGB swatch first *Red, green and blue*; Escape assigns nothing. TextureCraft cannot read a map's gray or alpha yet, so those choices are greyed. A click on a swatch offers *Clear channel*, on RGB, R, G and B also *Separate R, G and B*; R, G - and B that read different maps cannot be joined (the item is greyed). The right side has the + and B that read different maps or are inverted differently cannot be joined (the item is greyed). The right side has the *Input maps* pane in the OpenPBR parameter groups (Base ... Geometry, then Other for TextureCraft's channels outside OpenPBR), each map TextureCraft has under its own name, and a pane with *Mesh maps* above *Converted maps* (highlighted). Maps the selected template uses get a square in their swatch's colour. OpenPBR inputs TextureCraft has no channel for are greyed and cannot be dragged; *Converted maps* lists the maps TextureCraft computes. TextureCraft keeps some things the reference does not have, out of the way: Import and Export of template files - at the end of a preset's right-click menu; a swatch's right-click menu with Invert (an inverted + at the end of a preset's right-click menu and in a *Template actions* button (three dots, left of + copy on the *Presets* row) that the keyboard reaches, with Import focused when it opens; a swatch's right-click menu with Invert (an inverted swatch has a corner mark), Black, Gray 50%, White, the constant's value and the map's layout (RGB, RGBA, Gray, Gray + A); *Move up* and *Move down* in the grip's right-click menu and the arrow keys on a focused grip; the planned file name in the file name's tooltip; and From f4a8283d741582c3c729af896b8265ad7cd929b5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:15:22 +0100 Subject: [PATCH 124/153] Export templates: subfolders and spec-based URP/USD templates --- crates/formats/README.md | 8 +- crates/formats/src/export/mod.rs | 54 ++++-- crates/formats/src/export/tests.rs | 161 +++++++++++++++++- crates/formats/src/presets.rs | 43 +++++ crates/ui-egui/src/export_window.rs | 14 +- .../tests/it/export_template_guards.rs | 6 +- crates/ui-egui/tests/it/output_templates.rs | 3 + docs/features.md | 5 +- 8 files changed, 268 insertions(+), 26 deletions(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index f56dbc36..ca377337 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -119,7 +119,11 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; the normal channel, then with the baked normal map, by Reoriented Normal Mapping. DirectX flips green. -Built-in presets: +File names may hold folders: `/` separates folder names inside the output directory (each one +sanitized; a backslash, `..`, a leading `/` and empty folder names are refused), and the folders +are created when the files are written. + +Built-in presets (each one lists the public specification its packing follows in `src/presets.rs`): | Preset | Files (`$mesh_$textureSet_…`) | |---|---| @@ -131,6 +135,8 @@ Built-in presets: | Blender (Principled BSDF) | `BaseColor`, `Metallic`, `Roughness`, `Normal` (OpenGL), `Height` (16-bit), `Emission`, `Specular` | | Godot 4 (ORM) | `albedo` (A = opacity), `orm` (R AO, G roughness, B metal), `normal` (OpenGL), `emission` | | OpenPBR (separate maps) | one map per OpenPBR Surface input the set has: `base_color`, `base_metalness`, `specular_roughness`, `specular_roughness_anisotropy`, `coat_weight`, `coat_roughness`, `fuzz_weight`, `fuzz_color`, `fuzz_roughness`, `transmission_weight`, `subsurface_weight`, `emission_color`, `geometry_opacity`, `geometry_normal` (OpenGL), `height` (16-bit) | +| Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | +| USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index a76a46b0..35fe4621 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -53,14 +53,18 @@ pub const FILE_TOKENS: [(&str, &str); 6] = [ ("$udim", "UV tile number (1001 for sets without UV tiles)"), ]; -/// Why `template` is not a valid file name template: path separators, `..`, control characters -/// and unknown `$` variables are refused. +/// Why `template` is not a valid file name template. `/` separates folders inside the output +/// directory; a backslash, `..`, a leading `/`, an empty folder name, control characters and +/// unknown `$` variables are refused. pub fn template_error(template: &str) -> Option { if template.trim().is_empty() || template.len() > MAX_TEMPLATE { return Some(format!("file name \"{template}\" is empty or longer than {MAX_TEMPLATE} bytes")); } - if template.contains(['/', '\\']) || template.contains("..") || template.chars().any(char::is_control) { - return Some(format!("file name \"{template}\" contains a path separator, \"..\" or a control character")); + if template.contains('\\') || template.contains("..") || template.chars().any(char::is_control) { + return Some(format!("file name \"{template}\" contains a backslash, \"..\" or a control character")); + } + if template.split('/').any(|segment| segment.trim().is_empty()) { + return Some(format!("file name \"{template}\" starts or ends with \"/\" or has an empty folder name")); } let mut rest = template; while let Some(i) = rest.find('$') { @@ -574,6 +578,11 @@ pub fn sanitize_file_stem(s: &str) -> String { out } +/// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. +pub fn sanitize_file_path(s: &str) -> String { + s.split('/').map(sanitize_file_stem).collect::>().join("/") +} + /// The files `opts` produces for texture set `ts`, without rendering (for the export dialog). /// Template variables: [`FILE_TOKENS`]. pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { @@ -635,11 +644,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export check_psd_size(size, channels, bit_depth)?; } + // A name of the project, mesh or texture set never adds a folder + let no_folder = |name: &str| name.replace('/', "_"); let stem = template .replace("$udim", &tile.unwrap_or(1001).to_string()) - .replace("$project", &project.name) - .replace("$mesh", mesh_name) - .replace("$textureSet", &set.name) + .replace("$project", &no_folder(&project.name)) + .replace("$mesh", &no_folder(mesh_name)) + .replace("$textureSet", &no_folder(&set.name)) .replace("$channel", channel_label(map)) .replace("$colorSpace", color_space); @@ -647,14 +658,14 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let token_stem = tile.map(|_| { let t = template .replace("$udim", "UDIMTOKEN") - .replace("$project", &project.name) - .replace("$mesh", mesh_name) - .replace("$textureSet", &set.name) + .replace("$project", &no_folder(&project.name)) + .replace("$mesh", &no_folder(mesh_name)) + .replace("$textureSet", &no_folder(&set.name)) .replace("$channel", channel_label(map)) .replace("$colorSpace", color_space); - sanitize_file_stem(&t) + sanitize_file_path(&t) }); - let stem = sanitize_file_stem(&stem); + let stem = sanitize_file_path(&stem); let ext = format.extension(); let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); @@ -1544,18 +1555,29 @@ fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl /// Write exported files into `dir` (created if missing) via [`crate::write_batch_atomic`]: /// all filenames are validated and staged before any rename, and a later rename failure rolls /// back earlier publications (concurrent readers may briefly observe a mixed generation during -/// the rename loop). Names must be plain file names. +/// the rename loop). Names are file names, or relative paths with `/` between sanitized folder +/// names; the folders are created inside `dir`. #[cfg(not(target_arch = "wasm32"))] pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result> { std::fs::create_dir_all(dir)?; + let root = dir.canonicalize()?; let mut targets = Vec::with_capacity(files.len()); for f in files { // Cap the sanitized stem before adding the extension let (stem, ext) = f.name.rsplit_once('.').unwrap_or((&f.name, "")); - if f.name.is_empty() || stem != sanitize_file_stem(stem) || !ext.chars().all(|c| c.is_ascii_alphanumeric()) || f.name.trim_matches('.').is_empty() { - return Err(FormatError::Invalid(format!("\"{}\" is not a plain file name", f.name))); + if f.name.is_empty() || stem != sanitize_file_path(stem) || !ext.chars().all(|c| c.is_ascii_alphanumeric()) || f.name.trim_matches('.').is_empty() { + return Err(FormatError::Invalid(format!("\"{}\" is not a file name or a relative path", f.name))); } - targets.push((dir.join(&f.name), f.bytes.as_slice())); + + // A folder that links elsewhere must not take the file out of `dir` + let target = dir.join(&f.name); + if let Some(parent) = target.parent().filter(|parent| *parent != dir) { + std::fs::create_dir_all(parent)?; + if !parent.canonicalize()?.starts_with(&root) { + return Err(FormatError::Invalid(format!("\"{}\" leads out of the output folder", f.name))); + } + } + targets.push((target, f.bytes.as_slice())); } crate::write_batch_atomic(targets.iter().map(|(path, bytes)| (path.as_path(), *bytes)))?; Ok(targets.into_iter().map(|(path, _)| path).collect()) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 8a8ca682..f7077577 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -565,7 +565,7 @@ fn validation_rejects_bad_presets() { p.validate().is_err() }; let long = "x".repeat(300); - for file in ["a/b", r"a\b", "..", "x..y", "$meshes_$foo", "$", "", " ", "a\u{7}b", long.as_str()] { + for file in ["/a", "a/", "a//b", r"a\b", "..", "x..y", "a/../b", "$meshes_$foo", "$", "", " ", "a\u{7}b", long.as_str()] { assert!(refused(&|p| p.maps[0].file = file.into()), "file template {file:?} must be refused"); } assert!(refused(&|p| p.name = " ".into())); @@ -726,6 +726,9 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() { // The length limit cuts the longer placeholder where it doesn't cut the tile number: none then assert_eq!(udim_names(format!("{}_$udim_$textureSet", "a".repeat(MAX_STEM - 10))), [None, None]); + + // A folder stays in the placeholder name + assert_eq!(udim_names("Base/$textureSet_$udim".into()), [Some("Base/Body_.png".to_string()), Some("Base/Body_.png".to_string())]); } #[test] @@ -1329,3 +1332,159 @@ fn diffusion_padding_fills_beyond_the_dilation_smoothly() { } } } + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn folder_templates_write_their_folders_inside_the_output_directory() { + let fx = Fx::new(&default_channels()); + let dir = std::env::temp_dir().join(format!("tc-formats-export-folders-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("$project.ts/$textureSet/roughness"), rough("Roughness/$textureSet_Roughness")] }; + let files = fx.render(&ExportOptions::new(preset)); + + write_files(&files, &dir).unwrap(); + + assert!(dir.join("My_Project.ts/Body_Set/roughness.png").is_file(), "{:?}", files.iter().map(|f| f.name.as_str()).collect::>()); + assert!(dir.join("Roughness/Body_Set_Roughness.png").is_file()); + for name in ["../evil.png", "/evil.png", "a//evil.png", r"a\evil.png"] { + let evil = ExportedFile { name: name.into(), ..files[0].clone() }; + assert!(write_files(&[evil], &dir).is_err(), "{name}"); + } + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn file_names_in_different_folders_do_not_collide_and_the_same_path_does() { + let fx = Fx::new(&default_channels()); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("a/x"), rough("b/x"), rough("A/x")] }; + + let names: Vec = list_outputs(&fx.project, 0, "sphere", &ExportOptions::new(preset)).unwrap().into_iter().map(|p| p.name).collect(); + + assert_eq!(names, ["a/x.png", "b/x.png", "A/x_2.png"]); +} + +/// A set whose channels hold distinct constants, to see where a template writes each of them +fn packing_fixture() -> Fx { + let mut channels = default_channels(); + channels.extend([Channel::AmbientOcclusion, Channel::Opacity, Channel::Emissive]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::AmbientOcclusion, |_, _| [0.6; 3]); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + fx.set_all(Channel::Emissive, |_, _| [0.3; 3]); + fx +} + +/// The 8-bit value of an image position as RGBA +fn pixel(file: &ExportedFile) -> [i32; 4] { + decode(file).to_rgba8().get_pixel(3, 3).0.map(i32::from) +} + +fn byte(value: f32) -> i32 { + (value * 255.0).round() as i32 +} + +fn assert_close(actual: [i32; 4], expected: [i32; 4], what: &str) { + assert!(actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= 1), "{what}: {actual:?} instead of {expected:?}"); +} + +#[test] +fn packed_templates_write_occlusion_roughness_and_metallic_where_the_spec_says() { + let fx = packing_fixture(); + let expected = [byte(0.6), byte(0.4), byte(0.8)]; + + for (template, file) in + [("glTF PBR Metal Roughness", "OcclusionRoughnessMetallic"), ("Unreal Engine (Packed)", "OcclusionRoughnessMetallic"), ("Godot 4 (ORM)", "orm")] + { + let files = fx.render_preset(template); + + let [r, g, b, _] = pixel(find(&files, file)); + assert_close([r, g, b, 0], [expected[0], expected[1], expected[2], 0], &format!("{template}: R occlusion, G roughness, B metallic")); + } +} + +#[test] +fn unity_templates_write_smoothness_in_the_alpha_of_the_metallic_map() { + let fx = packing_fixture(); + let smoothness = byte(1.0 - 0.4); + + let hdrp = pixel(find(&fx.render_preset("Unity HDRP (Mask Map)"), "MaskMap")); + let urp = pixel(find(&fx.render_preset("Unity URP Lit (Metallic Smoothness)"), "MetallicMap")); + + assert_close(hdrp, [byte(0.8), byte(0.6), 0, smoothness], "HDRP mask map: R metallic, G occlusion, B detail mask, A smoothness"); + assert_close(urp, [byte(0.8), 0, 0, smoothness], "URP metallic map: R metallic, A smoothness"); +} + +#[test] +fn the_usd_preview_surface_template_writes_one_map_per_input_named_like_it() { + let fx = packing_fixture(); + + let files = fx.render_preset("USD Preview Surface (separate maps)"); + + let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect(); + for (input, expected) in [("roughness", byte(0.4)), ("metallic", byte(0.8)), ("occlusion", byte(0.6)), ("opacity", byte(0.9))] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is one 8-bit channel: {names:?}"); + assert_close(pixel(file), [expected, expected, expected, 255], input); + } + for input in ["diffuseColor", "emissiveColor", "normal"] { + assert_eq!(decode(find(&files, &format!("_{input}.png"))).color(), image::ColorType::Rgb8, "{input} is a colour map: {names:?}"); + } + assert!(!names.iter().any(|name| name.contains("clearcoat")), "sets without the coat write no coat maps: {names:?}"); +} + +#[test] +fn only_the_unreal_template_writes_a_directx_normal_map() { + let mut fx = packing_fixture(); + let tilt = Vec3::new(0.3, 0.4, 0.0); + let tilt = Vec3::new(tilt.x, tilt.y, (1.0 - tilt.length_squared()).sqrt()); + fx.set_all(Channel::Normal, |_, _| (tilt * 0.5 + Vec3::splat(0.5)).to_array()); + let open_gl_green = byte(tilt.y * 0.5 + 0.5); + + for (template, file, flipped) in [ + ("glTF PBR Metal Roughness", "_Normal.png", false), + ("Unreal Engine (Packed)", "_Normal.png", true), + ("Unity HDRP (Mask Map)", "_Normal.png", false), + ("Unity URP Lit (Metallic Smoothness)", "NormalMap", false), + ("Godot 4 (ORM)", "normal", false), + ("USD Preview Surface (separate maps)", "_normal.png", false), + ] { + let green = pixel(find(&fx.render_preset(template), file))[1]; + + let want = if flipped { 255 - open_gl_green } else { open_gl_green }; + assert!((green - want).abs() <= 1, "{template}: green {green} instead of {want}"); + } +} + +#[test] +fn spec_templates_write_8_bit_png_files_with_the_expected_colour_encoding() { + let fx = packing_fixture(); + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + + for template in ["glTF PBR Metal Roughness", "Unreal Engine (Packed)", "Unity HDRP (Mask Map)", "Unity URP Lit (Metallic Smoothness)", "Godot 4 (ORM)"] { + let files = fx.render_preset(template); + + let color = files.iter().find(|f| ["BaseColor", "BaseMap", "albedo"].iter().any(|stem| f.name.contains(stem))).unwrap(); + + assert!(files.iter().all(|f| f.name.ends_with(".png")), "{template}: {:?}", files.iter().map(|f| &f.name).collect::>()); + let [r, g, b, a] = pixel(color); + assert_close([r, g, b, 0], [base[0], base[1], base[2], 0], &format!("{template}: sRGB-encoded base color")); + assert!((a - byte(0.9)).abs() <= 1, "{template}: opacity in alpha"); + } +} + +#[test] +fn a_slash_in_a_project_or_texture_set_name_does_not_make_a_folder() { + let mut fx = Fx::new(&default_channels()); + fx.project.name = "Wood/Oak".into(); + fx.project.texture_sets[0].name = "Body/Hull".into(); + let preset = + ExportPreset { name: "t".into(), maps: vec![gray_map("$project_$textureSet", SourceRef::Channel { channel: Channel::Roughness, component: 0 })] }; + + let names: Vec = list_outputs(&fx.project, 0, "sphere", &ExportOptions::new(preset)).unwrap().into_iter().map(|p| p.name).collect(); + + assert_eq!(names, ["Wood_Oak_Body_Hull.png"]); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 24f9f050..2f2879a4 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -92,11 +92,15 @@ pub fn builtin_presets() -> Vec { maps.push(map("ambientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0)))); maps }), + // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material preset("glTF PBR Metal Roughness", gltf_pbr_maps(|s| format!("$mesh_$textureSet_{s}"))), + // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material (R occlusion, G roughness, B metallic) and the base color, roughness, metallic and normal inputs of + // https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine preset( "Unreal Engine (Packed)", vec![map("BaseColor", 8, base_with_alpha()), map("OcclusionRoughnessMetallic", 8, orm()), map("Normal", 8, normal(VirtualMap::NormalDirectX))], ), + // Spec: https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@17.0/manual/Mask-Map-and-Detail-Map.html preset( "Unity HDRP (Mask Map)", vec![ @@ -115,6 +119,7 @@ pub fn builtin_presets() -> Vec { map("Normal", 8, normal(VirtualMap::NormalOpenGl)), ], ), + // Spec: https://docs.unity3d.com/Manual/StandardShaderMaterialParameterMetallic.html (smoothness in the metallic map's alpha) preset( "Unity Standard (Metallic Smoothness)", vec![ @@ -133,6 +138,7 @@ pub fn builtin_presets() -> Vec { map("Occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), ], ), + // Spec: https://docs.blender.org/manual/en/latest/render/shader_nodes/shader/principled.html preset( "Blender (Principled BSDF)", vec![ @@ -145,6 +151,7 @@ pub fn builtin_presets() -> Vec { map("Specular", 8, gray(ch(Channel::SpecularLevel, 0))), ], ), + // Spec: https://docs.godotengine.org/en/stable/tutorials/3d/standard_material_3d.html (ORM material: R occlusion, G roughness, B metallic) preset( "Godot 4 (ORM)", vec![ @@ -154,6 +161,7 @@ pub fn builtin_presets() -> Vec { map("emission", 8, rgb(|k| ch(Channel::Emissive, k))), ], ), + // Spec: https://academysoftwarefoundation.github.io/OpenPBR/ // One map per OpenPBR input present in the texture set preset("OpenPBR (separate maps)", { let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0))); @@ -176,6 +184,41 @@ pub fn builtin_presets() -> Vec { map("height", 16, gray(ch(Channel::Height, 0))), ] }), + // Spec: https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.0/manual/lit-shader.html (smoothness in the metallic map's alpha) + preset( + "Unity URP Lit (Metallic Smoothness)", + vec![ + map("BaseMap", 8, base_with_alpha()), + map( + "MetallicMap", + 8, + vec![ + (Dest::R, ch(Channel::Metallic, 0)), + (Dest::G, SourceRef::Constant(0.0)), + (Dest::B, SourceRef::Constant(0.0)), + (Dest::A, virt(VirtualMap::Glossiness, 0)), + ], + ), + map("NormalMap", 8, normal(VirtualMap::NormalOpenGl)), + map("OcclusionMap", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("EmissionMap", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), + // Spec: https://openusd.org/release/spec_usdpreviewsurface.html (one texture per input, named like it) + preset( + "USD Preview Surface (separate maps)", + vec![ + map("diffuseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("emissiveColor", 8, rgb(|k| ch(Channel::Emissive, k))), + map("metallic", 8, gray(ch(Channel::Metallic, 0))), + map("roughness", 8, gray(ch(Channel::Roughness, 0))), + map("normal", 8, normal(VirtualMap::NormalOpenGl)), + map("occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("opacity", 8, gray(ch(Channel::Opacity, 0))), + map("clearcoat", 8, gray(ch(Channel::CoatWeight, 0))), + map("clearcoatRoughness", 8, gray(ch(Channel::CoatRoughness, 0))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 0e696bcd..6a46f757 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -363,6 +363,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { params["reservedNames"] = job.written.iter().chain(&job.material_udim_patterns).map(|name| json!(name)).collect(); } + let directory = std::path::PathBuf::from(params["dir"].as_str().unwrap_or_default()); + // The last command writes the USD asset from the params of every command, so a canceled or failed export writes none if let Some(job) = app.ui.export.job.as_mut().filter(|job| job.usd_asset) { job.sent.push(params.clone()); @@ -382,9 +384,15 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { app.toast(warning.to_string(), true); } - let files: Vec = response_strings(&response, "files") - .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) - .collect(); + // Names relative to the output folder keep a template's folders + let relative = |file: &str| { + let path = std::path::Path::new(file); + match path.strip_prefix(&directory) { + Ok(inside) => inside.components().map(|part| part.as_os_str().to_string_lossy().into_owned()).collect::>().join("/"), + Err(_) => path.file_name().map_or_else(|| file.to_string(), |name| name.to_string_lossy().into_owned()), + } + }; + let files: Vec = response_strings(&response, "files").map(relative).collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; // The USD asset is no texture: it stays in the list of written files only for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 9cfc0071..3290256a 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -33,7 +33,7 @@ fn harness(library: &Library) -> Harness<'static, TextureCraftApp> { /// Type an invalid file name into the first output of the selected template, as the editor would. fn break_draft(h: &mut Harness<'_, TextureCraftApp>) { let draft = h.state_mut().ui.export.draft.as_mut().unwrap(); - draft.maps[0].file = "a/b".into(); + draft.maps[0].file = r"a\b".into(); assert!(draft.validate().is_err()); h.run_steps(3); } @@ -98,7 +98,7 @@ fn unfinished_edit_asks_before_selecting_another_template_and_keep_editing_stays h.get_by_label("Keep editing").click(); h.run_steps(3); assert_eq!(selected(&h), "Alpha tpl"); - assert_eq!(h.state().ui.export.draft.as_ref().unwrap().maps[0].file, "a/b", "the edit is intact"); + assert_eq!(h.state().ui.export.draft.as_ref().unwrap().maps[0].file, r"a\b", "the edit is intact"); assert!(h.state().ui.export.ask.is_none()); } @@ -118,7 +118,7 @@ fn unfinished_edit_discard_switches_to_the_other_template() { assert_eq!(draft.name, "Beta tpl"); assert!(draft.validate().is_ok(), "the dropped edit did not follow"); let alpha = h.state().session.export_preset("Alpha tpl").unwrap(); - assert_ne!(alpha.maps[0].file, "a/b", "the invalid edit was never saved"); + assert_ne!(alpha.maps[0].file, r"a\b", "the invalid edit was never saved"); } #[test] diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 1cdba31a..061c2779 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -84,6 +84,9 @@ fn drop_on(h: &mut Harness<'_, TextureCraftApp>, source: SourceRef, at: egui::Po /// Right-click the Presets list's `label` (listed before the selected one's name in the middle) fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + // The list holds more templates than it shows + h.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).scroll_to_me(); + h.run_steps(4); h.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).click_secondary(); h.run_steps(4); } diff --git a/docs/features.md b/docs/features.md index 04702ee9..42ea07a6 100644 --- a/docs/features.md +++ b/docs/features.md @@ -162,13 +162,14 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), - Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, + Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, - and share them as JSON. Right-click a preset to rename, duplicate or remove it; F2 renames. + and share them as JSON. File names may hold folders (`Roughness/$textureSet_Roughness`). + Right-click a preset to rename, duplicate or remove it; F2 renames. - **Export panel** on the right bar: *Export Mesh...* asks for the mesh export options, then for the file; *Export Textures...* opens the Export textures window (Settings, Output templates and List of exports, *Include all*, *Save settings* and the number of textures the export writes; From 56efb48efb72fa74fe28f67741a9cccebd3e65eb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 24 Nov 2026 20:05:51 -0500 Subject: [PATCH 125/153] packaging(linux): support co-installable nightly packages (#801) Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch. Co-authored-by: Dylan M. Taylor --- .github/nightly-signing-policy.json | 110 ++++ .github/workflows/nightly-macos.yml | 91 ++++ .github/workflows/nightly-sign.yml | 42 ++ .github/workflows/nightly.yml | 34 ++ .github/workflows/packaging-lint.yml | 4 + .gitignore | 6 + apps/texturecraft-cli/build.rs | 73 ++- apps/texturecraft-cli/src/main.rs | 10 + apps/texturecraft/Cargo.toml | 3 +- apps/texturecraft/build.rs | 77 ++- apps/texturecraft/src/build_channel.rs | 62 +++ apps/texturecraft/src/build_flavor.rs | 94 ++++ apps/texturecraft/src/launch_profile.rs | 217 ++++++++ apps/texturecraft/src/main.rs | 283 +++++++++- apps/texturecraft/src/nightly_session.rs | 277 ++++++++++ apps/texturecraft/src/process_identity.rs | 78 +++ apps/texturecraft/src/profile_root.rs | 489 ++++++++++++++++++ assets/app-icon/README.md | 20 + assets/app-icon/nightly-provenance.json | 81 +++ assets/app-icon/nightly/128.png | Bin 0 -> 9309 bytes assets/app-icon/nightly/16.png | Bin 0 -> 484 bytes assets/app-icon/nightly/24.png | Bin 0 -> 810 bytes assets/app-icon/nightly/256.png | Bin 0 -> 27975 bytes assets/app-icon/nightly/32.png | Bin 0 -> 1168 bytes assets/app-icon/nightly/48.png | Bin 0 -> 2092 bytes assets/app-icon/nightly/512.png | Bin 0 -> 83849 bytes assets/app-icon/nightly/64.png | Bin 0 -> 3194 bytes assets/app-icon/texturecraft-nightly-1024.png | Bin 0 -> 225374 bytes assets/app-icon/texturecraft-nightly.icns | Bin 0 -> 358850 bytes assets/app-icon/texturecraft-nightly.ico | Bin 0 -> 47362 bytes assets/app-icon/texturecraft-nightly.png | Bin 0 -> 27975 bytes crates/ui-egui/src/lib.rs | 27 +- crates/ui-egui/src/os_window.rs | 120 +++++ crates/ui-egui/src/settings_window.rs | 16 +- crates/ui-egui/src/titlebar.rs | 13 +- crates/ui-egui/src/updates_ui.rs | 14 +- crates/ui-egui/src/windows.rs | 9 +- docs/nightly-release-preparation.md | 133 +++++ docs/nightly-signing-policy.example.json | 54 ++ packaging/linux/AppRun | 13 + .../linux/ai.storyteller.texturecraft.desktop | 2 +- packaging/linux/apprun-test.sh | 18 + packaging/linux/flatpak-bundle.sh | 86 ++- packaging/linux/nfpm.yaml | 20 +- packaging/linux/nightly-arch-launch.sh | 14 + packaging/linux/nightly-arch-tar-test.sh | 58 +++ packaging/linux/nightly-arch-tar.sh | 22 + packaging/linux/nightly-launch-test.sh | 57 ++ packaging/linux/nightly-launch.sh | 21 + packaging/linux/nightly.sh | 33 ++ packaging/linux/package.sh | 184 ++++++- packaging/macos/nightly-lib.sh | 125 +++++ packaging/macos/nightly-sign.sh | 141 +++++ packaging/macos/nightly-verify.sh | 74 +++ packaging/macos/nightly.sh | 53 ++ packaging/macos/nightly_plist.py | 70 +++ packaging/macos/nightly_plist_tests.py | 202 ++++++++ packaging/macos/nightly_sign_tests.py | 182 +++++++ packaging/nightly-archive-tests.py | 234 +++++++++ packaging/nightly-archive.py | 130 +++++ packaging/nightly-checks.sh | 33 ++ packaging/nightly-common.sh | 93 ++++ packaging/nightly-icons.py | 297 +++++++++++ packaging/nightly-release-tests.py | 389 ++++++++++++++ packaging/nightly-tests.py | 46 ++ packaging/nightly_paths.py | 139 +++++ packaging/windows/nightly-package-tests.ps1 | 95 ++++ packaging/windows/nightly-signing-tests.ps1 | 104 ++++ packaging/windows/nightly.ps1 | 131 +++++ packaging/windows/package.ps1 | 23 +- packaging/windows/sign.ps1 | 41 +- sonar-project.properties | 1 + 72 files changed, 5488 insertions(+), 80 deletions(-) create mode 100644 .github/nightly-signing-policy.json create mode 100644 .github/workflows/nightly-macos.yml create mode 100644 .github/workflows/nightly-sign.yml create mode 100644 .github/workflows/nightly.yml create mode 100644 apps/texturecraft/src/build_channel.rs create mode 100644 apps/texturecraft/src/build_flavor.rs create mode 100644 apps/texturecraft/src/launch_profile.rs create mode 100644 apps/texturecraft/src/nightly_session.rs create mode 100644 apps/texturecraft/src/process_identity.rs create mode 100644 apps/texturecraft/src/profile_root.rs create mode 100644 assets/app-icon/nightly-provenance.json create mode 100644 assets/app-icon/nightly/128.png create mode 100644 assets/app-icon/nightly/16.png create mode 100644 assets/app-icon/nightly/24.png create mode 100644 assets/app-icon/nightly/256.png create mode 100644 assets/app-icon/nightly/32.png create mode 100644 assets/app-icon/nightly/48.png create mode 100644 assets/app-icon/nightly/512.png create mode 100644 assets/app-icon/nightly/64.png create mode 100644 assets/app-icon/texturecraft-nightly-1024.png create mode 100644 assets/app-icon/texturecraft-nightly.icns create mode 100644 assets/app-icon/texturecraft-nightly.ico create mode 100644 assets/app-icon/texturecraft-nightly.png create mode 100644 crates/ui-egui/src/os_window.rs create mode 100644 docs/nightly-release-preparation.md create mode 100644 docs/nightly-signing-policy.example.json create mode 100755 packaging/linux/nightly-arch-launch.sh create mode 100755 packaging/linux/nightly-arch-tar-test.sh create mode 100755 packaging/linux/nightly-arch-tar.sh create mode 100755 packaging/linux/nightly-launch-test.sh create mode 100755 packaging/linux/nightly-launch.sh create mode 100755 packaging/linux/nightly.sh create mode 100644 packaging/macos/nightly-lib.sh create mode 100755 packaging/macos/nightly-sign.sh create mode 100755 packaging/macos/nightly-verify.sh create mode 100755 packaging/macos/nightly.sh create mode 100644 packaging/macos/nightly_plist.py create mode 100644 packaging/macos/nightly_plist_tests.py create mode 100644 packaging/macos/nightly_sign_tests.py create mode 100755 packaging/nightly-archive-tests.py create mode 100644 packaging/nightly-archive.py create mode 100755 packaging/nightly-checks.sh create mode 100644 packaging/nightly-common.sh create mode 100755 packaging/nightly-icons.py create mode 100755 packaging/nightly-release-tests.py create mode 100755 packaging/nightly-tests.py create mode 100644 packaging/nightly_paths.py create mode 100644 packaging/windows/nightly-package-tests.ps1 create mode 100644 packaging/windows/nightly-signing-tests.ps1 create mode 100644 packaging/windows/nightly.ps1 create mode 100644 sonar-project.properties diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 00000000..92288670 --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,110 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/texturecraft", + "repository_id": 1419654881, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea", + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "release_branch": "release", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "texturecraft-nightly-20261124", + "repository": "storytold/texturecraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 384666426, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + }, + { + "name": "gate / gate (windows-latest)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_texturecraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_texturecraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [], + "required_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_reliability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_maintainability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_coverage", + "comparator": "LT", + "error_threshold": "80" + }, + { + "metric": "new_duplicated_lines_density", + "comparator": "GT", + "error_threshold": "3" + }, + { + "metric": "new_security_hotspots_reviewed", + "comparator": "LT", + "error_threshold": "100" + } + ], + "debt": [] + } + }, + "max_artifact_bytes": 2147483648, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml new file mode 100644 index 00000000..75134544 --- /dev/null +++ b/.github/workflows/nightly-macos.yml @@ -0,0 +1,91 @@ +name: Nightly macOS build + +# Builds the unsigned Apple-silicon TextureCraft Nightly (packaging/macos/nightly.sh) on a hosted +# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version +# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the real +# Nightly is signed and notarized by the shared release-ref signer (craft-common-actions), which calls +# packaging/macos/nightly-sign.sh. +on: + # macOS minutes are shared with release builds: pull requests run this only with the `full-ci` + # label, never by changed paths. `labeled` so adding it starts a run. + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci` +# label, or another label added) gets a group of its own, so it never cancels a real build. +concurrency: + group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + name: Nightly .app (aarch64, unsigned) + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: macos-15 + timeout-minutes: 90 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + RUST_BACKTRACE: 1 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. + - name: Check out craft-fonts + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@605d58766e8f536564da8fc81d3676ac86816dea + with: + ref: aced4137c022f1f587624d48e81ec77e1914a9cc + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea + - id: rust + uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea + with: + targets: aarch64-apple-darwin + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: ${{ steps.rust.outputs.toolchain }} + targets: ${{ steps.rust.outputs.targets }} + components: ${{ steps.rust.outputs.components }} + # A version of the prepared Nightly form for this commit; the real one comes from the feed's + # identity job. Only nightly.sh's input checks read it. + - name: Prepare a Nightly identity for this commit + run: | + set -euo pipefail + base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')" + sha="$(git rev-parse HEAD)" + date="$(date -u +%Y-%m-%d)" + { + echo "TEXTURECRAFT_BUILD_SHA=$sha" + echo "TEXTURECRAFT_BUILD_DATE=$date" + echo "TEXTURECRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly bundle + env: + TEXTURECRAFT_BUILD_CHANNEL: nightly-v1 + CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets + DIST: ${{ runner.temp }}/nightly-dist + CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts + CRAFT_FONTS_REQUIRED: "1" + run: bash packaging/macos/nightly.sh --arch aarch64 + - name: Check the archive and the bundle's version + run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/texturecraft-$TEXTURECRAFT_VERSION-macos-aarch64-nightly.zip" + # Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only. + - name: Keep the unsigned archive + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: texturecraft-nightly-macos-aarch64-unsigned + path: ${{ runner.temp }}/nightly-dist/texturecraft-${{ env.TEXTURECRAFT_VERSION }}-macos-aarch64-nightly.zip + if-no-files-found: error + retention-days: 7 + compression-level: 0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 00000000..d07db551 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: TextureCraft release-ref nightly signer + +# Enabled for supervised manual dispatch on release. Main/release contents must match. +# A reusable callee does not change context; this must be a real top-level release dispatch. +on: + workflow_dispatch: + inputs: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: texturecraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/texturecraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/release' && github.ref_type == 'branch' + permissions: + contents: write + actions: read + checks: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + producer_run_id: ${{ inputs.producer_run_id }} + producer_run_attempt: ${{ inputs.producer_run_attempt }} + # No secrets: inherit or raw platform values in this caller. Only the isolated native + # callee job may bind the existing release environment and export keys in its signing step. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 00000000..5345fe9a --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: TextureCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. +# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/texturecraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + app-name: texturecraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc + # One producer run builds every listed platform for one all-or-nothing release. The pin is the + # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the + # Linux/macOS signer (#342). + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index f54b0538..feb8675d 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -21,3 +21,7 @@ jobs: lint: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main + with: + # Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks + # that need no compiler are part of CI rather than a local step. + extra-checks-script: packaging/nightly-checks.sh diff --git a/.gitignore b/.gitignore index 0996cb2f..14362878 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,11 @@ target/ /log /secrets /temp +# The shared nightly workflow checks these out into the workspace; `nightly_init` refuses a dirty tree. +/.nightly-tools +/.nightly-input /craft-fonts +/craft-i18n +__pycache__/ +*.pyc *.tcraft.tmp diff --git a/apps/texturecraft-cli/build.rs b/apps/texturecraft-cli/build.rs index 37e0bd12..d58a4323 100644 --- a/apps/texturecraft-cli/build.rs +++ b/apps/texturecraft-cli/build.rs @@ -1,2 +1,71 @@ -// The same build provenance and Windows icon/VERSIONINFO as the app; see that file. -include!("../texturecraft/build.rs"); +// Provenance for the headless CLI: the same commit and date variables as the app, and (Windows +// only) its own icon and VERSIONINFO into `texturecraft-cli.exe`. +// +// This is deliberately not an `include!` of the app's build script: that one resolves a `#[path]` +// submodule and reads the Nightly channel, neither of which a CLI build has any use for, and a +// module path inside an included script is resolved from the included file, not from here. + +use std::process::Command; + +const ICON: &str = "../../assets/app-icon/texturecraft.ico"; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed={ICON}"); + for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-env-changed={var}"); + } + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + windows_resources(); + } +} + +fn env_or(var: &str, fallback: fn() -> Option) -> String { + std::env::var(var).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).or_else(fallback).unwrap_or_default() +} + +fn git_sha() -> Option { + let out = Command::new("git").args(["rev-parse", "HEAD"]).output().ok().filter(|o| o.status.success())?; + let sha = String::from_utf8(out.stdout).ok()?.trim().to_owned(); + (sha.len() >= 7 && sha.bytes().all(|b| b.is_ascii_hexdigit())).then_some(sha) +} + +/// UTC date of `SOURCE_DATE_EPOCH`, or of now. +fn today() -> Option { + let secs = match std::env::var("SOURCE_DATE_EPOCH") { + Ok(v) => v.trim().parse::().ok()?, + Err(_) => std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(), + }; + // Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm, proleptic Gregorian). + let z = i64::try_from(secs / 86_400).ok()? + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + Some(format!("{year:04}-{month:02}-{day:02}")) +} + +fn windows_resources() { + let mut res = winresource::WindowsResource::new(); + res.set_icon(ICON) + .set("ProductName", "TextureCraft") + .set("FileDescription", "TextureCraft command-line tool") + .set("CompanyName", "Learning Machines LLC") + .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") + .set("OriginalFilename", "texturecraft-cli.exe") + .set("InternalName", "texturecraft-cli"); + if let Err(e) = res.compile() { + if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() { + println!("cargo::error=embedding Windows resources into texturecraft-cli.exe failed: {e}"); + } else { + println!("cargo:warning=texturecraft-cli.exe built without icon/version resources: {e}"); + } + } +} diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index f15dc209..c38b323a 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -120,8 +120,18 @@ fn version() -> String { } } +/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the +/// GUI only, and a script that passes them to the CLI has the wrong program. +fn is_launch_profile_flag(arg: &str) -> bool { + arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") +} + fn main() { let args: Vec = std::env::args().skip(1).collect(); + if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) { + eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); + std::process::exit(2); + } let code = match args.first().map(String::as_str) { None => { eprint!("{USAGE}"); diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index e0c2f660..7f5ee538 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -30,7 +30,8 @@ ron = "0.12" # borderless (src/window_frame.rs; winsafe is MIT, User32 only). [target.'cfg(windows)'.dependencies] winit = { version = "0.30", default-features = false } -winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +# `shell` carries SetCurrentProcessExplicitAppUserModelID, the Nightly taskbar identity (src/process_identity.rs). +winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] } # The update helper is a copy of this program (`main`). craft-update = { workspace = true } diff --git a/apps/texturecraft/build.rs b/apps/texturecraft/build.rs index c77d91bd..9f712207 100644 --- a/apps/texturecraft/build.rs +++ b/apps/texturecraft/build.rs @@ -2,31 +2,78 @@ // // Shared by `texturecraft` and `texturecraft-cli` (whose build.rs `include!`s this file). // +// - Sets `TEXTURECRAFT_VERSION` for `env!`: the prepared Nightly feed identity when +// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1`, else the workspace package version. A Nightly build +// without a well-formed `TEXTURECRAFT_VERSION` fails rather than falling back to the Cargo +// version, so an archive can never carry the wrong identity. // - Always sets `TEXTURECRAFT_BUILD_SHA` (full git commit) and `TEXTURECRAFT_BUILD_DATE` // (`YYYY-MM-DD`, UTC) for `env!`. They come from the same-named environment variables (CI and // packaging/env.sh set them), else from `git` and the clock (`SOURCE_DATE_EPOCH` wins for // reproducible builds); either is an empty string when unknown, so source tarballs, wasm and // offline builds still compile. Without the env vars the commit is read when this script runs, // so a local build can show a stale commit; release builds always set the variable. -// - Windows targets only: embeds assets/app-icon/texturecraft.ico and VERSIONINFO into the exe. +// - Windows targets only: embeds the flavor's `assets/app-icon/*.ico` and VERSIONINFO into the exe. // A missing resource compiler is a warning, so a cross-compile still links, unless // `TEXTURECRAFT_REQUIRE_WINRES=1` (set by packaging/windows/package.ps1) makes it an error. -use std::process::Command; +#[path = "src/build_channel.rs"] +mod build_channel; -const ICON: &str = "../../assets/app-icon/texturecraft.ico"; +use std::process::Command; fn main() { println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-changed={ICON}"); - for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-changed=src/build_channel.rs"); + for icon in [build_channel::windows_icon_path(false), build_channel::windows_icon_path(true)] { + println!("cargo:rerun-if-changed={icon}"); + } + for var in [ + "TEXTURECRAFT_BUILD_SHA", + "TEXTURECRAFT_BUILD_DATE", + "TEXTURECRAFT_BUILD_CHANNEL", + "TEXTURECRAFT_VERSION", + "TEXTURECRAFT_OVERRIDE_VERSION", + "TEXTURECRAFT_REQUIRE_WINRES", + "SOURCE_DATE_EPOCH", + ] { println!("cargo:rerun-if-env-changed={var}"); } + println!("cargo:rustc-check-cfg=cfg(texturecraft_nightly_v1)"); + let nightly = match std::env::var("TEXTURECRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=texturecraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported TEXTURECRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + // `TEXTURECRAFT_VERSION` is the feed identity the workflow exports; the packaging scripts + // (packaging/env.sh, nightly-common.sh, linux/package.sh) spell the same value + // `TEXTURECRAFT_OVERRIDE_VERSION`, so both name the version the binary reports. + let requested = ["TEXTURECRAFT_VERSION", "TEXTURECRAFT_OVERRIDE_VERSION"] + .into_iter() + .find_map(|name| std::env::var(name).ok().map(|value| value.trim().to_owned()).filter(|value| !value.is_empty())); + let built_version = if nightly { + match requested { + Some(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit prepared feed identity in TEXTURECRAFT_VERSION"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=TEXTURECRAFT_VERSION={built_version}"); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - windows_resources(); + windows_resources(nightly, &built_version); } } @@ -59,17 +106,27 @@ fn today() -> Option { Some(format!("{year:04}-{month:02}-{day:02}")) } -fn windows_resources() { +fn windows_resources(nightly: bool, built_version: &str) { let name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "texturecraft".into()); - let description = if name.ends_with("-cli") { "TextureCraft command-line tool" } else { "TextureCraft 3D texture painter" }; + let description = if name.ends_with("-cli") { + if nightly { "TextureCraft Nightly command-line tool" } else { "TextureCraft command-line tool" } + } else if nightly { + "TextureCraft Nightly 3D texture painter" + } else { + "TextureCraft 3D texture painter" + }; let mut res = winresource::WindowsResource::new(); - res.set_icon(ICON) - .set("ProductName", "TextureCraft") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "TextureCraft Nightly" } else { "TextureCraft" }) .set("FileDescription", description) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") .set("OriginalFilename", &format!("{name}.exe")) .set("InternalName", &name); + if nightly { + // The Launcher checks the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", built_version); + } if let Err(e) = res.compile() { if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() { println!("cargo::error=embedding Windows resources into {name}.exe failed: {e}"); diff --git a/apps/texturecraft/src/build_channel.rs b/apps/texturecraft/src/build_channel.rs new file mode 100644 index 00000000..ebfc4a2a --- /dev/null +++ b/apps/texturecraft/src/build_channel.rs @@ -0,0 +1,62 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +//! +//! `build.rs` includes this file (`#[path = "src/build_channel.rs"]`) and the app compiles it for +//! the same checks, so the icon and the version shape cannot drift apart between them. + +/// `X.Y.Z-nightly.YYYYMMDD...g`, the Launcher's immutable feed identity. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} + +/// The Windows icon embedded in the executable: the nightly art only in a nightly build. +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/texturecraft-nightly.ico" } else { "../../assets/app-icon/texturecraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/texturecraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/texturecraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345")); + for invalid in [ + "", + "0.23.1", + "0.23.1-nightly", + "0.23.1-nightly.20261120", + "0.23.1-nightly.20261120.17.1.gABCDEF012345", + "0.23.1-nightly.20261120.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.23.1-nightly.20261120.1.1.gabcdef012345", + "0.23.1-nightly.20261120.1.1.gabcdef012345/other", + "0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs new file mode 100644 index 00000000..294f1e19 --- /dev/null +++ b/apps/texturecraft/src/build_flavor.rs @@ -0,0 +1,94 @@ +//! The build-time channel, which is distinct from a launch selector: no runtime environment can +//! promote a stable build into the Nightly one. + +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +/// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). +pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +/// The version this binary was built as: the prepared feed identity in a nightly build, else the +/// workspace version (`build.rs` bakes it so both flavors read it the same way). +pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); + +/// A nightly build starts only with its profile, and a stable build only without one. +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), + _ => Ok(()), + } +} + +/// A refused nightly start explains itself in a native dialog: a release Windows build has no +/// console, and a Dock launch on macOS has none either. +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +/// `--version` or `-V` alone; a file called `--version` after `--` is never a query. +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +/// The line `--version` prints: ` (nightly-v1)` in a nightly build, exactly as the +/// Launcher and the release smoke test read it. +pub fn version(flavor: BuildFlavor) -> String { + match flavor { + BuildFlavor::Stable => format!("TextureCraft {BUILT_VERSION}"), + BuildFlavor::NightlyV1 => format!("TextureCraft {BUILT_VERSION} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + + #[test] + fn the_nightly_version_line_is_exact_and_says_its_channel() { + let nightly = version(BuildFlavor::NightlyV1); + assert!(nightly.starts_with("TextureCraft "), "{nightly}"); + assert!(nightly.ends_with(" (nightly-v1)"), "{nightly}"); + assert_eq!(nightly, format!("TextureCraft {} (nightly-v1)", BUILT_VERSION)); + assert_eq!(version(BuildFlavor::Stable), format!("TextureCraft {BUILT_VERSION}")); + } + + #[test] + fn only_a_bare_version_flag_is_a_query() { + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&["--version".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs new file mode 100644 index 00000000..84f5061f --- /dev/null +++ b/apps/texturecraft/src/launch_profile.rs @@ -0,0 +1,217 @@ +//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. +//! Stable launches keep their arguments and directory policy unchanged, and no environment is +//! mutated: the profile is a value this process reads, not a variable it exports. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +static PROFILE: OnceLock = OnceLock::new(); + +pub fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a +/// file, even when it looks like a profile flag. No filesystem or startup hook runs here. +pub fn parse(args: Vec) -> Result { + let mut selector = None; + let mut root = None; + let mut other = Vec::new(); + let mut files = Vec::new(); + let mut iter = args.iter(); + let mut delimiter = false; + while let Some(arg) = iter.next() { + if arg == "--" { + delimiter = true; + files.extend(iter.cloned()); + break; + } + if arg == "--launch-profile" || arg == "--profile-root" { + let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; + if slot.is_some() { + return Err("the profile selector and root must each occur exactly once".into()); + } + let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; + if value.to_string_lossy().starts_with("--") { + return Err("the profile selector/root needs a value".into()); + } + *slot = Some(value.clone()); + } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { + return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); + } else { + other.push(arg.clone()); + } + } + match (selector, root) { + (None, None) => Ok(Launch { profile: Profile::Stable, args }), + (Some(version), Some(root)) if version == VERSION => { + if !delimiter || !other.is_empty() { + return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); + } + let root = PathBuf::from(root); + if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { + return Err("the nightly profile root must be absolute and contain no parent traversal".into()); + } + Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + } + (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), + _ => Err("--launch-profile and --profile-root must be supplied together".into()), + } +} + +/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), +/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never +/// validated or touched, and `-- --version` stays a file name. +pub fn version_query(args: &[OsString]) -> bool { + let Some((last, pair)) = args.split_last() else { return false }; + if last != "--version" && last != "-V" { + return false; + } + let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); + matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old directory resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(validate(root)?); + } + Ok(launch) +} + +/// Resolve the selected private root before the caller's first startup effect. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + } + + #[test] + fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "model with spaces.glb"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + ] { + assert!(parse(argv.clone()).is_err(), "{argv:?}"); + } + } + + #[test] + fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { + let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; + let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + for argv in [ + args(&["--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 7787e1cf..349b9275 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -5,11 +5,22 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(test)] +mod build_channel; +mod build_flavor; mod control_server; mod gpu; +mod launch_profile; +mod nightly_session; +mod process_identity; +mod profile_root; mod window_frame; +use std::ffi::OsString; + +use launch_profile::Profile; use texturecraft_engine::Session; +use texturecraft_ui_egui::os_window::{self, LaunchIdentity}; use texturecraft_ui_egui::titlebar::TitleBar; use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; @@ -17,14 +28,25 @@ use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). const APP_NAME: &str = "TextureCraft"; +/// The data folder Dylan's #801 packaging lets a Stable wrapper set. A Nightly launch never reads +/// it: its profile arrives as the Launcher's literal selector/root pair, and nothing else. +const DATA_DIR_ENV: &str = "TEXTURECRAFT_DATA_DIR"; + /// The window's size when it opens, in points. const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0]; /// The smallest size the window can be resized to, in points. const MIN_SIZE: [f32; 2] = [960.0, 600.0]; const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); +/// The Nightly window icon: the same artwork on the deeper background the package icon uses. +const NIGHTLY_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/texturecraft-nightly.png"); +/// The version line: a Nightly build names its exact feed identity and channel, and every other +/// build keeps the workspace version with the commit and date it was built from. fn version() -> String { + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { + return build_flavor::version(build_flavor::COMPILED); + } let sha = env!("TEXTURECRAFT_BUILD_SHA"); let short = sha.get(..7).unwrap_or(sha); let date = env!("TEXTURECRAFT_BUILD_DATE"); @@ -44,15 +66,23 @@ struct Args { power_pref: Option, } -fn parse_args() -> Result, String> { - parse_args_from(std::env::args().skip(1)) -} - fn parse_args_from>(it: I) -> Result, String> { let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; let mut it = it.into_iter(); + // Everything after `--` is a file, even when it looks like an option: the Launcher's nightly + // protocol passes the selected file that way (and a file may be called `--version`). + let mut after_delimiter = false; while let Some(a) = it.next() { + if after_delimiter { + // A Launcher hand-off may carry more than one file. Opening the first one beats a + // silent exit on a Windows build, which has no console to show the refusal on. + if args.file.is_none() { + args.file = Some(a); + } + continue; + } match a.as_str() { + "--" => after_delimiter = true, "--version" | "-V" => { println!("{}", version()); return Ok(None); @@ -119,7 +149,8 @@ fn initial_session(args: &Args) -> Session { } fn icon() -> Option { - let img = craft_image_codecs::decode(ICON_PNG).ok()?; + let png = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { NIGHTLY_ICON_PNG } else { ICON_PNG }; + let img = craft_image_codecs::decode(png).ok()?; Some(egui::IconData { rgba: img.to_rgba8(), width: img.width(), height: img.height() }) } @@ -134,13 +165,39 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } +/// Directory for saved settings, UI state, and error logs: a Nightly launch's validated profile, +/// else `TEXTURECRAFT_DATA_DIR` (when non-empty, as a Stable package wrapper sets it), else +/// eframe's own folder for this app. +fn storage_dir() -> Option { + settings_folder( + launch_profile::current().root(), + std::env::var_os(DATA_DIR_ENV).filter(|v| !v.is_empty()).map(std::path::PathBuf::from), + eframe::storage_dir(APP_NAME), + ) +} + +/// The settings folder, in the order a launch decides it: a Nightly profile, a Stable wrapper's +/// `TEXTURECRAFT_DATA_DIR`, else eframe's own folder for this app. +/// +/// The last one is passed in rather than left to eframe. With `with_app_id` set (the Linux window +/// class the Stable entry needs), eframe derives its folder from the app id, so Stable's `app.ron` +/// — window state and the user's export presets — would move to `ai.storyteller.texturecraft` while +/// `ui.json` and `errors.log` stayed behind. `persistence_path` therefore names the file explicitly. +fn settings_folder( + profile: Option<&std::path::Path>, + wrapper_dir: Option, + legacy: Option, +) -> Option { + profile.map(std::path::Path::to_path_buf).or(wrapper_dir).or(legacy) +} + /// Preferences needed before opening the initial project or window, with legacy storage fallback. fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs { if let Some(ui) = ui_file.and_then(ui_state_store::read) { return ui.prefs; } - 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 file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| storage_dir().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()).map(|ui| ui.prefs).unwrap_or_default() @@ -151,6 +208,10 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std: struct Shell { app: TextureCraftApp, window_frame: Option, + /// Runs once when the window closes. On macOS that is the only place a clean quit is handled: + /// Cmd+Q ends the process inside AppKit's terminate, after eframe's `on_exit` and before + /// `eframe::run_native` returns, so the Nightly session record is finished here, not there. + exit_hook: Option>, #[cfg(target_os = "macos")] movable: Option, } @@ -183,6 +244,12 @@ impl eframe::App for Shell { #[cfg(target_os = "macos")] texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable); } + + fn on_exit(&mut self) { + if let Some(hook) = self.exit_hook.take() { + hook(); + } + } } /// A script driving the app gets no network check and no update prompt over its window. @@ -190,20 +257,97 @@ fn checks_for_updates_at_start(control: Option) -> bool { control.is_none() } +/// The AppUserModelID a Nightly window is grouped under, set before any native window exists. +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1)) +} + +/// A refused Nightly start explains itself in a dialog where there is a desktop to show one. +fn report_launch_profile_error(error: &str) { + eprintln!("texturecraft: {error}"); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("texturecraft: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title(os_window::name_for(LaunchIdentity::NightlyV1)) + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile before any startup service or side effect, and answer the +/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the +/// launch is already answered and the process returns. +fn prepare_launch() -> Option> { + let argv: Vec = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: both are answered here, with nothing but standard output written. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; + if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + report_launch_profile_error(&error); + std::process::exit(2); + } + if let Profile::NightlyV1(root) = launch_profile::current() { + // Every data folder follows the profile before the first one is used. + texturecraft_ui_egui::set_data_root(root.clone()); + texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); + } + Some(early.args) +} + +/// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value +/// that is not valid Unicode is refused rather than silently replaced. +fn launch_arguments(arguments: Vec) -> Result, String> { + arguments.into_iter().map(|value| value.into_string().map_err(|_| "an argument is not valid Unicode".to_string())).collect() +} + fn main() { - // Windows: the update helper is a copy of this program started with `--finish-update` + // Windows: the update helper is a copy of this program started with `--finish-update`. A + // Nightly install is updated by ArtCraft Launcher, so it never installs an update itself. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable + && let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { std::process::exit(i32::from(result.is_err())); } - // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument + // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with + // its own argument. It reads no user state and is started without the profile tokens, so it + // runs before the launch protocol would refuse it. #[cfg(windows)] if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) { std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer()); } - let args = match parse_args() { + let Some(arguments) = prepare_launch() else { return }; + let nightly = launch_profile::current().is_nightly(); + let args = match launch_arguments(arguments).and_then(parse_args_from) { Ok(Some(a)) => a, Ok(None) => return, Err(e) => { @@ -211,6 +355,12 @@ fn main() { std::process::exit(2); } }; + // The control server is a stable-install service: a Nightly window is driven by the Launcher, + // and its token file would sit in the shared temp folder rather than its private profile. + if nightly && args.control.is_some() { + eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli"); + std::process::exit(2); + } // 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()); @@ -221,11 +371,13 @@ fn main() { previous_hook(info); })); - // Scripted runs use temporary files so they cannot overwrite saved settings - let persistence_path = + // Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe + // is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the + // folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`). + let no_prefs_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - 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"))); + let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron"))); + let ui_file = no_prefs_path.as_ref().map(|path| path.with_extension("json")).or_else(|| storage_dir().map(|folder| folder.join("ui.json"))); if let Some(file) = &ui_file { let _ = ui_state_store::FILE.set(file.clone()); } @@ -236,7 +388,11 @@ fn main() { prefs.apply_resource_limits(); let session = initial_session(&args); let title_bar = TitleBar::decide(prefs.system_title_bar); - let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); + let mut viewport = egui::ViewportBuilder::default() + .with_app_id(os_window::app_id()) + .with_title(os_window::name()) + .with_inner_size(DEFAULT_SIZE) + .with_min_inner_size(MIN_SIZE); if let Some(i) = icon() { viewport = viewport.with_icon(i); } @@ -247,8 +403,34 @@ fn main() { std::process::exit(2); } let control = args.control; + // The Nightly session record: one owner per profile, an unclean exit reported by the next + // start, and no document name, path or diagnostic payload collected. + let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health( + launch_profile::current().root(), + build_flavor::BUILT_VERSION, + Some(env!("TEXTURECRAFT_BUILD_SHA")), + ) { + Ok(state) => state, + Err(error) => { + log::warn!("Nightly session health is unavailable: {error}"); + (None, true) + } + }; + let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean); + // Set once a window has posted the interruption notice; until then the record must survive. + let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let notice_shown_in_window = unclean_notice_shown.clone(); + let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session)); + // The exit hook is the controlled return on macOS, where every quit ends the process inside + // AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes. + let finish_at_exit = { + let shared = nightly_session.clone(); + let shown = unclean_notice_shown.clone(); + move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed)) + }; + let window_name = os_window::name(); let result = eframe::run_native( - APP_NAME, + window_name, options, Box::new(move |cc| { #[cfg(windows)] @@ -258,7 +440,7 @@ fn main() { // winit's Quit ends the process without asking; this menu's asks like the close button #[cfg(target_os = "macos")] - if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { + if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) { log::warn!("the app menu could not be installed: {e}"); } let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); @@ -268,14 +450,27 @@ fn main() { if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } + if previous_nightly_unclean || session_health_warning { + use texturecraft_ui_egui::i18n::tr; + app.banner = Some(if previous_nightly_unclean { + tr("The previous TextureCraft Nightly session did not finish normally. No diagnostics have been sent.") + } else { + tr("TextureCraft Nightly could not record session health in its profile; abnormal-exit detection is unavailable.") + }); + notice_shown_in_window.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed); + } Ok(Box::new(Shell { app, window_frame, + exit_hook: Some(Box::new(finish_at_exit)), #[cfg(target_os = "macos")] movable: None, })) }), ); + // A controlled return, including a handled startup error. On macOS a window already finished in + // its exit hook, so this is then a no-op. + nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed)); if let Err(e) = result { fatal(&e.to_string(), true); std::process::exit(1); @@ -284,7 +479,7 @@ fn main() { /// The file startup errors and crashes are appended to, beside the saved settings. fn error_log() -> Option { - eframe::storage_dir(APP_NAME).map(|d| d.join("errors.log")) + storage_dir().map(|d| d.join("errors.log")) } /// Append a line with the time (Unix seconds) and the app version; true when it was written. @@ -305,7 +500,7 @@ fn fatal(msg: &str, dialog: bool) { let saved = log.map(|f| format!("\n\n{}", trf("Details saved to {file}", &[("file", &f.display())]))).unwrap_or_default(); rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Error) - .set_title(APP_NAME) + .set_title(os_window::name()) .set_description(format!("{}\n\n{msg}{saved}", tr("TextureCraft had to close:"))) .set_buttons(rfd::MessageButtons::Ok) .show(); @@ -330,6 +525,55 @@ mod tests { assert_eq!(args.gpu.as_deref(), Some("3080")); } + #[test] + fn stable_settings_stay_in_the_folder_eframe_used_before_the_app_id() { + let legacy = std::path::PathBuf::from("/legacy/TextureCraft"); + // Stable, no wrapper folder: the folder eframe picked for `APP_NAME` before `with_app_id` + // existed, so `app.ron` (window state and the export presets stored in it) does not move. + let folder = settings_folder(None, None, Some(legacy.clone())).expect("a legacy folder"); + assert_eq!(folder.join("app.ron"), legacy.join("app.ron")); + // A Stable wrapper's data folder still wins, which is what #801's packaging expects. + let wrapper = std::path::PathBuf::from("/wrapper/data"); + assert_eq!(settings_folder(None, Some(wrapper.clone()), Some(legacy.clone())), Some(wrapper.clone())); + // A Nightly profile wins over both, so no Stable folder is ever read. + assert_eq!(settings_folder(Some(std::path::Path::new("/profile")), Some(wrapper), Some(legacy)), Some(std::path::PathBuf::from("/profile"))); + // Nothing resolvable: there is no folder to fall back to and eframe keeps its own default. + assert_eq!(settings_folder(None, None, None), None); + // The app's wiring: with no profile and no wrapper folder, `app.ron` sits beside `ui.json` + // in eframe's folder for `APP_NAME`, not in the folder of the app id `with_app_id` sets. + if std::env::var_os(DATA_DIR_ENV).is_none() + && !launch_profile::current().is_nightly() + && let Some(stable) = eframe::storage_dir(APP_NAME) + { + assert_eq!(storage_dir(), Some(stable.clone())); + assert_eq!(storage_dir().map(|dir| dir.join("app.ron")), Some(stable.join("app.ron"))); + } + } + + #[test] + fn a_file_after_the_delimiter_is_a_file_even_when_it_looks_like_an_option() { + let args = parse_args_from(["--".to_string(), "--version".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--version")); + let args = parse_args_from(["--".to_string(), "--launch-profile".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--launch-profile")); + // Options before the delimiter still parse as options. + let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string(), "--".to_string(), "a.glb".to_string()]).unwrap().unwrap(); + assert_eq!((args.gpu.as_deref(), args.file.as_deref()), (Some("nvidia"), Some("a.glb"))); + // One window opens one project: extra files after the delimiter are ignored, in that order. + let args = parse_args_from(["--".to_string(), "a.glb".to_string(), "b.glb".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("a.glb")); + } + + #[test] + fn launch_arguments_refuse_a_name_that_is_not_unicode() { + assert_eq!(launch_arguments(vec![OsString::from("--version")]).unwrap(), vec!["--version".to_string()]); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt as _; + assert!(launch_arguments(vec![OsString::from_vec(vec![b'a', 0xff, b'b'])]).is_err()); + } + } + #[test] fn rejects_missing_or_invalid_gpu_args() { assert!(parse_args_from(["--gpu".to_string()]).is_err()); @@ -410,6 +654,7 @@ mod tests { let mut harness = builder.build_eframe(|cc| Shell { app: TextureCraftApp::new(cc, session), window_frame: None, + exit_hook: None, #[cfg(target_os = "macos")] movable: None, }); diff --git a/apps/texturecraft/src/nightly_session.rs b/apps/texturecraft/src/nightly_session.rs new file mode 100644 index 00000000..a1f2dee5 --- /dev/null +++ b/apps/texturecraft/src/nightly_session.rs @@ -0,0 +1,277 @@ +//! App-private Nightly session health, not telemetry and not a Launcher protocol. +//! +//! A live owner holds a separate persistent lease; a secondary launch never rewrites its record. +//! Dropping the guard does not clear the marker; only the app's controlled return path does. + +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Write `bytes` to `path` without ever following a link at the destination: the temporary file is +/// created exclusively beside it and renamed over the name, which replaces a link rather than +/// writing through it (the engine's `write_atomic` deliberately resolves the target instead). +fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| io::Error::other("the Nightly record has no folder"))?; + let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| io::Error::other("the Nightly record name is not Unicode"))?; + let temporary = parent.join(format!(".{name}.{}.tmp", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let staged = write_staged(&mut options, &temporary, bytes).and_then(|()| std::fs::rename(&temporary, path)); + if let Err(error) = staged { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + // The rename is durable only once its folder is synced (no-op where the platform has no handle). + #[cfg(unix)] + if let Ok(folder) = File::open(parent) { + let _ = folder.sync_all(); + } + Ok(()) +} + +/// Write the whole file and flush it to the device before it may replace the destination. +fn write_staged(options: &mut std::fs::OpenOptions, temporary: &Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write as _; + let mut file = options.open(temporary)?; + file.write_all(bytes)?; + file.sync_all() +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and +/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path +/// still runs for a start that created no window. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, while + /// Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is Stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit.filter(|value| !value.is_empty()), + }))?; + write_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + /// Controlled return. If an earlier session's interruption was detected but no window showed it + /// yet, the record is left for the next owner to report; otherwise this is [`Self::complete`]. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// A handled startup error is a controlled return too. An unwind, abort, forced exit or killed + /// process never calls this method. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = std::env::temp_dir().join(format!("texturecraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The next start still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_hook_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + // The exit hook (macOS quit: the only path that runs there). + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit"); + // Elsewhere the return path runs too, by then possibly after a successor took the profile. + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } +} diff --git a/apps/texturecraft/src/process_identity.rs b/apps/texturecraft/src/process_identity.rs new file mode 100644 index 00000000..f9ef611e --- /dev/null +++ b/apps/texturecraft/src/process_identity.rs @@ -0,0 +1,78 @@ +//! Set the immutable Nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so MSI shortcut +//! matching keeps working. + +use std::fmt; +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityError(pub String); + +impl fmt::Display for IdentityError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for IdentityError {} + +/// The AppUserModelID the taskbar groups the Nightly window under, distinct from Stable's. +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs new file mode 100644 index 00000000..71265909 --- /dev/null +++ b/apps/texturecraft/src/profile_root.rs @@ -0,0 +1,489 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! +//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error +//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export +//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the +//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, +//! or when it is not writable. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +/// The folder names the launch checks use for this app in each platform's location. +const BRAND: &str = "TextureCraft"; +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that +/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; +/// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder +/// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. +const LINUX_STORAGE_BRAND: &str = "texturecraft"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + Linux, + Mac, +} + +impl Platform { + fn current() -> Result { + match std::env::consts::OS { + "windows" => Ok(Self::Windows), + "linux" => Ok(Self::Linux), + "macos" => Ok(Self::Mac), + _ => Err("nightly-v1 is not defined for this operating system".into()), + } + } + + fn ignores_case(self) -> bool { + self != Self::Linux + } +} + +fn absolute(path: PathBuf, label: &str) -> Result { + if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(format!("{label} must be absolute and contain no parent traversal")); + } + Ok(path) +} + +fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { + let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; + absolute(PathBuf::from(value), key) +} + +fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { + match env(key).filter(|v| !v.is_empty()) { + Some(value) => absolute(PathBuf::from(value), key), + None => Ok(required_base(env, "HOME")?.join(fallback)), + } +} + +/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor +/// is not a missing directory that may be replaced or followed later. +fn canonical_future(path: &Path) -> Result { + let mut parent = path; + let mut missing = Vec::new(); + loop { + match std::fs::symlink_metadata(parent) { + Ok(_) => break, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); + parent = parent.parent().ok_or("the profile root has no existing ancestor")?; + } + Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), + } + } + let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; + for part in missing.into_iter().rev() { + resolved.push(part); + } + Ok(resolved) +} + +/// Whether one path is the other or contains it (in either direction), compared component by +/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not +/// inside `TextureCraft`. +fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { + let parts = |p: &Path| { + p.components() + .map(|c| { + let value = c.as_os_str().to_string_lossy().into_owned(); + if platform.ignores_case() { value.to_lowercase() } else { value } + }) + .collect::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +/// The running install: never let the profile live inside it (it would be replaced or removed by +/// the next update). +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + let parent = exe.parent().ok_or("cannot establish the installation boundary")?; + if platform == Platform::Mac { + // A profile in Resources is still inside the versioned bundle, not beside MacOS. + if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { + return Ok(bundle.to_path_buf()); + } + } + Ok(parent.to_path_buf()) +} + +/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it +/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. +fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { + let home = match platform { + Platform::Windows => required_base(env, "USERPROFILE")?, + _ => required_base(env, "HOME")?, + }; + Ok(home.join("Documents").join(BRAND)) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's + // per-machine and any per-user install folders. A custom install folder is covered by the + // executable's own folder below. + let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = env(key).filter(|v| !v.is_empty()) { + roots.push(absolute(PathBuf::from(base), key)?.join(BRAND)); + } + } + roots + } + Platform::Linux => { + // The four XDG roots carry eframe's settings, caches and state under the app's name. + let mut roots = + [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] + .into_iter() + .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND))) + .collect::, _>>()?; + // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, + // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. + roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + // The stable Flatpak keeps its own per-app data folder. + roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support").join(BRAND), + library.join("Caches").join(BRAND), + library.join("Caches").join(STABLE_ID), + library.join("Preferences").join(BRAND), + library.join("Preferences").join(format!("{STABLE_ID}.plist")), + library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), + home.join("Applications").join(format!("{BRAND}.app")), + PathBuf::from("/Applications").join(format!("{BRAND}.app")), + ] + } + }; + // The user's own documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + roots.push(default_data_folder(platform, env)?); + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +/// An entry inside the profile must resolve inside it, so a link planted there cannot point +/// Nightly's writes at another app's files. +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; + let child = canonical_future(&chosen.join(name))?; + if child == chosen || !child.starts_with(&chosen) { + return Err(format!("the nightly {label} must stay inside its selected profile")); + } + Ok(child) +} + +/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve +/// inside it. +fn entries_stay_inside(root: &Path) -> Result<(), String> { + let entries = match std::fs::read_dir(root) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), + }; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + private_subdirectory(root, entry.file_name(), "profile entry")?; + } + Ok(()) +} + +/// The app's writable probe: create a file exclusively in the profile and remove it again. +pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { + let probe = dir.join("exclusive-write-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe) +} + +/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only +/// access where the platform has it, and return the resolved root to use. +pub fn validate( + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + absolute(root.to_path_buf(), "the nightly profile root")?; + // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must + // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its + // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) + && id != NIGHTLY_ID + { + return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + } + let chosen = canonical_future(root)?; + let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err("the nightly root must not overlap stable data or an installation".into()); + } + // Existing aliases under the profile must not redirect any of its folders elsewhere. + entries_stay_inside(&chosen)?; + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + entries_stay_inside(&confirmed)?; + writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = + std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + }; + let home = root.join("home"); + let exe = root.join("install/texturecraft"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"fixture executable, never run").unwrap(); + let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + + fn profile(&self, name: &str) -> PathBuf { + self.root.join("profiles").join(name) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory this fixture created is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn a_fresh_private_profile_is_created_and_returned_resolved() { + let fixture = Fixture::new(); + let profile = fixture.profile("nightly"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert_eq!(fixture.check(platform, &profile).unwrap(), profile); + assert!(profile.is_dir()); + std::fs::remove_dir_all(&profile).ok(); + } + } + + #[test] + fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { + let fixture = Fixture::new(); + let home = fixture.home(); + let candidates: Vec<(Platform, PathBuf)> = vec![ + (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), + (Platform::Windows, home.join("Documents").join(BRAND)), + (Platform::Linux, home.join(".config").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), + (Platform::Linux, home.join(".cache").join(BRAND)), + (Platform::Linux, home.join(".local/state").join(BRAND)), + (Platform::Linux, home.join("Documents").join(BRAND)), + (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), + (Platform::Linux, PathBuf::from("/opt/texturecraft")), + (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), + (Platform::Mac, home.join("Library/Application Support").join(BRAND)), + (Platform::Mac, home.join("Library/Caches").join(BRAND)), + (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), + (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), + (Platform::Mac, home.join("Documents").join(BRAND)), + (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), + ]; + for (platform, stable) in candidates { + for candidate in [stable.clone(), stable.join("nested nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "{platform:?} accepted {}", candidate.display()); + assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); + } + } + } + + #[test] + fn the_running_install_is_fenced_on_every_platform() { + let fixture = Fixture::new(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + let inside = fixture.exe.parent().unwrap().join("profile"); + assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); + } + } + + #[test] + fn lookalike_names_are_not_overlaps_but_case_folding_is() { + let fixture = Fixture::new(); + let documents = fixture.home().join("Documents"); + assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); + assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); + for platform in [Platform::Windows, Platform::Mac] { + assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); + } + } + + #[test] + fn relative_parent_traversal_and_empty_roots_are_refused() { + let fixture = Fixture::new(); + for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { + assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); + } + } + + #[test] + fn only_the_nightly_flatpak_may_start_with_its_own_id() { + let fixture = Fixture::new(); + let profile = fixture.profile("flatpak"); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + std::fs::remove_dir_all(&profile).ok(); + let check_with = |id: &str, candidate: &Path| { + let id = OsString::from(id); + validate_for( + Platform::Linux, + candidate, + |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, + Some(&fixture.exe), + ensure_writable, + ) + }; + // Stable's id, its window id and an unrelated app's id are all refusals. + for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { + assert!(check_with(id, &profile).is_err(), "{id} was accepted"); + } + // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the + // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). + let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); + let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); + assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); + std::fs::remove_dir_all(&sandbox).ok(); + } + + #[test] + #[cfg(unix)] + fn an_entry_that_leaves_the_profile_is_refused() { + let fixture = Fixture::new(); + let profile = fixture.profile("aliased"); + let outside = fixture.root.join("somewhere else"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); + // A dangling link is not a missing folder that may be created. + std::fs::remove_file(profile.join("autosave")).unwrap(); + std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err()); + std::fs::remove_file(profile.join("logs")).unwrap(); + // A plain folder inside it is fine. + std::fs::create_dir(profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + } + + #[test] + fn a_failed_write_probe_never_falls_back_to_stable() { + let fixture = Fixture::new(); + let profile = fixture.profile("read only"); + let reached = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &profile, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + reached.set(true); + Err(std::io::Error::other("read-only filesystem")) + }, + ); + assert!(result.is_err()); + assert!(reached.get()); + assert!(result.unwrap_err().contains("not writable")); + // The app must not then use the stable folder: it simply refuses to start. + assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); + } + + #[test] + #[cfg(unix)] + fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { + let fixture = Fixture::new(); + let real = fixture.root.join("real profiles"); + std::fs::create_dir_all(&real).unwrap(); + let link = fixture.root.join("linked"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + // A link to a private folder is fine, and the resolved root is what the app uses. + let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); + assert_eq!(resolved, real.join("nightly")); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 07351074..38a8538c 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -57,3 +57,23 @@ pillow and potracer): OPT=0.4 DP=1 python3 vectorize_tile.py source.png '#c2672b' 2048 2 texturecraft.svg OPT=1.0 DP=0 python3 vectorize_tile.py source.png '#c2672b' 1024 4 texturecraft-small.svg ``` + +## Nightly icon + +The Nightly build ships the same engraving on a deeper copper field (`#643418`): the background +contribution of each pixel is replaced and the ink, paper and alpha padding are left exactly as +they are. No badge, crescent or letter is added, so the two icons differ only in the field. + +| File | What | +|---|---| +| `texturecraft-nightly.png` | 256 px window icon (`apps/texturecraft/src/main.rs`) | +| `texturecraft-nightly-1024.png` | full tile, 1024 px (docs) | +| `texturecraft-nightly.icns` | macOS icon set, the stable `.icns`'s own PNG slots recoloured | +| `texturecraft-nightly.ico` | Windows icon, the stable `.ico`'s own frames (16 to 256 px) recoloured | +| `nightly/.png` | per-size renders for the Nightly package and the title bar's icon in a Nightly window (16 to 512 px). Kept out of `hicolor/`, which Stable's Linux and FreeBSD packagers copy whole | +| `nightly-provenance.json` | the inputs, the palette, the transform and the SHA-256 of every output | + +`packaging/nightly-icons.py` derives all of them from the committed stable renders (no upscale, no +resvg, no Pillow): run it after `packaging/icons.sh` changes a stable file, and +`python3 packaging/nightly-icons.py --check` (part of `packaging/nightly-tests.py`) fails when a +committed Nightly file has drifted. diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 00000000..b9c4fc52 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,81 @@ +{ + "title": "TextureCraft nightly deep-background icons", + "license": "MIT OR Apache-2.0", + "generator": "packaging/nightly-icons.py", + "generator_sha256": "745786e3bfbecf29077df1e4a64ed717953694038f95533d2d37507c520b791c", + "inputs": [ + { + "path": "assets/app-icon/texturecraft.icns", + "sha256": "eb5e1b19679aa9a23531219d92922e37edbdc3e2046454b8f6c64423f471b57b" + }, + { + "path": "assets/app-icon/texturecraft.ico", + "sha256": "9c3366e4af9f2c0772e00193c348feba834d407fc8b826d4276a8fcb4cc01dcb" + }, + { + "path": "assets/app-icon/texturecraft-1024.png", + "sha256": "8451f91be8c1bc9c2e1a594e193ae5d1793d2d12f26a8bc64d2bd83fe4b789e4" + }, + { + "path": "assets/app-icon/hicolor/16x16/apps/ai.storyteller.texturecraft.png", + "sha256": "79ee309754be54b56052ab05fff87a2427bbc38bb057c96094f8f070ee13ca1d" + }, + { + "path": "assets/app-icon/hicolor/24x24/apps/ai.storyteller.texturecraft.png", + "sha256": "f8f89220ce68be236d63edfd94d4fef2aad2aa9840a50e430f874649a9816171" + }, + { + "path": "assets/app-icon/hicolor/32x32/apps/ai.storyteller.texturecraft.png", + "sha256": "ff8578ffc95f5123bb2e4a00636080f02adf259334ecb0ac9f952fac3378ddb2" + }, + { + "path": "assets/app-icon/hicolor/48x48/apps/ai.storyteller.texturecraft.png", + "sha256": "f7f19ffbd8904ff462bc6d785b865153112025bbdeb868bc0f136e39c7d725e1" + }, + { + "path": "assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png", + "sha256": "39d17421579ace5dbe4705fb0a52cd6002d433ded7ba0ee2fdeb5d6d7cd16c8c" + }, + { + "path": "assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png", + "sha256": "ac629a038a215a13d86172286142502b6efd17618869652050f291d9745346d2" + }, + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png", + "sha256": "757f858b26897cb0e9f0c8cd43db9ade9664dd6199bd190d1af406839769c71f" + }, + { + "path": "assets/app-icon/hicolor/512x512/apps/ai.storyteller.texturecraft.png", + "sha256": "705513dc82aa908f962b9a466743b42e53b0f586752d2d69a5b6596b8ff928f0" + } + ], + "method": { + "kind": "derivative of the project-owned stable renders; no badge, crescent or letter", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#c2672b" + }, + "nightly_background": "#643418", + "transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling." + }, + "outputs": { + "assets/app-icon/texturecraft-nightly.icns": "e21e2c90f7402e6289038ad7db896a14780766e07f33d9cb68cbe0d423efe66d", + "assets/app-icon/texturecraft-nightly.ico": "b0dc8817a3b07f0eb8175241c1fdc1ce21ffb8d5a54e6b03979ba2f73e62d47e", + "assets/app-icon/nightly/16.png": "657c7a39547828b0eaafe4b78df28771bb953afdb62440d0c001c695ff586e76", + "assets/app-icon/nightly/24.png": "b4c263436402faa93276b77614291107f6b44309ccfe329b71c3562c1f382c11", + "assets/app-icon/nightly/32.png": "cefb99a330d103f32a07d07e49542da2231897224a3dfe479e9c9d4a53a0a17b", + "assets/app-icon/nightly/48.png": "126316a058f4a225fbea7e1c0e49dc3d27941e2a91a7f033f35b84bc6d646f22", + "assets/app-icon/nightly/64.png": "d471a4bd691fca348603571bfe9c05357120e492566e31c7b2c936361a4a2510", + "assets/app-icon/nightly/128.png": "b36b07739b98b7884ce308641407725bb499adfefd87a4286c3aa117abdb57d5", + "assets/app-icon/nightly/256.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2", + "assets/app-icon/nightly/512.png": "de756e67f16076a08cb5c2726d1a63181a0a8b61c73ff3df0cf49e065f1c8bc2", + "assets/app-icon/texturecraft-nightly-1024.png": "509ebc6130db6c10c380bc4ee2280a6b1810eea5dc03293b86a575c1ef120736", + "assets/app-icon/texturecraft-nightly.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2" + }, + "ico_frames": [ + "the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)" + ], + "icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)", + "validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole." +} diff --git a/assets/app-icon/nightly/128.png b/assets/app-icon/nightly/128.png new file mode 100644 index 0000000000000000000000000000000000000000..c220657a57c3e628ca1c6793757d8036cf46131b GIT binary patch literal 9309 zcmV-jB%<4iP)$1x#(RpX?sDNcD71Mw{6sfdO z(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AaCv)b7x37hS9vrm=*oiiIS|9Rdq`R3^ZaYI`cYay3>U-h36siSay7gAgO$J(n(sc-Su` z?1rQC@?d8@Ej=eFA_DN2gAei>BEtM;aq)NrRb7+b6Br}x_49@tDI21!7MA{xAipqc zNi01lIE>#h!V$Zi*b<;Txsl$(Qy9Ksq(mSDIL4u&6Jj|qHW&eb0RV6qHUktK zc}9Tm!RaZXO`hsafT}PPVB`C@dxk8(ettLfXAxk;T8yQbrw>8oq5)12>P}f$vW$>D z1G`&F_9l2zza@bPN*VYK5wQR`B0@GL`lFJG$%a+z}1Wy}3{5K)H~%5+M7o@iC)f=sC}z`DpM^=Qb&T z01Q$R@|ii?+$dQI){W}2vk)S zmuGy&y#T9ZZ_@gthE!)Aq`Qt$Uo7mNy&j07Qvo zBT5pP&!?5lf-o-s&P%_aMZ+^jiBckflW70dW3f8r%vt|g97fVK=cJpVfpSX;S?4HS oRLi%6eWB+UTlM06)BLyP4;qF>9$rH{(f|Me07*qoM6N<$f)Ph_h5!Hn literal 0 HcmV?d00001 diff --git a/assets/app-icon/nightly/256.png b/assets/app-icon/nightly/256.png new file mode 100644 index 0000000000000000000000000000000000000000..3ca334c3336e31f486d090605a83bb2048db2c3e GIT binary patch literal 27975 zcmWh!byO5@8=Yl=C6`W@1}PCFB$ik@l#*^F1jL`x9ZRD~iG)grbg4*phkzgw0=o#f z^e(;h$M@IFnRDjMnP=YTKKH%%&T9ibO-eFWG5`Q5wYAiq008Lr6aJ%ANth ze^6~TW#fQ_-F8&1(`owBpg*RYYB=S+d`gvFBjOQ#`QEd`(w5;zu}WQc)!!5g=oD+c zrsaDZn`tOnr{VdmPiFP0z1ozjgX1%Tx2Y5`E;0MW6^cuHgt!>OHrre)C6g1kA&AJm zd(-{HrgYoLx*;gM6Z31gt9~J!0Wyp(0)uyY{h76a4 z+@|Ty!0VH!`3=nKJvngouB^DgHCy2DsAk}dQXbQA$WEWdE$?F-6&Gl_Kim_v6zrN&~7z}v}Q(Z?_ zA!AT2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tl3mw9dFfHZ|3^=&lUJ&hMd&F`=bbAs=8B)mdLe`{gAN7h}tR>^jE%>FnZP z6Wkc-DK)r7_Ft-l?1DTP8eh9}?YQ-O*@o%2)NlRu+kXZAY(}Q?2SgdFAywX|pXD)j zuJObYboVR2Sag)SilC|YOra_Iu4{EMZweS1ux(|^Fc2Kn_j4Rq8%D?$4a1S`;qGnw z2e*@uhAZEvh>hWBz3p2mmOrT!{n({dQs9P*FbyDIknUS7t65wp9$hvsdWQTmsIPWa zPBYCZ#!sT0=M8@MX+F20tN(mZ?fkxEGkT<~3)!NY(PcMrQIgS{bH#=7D)3oT%pJpL zYlj1V zmq&F&p$&tT`OFYGI3sit(avo!oOPmaQ@;JseEZ$xF}?o1%Ec zG{LkWZW&6#gB>8e3lA_6|!A)`R{V%OfnA}(xuEKc2e>9u=y zq-d%@laJT=_bqsFEz#Y_k@Hy~d=TL7z6eOz5Q!f#ENG>Z1|?O5zzT%!PM4prM&B)NZ&yYD&HHc;t`Gbaw-V#|oN85v2yOl?i> zO9hIchprr``#nswzDG4;8!vDpS;qgPp$)XTcReq2k5EL@}`rc4p=V_ZM z@{JF*)iu^5klXxm56evwqEc95D&R_9e?|H&p1VKlCXqX6xPr5Mpa(Rg$$j&_ql9^Z0*3IYSV~5Z+G!0000P>z29 literal 0 HcmV?d00001 diff --git a/assets/app-icon/nightly/64.png b/assets/app-icon/nightly/64.png new file mode 100644 index 0000000000000000000000000000000000000000..a85b82334c52767217105fc4168d3bafe01a48de GIT binary patch literal 3194 zcmV-=42AQFP)>>Ia2LNuwbqBbAIPMS|Uv4ia>#!iA$$F-9{8C}o?g`GKw7R>I1$B!O* z;`Io7Wnv&39@v+in;6Pw#)q;kn_tSl`|VrV@R7mf0Vs1LyZ~8OyZ-JM&Nq9L^Jh+G zEC2atc5-q&4PGTgY~cIVp;wczyLN8RcD%YZ>*?u9g0n|p{^!PhP|ijGfl%U^Wzh^-;j`KmL}KfMO7wEdgbI9xvfI zUc!W=|b2t;U8>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23tF&}J_-|f4mpsbmY4Vn$&nMMop!E=LHcxwtq6gt4K4=8VPgH>37O|&t8pQf6 zSrJfr!}PZbiOme%UyyVV2*qNDSf59)ik%|UrNTQg5-~_N>3=0tF&tuhK86G1s~iFp zJ-WKu6`0~Qm~n0G4*=Q~;<{r;4}Xr1-nw+Ayr-TZand6q+wc+ZWCC=zw9(!EMl#uByR-~0f z0O}i&)(1u}5D2ljZ8FZY6n4G79AObTyqzUuS0WTWO)raB6hop>0j5HmHQckZ2hjgV zs2KYSF6WMDE^A|1Y?TQLDoeA1bXwF`_?UIHeq4OT7#c%Dk|apWFASebL?|t4K0Q{Z zu(<4voSrDNjBKqQ))-2P#Fu(liKewBI5GDd2Bts5mV3N?Y{!Gj3nd{9aqXXb z=l|pS!2NsrvNPMCPm?Fj5H0Dj6Q6oTEU?m=Pux=As&~%x&Wf2xP>)v|7L_Q!S=#*$@Z+@8(F2#h+rHs!Se#8Mw1~*lvu=_mdZA> zSejV9IQM#~eKl>IvH_TH?60@9VnZ*mH72cgQ@9AkdPhu?meXblW8UN3KdmzJ?UDT9 z%T2YzMh_$n#x~c^ZLg%8YI)xZX?DWZeqNkVVPi%qraXB^^bD)hm=X68nUa?#67;m=5EtkQR4&jZ3q0ntJ#&-|u6|n*_@lrN{xK z#BqKxa)HPb2pRi{y8qIx#q9RKzwTyXGK*uL@K6STbvUGFP6J9#(#z7#HajCNv9x z#;OD-VL{PkWgmqn1T2;sc>?$P_rD$_z{_#ze&ttZAM-lh@{-EYigHwL#Xe-7k_ze~JJJ&RB9G@T9 g`hYPq)~fFQU&8bQWl5%=TmS$707*qoM6N<$f@9wRZvX%Q literal 0 HcmV?d00001 diff --git a/assets/app-icon/texturecraft-nightly-1024.png b/assets/app-icon/texturecraft-nightly-1024.png new file mode 100644 index 0000000000000000000000000000000000000000..d43e9fbc6dfcb823980f607f60991a10e4056bf6 GIT binary patch literal 225374 zcmYg%1yodB_xGJ)C`DQt=`?7h2c)}HKuL#EKw6p^K#^`~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az`JLELsKgBTA=<}&T(E129iQU%cAbCr!uUkDK5xa9x? zVdZP`ZPDEr!Lhz)5{>}!b7XM9OpZ()RRPL5a7sA#GUap)F>Y;aJ!!QoP_?w0*)sF_lE`@{N&HKVx2F54N0{u z(o^CURhkrz-^Q^h@+Te+07HiwKx-;{-NV7dkN1RfK+=oDHm3?=mQ)=}Tt9m8l`YP2 zTe^TeSr~#-A{dZfMds^cok8A14OY4KTP#< zd$8_qF%uE(;ZDv+;2!Z0to40oOIJ!=I&~s+Mjx5)r1J%yY=Xf@k3ra3F>3Oju?vuN zHrIU(C*CY|v>boIexm_IhEco1a@(^yEw`H)lfm6SIMGq3xeaFB-{sj)?6VbnIP)Y~GAC!x=I)2l}=Uxpi+cy75%)ZM! zXdb`6hi>&I0}kUX+_F#coy3|>b~i>o7%<8LiR(w(F*UrLC?f@gI6)_!&I9Pl15z$%wTg<;>b!QA{u|JEF zsMl|&StUG$&g%Hd0G%cx*aUc&w(?^^*9if@JW))r*5bS)oY=&5{jLztl>oh;r>RQJ z4~YQ1b@T@=2$SHH2Z@{L3lsn2PZs)4v}zP@No$a@{?F&k7D%2^{5y~2x73W_kkjPG z67K<`M|Uy{NzTjQf6sK-F2ryQHqeVd|I0_b`zBe+<&K-4_sPee6Ws@}gQ^aMHCW#r z(kXLa;`TyMKA3?EMWe3g(GvR6w5b#kY*uuIfh`;`4eqtc2wQUlMaL>2I O_33CBs8`>!3;TcZs!Y@X literal 0 HcmV?d00001 diff --git a/assets/app-icon/texturecraft-nightly.ico b/assets/app-icon/texturecraft-nightly.ico new file mode 100644 index 0000000000000000000000000000000000000000..9d1f3eb32d7c5b6b6a4f2f6e42ab7a343b604ac8 GIT binary patch literal 47362 zcmagEWl-K+*9Mv!*W&K(R@^D>P~71LiaQi{cP;LP;_mKR+}$Zw+?~_&KIi9|`7)E) zxw0}@nOWD;9RL6U@Bk_*@NXpr_CWxU0ssIe=6~1#0suV!ow&IFVR}daScU=sQquo$ z{J(1mH~^rf{SQ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=~t<`SW!O^3rop z4>Ke+B=(gH9~rxsKc5Z12^QY|&deb=orh%6X-ruu{9bwd@L&GZe>|YsKl_va`ta}n z?!nhJ&EPyfr|?;ro@M<($EVE)ljhYlVkyc7&^W99dM{%2ROf$PvU z>d>|5nz&}aejfkjpa1v6?>we+JpRb%hi*uXo>w&V = std::sync::OnceLock::new(); +/// A private Nightly profile's data folder, fixed before the first window (unset: stable's +/// Settings folder or the default). Every user folder this app writes — logs, autosave, smart +/// materials, layouts, templates, brushes and export presets — hangs off [`data_dir`], so a +/// Nightly install keeps all of it beside its own settings and never reads Stable's. +#[cfg(not(target_arch = "wasm32"))] +static DATA_ROOT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Use `root` as the data folder for this process; called once, before the first window, by a +/// Nightly launch with its validated profile. The Settings › Data folder value is not consulted. +#[cfg(not(target_arch = "wasm32"))] +pub fn set_data_root(root: std::path::PathBuf) { + let _ = DATA_ROOT.set(root); +} + +/// Whether this process runs from a private Nightly profile. +#[cfg(not(target_arch = "wasm32"))] +pub fn has_data_root() -> bool { + DATA_ROOT.get().is_some() +} + /// The data folder for a `Prefs::data_folder` value: that path when it is absolute, otherwise /// `Documents/TextureCraft` in the user's home folder. #[cfg(not(target_arch = "wasm32"))] @@ -1228,9 +1250,12 @@ pub fn data_folder(pref: &str) -> std::path::PathBuf { std::path::Path::new(&home).join("Documents").join("TextureCraft") } -/// The data folder in use (Settings › Folders › Data folder). +/// The data folder in use: the Nightly profile when this is one, else Settings › Folders › Data folder. #[cfg(not(target_arch = "wasm32"))] pub fn data_dir() -> std::path::PathBuf { + if let Some(root) = DATA_ROOT.get() { + return root.clone(); + } DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder("")) } diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs new file mode 100644 index 00000000..f1b60cbe --- /dev/null +++ b/crates/ui-egui/src/os_window.rs @@ -0,0 +1,120 @@ +//! The channel's OS identity: the app id every TextureCraft window carries and the names its +//! windows and About dialog show. +//! +//! The stable app id matches the `.desktop` file and the hicolor icon name, so Linux docks show +//! the TextureCraft icon and Wayland window rules match it. The Nightly window carries its own id +//! (the `.desktop` id the Nightly package installs), so a taskbar, a dock and a window rule can +//! tell the two side by side installs apart. The *package* identity is a different string again +//! (`ai.storyteller.texturecraft.nightly`, the bundle and package id); the two are never mixed. + +/// Matches the stable `.desktop` file and hicolor icon name. +pub const APP_ID: &str = "ai.storyteller.texturecraft"; + +/// The Nightly window's id, matching `packaging/linux/package.sh`'s `StartupWMClass` and the +/// nightly `.desktop` file. +pub const NIGHTLY_APP_ID: &str = "ai.storyteller.texturecraft.nightly-v1"; + +/// Immutable startup identity. The desktop app selects it before any window or service exists. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LaunchIdentity { + Stable, + NightlyV1, +} + +static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// `Err` when the identity was already selected: it is decided once per process, at startup. +pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> { + let value = match identity { + LaunchIdentity::Stable => 1, + LaunchIdentity::NightlyV1 => 2, + }; + IDENTITY + .compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire) + .map(|_| ()) + .map_err(|_| "the window launch identity was already selected".into()) +} + +pub fn identity() -> LaunchIdentity { + if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable } +} + +pub const fn id_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_ID, + LaunchIdentity::NightlyV1 => NIGHTLY_APP_ID, + } +} + +pub fn app_id() -> &'static str { + id_for(identity()) +} + +pub const fn name_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => "TextureCraft", + LaunchIdentity::NightlyV1 => "TextureCraft Nightly", + } +} + +/// The app's name in this window: "TextureCraft" or "TextureCraft Nightly". +pub fn name() -> &'static str { + name_for(identity()) +} + +/// Whether the services that belong to a stable install (updates, the control server) may run. +pub const fn stable_services_for(identity: LaunchIdentity) -> bool { + matches!(identity, LaunchIdentity::Stable) +} + +pub fn stable_services_allowed() -> bool { + stable_services_for(identity()) +} + +/// The version this window shows. A Nightly build is prepared with an exact feed identity, which +/// the engine's own constant (the workspace version) does not know; the app sets it at startup. +static DISPLAY_VERSION: std::sync::OnceLock = std::sync::OnceLock::new(); + +pub fn set_display_version(version: String) { + let _ = DISPLAY_VERSION.set(version); +} + +pub fn display_version() -> &'static str { + DISPLAY_VERSION.get().map(String::as_str).unwrap_or(texturecraft_engine::VERSION) +} + +/// A builder for an extra OS window, carrying [`app_id`]. +pub fn builder() -> egui::ViewportBuilder { + egui::ViewportBuilder::default().with_app_id(app_id()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nightly_identity_is_distinct_and_never_enables_stable_services() { + assert_eq!(id_for(LaunchIdentity::Stable), APP_ID); + assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID); + assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_APP_ID); + assert!(stable_services_for(LaunchIdentity::Stable)); + assert!(!stable_services_for(LaunchIdentity::NightlyV1)); + assert_eq!(name_for(LaunchIdentity::Stable), "TextureCraft"); + assert_eq!(name_for(LaunchIdentity::NightlyV1), "TextureCraft Nightly"); + } + + #[test] + fn the_unset_process_is_the_stable_one_and_extra_windows_carry_its_id() { + // The identity is a process-wide value set once at startup; without it the app is stable. + assert_eq!(identity(), LaunchIdentity::Stable); + assert_eq!(builder().app_id.as_deref(), Some(APP_ID)); + assert_eq!(name(), "TextureCraft"); + } + + #[test] + fn the_shown_version_falls_back_to_the_workspace_version() { + // `set_display_version` is set once per process by the desktop app; the fallback is the + // engine's constant, which is what a stable build shows. + assert!(display_version() == texturecraft_engine::VERSION || !display_version().is_empty()); + } +} diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index 8fda17b0..88d73912 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -543,6 +543,12 @@ fn general( section(ui, n_("FOLDERS")); row(ui, tr("Data folder"), |ui, label| { + // A Nightly install keeps every folder inside its own profile (the Launcher picks it), + // so the Setting would be ignored: show where they are instead of editing it. + if crate::has_data_root() { + ui.label(RichText::new(crate::data_dir().display().to_string()).small().color(tk.text_dim)); + return; + } let default = crate::data_folder("").display().to_string(); ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)).labelled_by(label); if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() { @@ -554,9 +560,13 @@ fn general( } note( ui, - tr( - "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", - ), + if crate::has_data_root() { + tr("TextureCraft Nightly keeps its autosaves, smart materials, presets, templates and UI layouts in its own profile, beside its settings.") + } else { + tr( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + ) + }, ); } } diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 857c7f10..4f328a85 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -53,6 +53,16 @@ const ICONS: [(f32, &[u8]); 5] = [ (64.0, include_bytes!("../../../assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png")), ]; +/// The Nightly strip's icon PNGs, same sizes: the deeper background tells the two windows apart at +/// a glance and matches the packaged Nightly icon. +const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [ + (16.0, include_bytes!("../../../assets/app-icon/nightly/16.png")), + (24.0, include_bytes!("../../../assets/app-icon/nightly/24.png")), + (32.0, include_bytes!("../../../assets/app-icon/nightly/32.png")), + (48.0, include_bytes!("../../../assets/app-icon/nightly/48.png")), + (64.0, include_bytes!("../../../assets/app-icon/nightly/64.png")), +]; + impl TitleBar { /// Decide who draws the title bar; call once at startup, before the window is created. /// `system` is Settings › Interface › System title bar. @@ -137,7 +147,8 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { /// The app icon at the cursor, [`ICON`] points square, centred on the row and on whole pixels. fn paint_icon(ui: &mut Ui) { let ppp = ui.ctx().pixels_per_point(); - let Some(&(px, png)) = ICONS.iter().find(|(px, _)| *px >= ICON * ppp - 0.5).or(ICONS.last()) else { return }; + let icons = if crate::os_window::stable_services_allowed() { &ICONS } else { &NIGHTLY_ICONS }; + let Some(&(px, png)) = icons.iter().find(|(px, _)| *px >= ICON * ppp - 0.5).or(icons.last()) else { return }; let id = Id::unique(("app_icon", px as u32)); let texture = match ui.data(|d| d.get_temp::>(id)) { Some(t) => t, diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 26e6d85a..5544b8fc 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -22,12 +22,19 @@ impl Default for Runtime { impl TextureCraftApp { /// Whether the app asks for a newer release when it starts (off until the desktop app turns it on). pub fn set_startup_update_check(&mut self, on: bool) { - self.updates_rt.startup_check = on; + // A Nightly install is updated by ArtCraft Launcher with the rest of the suite, never by + // the app: an in-app update would replace a copy the Launcher believes it manages. + self.updates_rt.startup_check = on && crate::os_window::stable_services_allowed(); } } -/// Help > Check for Updates: the next frame starts a check that reports its outcome. +/// Help > Check for Updates: the next frame starts a check that reports its outcome. In a Nightly +/// build the Launcher owns updates, so it says so instead of checking. pub(crate) fn request_check(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !crate::os_window::stable_services_allowed() { + app.toast(crate::i18n::tr("TextureCraft Nightly is updated by ArtCraft Launcher."), false); + return; + } app.updates_rt.check_requested = true; ctx.request_repaint(); } @@ -45,6 +52,9 @@ fn holds_keyboard(status: &Status, prompt_open: bool) -> bool { } pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !crate::os_window::stable_services_allowed() { + return; + } let rt = &mut app.updates_rt; if std::mem::take(&mut rt.check_requested) { rt.updater.check_now(ctx); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9e8fa5c..56e64caf 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -307,10 +307,13 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); let mut open = app.ui.windows.about; - dialog(ctx, "about", tr("About TextureCraft"), &mut open).show(ctx, |ui| { + let name = crate::os_window::name(); + // A Nightly window names its channel in the title too; the stable title keeps its translations. + let title = if name == "TextureCraft" { tr("About TextureCraft").to_owned() } else { trf("About {app}", &[("app", &name)]) }; + dialog(ctx, "about", &title, &mut open).show(ctx, |ui| { ui.vertical_centered(|ui| { - ui.label(RichText::new("TextureCraft").size(22.0).strong().color(tk.text_strong)); - ui.label(trf("Version {version}", &[("version", &texturecraft_engine::VERSION)])); + ui.label(RichText::new(name).size(22.0).strong().color(tk.text_strong)); + ui.label(trf("Version {version}", &[("version", &crate::os_window::display_version())])); ui.add_space(6.0); ui.label(tr("3D texture painting: layers, masks, smart materials, mesh map baking and export.")); ui.label(tr("Free and open source (MIT OR Apache-2.0), written in Rust.")); diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 00000000..2b504a7e --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,133 @@ +# Windows, Linux and macOS release-ref nightly: supervised manual go-live + +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the +signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed +manual actors dispatches them. There is no schedule yet. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 +policy. Once `nightly.yml` is registered on `main`, populate `producer_workflow_id` by reading: + +```bash +gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id +``` + +The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions +main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded +lineage compares and an issue reread at the end of candidate admission) on top of +[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input +and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed +source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that +producer run ID and attempt, by a listed manual actor. + +**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the +producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers +team (id 19837241), leaving out `echelon-robot`, which only has read access; update it by PR +in both places when the team changes. + +**Admission timing.** The candidate check reads the newest CI run on the candidate commit and +main's latest finished Sonar analysis, so when to dispatch matters: +- The candidate must be main's latest finished Sonar analysis. Pick a quiet main, wait for its + CI and SonarCloud analysis to finish green, then dispatch the producer and, once it succeeds, + the signer, before another main push lands a newer analysis. + +**Platform rows.** The producer caller lists +`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer +run builds every listed platform for one all-or-nothing release (one failed or +skipped platform stops that night's release, Windows included), and the release-ref signer admits +platforms only from the protected policy, so there is no separate Linux or macOS caller job and +the signer caller has no platform input. + +## Installed policy values and their sources + +Read on 2026-11-24; re-read anything that may have moved before the policy is promoted to `release`. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1419654881` | `gh api repos/storytold/texturecraft --jq .id` | +| `producer_workflow_id` | `null` (pending registration on `main`) | Populate via `gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` reaches `main` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | +| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | +| `platforms` | three rows (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | Stable suite signing identities (`Learning Machines Inc` Authenticode subject, Linux OpenPGP fingerprint `2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, Apple Team ID `DJ6XS33FX8`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `384666426`), 2 gate jobs | Workflow list API; jobs that succeeded on recent `main` push runs | +| `candidate_policy.sonar` | `storytold` / `storytold_texturecraft`, app `12526` | SonarCloud check on `main` commits | +| Sonar `issue_types` / `debt` | `VULNERABILITY`; `[]` (0 unresolved main vulnerabilities) | `api/issues/search` on `main` | + +The candidate check refuses whenever main's unresolved vulnerability set differs from `debt`, whether +an issue is new or fixed, and whenever a required condition fails or a listed CI job is renamed. Refresh +those values in the same reviewed change that promotes the policy to `release`. + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `TextureCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets + may be passed or inherited. +- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, + and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch, + including same-name tags. Its constant whole-run concurrency is distinct from stable, + cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no + credentials; only the shared callee's sign jobs bind the `release` environment. +- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in + `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable + commit**; the defining workflow SHA and tooling input must match. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` verifies the nightly workflow contracts: +- Both callers share one immutable 40-character SHA pin in `uses` and `tooling-revision`. +- Both callers keep their exact context guards (`if: >-` with no hidden continuation lines). +- `manual-actors` in `nightly.yml` and `manual_actors` in `.github/nightly-signing-policy.json` + match the reviewed release managers list, and `automatic_signer_actors` is empty. +- No nightly schedule is registered. +- No cache actions, cache setup options, `environment:`, or `secrets` appear in the app callers. +- `nightly-sign.yml` keeps its literal root `concurrency:` block (`texturecraft-nightly-release`, + `cancel-in-progress: false`, `queue: max`). +- `.github/nightly-signing-policy.json` matches the v3 schema, repository identity, platform + trust anchors, CI workflow trigger contract, and SonarCloud project identity. + + +## App-side producer scripts (Windows and macOS) + +**Every Linux Nightly format starts the app the flavor's way.** The `.deb`/`.rpm` wrapper, the +Arch launcher, the Flatpak wrapper, the AppImage's `AppRun` and the launcher inside the plain +`nightly.tar.gz` all exec the real GUI with the literal +`--launch-profile nightly-v1 --profile-root <${XDG_DATA_HOME:-~/.local/share}/TextureCraft-Nightly> --`, +and pass a Launcher protocol or a `--version`/`-V` query through untouched (so the smoke checks and +`texturecraft-nightly --version` still answer). The profile is outside stable's folders and outside +the unpacked or installed copy, which the flavor's fence would otherwise refuse. + +Every Nightly Linux format is GUI only. `texturecraft-cli` stays in the Stable packages: a headless +run loads its brush presets from `Documents/TextureCraft`, which is Stable's folder on every +platform and cannot be redirected by the launch profile, so a Nightly CLI would read and rewrite +Stable's brushes. The Flatpak smoke test therefore asks the app (`flatpak run --command=texturecraft`), +and the Arch handoff no longer stages a CLI. + +The producer's Windows and macOS legs run scripts this repository owns. Their inputs are the four +`TEXTURECRAFT_*` values the feed prepares (channel, exact version, commit, original run date), an +absolute `CARGO_TARGET_DIR` and `DIST`, and optionally `CRAFT_FONTS_DIR` with +`CRAFT_FONTS_REQUIRED=1`: + +| Platform | Compile step (no secrets) | Trusted signer step (release checkout) | +|---|---|---| +| Windows x86_64 | `pwsh packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly` (through `nightly.ps1`) | `pwsh packaging/windows/sign.ps1 -Required` | +| macOS aarch64 | `bash packaging/macos/nightly.sh --arch aarch64` | `bash packaging/macos/nightly-sign.sh`, then `nightly-verify.sh --expect signed --team` in a job without secrets | + +Both compile steps refuse every signing variable before Cargo runs +(`sign.ps1 -CheckBuildEnvironment`, `nightly_refuse_signing_env`), require the prepared commit to +be the checked-out one and the tree clean, and refuse `-SkipBuild`/an existing output. The +archives are GUI only: `texturecraft.exe` plus notices on Windows, `TextureCraft Nightly.app` on +macOS. The app-side surface — the build channel, the launch profile, the data root and the +fences — is described in the PR that adds it; the installed policy above is unchanged by it. + +Local checks with no compiler, macOS or network: `python3 packaging/nightly-tests.py` (the plist, +release-dispatch and macOS signing suites, plus the Nightly icons must be byte-identical to what +`packaging/nightly-icons.py` derives), `packaging/windows/nightly-package-tests.ps1` and +`nightly-signing-tests.ps1` (Windows, with `-FixtureRoot`), and `bash -n` plus shellcheck over the +three macOS scripts. The full-ci macOS job (`nightly-macos.yml`) is the only place the bundle and +its version query actually run before the first supervised release. diff --git a/docs/nightly-signing-policy.example.json b/docs/nightly-signing-policy.example.json new file mode 100644 index 00000000..99924a91 --- /dev/null +++ b/docs/nightly-signing-policy.example.json @@ -0,0 +1,54 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/texturecraft", + "repository_id": null, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": null, + "producer_workflow_ref": null, + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": null, + "release_branch": "release", + "manual_actors": [], + "max_age_seconds": null, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": null, + "repository": "storytold/texturecraft", + "branch": "main", + "required_workflows": null, + "sonar": { + "organization": null, + "project": null, + "app_id": null, + "check_name": null, + "details_url": null, + "issue_types": null, + "accepted_conditions": null, + "required_conditions": null, + "debt": null + } + }, + "max_artifact_bytes": null, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index 4feb8f88..cd1fd9c2 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -13,6 +13,9 @@ set -u APPDIR="$(dirname "$(readlink -f "$0")")" DESK_ID=ai.storyteller.texturecraft +# package.sh rewrites this line for a Nightly AppImage, which starts the app with the Launcher's +# private profile exactly as the deb, rpm, Arch, Flatpak and tarball launchers do. +CHANNEL=stable integrate() { case "${TEXTURECRAFT_NO_DESKTOP_INTEGRATION:-}" in @@ -69,4 +72,14 @@ integrate() { } integrate + +# The Launcher's own protocol, and a bare version query, pass through untouched: the first already +# names its profile, and the second must answer without one. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$APPDIR/usr/bin/texturecraft" "$@" ;; +esac +if [ "$CHANNEL" = nightly-v1 ]; then + exec "$APPDIR/usr/bin/texturecraft" --launch-profile nightly-v1 \ + --profile-root "${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" -- "$@" +fi exec "$APPDIR/usr/bin/texturecraft" "$@" diff --git a/packaging/linux/ai.storyteller.texturecraft.desktop b/packaging/linux/ai.storyteller.texturecraft.desktop index ded29c5d..8c27063c 100644 --- a/packaging/linux/ai.storyteller.texturecraft.desktop +++ b/packaging/linux/ai.storyteller.texturecraft.desktop @@ -8,7 +8,7 @@ TryExec=texturecraft Icon=ai.storyteller.texturecraft Terminal=false StartupNotify=true -StartupWMClass=texturecraft +StartupWMClass=ai.storyteller.texturecraft Categories=Graphics;3DGraphics; Keywords=texture;paint;pbr;material;3d;mesh;bake;gltf;fbx;usd; MimeType=application/x-texturecraft;model/gltf-binary;model/gltf+json;model/x-fbx;model/vnd.collada+xml;model/x-usd;model/vnd.usda;model/vnd.usdz+zip;model/x-alembic;model/obj;model/x-ply;model/stl; diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index cfb9548e..34034f96 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -95,4 +95,22 @@ out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exi [[ "$out" = "stub: x" ]] || fail "odd path: $out" [[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated an AppImage path that needs escaping" +# 10. A Nightly AppImage (package.sh rewrites the channel line) starts the app with the Launcher's +# private profile; a version query still passes through untouched. +NIGHTLY_APPDIR="$TMP/Nightly.AppDir" +mkdir -p "$NIGHTLY_APPDIR/usr/bin" +install -Dm755 "$HERE/AppRun" "$NIGHTLY_APPDIR/AppRun" +cat >"$NIGHTLY_APPDIR/usr/bin/texturecraft" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod +x "$NIGHTLY_APPDIR/usr/bin/texturecraft" +sed -i 's|^CHANNEL=stable$|CHANNEL=nightly-v1|' "$NIGHTLY_APPDIR/AppRun" +grep -qx 'CHANNEL=nightly-v1' "$NIGHTLY_APPDIR/AppRun" || fail "Nightly AppRun was not switched" +out="$(env -u APPIMAGE XDG_DATA_HOME="$TMP/nightly-data" "$NIGHTLY_APPDIR/AppRun" a.glb)" || fail "Nightly AppRun exited non-zero" +expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$TMP/nightly-data/TextureCraft-Nightly" -- a.glb)" +[[ "$out" = "$expected" ]] || fail "Nightly AppRun did not use the Launcher profile: $out" +out="$(env -u APPIMAGE "$NIGHTLY_APPDIR/AppRun" --version)" || fail "Nightly version query exited non-zero" +[[ "$out" = "<--version>" ]] || fail "Nightly AppRun rewrote a version query: $out" + echo "AppRun desktop integration ok" diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 4e884d84..1cce735c 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -9,14 +9,20 @@ # is built for the host architecture (x86_64 or aarch64), which must match the tarball's. # Needs flatpak, flatpak-builder and the SVG pixbuf loader (librsvg2-common) for the host's # `appstreamcli compose`; the freedesktop runtime and SDK named in the manifest are -# installed per-user from Flathub. Unless --no-test, the bundle is then installed per-user and -# `texturecraft-cli --version` is run inside the sandbox as a smoke test. +# installed per-user from Flathub. Unless --no-test, the bundle is then installed per-user and the +# app (`texturecraft --version`) is run inside the sandbox as a smoke test. # Manifest: packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml. set -euo pipefail # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.texturecraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo # The OCI repository serves only the latest stable release, so a prerelease bundle gets no update # source: Flatpak would otherwise replace it with that older stable build. @@ -56,38 +62,98 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/texturecraft" ]] || { echo "error: $TARBALL has no bin/texturecraft" >&2; exit 1; } -cp "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + # A Nightly tarball from package.sh already separates the launcher from the GUI; an older one + # does not. Either way this bundle installs its own wrapper and the GUI in /app/libexec. + if [[ -e "$WORK/stage/bin/texturecraft-bin" ]]; then + rm -f "$WORK/stage/bin/texturecraft" + else + mv "$WORK/stage/bin/texturecraft" "$WORK/stage/bin/texturecraft-bin" + fi + cat >"$WORK/stage/bin/texturecraft" <<'WRAPPER' +#!/bin/sh +# TextureCraft Nightly: the GUI runs with the Launcher's private profile. Inside the sandbox +# $XDG_DATA_HOME is the app's own per-app folder, so the profile never meets stable's. +set -eu +bin=/app/libexec/texturecraft +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# The Launcher's protocol, and a bare version query, pass through untouched. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" +WRAPPER + chmod 755 "$WORK/stage/bin/texturecraft" + sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \ + -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.texturecraft.nightly-v1|' \ + -e '/^MimeType=/d' \ + "$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop" + rm -f "$WORK/stage/share/applications/$APP_ID.desktop" + # The Nightly entry drops MimeType=, so the metainfo must not advertise the types either. + sed -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|TextureCraft|TextureCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e '//d' \ + "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml" + rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$WORK/stage/share/mime" + rm -rf "$WORK/stage/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/texturecraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + # Omit conflicting MIME registrations and disable host Flatpak updater talk-name until + # craft_update supports the nightly FLATPAK_ID. A Nightly bundle is also GUI-only: its tarball has + # no texturecraft-cli, and a CLI would read Stable's Documents/TextureCraft brushes. + sed -e "s|ai\.storyteller\.texturecraft|$FLATPAK_ID|g" \ + -e '/share\/mime\/packages\//d' \ + -e '/^\( *\)# \.tcraft, plus mesh types/d' \ + -e '/bin\/texturecraft-cli/d' \ + -e '/--talk-name=org\.freedesktop\.Flatpak/d' \ + -e 's|- install -Dm755 bin/texturecraft /app/bin/texturecraft|- install -Dm755 bin/texturecraft-bin /app/libexec/texturecraft\n - install -Dm755 bin/texturecraft /app/bin/texturecraft|' \ + "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" >"$WORK/$FLATPAK_ID.yml" +else + cp "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" "$WORK/$FLATPAK_ID.yml" +fi flatpak remote-add --user --if-not-exists flathub "$FLATHUB" # --disable-rofiles-fuse: no FUSE in containers and CI runners. flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \ - --default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml" + --default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml" OUT="$DIST/$BASENAME.flatpak" # A release build (the shared release workflow sets SIGNING_FPR, SIGNING_PUBKEY and GNUPGHOME) # signs the commit and embeds the public key, so Flatpak verifies the bundle when installing it. GPG_KEYS=() if [[ -n "${SIGNING_FPR:-}" ]]; then - flatpak build-sign "$WORK/repo" "$APP_ID" stable --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}" + flatpak build-sign "$WORK/repo" "$FLATPAK_ID" "$FLATPAK_BRANCH" --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}" GPG_KEYS=(--gpg-keys="${SIGNING_PUBKEY:?}") if [[ "${OCI_SIGNATURES_READY:-}" != 1 ]]; then OCI_REPO=""; fi fi # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. # --repo-url makes the installed origin update from the ArtCraft OCI repository. -flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$APP_ID" stable +flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote $OUT" if [[ "$OCI" = 1 ]]; then OUT_OCI="$DIST/$BASENAME-oci" rm -rf "$OUT_OCI" - flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote OCI layout to $OUT_OCI" fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" - flatpak info --user "$APP_ID" - flatpak run --command=texturecraft-cli "$APP_ID" --version - flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps' + flatpak info --user "$FLATPAK_ID" + flatpak run --command=texturecraft "$FLATPAK_ID" --version + if [[ "$FLATPAK_ID" == "$APP_ID" ]]; then + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps' + else + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps && test ! -e /app/share/mime/packages' + fi fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 8d4cebf0..1cea1c4b 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -1,9 +1,12 @@ # .deb and .rpm packages (nfpm: https://nfpm.goreleaser.com). Run by package.sh, which stages # the file tree, substitutes its path for ${STAGE} (nfpm doesn't expand env vars in `src`) and -# exports VERSION and NFPM_ARCH. +# exports VERSION, NFPM_ARCH, NFPM_NAME, NFPM_BIN and NFPM_CLI (the Nightly package renames the +# first two and has no CLI, so package.sh removes the CLI entry for it). By hand, all five are +# needed: # -# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: texturecraft +# VERSION=1.2.3 NFPM_ARCH=amd64 NFPM_NAME=texturecraft NFPM_BIN=texturecraft \ +# NFPM_CLI=texturecraft-cli nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -66,12 +69,15 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/texturecraft - dst: /usr/bin/texturecraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/texturecraft-cli - dst: /usr/bin/texturecraft-cli + - src: ${STAGE}/usr/bin/${NFPM_CLI} + dst: /usr/bin/${NFPM_CLI} file_info: { mode: 0755 } + - src: ${STAGE}/usr/lib/ + dst: /usr/lib/ + type: tree - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree diff --git a/packaging/linux/nightly-arch-launch.sh b/packaging/linux/nightly-arch-launch.sh new file mode 100755 index 00000000..6e5c07d5 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# The TextureCraft Nightly launcher for the Arch handoff (packaging/linux/nightly-arch-tar.sh): +# the real GUI stays in .texturecraft-nightly/, and this starts it with the Launcher's private +# profile, as every other Nightly package does. +set -eu + +bin="$(dirname "$0")/.texturecraft-nightly/texturecraft" +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" + +# The Launcher's protocol, and a bare version query, pass through untouched. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 00000000..5bd69fa2 --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening TextureCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=texturecraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/texturecraft" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod 755 "$stage/bin/texturecraft" + +bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base" +tar -xzf "$dst/$base.tar.gz" -C "$work/extract" +bin="$work/extract/$base/bin" +# Simulate the existing Arch bin-tree copy and public launcher rename. +mkdir -p "$work/installed" +cp -R "$bin" "$work/installed/bin" +bin="$work/installed/bin" +mv "$bin/texturecraft" "$bin/texturecraft-nightly" + +test ! -e "$stage/bin/.texturecraft-nightly" +cmp "$stage/bin/texturecraft" "$bin/.texturecraft-nightly/texturecraft" +# A Nightly package is GUI-only: the handoff must not carry a CLI that would use Stable's brushes. +test ! -e "$bin/texturecraft-nightly-cli" || { echo "FAIL: the Arch handoff still ships a Nightly CLI" >&2; exit 1; } +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# A launch adds the Launcher's literal selector/root pair and the file delimiter; a version query or +# an already-formed protocol passes through untouched. +expect_launch() { + expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")" + actual=$(PATH="$bin:$PATH" texturecraft-nightly "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} +expect_forwarded() { + expected="$(printf '<%s>\n' "$@")" + actual=$(PATH="$bin:$PATH" texturecraft-nightly "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} +expect_launch +expect_launch 'mesh with spaces.glb' '--other-name.tcraft' +expect_forwarded --version +expect_forwarded -V +expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version + +echo "PASS: Arch Nightly handoff preserves binary layout and passes the Launcher profile" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 00000000..69581347 --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Stage the TextureCraft Nightly-only handoff for the Arch packager. +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +source_tree="$1" +work="$2" +destination="$3" +basename="$4" +stage="$work/$basename" + +mkdir -p "$work" +cp -R "$source_tree" "$stage" +# The Nightly package is GUI-only: texturecraft-cli would read and rewrite Stable's +# Documents/TextureCraft brushes, which a private profile cannot redirect. +rm -f "$stage/bin/texturecraft-cli" +mkdir "$stage/bin/.texturecraft-nightly" +mv "$stage/bin/texturecraft" "$stage/bin/.texturecraft-nightly/texturecraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/texturecraft" +chmod 755 "$stage/bin/texturecraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch-test.sh b/packaging/linux/nightly-launch-test.sh new file mode 100755 index 00000000..4da17cd3 --- /dev/null +++ b/packaging/linux/nightly-launch-test.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# The launcher inside the plain Nightly tarball (packaging/linux/nightly-launch.sh): a launch adds +# the Launcher's private profile, a version query or an existing protocol passes through, and the +# fence's shape holds (absolute root, no parent traversal, outside this copy). +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/tree" + +# An argv recorder stands in for the GUI. It never opens a window. +cat >"$work/tree/texturecraft-bin" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod 755 "$work/tree/texturecraft-bin" +cp "$HERE/nightly-launch.sh" "$work/tree/texturecraft" + +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# The profile must be something the app's fence accepts: absolute, no parent traversal, and not +# inside the unpacked copy (the running install). +case "$profile" in + /*) ;; + *) echo "FAIL: the launcher profile is not absolute: $profile" >&2; exit 1 ;; +esac +case "/$profile/" in + */../*) echo "FAIL: the launcher profile contains parent traversal" >&2; exit 1 ;; +esac +case "$profile/" in + "$work/tree/"*) echo "FAIL: the launcher profile is inside the unpacked copy" >&2; exit 1 ;; +esac + +expect_launch() { + expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")" + actual=$("$work/tree/texturecraft" "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} +expect_forwarded() { + expected="$(printf '<%s>\n' "$@")" + actual=$("$work/tree/texturecraft" "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} + +expect_launch +expect_launch 'model with spaces.glb' '--other-name.tcraft' +expect_forwarded --version +expect_forwarded -V +expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version + +echo "PASS: tarball Nightly launcher starts the GUI with the Launcher profile and forwards files" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100755 index 00000000..77fa7d9c --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# The entry point inside the Nightly tarball (packaging/linux/nightly.sh installs it as +# `texturecraft`, beside the GUI as `texturecraft-bin`). +# +# A Nightly build only starts with its private profile, and every package format passes the +# Launcher's literal protocol: `--launch-profile nightly-v1 --profile-root

-- `. The +# profile sits outside stable's folders (its own settings, ui.json, crash log, autosaves, smart +# materials, layouts, templates and presets) and outside this unpacked copy, which the app's own +# fence would refuse. +set -eu + +here="$(dirname "$(readlink -f "$0")")" +bin="$here/texturecraft-bin" +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" + +# The Launcher's protocol, and a bare version query, pass through untouched: the first already +# names its profile, and the second must answer without one. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 00000000..687344c7 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +# shellcheck source=../nightly-common.sh +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/texturecraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +# The launcher is the entry point (`texturecraft`); the GUI sits beside it and is started with the +# Launcher's private profile, so an unpacked tarball never writes stable's folders. The flat layout +# is what nightly-archive.py allows, and the launcher is a committed script so shellcheck covers +# it like every other shell script. +cp "$NIGHTLY_GUI" "$STAGE/texturecraft-bin" +chmod 755 "$STAGE/texturecraft-bin" +cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/texturecraft" +chmod 755 "$STAGE/texturecraft" +cp "$ROOT/assets/app-icon/texturecraft-nightly-1024.png" "$STAGE/texturecraft-nightly.png" +nightly_copy_notices "$STAGE" +# The private mktemp cwd is the helper authority root, not a CLI path parent. +(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz) +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index a5a3ffd1..8c2ca936 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -7,7 +7,7 @@ # $DIST/texturecraft--linux-.rpm Fedora, openSUSE, RHEL, ... # $DIST/texturecraft--linux-.tar.gz plain FHS-style tree (bin/, share/) # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY] # # Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage # (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04, @@ -21,10 +21,16 @@ APP_ID=ai.storyteller.texturecraft SKIP_BUILD=0 FORMATS="appimage deb rpm tar" +ARCH_TAR_DIR= while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; + --arch-tar-dir) + [[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; } + ARCH_TAR_DIR="$2" + shift 2 + ;; -h | --help) sed -n '2,15p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -38,9 +44,24 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export TEXTURECRAFT_MAINTAINER="${TEXTURECRAFT_MAINTAINER:-TextureCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export TEXTURECRAFT_BUILD_CHANNEL=nightly-v1 + export TEXTURECRAFT_OVERRIDE_VERSION="$VERSION" +fi +NIGHTLY_ICON="$ROOT/assets/app-icon/texturecraft-nightly.png" +if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" +fi BASENAME="texturecraft-$VERSION-linux-$ARCH" -echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS)" +if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then + echo "error: --arch-tar-dir is only for Nightly builds" >&2 + exit 2 +fi + +echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS, channel=${TEXTURECRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) @@ -52,9 +73,20 @@ rm -rf "$WORK" # ---- stage an FHS tree (shared by every format) ------------------------------------------------- install -Dm755 "$BIN/texturecraft" "$STAGE/usr/bin/texturecraft" -install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli" -"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true +"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft" 2>/dev/null || true +# The Nightly formats ship the GUI only (the kit's rule). texturecraft-cli loads its brush presets +# from the host's Documents/TextureCraft, which is Stable's folder (`crates/automation`'s Headless), +# so a Nightly CLI would read and rewrite Stable's brushes. Stable keeps its CLI. +if [[ "$IS_NIGHTLY" = 0 ]]; then + install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli" + "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true +fi install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" +if [[ "$IS_NIGHTLY" = 1 ]]; then + sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.texturecraft.nightly-v1|' \ + "$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp" + mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop" +fi install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" mkdir -p "$STAGE/usr/share/metainfo" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$TEXTURECRAFT_BUILD_DATE/g" \ @@ -77,17 +109,91 @@ has() { case " $FORMATS " in *" $1 "*) return 0 ;; *) return 1 ;; esac; } if has tar; then mkdir -p "$WORK/tar" cp -R "$STAGE/usr" "$WORK/tar/$BASENAME" + if [[ "$IS_NIGHTLY" = 1 ]]; then + # A Nightly binary only starts with its private profile, so an unpacked tarball gets the same + # launcher the other Nightly formats install: `texturecraft` starts `texturecraft-bin`. + mv "$WORK/tar/$BASENAME/bin/texturecraft" "$WORK/tar/$BASENAME/bin/texturecraft-bin" + install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/texturecraft" + fi tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME" echo "wrote $DIST/$BASENAME.tar.gz" fi +# The Arch handoff keeps the same basename as the plain tarball in a separate directory. +if [[ -n "$ARCH_TAR_DIR" ]]; then + mkdir -p "$ARCH_TAR_DIR" + if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then + echo "error: the Arch tar directory must differ from the release directory" >&2 + exit 2 + fi + bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME" +fi + # ---- .deb / .rpm -------------------------------------------------------------------------------- if has deb || has rpm; then command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } export VERSION export NFPM_ARCH="$DEB_ARCH" + NFPM_STAGE="$STAGE" + export NFPM_NAME="texturecraft" + export NFPM_BIN="texturecraft" + export NFPM_CLI="texturecraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + export NFPM_NAME="texturecraft-nightly" + export NFPM_BIN="texturecraft-nightly" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + install -Dm755 "$NFPM_STAGE/usr/bin/texturecraft" "$NFPM_STAGE/usr/lib/texturecraft-nightly/texturecraft" + cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER' +#!/bin/sh +# TextureCraft Nightly: the GUI runs with the Launcher's private profile, which holds every +# per-user file (settings, ui.json, logs, autosaves, materials, layouts, templates, presets). +set -eu +bin=/usr/lib/texturecraft-nightly/texturecraft +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# The Launcher's protocol, and a bare version query, pass through untouched. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" +WRAPPER + chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN" + rm -f "$NFPM_STAGE/usr/bin/texturecraft" + mv "$NFPM_STAGE/usr/share/doc/texturecraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=texturecraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=texturecraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" + # The Nightly entry claims no MIME types (stable keeps the associations), so the metainfo must + # not advertise them either. + sed -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|TextureCraft|TextureCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|texturecraft|$NFPM_BIN|g" \ + -e '//d' \ + "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$NFPM_STAGE/usr/share/mime" + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + DROP_LIB_TREE= + DROP_CLI= + # shellcheck disable=SC2016 + [[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;' + # A Nightly package has no CLI, so its file list must not name one either. + # shellcheck disable=SC2016 + [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI='\|^ - src: \${STAGE}/usr/bin/\${NFPM_CLI}|,+2d;/Includes texturecraft-cli/d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_TREE}${DROP_CLI}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39. if [[ "$ARCH" = riscv64 ]]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi for fmt in deb rpm; do @@ -105,9 +211,46 @@ if has appimage; then # app_id to our icon instead of the generic Wayland logo (opt-out env in the # script header). Logic is covered by packaging/linux/apprun-test.sh. install -Dm755 "$HERE/AppRun" "$APPDIR/AppRun" - cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" - cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" - ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + if [[ "$IS_NIGHTLY" = 1 ]]; then + APPIMAGE_ID="$APP_ID.nightly-v1" + # The desktop id and the channel line: a Nightly AppImage must start the app with the + # Launcher's private profile, not with stable's folders (AppRun's tail does the exec). + awk -v old_id="$APP_ID" -v new_id="$APPIMAGE_ID" ' + $0 == "DESK_ID=" old_id { print "DESK_ID=" new_id; next } + $0 == "CHANNEL=stable" { print "CHANNEL=nightly-v1"; next } + { print } + ' "$APPDIR/AppRun" >"$APPDIR/AppRun.tmp" + grep -qx 'CHANNEL=nightly-v1' "$APPDIR/AppRun.tmp" || { + echo "error: AppRun has no CHANNEL=stable line to switch for Nightly" >&2 + exit 1 + } + mv "$APPDIR/AppRun.tmp" "$APPDIR/AppRun" + chmod 755 "$APPDIR/AppRun" + sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" + rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop" + cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop" + # The Nightly desktop entry drops MimeType=, so the metainfo must not advertise the same types + # either: AppStream would otherwise list a type the package cannot open. + sed -e "s|$APP_ID|$APPIMAGE_ID|g" \ + -e "s|TextureCraft|TextureCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$APPIMAGE_ID.desktop|g" \ + -e "s|$APP_ID|$APPIMAGE_ID|g" \ + -e '//d' \ + "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" >"$APPDIR/usr/share/metainfo/$APPIMAGE_ID.metainfo.xml" + rm -f "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$APPDIR/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + fi TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" if [[ -z "$TOOL" ]]; then @@ -129,11 +272,24 @@ if has appimage; then # next to each AppImage on GitHub Releases. `latest` is the newest published release that is # not a pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY. REPO="${GITHUB_REPOSITORY:-storytold/texturecraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|texturecraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|texturecraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + else + # Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point + # zsync update metadata at pre-release tags rather than stable `latest`. + if [[ "$VERSION" == *-nightly* ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|texturecraft-*-nightly*-linux-$ARCH.AppImage.zsync" + else + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|texturecraft-*-linux-$ARCH.AppImage.zsync" + fi + UPDATE_ARGS=(-u "$UPDATE_INFO") + fi # Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime, # so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync # package) appimagetool also writes the .zsync, into its working directory, hence the cd. - (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT") echo "wrote $OUT" if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" @@ -142,10 +298,14 @@ if has appimage; then fi fi +# A Stable tree is checked through its CLI; a Nightly tree has only the GUI, which answers the +# same bare `--version` query (no profile, so nothing is created) with its channel line. +SMOKE_BIN="$STAGE/usr/bin/texturecraft-cli" +if [[ "$IS_NIGHTLY" = 1 ]]; then SMOKE_BIN="$STAGE/usr/bin/texturecraft"; fi if [[ -n "${CROSS_TARGET:-}" ]]; then - if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$STAGE/usr/bin/texturecraft-cli" --version; fi + if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$SMOKE_BIN" --version; fi else - "$STAGE/usr/bin/texturecraft-cli" --version + "$SMOKE_BIN" --version fi echo "==> done" ls -lh "$DIST" diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100644 index 00000000..0bafd63d --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,125 @@ +# shellcheck shell=bash +# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh). +# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output +# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS. + +MAC_NIGHTLY_APP='TextureCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.texturecraft.nightly' +MAC_NIGHTLY_EXECUTABLE='TextureCraft' +# nightly.sh copies it into the bundle; the file is linted on its own, without -x, so shellcheck +# cannot see that use. +# shellcheck disable=SC2034 +MAC_NIGHTLY_ICON='texturecraft-nightly' +# The release environment's names, as release.yml passes them (packaging/macos/import-cert.sh). +MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID) + +mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +# The exact prepared version from the feed asset name, or failure. +mac_nightly_version_from_asset() { + local name="$1" version + [[ "$name" =~ ^texturecraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# The keychain this app's import-cert.sh made belongs to this run: a regular file (no link) with the +# app's keychain name, inside the run directory. Its script makes its own name under RUNNER_TEMP, so +# the path is read from its printed output rather than assumed. +mac_nightly_keychain_is_ours() { + local keychain="$1" work="$2" + [[ -f "$keychain" && ! -L "$keychain" ]] || return 1 + [[ "$(basename -- "$keychain")" == texturecraft-signing.keychain-db ]] || return 1 + case "$keychain" in "$work"/*) return 0 ;; *) return 1 ;; esac +} + +# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team. +mac_nightly_identity_is_team() { + local line="$1" identity="$2" team="$3" + [[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]] +} + +# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the +# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict). +mac_nightly_check_signature() { + local details="$1" team="$2" ok=0 + grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; } + grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; } + grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; } + grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; } + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; } + return "$ok" +} + +# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized. +mac_nightly_check_assessment() { + grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1" +} + +# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly +# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file. +mac_nightly_check_zip_entries() { + python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file' +import stat, sys, zipfile +archive, app = sys.argv[1:] +with zipfile.ZipFile(archive) as z: + for info in z.infolist(): + name = info.filename + parts = name.rstrip("/").split("/") + mode = info.external_attr >> 16 + if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app + or any(part in ("", ".", "..") for part in parts) + or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)): + sys.exit(f"refused entry: {name!r}") +PY +} + +# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 executable, +# the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special +# files, no document or URL types. +mac_nightly_check_bundle() { + local payload="$1" version="$2" app entries plist key value + app="$payload/$MAC_NIGHTLY_APP" + entries="$(ls -A "$payload")" + [[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP" + [[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files' + [[ "$(ls -A "$app/Contents/MacOS")" == "$MAC_NIGHTLY_EXECUTABLE" ]] || mac_nightly_die 'Contents/MacOS must hold only the GUI executable (no CLI)' + [[ -f "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" && -x "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable TextureCraftVersion; do + value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key" + case "$key" in + CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;; + CFBundleExecutable) [[ "$value" == "$MAC_NIGHTLY_EXECUTABLE" ]] ;; + TextureCraftVersion) [[ "$value" == "$version" ]] ;; + esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity" + done + for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do + if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi + done +} + +# `stapler validate` asks the CloudKit service, which sometimes drops the connection (error 68) +# though the ticket is there (verify.sh). +mac_nightly_validate_staple() { + local target="$1" attempt + for attempt in 1 2 3 4 5; do + xcrun stapler validate "$target" && return 0 + [[ "$attempt" = 5 ]] || sleep $((attempt * 20)) + done + return 1 +} diff --git a/packaging/macos/nightly-sign.sh b/packaging/macos/nightly-sign.sh new file mode 100755 index 00000000..9ecc91b2 --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route +# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps): +# +# nightly-sign.sh --arch aarch64 --input /abs/texturecraft--macos-aarch64-nightly.zip \ +# --output /abs//texturecraft--macos-aarch64-nightly.zip +# +# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and +# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended +# attributes. Writes only that file, never replacing one; the temporary keychain and work directory +# are removed on every exit. +# +# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, +# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must +# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base). +# +# Never compiles, and never runs anything from the payload: the version query runs on the signed +# bundle in a job without secrets (nightly-verify.sh). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" + +ARCH='' INPUT='' OUTPUT='' +while [[ $# -gt 0 ]]; do + case "$1" in + --arch | --input | --output) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,18p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported' +[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths' +NAME="$(basename -- "$INPUT")" +VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name' +[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file' +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output' +[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist' +mac_nightly_require_secrets +[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)' + +BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +WORK="$(mktemp -d "${BASE%/}/texturecraft-nightly-sign.XXXXXX")" +KEYCHAIN="$WORK/texturecraft-signing.keychain-db" +cleanup() { + if [[ -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi + rm -rf -- "$WORK" +} +trap cleanup EXIT + +# ---- identity: import-cert.sh, into this run's private directory ------------------------------ +# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps. +imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")" +IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")" +KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" +[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ ]] || mac_nightly_die 'import-cert.sh did not import a signing identity' +mac_nightly_keychain_is_ours "$KEYCHAIN" "$WORK" || mac_nightly_die 'import-cert.sh did not create this run keychain' +mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \ + || mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID" +echo "==> TextureCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY" + +# ---- the unsigned bundle --------------------------------------------------------------------------- +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +# ---- package.sh's signing and notarization, with a required Developer ID --------------------------- +sign() { + codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@" +} + +notarize() { + local file="$1" out id status + echo "==> notarizing $(basename "$file") (this can take a few minutes)" + out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \ + --team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true + echo "$out" + id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" + status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then + # Capped: the shared signer bounds a step output at 256 KiB. + xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true + fi + echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 + exit 1 + fi +} + +# Stapling and validating both look the ticket up in the CloudKit service, which can drop the +# connection right after notarization (error 68), so retry the pair (package.sh). +staple() { + local file="$1" attempt + for attempt in 1 2 3 4 5; do + if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then + return + fi + if [[ "$attempt" = 5 ]]; then + echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2 + exit 1 + fi + echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2 + sleep $((attempt * 20)) + done +} + +# Inside-out: the executable, then the bundle (no --deep on the final signature). +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" +codesign --verify --strict --deep --verbose=2 "$APP" +ditto -c -k --keepParent "$APP" "$WORK/notarize.zip" +notarize "$WORK/notarize.zip" +# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs. +staple "$APP" + +# ---- the final archive, checked as the Launcher unpacks it ----------------------------------------- +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip" +ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check" +mac_nightly_check_bundle "$WORK/check" "$VERSION" +CHECK="$WORK/check/$MAC_NIGHTLY_APP" +codesign --verify --strict --deep --verbose=2 "$CHECK" +mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \ + || mac_nightly_die 'the signed bundle is not the required Developer ID signature' +mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle' +# spctl lookup can lag a few seconds behind notarytool Accepted (verify.sh). +for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 +done +printf '%s\n' "$assessment" +mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' + +nightly_publish_archive "$WORK/final.zip" "$OUTPUT" diff --git a/packaging/macos/nightly-verify.sh b/packaging/macos/nightly-verify.sh new file mode 100755 index 00000000..07d968be --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version. +# For a job without signing material (it refuses to run with any), after nightly-sign.sh: +# +# nightly-verify.sh --input /abs/texturecraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/texturecraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact TextureCraftVersion, unpacked +# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else +# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as +# notarized. `unsigned` (nightly.sh compile output, e.g. pull-request CI) checks no signature. +# Last, the GUI answers its version query with an empty environment, both plainly and in the +# Launcher form `--launch-profile nightly-v1 --profile-root --version` (the shared producer +# smoke): each must exit 0 within 15 seconds, print exactly `TextureCraft (nightly-v1)` and +# write nothing to standard error. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" + +INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}" +while [[ $# -gt 0 ]]; do + case "$1" in + --input | --expect | --team) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do + [[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)" +done +[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned' +[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)' +[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file' +VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac' + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/texturecraft-nightly-verify.XXXXXX")" +trap 'rm -rf -- "$WORK"' EXIT +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +if [[ "$EXPECT" == signed ]]; then + codesign --verify --strict --deep --verbose=2 "$APP" + mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \ + || mac_nightly_die 'the bundle is not the required Developer ID signature' + mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle' + for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 + done + printf '%s\n' "$assessment" + mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' +fi + +# macOS has no timeout(1): perl alarm survives its exec and ends a query that hangs (a dialog, say). +query() { + local out + out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \ + /usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" "$@" 2>"$WORK/stderr")" \ + || mac_nightly_die "the version query ($*) failed or did not finish within 15 s" + [[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")" + [[ "$out" == "TextureCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not TextureCraft $VERSION (nightly-v1)" +} +mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile" +query --version +query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version +echo "==> verified ($EXPECT): TextureCraft $VERSION (nightly-v1), plain and in the Launcher profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100755 index 00000000..4140e45a --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/texturecraft--macos-aarch64-nightly.zip TextureCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): TEXTURECRAFT_BUILD_CHANNEL=nightly-v1, TEXTURECRAFT_VERSION, +# TEXTURECRAFT_BUILD_SHA, TEXTURECRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional. +# +# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI, +# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query +# runs on the signed bundle (nightly-verify.sh). +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; } +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +nightly_refuse_signing_env +nightly_init macos "$ARCH" aarch64-apple-darwin +# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh). +export MACOSX_DEPLOYMENT_TARGET=11.0 +OUTPUT="$DIST/texturecraft-$VERSION-macos-aarch64-nightly.zip" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_compile_gui + +APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" +chmod 755 "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" +cp "$ROOT/assets/app-icon/$MAC_NIGHTLY_ICON.icns" "$APP/Contents/Resources/$MAC_NIGHTLY_ICON.icns" +nightly_copy_notices "$APP/Contents/Resources" +# The private mktemp cwd is the helper authority root: stage the template inside it. +cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" +(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ + --output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$TEXTURECRAFT_BUILD_SHA") +plutil -lint "$APP/Contents/Info.plist" +printf 'APPL????' >"$APP/Contents/PkgInfo" +mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION" + +# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them. +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip" +nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100644 index 00000000..63a2e369 --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Nightly metadata: run from a private owned build cwd with a staged template. + +All file arguments must stay beneath that cwd; this is not native/signing acceptance. +""" +import argparse +import datetime +import os +from pathlib import Path +import plistlib +import re +import sys + +# The shared helper location is fixed by this script, not by CLI file arguments. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from nightly_paths import OwnedBuildRoot + +MAX_TEMPLATE_BYTES = 256 * 1024 + +IDENTIFIER = "ai.storyteller.texturecraft.nightly" +# Stable's own document, mesh and project declarations: a Nightly install registers no associations. +ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations") +VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z") + + +def render(template: bytes, version: str, commit: str) -> bytes: + match = VERSION.fullmatch(version) + if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]: + raise ValueError("exact prepared Nightly version and matching source commit are required") + datetime.datetime.strptime(match[2], "%Y%m%d") + data = plistlib.loads(template) + if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL": + raise ValueError("expected the app-owned application plist template") + for key in ASSOCIATIONS: + data.pop(key, None) + data.update( + CFBundleDisplayName="TextureCraft Nightly", + CFBundleName="TextureCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="TextureCraft", + CFBundleIconFile="texturecraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + TextureCraftVersion=version, + TextureCraftBuildCommit=commit, + ) + return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False) + + +def write_plist(template: Path, destination: Path, version: str, commit: str) -> None: + with OwnedBuildRoot() as root: + content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit) + with root.create(destination) as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--template", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--source-commit", required=True) + args = parser.parse_args() + write_plist(args.template, args.output, args.version, args.source_commit) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100644 index 00000000..1662c607 --- /dev/null +++ b/packaging/macos/nightly_plist_tests.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network.""" +import importlib.util +import os +from pathlib import Path +import plistlib +import runpy +import sys +from unittest import mock +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("texturecraft_nightly_plist", HERE / "nightly_plist.py") +POLICY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(POLICY) +COMMIT = "a" * 40 +VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12] + + +class NightlyMetadata(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.template = self.root / "Info.plist.in" + self.original = (HERE / "Info.plist.in").read_bytes() + self.template.write_bytes(self.original) + self.output = self.root / "Info.plist" + + def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self): + stable = plistlib.loads(self.original) + stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}] + prepared = plistlib.dumps(stable) + self.template.write_bytes(prepared) + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + rendered = plistlib.loads(self.output.read_bytes()) + for key in POLICY.ASSOCIATIONS: + self.assertNotIn(key, rendered) + self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"]) + self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.texturecraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "TextureCraft") + self.assertEqual(rendered["TextureCraftVersion"], VERSION) + self.assertEqual(rendered["TextureCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "LSApplicationCategoryType", "NSHighResolutionCapable", "NSHumanReadableCopyright"): + self.assertEqual(rendered[key], stable[key]) + self.assertEqual(self.template.read_bytes(), prepared) + self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original) + + def test_bad_identity_or_template_refuses_before_creating_output(self): + for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)): + with self.subTest(version=version, commit=commit): + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, version, commit) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_cli_writes_the_requested_identity_without_replacing_the_template(self): + helper = HERE / "nightly_plist.py" + argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT] + with mock.patch.object(sys, "argv", argv): + runpy.run_path(str(helper), run_name="__main__") + result = plistlib.loads(self.output.read_bytes()) + self.assertEqual(result["TextureCraftVersion"], VERSION) + self.assertEqual(result["TextureCraftBuildCommit"], COMMIT) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_template_alias_or_nonfile_refuses_before_output(self): + alias = self.root / "template-alias" + alias.symlink_to(self.template) + for template in (alias, self.root, self.root / "missing-template"): + with self.subTest(template=template), self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self): + sentinel = b"generated replacement artifact" + for disposition in ("owned", "missing", "replacement"): + with self.subTest(disposition=disposition): + if self.output.exists(): + self.output.unlink() + + def fail_sync(_descriptor): + # macOS/Linux allow unlink of an open file: exercise the real + # cleanup ownership check, not a mocked inode comparison. + if disposition != "owned": + self.output.unlink() + if disposition == "replacement": + self.output.write_bytes(sentinel) + raise OSError("generated fsync failure") + + with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + if disposition == "replacement": + self.assertEqual(self.output.read_bytes(), sentinel) + else: + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self): + sentinel = b"generated owned sentinel, not an existing app or user file" + self.output.write_bytes(sentinel) + with self.assertRaises(FileExistsError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(self.output.read_bytes(), sentinel) + self.output.unlink() + external = self.root / "sentinel" + external.write_bytes(sentinel) + self.output.symlink_to(external) + with self.assertRaisesRegex(ValueError, "symlinks or aliases"): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(external.read_bytes(), sentinel) + self.assertTrue(self.output.is_symlink()) + + + def test_template_outside_build_root_refuses_before_output(self): + with tempfile.TemporaryDirectory() as external: + template = Path(external) / "Info.plist.in" + template.write_bytes(self.original) + with self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(template.read_bytes(), self.original) + + def test_output_outside_build_root_refuses_before_write(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse(output.exists()) + + def test_parent_traversal_refuses_even_to_an_owned_sibling(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_symlinked_output_parent_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_template_read_is_bounded_before_output(self): + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_nonprivate_build_root_refuses(self): + self.root.chmod(0o755) + try: + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + finally: + self.root.chmod(0o700) + + + def test_output_keeps_normal_new_file_permissions_inside_private_root(self): + previous = os.umask(0o022) + try: + reference = self.root / "reference" + reference.write_bytes(b"generated ordinary output") + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + finally: + os.umask(previous) + self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777) + + def test_open_parent_anchor_prevents_a_later_alias_redirect(self): + parent = self.root / "stage" + parent.mkdir() + retained = self.root / "retained-stage" + destination = parent / "Info.plist" + original = POLICY.OwnedBuildRoot._parent + with tempfile.TemporaryDirectory() as external: + def swap_after_parent_open(root, path): + descriptor, name = original(root, path) + if Path(path) == destination: + parent.rename(retained) + parent.symlink_to(external, target_is_directory=True) + return descriptor, name + with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open): + POLICY.write_plist(self.template, destination, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["TextureCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py new file mode 100644 index 00000000..f0a2eddc --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""The Nightly signing and archive helpers, exercised on Linux with stand-in Apple tool output. + +Nothing here signs, notarizes, unpacks or runs a payload: each helper takes the tool output (or a +crafted archive) as an argument, which is why packaging/macos/nightly_sign_tests.py can run in the +app's ordinary Linux CI. +""" +import os +import stat +import subprocess +import tempfile +import unittest +import zipfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +LIB = HERE / "nightly-lib.sh" +APP = "TextureCraft Nightly.app" +IDENTITY = "A" * 40 +TEAM = "DJ6XS33FX8" +APP_CONFIG_ID = "ai.storyteller.texturecraft.nightly" + + + +class VersionFromAsset(unittest.TestCase): + def check(self, name): + """True when the helper accepts the asset name.""" + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_version_from_asset "$1"', "bash", name], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_accepts_only_the_prepared_nightly_archive_name(self): + version = "0.24.0-nightly.20261124.7.2.g" + "0123456789ab" + self.assertTrue(self.check(f"texturecraft-{version}-macos-aarch64-nightly.zip")) + for name in [ + f"texturecraft-{version}-macos-aarch64.zip", + f"texturecraft-{version}-linux-x86_64-nightly.tar.gz", + f"texturecraft-0.24.0-macos-aarch64-nightly.zip", + f"texturecraft-{version.upper()}-macos-aarch64-nightly.zip", + f"photocraft-{version}-macos-aarch64-nightly.zip", + f"texturecraft-{version}-macos-x86_64-nightly.zip", + f"texturecraft-{version}-macos-aarch64-nightly.zip.sig", + ]: + self.assertFalse(self.check(name), name) + + +class Keychain(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.work = Path(self.directory.name).resolve() + self.keychain = self.work / "texturecraft-signing.keychain-db" + self.keychain.write_bytes(b"stand-in keychain") + + def ours(self, keychain, work=None): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_keychain_is_ours "$1" "$2"', "bash", str(keychain), str(work or self.work)], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_only_this_runs_own_keychain_counts(self): + self.assertTrue(self.ours(self.keychain)) + # import-cert.sh may put it in a private directory of its own under the run. + nested = self.work / "private" + nested.mkdir() + self.assertFalse(self.ours(nested / "texturecraft-signing.keychain-db"), "a missing file is not ours") + (nested / "texturecraft-signing.keychain-db").write_bytes(b"x") + self.assertTrue(self.ours(nested / "texturecraft-signing.keychain-db")) + self.assertFalse(self.ours(self.work / "other.keychain-db")) + with tempfile.TemporaryDirectory() as outside: + (Path(outside) / "texturecraft-signing.keychain-db").write_bytes(b"x") + self.assertFalse(self.ours(Path(outside) / "texturecraft-signing.keychain-db")) + alias = self.work / "texturecraft-signing.keychain-db-alias" + alias.symlink_to(self.keychain) + self.assertFalse(self.ours(alias)) + + +class Identity(unittest.TestCase): + LINE = f' 1) {IDENTITY} "Developer ID Application: Learning Machines Inc ({TEAM})"' + + def matcher(self, line, identity=IDENTITY, team=TEAM): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_identity_is_team "$1" "$2" "$3"', "bash", line, identity, team], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_a_developer_id_of_the_team_and_nothing_else(self): + self.assertTrue(self.matcher(self.LINE)) + self.assertFalse(self.matcher(self.LINE.replace("Developer ID Application", "Apple Development"))) + self.assertFalse(self.matcher(self.LINE.replace(TEAM, "ZZZZZZZZZZ"))) + self.assertFalse(self.matcher(self.LINE, identity="B" * 40)) + self.assertFalse(self.matcher("")) + + +class Signature(unittest.TestCase): + DETAILS = "\n".join([ + f"Identifier={APP_CONFIG_ID}", + "Authority=Developer ID Application: Learning Machines Inc (DJ6XS33FX8)", + "Authority=Developer ID Certification Authority", + f"TeamIdentifier={TEAM}", + "Timestamp=Nov 24, 2026 at 10:00:00", + "CodeDirectory v=20500 size=1234 flags=0x10000(runtime) hashes=1+7 location=embedded", + ]) + + def check(self, details, team=TEAM): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_check_signature "$1" "$2"', "bash", details, team], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_the_required_developer_id_signature(self): + self.assertTrue(self.check(self.DETAILS)) + for missing in [ + "Timestamp=Nov 24, 2026 at 10:00:00", + f"TeamIdentifier={TEAM}", + "Authority=Developer ID Application: Learning Machines Inc (DJ6XS33FX8)", + ]: + self.assertFalse(self.check(self.DETAILS.replace(missing, "")), missing) + self.assertFalse(self.check(self.DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"))) + self.assertFalse(self.check(self.DETAILS, team="ZZZZZZZZZZ")) + self.assertFalse(self.check(self.DETAILS.replace(APP_CONFIG_ID, "ai.storyteller.texturecraft"))) + + +class Assessment(unittest.TestCase): + def check(self, text): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_check_assessment "$1"', "bash", text], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_gatekeeper_must_report_a_notarized_developer_id(self): + self.assertTrue(self.check(f"{APP}: accepted\nsource=Notarized Developer ID")) + self.assertFalse(self.check(f"{APP}: accepted\nsource=Unnotarized Developer ID")) + self.assertFalse(self.check(f"{APP}: rejected\nsource=Notarized Developer ID")) + self.assertFalse(self.check("")) + + +class ZipEntries(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + + def checked(self, entries): + """True when mac_nightly_check_zip_entries accepts the archive of (name, mode) entries.""" + archive = self.root / "test.zip" + with zipfile.ZipFile(archive, "w") as z: + for name, mode in entries: + info = zipfile.ZipInfo(name) + info.external_attr = (mode or stat.S_IFREG | 0o644) << 16 if mode else 0 + z.writestr(info, b"stand-in payload") + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_check_zip_entries "$1"', "bash", str(archive)], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB), "MAC_NIGHTLY_APP": APP}, + ) + return result.returncode == 0 + + def test_a_plain_bundle_is_accepted_and_anything_else_refused(self): + good = [ + (f"{APP}/", stat.S_IFDIR | 0o755), + (f"{APP}/Contents/Info.plist", stat.S_IFREG | 0o644), + (f"{APP}/Contents/MacOS/TextureCraft", stat.S_IFREG | 0o755), + ] + self.assertTrue(self.checked(good)) + for entry in [ + (f"{APP}/../escape", stat.S_IFREG | 0o644), + ("/absolute/path", stat.S_IFREG | 0o644), + (f"{APP}/Contents/link", stat.S_IFLNK | 0o777), + ("Other.app/Contents/Info.plist", stat.S_IFREG | 0o644), + (f"{APP}/Contents/with\\backslash", stat.S_IFREG | 0o644), + ]: + self.assertFalse(self.checked([*good, entry]), entry[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100755 index 00000000..e917ce8d --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + self.required = {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "texturecraft").chmod(0o755) + (self.stage / "texturecraft-bin").chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("texturecraft").read(), (self.stage / "texturecraft").read_bytes()) + # The launcher is what a user runs; the GUI beside it must be runnable too. + modes = {member.name: member.mode for member in archive.getmembers()} + for name in ("texturecraft", "texturecraft-bin"): + self.assertEqual(modes[name] & 0o111, 0o111, f"{name} must be executable") + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["texturecraft-cli", "portable.txt", "texturecraft.desktop"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "texturecraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "texturecraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_cli_dispatches_only_the_supported_archive_kind(self): + helper = HERE / "nightly-archive.py" + with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]): + runpy.run_path(str(helper), run_name="__main__") + with tarfile.open(self.output) as archive: + self.assertEqual({member.name for member in archive}, self.required) + refused = self.root / "refused.tar.gz" + for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]): + with self.subTest(args=args), mock.patch.object(sys, "argv", args): + with self.assertRaises(SystemExit): + runpy.run_path(str(helper), run_name="__main__") + self.assertFalse(refused.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + + def test_archive_output_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse(output.exists()) + + def test_archive_stage_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + stage = Path(external) + for name in self.required: + (stage / name).write_bytes(b"generated external fixture") + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(stage, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_stage_alias_refuses(self): + alias = self.root / "stage-alias" + alias.symlink_to(self.stage, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(alias, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_output_parent_alias_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "output-alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz") + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_archive_parent_traversal_refuses(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_nonflat_member_name_refuses(self): + stage_root = os.path.realpath(self.stage) + with open(self.stage / "README.md", "rb") as incoming: + for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."): + with self.subTest(name=bad), self.assertRaises(ValueError): + ARCHIVE.member_info(stage_root, bad, incoming) + + def test_member_header_matches_what_gettarinfo_records(self): + stage_root = os.path.realpath(self.stage) + for name in sorted(self.required): + with self.subTest(name=name), open(self.stage / name, "rb") as incoming: + ours = ARCHIVE.member_info(stage_root, name, incoming) + with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference: + theirs = reference.gettarinfo(fileobj=incoming, arcname=name) + self.assertEqual(ours.get_info(), theirs.get_info()) + + def test_member_read_budget_refuses_before_output(self): + (self.stage / "OFL-Large.txt").write_bytes(b"x" * 65) + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + + def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self): + growing = self.stage / "OFL-Growing.txt" + growing.write_bytes(b"x" * 32) + original = ARCHIVE.member_info + + def grow_before_stat(stage_root, name, incoming): + if name == growing.name: + growing.write_bytes(b"x" * 65) + return original(stage_root, name, incoming) + + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \ + mock.patch.object(ARCHIVE, "member_info", grow_before_stat): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 00000000..b4b380ac --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 1024 * 1024 * 1024 +MAX_MEMBERS = 128 + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def checked_entries(root, stage): + entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name) + folded = set() + total = 0 + for entry in entries: + name = entry.name + if name not in {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png"} and not notice(name): + raise ValueError(f"unexpected nightly member: {name}") + if len(name.encode("utf-8")) > 100: + raise ValueError(f"nightly member must be a short regular file: {name}") + with root.reader(entry, MAX_MEMBER_BYTES) as stream: + total += os.fstat(stream.fileno()).st_size + if total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage exceeds its read bound") + if name.casefold() in folded: + raise ValueError(f"case-colliding nightly member: {name}") + folded.add(name.casefold()) + required = {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + info = tarfile.TarInfo(os.path.basename(destination)) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-checks.sh b/packaging/nightly-checks.sh new file mode 100755 index 00000000..33c39b8f --- /dev/null +++ b/packaging/nightly-checks.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# The Nightly checks that need no compiler, macOS or network: the synthetic suites (release +# contracts, the macOS plist and signing helpers, the icons), the launcher tests, and `bash -n` +# over every Nightly shell script. Run by .github/workflows/packaging-lint.yml. +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/.." && pwd)" +cd "$ROOT" + +python3 packaging/nightly-tests.py +bash packaging/linux/nightly-arch-tar-test.sh +bash packaging/linux/nightly-launch-test.sh + +for script in \ + packaging/nightly-common.sh \ + packaging/linux/nightly.sh \ + packaging/linux/nightly-launch.sh \ + packaging/linux/nightly-launch-test.sh \ + packaging/linux/nightly-arch-launch.sh \ + packaging/linux/nightly-arch-tar.sh \ + packaging/linux/nightly-arch-tar-test.sh \ + packaging/linux/package.sh \ + packaging/linux/flatpak-bundle.sh \ + packaging/linux/apprun-test.sh \ + packaging/macos/nightly.sh \ + packaging/macos/nightly-lib.sh \ + packaging/macos/nightly-sign.sh \ + packaging/macos/nightly-verify.sh; do + bash -n "$script" +done + +echo "Nightly checks passed" diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 00000000..be77cca2 --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,93 @@ +# shellcheck shell=bash +# Shared setup for app-owned native nightly archives; stable packaging does not source this file. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'TEXTURECRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${TEXTURECRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required' + [[ "${TEXTURECRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${TEXTURECRAFT_VERSION##*.g}" == "${TEXTURECRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${TEXTURECRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${TEXTURECRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${TEXTURECRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch' + [[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required' + [[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required' + [[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal' + ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + # shellcheck source=./env.sh + . "$ROOT/packaging/env.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +# Compile only: macOS runs the version query after signing (packaging/macos/nightly-verify.sh). +nightly_compile_gui() { + # Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). + nightly_refuse_signing_env + (cd "$ROOT" && TEXTURECRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p texturecraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/texturecraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + # Exactly what the flavor prints: the prepared version and its channel (build_flavor::version). + [[ "$actual" == "TextureCraft $VERSION (nightly-v1)" ]] || nightly_die "the built binary reports '$actual', not TextureCraft $VERSION (nightly-v1)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + # The signing names release.yml passes, for every platform, and import-cert.sh's outputs. + for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \ + MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \ + AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do + [[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step" + done +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 -I - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/nightly-icons.py b/packaging/nightly-icons.py new file mode 100755 index 00000000..1643e8c4 --- /dev/null +++ b/packaging/nightly-icons.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""Derive TextureCraft's Nightly icons from the committed stable renders. + +The Nightly icon is the same artwork on a deeper background — no badge, crescent or letter. Each +pixel is fitted as a blend of the tile's background and one of the two engraved foregrounds (ink, +paper); only the background's contribution is replaced, so the engraving and the alpha padding are +untouched. Every frame comes from the committed stable master of its own size (the `.ico` and +`.icns` frames, the hicolor PNGs and the 1024 master), never from an upscale. + + packaging/nightly-icons.py # write the Nightly assets + packaging/nightly-icons.py --check # fail if the committed Nightly assets differ + +No third-party packages: zlib and struct only, as the build server has no Pillow or ImageMagick. +""" +import argparse +import hashlib +import io +import json +from pathlib import Path +import struct +import sys +import zlib + +ROOT = Path(__file__).resolve().parent.parent +ICONS = ROOT / "assets" / "app-icon" +STABLE_ID = "ai.storyteller.texturecraft" + +# The palette the artwork is drawn in, read from the tile itself (the three colours it is made of). +INK = (11, 11, 12) +PAPER = (239, 233, 220) +STABLE_BG = (194, 103, 43) +NIGHTLY_BG = (100, 52, 24) + +# How far a pixel may sit from the fitted blend before it is left alone (anti-aliased edges onto the +# transparent margin, and the few pixels that shade the tile itself). +RESIDUAL = 24 +PNG_MAGIC = b"\x89PNG\r\n\x1a\n" + +# Sizes the Nightly set carries (the 256 one is also the window and package icon). They live in +# `assets/app-icon/nightly/`, not in `hicolor/`: Stable's Linux and FreeBSD packagers copy that +# whole theme tree, so Nightly renders stored under it would ship in every Stable package. +NIGHTLY_SIZES = (16, 24, 32, 48, 64, 128, 256, 512) + + +def decode_png(data): + """(width, height, RGBA bytes) for an 8-bit RGB/RGBA PNG, filters included.""" + if data[:8] != PNG_MAGIC: + raise ValueError("not a PNG") + pos, idat, header = 8, [], None + while pos < len(data): + (length,) = struct.unpack(">I", data[pos:pos + 4]) + kind = data[pos + 4:pos + 8] + body = data[pos + 8:pos + 8 + length] + if kind == b"IHDR": + header = struct.unpack(">IIBBBBB", body) + elif kind == b"IDAT": + idat.append(body) + elif kind == b"IEND": + break + pos += 12 + length + if header is None: + raise ValueError("no IHDR") + width, height, depth, color, _compression, _filter, interlace = header + if depth != 8 or interlace != 0 or color not in (2, 6): + raise ValueError(f"unsupported PNG (depth {depth}, color {color}, interlace {interlace})") + channels = 3 if color == 2 else 4 + raw = zlib.decompress(b"".join(idat)) + stride = width * channels + out = bytearray(width * height * 4) + previous = bytearray(stride) + position = 0 + for row in range(height): + filter_type = raw[position] + position += 1 + line = bytearray(raw[position:position + stride]) + position += stride + if filter_type == 1: + for i in range(channels, stride): + line[i] = (line[i] + line[i - channels]) & 0xFF + elif filter_type == 2: + for i in range(stride): + line[i] = (line[i] + previous[i]) & 0xFF + elif filter_type == 3: + for i in range(stride): + left = line[i - channels] if i >= channels else 0 + line[i] = (line[i] + ((left + previous[i]) >> 1)) & 0xFF + elif filter_type == 4: + for i in range(stride): + a = line[i - channels] if i >= channels else 0 + b = previous[i] + c = previous[i - channels] if i >= channels else 0 + pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c) + predictor = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c) + line[i] = (line[i] + predictor) & 0xFF + elif filter_type != 0: + raise ValueError(f"unknown PNG filter {filter_type}") + if channels == 4: + out[row * width * 4:(row + 1) * width * 4] = line + else: + for x in range(width): + source = x * 3 + target = (row * width + x) * 4 + out[target:target + 3] = line[source:source + 3] + out[target + 3] = 255 + previous = line + return width, height, out + + +def encode_png(width, height, rgba): + raw = bytearray() + stride = width * 4 + for row in range(height): + raw.append(0) + raw.extend(rgba[row * stride:(row + 1) * stride]) + + def chunk(kind, body): + return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF) + + return ( + PNG_MAGIC + + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + + chunk(b"IEND", b"") + ) + + +def solve(pixel): + """(ink, paper, background) weights for one pixel, clamped to the three-colour simplex. + + The engraving is drawn as a mix of ink and paper over the tile, so a shaded grey is ink plus + paper with no background at all; only the background share moves in a Nightly icon. + """ + rows = [[INK[c] - STABLE_BG[c] for c in range(3)], [PAPER[c] - STABLE_BG[c] for c in range(3)]] + rhs = [pixel[c] - STABLE_BG[c] for c in range(3)] + a11 = sum(v * v for v in rows[0]) + a12 = sum(rows[0][c] * rows[1][c] for c in range(3)) + a22 = sum(v * v for v in rows[1]) + b1 = sum(rows[0][c] * rhs[c] for c in range(3)) + b2 = sum(rows[1][c] * rhs[c] for c in range(3)) + determinant = a11 * a22 - a12 * a12 + if determinant == 0: + return 0.0, 0.0, 1.0 + ink = (b1 * a22 - b2 * a12) / determinant + paper = (b2 * a11 - b1 * a12) / determinant + ink, paper = max(0.0, min(1.0, ink)), max(0.0, min(1.0, paper)) + if ink + paper > 1.0: + total = ink + paper + ink, paper = ink / total, paper / total + return ink, paper, 1.0 - ink - paper + + +def recolour(rgba): + """The same frame with only its background contribution moved to the Nightly colour.""" + out = bytearray(rgba) + cache = {} + for index in range(0, len(rgba), 4): + if rgba[index + 3] == 0: + continue + pixel = (rgba[index], rgba[index + 1], rgba[index + 2]) + got = cache.get(pixel) + if got is None: + ink, paper, background = solve(pixel) + fitted = tuple(ink * INK[c] + paper * PAPER[c] + background * STABLE_BG[c] for c in range(3)) + residual = sum(abs(pixel[c] - fitted[c]) for c in range(3)) + # A pixel the three-colour palette cannot explain is left exactly as it is. + if residual <= RESIDUAL: + got = bytes(min(255, max(0, round(ink * INK[c] + paper * PAPER[c] + background * NIGHTLY_BG[c]))) for c in range(3)) + else: + got = bytes(pixel) + cache[pixel] = got + out[index:index + 3] = got + return out + + +def read_icon_frames(container): + """(kind, name, png_bytes) frames of an .ico or .icns file, in file order.""" + if container[:4] == b"icns": + frames = [] + position = 8 + while position < len(container): + kind = container[position:position + 4] + (size,) = struct.unpack(">I", container[position + 4:position + 8]) + body = container[position + 8:position + size] + if body[:8] != PNG_MAGIC: + raise ValueError(f"{kind!r} is not a PNG frame; regenerate the stable .icns") + frames.append(("icns", kind, body)) + position += size + return frames + reserved, kind, count = struct.unpack("I", len(png) + 8) + png) + return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body) + + +def nightly_frames(container): + frames = read_icon_frames(container) + out = [] + for kind, name, png in frames: + width, height, rgba = decode_png(png) + out.append((kind, name, (width, height), encode_png(width, height, recolour(rgba)))) + return out + + +def targets(): + """Every Nightly asset the app and its packaging use, as (path, bytes).""" + assets = [] + icon_frames = nightly_frames((ICONS / "texturecraft.icns").read_bytes()) + assets.append((ICONS / "texturecraft-nightly.icns", write_icns([(name, png) for _kind, name, _size, png in icon_frames]))) + ico_frames = nightly_frames((ICONS / "texturecraft.ico").read_bytes()) + assets.append((ICONS / "texturecraft-nightly.ico", write_ico([(size, png) for _kind, _name, size, png in ico_frames]))) + for size in NIGHTLY_SIZES: + source = ICONS / "hicolor" / f"{size}x{size}" / "apps" / f"{STABLE_ID}.png" + width, height, rgba = decode_png(source.read_bytes()) + assets.append((ICONS / "nightly" / f"{size}.png", encode_png(width, height, recolour(rgba)))) + width, height, rgba = decode_png((ICONS / "texturecraft-1024.png").read_bytes()) + assets.append((ICONS / "texturecraft-nightly-1024.png", encode_png(width, height, recolour(rgba)))) + # The window icon is the same 256 render the Nightly set carries. + window = ICONS / "nightly" / "256.png" + assets.append((ICONS / "texturecraft-nightly.png", next(data for path, data in assets if path == window))) + return assets + + +def provenance(assets): + inputs = [ICONS / "texturecraft.icns", ICONS / "texturecraft.ico", ICONS / "texturecraft-1024.png"] + inputs += [ICONS / "hicolor" / f"{size}x{size}" / "apps" / f"{STABLE_ID}.png" for size in NIGHTLY_SIZES] + digest = lambda data: hashlib.sha256(data).hexdigest() + return { + "title": "TextureCraft nightly deep-background icons", + "license": "MIT OR Apache-2.0", + "generator": "packaging/nightly-icons.py", + "generator_sha256": digest(Path(__file__).read_bytes()), + "inputs": [{"path": str(path.relative_to(ROOT)), "sha256": digest(path.read_bytes())} for path in inputs], + "method": { + "kind": "derivative of the project-owned stable renders; no badge, crescent or letter", + "original_palette": {"ink": "#0b0b0c", "paper": "#efe9dc", "background": "#c2672b"}, + "nightly_background": "#643418", + "transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling.", + }, + "outputs": {str(path.relative_to(ROOT)): digest(data) for path, data in assets}, + "ico_frames": ["the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)"], + "icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)", + "validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole.", + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="fail if the committed assets differ from these bytes") + args = parser.parse_args() + assets = targets() + record = (json.dumps(provenance(assets), indent=2) + "\n").encode() + if args.check: + stale = [path for path, data in assets if not path.is_file() or path.read_bytes() != data] + if not (ICONS / "nightly-provenance.json").is_file() or (ICONS / "nightly-provenance.json").read_bytes() != record: + stale.append(ICONS / "nightly-provenance.json") + if stale: + for path in stale: + print(f"stale: {path.relative_to(ROOT)}", file=sys.stderr) + return 1 + print(f"{len(assets)} Nightly icon files match the generator") + return 0 + for path, data in assets: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + print(f"wrote {path.relative_to(ROOT)} ({len(data)} bytes)") + (ICONS / "nightly-provenance.json").write_bytes(record) + print("wrote assets/app-icon/nightly-provenance.json") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 00000000..ee421e95 --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +"""Local contract tests for TextureCraft nightly workflows and signing policy.""" +import copy +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +NIGHTLY_TRUST = { + "windows-x86_64": ("publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} + +# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot. +# Update by PR, in the caller and the policy, when the team changes. +RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"] + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract.""" + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != {"group": "texturecraft-nightly-release", "cancel-in-progress": "false"}: + raise ValueError("nightly serialization must use its stable group and no cancellation") + + +def job_conditions(jobs): + """Each job-level `if:` as (block indicator or None, the whole expression YAML would read).""" + lines = jobs.splitlines() + found = [] + for index, line in enumerate(lines): + head = re.fullmatch(r" if:(?: (.*))?", line) + if head is None: + continue + value = (head[1] or "").strip() + continuation = [] + for follow in lines[index + 1:]: + if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4: + break + continuation.append(follow.strip()) + indicator = value if re.fullmatch(r"[>|][+-]?", value) else None + parts = continuation if indicator else [value] + continuation + found.append((indicator, " ".join(part for part in parts if part))) + return found + + +def producer_platforms(source): + """Read the one producer job's literal platform list.""" + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +def reviewed_manual_actors(caller_source, policy): + """The one reviewed manual-actor list, identical in the producer caller and the policy.""" + rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source) + if len(rows) != 1: + raise ValueError("exactly one literal manual-actors list is required") + caller = json.loads(rows[0]) + if caller != policy["manual_actors"]: + raise ValueError("caller and policy must grant the same actors in the same order") + if caller != RELEASE_MANAGERS: + raise ValueError("manual actors must be exactly the reviewed release managers") + if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller): + raise ValueError("manual actors must be distinct and sorted case-insensitively") + if set(caller) & {login for login in policy["automatic_signer_actors"]}: + raise ValueError("manual and automatic actors overlap") + return caller + + +def caller_pin(name): + return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")): + source = (ROOT / ".github/workflows" / workflow).read_text() + expected = NightlyEnabledCallers.GUARDS[name] + guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] + for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"): + jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1] + with self.subTest(workflow=name, replacement=replacement[-30:]): + (indicator, expression), = job_conditions(jobs) + self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) + + def test_no_nightly_schedule_is_registered(self): + for name, event in (("nightly.yml", "workflow_dispatch"), + ("nightly-sign.yml", "workflow_dispatch")): + source = (ROOT / ".github/workflows" / name).read_text() + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + triggers = [line for line in events.splitlines() if line.startswith(" ") + and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] + with self.subTest(workflow=name): + self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + + def test_signer_serialization_contract_is_enforced(self): + assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) + + def test_weakened_or_malformed_serialization_is_rejected(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for old, new in ( + ("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"), + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("group: texturecraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: texturecraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() + if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry.""" + + def setUp(self): + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self): + self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}", + "the artifact kind is fixed by platform, never a caller pattern") + self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity") + + def test_trust_values_have_the_shapes_the_shared_signer_accepts(self): + rows = self.policy["platforms"] + self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$") + self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$") + subject = rows["windows-x86_64"]["trust"]["publisher_subject"] + self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"}) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + r"@(\S+)$", source) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actor.""" + + GUARDS = { + "nightly.yml": "github.repository == 'storytold/texturecraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +def push_block(source): + """The whole `push:` mapping, blank lines and nested keys included. + + A blank line does not end a YAML mapping, so the block is delimited by indentation rather than + by contiguous non-empty lines; a path filter after a blank line stays visible to the check. + """ + lines = source.splitlines() + for index, line in enumerate(lines): + if re.fullmatch(r" push:.*", line): + block = [] + for follow in lines[index + 1:]: + if follow.strip() and not follow.startswith(" "): + break + block.append(follow) + return "\n".join(block) + return None + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + def setUp(self): + self.assertFalse(INSTALLED_POLICY.is_symlink()) + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_exact_v3_fields_and_repository_identity(self): + expected = {"schema", "repository", "repository_id", "producer_workflow_id", + "producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref", + "signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors", + "automatic_signer_actors", "max_age_seconds", "candidate_policy", + "max_artifact_bytes", "platforms"} + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/texturecraft") + self.assertEqual(self.policy["release_branch"], "release") + self.assertIs(type(self.policy["repository_id"]), int) + self.assertGreater(self.policy["repository_id"], 0) + # producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int. + prod_id = self.policy["producer_workflow_id"] + if prod_id is not None: + self.assertIs(type(prod_id), int) + self.assertGreater(prod_id, 0) + self.assertNotEqual(prod_id, + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow") + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual(self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin) + + def test_platforms_equal_the_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + + def test_bounds(self): + self.assertIs(type(self.policy["max_age_seconds"]), int) + self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800) + self.assertIs(type(self.policy["max_artifact_bytes"]), int) + self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3) + + def test_candidate_workflows_run_on_every_main_push(self): + candidate = self.policy["candidate_policy"] + self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/texturecraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = push_block(source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn("branches: [main]", push) + self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_a_path_filter_after_a_blank_line_is_still_rejected(self): + workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n" + block = push_block(workflow) + self.assertIsNotNone(block) + self.assertIn("branches: [main]", block) + self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:") + for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"): + with self.subTest(ignored=ignored): + variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored) + self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:", + "a quoted or unquoted filter must not hide behind a blank line") + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + self.assertEqual(sonar["organization"], "storytold") + self.assertEqual(sonar["project"], "storytold_texturecraft") + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main") + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100755 index 00000000..0ff2ff4f --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Run the synthetic Nightly packaging suites together; no app build, signing or network. + +Suites that a checkout does not carry are skipped with a note: the Linux archive suite belongs to +whoever owns `nightly-archive.py`, and this branch does not add one. +""" +import importlib.util +from pathlib import Path +import sys +import unittest + + +def load(here, name, relative, suite): + path = here / relative + if not path.is_file(): + print(f"skip: {relative} is not in this checkout", file=sys.stderr) + return + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + + +def icons_match(here) -> bool: + """The committed Nightly icons must be exactly what the generator derives from the masters.""" + import subprocess + result = subprocess.run([sys.executable, str(here / "nightly-icons.py"), "--check"], capture_output=True, text=True) + print(result.stdout.strip(), file=sys.stderr) + if result.returncode != 0: + print(result.stderr.strip(), file=sys.stderr) + return result.returncode == 0 + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + load(here, "texturecraft_archive_suite", "nightly-archive-tests.py", suite) + load(here, "texturecraft_plist_suite", "macos/nightly_plist_tests.py", suite) + load(here, "texturecraft_release_dispatch_suite", "nightly-release-tests.py", suite) + load(here, "texturecraft_mac_sign_suite", "macos/nightly_sign_tests.py", suite) + passed = unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() + return 0 if passed and icons_match(here) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 00000000..79219858 --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 00000000..35a7811c --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'texturecraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'texturecraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.texturecraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'TextureCraft Nightly' 'TextureCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('TextureCraft', 'TextureCraft 0.23.1 (nightly-v1)'), @('TextureCraft Nightly', 'TextureCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.23.1-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/texturecraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'texturecraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 00000000..bf3bf959 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,104 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +# The source preflight reads the real checkout; the fixture answers for its own commit, whose sha +# the version names, so the clean case reaches the mocked compiler instead of the preflight. +function global:git { + param([Parameter(ValueFromRemainingArguments=$true)][object[]] $Arguments) + $joined = ($Arguments | ForEach-Object { "$_" }) -join ' ' + if ($joined -match 'rev-parse HEAD$') { $global:LASTEXITCODE = 0; return ('a' * 40) } + if ($joined -match 'status --porcelain$') { $global:LASTEXITCODE = 0; return '' } + throw "the fixture must not run git: $joined" +} +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +# The caller's own values, restored in `finally`: this script may run inside a developer's session. +$savedEnvironment = foreach ($name in (@('TEXTURECRAFT_VERSION', 'TEXTURECRAFT_BUILD_SHA', 'TEXTURECRAFT_BUILD_DATE') + $names)) { + [pscustomobject]@{ Name = $name; Value = [Environment]::GetEnvironmentVariable($name) } +} +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa' +$env:TEXTURECRAFT_VERSION = $version +# The identity the version names: the mocked HEAD and its run date. +$env:TEXTURECRAFT_BUILD_SHA = 'a' * 40 +$env:TEXTURECRAFT_BUILD_DATE = '2026-11-21' +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + # Put back exactly what the caller had (an unset variable is restored as unset), and drop the + # command mocks: a `function global:` binding outlives this script and outranks the real program. + foreach ($entry in $savedEnvironment) { [Environment]::SetEnvironmentVariable($entry.Name, $entry.Value) } + foreach ($mock in @('cargo', 'git', 'Invoke-WebRequest')) { + Remove-Item -LiteralPath "function:global:$mock" -ErrorAction SilentlyContinue + } + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 00000000..e7f610fc --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,131 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "texturecraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "texturecraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('texturecraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.texturecraft.nightly-v1' + } +} + +# The same source identity the Unix helper enforces (nightly-common.sh): the version names the +# commit being built, the date is the original run's, and the tree is clean. +function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) { + if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (TEXTURECRAFT_BUILD_SHA)' } + if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' } + if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (TEXTURECRAFT_BUILD_DATE)' } + $versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8) + if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' } + if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' } + if ($Status) { throw 'nightly packaging requires the frozen clean source' } +} + +function Get-NightlySourceState([string] $RepositoryRoot) { + $head = git -C $RepositoryRoot rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' } + $status = git -C $RepositoryRoot status --porcelain + if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' } + return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + if ($ProductName -ne 'TextureCraft Nightly' -or $VersionOutput -cne "TextureCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:TEXTURECRAFT_VERSION -or $Version -cne $env:TEXTURECRAFT_VERSION) { throw 'nightly-v1 requires explicit TEXTURECRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' } +# No key values may enter compilation. This produces an internal intermediate, not a feed artifact. +& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$Source = Get-NightlySourceState $Root +Assert-NightlySource $Version $env:TEXTURECRAFT_BUILD_SHA $env:TEXTURECRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:TEXTURECRAFT_BUILD_CHANNEL +try { + # `build.rs` reads TEXTURECRAFT_VERSION (checked equal above) and this channel. + $env:TEXTURECRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:TEXTURECRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + # The GUI only: a Nightly install ships no CLI. + cargo build --release --locked -p texturecraft --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:TEXTURECRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:TEXTURECRAFT_BUILD_SHA $env:TEXTURECRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\texturecraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'TextureCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'texturecraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate name cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'texturecraft-cli.exe')) -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('texturecraft.exe' -notin $Names -or 'texturecraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index a5241d21..7296e424 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -21,9 +21,12 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -50,12 +53,23 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' } $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' } New-Item -ItemType Directory -Force -Path $Dist | Out-Null -if (-not $env:TEXTURECRAFT_BUILD_SHA) { $env:TEXTURECRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:TEXTURECRAFT_BUILD_DATE) { $env:TEXTURECRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:TEXTURECRAFT_BUILD_SHA) { $env:TEXTURECRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:TEXTURECRAFT_BUILD_DATE) { $env:TEXTURECRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "TextureCraft $Version for Windows $Arch ($Target)" +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + if ($LASTEXITCODE -ne 0) { throw "nightly packaging failed: $LASTEXITCODE" } + return +} + if (-not $SkipBuild) { + $env:TEXTURECRAFT_BUILD_CHANNEL = 'stable' + # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -83,6 +97,9 @@ foreach ($check in @(@('texturecraft.exe', 2), @('texturecraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +if ((Get-Item -LiteralPath (Join-Path $Bin 'texturecraft.exe')).VersionInfo.ProductName -eq 'TextureCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 794dd266..c9fa6ea6 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,7 +9,9 @@ AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net), AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds - still produce installers. + still produce installers. Nightly callers require signing with -Required and can + check signing configuration with -Required -CheckOnly. Compilation uses the + separate -CheckBuildEnvironment mode, without importing signing keys. This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). @@ -18,8 +20,11 @@ pwsh packaging/windows/sign.ps1 dist/texturecraft.exe dist/TextureCraft.msi #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' @@ -27,6 +32,12 @@ function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } +function Assert-AuthenticodeSignature($Signature) { + if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) { + throw 'Required signing must produce a valid Authenticode signature and signer certificate' + } +} + function Find-SignTool { if ($env:SIGNTOOL) { return $env:SIGNTOOL } $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue @@ -44,11 +55,28 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +if ($CheckBuildEnvironment) { + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -89,6 +117,9 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 00000000..21de440a --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1 @@ +sonar.coverage.exclusions=packaging/** From b1c8bd67184668bf50fdfc795bce53a73ac59076 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:36:09 +0000 Subject: [PATCH 126/153] Generators: a click on the preview opens it enlarged in a tool window, following the settings --- crates/ui-egui/src/generator_panel.rs | 52 +++++++++++++--- .../ui-egui/src/generator_preview_window.rs | 61 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/state.rs | 3 + crates/ui-egui/src/thumbs.rs | 10 +-- crates/ui-egui/src/windows.rs | 1 + crates/ui-egui/tests/it/generator_panel.rs | 39 ++++++++++++ 7 files changed, 153 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/generator_preview_window.rs diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 270ff5e1..dc4efa55 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -1,6 +1,6 @@ //! A generator effect's properties, laid out like the reference app's: its slot, Parameters, Image inputs, Resolution, Attributes -use egui::{Painter, Rect, TextureHandle}; +use egui::{CursorIcon, Painter, Rect, Role, Sense, Stroke, StrokeKind, TextureHandle, WidgetInfo}; use serde_json::json; use texturecraft_engine::core::{ CookResolution, Generator, GeneratorKind, KindControls, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters, @@ -103,7 +103,7 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, // The Curvature size under the pointer shows alone in the preview: the columns are drawn after it, so it is kept from the frame before let solo_id = sheet.ui.make_persistent_id(("generator_solo", id)); - let mut solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); + let solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); let solo_texture = match (kind, generator.detail_in_use(), solo) { (GeneratorKind::Curvature, Some(detail), Some(size)) => { app.thumbs.generator_picture(&ctx, ShelfPreview::Curvature { mode: detail.mode, solo: Some(size) }, PREVIEW_ORB_PX) @@ -116,37 +116,71 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, let texture = solo_texture .or_else(|| app.thumbs.generator_set_picture(&ctx, id, set, PREVIEW_ORB_PX)) .or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); - let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); + let drawn_at = std::cell::Cell::new(None); + let picture = |painter: &Painter, rect: Rect| { + drawn_at.set(Some(rect)); + orb(painter, rect, texture.as_ref(), &tokens, &ctx); + }; + rows(app, sheet, (layer, id), generator, &picture, solo_id); + if let Some(rect) = drawn_at.get() { + enlarge_on_click(app, sheet, id, rect); + } +} + +/// The preview opens enlarged in its own window on a click: a grey outline shows it can while the pointer is on it, and that it is open +fn enlarge_on_click(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, rect: Rect) { + let response = sheet.ui.interact(rect, sheet.ui.make_persistent_id(("generator_preview_enlarge", id)), Sense::click()).on_hover_cursor(CursorIcon::ZoomIn); + let open = app.ui.windows.generator_preview == Some(id); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, open, tr("Enlarge preview"))); + if response.hovered() || response.has_focus() || open { + let tokens = Tokens::get(sheet.ui.ctx()); + sheet.ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); + } + if response.clicked() { + crate::generator_preview_window::toggle(app, id); + } +} + +/// The kind's rows, `picture` drawing the preview; `solo_id` keeps the Curvature size under the pointer for the next frame's preview +fn rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + (layer, id): (LayerId, u64), + generator: &Generator, + picture: &dyn Fn(&Painter, Rect), + solo_id: egui::Id, +) { + let kind = generator.kind; if let Some(controls) = generator.kind_controls() { - crate::generator_kind_rows::kind_rows(app, sheet, id, generator, controls, &picture); + crate::generator_kind_rows::kind_rows(app, sheet, id, generator, controls, picture); return; } if let Some(defaults) = WearParameters::defaults(kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them - wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), &picture); + wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), picture); return; } if let Some(light) = generator.light { - light_rows(app, sheet, id, Some(generator.invert), light, &picture); + light_rows(app, sheet, id, Some(generator.invert), light, picture); return; } - global_rows(app, sheet, id, generator, &picture); + global_rows(app, sheet, id, generator, picture); if generator.on_earlier_model() { ramp_rows(app, sheet, id, generator); } // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(kind) { - solo = None; + let mut solo = None; section_rows(app, sheet, id, generator, generator.section_controls().unwrap_or(defaults), &mut solo); texture_card(app, sheet, (layer, id), generator.texture.as_deref().cloned().unwrap_or_default()); micro_switch_card(app, sheet, (layer, id), generator); sheet.ui.data_mut(|data| data.insert_temp(solo_id, solo)); } if let Some(defaults) = LightParameters::defaults(kind) { - light_rows(app, sheet, id, None, defaults, &picture); + light_rows(app, sheet, id, None, defaults, picture); } } diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs new file mode 100644 index 00000000..e8a8d406 --- /dev/null +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -0,0 +1,61 @@ +//! A generator's preview enlarged in a tool window, following its settings while they change + +use egui::{Rect, Sense, pos2}; +use texturecraft_engine::core::{EffectKind, LayerId}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; + +/// The width the enlarged picture is rendered at, in pixels: the most a preview renders +const PICTURE_PX: usize = texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; + +/// The window's first width, in points +const DEFAULT_WIDTH: f32 = 420.0; + +/// The narrowest the picture shrinks to, in points +const MIN_SIDE: f32 = 160.0; + +/// How soon a picture still rendering is looked for again +const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); + +/// The open enlarged preview, if any: closed by its ×, and when its generator is gone +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(effect) = app.ui.windows.generator_preview else { return }; + let generator = match app.session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => generator.clone(), + _ => { + app.ui.windows.generator_preview = None; + return; + } + }; + + let set = ShelfPreview::generator_set(&generator, &app.session.images); + let texture = app.thumbs.generator_set_picture(ctx, effect, set, PICTURE_PX); + let tokens = Tokens::get(ctx); + let mut open = true; + crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH).show(ctx, |ui| { + let side = ui.available_width().max(MIN_SIDE); + let (rect, response) = ui.allocate_exact_size(egui::vec2(side, side), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Preview"))); + match &texture { + Some(texture) => { + ui.painter().image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => { + ui.painter().rect_filled(rect, 0.0, tokens.button); + ctx.request_repaint_after(PICTURE_POLL); + } + } + }); + if !open { + app.ui.windows.generator_preview = None; + } +} + +/// Opens generator effect `effect`'s enlarged preview, or closes it when it is the one open +pub(crate) fn toggle(app: &mut TextureCraftApp, effect: u64) { + let open = &mut app.ui.windows.generator_preview; + *open = if *open == Some(effect) { None } else { Some(effect) }; +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f13365a8..498f6f28 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -50,6 +50,7 @@ mod generator_kind_rows; mod generator_panel; mod generator_params; mod generator_point_pick; +mod generator_preview_window; mod generator_section_rows; mod generator_slot; mod generator_wear_rows; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ae9d4980..b1a7483a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -121,6 +121,9 @@ pub struct Windows { /// Window ▸ Reset UI is waiting for its answer. #[serde(skip)] pub confirm_reset_ui: bool, + /// The generator effect whose preview is open enlarged in its own window + #[serde(skip)] + pub generator_preview: Option, } /// An action that replaces or ends the project, held while the project has unsaved changes. diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 82755d8b..38552ce4 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -64,8 +64,8 @@ pub struct Thumbs { big_shown: VecDeque, /// The frame that last took in the worker's results received_in_pass: u64, - /// Per generator panel: the picture of its settings being rendered, and the last one finished (shown meanwhile) - set_pictures: HashMap, Option)>, + /// Per generator effect and picture size: the picture of its settings being rendered, and the last one finished (shown meanwhile) + set_pictures: HashMap<(u64, usize), (Option, Option)>, } impl Thumbs { @@ -312,7 +312,7 @@ impl Thumbs { self.receive(ctx); let size_px = size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX); let key = self.worker_key(&preview, size_px); - let (in_flight, last) = self.set_pictures.get(&effect).cloned().unwrap_or_default(); + let (in_flight, last) = self.set_pictures.get(&(effect, size_px)).cloned().unwrap_or_default(); // The picture in flight landed: it is the latest shown let last = match in_flight.as_ref().map(|key| self.rendered.get(key)) { @@ -326,7 +326,7 @@ impl Thumbs { None => self.big(ctx, preview, size_px).or_else(|| last.clone()), }; let in_flight = if busy { in_flight } else { Some(key) }; - self.set_pictures.insert(effect, (in_flight, shown.clone().or(last))); + self.set_pictures.insert((effect, size_px), (in_flight, shown.clone().or(last))); shown } @@ -505,7 +505,7 @@ mod tests { let last = ctx.load_texture("last", ColorImage::filled([1, 1], Color32::RED), TextureOptions::LINEAR); let rendering = thumbs.worker_key(&set(false), 8); thumbs.rendered.insert(rendering.clone(), WorkerPreview::Rendering); - thumbs.set_pictures.insert(1, (Some(rendering), Some(last.clone()))); + thumbs.set_pictures.insert((1, 8), (Some(rendering), Some(last.clone()))); let shown = thumbs.generator_set_picture(&ctx, 1, set(true), 8); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9e8fa5c..240f43ed 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -33,6 +33,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { unsaved(app, ctx); reset_ui(app, ctx); crate::named_layouts::show(app, ctx); + crate::generator_preview_window::show(app, ctx); } /// Window ▸ Reset UI asks first: Escape closes the question, Enter answers Reset. diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 5d2e24b1..245bffcd 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -517,3 +517,42 @@ fn new_kind_panel_snapshots() { } } } + +#[test] +fn the_preview_opens_enlarged_in_its_own_window() { + let (mut harness, effect) = harness_with(false, json!({"generator": "edgeWear"})); + let enlarged = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_role_and_label(Role::Image, "Preview").is_some(); + assert!(!enlarged(&harness)); + + click_live(&mut harness, Role::Button, "Enlarge preview"); + assert!(enlarged(&harness), "a click on the preview opens it enlarged"); + assert!(is_on(&harness, Role::Button, "Enlarge preview"), "the preview shows it is open"); + + click_live(&mut harness, Role::Button, "Enlarge preview"); + assert!(!enlarged(&harness), "a second click closes it"); + + click_live(&mut harness, Role::Button, "Enlarge preview"); + execute(&mut harness.state_mut().session, "effect.remove", &json!({"effect": effect.0})).unwrap(); + harness.run_steps(3); + assert!(!enlarged(&harness), "it closes with its generator"); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn enlarged_preview_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, _) = harness_with(true, json!({"generator": "edgeWear", "seed": 12})); + click_live(&mut harness, Role::Button, "Enlarge preview"); + + // The pictures render on the preview worker + for _ in 0..60 { + harness.run_steps(4); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-enlarged-preview-{name}.png"))).unwrap(); + } +} From 99c14baaed6b05d81b9724c6eb4dfa2b38be24ac Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:38:54 +0000 Subject: [PATCH 127/153] Map preview tests wait up to a minute for a bake, not a fixed number of frames --- crates/ui-egui/tests/it/bake_live_preview.rs | 52 ++++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs index 5944e3ce..848543c9 100644 --- a/crates/ui-egui/tests/it/bake_live_preview.rs +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -8,8 +8,11 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::Mode; -/// How long a steady drag may take to bring its first new pictures, on a slow machine -const MOVING_DRAG_LIMIT: std::time::Duration = std::time::Duration::from_secs(20); +/// How long a preview bake may take on a busy CI machine running every test at once +const PREVIEW_LIMIT: std::time::Duration = std::time::Duration::from_secs(60); + +/// How long the tests let the worker run between frames while they wait +const WAIT_STEP: std::time::Duration = std::time::Duration::from_millis(10); /// Bake mode on the sample with Ambient Occlusion's settings in front fn harness() -> Harness<'static, TextureCraftApp> { @@ -28,18 +31,27 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } -/// The size of the picture the preview shows for the first set, once it is `wanted` (the worker gets a few seconds) -fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option { - for _ in 0..600 { +/// Run frames until `done` holds, letting the worker run between them; false when the preview limit passes first +fn run_until(harness: &mut Harness<'static, TextureCraftApp>, mut done: impl FnMut(&Harness<'static, TextureCraftApp>) -> bool) -> bool { + let started = std::time::Instant::now(); + while started.elapsed() < PREVIEW_LIMIT { harness.run_steps(1); - let shown = - harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution)); - if shown.is_some_and(&wanted) { - return shown; + if done(harness) { + return true; } - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(WAIT_STEP); } - None + false +} + +/// The size of the picture the preview shows for the first set +fn shown_size(harness: &Harness<'static, TextureCraftApp>) -> Option { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution)) +} + +/// The size of the picture the preview shows for the first set, once it is `wanted` +fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option { + run_until(harness, |harness| shown_size(harness).is_some_and(&wanted)).then(|| shown_size(harness)).flatten() } #[test] @@ -107,7 +119,7 @@ fn pictures_keep_coming_while_the_slider_is_still_moving() { let mut pictures = 0; let started = std::time::Instant::now(); for step in 0.. { - if pictures > 2 || started.elapsed() > MOVING_DRAG_LIMIT { + if pictures > 2 || started.elapsed() > PREVIEW_LIMIT { break; } @@ -139,15 +151,7 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() // A change that doesn't come from the panel: a script, an undo or a synced set let before = picture(&harness); harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } })); - let mut changed = false; - for _ in 0..600 { - harness.run_steps(1); - if picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) { - changed = true; - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } + let changed = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); assert!(changed, "the settings change brings a new picture"); // The same file loaded again: same name, new geometry @@ -158,11 +162,7 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() } session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); let before = picture(&harness); - let reloaded = (0..600).any(|_| { - harness.run_steps(1); - std::thread::sleep(std::time::Duration::from_millis(10)); - picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) - }); + let reloaded = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); assert!(reloaded, "high poly load {index} brings a new picture"); } } From 577981a3d2537a5a7922fa64be26ca4feee6f5e5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:44:17 +0000 Subject: [PATCH 128/153] Generators: the enlarged preview first opens beside the small one --- crates/ui-egui/src/generator_panel.rs | 3 ++- crates/ui-egui/src/generator_preview_window.rs | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index dc4efa55..b07914a4 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -138,7 +138,8 @@ fn enlarge_on_click(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id sheet.ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); } if response.clicked() { - crate::generator_preview_window::toggle(app, id); + let ctx = sheet.ui.ctx().clone(); + crate::generator_preview_window::toggle(app, &ctx, id, rect); } } diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs index e8a8d406..fbdc227b 100644 --- a/crates/ui-egui/src/generator_preview_window.rs +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -17,6 +17,9 @@ const DEFAULT_WIDTH: f32 = 420.0; /// The narrowest the picture shrinks to, in points const MIN_SIDE: f32 = 160.0; +/// From the small preview's left edge to the window's right edge when it first opens, in points: clear of the properties panel +const BESIDE_GAP: f32 = 24.0; + /// How soon a picture still rendering is looked for again const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); @@ -35,7 +38,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let texture = app.thumbs.generator_set_picture(ctx, effect, set, PICTURE_PX); let tokens = Tokens::get(ctx); let mut open = true; - crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH).show(ctx, |ui| { + let beside = + ctx.data(|data| data.get_temp::(anchor_id())).map_or(ctx.content_rect().center(), |small| pos2(small.left() - BESIDE_GAP, small.center().y)); + let window = crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH); + window.default_pos(beside).pivot(egui::Align2::RIGHT_CENTER).show(ctx, |ui| { let side = ui.available_width().max(MIN_SIDE); let (rect, response) = ui.allocate_exact_size(egui::vec2(side, side), Sense::hover()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Preview"))); @@ -54,8 +60,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// Opens generator effect `effect`'s enlarged preview, or closes it when it is the one open -pub(crate) fn toggle(app: &mut TextureCraftApp, effect: u64) { +/// Opens generator effect `effect`'s enlarged preview beside its small one at `small`, or closes it when it is the one open +pub(crate) fn toggle(app: &mut TextureCraftApp, ctx: &egui::Context, effect: u64, small: Rect) { + ctx.data_mut(|data| data.insert_temp(anchor_id(), small)); let open = &mut app.ui.windows.generator_preview; *open = if *open == Some(effect) { None } else { Some(effect) }; } + +/// Where the small preview was when the window was asked for: it first opens beside it +fn anchor_id() -> egui::Id { + egui::Id::unique("generator_preview_anchor") +} From 582c6853b5984fa1ceb9ec3ea79ebab4503c1f5d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:57:26 +0000 Subject: [PATCH 129/153] Bake mode pass 2: review fixes - Automatic cage: coincident vertices of different mesh-name groups keep separate distances - A sync edit fails, changing no set, when a partner's merged settings would be invalid - A high poly read during a paint stroke is added once the stroke ends, so its cancel or undo keeps it - Quick bake and the map preview read the low poly's colours for the requested map even when it is unchecked - The set picker's differing-values note compares with the set bake.sync will take settings from - Map thumbnails redraw when the UV tiles' scales change - Checkbox drags start on the primary button only and reach rows crossed between two frames - A long texture set name or folder is cut to fit its row - Map preview tests require a new picture, not just a missing one --- crates/bake/src/cage/fitted_cage.rs | 30 +++++++++- crates/bake/src/test/fitted_cage.rs | 36 ++++++++++++ crates/core/src/project.rs | 6 ++ crates/engine/src/bake/mesh_map_command.rs | 58 ++++++++++++++++--- crates/engine/src/bake/sync_command.rs | 17 ++++-- crates/ui-egui/src/bake_mode/breadcrumb.rs | 10 +++- crates/ui-egui/src/bake_mode/live_preview.rs | 3 +- .../ui-egui/src/bake_mode/map_thumbnails.rs | 20 +++++-- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 50 ++++++++++++---- crates/ui-egui/src/bake_mode/set_picker.rs | 52 ++++++++++++----- crates/ui-egui/src/high_poly_job.rs | 7 ++- crates/ui-egui/src/lib.rs | 12 ++-- .../ui-egui/src/property_sheet/file_list.rs | 37 +++++++++--- crates/ui-egui/tests/it/bake_live_preview.rs | 9 ++- crates/ui-egui/tests/it/bake_map_rows.rs | 35 ++++++++++- crates/ui-egui/tests/it/bake_mode.rs | 11 ++++ crates/ui-egui/tests/it/high_poly_loading.rs | 29 ++++++++++ 17 files changed, 358 insertions(+), 64 deletions(-) diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs index 088dae2f..54bbde47 100644 --- a/crates/bake/src/cage/fitted_cage.rs +++ b/crates/bake/src/cage/fitted_cage.rs @@ -2,7 +2,7 @@ use super::name_keys::NameKeys; use crate::map::interpolate; use crate::{BakeRequest, HighPoly, MeshExtent}; use rayon::prelude::*; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use texturecraft_geom::Mesh; use texturecraft_geom::glam::Vec3; @@ -26,6 +26,7 @@ impl FittedCage { pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { let low = request.mesh; let keys = NameKeys::of(request, high); + let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); let mut reach: Vec> = vec![None; welded_count]; @@ -71,6 +72,23 @@ impl FittedCage { } } +/// `welded_indices` with the vertices of different mesh-name groups (`vertex_keys`, empty when names don't matter) kept apart, so a group's distances come only from its own high poly and never spread into another group +fn welded_within_groups(welded_indices: &[u32], vertex_keys: &[u32]) -> Vec { + if vertex_keys.is_empty() { + return welded_indices.to_vec(); + } + + let mut indices: HashMap<(u32, Option), u32> = HashMap::new(); + welded_indices + .iter() + .enumerate() + .map(|(vertex, &welded)| { + let next = indices.len() as u32; + *indices.entry((welded, vertex_keys.get(vertex).copied())).or_insert(next) + }) + .collect() +} + /// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { low.positions @@ -153,7 +171,15 @@ fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterat #[cfg(test)] mod tests { - use super::spread_to_neighbours; + use super::{spread_to_neighbours, welded_within_groups}; + + #[test] + fn coincident_vertices_of_different_name_groups_are_not_welded() { + // Vertices 0 and 1 share a position, as do 2 and 3; 1 and 2 are in group 7, the others in group 5 + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]), [0, 1, 2, 3]); + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]), [0, 0, 1, 1], "same group: still welded"); + assert_eq!(welded_within_groups(&[0, 0, 1], &[]), [0, 0, 1], "without name matching nothing changes"); + } #[test] fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index 3aa96e6b..903c5c99 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -148,3 +148,39 @@ fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); } + +#[test] +fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.3; + + // Two low parts sharing the edge x = 0, under a low and a raised high-poly part matched by name + let part = |name: &str, side: f32, height: f32, subdivisions: usize| { + let mut part = primitives::plane(1.0, subdivisions); + for position in &mut part.positions { + *position += Vec3::new(side * 0.5, height, 0.0); + } + part.submeshes[0].name = name.into(); + part + }; + let mut low = part("left_low", -1.0, 0.0, 4); + low.append(&part("right_low", 1.0, 0.0, 4)); + let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); + high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + for mesh in [&mut low, &mut high] { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } + } + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The left part's triangles come first, three corners each + let left_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..left_corners] { + assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); + } +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 6bcf92e4..b8e66cd4 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -489,6 +489,12 @@ impl Project { } } + /// The set whose `group` settings the sets joining a sync of `members` take: one of them already sharing the group, else `active` when it is one of them, else the first + pub fn bake_sync_source(&self, group: BakeSyncGroup, members: &[usize], active: usize) -> Option { + let staying = members.iter().copied().find(|index| self.texture_sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); + staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()) + } + pub fn layer(&self, id: LayerId) -> Result<&Layer> { self.layers.get(&id).ok_or(CoreError::NoLayer(id)) } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 6bb70d19..3e544857 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -117,15 +117,30 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } impl Session { + /// The bake of texture set `texture_set`'s checked maps pub fn bake_task(&self, texture_set: usize) -> Result { + self.bake_task_of(texture_set, None) + } + + /// The bake of texture set `texture_set`'s map `map` alone, checked or not + pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result { + self.bake_task_of(texture_set, Some(map)) + } + + fn bake_task_of(&self, texture_set: usize, only: Option) -> 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))); } - 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.doc.bake_meshes.high.is_empty()) { + let mut settings = set.bake.clone(); + if let Some(map) = only { + settings.maps.select([map]); + } + // Read from the maps that bake, so a map baked alone while unchecked still gets the colours + let needs_low_color = settings.maps.opacity.is_enabled + || (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); + let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) { self.doc .bake_meshes .low_base_color @@ -158,7 +173,7 @@ impl Session { mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, - settings: set.bake.clone(), + settings, high, cage, skew, @@ -730,14 +745,19 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { let targets = updated_settings(session, params, command)?; let sets = targets.iter().map(|(index, _)| *index).collect(); - let next = with_sync_partners(&session.doc.project, targets, command)?; + let next = with_sync_partners(&session.doc.project, targets, command, boolp(params, "preset") == Some(true))?; super::sync_command::store(session, "Bake Settings", next)?; Ok(sets) } -/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group -fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { +/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's settings come out invalid (`from_preset`: preset limits apply) +fn with_sync_partners( + project: &texturecraft_core::Project, + targets: Vec<(usize, BakeSettings)>, + command: &str, + from_preset: bool, +) -> Result> { let mut next: BTreeMap = BTreeMap::new(); for (target, settings) in &targets { let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue }; @@ -755,6 +775,10 @@ fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, } } } + // A field valid beside the target's other values can be invalid beside a partner's: min above the partner's max + for (partner, settings) in &next { + validate_model_settings(settings, command, from_preset, project.texture_sets.get(*partner).map(|set| &set.bake))?; + } next.extend(targets); Ok(next.into_iter().collect()) } @@ -861,3 +885,23 @@ mod gpu_raytracing_tests { assert!(chosen_tracer(None, true).is_none(), "no installed tracer bakes on the CPU"); } } + +#[cfg(test)] +mod bake_task_tests { + use std::sync::Arc; + + use texturecraft_core::BakedMap; + + #[test] + fn a_map_baked_alone_while_unchecked_still_reads_the_low_polys_colours() { + let mut session = crate::sample_session(64, 64).unwrap(); + session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); + let colours = Arc::new(vec![None]); + let _ = session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())); + + assert!(session.bake_task(0).unwrap().low_base_color.is_empty(), "the checked maps need no colours"); + let task = session.bake_task_only(0, BakedMap::Opacity).unwrap(); + assert!(Arc::ptr_eq(&task.low_base_color, &colours), "Opacity reads them"); + assert!(task.settings.maps.opacity.is_enabled); + } +} diff --git a/crates/engine/src/bake/sync_command.rs b/crates/engine/src/bake/sync_command.rs index e244e507..88018b6f 100644 --- a/crates/engine/src/bake/sync_command.rs +++ b/crates/engine/src/bake/sync_command.rs @@ -51,10 +51,7 @@ fn sync(session: &mut Session, params: &Value) -> Result { let members = sets_param(session, COMMAND, params)?; let sets = &session.doc.project.texture_sets; - // Additions take the settings of a set that already shares them; with none left, of the active set when it joins, else of the first - let staying = members.iter().copied().find(|index| sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); - let active = session.ts(); - let source = staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()); + let source = session.doc.project.bake_sync_source(group, &members, session.ts()); let source = source.and_then(|index| sets.get(index)).map(|set| set.bake.clone()); let next: Vec<(usize, BakeSettings)> = sets @@ -265,4 +262,16 @@ mod tests { assert_eq!(bake(&session, 1).maps.ao.parameters.rays.rays, 6); assert_eq!(bake(&session, 1).common.dilation, 3); } + + #[test] + fn an_edit_that_would_leave_a_synced_set_with_an_invalid_interval_changes_no_set() { + let mut session = session(); + session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.max_distance = 0.5; + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.max_distance = 0.05; + let before = session.doc.project.texture_sets.clone(); + + let patch = json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "min_distance": 0.1 } } } } } }); + assert!(execute(&mut session, "bake.settings", &patch).is_err(), "set 1 would get a minimum above its maximum"); + assert_eq!(session.doc.project.texture_sets, before); + } } diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs index 2ece6800..ac3cda17 100644 --- a/crates/ui-egui/src/bake_mode/breadcrumb.rs +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -26,7 +26,7 @@ const RESET_BOX: f32 = 20.0; /// Size of the names const NAME_SIZE: f32 = 12.0; -/// › texture set › map above Mesh Map Settings, each caret a menu to switch it, with ⟲ (Restore Defaults) at the right when the map has parameters; returns whether ⟲ was clicked +/// › texture set › map above Mesh Map Settings, each caret a menu to switch it, with ⟲ (Restore Defaults) at the right when the map has parameters; a long set name is cut with "…"; returns whether ⟲ was clicked pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, restorable: bool) -> bool { let tokens = Tokens::get(ui.ctx()); let active_set = app.session.ts(); @@ -39,13 +39,17 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, r let set_caret = caret(ui, &painter, &tokens, x, center_y, "texture_set_caret", tr("Switch Texture Set")); x += CARET_BOX + CARET_TO_NAME; let set_name = set_names.get(active_set).map_or("", String::as_str); - let set_galley = painter.layout_no_wrap(set_name.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let map_name = tr(baked_map_label(selected)); + let map_width = painter.layout_no_wrap(map_name.to_owned(), semibold(NAME_SIZE), tokens.text_strong).size().x; + let reset_width = if restorable { RESET_BOX } else { 0.0 }; + let set_room = line.right() - reset_width - map_width - CARET_TO_NAME - CARET_BOX - NAME_TO_CARET - x; + let set_galley = crate::widgets::elided(&painter, set_name, NAME_SIZE, tokens.text, set_room); let set_width = set_galley.size().x; painter.galley(pos2(x, center_y - set_galley.size().y / 2.0), set_galley, tokens.text); x += set_width + NAME_TO_CARET; let map_caret = caret(ui, &painter, &tokens, x, center_y, "map_caret", tr("Switch Mesh Map")); x += CARET_BOX + CARET_TO_NAME; - painter.text(pos2(x, center_y), Align2::LEFT_CENTER, tr(baked_map_label(selected)), semibold(NAME_SIZE), tokens.text_strong); + painter.text(pos2(x, center_y), Align2::LEFT_CENTER, map_name, semibold(NAME_SIZE), tokens.text_strong); egui::Popup::menu(&set_caret).show(|ui| { for (set_index, name) in set_names.iter().enumerate() { diff --git a/crates/ui-egui/src/bake_mode/live_preview.rs b/crates/ui-egui/src/bake_mode/live_preview.rs index 4c358962..af8f4732 100644 --- a/crates/ui-egui/src/bake_mode/live_preview.rs +++ b/crates/ui-egui/src/bake_mode/live_preview.rs @@ -231,7 +231,7 @@ fn input(app: &TextureCraftApp, target: LivePreviewTarget, size: BakeResolution) fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget, size: BakeResolution, dragging: bool) { app.live_preview.cancel(); app.live_preview.made_from = input(app, target, size); - let mut task = match app.session.bake_task(target.set) { + let mut task = match app.session.bake_task_only(target.set, target.map) { Ok(task) => task, Err(error) => { // Once, not on every change while it stays unbakeable @@ -245,7 +245,6 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarg }; app.live_preview.cannot_bake = false; - task.settings.maps.select([target.map]); let own = task.settings.common.resolution; let size = if own.pixels() < size.pixels() { own } else { size }; task.settings.common.resolution = size; diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs index 433cbb98..0cba2eeb 100644 --- a/crates/ui-egui/src/bake_mode/map_thumbnails.rs +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -3,13 +3,13 @@ use std::sync::{Arc, Weak}; use egui::{ColorImage, TextureHandle, TextureOptions}; use texturecraft_engine::Session; -use texturecraft_engine::core::BakedMap; +use texturecraft_engine::core::{BakedMap, BlockScales}; /// Side of a thumbnail's texture, in pixels (twice the row's square, for high-density screens) const THUMBNAIL_PIXELS: u32 = 44; -/// A thumbnail's texture, with the baked data and the working size it was drawn from -type Thumbnail = (Weak>, (u32, u32), TextureHandle); +/// A thumbnail's texture, with the baked data, the working size and the UV tiles' scales it was drawn from +type Thumbnail = (Weak>, (u32, u32), BlockScales, TextureHandle); /// The Mesh Map Bakers rows' thumbnails of the baked maps, redrawn when a map is baked again #[derive(Default)] @@ -27,9 +27,10 @@ impl MapThumbnails { return None; }; - if let Some((drawn_from, working_size, texture)) = self.textures.get(&key) + if let Some((drawn_from, working_size, block_scales, texture)) = self.textures.get(&key) && drawn_from.ptr_eq(&Arc::downgrade(data)) && *working_size == cache.size + && *block_scales == cache.composite.block_scales { return Some(texture.clone()); } @@ -38,7 +39,7 @@ impl MapThumbnails { let side = THUMBNAIL_PIXELS as usize; let image = ColorImage::from_rgba_unmultiplied([side, side], &rgba); let texture = context.load_texture(format!("bake_map_{texture_set}_{}", map.id()), image, TextureOptions::LINEAR); - self.textures.insert(key, (Arc::downgrade(data), cache.size, texture.clone())); + self.textures.insert(key, (Arc::downgrade(data), cache.size, cache.composite.block_scales.clone(), texture.clone())); Some(texture) } } @@ -63,6 +64,15 @@ mod tests { baked.maps.insert(map, Arc::new(rebaked)); assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "a new bake is drawn again"); + let mut tiled = + texturecraft_engine::Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + let tiled_set = &mut tiled.doc.project.texture_sets[0]; + let tile = *tiled_set.uv_tiles.iter().next().expect("the UDIM plane has UV tiles"); + tiled_set.tile_resolutions.insert(tile, 128); + let second = thumbnails.texture(&context, &session, 0, map).unwrap(); + session.caches[0].composite.block_scales = tiled_set.block_scales(); + assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), second.id(), "a UV tile resolution edit draws it again"); + session.doc.baked.get_mut(&0).unwrap().maps.remove(&map); assert!(thumbnails.texture(&context, &session, 0, map).is_none(), "a map not baked has none"); } diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 4fbe3505..72d3b1b9 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,4 +1,4 @@ -use egui::{Align, CornerRadius, FontId, Layout, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; +use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::ViewMode; @@ -17,6 +17,9 @@ use crate::theme::{Tokens, semibold}; const PRESETS_MENU_MIN_WIDTH: f32 = 220.0; const PRESET_NAME_FIELD_WIDTH: f32 = 130.0; +/// Spacing of the points tested along a checkbox drag's path between two frames, well under a row's height +const CROSS_STEP: f32 = 4.0; + /// How far past its box a row's check takes clicks, so it is easy to hit const CHECK_HIT_AIR: f32 = 3.0; @@ -80,9 +83,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let selected = super::selected_map(app.ui.selected_baked_map, settings); let check_drag_id = ui.scope_id().with("check_drag"); + let drag_from_id = ui.scope_id().with("check_drag_from"); let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); + let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag)).inner { + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } @@ -90,11 +95,16 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe // Kept through the frame of the release, so the click that ends a drag does not toggle its last checkbox back let is_held = ui.input(|input| input.pointer.primary_down()); + let pointer = ui.input(|input| input.pointer.latest_pos()); ui.data_mut(|data| { - if let Some(value) = check_drag.filter(|_| is_held) { + if let (Some(value), true) = (check_drag, is_held) { data.insert_temp(check_drag_id, value); + if let Some(pointer) = pointer { + data.insert_temp(drag_from_id, pointer); + } } else { data.remove_temp::(check_drag_id); + data.remove_temp::(drag_from_id); } }); } @@ -223,8 +233,16 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, what: &'static str, map: O } } -/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses); returns whether the row itself was clicked -fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option) -> bool { +/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +fn row( + app: &mut TextureCraftApp, + ui: &mut Ui, + map: BakedMap, + settings: &mut BakeSettings, + is_selected: bool, + check_drag: &mut Option, + drag_from: Option, +) -> bool { let several_sets = app.session.doc.project.texture_sets.len() > 1; let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); @@ -243,7 +261,7 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut Bak let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); let checkbox = ui.interact(check.expand(CHECK_HIT_AIR), ui.scope_id().with("include"), Sense::click()).on_hover_text(tr("Include in Bake")); checkbox.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, settings.maps.is_enabled(map), name)); - let is_dragged_over = drag_check(ui, &checkbox, rect, settings.maps.is_enabled(map), check_drag); + let is_dragged_over = drag_check(ui, &checkbox, rect, settings.maps.is_enabled(map), check_drag, drag_from); if let Some(value) = check_drag.filter(|_| is_dragged_over) { settings.maps.set_enabled(map, value); } else if checkbox.clicked() && check_drag.is_none() { @@ -311,12 +329,24 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut Bak response.clicked() } -/// Start a checkbox drag at a press on `checkbox`; returns whether a drag is in this row's checkbox column now (the whole row height counts) -fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option) -> bool { - if check_drag.is_none() && checkbox.is_pointer_button_down_on() { +/// Start a checkbox drag at a primary press on `checkbox`; returns whether the drag's pointer crossed this row's checkbox column (the whole row height counts) since `drag_from` +fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option, drag_from: Option) -> bool { + let is_primary = ui.input(|input| input.pointer.primary_down()); + if check_drag.is_none() && is_primary && checkbox.is_pointer_button_down_on() { *check_drag = Some(!is_enabled); } - check_drag.is_some() && ui.rect_contains_pointer(Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range())) + let Some(pointer) = ui.input(|input| input.pointer.latest_pos()).filter(|_| check_drag.is_some()) else { + return false; + }; + + let column = Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range()); + ui.rect_contains_pointer(column) || crosses(column, drag_from.unwrap_or(pointer), pointer) +} + +/// Whether the straight line from `from` to `to` passes through `rect`, so a row skipped between two frames still counts +fn crosses(rect: Rect, from: Pos2, to: Pos2) -> bool { + let steps = (from.distance(to) / CROSS_STEP).ceil().max(1.0) as u32; + (0..=steps).any(|step| rect.contains(from.lerp(to, step as f32 / steps as f32))) } /// The baked map's thumbnail in `rect`; before it is baked, an empty square crossed by a diagonal diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs index fc27b9e9..51ce9eef 100644 --- a/crates/ui-egui/src/bake_mode/set_picker.rs +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -4,7 +4,7 @@ use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKi use egui_phosphor::regular as icon; use serde_json::{Value, json}; use texturecraft_engine::bake::settings_patch; -use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap, Project}; use super::common_settings::antialiasing_label; use super::set_picker_purpose::SetPickerPurpose; @@ -66,7 +66,7 @@ impl SetPicker { pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { return }; - let rows = picker.rows(app); + let rows = picker.rows(&app.session.doc.project, app.session.ts()); let active = app.session.ts(); let tokens = Tokens::get(ctx); let frame = egui::Frame::new() @@ -98,14 +98,8 @@ impl SetPicker { } /// The listed sets - fn rows(&self, app: &TextureCraftApp) -> Vec { - let project = &app.session.doc.project; - let active = app.session.ts(); - let source = match self.purpose { - // New additions take on the settings already shared, or the active set's when none are - SetPickerPurpose::Sync(group) => project.texture_sets.iter().find(|set| set.bake.sync.shares(group)).or(project.texture_sets.get(active)), - SetPickerPurpose::Copy { .. } => None, - }; + fn rows(&self, project: &Project, active: usize) -> Vec { + let chosen: Vec = self.chosen.iter().enumerate().filter(|(_, chosen)| **chosen).map(|(index, _)| index).collect(); project .texture_sets .iter() @@ -113,8 +107,19 @@ impl SetPicker { // A copy goes from the active set, so it isn't listed .filter(|(index, _)| matches!(self.purpose, SetPickerPurpose::Sync(_)) || *index != active) .map(|(index, set)| { - let note = match (self.purpose, source) { - (SetPickerPurpose::Sync(group), Some(source)) if !set.bake.sync.shares(group) => differing_values(&set.bake, &source.bake, group), + let note = match self.purpose { + // What the set would take on OK when ticked: the source `bake.sync` picks from the ticked sets with this one among them + SetPickerPurpose::Sync(group) if !set.bake.sync.shares(group) => { + let mut members = chosen.clone(); + if let Err(slot) = members.binary_search(&index) { + members.insert(slot, index); + } + project + .bake_sync_source(group, &members, active) + .filter(|source| *source != index) + .and_then(|source| project.texture_sets.get(source)) + .and_then(|source| differing_values(&set.bake, &source.bake, group)) + } _ => None, }; SetPickerRow { index, name: set.name.clone(), note } @@ -261,7 +266,7 @@ fn leaf_count(patch: &Value) -> usize { mod tests { use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap}; - use super::differing_values; + use super::{SetPicker, SetPickerPurpose, differing_values}; #[test] fn a_set_shows_its_own_size_and_antialiasing_and_counts_the_rest() { @@ -287,4 +292,25 @@ mod tests { assert_eq!(differing_values(&set, &source, BakeSyncGroup::Common), None); assert_eq!(differing_values(&set, &source, BakeSyncGroup::Map(BakedMap::AmbientOcclusion)).as_deref(), Some("1 differing setting")); } + + #[test] + fn the_note_compares_with_the_set_the_sync_will_take_settings_from() { + let ao = BakeSyncGroup::Map(BakedMap::AmbientOcclusion); + let mut project = texturecraft_engine::sample_session(256, 64).unwrap().doc.project; + let third = project.texture_sets[1].clone(); + project.texture_sets.push(third); + for (index, set) in project.texture_sets.iter_mut().enumerate() { + set.bake = BakeSettings::default(); + set.bake.sync.set_shares(ao, index == 0); + } + project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 16; + + // Set 0 leaves the group and sets 1 and 2 join with set 1 active: set 2 takes set 1's values, not set 0's + let picker = SetPicker { purpose: SetPickerPurpose::Sync(ao), chosen: vec![false, true, true] }; + let rows = picker.rows(&project, 1); + let note = |index: usize| rows.iter().find(|row| row.index == index).and_then(|row| row.note.clone()); + + assert_eq!(note(2).as_deref(), Some("1 differing setting")); + assert_eq!(note(1), None, "the source itself has nothing to take"); + } } diff --git a/crates/ui-egui/src/high_poly_job.rs b/crates/ui-egui/src/high_poly_job.rs index 37ac21df..09716f9a 100644 --- a/crates/ui-egui/src/high_poly_job.rs +++ b/crates/ui-egui/src/high_poly_job.rs @@ -50,7 +50,7 @@ impl TextureCraftApp { }); } - /// Add a loaded high poly to the session and start on the next file; drop them all once another project is open + /// Add a loaded high poly to the session (once no paint stroke is running) and start on the next file; drop them all once another project is open #[cfg(not(target_arch = "wasm32"))] pub(crate) fn poll_high_poly_job(&mut self, context: &egui::Context) { let Some(job) = &self.high_poly_job else { return }; @@ -61,6 +61,11 @@ impl TextureCraftApp { } context.request_repaint_after(POLL_INTERVAL); + // A stroke's cancel or undo restores the document from its start, which would drop a high poly added during it + if self.session.stroke_active() { + return; + } + let loaded = match job.answer.try_recv() { Ok(loaded) => loaded, Err(TryRecvError::Empty) => return, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1dcf34e..a0c23f0c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -814,12 +814,12 @@ impl TextureCraftApp { let only = job.only; self.session.bake_preview_set_current(set_index); - match self.session.bake_task(set_index) { - Ok(mut task) => { - if let Some(map) = only { - task.settings.maps.select([map]); - } - + let task = match only { + Some(map) => self.session.bake_task_only(set_index, map), + None => self.session.bake_task(set_index), + }; + match task { + Ok(task) => { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); diff --git a/crates/ui-egui/src/property_sheet/file_list.rs b/crates/ui-egui/src/property_sheet/file_list.rs index 69a34386..8563df58 100644 --- a/crates/ui-egui/src/property_sheet/file_list.rs +++ b/crates/ui-egui/src/property_sheet/file_list.rs @@ -99,14 +99,8 @@ impl PropertySheet<'_> { let name = painter.layout_job(job); painter.galley(pos2(rect.left() + NAME_LEFT, name_y - name.size().y / 2.0), name, name_color); if let Some(folder) = row.folder { - let shown = shortened_folder(&painter, folder, words_right - rect.left() - NAME_LEFT); - painter.text( - pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER), - Align2::LEFT_CENTER, - shown, - FontId::proportional(SMALL_TEXT_SIZE), - tokens.text_dim, - ); + let shown = folder_galley(&painter, folder, words_right - rect.left() - NAME_LEFT, tokens.text_dim); + painter.galley(pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER - shown.size().y / 2.0), shown, tokens.text_dim); } let words = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(words_right, rect.bottom())); @@ -135,6 +129,11 @@ impl PropertySheet<'_> { } } +/// `folder` shortened to fit `room`, cut with "…" when even its first and last folders are too wide +fn folder_galley(painter: &egui::Painter, folder: &str, room: f32, color: egui::Color32) -> std::sync::Arc { + crate::widgets::elided(painter, shortened_folder(painter, folder, room), SMALL_TEXT_SIZE, color, room) +} + /// `folder` with folders after its first one left out, from the second on, until it fits in `room` fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String { let fits = |text: &str| painter.layout_no_wrap(text.to_owned(), FontId::proportional(SMALL_TEXT_SIZE), egui::Color32::WHITE).size().x <= room; @@ -150,3 +149,25 @@ fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String } shown } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_folder_too_long_even_when_shortened_is_cut_to_its_room() { + let room = 120.0; + let folder = format!("C:\\{}", "W".repeat(80)); + let mut laid_out = None; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + laid_out = Some(folder_galley(ui.painter(), &folder, room, egui::Color32::WHITE)); + }); + + // The font atlas upload is not under test + output.textures_delta.clear(); + let galley = laid_out.unwrap(); + + assert!(galley.size().x <= room); + assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); + } +} diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs index 848543c9..89c6e301 100644 --- a/crates/ui-egui/tests/it/bake_live_preview.rs +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -151,7 +151,7 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() // A change that doesn't come from the panel: a script, an undo or a synced set let before = picture(&harness); harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } })); - let changed = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); + let changed = run_until(&mut harness, |harness| is_new(picture(harness), before.as_ref())); assert!(changed, "the settings change brings a new picture"); // The same file loaded again: same name, new geometry @@ -162,7 +162,12 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() } session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); let before = picture(&harness); - let reloaded = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); + let reloaded = run_until(&mut harness, |harness| is_new(picture(harness), before.as_ref())); assert!(reloaded, "high poly load {index} brings a new picture"); } } + +/// True when the preview holds a picture other than `before`, which the caller keeps alive so its address can't be reused +fn is_new(now: Option>>, before: Option<&std::sync::Arc>>) -> bool { + now.is_some_and(|now| before.is_none_or(|before| !std::sync::Arc::ptr_eq(&now, before))) +} diff --git a/crates/ui-egui/tests/it/bake_map_rows.rs b/crates/ui-egui/tests/it/bake_map_rows.rs index ce17536c..8a03a411 100644 --- a/crates/ui-egui/tests/it/bake_map_rows.rs +++ b/crates/ui-egui/tests/it/bake_map_rows.rs @@ -1,4 +1,4 @@ -//! The Mesh Map Bakers rows: a drag down the checkboxes gives each the state the first one took +//! The Mesh Map Bakers rows: a primary drag down the checkboxes gives each the state the first one took use egui::{Event, Modifiers, PointerButton, Role}; use egui_kittest::Harness; @@ -52,6 +52,39 @@ fn a_drag_down_the_checkboxes_unchecks_every_row_it_crosses() { assert_eq!(enabled(&harness), expected, "the three rows are unchecked, the release does not check the last one again"); } +#[test] +fn a_drag_that_jumps_past_a_row_between_two_frames_still_unchecks_it() { + let mut harness = harness(); + let [from, _, to] = DRAGGED.map(|(_, name)| checkbox_center(&harness, name)); + + 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); + harness.hover_at(to); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|map| DRAGGED.iter().all(|(dragged, _)| dragged != map)).collect(); + assert_eq!(enabled(&harness), expected, "World Space Normal, between Normal and ID, is unchecked too"); +} + +#[test] +fn holding_the_secondary_button_on_a_checkbox_leaves_it_alone() { + let mut harness = harness(); + let at = checkbox_center(&harness, DRAGGED[1].1); + + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(3); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + assert_eq!(enabled(&harness), BakedMap::ALL); +} + #[test] fn a_click_on_one_checkbox_still_toggles_only_that_row() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 2339512d..51a543ed 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -450,6 +450,17 @@ fn the_breadcrumb_switches_the_shown_map() { assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); } +#[test] +fn a_long_texture_set_name_leaves_the_map_switcher_and_restore_defaults_in_the_breadcrumb() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.state_mut().session.doc.project.texture_sets[0].name = "W".repeat(200); + harness.run_steps(3); + + let switcher = harness.get_by_label("Switch Mesh Map").rect(); + let restore = harness.get_by_role_and_label(Role::Button, "Restore Defaults").rect(); + assert!(switcher.right() <= restore.left(), "the map switcher stays left of Restore Defaults"); +} + #[test] fn curvature_controls_follow_the_method_and_grey_out_by_their_switches() { let mut harness = harness(Some(BakedMap::Curvature)); diff --git a/crates/ui-egui/tests/it/high_poly_loading.rs b/crates/ui-egui/tests/it/high_poly_loading.rs index 4808c98c..c332cb95 100644 --- a/crates/ui-egui/tests/it/high_poly_loading.rs +++ b/crates/ui-egui/tests/it/high_poly_loading.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::state::Mode; const TRIANGLE_OBJ: &str = "o Part_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"; /// Longest the test waits for the worker const LOAD_TIMEOUT: Duration = Duration::from_secs(60); +/// Frames (5 ms apart) a stroke stays open while a high poly loads +const STROKE_FRAMES: usize = 200; /// A bake-mode app with Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { @@ -95,3 +97,30 @@ fn a_high_poly_that_finishes_after_the_list_changed_joins_the_list_as_it_is() { assert_eq!(session.apply_high_poly_load(load), "2_part.obj", "the name is made unique against the list of now"); assert_eq!(session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2, "both meshes bake"); } + +#[test] +fn a_high_poly_read_during_a_paint_stroke_is_added_after_it_and_survives_its_cancel() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-stroke-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("part.obj").display().to_string(); + std::fs::write(&path, TRIANGLE_OBJ).unwrap(); + + let mut harness = harness(); + // Bake mode finishes strokes at once: the files go on loading after a switch back to painting + harness.state_mut().ui.mode = Mode::Painting; + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::json!({})).unwrap(); + harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + harness.state_mut().load_high_polys([path]); + // Time for the worker to read one triangle + for _ in 0..STROKE_FRAMES { + std::thread::sleep(Duration::from_millis(5)); + harness.run_steps(1); + } + assert!(harness.state().session.stroke_active()); + assert!(high_names(&harness).is_empty(), "nothing is added while the stroke runs"); + + harness.state_mut().session.cancel_stroke(); + run_until_loaded(&mut harness); + assert_eq!(high_names(&harness), ["part.obj"]); + let _ = std::fs::remove_dir_all(folder); +} From d9f43048c56cb067a8faa9a17f760741c2191d47 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:02:05 +0000 Subject: [PATCH 130/153] Bake mode pass 2: review fixes, critic round 1 - Partner validation skips the edited sets and is set apart by blank lines - A drag whose pointer left the window starts a new line on its return - Tests for a legacy preset on synced sets and for each sync source rule --- crates/bake/src/test/fitted_cage.rs | 1 + crates/core/src/project.rs | 17 +++++++++++++++++ crates/engine/src/bake/mesh_map_command.rs | 5 ++++- crates/engine/src/bake/sync_command.rs | 13 +++++++++++++ crates/ui-egui/src/bake_mode/mesh_map_bakers.rs | 3 +++ crates/ui-egui/src/bake_mode/set_picker.rs | 2 +- 6 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index 903c5c99..b6253f51 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -167,6 +167,7 @@ fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() low.append(&part("right_low", 1.0, 0.0, 4)); let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + // One material, so the cage shell covers both low parts for mesh in [&mut low, &mut high] { mesh.materials.truncate(1); for submesh in &mut mesh.submeshes { diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index b8e66cd4..db74dc2a 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -804,6 +804,23 @@ mod tests { p } + #[test] + fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() { + let group = BakeSyncGroup::Common; + let mut project = project(); + for name in ["Legs", "Arms"] { + project.texture_sets.push(TextureSet::new(name, 0, 512)); + } + for (index, set) in project.texture_sets.iter_mut().enumerate() { + set.bake.sync.set_shares(group, index == 2); + } + + assert_eq!(project.bake_sync_source(group, &[0, 1, 2], 0), Some(2), "a member already sharing the group"); + assert_eq!(project.bake_sync_source(group, &[0, 1], 1), Some(1), "the active set when it joins"); + assert_eq!(project.bake_sync_source(group, &[0, 1], 2), Some(0), "else the first member"); + assert_eq!(project.bake_sync_source(group, &[], 0), None); + } + fn paint(p: &mut Project, name: &str) -> Layer { Layer::new(p.alloc_id(), name, LayerKind::Paint, &Channel::DEFAULT_SET) } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 3e544857..b52268a4 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -137,6 +137,7 @@ impl Session { if let Some(map) = only { settings.maps.select([map]); } + // Read from the maps that bake, so a map baked alone while unchecked still gets the colours let needs_low_color = settings.maps.opacity.is_enabled || (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); @@ -775,10 +776,12 @@ fn with_sync_partners( } } } + // A field valid beside the target's other values can be invalid beside a partner's: min above the partner's max - for (partner, settings) in &next { + for (partner, settings) in next.iter().filter(|(partner, _)| targets.iter().all(|(target, _)| target != *partner)) { validate_model_settings(settings, command, from_preset, project.texture_sets.get(*partner).map(|set| &set.bake))?; } + next.extend(targets); Ok(next.into_iter().collect()) } diff --git a/crates/engine/src/bake/sync_command.rs b/crates/engine/src/bake/sync_command.rs index 88018b6f..cd6ceb0c 100644 --- a/crates/engine/src/bake/sync_command.rs +++ b/crates/engine/src/bake/sync_command.rs @@ -151,6 +151,9 @@ mod tests { use crate::{execute, sample_session}; use texturecraft_core::BakeSettings; + /// A dilation only presets may hold, above what an edit may set + const LEGACY_DILATION: u32 = 200; + fn session() -> Session { let session = sample_session(128, 32).unwrap(); assert_eq!(session.set_count(), 2); @@ -274,4 +277,14 @@ mod tests { assert!(execute(&mut session, "bake.settings", &patch).is_err(), "set 1 would get a minimum above its maximum"); assert_eq!(session.doc.project.texture_sets, before); } + + #[test] + fn a_preset_with_a_legacy_value_loads_on_a_set_sharing_it() { + let mut session = session(); + let mut preset = bake(&session, 0).clone(); + preset.common.dilation = LEGACY_DILATION; + + execute(&mut session, "bake.settings", &json!({ "ts": 0, "model": preset, "preset": true })).unwrap(); + assert_eq!(bake(&session, 1).common.dilation, LEGACY_DILATION, "set 1 shares Common Settings with set 0"); + } } diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 72d3b1b9..b235b154 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -99,8 +99,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe ui.data_mut(|data| { if let (Some(value), true) = (check_drag, is_held) { data.insert_temp(check_drag_id, value); + // A pointer back from outside the window starts a new line, so rows it never crossed stay as they were if let Some(pointer) = pointer { data.insert_temp(drag_from_id, pointer); + } else { + data.remove_temp::(drag_from_id); } } else { data.remove_temp::(check_drag_id); diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs index 51ce9eef..27fbcecf 100644 --- a/crates/ui-egui/src/bake_mode/set_picker.rs +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -66,8 +66,8 @@ impl SetPicker { pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { return }; - let rows = picker.rows(&app.session.doc.project, app.session.ts()); let active = app.session.ts(); + let rows = picker.rows(&app.session.doc.project, active); let tokens = Tokens::get(ctx); let frame = egui::Frame::new() .fill(tokens.panel) From 3ec569def7e9d87d971b6b461383b78e52939e7d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:18:40 +0000 Subject: [PATCH 131/153] Generators: review fixes for the previews (an image read twice goes once and the orb gets its own back, pictures of a deleted generator dropped) --- crates/engine/src/orb_preview.rs | 6 +-- crates/ui-egui/src/generator_panel.rs | 9 +++- .../ui-egui/src/generator_preview_window.rs | 17 +++++--- crates/ui-egui/src/shelf_preview.rs | 43 ++++++++++++++++--- crates/ui-egui/src/thumbs.rs | 5 +++ crates/ui-egui/tests/it/generator_panel.rs | 11 +++-- 6 files changed, 69 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index e40366e1..eb096fe9 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -16,7 +16,6 @@ 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; @@ -123,13 +122,14 @@ impl OrbPreview { let replaced: Vec<_> = images.iter().map(|(name, image)| (name.clone(), self.session.images.insert(name.clone(), image.clone()))).collect(); let pixels = self.generator_of(with_sample_image(generator), size); - // The orb's own images come back: the next preview reads only what it brings - for (name, previous) in replaced { + // The orb's own images come back, last replaced first so a name given twice ends as it began: the next preview reads only what it brings + for (name, previous) in replaced.into_iter().rev() { match previous { Some(previous) => self.session.images.insert(name, previous), None => self.session.images.remove(&name), }; } + pixels } diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index b07914a4..ba425222 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -1,6 +1,6 @@ //! A generator effect's properties, laid out like the reference app's: its slot, Parameters, Image inputs, Resolution, Attributes -use egui::{CursorIcon, Painter, Rect, Role, Sense, Stroke, StrokeKind, TextureHandle, WidgetInfo}; +use egui::{CornerRadius, CursorIcon, Painter, Rect, Role, Sense, Stroke, StrokeKind, TextureHandle, WidgetInfo}; use serde_json::json; use texturecraft_engine::core::{ CookResolution, Generator, GeneratorKind, KindControls, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters, @@ -18,6 +18,9 @@ use crate::property_sheet::PropertySheet; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +/// The outline on the preview while it can open enlarged under the pointer, or is open, in points +const ENLARGE_OUTLINE_WIDTH: f32 = 1.0; + /// The width the preview's orb is rendered at, in pixels: sharp at twice the preview's size const PREVIEW_ORB_PX: usize = 256; @@ -133,10 +136,12 @@ fn enlarge_on_click(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id let response = sheet.ui.interact(rect, sheet.ui.make_persistent_id(("generator_preview_enlarge", id)), Sense::click()).on_hover_cursor(CursorIcon::ZoomIn); let open = app.ui.windows.generator_preview == Some(id); response.widget_info(|| WidgetInfo::selected(Role::Button, true, open, tr("Enlarge preview"))); + if response.hovered() || response.has_focus() || open { let tokens = Tokens::get(sheet.ui.ctx()); - sheet.ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); + sheet.ui.painter().rect_stroke(rect, CornerRadius::ZERO, Stroke::new(ENLARGE_OUTLINE_WIDTH, tokens.text_dim), StrokeKind::Inside); } + if response.clicked() { let ctx = sheet.ui.ctx().clone(); crate::generator_preview_window::toggle(app, &ctx, id, rect); diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs index fbdc227b..a67f4456 100644 --- a/crates/ui-egui/src/generator_preview_window.rs +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -1,6 +1,6 @@ //! A generator's preview enlarged in a tool window, following its settings while they change -use egui::{Rect, Sense, pos2}; +use egui::{Align2, Color32, CornerRadius, Rect, Role, Sense, WidgetInfo, pos2, vec2}; use texturecraft_engine::core::{EffectKind, LayerId}; use crate::TextureCraftApp; @@ -30,6 +30,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { Some(EffectKind::Generator(generator)) => generator.clone(), _ => { app.ui.windows.generator_preview = None; + app.thumbs.forget_generator_pictures(effect); return; } }; @@ -37,24 +38,28 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let set = ShelfPreview::generator_set(&generator, &app.session.images); let texture = app.thumbs.generator_set_picture(ctx, effect, set, PICTURE_PX); let tokens = Tokens::get(ctx); + + // It first opens beside the small preview it was asked from, then stays where it is moved let mut open = true; let beside = ctx.data(|data| data.get_temp::(anchor_id())).map_or(ctx.content_rect().center(), |small| pos2(small.left() - BESIDE_GAP, small.center().y)); let window = crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH); - window.default_pos(beside).pivot(egui::Align2::RIGHT_CENTER).show(ctx, |ui| { + window.default_pos(beside).pivot(Align2::RIGHT_CENTER).show(ctx, |ui| { let side = ui.available_width().max(MIN_SIDE); - let (rect, response) = ui.allocate_exact_size(egui::vec2(side, side), Sense::hover()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Preview"))); + let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tr("Preview"))); + match &texture { Some(texture) => { - ui.painter().image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + ui.painter().image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } None => { - ui.painter().rect_filled(rect, 0.0, tokens.button); + ui.painter().rect_filled(rect, CornerRadius::ZERO, tokens.button); ctx.request_repaint_after(PICTURE_POLL); } } }); + if !open { app.ui.windows.generator_preview = None; } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index f6bad1cb..4ca10aef 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -65,13 +65,17 @@ impl ShelfPreview { /// `generator` as set, with the images it reads from `store` pub fn generator_set(generator: &Generator, store: &ImageStore) -> ShelfPreview { - let images = generator - .sources() - .filter_map(|source| match source { - texturecraft_engine::core::Source::Image { name, .. } => store.get(name).map(|image| (name.clone(), image.clone())), - _ => None, - }) - .collect(); + // An image read in two slots goes once + let mut images: Vec<(String, Arc)> = Vec::new(); + for source in generator.sources() { + if let texturecraft_engine::core::Source::Image { name, .. } = source + && let Some(image) = store.get(name) + && !images.iter().any(|(taken, _)| taken == name) + { + images.push((name.clone(), image.clone())); + } + } + ShelfPreview::GeneratorSet { generator: Box::new(generator.clone()), images } } @@ -193,6 +197,31 @@ mod tests { use super::*; + #[test] + fn a_generator_preview_is_keyed_by_its_settings_and_reads_an_image_once() { + let image = Arc::new(ImageRes::new(1, 1, vec![[0.5; 4]], false)); + let store: ImageStore = [("grunge.png".to_owned(), image)].into(); + let dirt = |grunge: Option<&str>, invert| Generator { + grunge: grunge.map(texturecraft_engine::core::Source::image), + micro: None, + invert, + ..Generator::new(GeneratorKind::Dirt) + }; + + let plain = ShelfPreview::generator_set(&dirt(None, false), &store); + assert_eq!(plain.key(), ShelfPreview::generator_set(&dirt(None, false), &store).key(), "the same settings share a picture"); + assert_ne!(plain.key(), ShelfPreview::generator_set(&dirt(None, true), &store).key(), "another setting is another picture"); + assert_ne!(plain.key(), ShelfPreview::generator_set(&dirt(Some("grunge.png"), false), &store).key(), "so is an image read"); + + let mut both = dirt(Some("grunge.png"), false); + both.texture = Some(Box::new(texturecraft_engine::core::TextureLayer { + source: Some(texturecraft_engine::core::Source::image("grunge.png")), + ..Default::default() + })); + let ShelfPreview::GeneratorSet { images, .. } = ShelfPreview::generator_set(&both, &store) else { panic!("a generator preview") }; + assert_eq!(images.len(), 1, "an image in two slots goes once"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn named_brush_files_render_their_saved_settings() { diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 38552ce4..08a7d5ae 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -330,6 +330,11 @@ impl Thumbs { shown } + /// Drops the pictures kept for generator effect `effect`, gone from the project + pub fn forget_generator_pictures(&mut self, effect: u64) { + self.set_pictures.retain(|(kept, _), _| *kept != effect); + } + /// 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) diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 245bffcd..f28b20a5 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -545,10 +545,13 @@ fn enlarged_preview_snapshots() { let (mut harness, _) = harness_with(true, json!({"generator": "edgeWear", "seed": 12})); click_live(&mut harness, Role::Button, "Enlarge preview"); - // The pictures render on the preview worker - for _ in 0..60 { - harness.run_steps(4); - std::thread::sleep(std::time::Duration::from_millis(50)); + // The pictures render on the preview worker: up to three seconds of frames + const WAITS: usize = 60; + const STEPS_PER_WAIT: usize = 4; + const WAIT: std::time::Duration = std::time::Duration::from_millis(50); + for _ in 0..WAITS { + harness.run_steps(STEPS_PER_WAIT); + std::thread::sleep(WAIT); } for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; From a7e15a489cc97d503a9a889e2ec47c5c1b2b3841 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:21:07 +0000 Subject: [PATCH 132/153] Generators: preview review round (pictures of any removed generator dropped, a test for the orb's restored images, imports) --- crates/engine/src/orb_preview.rs | 20 ++++++++++++++++++- .../ui-egui/src/generator_preview_window.rs | 15 +++++++++----- crates/ui-egui/src/shelf_preview.rs | 18 ++++++----------- crates/ui-egui/src/thumbs.rs | 17 +++++++++++++--- crates/ui-egui/tests/it/generator_panel.rs | 19 ++++++++++-------- 5 files changed, 60 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index eb096fe9..c63aa524 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -122,7 +122,7 @@ impl OrbPreview { let replaced: Vec<_> = images.iter().map(|(name, image)| (name.clone(), self.session.images.insert(name.clone(), image.clone()))).collect(); let pixels = self.generator_of(with_sample_image(generator), size); - // The orb's own images come back, last replaced first so a name given twice ends as it began: the next preview reads only what it brings + // Restore in reverse so a name given twice ends as it began for (name, previous) in replaced.into_iter().rev() { match previous { Some(previous) => self.session.images.insert(name, previous), @@ -267,6 +267,24 @@ mod tests { pixels.iter().flatten().map(|pixel| pixel.mask).sum::() / pixels.iter().flatten().count().max(1) as f32 } + #[test] + fn a_render_reading_an_image_twice_leaves_the_orbs_own_images() { + 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 image = |value| Arc::new(ImageRes::new(1, 1, vec![[value; 4]], false)); + let own = image(0.1); + preview.session.images.insert("shared.png".into(), own.clone()); + + let brought = image(0.9); + let images = [("shared.png".into(), brought.clone()), ("shared.png".into(), brought.clone()), ("added.png".into(), brought)]; + preview.generator_reading(Generator::new(GeneratorKind::Dirt), &images, 0); + + assert!(preview.session.images.get("shared.png").is_some_and(|kept| Arc::ptr_eq(kept, &own)), "the orb's own image is back"); + assert!(!preview.session.images.contains_key("added.png"), "an image it lacked is gone again"); + } + #[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(); diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs index a67f4456..48033859 100644 --- a/crates/ui-egui/src/generator_preview_window.rs +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -1,6 +1,8 @@ //! A generator's preview enlarged in a tool window, following its settings while they change -use egui::{Align2, Color32, CornerRadius, Rect, Role, Sense, WidgetInfo, pos2, vec2}; +use std::time::Duration; + +use egui::{Align2, Color32, Context, CornerRadius, Rect, Role, Sense, WidgetInfo, pos2, vec2}; use texturecraft_engine::core::{EffectKind, LayerId}; use crate::TextureCraftApp; @@ -21,16 +23,19 @@ const MIN_SIDE: f32 = 160.0; const BESIDE_GAP: f32 = 24.0; /// How soon a picture still rendering is looked for again -const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); +const PICTURE_POLL: Duration = Duration::from_millis(100); /// The open enlarged preview, if any: closed by its ×, and when its generator is gone -pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &Context) { + // Pictures of generators gone from the project are dropped, whether or not their window is open + let project = &app.session.doc.project; + app.thumbs.keep_generator_pictures(|effect| project.effect(LayerId(effect)).is_some()); + let Some(effect) = app.ui.windows.generator_preview else { return }; let generator = match app.session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) { Some(EffectKind::Generator(generator)) => generator.clone(), _ => { app.ui.windows.generator_preview = None; - app.thumbs.forget_generator_pictures(effect); return; } }; @@ -66,7 +71,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } /// Opens generator effect `effect`'s enlarged preview beside its small one at `small`, or closes it when it is the one open -pub(crate) fn toggle(app: &mut TextureCraftApp, ctx: &egui::Context, effect: u64, small: Rect) { +pub(crate) fn toggle(app: &mut TextureCraftApp, ctx: &Context, effect: u64, small: Rect) { ctx.data_mut(|data| data.insert_temp(anchor_id(), small)); let open = &mut app.ui.windows.generator_preview; *open = if *open == Some(effect) { None } else { Some(effect) }; diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 4ca10aef..4c6026ca 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::compose::ImageStore; -use texturecraft_engine::core::{CurvatureMode, Generator, GeneratorKind, ProceduralKind}; +use texturecraft_engine::core::{CurvatureMode, Generator, GeneratorKind, ProceduralKind, Source}; use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; @@ -68,7 +68,7 @@ impl ShelfPreview { // An image read in two slots goes once let mut images: Vec<(String, Arc)> = Vec::new(); for source in generator.sources() { - if let texturecraft_engine::core::Source::Image { name, .. } = source + if let Source::Image { name, .. } = source && let Some(image) = store.get(name) && !images.iter().any(|(taken, _)| taken == name) { @@ -195,18 +195,15 @@ mod tests { use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::PRESETS; + use texturecraft_engine::core::TextureLayer; + use super::*; #[test] fn a_generator_preview_is_keyed_by_its_settings_and_reads_an_image_once() { let image = Arc::new(ImageRes::new(1, 1, vec![[0.5; 4]], false)); let store: ImageStore = [("grunge.png".to_owned(), image)].into(); - let dirt = |grunge: Option<&str>, invert| Generator { - grunge: grunge.map(texturecraft_engine::core::Source::image), - micro: None, - invert, - ..Generator::new(GeneratorKind::Dirt) - }; + let dirt = |grunge: Option<&str>, invert| Generator { grunge: grunge.map(Source::image), micro: None, invert, ..Generator::new(GeneratorKind::Dirt) }; let plain = ShelfPreview::generator_set(&dirt(None, false), &store); assert_eq!(plain.key(), ShelfPreview::generator_set(&dirt(None, false), &store).key(), "the same settings share a picture"); @@ -214,10 +211,7 @@ mod tests { assert_ne!(plain.key(), ShelfPreview::generator_set(&dirt(Some("grunge.png"), false), &store).key(), "so is an image read"); let mut both = dirt(Some("grunge.png"), false); - both.texture = Some(Box::new(texturecraft_engine::core::TextureLayer { - source: Some(texturecraft_engine::core::Source::image("grunge.png")), - ..Default::default() - })); + both.texture = Some(Box::new(TextureLayer { source: Some(Source::image("grunge.png")), ..TextureLayer::default() })); let ShelfPreview::GeneratorSet { images, .. } = ShelfPreview::generator_set(&both, &store) else { panic!("a generator preview") }; assert_eq!(images.len(), 1, "an image in two slots goes once"); } diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 08a7d5ae..da1e1712 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -330,9 +330,9 @@ impl Thumbs { shown } - /// Drops the pictures kept for generator effect `effect`, gone from the project - pub fn forget_generator_pictures(&mut self, effect: u64) { - self.set_pictures.retain(|(kept, _), _| *kept != effect); + /// Keeps the generator pictures only of the effects `exists` still finds + pub fn keep_generator_pictures(&mut self, exists: impl Fn(u64) -> bool) { + self.set_pictures.retain(|(effect, _), _| exists(*effect)); } /// Sphere thumbnail of library filter `id` applied to a sample material @@ -502,6 +502,17 @@ mod tests { static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + #[test] + fn the_pictures_of_a_removed_generator_go() { + let mut thumbs = Thumbs::default(); + thumbs.set_pictures.insert((1, 8), (None, None)); + thumbs.set_pictures.insert((2, 8), (None, None)); + + thumbs.keep_generator_pictures(|effect| effect == 2); + + assert!(!thumbs.set_pictures.contains_key(&(1, 8)) && thumbs.set_pictures.contains_key(&(2, 8))); + } + #[test] fn a_generator_picture_shows_the_last_one_while_the_next_renders() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index f28b20a5..931f469a 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -1,5 +1,8 @@ //! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator +use std::path::PathBuf; +use std::time::Duration; + use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -279,7 +282,7 @@ fn micro_details_show_their_settings_once_switched_on() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let (mut harness, effect) = harness(true); harness.run_steps(12); @@ -312,7 +315,7 @@ fn generator_panel_snapshots() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn full_set_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let kinds = ["edgeWear", "fiberGlassEdgeWear", "dirt", "direction", "curvature", "ambientOcclusion", "position", "worldSpaceNormals"]; for kind in kinds { @@ -324,7 +327,7 @@ fn full_set_panel_snapshots() { // The orbs render on the preview worker for _ in 0..40 { harness.run_steps(4); - std::thread::sleep(std::time::Duration::from_millis(50)); + std::thread::sleep(Duration::from_millis(50)); } for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -375,7 +378,7 @@ fn the_texture_slot_takes_a_uniform_value_and_empties_again() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn texture_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); for kind in ["position", "ambientOcclusion"] { let (mut harness, _) = harness_with(true, json!({"generator": kind, "useTexture": true, "textureOpacity": 0.6, "textureBlend": "normal"})); @@ -485,7 +488,7 @@ fn the_color_rows_follow_the_color_mode() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn new_kind_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let gradient = json!([[0.02, 0.02, 0.02], [0.6, 0.12, 0.03], [0.8, 0.8, 0.8]]); let kinds = [ @@ -508,7 +511,7 @@ fn new_kind_panel_snapshots() { // The orbs render on the preview worker for _ in 0..40 { harness.run_steps(4); - std::thread::sleep(std::time::Duration::from_millis(50)); + std::thread::sleep(Duration::from_millis(50)); } for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -540,7 +543,7 @@ fn the_preview_opens_enlarged_in_its_own_window() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn enlarged_preview_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let (mut harness, _) = harness_with(true, json!({"generator": "edgeWear", "seed": 12})); click_live(&mut harness, Role::Button, "Enlarge preview"); @@ -548,7 +551,7 @@ fn enlarged_preview_snapshots() { // The pictures render on the preview worker: up to three seconds of frames const WAITS: usize = 60; const STEPS_PER_WAIT: usize = 4; - const WAIT: std::time::Duration = std::time::Duration::from_millis(50); + const WAIT: Duration = Duration::from_millis(50); for _ in 0..WAITS { harness.run_steps(STEPS_PER_WAIT); std::thread::sleep(WAIT); From 2f5b8025302bc6edfd9f5435e8ee45381326bf33 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:21 +0000 Subject: [PATCH 133/153] Shelf preview: test imports in one group --- crates/ui-egui/src/shelf_preview.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 4c6026ca..7fc3ac1c 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -190,13 +190,12 @@ fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u #[cfg(test)] mod tests { + use texturecraft_engine::core::TextureLayer; use texturecraft_engine::filter_lib::FILTERS; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::PRESETS; - use texturecraft_engine::core::TextureLayer; - use super::*; #[test] From 1d7669c0384a11cb3c43d2ee9c38300c0bb39667 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:41 +0000 Subject: [PATCH 134/153] Bake mode pass 2: synced sets check only that their values agree The edited set's checks already bound every value it changes, so a legacy value it may keep (flat parameters, presets) also reaches the sets sharing it; a synced set is refused only when a copied value clashes with its own, such as a minimum above its maximum. Also fixes the new tests' sample resolution and a clippy lint --- crates/engine/src/bake/mesh_map_command.rs | 20 ++++++++----------- .../ui-egui/src/bake_mode/map_thumbnails.rs | 2 +- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index b52268a4..0edd341b 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -746,19 +746,14 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { let targets = updated_settings(session, params, command)?; let sets = targets.iter().map(|(index, _)| *index).collect(); - let next = with_sync_partners(&session.doc.project, targets, command, boolp(params, "preset") == Some(true))?; + let next = with_sync_partners(&session.doc.project, targets, command)?; super::sync_command::store(session, "Bake Settings", next)?; Ok(sets) } -/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's settings come out invalid (`from_preset`: preset limits apply) -fn with_sync_partners( - project: &texturecraft_core::Project, - targets: Vec<(usize, BakeSettings)>, - command: &str, - from_preset: bool, -) -> Result> { +/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's values come out inconsistent +fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { let mut next: BTreeMap = BTreeMap::new(); for (target, settings) in &targets { let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue }; @@ -769,6 +764,7 @@ fn with_sync_partners( for partner in project.bake_synced_sets(*target, group).into_iter().filter(|partner| partner != target) { let Some(set) = project.texture_sets.get(partner) else { continue }; let entry = next.entry(partner).or_insert_with(|| set.bake.clone()); + let mut model = json!(entry); model_patch::apply_patch(&mut model, &changed, command)?; let patched: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; @@ -777,9 +773,9 @@ fn with_sync_partners( } } - // A field valid beside the target's other values can be invalid beside a partner's: min above the partner's max - for (partner, settings) in next.iter().filter(|(partner, _)| targets.iter().all(|(target, _)| target != *partner)) { - validate_model_settings(settings, command, from_preset, project.texture_sets.get(*partner).map(|set| &set.bake))?; + // The target's checks already bound each value it changed, but beside a partner's other values one can clash: min above the partner's max + for (_, settings) in next.iter().filter(|(partner, _)| targets.iter().all(|(target, _)| target != *partner)) { + validate_model_settings(settings, command, false, Some(settings))?; } next.extend(targets); @@ -897,7 +893,7 @@ mod bake_task_tests { #[test] fn a_map_baked_alone_while_unchecked_still_reads_the_low_polys_colours() { - let mut session = crate::sample_session(64, 64).unwrap(); + let mut session = crate::sample_session(128, 64).unwrap(); session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); let colours = Arc::new(vec![None]); let _ = session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())); diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs index 0cba2eeb..191cf805 100644 --- a/crates/ui-egui/src/bake_mode/map_thumbnails.rs +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -67,7 +67,7 @@ mod tests { let mut tiled = texturecraft_engine::Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); let tiled_set = &mut tiled.doc.project.texture_sets[0]; - let tile = *tiled_set.uv_tiles.iter().next().expect("the UDIM plane has UV tiles"); + let tile = *tiled_set.uv_tiles.first().expect("the UDIM plane has UV tiles"); tiled_set.tile_resolutions.insert(tile, 128); let second = thumbnails.texture(&context, &session, 0, map).unwrap(); session.caches[0].composite.block_scales = tiled_set.block_scales(); From e0c4fc49e9099bd39709c08ced2116d6a78e49f1 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:36:37 +0000 Subject: [PATCH 135/153] Map-alone bake test: clear the colours the sample read when it baked --- crates/engine/src/bake/mesh_map_command.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 0edd341b..8d95ce1e 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -896,7 +896,9 @@ mod bake_task_tests { let mut session = crate::sample_session(128, 64).unwrap(); session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); let colours = Arc::new(vec![None]); - let _ = session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())); + // The sample bakes when made, which already read the colours + session.doc.bake_meshes.low_base_color = Default::default(); + assert!(session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())).is_ok()); assert!(session.bake_task(0).unwrap().low_base_color.is_empty(), "the checked maps need no colours"); let task = session.bake_task_only(0, BakedMap::Opacity).unwrap(); From 0535d1ddc6ba0c4dacc0c3ab0632120e666da2d5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:11:54 +0700 Subject: [PATCH 136/153] Export templates: reject file/folder conflicts and confine writes with cap-std --- Cargo.lock | 1 + crates/formats/Cargo.toml | 1 + crates/formats/src/export/mod.rs | 58 +++-- crates/formats/src/export/tests.rs | 53 +++++ crates/formats/src/lib.rs | 357 +++++++++++++++++++++-------- 5 files changed, 356 insertions(+), 114 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 59d9a90a..d82d26f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5202,6 +5202,7 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "bytemuck", + "cap-std", "craft-cms", "craft-image-codecs", "craft-materialx", diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index fbc4138a..516e0f5d 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -39,6 +39,7 @@ rayon = { workspace = true } base64 = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +cap-std = { workspace = true } sysinfo = { workspace = true } [dev-dependencies] diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 35fe4621..235f261d 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -595,6 +595,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } let mut used = BTreeSet::new(); + let mut active_files = BTreeSet::new(); + let mut active_dirs = BTreeSet::new(); let mut out = Vec::new(); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; let grid = set.tile_grid(); @@ -697,11 +699,25 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export if k > 2 { warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); } - used.insert(name.to_ascii_lowercase()); + let lower = name.to_ascii_lowercase(); + used.insert(lower.clone()); if !enabled { continue; } + if active_dirs.contains(&lower) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); + } + let mut prefix = lower.as_str(); + while let Some((folder, _)) = prefix.rsplit_once('/') { + if active_files.contains(folder) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); + } + active_dirs.insert(folder.to_owned()); + prefix = folder; + } + active_files.insert(lower); + if color_map && requested_space != space { warnings.push(format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())); } @@ -1559,9 +1575,9 @@ fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl /// names; the folders are created inside `dir`. #[cfg(not(target_arch = "wasm32"))] pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result> { - std::fs::create_dir_all(dir)?; - let root = dir.canonicalize()?; - let mut targets = Vec::with_capacity(files.len()); + let mut seen_files = BTreeSet::new(); + let mut seen_dirs = BTreeSet::new(); + let mut rel_targets = Vec::with_capacity(files.len()); for f in files { // Cap the sanitized stem before adding the extension let (stem, ext) = f.name.rsplit_once('.').unwrap_or((&f.name, "")); @@ -1569,18 +1585,32 @@ pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result>(), ["a/x.png", "b/x.png"]); + + #[cfg(not(target_arch = "wasm32"))] + { + let dir = std::env::temp_dir().join(format!("tc-formats-conflict-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file_a = ExportedFile { name: "a.png".into(), ..valid_files[0].clone() }; + let nested_b = ExportedFile { name: "a.png/b.png".into(), ..valid_files[1].clone() }; + let upper_a = ExportedFile { name: "A.PNG".into(), ..valid_files[0].clone() }; + for pair in [[file_a, nested_b.clone()], [nested_b, upper_a]] { + assert!(write_files(&pair, &dir).is_err()); + assert!(std::fs::read_dir(&dir).unwrap().next().is_none(), "conflict must not create folders or files"); + } + std::fs::remove_dir_all(&dir).unwrap(); + } +} + +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[test] +fn folder_templates_reject_symlink_escapes_before_creating_subfolders() { + let fx = Fx::new(&default_channels()); + let files = fx.render_preset("Unreal Engine (Packed)"); + let base = std::env::temp_dir().join(format!("tc-formats-symlink-escape-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("out"); + let outside = base.join("outside"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("link")).unwrap(); + + let nested = ExportedFile { name: "link/new/map.png".into(), ..files[0].clone() }; + assert!(write_files(&[nested], &dir).is_err()); + assert!(!outside.join("new").exists(), "must not create directories through an escaping symlink"); + + let direct = ExportedFile { name: "link/map.png".into(), ..files[0].clone() }; + assert!(write_files(&[direct], &dir).is_err()); + assert!(!outside.join("map.png").exists()); + + std::fs::remove_dir_all(&base).unwrap(); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 8dc7d67e..03dc8cef 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -123,15 +123,199 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { /// Create a new temporary file beside `path`, refusing to reuse an existing (possibly symlinked) name. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> { - create_temp_with_mode(path, &std::collections::HashSet::new(), None) + let (tmp, file) = create_temp_with_mode(BatchRoot::Ambient, path, &std::collections::HashSet::new(), None)?; + match file { + BatchFile::Std(file) => Ok((tmp, file)), + BatchFile::Cap(_) => Err(FormatError::Io(std::io::Error::other("unexpected capability handle"))), + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy)] +enum BatchRoot<'a> { + Ambient, + Dir(&'a cap_std::fs::Dir), +} + +#[cfg(not(target_arch = "wasm32"))] +enum BatchFile { + Std(std::fs::File), + Cap(cap_std::fs::File), +} + +#[cfg(not(target_arch = "wasm32"))] +impl BatchFile { + fn write_and_sync(&mut self, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + match self { + Self::Std(file) => file.write_all(bytes).and_then(|()| file.sync_all()), + Self::Cap(file) => file.write_all(bytes).and_then(|()| file.sync_all()), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl BatchRoot<'_> { + fn is_dir(self, path: &std::path::Path) -> bool { + match self { + Self::Ambient => path.is_dir(), + Self::Dir(dir) => dir.is_dir(path), + } + } + + fn open_create_new(self, path: &std::path::Path, #[cfg_attr(not(unix), allow(unused_variables))] unix_mode: Option) -> std::io::Result { + match self { + Self::Ambient => { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if let Some(mode) = unix_mode { + use std::os::unix::fs::OpenOptionsExt; + options.mode(mode); + } + options.open(path).map(BatchFile::Std) + } + Self::Dir(dir) => { + let mut options = cap_std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if let Some(mode) = unix_mode { + use cap_std::fs::OpenOptionsExt; + options.mode(mode); + } + dir.open_with(path, &options).map(BatchFile::Cap) + } + } + } + + fn remove_file(self, path: &std::path::Path) -> std::io::Result<()> { + match self { + Self::Ambient => std::fs::remove_file(path), + Self::Dir(dir) => dir.remove_file(path), + } + } + + fn rename(self, from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { + match self { + Self::Ambient => std::fs::rename(from, to), + Self::Dir(dir) => dir.rename(from, dir, to), + } + } + + #[cfg(unix)] + fn restore_symlink(self, link_target: &std::path::Path, target_path: &std::path::Path) -> std::io::Result<()> { + match self { + Self::Ambient => std::fs::remove_file(target_path).and_then(|()| std::os::unix::fs::symlink(link_target, target_path)), + Self::Dir(dir) => dir.remove_file(target_path).and_then(|()| dir.symlink_contents(link_target, target_path)), + } + } + + fn target_matches_bytes(self, target_path: &std::path::Path, expected_bytes: &[u8]) -> bool { + use std::io::Read; + + let mut buf = Vec::with_capacity(expected_bytes.len().min(4096)); + let ok = match self { + Self::Ambient => { + let Ok(meta) = std::fs::symlink_metadata(target_path) else { return false }; + if !meta.file_type().is_file() { + return false; + } + let Ok(file) = std::fs::File::open(target_path) else { return false }; + let Ok(handle_meta) = file.metadata() else { return false }; + handle_meta.file_type().is_file() && file.take(expected_bytes.len() as u64 + 1).read_to_end(&mut buf).is_ok() + } + Self::Dir(dir) => { + let Ok(meta) = dir.symlink_metadata(target_path) else { return false }; + if !meta.file_type().is_file() { + return false; + } + let Ok(file) = dir.open(target_path) else { return false }; + let Ok(handle_meta) = file.metadata() else { return false }; + handle_meta.file_type().is_file() && file.take(expected_bytes.len() as u64 + 1).read_to_end(&mut buf).is_ok() + } + }; + ok && buf.as_slice() == expected_bytes + } + + fn prepare_backup( + self, + target_path: &std::path::Path, + reserved: &mut std::collections::HashSet, + ) -> std::io::Result> { + match self { + Self::Ambient => match std::fs::symlink_metadata(target_path) { + Ok(meta) => { + #[cfg(unix)] + if meta.file_type().is_symlink() { + return std::fs::read_link(target_path).map(|t| Some(RollbackBackup::Symlink(t))); + } + if !meta.file_type().is_file() { + return Err(std::io::Error::other(format!("{} is not a regular file", target_path.display()))); + } + let (backup_path, backup_file) = + create_temp_with_mode(self, target_path, reserved, Some(0o600)).map_err(|e| std::io::Error::other(e.to_string()))?; + reserved.insert(backup_path.clone()); + let copy_result = (|| -> std::io::Result<()> { + let mut src = std::fs::File::open(target_path)?; + let BatchFile::Std(mut dst) = backup_file else { + return Err(std::io::Error::other("unexpected capability handle")); + }; + std::io::copy(&mut src, &mut dst)?; + dst.set_permissions(meta.permissions())?; + dst.sync_all()?; + Ok(()) + })(); + if let Err(error) = copy_result { + let _ = std::fs::remove_file(&backup_path); + return Err(error); + } + Ok(Some(RollbackBackup::File(backup_path))) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + }, + Self::Dir(dir) => match dir.symlink_metadata(target_path) { + Ok(meta) => { + #[cfg(unix)] + if meta.file_type().is_symlink() { + return dir.read_link_contents(target_path).map(|t| Some(RollbackBackup::Symlink(t))); + } + if !meta.file_type().is_file() { + return Err(std::io::Error::other(format!("{} is not a regular file", target_path.display()))); + } + let (backup_path, backup_file) = + create_temp_with_mode(self, target_path, reserved, Some(0o600)).map_err(|e| std::io::Error::other(e.to_string()))?; + reserved.insert(backup_path.clone()); + let copy_result = (|| -> std::io::Result<()> { + let mut src = dir.open(target_path)?; + let BatchFile::Cap(mut dst) = backup_file else { + return Err(std::io::Error::other("unexpected std file handle")); + }; + std::io::copy(&mut src, &mut dst)?; + dst.set_permissions(meta.permissions())?; + dst.sync_all()?; + Ok(()) + })(); + if let Err(error) = copy_result { + let _ = dir.remove_file(&backup_path); + return Err(error); + } + Ok(Some(RollbackBackup::File(backup_path))) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + }, + } + } } #[cfg(not(target_arch = "wasm32"))] fn create_temp_with_mode( + root: BatchRoot<'_>, path: &std::path::Path, excluded: &std::collections::HashSet, - #[cfg_attr(not(unix), allow(unused_variables))] unix_mode: Option, -) -> Result<(std::path::PathBuf, std::fs::File)> { + unix_mode: Option, +) -> Result<(std::path::PathBuf, BatchFile)> { let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out"); @@ -143,14 +327,7 @@ fn create_temp_with_mode( if excluded.contains(&temporary_path) { continue; } - let mut options = std::fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - if let Some(mode) = unix_mode { - use std::os::unix::fs::OpenOptionsExt; - options.mode(mode); - } - match options.open(&temporary_path) { + match root.open_create_new(&temporary_path, unix_mode) { Ok(file) => return Ok((temporary_path, file)), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => return Err(error.into()), @@ -177,6 +354,13 @@ pub fn write_batch_atomic<'a>(entries: impl IntoIterator(root: &cap_std::fs::Dir, entries: impl IntoIterator) -> Result<()> { + write_batch_atomic_with_root(BatchRoot::Dir(root), entries, |_, _| Ok(())) +} + #[cfg(not(target_arch = "wasm32"))] enum RollbackBackup { File(std::path::PathBuf), @@ -185,32 +369,28 @@ enum RollbackBackup { } #[cfg(not(target_arch = "wasm32"))] -fn target_matches_bytes(target_path: &std::path::Path, expected_bytes: &[u8]) -> bool { - use std::io::Read; +fn write_batch_atomic_with_hook<'a>( + entries: impl IntoIterator, + before_rename: impl FnMut(usize, &std::path::Path) -> std::io::Result<()>, +) -> Result<()> { + write_batch_atomic_with_root(BatchRoot::Ambient, entries, before_rename) +} - let Ok(meta) = std::fs::symlink_metadata(target_path) else { return false }; - if !meta.file_type().is_file() { - return false; - } - let Ok(file) = std::fs::File::open(target_path) else { return false }; - let Ok(handle_meta) = file.metadata() else { return false }; - if !handle_meta.file_type().is_file() { - return false; - } - let mut buf = Vec::with_capacity(expected_bytes.len().min(4096)); - if file.take(expected_bytes.len() as u64 + 1).read_to_end(&mut buf).is_err() { - return false; - } - buf.as_slice() == expected_bytes +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn write_batch_atomic_in_dir_with_hook<'a>( + root: &cap_std::fs::Dir, + entries: impl IntoIterator, + before_rename: impl FnMut(usize, &std::path::Path) -> std::io::Result<()>, +) -> Result<()> { + write_batch_atomic_with_root(BatchRoot::Dir(root), entries, before_rename) } #[cfg(not(target_arch = "wasm32"))] -fn write_batch_atomic_with_hook<'a>( +fn write_batch_atomic_with_root<'a>( + root: BatchRoot<'_>, entries: impl IntoIterator, mut before_rename: impl FnMut(usize, &std::path::Path) -> std::io::Result<()>, ) -> Result<()> { - use std::io::Write; - // Serialize in-process batch publications so concurrent tasks cannot interleave backups/rollbacks. static BATCH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); let _guard = BATCH_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -223,16 +403,16 @@ fn write_batch_atomic_with_hook<'a>( let mut staged: Vec<(std::path::PathBuf, &std::path::Path, &[u8])> = Vec::with_capacity(entries.len()); let cleanup_staged = |staged: &[(std::path::PathBuf, &std::path::Path, &[u8])]| { for (temp_path, _, _) in staged { - let _ = std::fs::remove_file(temp_path); + let _ = root.remove_file(temp_path); } }; for (path, bytes) in entries { - if path.is_dir() { + if root.is_dir(path) { cleanup_staged(&staged); return Err(FormatError::Io(std::io::Error::other(format!("{} is a directory", path.display())))); } - let (temporary_path, mut file) = match create_temp_with_mode(path, &reserved, None) { + let (temporary_path, mut file) = match create_temp_with_mode(root, path, &reserved, None) { Ok(pair) => pair, Err(error) => { cleanup_staged(&staged); @@ -240,10 +420,10 @@ fn write_batch_atomic_with_hook<'a>( } }; reserved.insert(temporary_path.clone()); - let write_result = file.write_all(bytes).and_then(|_| file.sync_all()); + let write_result = file.write_and_sync(bytes); drop(file); if let Err(error) = write_result { - let _ = std::fs::remove_file(&temporary_path); + let _ = root.remove_file(&temporary_path); cleanup_staged(&staged); return Err(error.into()); } @@ -253,8 +433,8 @@ fn write_batch_atomic_with_hook<'a>( // Single-file writes have no earlier publications to roll back, so rename directly. if staged.len() == 1 { let (ref temporary_path, target_path, _) = staged[0]; - if let Err(error) = before_rename(0, target_path).and_then(|()| std::fs::rename(temporary_path, target_path)) { - let _ = std::fs::remove_file(temporary_path); + if let Err(error) = before_rename(0, target_path).and_then(|()| root.rename(temporary_path, target_path)) { + let _ = root.remove_file(temporary_path); return Err(error.into()); } return Ok(()); @@ -268,7 +448,7 @@ fn write_batch_atomic_with_hook<'a>( let mut incomplete = Vec::new(); for (target_path, expected_bytes, backup) in published.drain(..).rev() { // Do not overwrite if an external writer modified the target after we published it. - if !target_matches_bytes(target_path, expected_bytes) { + if !root.target_matches_bytes(target_path, expected_bytes) { if let Some(RollbackBackup::File(backup_path)) = backup { incomplete.push(format!("{} (modified by another writer; backup at {})", target_path.display(), backup_path.display())); } else { @@ -278,18 +458,18 @@ fn write_batch_atomic_with_hook<'a>( } match backup { Some(RollbackBackup::File(backup_path)) => { - if let Err(err) = std::fs::rename(&backup_path, target_path) { + if let Err(err) = root.rename(&backup_path, target_path) { incomplete.push(format!("{} (backup at {}): {err}", target_path.display(), backup_path.display())); } } #[cfg(unix)] Some(RollbackBackup::Symlink(link_target)) => { - if let Err(err) = std::fs::remove_file(target_path).and_then(|()| std::os::unix::fs::symlink(&link_target, target_path)) { + if let Err(err) = root.restore_symlink(&link_target, target_path) { incomplete.push(format!("{} (symlink -> {}): {err}", target_path.display(), link_target.display())); } } None => { - if let Err(err) = std::fs::remove_file(target_path) { + if let Err(err) = root.remove_file(target_path) { incomplete.push(format!("{}: {err}", target_path.display())); } } @@ -309,44 +489,14 @@ fn write_batch_atomic_with_hook<'a>( if let Err(error) = before_rename(index, target_path) { return Err(rollback(&mut published, &staged[index..], error)); } - let backup = match std::fs::symlink_metadata(target_path) { - Ok(meta) => { - #[cfg(unix)] - if meta.file_type().is_symlink() { - match std::fs::read_link(target_path) { - Ok(link_target) => Some(RollbackBackup::Symlink(link_target)), - Err(error) => return Err(rollback(&mut published, &staged[index..], error)), - } - } else if !meta.file_type().is_file() { - return Err(rollback(&mut published, &staged[index..], std::io::Error::other(format!("{} is not a regular file", target_path.display())))); - } else { - match stage_file_backup(target_path, &meta, &mut reserved) { - Ok(path) => Some(RollbackBackup::File(path)), - Err(error) => return Err(rollback(&mut published, &staged[index..], error)), - } - } - #[cfg(not(unix))] - { - if !meta.file_type().is_file() { - return Err(rollback( - &mut published, - &staged[index..], - std::io::Error::other(format!("{} is not a regular file", target_path.display())), - )); - } - match stage_file_backup(target_path, &meta, &mut reserved) { - Ok(path) => Some(RollbackBackup::File(path)), - Err(error) => return Err(rollback(&mut published, &staged[index..], error)), - } - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + let backup = match root.prepare_backup(target_path, &mut reserved) { + Ok(backup) => backup, Err(error) => return Err(rollback(&mut published, &staged[index..], error)), }; - if let Err(error) = std::fs::rename(&staged[index].0, target_path) { + if let Err(error) = root.rename(&staged[index].0, target_path) { if let Some(RollbackBackup::File(ref backup_path)) = backup { - let _ = std::fs::remove_file(backup_path); + let _ = root.remove_file(backup_path); } return Err(rollback(&mut published, &staged[index..], error)); } @@ -355,36 +505,13 @@ fn write_batch_atomic_with_hook<'a>( for (_, _, backup) in published { if let Some(RollbackBackup::File(backup_path)) = backup { - let _ = std::fs::remove_file(backup_path); + let _ = root.remove_file(&backup_path); } } Ok(()) } -#[cfg(not(target_arch = "wasm32"))] -fn stage_file_backup( - target_path: &std::path::Path, - meta: &std::fs::Metadata, - reserved: &mut std::collections::HashSet, -) -> std::io::Result { - let (backup_path, mut backup_file) = create_temp_with_mode(target_path, reserved, Some(0o600)).map_err(|e| std::io::Error::other(e.to_string()))?; - reserved.insert(backup_path.clone()); - let copy_result = (|| -> std::io::Result<()> { - let mut src = std::fs::File::open(target_path)?; - std::io::copy(&mut src, &mut backup_file)?; - backup_file.set_permissions(meta.permissions())?; - backup_file.sync_all()?; - Ok(()) - })(); - drop(backup_file); - if let Err(error) = copy_result { - let _ = std::fs::remove_file(&backup_path); - return Err(error); - } - Ok(backup_path) -} - #[cfg(test)] mod batch_atomic_tests { use super::{write_batch_atomic, write_batch_atomic_with_hook}; @@ -458,7 +585,7 @@ mod batch_atomic_tests { #[cfg(all(test, unix))] mod atomic_tests { - use super::{write_atomic, write_batch_atomic_with_hook}; + use super::{write_atomic, write_batch_atomic_in_dir_with_hook, write_batch_atomic_with_hook}; #[test] fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> { @@ -504,4 +631,34 @@ mod atomic_tests { let _ = std::fs::remove_dir_all(&directory); Ok(()) } + + #[test] + fn write_batch_atomic_in_dir_rejects_parent_replaced_with_symlink_mid_batch() -> std::io::Result<()> { + let base = std::env::temp_dir().join(format!("tc-dir-symlink-race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("out"); + let outside = base.join("outside"); + std::fs::create_dir_all(dir.join("sub"))?; + std::fs::create_dir_all(&outside)?; + + let root_dir = cap_std::fs::Dir::open_ambient_dir(&dir, cap_std::ambient_authority())?; + let result = write_batch_atomic_in_dir_with_hook( + &root_dir, + [(std::path::Path::new("first.png"), b"first".as_slice()), (std::path::Path::new("sub/second.png"), b"second".as_slice())], + |index, _target| { + if index == 1 { + std::fs::remove_dir(dir.join("sub"))?; + std::os::unix::fs::symlink(&outside, dir.join("sub"))?; + } + Ok(()) + }, + ); + + assert!(result.is_err()); + assert!(!dir.join("first.png").exists()); + assert!(!outside.join("second.png").exists()); + + let _ = std::fs::remove_dir_all(&base); + Ok(()) + } } From c4958764f1a508846087967a00663b855fe69e92 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:21:35 +0000 Subject: [PATCH 137/153] Automatic cage: fit along a vertex's own normal where welding cancelled it Parts welded back to back (or a double-sided sheet) sum to a zero averaged normal; the transfer ray there falls back to the surface normal, so the fit now measures along the vertex's own normal too instead of finding no direction and keeping only the padding --- crates/bake/src/cage/fitted_cage.rs | 23 +++++++-- crates/bake/src/test/fitted_cage.rs | 76 ++++++++++++++++++++++++++--- 2 files changed, 88 insertions(+), 11 deletions(-) diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs index 54bbde47..05d205f8 100644 --- a/crates/bake/src/cage/fitted_cage.rs +++ b/crates/bake/src/cage/fitted_cage.rs @@ -22,13 +22,15 @@ pub(crate) struct FittedCage { } impl FittedCage { - /// Fit the cage of `request`'s low poly around `high` along `ray_normals`: each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + /// Fit the cage of `request`'s low poly around `high` along `ray_normals` (where parts welded back to back cancelled a vertex's normal out, along its own): each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { let low = request.mesh; let keys = NameKeys::of(request, high); let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + + let fitting_normals = fitting_normals(low, ray_normals); let mut reach: Vec> = vec![None; welded_count]; let mut widen = |vertex: usize, height: f32| { if let Some(distances) = reach.get_mut(welded(vertex)) { @@ -37,12 +39,12 @@ impl FittedCage { } }; - for (vertex, height) in heights_at_low_vertices(low, high, ray_normals, &keys, extent.diagonal).into_iter().enumerate() { + for (vertex, height) in heights_at_low_vertices(low, high, &fitting_normals, &keys, extent.diagonal).into_iter().enumerate() { if let Some(height) = height { widen(vertex, height); } } - for (triangle, height) in heights_of_high_vertices(request, high, ray_normals, &keys).into_iter().flatten() { + for (triangle, height) in heights_of_high_vertices(request, high, &fitting_normals, &keys).into_iter().flatten() { for corner in low.tri(triangle).into_iter().flatten() { widen(corner, height); } @@ -89,6 +91,21 @@ fn welded_within_groups(welded_indices: &[u32], vertex_keys: &[u32]) -> Vec .collect() } +/// `ray_normals`, except where parts welded back to back cancelled a vertex's normal out: there, the vertex's own normal, the direction its transfer rays fall back to +fn fitting_normals(low: &Mesh, ray_normals: &[Vec3]) -> Vec { + ray_normals + .iter() + .enumerate() + .map(|(vertex, &welded_normal)| { + if welded_normal != Vec3::ZERO { + return welded_normal; + } + + low.normals.get(vertex).and_then(|normal| normal.try_normalize()).unwrap_or(welded_normal) + }) + .collect() +} + /// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { low.positions diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index b6253f51..419b6fc4 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -1,6 +1,6 @@ use super::{covered_values, settings, transfer}; use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; -use texturecraft_core::{BakeSettings, BakedMap, CageType}; +use texturecraft_core::{BakeSettings, BakedMap, CageType, MeshMatchMode}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Bvh, Mesh, primitives}; @@ -36,6 +36,14 @@ fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(V shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() } +/// Every submesh on the first material, so the cage shell of material 0 covers all the parts +fn one_material(mesh: &mut Mesh) { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } +} + #[test] fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { let low = primitives::cube(1.0); @@ -142,7 +150,7 @@ fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { low.submeshes[0].name = "panel_low".into(); high.submeshes[0].name = "door_high".into(); let mut bake_settings = automatic(&[BakedMap::Normal]); - bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; let heights = cage_heights(&low, &high, &bake_settings); @@ -167,15 +175,11 @@ fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() low.append(&part("right_low", 1.0, 0.0, 4)); let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); - // One material, so the cage shell covers both low parts for mesh in [&mut low, &mut high] { - mesh.materials.truncate(1); - for submesh in &mut mesh.submeshes { - submesh.material = 0; - } + one_material(mesh); } let mut bake_settings = automatic(&[BakedMap::Normal]); - bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; let heights = cage_heights(&low, &high, &bake_settings); @@ -185,3 +189,59 @@ fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); } } + +#[test] +fn parts_back_to_back_fit_their_cages_along_their_own_normals() { + const SHEET_DISTANCE: f32 = 0.2; + + // A plane facing up and the same plane facing down, each facing its own high-poly sheet: welded, their normals cancel out + let named = |mut mesh: Mesh, name: &str| { + mesh.submeshes[0].name = name.into(); + mesh + }; + let facing_down = |mut mesh: Mesh| { + for normal in &mut mesh.normals { + *normal = -*normal; + } + for triangle in mesh.indices.chunks_exact_mut(3) { + triangle.swap(1, 2); + } + mesh + }; + let sheet = |height: f32| { + let mut sheet = primitives::plane(1.0, 8); + for position in &mut sheet.positions { + position.y = height; + } + sheet + }; + let mut low = named(primitives::plane(1.0, 4), "front_low"); + low.append(&named(facing_down(primitives::plane(1.0, 4)), "back_low")); + let mut high = named(sheet(SHEET_DISTANCE), "front_high"); + high.append(&named(facing_down(sheet(-SHEET_DISTANCE)), "back_high")); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + + for match_mode in [MeshMatchMode::Always, MeshMatchMode::ByMeshName] { + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = match_mode; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The front part's triangles come first, three corners each + let front_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..front_corners] { + assert!( + (SHEET_DISTANCE..UNFITTED_DISTANCE).contains(height), + "{match_mode:?}: the front part's cage at {position} reaches the sheet above it, fitted: {height}" + ); + } + for (position, height) in &heights[front_corners..] { + assert!( + (-UNFITTED_DISTANCE..=-SHEET_DISTANCE).contains(height), + "{match_mode:?}: the back part's cage at {position} reaches the sheet below it, fitted: {height}" + ); + } + } +} From 6c72fcb34e241a56aeb4072c5df5d18f1ed6f892 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:22:16 +0700 Subject: [PATCH 138/153] Fix Windows test cfg gate for write_batch_atomic_in_dir_with_hook --- crates/formats/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 03dc8cef..4b22ddba 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -376,7 +376,7 @@ fn write_batch_atomic_with_hook<'a>( write_batch_atomic_with_root(BatchRoot::Ambient, entries, before_rename) } -#[cfg(all(test, not(target_arch = "wasm32")))] +#[cfg(all(test, unix))] pub(crate) fn write_batch_atomic_in_dir_with_hook<'a>( root: &cap_std::fs::Dir, entries: impl IntoIterator, From d2a4b44a1d696316e789033d118a1c64cf1d4f4c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:33:19 +0000 Subject: [PATCH 139/153] Back-to-back cage test: chunk the indices with as_chunks_mut --- crates/bake/src/test/fitted_cage.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index 419b6fc4..5c44dba6 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -203,7 +203,7 @@ fn parts_back_to_back_fit_their_cages_along_their_own_normals() { for normal in &mut mesh.normals { *normal = -*normal; } - for triangle in mesh.indices.chunks_exact_mut(3) { + for triangle in mesh.indices.as_chunks_mut::<3>().0 { triangle.swap(1, 2); } mesh From 0e1d9dfff1e57ab4258bb6e857d82d876cdb99f3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:43:23 +0700 Subject: [PATCH 140/153] Export templates: reject in-tree symlink folder aliases Stage capability-scoped temps in the output root so the mid-batch escape test can actually install a parent symlink, and refuse export folders that are symbolic links so two names cannot resolve to the same file. --- crates/formats/src/export/mod.rs | 28 +++++++++++++++++++++++++--- crates/formats/src/export/tests.rs | 18 ++++++++++++++++++ crates/formats/src/lib.rs | 22 +++++++++++++++++++--- 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 235f261d..f2134a0c 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -1605,13 +1605,35 @@ pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result Result<()> { + let Some(parent) = rel.parent().filter(|parent| !parent.as_os_str().is_empty()) else { + return Ok(()); + }; + + let mut prefix = std::path::PathBuf::new(); + for component in parent.components() { + prefix.push(component); + match root.symlink_metadata(&prefix) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(FormatError::Invalid(format!("\"{}\" cannot use a symbolic link as a folder", rel.display()))); + } + Ok(meta) if meta.file_type().is_dir() => {} + Ok(_) => return Err(FormatError::Invalid(format!("\"{}\" cannot use an existing file as a folder", rel.display()))), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => root.create_dir(&prefix)?, + Err(error) => return Err(error.into()), + } + } + Ok(()) +} + #[cfg(test)] mod tests; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 41c81f71..45ef06cb 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1541,3 +1541,21 @@ fn folder_templates_reject_symlink_escapes_before_creating_subfolders() { std::fs::remove_dir_all(&base).unwrap(); } + +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[test] +fn folder_templates_reject_in_tree_symlink_aliases() { + let fx = Fx::new(&default_channels()); + let files = fx.render_preset("Unreal Engine (Packed)"); + let dir = std::env::temp_dir().join(format!("tc-formats-symlink-alias-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("a")).unwrap(); + std::os::unix::fs::symlink(dir.join("a"), dir.join("b")).unwrap(); + + let one = ExportedFile { name: "a/map.png".into(), ..files[0].clone() }; + let two = ExportedFile { name: "b/map.png".into(), ..files[1].clone() }; + assert!(write_files(&[one, two], &dir).is_err()); + assert!(!dir.join("a").join("map.png").exists()); + + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 4b22ddba..7968b2d8 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -316,12 +316,24 @@ fn create_temp_with_mode( excluded: &std::collections::HashSet, unix_mode: Option, ) -> Result<(std::path::PathBuf, BatchFile)> { - let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); - let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out"); - // Bound retries when stale files, batch targets, or concurrent writers occupy candidate names const MAX_TEMP_ATTEMPTS: u32 = 256; + // Capability-scoped writes keep temporary files in the output root so a parent folder that is + // replaced after staging cannot hide the staged file, and so two maps with the same basename + // in different folders do not share a temporary name + let (parent, name) = match root { + BatchRoot::Ambient => { + let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); + let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out").to_owned(); + (parent.to_path_buf(), name) + } + BatchRoot::Dir(_) => { + let name: String = path.iter().map(|part| part.to_string_lossy()).collect::>().join("_"); + (std::path::PathBuf::from("."), if name.is_empty() { "out".into() } else { name }) + } + }; + for attempt in 0..MAX_TEMP_ATTEMPTS { let temporary_path = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id())); if excluded.contains(&temporary_path) { @@ -642,18 +654,22 @@ mod atomic_tests { std::fs::create_dir_all(&outside)?; let root_dir = cap_std::fs::Dir::open_ambient_dir(&dir, cap_std::ambient_authority())?; + let replaced = std::cell::Cell::new(false); let result = write_batch_atomic_in_dir_with_hook( &root_dir, [(std::path::Path::new("first.png"), b"first".as_slice()), (std::path::Path::new("sub/second.png"), b"second".as_slice())], |index, _target| { if index == 1 { + // Temporary files for capability-scoped writes live in the output root, so `sub` is still empty std::fs::remove_dir(dir.join("sub"))?; std::os::unix::fs::symlink(&outside, dir.join("sub"))?; + replaced.set(std::fs::symlink_metadata(dir.join("sub"))?.file_type().is_symlink()); } Ok(()) }, ); + assert!(replaced.get(), "the hook must install the escaping symlink before the second rename"); assert!(result.is_err()); assert!(!dir.join("first.png").exists()); assert!(!outside.join("second.png").exists()); From 77850f6374e334f3c0f419108e1710c8375fb329 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:54:11 +0700 Subject: [PATCH 141/153] Use a short temp name for confined export writes --- crates/formats/src/export/tests.rs | 16 ++++++++++++++++ crates/formats/src/lib.rs | 11 ++++------- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 45ef06cb..392148a1 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1559,3 +1559,19 @@ fn folder_templates_reject_in_tree_symlink_aliases() { std::fs::remove_dir_all(&dir).unwrap(); } + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn write_files_accepts_a_long_nested_folder_and_stem() { + let fx = Fx::new(&default_channels()); + let files = fx.render_preset("Unreal Engine (Packed)"); + let folder = "a".repeat(200); + let stem = "b".repeat(200); + let name = format!("{folder}/{stem}.png"); + let dir = std::env::temp_dir().join(format!("tc-formats-export-long-nested-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let paths = write_files(&[ExportedFile { name: name.clone(), ..files[0].clone() }], &dir).unwrap(); + assert_eq!(paths, [dir.join(&folder).join(format!("{stem}.png"))]); + assert!(paths[0].is_file()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 7968b2d8..a3a8a3f4 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -319,19 +319,16 @@ fn create_temp_with_mode( // Bound retries when stale files, batch targets, or concurrent writers occupy candidate names const MAX_TEMP_ATTEMPTS: u32 = 256; - // Capability-scoped writes keep temporary files in the output root so a parent folder that is - // replaced after staging cannot hide the staged file, and so two maps with the same basename - // in different folders do not share a temporary name + // Capability-scoped writes keep a short temporary name in the output root so a parent folder + // that is replaced after staging cannot hide the staged file, and so a long nested export name + // cannot overflow the filesystem name limit let (parent, name) = match root { BatchRoot::Ambient => { let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out").to_owned(); (parent.to_path_buf(), name) } - BatchRoot::Dir(_) => { - let name: String = path.iter().map(|part| part.to_string_lossy()).collect::>().join("_"); - (std::path::PathBuf::from("."), if name.is_empty() { "out".into() } else { name }) - } + BatchRoot::Dir(_) => (std::path::PathBuf::from("."), "export".into()), }; for attempt in 0..MAX_TEMP_ATTEMPTS { From f9ba93a7bee13d2e096c3049236eecfabc322e43 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:07:53 +0700 Subject: [PATCH 142/153] Give each confined export temp a unique short id A directory-scoped batch previously reused one .export.{pid}.{attempt}.tmp namespace of 256 names for every staging file and backup. Exports larger than that limit, or overwrites of about half as many existing files, failed even when every output path was valid. Each allocation now gets its own short identifier, while the collision retries stay within that namespace. --- crates/formats/src/lib.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a3a8a3f4..a46a6f62 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -321,14 +321,19 @@ fn create_temp_with_mode( // Capability-scoped writes keep a short temporary name in the output root so a parent folder // that is replaced after staging cannot hide the staged file, and so a long nested export name - // cannot overflow the filesystem name limit + // cannot overflow the filesystem name limit. Each allocation gets its own identifier so a large + // batch, including backups of existing files, does not exhaust the shared 256-name retry set let (parent, name) = match root { BatchRoot::Ambient => { let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out").to_owned(); (parent.to_path_buf(), name) } - BatchRoot::Dir(_) => (std::path::PathBuf::from("."), "export".into()), + BatchRoot::Dir(_) => { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + (std::path::PathBuf::from("."), format!("export-{id}")) + } }; for attempt in 0..MAX_TEMP_ATTEMPTS { @@ -674,4 +679,26 @@ mod atomic_tests { let _ = std::fs::remove_dir_all(&base); Ok(()) } + + #[test] + fn write_batch_atomic_in_dir_can_stage_more_files_than_the_collision_retry_limit() -> std::io::Result<()> { + let directory = std::env::temp_dir().join(format!("tc-dir-many-temps-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&directory); + std::fs::create_dir_all(&directory)?; + let names: Vec = (0..257).map(|i| std::path::PathBuf::from(format!("f{i}.png"))).collect(); + let bytes = vec![b"x".to_vec(); names.len()]; + let entries: Vec<(&std::path::Path, &[u8])> = names.iter().map(std::path::PathBuf::as_path).zip(bytes.iter().map(Vec::as_slice)).collect(); + + let root_dir = cap_std::fs::Dir::open_ambient_dir(&directory, cap_std::ambient_authority())?; + crate::write_batch_atomic_in_dir(&root_dir, entries).map_err(std::io::Error::other)?; + assert!(names.iter().all(|name| directory.join(name).is_file())); + + let bytes = vec![b"y".to_vec(); names.len()]; + let entries: Vec<(&std::path::Path, &[u8])> = names.iter().map(std::path::PathBuf::as_path).zip(bytes.iter().map(Vec::as_slice)).collect(); + crate::write_batch_atomic_in_dir(&root_dir, entries).map_err(std::io::Error::other)?; + assert!(names.iter().all(|name| std::fs::read(directory.join(name)).ok() == Some(b"y".to_vec()))); + + let _ = std::fs::remove_dir_all(&directory); + Ok(()) + } } From 333605327e437e29f8708d53efb696b58bfef677 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:57:21 +0000 Subject: [PATCH 143/153] Generators: a micro detail saved before Micro Details renders as saved while its generator stays on the earlier model MicroDetails.earlier marks a migrated {anchor, amount}: an earlier-model generator adds the anchor's height times the amount to its signal as #395 did; microAnchor/microAmount keep that reading on the earlier model, and any Micro Details control moves the generator onto the reference's controls and the anchor's curvature. --- crates/compose/src/eval.rs | 86 ++++++++++++++++++++--- crates/core/src/layer.rs | 32 ++++++++- crates/core/src/layer/micro_details.rs | 7 +- crates/engine/src/anchored_micro_edit.rs | 6 +- crates/engine/src/micro_params.rs | 1 + crates/engine/tests/it/content_effects.rs | 22 ++++++ 6 files changed, 140 insertions(+), 14 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a1a58358..a4c50ea2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3463,6 +3463,7 @@ impl<'a, 'b> Texel<'a, 'b> { } let coords = self.coords(); + let earlier_micro = generator.earlier_micro().map_or(0.0, |(anchor, amount)| self.earlier_micro_detail(generator.kind, anchor, amount)); // Micro details saved on the earlier model add to its curvature and occlusion inputs too let signal = match (generator.kind, &generator.detail) { @@ -3470,7 +3471,7 @@ impl<'a, 'b> Texel<'a, 'b> { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; let curvature = self.curvature_input(generator, maps); - self.curvature_detail(detail, sizes, curvature) + self.curvature_detail(detail, sizes, curvature, earlier_micro) } (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => (self.curvature_input(generator, maps).unwrap_or(0.5) - 0.5) * 2.0, (GeneratorKind::Curvature, None) => self.curvature_input(generator, maps).unwrap_or(0.5), @@ -3492,6 +3493,11 @@ impl<'a, 'b> Texel<'a, 'b> { _, ) => 0.0, }; + let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { + signal + } else { + signal + earlier_micro + }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -3519,7 +3525,7 @@ impl<'a, 'b> Texel<'a, 'b> { let detail = generator.detail_in_use().unwrap_or_default(); let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; let curvature = self.curvature_input(generator, maps); - self.curvature_detail(&detail, sizes, curvature) + self.curvature_detail(&detail, sizes, curvature, 0.0) } GeneratorKind::AmbientOcclusion => self.occlusion_input(generator, maps).unwrap_or(1.0), GeneratorKind::Position => { @@ -3682,6 +3688,31 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// How a micro detail saved before Micro Details moves an earlier-model generator's signal at this texel: anchor point `anchor`'s height times `amount` (0 where the anchor is not evaluated yet), an edge where raised and a cavity where recessed + fn earlier_micro_detail(&self, kind: GeneratorKind, anchor: LayerId, amount: f32) -> f32 { + let response = self.anchor_value(anchor, Channel::Height, ChannelKind::Signed)[0].clamp(-1.0, 1.0) * amount; + match kind { + GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::AmbientOcclusion => response, + + // Dirt gathers in dents + GeneratorKind::Dirt => -response, + + // Kinds the micro detail never moved, or without an earlier model + GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThinAreas + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, + } + } + /// The generator's curvature input at this texel with what its micro details add fn curvature_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { let curvature = self.generator_input(generator, BakedMap::Curvature)?; @@ -3715,16 +3746,20 @@ impl<'a, 'b> Texel<'a, 'b> { } } - /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { - 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), + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given and an earlier micro detail's term (see [`Texel::earlier_micro_detail`]) as an edge where positive and a cavity where negative + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, earlier_micro: f32) -> f32 { + let combine = |edges: f32, cavities: f32| { + let edges = 1.0 - (1.0 - edges) * (1.0 - earlier_micro.max(0.0)); + let cavities = 1.0 - (1.0 - cavities) * (1.0 + earlier_micro.min(0.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), + } }; - // Without curvature to read the texel is flat: no edges or cavities + // Without curvature to read only an earlier micro detail supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; @@ -7208,6 +7243,37 @@ soft {soft:?}" } } + #[test] + fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() { + const SAVED_AMOUNT: f32 = 0.25; + const FLAT_CURVATURE: f32 = 0.4; + let colors = |height: f32, curvature: f32, micro: bool| -> Vec { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![curvature; 64 * 64]))].into() }; + let low = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, Source::Uniform([height; 3])); + fixture.project.insert_layer(0, Layer::new(low, "Flat", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + let anchor = content_fx(&mut fixture, low, EffectKind::Anchor); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let earlier = Generator { section: None, detail: None, level: 0.5, softness: 0.5, noise_amount: 0.0, ..Generator::new(GeneratorKind::Curvature) }; + let micro = MicroDetails::of_anchor(GeneratorKind::Curvature, anchor, SAVED_AMOUNT).filter(|_| micro).map(Box::new); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(Generator { micro, ..earlier }))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + let composite = run(&fixture, None); + (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() + }; + + // The saved micro detail added the anchor's height times its amount to the curvature signal, even where the height is flat + for height in [0.0, 0.3, 0.6, 1.0] { + let saved = colors(0.0, FLAT_CURVATURE + height * SAVED_AMOUNT, false); + let loaded = colors(height, FLAT_CURVATURE, true); + let largest_change = saved.iter().zip(&loaded).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(largest_change < 1e-3, "height {height}: {largest_change}"); + } + } + #[test] fn fills_inside_folders_take_the_folders_scale_and_rotation_on_top_of_their_own() { // Nested folders (x2 turned 30, then x1.5 turned -10) around a procedural fill with a procedural mask fill diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 2e4371b5..ef7a535c 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1274,9 +1274,18 @@ impl Generator { self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } - /// The micro details as saved, when the generator computes with them: with a slot switched on, also on the earlier model where an anchor's micro detail saved before Micro Details reads (bring them into range before use: saved files are not trusted) + /// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted) pub fn micro_in_use(&self) -> Option<&MicroDetails> { - self.micro.as_deref().filter(|micro| micro.in_use(self.kind)) + self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model())) + } + + /// The anchor point and amount (0..1) of a micro detail saved before Micro Details, while the generator is still on the earlier model: its signal adds that anchor's height times the amount, as it did when saved + pub fn earlier_micro(&self) -> Option<(LayerId, f32)> { + let micro = self.micro.as_deref().filter(|micro| micro.earlier && micro.in_use(self.kind) && micro.height && self.on_earlier_model())?; + let Some(Source::Anchor { anchor, .. }) = µ.height_source else { return None }; + + let amount = micro.height_intensity / MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT; + Some((*anchor, if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 })) } /// Whether the generator is on the level, softness and noise it had before the reference app's controls @@ -2832,6 +2841,25 @@ mod tests { assert!(without.micro.is_none(), "a kind without micro details drops it"); } + #[test] + fn a_micro_detail_saved_on_an_anchor_keeps_its_earlier_reading_until_the_generator_leaves_the_earlier_model() { + // Saved before the reference's controls too: on the earlier model + let earlier = Generator { section: None, ..Generator::new(GeneratorKind::Curvature) }; + let mut saved = serde_json::to_value(earlier).unwrap(); + saved["micro"] = serde_json::json!({"anchor": 9, "amount": 0.25}); + let generator: Generator = serde_json::from_value(saved).unwrap(); + + assert_eq!(generator.earlier_micro(), Some((LayerId(9), 0.25))); + assert!(generator.micro_in_use().is_none(), "the earlier reading replaces the Micro Height's curvature"); + + let reloaded: Generator = serde_json::from_value(serde_json::to_value(&generator).unwrap()).unwrap(); + assert_eq!(reloaded.earlier_micro(), Some((LayerId(9), 0.25)), "saving again keeps the earlier reading"); + + let on_sections = Generator { section: SectionParameters::defaults(GeneratorKind::Curvature), ..generator }; + assert_eq!(on_sections.earlier_micro(), None); + assert!(on_sections.micro_in_use().is_some(), "on the reference's controls the anchor reads as a Micro Height"); + } + #[test] fn compare_masks_saved_before_sources_compare_the_mask_with_the_constant_hard() { let saved = r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#; diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 186f3af4..462cfa0d 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -29,6 +29,9 @@ pub struct MicroDetails { /// The micro normal image (None: an empty slot) #[serde(default, skip_serializing_if = "Option::is_none")] pub normal_source: Option, + /// Saved as the micro detail before Micro Details (an anchor's height times an amount): a generator still on the earlier model adds it that way, see [`super::Generator::earlier_micro`] + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub earlier: bool, } impl MicroDetails { @@ -37,7 +40,7 @@ impl MicroDetails { /// Height Details Intensity per unit of an anchor's micro detail amount (0..1): the earlier default amount, 0.5, reads at the default intensity pub const HEIGHT_INTENSITY_PER_AMOUNT: f32 = 2.0; - /// The micro details reading anchor point `anchor`'s height as their Micro Height at `amount` (0..1) on a `kind` generator, None for kinds without them + /// The micro detail saved before Micro Details, anchor point `anchor`'s height at `amount` (0..1), as Micro Details on a `kind` generator (None for kinds without them): the anchor is the Micro Height, `amount` its intensity pub fn of_anchor(kind: GeneratorKind, anchor: LayerId, amount: f32) -> Option { let amount = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 }; let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; @@ -46,6 +49,7 @@ impl MicroDetails { height: true, height_intensity: amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT, height_source: Some(source), + earlier: true, ..MicroDetails::defaults(kind)? }; Some(micro.clamped(kind)) @@ -64,6 +68,7 @@ impl MicroDetails { ao_depth: 0.05, height_source: None, normal_source: None, + earlier: false, }; match kind { GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion => Some(shared), diff --git a/crates/engine/src/anchored_micro_edit.rs b/crates/engine/src/anchored_micro_edit.rs index 75d2eb54..f509a525 100644 --- a/crates/engine/src/anchored_micro_edit.rs +++ b/crates/engine/src/anchored_micro_edit.rs @@ -42,9 +42,10 @@ impl AnchoredMicroEdit { Ok(Some(AnchoredMicroEdit { anchor, amount })) } - /// The edit made on `generator`: an anchor switches the micro details and their Micro Height on and reads it there + /// The edit made on `generator`: an anchor switches the micro details and their Micro Height on and reads it there; a generator on the earlier model reads it as these keys did before Micro Details pub fn apply(self, command: &str, generator: &mut Generator) -> Result<()> { let kind = generator.kind; + let earlier = generator.on_earlier_model(); let defaults = MicroDetails::defaults(kind); match (self.anchor, &defaults) { (Some(None), _) => { @@ -66,6 +67,9 @@ impl AnchoredMicroEdit { micro.height_intensity = amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT; **micro = micro.as_ref().clone().clamped(kind); } + if let Some(micro) = generator.micro.as_mut() { + micro.earlier = earlier; + } Ok(()) } } diff --git a/crates/engine/src/micro_params.rs b/crates/engine/src/micro_params.rs index 7e0ed083..bd62a209 100644 --- a/crates/engine/src/micro_params.rs +++ b/crates/engine/src/micro_params.rs @@ -60,6 +60,7 @@ pub fn micro_from(command: &str, params: &Value, generator: &mut Generator, earl } let micro = generator.micro.get_or_insert_with(|| Box::new(defaults)); + micro.earlier = false; for (key, value) in [("useMicroDetails", &mut micro.enabled), ("microHeight", &mut micro.height), ("microNormal", &mut micro.normal)] { if let Some(given) = boolp(params, key) { *value = given; diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index b8770541..278bfc04 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -211,6 +211,28 @@ fn generators_read_an_anchor_height_as_their_micro_height() { assert_eq!(back.doc.project, session.doc.project); } +#[test] +fn the_earlier_micro_keys_keep_an_earlier_model_generator_on_the_earlier_micro_detail() { + let mut session = session(); + let low = id(execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + let anchor = id(execute(&mut session, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); + let top = id(execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap(); + let earlier_micro = |session: &Session, generator: u64| match session.doc.project.effect(LayerId(generator)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => generator.earlier_micro(), + _ => None, + }; + + // `level` keeps the generator on the earlier model, where these keys read the anchor's height as before Micro Details + let generator = id(execute(&mut session, "effect.add.generator", &json!({"layer": top, "generator": "curvature", "level": 0.5})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 0.25})).unwrap(); + assert_eq!(earlier_micro(&session, generator), Some((LayerId(anchor), 0.25))); + + // A Micro Details control moves it onto the reference's controls and the anchor's curvature + execute(&mut session, "effect.set", &json!({"effect": generator, "microHeightIntensity": 1.0})).unwrap(); + assert_eq!(earlier_micro(&session, generator), None); +} + #[test] fn anchor_effects_added_through_instance_validate_against_source() { let mut session = session(); From eaf3ad1c2a630726654404144587475421df7084 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:07:40 +0000 Subject: [PATCH 144/153] Generators: every anchor height a render reads stays prepared, built lowest anchor first at the working size Anchor heights are kept while the texture set reads them (no 8-entry cap that dropped a ninth anchor to black), built in the anchors' draw order as their topmost reader reads them (an anchor's height can hold readers of lower anchors; layer ids no longer decide), rebuilt when the working atlas size changes, and prepared before the generator maps that read them. --- crates/compose/src/eval.rs | 135 +++++++++++++++++- .../src/micro_details/anchor_heights.rs | 5 + crates/compose/src/micro_details/mod.rs | 20 ++- 3 files changed, 149 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a4c50ea2..653e9f80 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2326,8 +2326,8 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La let mut order = Vec::new(); draw_order(inp, list, 0, around.into(), &mut order); let ids: Vec = order.iter().map(|(id, _)| *id).collect(); - prepare_curvature_sizes(inp, &ids); prepare_micro_anchors(inp); + prepare_curvature_sizes(inp, &ids); // Walk backwards to find the region each Compare needs below its position in the stack let mut below_margin = (0u32, false); @@ -2428,25 +2428,34 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { /// Build the height of every anchor point a visible generator's Micro Height reads, over the whole texture set, before tiles composite in parallel fn prepare_micro_anchors(inp: &EvaluationInputs) { let Ok(set) = inp.project.texture_set(inp.ts) else { return }; - let tree = inp.project.render_tree(&set.stack); - let visible = tree.iter().filter_map(|id| inp.project.layers.get(id)).filter(|layer| layer.visible); + let mut order = Vec::new(); + draw_order(inp, &set.stack, 0, ContentsOffset::NONE.into(), &mut order); + + // Each anchor is built as its topmost reader reads it: a reader the anchor was moved above reads the same heights let mut readers: Vec<(LayerId, LayerId)> = Vec::new(); - for layer in visible { + for layer in order.iter().filter_map(|(id, _)| inp.project.layers.get(id)).filter(|layer| layer.visible) { let effects = layer_mask(inp.project, layer.id).filter(|mask| mask.enabled).into_iter().flat_map(|mask| &mask.effects); for effect in effects.filter(|effect| effect.visible) { if let EffectKind::Generator(generator) = &effect.kind && let Some(micro) = generator.micro_in_use().filter(|micro| micro.height) && let Some(Source::Anchor { anchor, .. }) = µ.height_source - && !readers.iter().any(|(_, read)| read == anchor) { + readers.retain(|(_, read)| read != anchor); readers.push((layer.id, *anchor)); } } } + crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); if readers.is_empty() { return; } + // Lowest anchor first: an anchor's height holds the generators below it, which may read lower anchors + let drawn_at = |anchor: LayerId| { + let owner = inp.project.effect(anchor).map(|(owner, _)| owner); + order.iter().position(|(id, _)| Some(*id) == owner).unwrap_or(usize::MAX) + }; + readers.sort_by_key(|(_, anchor)| drawn_at(*anchor)); for (reader, anchor) in readers { let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; crate::micro_details::prepare_anchor_heights(inp, anchor, stack, || anchor_heights(inp, reader, anchor)); @@ -7243,6 +7252,122 @@ soft {soft:?}" } } + /// A 64 × 64 disc of raised height in an image named "disc", and a fixture with a flat baked curvature for micro details to read beside + fn micro_height_fixture() -> (Fixture, ImageStore) { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; + let disc = (0..64 * 64) + .map(|index| { + let (x, y) = ((index % 64) as f32 - 31.5, (index / 64) as f32 - 31.5); + if x * x + y * y < 100.0 { [1.0; 4] } else { [0.0, 0.0, 0.0, 1.0] } + }) + .collect(); + (fixture, [("disc".to_string(), Arc::new(ImageRes::new(64, 64, disc, false)))].into()) + } + + /// A Curvature generator whose Micro Height reads anchor point `anchor` + fn reading_micro_height(anchor: LayerId) -> Generator { + Generator { micro: MicroDetails::of_anchor(GeneratorKind::Curvature, anchor, 1.0).map(Box::new), ..Generator::new(GeneratorKind::Curvature) } + } + + /// A height fill of `source`, with an anchor point after it: the layer's id and the anchor's + fn anchored_height(fixture: &mut Fixture, id: LayerId, source: Source) -> (LayerId, LayerId) { + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, source); + let layer = fixture.project.insert_layer(0, Layer::new(id, "Height", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + (layer, content_fx(fixture, layer, EffectKind::Anchor)) + } + + fn base_color_reds(composite: &Composite) -> Vec { + (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() + } + + #[test] + fn every_anchor_height_a_render_reads_stays_prepared_however_many_it_reads() { + const OTHER_READERS: usize = 8; + let colors = |others_read: bool| { + let (mut fixture, images) = micro_height_fixture(); + let id = fixture.project.alloc_id(); + let (low, first) = anchored_height(&mut fixture, id, Source::image("disc")); + let others: Vec = (0..OTHER_READERS).map(|_| content_fx(&mut fixture, low, EffectKind::Anchor)).collect(); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(reading_micro_height(first)))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + + // Readers of eight more anchors on a layer of height only, drawn above + let id = fixture.project.alloc_id(); + let readers = + fixture.project.insert_layer(0, Layer::new(id, "Readers", LayerKind::Fill(Fill::default()), &[Channel::Height]), None, false).unwrap(); + let mut mask = Mask::new(MaskBackground::Black); + for (index, anchor) in others.iter().enumerate().filter(|_| others_read) { + mask.effects.push(Effect::new(LayerId(901 + index as u64), EffectKind::Generator(reading_micro_height(*anchor)))); + } + fixture.project.layer_mut(readers).unwrap().mask = Some(mask); + base_color_reds(&run_with_images(&fixture, None, &images)) + }; + + assert_eq!(colors(true), colors(false), "a ninth anchor read keeps the first one's height"); + } + + #[test] + fn an_anchor_height_holding_a_reader_of_a_lower_anchor_is_built_after_it_whatever_the_layer_ids() { + let colors = |top_id_first: bool| { + let (mut fixture, images) = micro_height_fixture(); + let early = fixture.project.alloc_id(); + let late = fixture.project.alloc_id(); + let (top_id, middle_id) = if top_id_first { (early, late) } else { (late, early) }; + let id = fixture.project.alloc_id(); + let (_, lower) = anchored_height(&mut fixture, id, Source::image("disc")); + + // The upper anchor records the middle layer's mask: a reader of the lower anchor + let middle = + fixture.project.insert_layer(0, Layer::new(middle_id, "Middle", LayerKind::Fill(Fill::default()), &[Channel::Height]), None, false).unwrap(); + let upper = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(reading_micro_height(lower)))); + mask.effects.push(Effect::new(upper, EffectKind::Anchor)); + fixture.project.layer_mut(middle).unwrap().mask = Some(mask); + + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let top = fixture.project.insert_layer(0, Layer::new(top_id, "Top", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(901), EffectKind::Generator(reading_micro_height(upper)))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + base_color_reds(&run_with_images(&fixture, None, &images)) + }; + + let (by_draw_order, against_it) = (colors(false), colors(true)); + let largest_change = by_draw_order.iter().zip(&against_it).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(largest_change < 1e-4, "{largest_change}"); + } + + #[test] + fn anchor_heights_are_built_again_at_another_working_size() { + let (mut fixture, images) = micro_height_fixture(); + let id = fixture.project.alloc_id(); + let (_, anchor) = anchored_height(&mut fixture, id, Source::image("disc")); + let stack = || { + StackKey::new(&fixture.project, &fixture.pixels, &fixture.baked, &images, 0, &fixture.project.texture_sets[0].stack) + .expect("the plane's stack has a key") + }; + let builds = std::cell::Cell::new(0); + let build = |size: (u32, u32)| { + builds.set(builds.get() + 1); + AnchorHeights::new(vec![0.0; (size.0 * size.1) as usize], size, fixture.project.texture_sets[0].block_scales()) + }; + let half = UvGBuffer::new(&fixture.mesh, 0, 32, 32); + let inputs_at = |gbuf| Inputs { gbuf, ..inputs(&fixture, &images, None) }; + + crate::micro_details::prepare_anchor_heights(&inputs_at(&fixture.gbuf), anchor, stack(), || build((64, 64))); + crate::micro_details::prepare_anchor_heights(&inputs_at(&fixture.gbuf), anchor, stack(), || build((64, 64))); + assert_eq!(builds.get(), 1, "the same stack and size reuse them"); + + crate::micro_details::prepare_anchor_heights(&inputs_at(&half), anchor, stack(), || build((32, 32))); + assert_eq!(builds.get(), 2, "a smaller working atlas builds them again"); + } + #[test] fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() { const SAVED_AMOUNT: f32 = 0.25; diff --git a/crates/compose/src/micro_details/anchor_heights.rs b/crates/compose/src/micro_details/anchor_heights.rs index 0a8b5c18..5fe6f76e 100644 --- a/crates/compose/src/micro_details/anchor_heights.rs +++ b/crates/compose/src/micro_details/anchor_heights.rs @@ -12,6 +12,11 @@ impl AnchorHeights { AnchorHeights { data, working_size, scales } } + /// The working atlas's size the heights were built at + pub(super) fn working_size(&self) -> (u32, u32) { + self.working_size + } + /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) pub(super) fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index ca5fa213..b6173ebd 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -73,14 +73,24 @@ fn baked_identity(inp: &Inputs) -> Option>> { [BakedMap::Curvature, BakedMap::AmbientOcclusion].iter().find_map(|map| inp.baked.maps.get(map)).map(Arc::downgrade) } -/// Keep anchor `anchor`'s heights for the micro details reading it, building them with `build` unless `stack` is the stack they were built for +/// Drop the anchor heights of `inp`'s texture set that its generators no longer read (`anchors` are the ones they read) and those of mesh maps gone: every height a render reads stays until it stops reading it +pub(crate) fn keep_anchor_heights(inp: &Inputs, anchors: &[LayerId]) { + let baked = baked_identity(inp); + let stale = |entry: &AnchorEntry| { + let this_set = baked.as_ref().is_some_and(|baked| entry.baked.ptr_eq(baked)) && entry.texture_set == inp.ts; + entry.baked.strong_count() == 0 || (this_set && !anchors.contains(&entry.anchor)) + }; + ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).retain(|entry| !stale(entry)); +} + +/// Keep anchor `anchor`'s heights for the micro details reading it, building them with `build` unless they were built for `stack` at this working size pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: StackKey, build: impl FnOnce() -> AnchorHeights) { let Some(baked) = baked_identity(inp) else { return }; let matches = |entry: &AnchorEntry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor; + let working_size = (inp.gbuf.width, inp.gbuf.height); { - let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|entry| entry.baked.strong_count() > 0); - if entries.iter().any(|entry| matches(entry) && entry.stack == stack) { + let entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if entries.iter().any(|entry| matches(entry) && entry.stack == stack && entry.heights.working_size() == working_size) { return; } } @@ -99,8 +109,6 @@ pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: Stack let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); entries.retain(|entry| !matches(entry)); entries.push(AnchorEntry { baked, texture_set: inp.ts, anchor, stack, heights }); - let excess = entries.len().saturating_sub(CACHE_ENTRIES); - entries.drain(..excess); } /// The heights prepared for anchor `anchor` (None before they are) From 44b1bc0273bf68a6d10e070bf77cfa1a80ed8d2d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:12:15 +0000 Subject: [PATCH 145/153] Generators: whole-map fields keyed by a coverage hash taken once per evaluation and by each mesh map's bake size The field cache read every 31st texel's triangle on each lookup (once per tile plan) and could miss an edit between samples; the evaluation now hashes every texel once, on first use. A mesh map's bake size joins its key (one allocation read as another layout), and a hit moves to the most recently used end. --- crates/compose/src/dripping_rust.rs | 5 +- crates/compose/src/eval.rs | 79 +++++++++++++++++++- crates/compose/src/eval/evaluation_inputs.rs | 7 ++ crates/compose/src/field_cache.rs | 44 +++++++++-- crates/compose/src/field_cache_key.rs | 13 ++-- crates/compose/src/generator_maps.rs | 12 +-- crates/compose/src/uv_border_distance.rs | 4 +- crates/compose/src/uv_islands.rs | 8 +- 8 files changed, 140 insertions(+), 32 deletions(-) diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index 4b5f84d5..c098fe29 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -36,8 +36,7 @@ const MIN_COVERAGE: f32 = 1e-3; static CACHE: FieldCache = FieldCache::new(); /// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) -pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) -> Arc> { - let occlusion = inp.baked.maps.get(&BakedMap::AmbientOcclusion); +pub(crate) fn rust_field(inp: &Inputs, coverage: u64, rust: &DrippingRustParameters, seed: u32) -> Arc> { let settings = vec![ rust.spreading_smoothness.to_bits(), rust.drips_intensity.to_bits(), @@ -46,7 +45,7 @@ pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) u32::from(rust.axis), seed, ]; - CACHE.get_or_build(inp, &occlusion.into_iter().collect::>(), settings, |block| build(inp, rust, seed, block)) + CACHE.get_or_build(inp, coverage, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block)) } /// The value at a working texel: the rust spread and contrasted diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 653e9f80..582f5bbf 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2419,7 +2419,7 @@ fn compares_this_layer(kind: &EffectKind) -> bool { } /// 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]) { +fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) { 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); @@ -2506,7 +2506,7 @@ fn wear_parameters(generator: &Generator) -> Option { } /// 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) { +fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(generator) = &effect.kind { @@ -2516,7 +2516,7 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator( None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; let maps = match &effect.kind { - EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator)), + EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), || inp.coverage_identity()), _ => GeneratorMaps::default(), }; let (depth, covers_all, projection) = match &effect.kind { @@ -7368,6 +7368,77 @@ soft {soft:?}" assert_eq!(builds.get(), 2, "a smaller working atlas builds them again"); } + /// Builds a field cache made: the counter goes up with each build + fn counted_build(builds: &std::cell::Cell) -> impl FnOnce((u32, u32)) -> Vec + '_ { + move |_| { + builds.set(builds.get() + 1); + vec![0.0; 4] + } + } + + #[test] + fn a_whole_map_field_is_built_again_when_its_mesh_map_is_read_at_another_bake_size() { + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let mut fixture = fixture(); + let occlusion = Arc::new(vec![0.5; 16]); + let images = ImageStore::default(); + for resolution in [4, 4, 8] { + fixture.baked = BakedMaps { resolution, maps: [(BakedMap::AmbientOcclusion, occlusion.clone())].into() }; + let inputs = inputs(&fixture, &images, None); + cache.get_or_build( + &inputs, + crate::field_cache::coverage_identity(&fixture.gbuf), + &[BakedMap::AmbientOcclusion], + Vec::new(), + counted_build(&builds), + ); + } + + assert_eq!(builds.get(), 2, "4 × 4 reuses its field; the same map read as 8 × 2 builds another"); + } + + #[test] + fn a_whole_map_field_is_built_again_after_any_texel_of_its_coverage_changes() { + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let mut fixture = fixture(); + let images = ImageStore::default(); + let build_on = |fixture: &Fixture| { + let inputs = inputs(fixture, &images, None); + cache.get_or_build(&inputs, crate::field_cache::coverage_identity(&fixture.gbuf), &[], Vec::new(), counted_build(&builds)); + }; + build_on(&fixture); + build_on(&fixture); + + // The second texel, in place: the same allocation, one triangle different + fixture.gbuf.tri[1] = if fixture.gbuf.tri[1] == NO_TRI { 0 } else { NO_TRI }; + build_on(&fixture); + + assert_eq!(builds.get(), 2); + } + + #[test] + fn a_whole_map_field_read_again_outlives_fields_built_before_it() { + const FIELDS_KEPT: u32 = 8; + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let fixture = fixture(); + let images = ImageStore::default(); + let inputs = inputs(&fixture, &images, None); + let coverage = crate::field_cache::coverage_identity(&fixture.gbuf); + let field = |settings: u32| { + cache.get_or_build(&inputs, coverage, &[], vec![settings], counted_build(&builds)); + }; + (0..FIELDS_KEPT).for_each(field); + field(0); + field(FIELDS_KEPT); + let built = builds.get(); + field(0); + + assert_eq!(builds.get(), built, "the field read again stays when a newer one pushes the oldest out"); + } + #[test] fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() { const SAVED_AMOUNT: f32 = 0.25; diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs index 2f9027fe..dbb8f392 100644 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -22,6 +22,7 @@ pub(super) struct EvaluationInputs<'a> { instance_draws: OnceLock>, depth_maps: Mutex>, gradients: Mutex>>, + coverage: OnceLock, } impl<'a> EvaluationInputs<'a> { @@ -33,9 +34,15 @@ impl<'a> EvaluationInputs<'a> { instance_draws: OnceLock::new(), depth_maps: Mutex::new(Vec::new()), gradients: Mutex::default(), + coverage: OnceLock::new(), } } + /// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`]) + pub(super) fn coverage_identity(&self) -> u64 { + *self.coverage.get_or_init(|| crate::field_cache::coverage_identity(self.inputs.gbuf)) + } + pub(super) fn environment(&self) -> EnvironmentSh { if let Some(environment) = self.environment.get() { return *environment; diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 1458cb3f..51581173 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -1,5 +1,9 @@ use std::sync::{Arc, Mutex}; +use rayon::prelude::*; +use texturecraft_core::BakedMap; +use texturecraft_geom::UvGBuffer; + use crate::eval::Inputs; use crate::field_cache_key::FieldCacheKey; use crate::working_field::working_block; @@ -8,8 +12,19 @@ use crate::working_field::working_block; const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; -/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile -const FINGERPRINT_STRIDE: usize = 31; +/// Texels hashed together before their hashes are combined, so the coverage hashes in parallel +const COVERAGE_CHUNK_TEXELS: usize = 1 << 16; + +/// The 64-bit FNV prime, spreading each step of the coverage hash over every bit +const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// The identity of `gbuf`'s coverage: its size and the triangle under every texel, hashed (read once per evaluation, as it reads every texel) +pub(crate) fn coverage_identity(gbuf: &UvGBuffer) -> u64 { + let chunk_hash = + |chunk: &[u32]| chunk.iter().fold(chunk.len() as u64, |hash, triangle| (hash.rotate_left(5) ^ u64::from(*triangle)).wrapping_mul(FNV_PRIME)); + let chunks: Vec = gbuf.tri.par_chunks(COVERAGE_CHUNK_TEXELS).map(chunk_hash).collect(); + chunks.iter().fold((u64::from(gbuf.width) << 32) | u64::from(gbuf.height), |hash, chunk| (hash.rotate_left(7) ^ chunk).wrapping_mul(FNV_PRIME)) +} /// Built fields by what they were built from, most recently used last pub(crate) struct FieldCache { @@ -21,26 +36,39 @@ impl FieldCache { FieldCache { entries: Mutex::new(Vec::new()) } } - /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work - pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { + /// The field of `inp`'s working layout (its coverage: [`coverage_identity`]) reading the baked `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work + pub(crate) fn get_or_build( + &self, + inp: &Inputs, + coverage: u64, + maps: &[BakedMap], + settings: Vec, + build: impl FnOnce((u32, u32)) -> Vec, + ) -> Arc> { let gbuf = inp.gbuf; let block = working_block(inp); + let read = maps.iter().filter_map(|map| inp.baked.maps.get(map).map(|data| (Arc::downgrade(data), (inp.baked.resolution, inp.baked.height(*map))))); let key = FieldCacheKey { layout: gbuf.tri.as_ptr() as usize, size: (gbuf.width, gbuf.height), - fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), + coverage, block, scales: inp.block_scales.clone(), positions: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), uvs: (inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), - maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), + maps: read.collect(), settings, }; + // A hit moves to the most recently used end let cached = { let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); - entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) + entries.retain(|(key, _)| key.maps.iter().all(|(map, _)| map.strong_count() > 0)); + let hit = entries.iter().position(|(cached, _)| *cached == key).map(|index| entries.remove(index)); + hit.map(|(cached, field)| { + entries.push((cached, field.clone())); + field + }) }; if let Some(field) = cached { return field; diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs index d29d80f5..1010ac97 100644 --- a/crates/compose/src/field_cache_key.rs +++ b/crates/compose/src/field_cache_key.rs @@ -2,28 +2,31 @@ use std::sync::Weak; use texturecraft_core::BlockScales; -/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits +/// What a field was built from: the working layout (the g-buffer's address, size, coverage, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits #[derive(Clone)] pub(crate) struct FieldCacheKey { pub(crate) layout: usize, pub(crate) size: (u32, u32), - pub(crate) fingerprint: u64, + /// Every texel's triangle, hashed: [`crate::field_cache::coverage_identity`] + pub(crate) coverage: u64, pub(crate) block: (u32, u32), pub(crate) scales: BlockScales, /// The mesh's positions and UVs, each by address and length: a UV edit changes island fields pub(crate) positions: (usize, usize), pub(crate) uvs: (usize, usize), - pub(crate) maps: Vec>>, + /// The mesh maps it samples, each with the size it was baked at: one allocation read as another layout reads other texels + pub(crate) maps: Vec<(Weak>, (u32, u32))>, pub(crate) settings: Vec, } impl PartialEq for FieldCacheKey { fn eq(&self, other: &FieldCacheKey) -> bool { - let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); + let same_maps = self.maps.len() == other.maps.len() + && self.maps.iter().zip(&other.maps).all(|((a, a_size), (b, b_size))| a.strong_count() > 0 && a.ptr_eq(b) && a_size == b_size); same_maps && self.layout == other.layout && self.size == other.size - && self.fingerprint == other.fingerprint + && self.coverage == other.coverage && self.block == other.block && self.scales == other.scales && self.positions == other.positions diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 151ae176..503a32c9 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -27,8 +27,8 @@ pub(crate) struct GeneratorMaps { } impl GeneratorMaps { - /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size) - pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps { + /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `coverage` gives the working layout's coverage identity for whole-map fields + pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl Fn() -> u64) -> GeneratorMaps { let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind)); let micro_curvature = micro.as_ref().filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); @@ -39,10 +39,10 @@ impl GeneratorMaps { }; let controls = generator.kind_controls(); let field = match &controls { - Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), - Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), - Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)), - Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, checker, generator.seed)), + Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, coverage(), border)), + Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, coverage(), rust, generator.seed)), + Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, coverage(), random, generator.seed)), + Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, coverage(), checker, generator.seed)), _ => None, }; GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index b324e4ac..9cced087 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -18,8 +18,8 @@ const SMOOTHNESS_SIGMA_2K: f32 = 45.0; static CACHE: FieldCache = FieldCache::new(); /// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) -pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) -> Arc> { - CACHE.get_or_build(inp, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) +pub(crate) fn border_gradient(inp: &Inputs, coverage: u64, border: &BorderDistanceParameters) -> Arc> { + CACHE.get_or_build(inp, coverage, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) } /// The value at a working texel: the gradient balanced, contrasted and inverted diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 6ce27082..d5233984 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -17,12 +17,12 @@ use crate::working_field::REFERENCE_TILE_TEXELS; static CACHE: FieldCache = FieldCache::new(); /// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) -pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { +pub(crate) fn random_color_field(inp: &Inputs, coverage: u64, random: &UvRandomColorParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(random.custom_gradient)]; settings.push(random.used_colors().len() as u32); settings.extend(random.used_colors().iter().flat_map(|color| color.map(f32::to_bits))); settings.extend(random.positions.iter().map(|position| position.to_bits())); - CACHE.get_or_build(inp, &[], settings, |_| { + CACHE.get_or_build(inp, coverage, &[], settings, |_| { let island_values = island_values(inp, |island| random_gray(random, seed, island)); let gbuf = inp.gbuf; gbuf.tri.par_iter().map(|triangle| island_values.get(triangle).copied().unwrap_or(0.0)).collect() @@ -73,10 +73,10 @@ const RANDOM_SATURATION: std::ops::RangeInclusive = 0.06..=0.57; const RANDOM_VALUE: std::ops::RangeInclusive = 0.42..=0.80; /// UV Checker at every working texel of `inp`: the gray of its color, the mean of the sRGB-encoded channels as the reference reads it (0 outside the islands) -pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u32) -> Arc> { +pub(crate) fn checker_field(inp: &Inputs, coverage: u64, checker: &UvCheckerParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(checker.random_colors), checker.grid_tile, checker.grid_opacity.to_bits(), checker.border_width.to_bits()]; settings.extend(checker.checker_color.iter().chain(&checker.border_color).map(|value| value.to_bits())); - CACHE.get_or_build(inp, &[], settings, |block| { + CACHE.get_or_build(inp, coverage, &[], settings, |block| { let gbuf = inp.gbuf; let (width, height) = (gbuf.width, gbuf.height); let island_colors = if checker.random_colors { island_colors(inp, seed) } else { HashMap::new() }; From 30dcceb3ef7328ba1d99b657770e5802e04b4a1c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:16:06 +0000 Subject: [PATCH 146/153] Generators: mask comparisons in tests reject missing texels; the micro blur's kernel is sampled once per pass bake_resolution checks the mask's length again (the zip let a short or empty mask pass), as do the texture and section test helpers. --- crates/compose/src/micro_details/mod.rs | 25 ++++++++++++++-------- crates/compose/tests/generator_sections.rs | 1 + crates/compose/tests/generator_texture.rs | 1 + crates/engine/tests/it/bake_resolution.rs | 1 + 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index b6173ebd..4ee72fd3 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -267,10 +267,12 @@ fn gaussian_wrapped(values: &[f32], (width, height): (u32, u32), sigma: f32) -> fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { let length = length.max(1); let mut out = vec![0.0; values.len()]; - out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| { - if sigma < BOX_BLUR_MIN_SIGMA { - kernel_blur(line, out, sigma); - } else { + + // Every line reads the same sampled kernel + let kernel = (sigma < BOX_BLUR_MIN_SIGMA).then(|| gaussian_kernel(sigma)); + out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| match &kernel { + Some(kernel) => kernel_blur(line, out, kernel), + None => { // Three box passes of radius r spread a value with variance r(r + 1) let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize; let mut current = line.to_vec(); @@ -283,18 +285,23 @@ fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { out } -/// `line` blurred into `out` by a sampled gaussian of `sigma`, wrapping around -fn kernel_blur(line: &[f32], out: &mut [f32], sigma: f32) { +/// A gaussian of `sigma` sampled at whole texels each side of its centre, its weights summing to 1 +fn gaussian_kernel(sigma: f32) -> Vec { let reach = (KERNEL_REACH_SIGMAS * sigma).ceil().max(1.0) as i64; let weights: Vec = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect(); let total: f32 = weights.iter().sum(); + weights.into_iter().map(|weight| weight / total).collect() +} + +/// `line` blurred into `out` by `kernel` (centred, as [`gaussian_kernel`] samples it), wrapping around +fn kernel_blur(line: &[f32], out: &mut [f32], kernel: &[f32]) { + let reach = (kernel.len() / 2) as i64; let length = line.len().max(1) as i64; for (index, value) in out.iter_mut().enumerate() { - let sum: f32 = (-reach..=reach) - .zip(&weights) + *value = (-reach..=reach) + .zip(kernel) .map(|(offset, weight)| line.get((index as i64 + offset).rem_euclid(length) as usize).copied().unwrap_or(0.0) * weight) .sum(); - *value = sum / total; } } diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs index 0724f4e6..799674d6 100644 --- a/crates/compose/tests/generator_sections.rs +++ b/crates/compose/tests/generator_sections.rs @@ -103,6 +103,7 @@ fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator { } fn assert_close(actual: &[f32], expected: &[f32], what: &str) { + assert_eq!(actual.len(), expected.len(), "{what}: texels read"); for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); } diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs index 3dcc0d46..d1cc4ccf 100644 --- a/crates/compose/tests/generator_texture.rs +++ b/crates/compose/tests/generator_texture.rs @@ -103,6 +103,7 @@ fn replacing() -> TextureLayer { } fn assert_all(actual: &[f32], expected: f32, what: &str) { + assert!(!actual.is_empty(), "{what}: no texels read"); for (index, actual) in actual.iter().enumerate() { assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); } diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index b2c88885..f690d2ae 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -128,6 +128,7 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap(); let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap(); let expected = [240.0 / 255.0, 20.0 / 255.0]; + assert_eq!(mask.len(), expected.len(), "one value per requested texel"); assert!( mask.iter().zip(expected).all(|(value, expected)| (value - expected).abs() < 0.001), "generators sample the whole bake through the working layout: {mask:?}" From ff298779c2488163e5044fdbbc30f9b655d419fc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:16:06 +0000 Subject: [PATCH 147/153] Generators panel: Restore defaults keeps the Resolution band, the input card offers anchors below the owner, a swapped kind drops its point pick, size columns step with the arrow keys - Restore defaults resets the Parameters only, as its band says (it was disabled when only the resolution differed, yet reset it otherwise) - an inherited generator's slots list the anchors below both the owner and the instance, as the Properties picker does (others were refused) - a pick armed on a generator swapped to a kind without that point is dropped - a focused size column takes the arrow keys, each press one step - the picker snapshot hovers the tile by its ListBoxOption role --- crates/ui-egui/src/generator_input_card.rs | 4 +- crates/ui-egui/src/generator_params.rs | 11 +-- crates/ui-egui/src/generator_point_pick.rs | 17 ++++- .../src/property_sheet/size_columns.rs | 20 +++++ crates/ui-egui/tests/it/generator_panel.rs | 75 ++++++++++++++++++- crates/ui-egui/tests/it/generator_picker.rs | 4 +- 6 files changed, 114 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/generator_input_card.rs b/crates/ui-egui/src/generator_input_card.rs index b63012ce..0f25860c 100644 --- a/crates/ui-egui/src/generator_input_card.rs +++ b/crates/ui-egui/src/generator_input_card.rs @@ -5,7 +5,7 @@ use serde_json::json; use texturecraft_engine::core::{LayerId, Source}; use crate::TextureCraftApp; -use crate::dock::{anchor_label, anchors_below, image_drop, mesh_map_color}; +use crate::dock::{anchor_label, image_drop, mesh_map_color, project_effect_anchors_below}; use crate::fill_material_panel::{source_choice, source_tabs}; use crate::generator_input_slot::GeneratorInputSlot; use crate::i18n::{baked_map_label, tr, trf}; @@ -93,7 +93,7 @@ pub(crate) fn input_card( } let current = source.map(|source| source_choice(&app.session, source)); let tabs = || { - let anchors = if slot.takes_anchor() { anchors_below(&app.session.doc.project, layer) } else { Vec::new() }; + let anchors = if slot.takes_anchor() { project_effect_anchors_below(&app.session.doc.project, layer, LayerId(id)) } else { Vec::new() }; let mut tabs = source_tabs(&app.session, &anchors, tokens.button, false); // A generator's inputs read images, values and anchor points, never a procedural diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs index 879efecc..f056d8ba 100644 --- a/crates/ui-egui/src/generator_params.rs +++ b/crates/ui-egui/src/generator_params.rs @@ -169,18 +169,11 @@ pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { params } -/// The `effect.set` params that put generator effect `id` back to the defaults of its kind; its images stay in their slots +/// The `effect.set` params that put generator effect `id`'s parameters back to the defaults of its kind; its images stay in their slots and its resolution, in a band of its own, stays as set pub(crate) fn defaults_of(id: u64, generator: &Generator) -> Value { let kind = generator.kind; let defaults = Generator::new(kind); - let params = json!({ - "effect": id, - "seed": defaults.seed, - "invert": defaults.invert, - "resolution": format!("{:?}", defaults.resolution.mode), - "customResolution": defaults.resolution.custom, - "resolutionFactor": defaults.resolution.factor, - }); + let params = json!({"effect": id, "seed": defaults.seed, "invert": defaults.invert}); if let Some(controls) = &defaults.controls { return merged(params, kind_params(controls)); } diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs index 4b876e78..293f4e7b 100644 --- a/crates/ui-egui/src/generator_point_pick.rs +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -1,6 +1,6 @@ //! Picking a 3D generator's point on the mesh: its crosshair button arms it, the next click in the 3D view sets the point, Esc or the button again cancels -use texturecraft_engine::core::LayerId; +use texturecraft_engine::core::{EffectKind, GeneratorKind, LayerId}; use texturecraft_engine::{Session, StackTarget}; /// Which point of which generator effect the next click in the 3D view sets @@ -12,6 +12,13 @@ pub(crate) struct PointPick { pub(crate) point: &'static str, } +impl PointPick { + /// Whether a `kind` generator has the point this pick sets + fn belongs_to(&self, kind: GeneratorKind) -> bool { + matches!((kind, self.point), (GeneratorKind::ThreeDDistance, "distance") | (GeneratorKind::ThreeDLinearGradient, "start" | "end")) + } +} + /// Where the armed pick is kept: a transient UI mode, like the depth of field's focus pick fn pick_id() -> egui::Id { egui::Id::unique("tc_generator_point_pick") @@ -28,10 +35,14 @@ pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { set(ctx, next); } -/// The armed pick while its effect is still the selected one; a pick whose effect was deselected or deleted is dropped +/// The armed pick while its effect is still the selected one and still has its point; a pick whose effect was deselected, deleted or swapped to a kind without that point is dropped pub(crate) fn armed_on(ctx: &egui::Context, session: &Session) -> Option { let pick = armed(ctx)?; - if session.target == StackTarget::Effect(LayerId(pick.effect)) { + let has_point = match session.doc.project.effect(LayerId(pick.effect)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => pick.belongs_to(generator.kind), + _ => false, + }; + if has_point && session.target == StackTarget::Effect(LayerId(pick.effect)) { return Some(pick); } set(ctx, None); diff --git a/crates/ui-egui/src/property_sheet/size_columns.rs b/crates/ui-egui/src/property_sheet/size_columns.rs index ec6dd9d7..2d0fbeb5 100644 --- a/crates/ui-egui/src/property_sheet/size_columns.rs +++ b/crates/ui-egui/src/property_sheet/size_columns.rs @@ -18,6 +18,9 @@ const FACE_AIR: f32 = 2.0; /// Width of a column's track and fill const COLUMN_TRACK_WIDTH: f32 = 2.0; +/// How far one arrow key press moves a focused column: a twentieth of its track +const KEY_STEP: f32 = 0.05; + impl PropertySheet<'_> { /// One 0..1 vertical slider per name in `values`, side by side across the panel pub(crate) fn size_columns(&mut self, names: &[&str], values: &mut [f32]) -> SizeColumnsResponse { @@ -43,6 +46,23 @@ impl PropertySheet<'_> { moved = true; } } + + // A focused column keeps the arrow keys: up and right raise it, down and left lower it, each press its own step + if hit.has_focus() { + self.ui.memory_mut(|memory| { + memory.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let presses = self.ui.input(|input| { + let raised = input.num_presses(egui::Key::ArrowUp) + input.num_presses(egui::Key::ArrowRight); + let lowered = input.num_presses(egui::Key::ArrowDown) + input.num_presses(egui::Key::ArrowLeft); + raised as f32 - lowered as f32 + }); + let stepped = (*value + presses * KEY_STEP).clamp(0.0, 1.0); + if stepped != *value { + *value = stepped; + moved = true; + } + } if let Some(merge) = crate::widgets::press_edit(self.ui, id, moved) { response.edit = Some((index, merge)); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 931f469a..3b5c8c2d 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -102,7 +102,10 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { click_live(&mut harness, Role::Button, "Restore defaults"); - assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); + // Resolution has its own band: restoring the parameters leaves it as set + let restored = generator(&harness, effect); + assert_eq!(restored.resolution.factor, -2); + assert_eq!(Generator { resolution: Generator::new(GeneratorKind::Curvature).resolution, ..restored }, Generator::new(GeneratorKind::Curvature)); } #[test] @@ -250,6 +253,29 @@ fn a_curvature_size_column_sets_its_size_alone_in_one_step() { assert_eq!(harness.state().session.history_labels().len(), history + 1); } +#[test] +fn a_focused_curvature_size_column_steps_with_the_arrow_keys() { + let (mut harness, effect) = harness(false); + let last = generator(&harness, effect).detail.unwrap().weights.len() - 1; + harness.get_by_role_and_label(Role::Slider, "Huge").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Slider, "Huge").focus(); + harness.run_steps(2); + let before = generator(&harness, effect).detail.unwrap().weights; + let history = harness.state().session.history_labels().len(); + + harness.key_press(egui::Key::ArrowDown); + harness.run_steps(3); + let lowered = generator(&harness, effect).detail.unwrap().weights; + harness.key_press(egui::Key::ArrowUp); + harness.run_steps(3); + + assert!(lowered[last] < before[last], "down lowered Huge: {} -> {}", before[last], lowered[last]); + assert_eq!(lowered[..last], before[..last], "the other sizes kept theirs"); + assert!((generator(&harness, effect).detail.unwrap().weights[last] - before[last]).abs() < 1e-6, "up raised it back"); + assert_eq!(harness.state().session.history_labels().len(), history + 2, "each press is a step"); +} + #[test] fn restore_defaults_puts_a_light_back_on_its_defaults() { let (mut harness, effect) = harness_with(false, json!({"generator": "direction", "lightHorizontal": 10.0, "highlightLevel": 0.7, "invert": true})); @@ -279,6 +305,45 @@ fn micro_details_show_their_settings_once_switched_on() { assert!(slot_reading(&harness, "Empty").rect().is_positive(), "Micro Height on: its slot, empty"); } +/// An instance showing its source's generator offers its Micro Height only the anchor points below both: one between the source and the instance is refused by the source's mask +#[test] +fn an_inherited_generators_micro_height_lists_only_anchors_below_its_owner() { + const BELOW: &str = "Height below"; + const BETWEEN: &str = "Height between"; + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + let low = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "content", "name": BELOW})).unwrap(); + let source = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.black", &json!({"layer": source})).unwrap(); + let added = execute(&mut session, "effect.add.generator", &json!({"layer": source, "generator": "dirt", "microHeight": true})).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); + let between = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "effect.add.anchor", &json!({"layer": between, "target": "content", "name": BETWEEN})).unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": instance})).unwrap(); + session.target = texturecraft_engine::StackTarget::Effect(effect); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + + harness.get_by_role_and_label(Role::Button, "Micro Details").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Micro Details").click(); + harness.run_steps(3); + slot_reading(&harness, "Empty").scroll_to_me(); + harness.run_steps(3); + slot_reading(&harness, "Empty").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Tab, "Anchor points").click(); + harness.run_steps(3); + + let offered: Vec<_> = harness.get_all_by_role(Role::ListBoxOption).filter_map(|row| row.accesskit_node().label()).collect(); + assert!(offered.iter().any(|label| label.contains(BELOW)), "the anchor below the source is offered: {offered:?}"); + assert!(!offered.iter().any(|label| label.contains(BETWEEN)), "the anchor above the source is excluded: {offered:?}"); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -438,6 +503,14 @@ fn a_point_pick_waits_for_the_view_until_escape() { harness.run_steps(3); assert!(!is_on(&harness, Role::Button, end), "a pick left behind is dropped"); + + // A kind without the point drops it too: swapped back, it waits no more + click_live(&mut harness, Role::Button, end); + for kind in ["position", "3dLinearGradient"] { + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "generator": kind})).unwrap(); + harness.run_steps(3); + } + assert!(!is_on(&harness, Role::Button, end), "a pick on a swapped kind is dropped"); } #[test] diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs index b300a7e2..d99f1006 100644 --- a/crates/ui-egui/tests/it/generator_picker.rs +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -95,8 +95,8 @@ fn generator_picker_snapshots() { harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap(); } - // The picker's tile is the button named Dirt - harness.get_by_role_and_label(Role::Button, "Dirt").hover(); + // The picker's tile is the list option named Dirt + harness.get_by_role_and_label(Role::ListBoxOption, "Dirt").hover(); for _ in 0..10 { harness.run_steps(5); std::thread::sleep(std::time::Duration::from_millis(300)); From e7fa9730f2b075c4dd124cd77affe44e8b7cda7d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:26:15 +0000 Subject: [PATCH 148/153] Generators: drips take no rust from lower on the axis, histogram ends hold at a hard step, Use Texture's X projection scales about the centre - a drip ray past a ridge no longer carries rust up from texels lower on the drip axis (the fitted captures move closer with the check) - position 0 stays all black and 1 all white at contrast 1, as the scan's ends are documented (3D Distance at offset 0, Dripping Rust spread 0) - Use Texture's triplanar X projection mirrors U about the bounds' centre like the scale it uses; custom grunge keeps its fitted placement (identical at whole scales, which every capture used) --- crates/compose/src/dripping_rust.rs | 55 +++++++++++++++++++++++++++- crates/compose/src/histogram_scan.rs | 14 +++++++ crates/compose/src/slot_placement.rs | 2 + crates/compose/src/texture_layer.rs | 18 ++++++++- crates/compose/src/wear.rs | 4 +- 5 files changed, 88 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index c098fe29..43e42858 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -144,7 +144,11 @@ fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, hei let along = step as f32 / samples as f32; let distance = reach * along; let (sample_x, sample_y) = (x as f32 + distance * uphill.0 / length, y as f32 + distance * uphill.1 / length); - match field_at(sample_x.round() as i64, sample_y.round() as i64) { + let (sample_x, sample_y) = (sample_x.round() as i64, sample_y.round() as i64); + + // Rust drips down: a tap the ray reaches past a ridge, lower on the axis, gives none + let above = axis_at(sample_x, sample_y).is_some_and(|axis| axis >= axis_here); + match field_at(sample_x, sample_y).filter(|_| above) { Some(value) => most.max(value * (1.0 - DRIP_FADE * along.powf(DRIP_FADE_POWER))), None => most, } @@ -152,3 +156,52 @@ fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, hei }) .collect() } + +#[cfg(test)] +mod tests { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{UvGBuffer, primitives}; + + use super::*; + use crate::{BakedMaps, PixelStore}; + + const RES: u32 = 256; + + #[test] + fn a_drip_takes_no_rust_from_past_a_ridge_lower_on_the_axis() { + // A strip rising gently to a ridge at its middle, then falling steeply + let mut mesh = primitives::plane(2.0, 64); + for position in &mut mesh.positions { + position.y = if position.z <= 0.0 { 1.0 + position.z } else { 1.0 - 8.0 * position.z }; + } + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "strip"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + // Rust only on the steep side, all lower than the gentle side's texel just below the ridge + let rusted = |surface: &texturecraft_geom::Surface| surface.pos.z > 0.01; + let field: Vec = (0..RES * RES).map(|texel| gbuf.surface(&mesh, texel as usize).filter(rusted).map_or(0.0, |_| 1.0)).collect(); + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: DrippingRustParameters::MAX_SAMPLES, axis: 1, ..Default::default() }; + let dripped = drips(&inputs, &rust, &field, (RES, RES), &|_, _| RES as f32); + + let below_ridge = (0..RES * RES) + .find(|texel| { + gbuf.surface(&mesh, *texel as usize).is_some_and(|surface| (surface.pos.z + 0.04).abs() < 1.0 / RES as f32 && surface.pos.x.abs() < 0.1) + }) + .expect("a texel just below the ridge"); + assert_eq!(dripped[below_ridge as usize], 0.0); + } +} diff --git a/crates/compose/src/histogram_scan.rs b/crates/compose/src/histogram_scan.rs index ca9c851c..8c474d7e 100644 --- a/crates/compose/src/histogram_scan.rs +++ b/crates/compose/src/histogram_scan.rs @@ -2,6 +2,14 @@ /// `value` scanned at `position` (0 all black, 1 all white) over a ramp `1 − contrast` wide; contrast 1 is a hard step pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 { + // The ends hold at a hard step too, where the ramp has no width to reach them + if position <= 0.0 { + return 0.0; + } + if position >= 1.0 { + return 1.0; + } + let width = 1.0 - contrast.clamp(0.0, 1.0); // The ramp's low end runs from 1 at position 0 to −width at position 1, so the ends are wholly black or white let low = (1.0 - position.clamp(0.0, 1.0)) * (1.0 + width) - width; @@ -23,6 +31,12 @@ mod tests { } } + #[test] + fn the_ends_of_the_position_hold_at_a_hard_step() { + assert_eq!(histogram_scan(1.0, 0.0, 1.0), 0.0, "position 0 is all black, even for white"); + assert_eq!(histogram_scan(0.0, 1.0, 1.0), 1.0, "position 1 is all white, even for black"); + } + #[test] fn the_middle_position_keeps_mid_gray_and_contrast_narrows_around_it() { assert!((histogram_scan(0.5, 0.5, 0.5) - 0.5).abs() < 1e-6); diff --git a/crates/compose/src/slot_placement.rs b/crates/compose/src/slot_placement.rs index 69af657b..d5c18cde 100644 --- a/crates/compose/src/slot_placement.rs +++ b/crates/compose/src/slot_placement.rs @@ -4,4 +4,6 @@ pub(crate) struct SlotPlacement { pub offset: f32, /// How sharply the three projections meet, or None to read in UV pub triplanar_contrast: Option, + /// The X projection's mirrored U turns about the bounds' centre, which a centred scale keeps fixed (Use Texture); else about 0, as custom grunge was fitted + pub mirrored_about_centre: bool, } diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs index 02cf6769..4d121f42 100644 --- a/crates/compose/src/texture_layer.rs +++ b/crates/compose/src/texture_layer.rs @@ -13,7 +13,12 @@ const MIN_NORMAL_COMPONENT: f32 = 1e-6; /// The texture is scaled about the centre of the UV square (or of the mesh's bounds) pub(crate) fn texture_placement(texture: &TextureLayer) -> SlotPlacement { - SlotPlacement { scale: texture.scale, offset: 0.5 * (1.0 - texture.scale), triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast) } + SlotPlacement { + scale: texture.scale, + offset: 0.5 * (1.0 - texture.scale), + triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast), + mirrored_about_centre: true, + } } /// Where a slot is read in UV @@ -24,7 +29,8 @@ pub(crate) fn uv_coordinates(placement: &SlotPlacement, uv: Vec2) -> Vec2 { /// Where a slot is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1) pub(crate) fn triplanar_coordinates(placement: &SlotPlacement, position: Vec3) -> [Vec2; 3] { let placed = |u: f32, v: f32| Vec2::new(u, v) * placement.scale + Vec2::splat(placement.offset); - [placed(-position.z, position.y), placed(position.x, position.z), placed(position.x, position.y)] + let mirrored_z = if placement.mirrored_about_centre { 1.0 - position.z } else { -position.z }; + [placed(mirrored_z, position.y), placed(position.x, position.z), placed(position.x, position.y)] } /// How much each projection (facing X, Y and Z) counts for a surface facing `normal` at triplanar `contrast`, summing to 1 @@ -153,4 +159,12 @@ mod tests { assert_eq!(uv_coordinates(&placement, Vec2::splat(0.5)), Vec2::splat(0.5)); assert_eq!(uv_coordinates(&placement, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); } + + #[test] + fn every_triplanar_projection_is_scaled_about_the_centre_of_the_bounds() { + let placement = texture_placement(&TextureLayer { scale: 1.5, triplanar: true, ..texture() }); + for (axis, at) in triplanar_coordinates(&placement, Vec3::splat(0.5)).into_iter().enumerate() { + assert!((at - Vec2::splat(0.5)).abs().max_element() < 1e-6, "projection {axis} reads {at} at the centre"); + } + } } diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 14903b8f..3eb2d7d9 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -65,9 +65,9 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor /// Where a custom grunge image is read: repeated grunge-scale times across the UV square (or the mesh's bounds, triplanar) pub(crate) fn custom_grunge_placement(wear: &WearParameters) -> SlotPlacement { if wear.triplanar { - SlotPlacement { scale: wear.grunge_scale, offset: 0.0, triplanar_contrast: Some(wear.triplanar_contrast) } + SlotPlacement { scale: wear.grunge_scale, offset: 0.0, triplanar_contrast: Some(wear.triplanar_contrast), mirrored_about_centre: false } } else { - SlotPlacement { scale: wear.grunge_scale, offset: CUSTOM_GRUNGE_UV_OFFSET, triplanar_contrast: None } + SlotPlacement { scale: wear.grunge_scale, offset: CUSTOM_GRUNGE_UV_OFFSET, triplanar_contrast: None, mirrored_about_centre: false } } } From 0d1f687b9abb13b294e02242eed8eda3729b0a70 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:35:22 +0000 Subject: [PATCH 149/153] Generators: a histogram's cut stack reads the anchor heights the whole stack prepared A histogram evaluates the stack cut below an effect: it rebuilt every anchor height under the cut's stack key, replacing the viewport's, so the next render built them again. A cut now builds only heights that are missing and leaves the set's prepared ones as they are. Review tidying: blank lines, histogram scan comment, the field cache test reads the cache's size. --- crates/compose/src/dripping_rust.rs | 1 + crates/compose/src/eval.rs | 49 ++++++++++++++++---- crates/compose/src/eval/evaluation_inputs.rs | 13 ++++++ crates/compose/src/field_cache.rs | 2 +- crates/compose/src/generator_maps.rs | 2 +- crates/compose/src/histogram_scan.rs | 5 +- crates/compose/src/micro_details/mod.rs | 5 ++ 7 files changed, 64 insertions(+), 13 deletions(-) diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index 43e42858..859088c9 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -118,6 +118,7 @@ fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, hei } field.get((y * i64::from(width) + x) as usize).copied() }; + // Central differences, one-sided at an island's border let slope = |before: Option, here: f32, after: Option| match (before, after) { (Some(before), Some(after)) => (after - before) * 0.5, diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 582f5bbf..e621c528 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2445,7 +2445,9 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { } } } - crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); + if inp.whole_stack() { + crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); + } if readers.is_empty() { return; } @@ -2457,6 +2459,10 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { }; readers.sort_by_key(|(_, anchor)| drawn_at(*anchor)); for (reader, anchor) in readers { + // A stack cut below an effect (a histogram's) reads the heights the whole stack prepared, building only those missing + if !inp.whole_stack() && crate::micro_details::has_anchor_heights(inp, anchor) { + continue; + } let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; crate::micro_details::prepare_anchor_heights(inp, anchor, stack, || anchor_heights(inp, reader, anchor)); } @@ -3446,6 +3452,7 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, maps); } + // The kinds with only their own controls: resolved once per plan, not per texel let resolved; let controls = match maps.controls.as_deref() { @@ -5111,7 +5118,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let (cut, in_mask) = cut_below(inp.project, owner, effect)?; let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); let channels = evaluation_channels(&cut_inp, cut.texture_set(inp.ts).map(|set| set.channel_list()).unwrap_or_default()); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); @@ -5235,7 +5242,7 @@ pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option< let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); let mut channels = evaluation_channels(&cut_inp, set.channel_list()); if !channels.contains(&channel) { channels.push(channel); @@ -7343,6 +7350,31 @@ soft {soft:?}" assert!(largest_change < 1e-4, "{largest_change}"); } + #[test] + fn a_histogram_below_a_reader_leaves_the_anchor_heights_it_reads() { + let (mut fixture, images) = micro_height_fixture(); + let id = fixture.project.alloc_id(); + let (low, anchor) = anchored_height(&mut fixture, id, Source::image("disc")); + let levels = content_fx(&mut fixture, low, EffectKind::Levels(Default::default())); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(reading_micro_height(anchor)))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + run_with_images(&fixture, None, &images); + + // The histogram evaluates the stack cut below the levels + effect_histogram(&inputs(&fixture, &images, None), levels, Channel::Height, 16); + + let stack = StackKey::new(&fixture.project, &fixture.pixels, &fixture.baked, &images, 0, &fixture.project.texture_sets[0].stack) + .expect("the plane's stack has a key"); + let builds = std::cell::Cell::new(0); + crate::micro_details::prepare_anchor_heights(&inputs(&fixture, &images, None), anchor, stack, || { + builds.set(builds.get() + 1); + AnchorHeights::new(vec![0.0; 64 * 64], (64, 64), fixture.project.texture_sets[0].block_scales()) + }); + assert_eq!(builds.get(), 0, "the render's heights are still prepared"); + } + #[test] fn anchor_heights_are_built_again_at_another_working_size() { let (mut fixture, images) = micro_height_fixture(); @@ -7368,7 +7400,7 @@ soft {soft:?}" assert_eq!(builds.get(), 2, "a smaller working atlas builds them again"); } - /// Builds a field cache made: the counter goes up with each build + /// A field build that counts each call in `builds` fn counted_build(builds: &std::cell::Cell) -> impl FnOnce((u32, u32)) -> Vec + '_ { move |_| { builds.set(builds.get() + 1); @@ -7420,7 +7452,7 @@ soft {soft:?}" #[test] fn a_whole_map_field_read_again_outlives_fields_built_before_it() { - const FIELDS_KEPT: u32 = 8; + let fields_kept = crate::field_cache::CACHE_ENTRIES as u32; let cache = crate::field_cache::FieldCache::new(); let builds = std::cell::Cell::new(0); let fixture = fixture(); @@ -7430,9 +7462,9 @@ soft {soft:?}" let field = |settings: u32| { cache.get_or_build(&inputs, coverage, &[], vec![settings], counted_build(&builds)); }; - (0..FIELDS_KEPT).for_each(field); + (0..fields_kept).for_each(field); field(0); - field(FIELDS_KEPT); + field(fields_kept); let built = builds.get(); field(0); @@ -7457,8 +7489,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(Generator { micro, ..earlier }))); fixture.project.layer_mut(top).unwrap().mask = Some(mask); - let composite = run(&fixture, None); - (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() + base_color_reds(&run(&fixture, None)) }; // The saved micro detail added the anchor's height times its amount to the curvature signal, even where the height is flat diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs index dbb8f392..ae870daa 100644 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -23,6 +23,8 @@ pub(super) struct EvaluationInputs<'a> { depth_maps: Mutex>, gradients: Mutex>>, coverage: OnceLock, + /// The project is the session's stack as drawn, not one cut below an effect (a histogram's) + whole_stack: bool, } impl<'a> EvaluationInputs<'a> { @@ -35,9 +37,20 @@ impl<'a> EvaluationInputs<'a> { depth_maps: Mutex::new(Vec::new()), gradients: Mutex::default(), coverage: OnceLock::new(), + whole_stack: true, } } + /// These inputs evaluating a project cut below an effect: it reads the anchor heights the whole stack prepared + pub(super) fn below_a_cut(self) -> Self { + Self { whole_stack: false, ..self } + } + + /// Whether the project evaluated is the session's whole stack + pub(super) fn whole_stack(&self) -> bool { + self.whole_stack + } + /// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`]) pub(super) fn coverage_identity(&self) -> u64 { *self.coverage.get_or_init(|| crate::field_cache::coverage_identity(self.inputs.gbuf)) diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 51581173..e03fcc94 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -9,7 +9,7 @@ use crate::field_cache_key::FieldCacheKey; use crate::working_field::working_block; /// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) -const CACHE_ENTRIES: usize = 8; +pub(crate) const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; /// Texels hashed together before their hashes are combined, so the coverage hashes in parallel diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 503a32c9..cd9b6e4a 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -28,7 +28,7 @@ pub(crate) struct GeneratorMaps { impl GeneratorMaps { /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `coverage` gives the working layout's coverage identity for whole-map fields - pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl Fn() -> u64) -> GeneratorMaps { + pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl FnOnce() -> u64) -> GeneratorMaps { let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind)); let micro_curvature = micro.as_ref().filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); diff --git a/crates/compose/src/histogram_scan.rs b/crates/compose/src/histogram_scan.rs index 8c474d7e..9e1bbbf7 100644 --- a/crates/compose/src/histogram_scan.rs +++ b/crates/compose/src/histogram_scan.rs @@ -11,8 +11,9 @@ pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 { } let width = 1.0 - contrast.clamp(0.0, 1.0); - // The ramp's low end runs from 1 at position 0 to −width at position 1, so the ends are wholly black or white - let low = (1.0 - position.clamp(0.0, 1.0)) * (1.0 + width) - width; + + // The ramp's low end runs from 1 towards position 0 to −width towards position 1 + let low = (1.0 - position) * (1.0 + width) - width; if width <= f32::EPSILON { return if value >= low { 1.0 } else { 0.0 }; } diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index 4ee72fd3..4120d0ed 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -111,6 +111,11 @@ pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: Stack entries.push(AnchorEntry { baked, texture_set: inp.ts, anchor, stack, heights }); } +/// Whether heights are prepared for anchor `anchor`, for any stack +pub(crate) fn has_anchor_heights(inp: &Inputs, anchor: LayerId) -> bool { + anchor_heights(inp, anchor).is_some() +} + /// The heights prepared for anchor `anchor` (None before they are) fn anchor_heights(inp: &Inputs, anchor: LayerId) -> Option> { let baked = baked_identity(inp)?; From 5f33d84f1e0a2aaa817bf1614cff6c9f5f7169e9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:40:42 +0000 Subject: [PATCH 150/153] Generators: only the session's own composite drops anchor heights it no longer reads Thumbnails, solo layers and histograms evaluate cut-down stacks without every reader: they now build only missing heights and drop none, so a thumbnail refresh no longer throws away the viewport's. Doc full stops on the touched preparation functions. --- crates/compose/src/eval.rs | 16 ++++++++-------- crates/compose/src/eval/evaluation_inputs.rs | 18 +++++++++--------- crates/compose/src/micro_details/mod.rs | 2 +- crates/ui-egui/tests/it/generator_panel.rs | 5 +++-- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index e621c528..944ac73c 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2418,7 +2418,7 @@ fn compares_this_layer(kind: &EffectKind) -> bool { matches!(kind, EffectKind::Compare { left, right, .. } if *left == CompareSource::ThisLayer || *right == CompareSource::ThisLayer) } -/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) { 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); @@ -2445,7 +2445,8 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { } } } - if inp.whole_stack() { + // Only the session's own stack knows every reader: a cut-down one (a histogram's, a thumbnail's) builds what is missing and drops nothing + if inp.is_session_stack() { crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); } if readers.is_empty() { @@ -2459,8 +2460,7 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { }; readers.sort_by_key(|(_, anchor)| drawn_at(*anchor)); for (reader, anchor) in readers { - // A stack cut below an effect (a histogram's) reads the heights the whole stack prepared, building only those missing - if !inp.whole_stack() && crate::micro_details::has_anchor_heights(inp, anchor) { + if !inp.is_session_stack() && crate::micro_details::has_anchor_heights(inp, anchor) { continue; } let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; @@ -2511,7 +2511,7 @@ fn wear_parameters(generator: &Generator) -> Option { generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) } -/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { @@ -4407,7 +4407,7 @@ pub fn composite_tiles_with_projectors( cache.bind_mesh(mesh); } - let inputs = EvaluationInputs::new(inputs, projectors); + let inputs = EvaluationInputs::new(inputs, projectors).of_the_session_stack(); composite_evaluation_tiles(&inputs, out, tiles, below); } @@ -5118,7 +5118,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let (cut, in_mask) = cut_below(inp.project, owner, effect)?; let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); let channels = evaluation_channels(&cut_inp, cut.texture_set(inp.ts).map(|set| set.channel_list()).unwrap_or_default()); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); @@ -5242,7 +5242,7 @@ pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option< let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); let mut channels = evaluation_channels(&cut_inp, set.channel_list()); if !channels.contains(&channel) { channels.push(channel); diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs index ae870daa..257ee055 100644 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -23,8 +23,8 @@ pub(super) struct EvaluationInputs<'a> { depth_maps: Mutex>, gradients: Mutex>>, coverage: OnceLock, - /// The project is the session's stack as drawn, not one cut below an effect (a histogram's) - whole_stack: bool, + /// The project is the session's own stack as the viewport composites it, not one cut down (a histogram's, a thumbnail's, a solo layer's) + session_stack: bool, } impl<'a> EvaluationInputs<'a> { @@ -37,18 +37,18 @@ impl<'a> EvaluationInputs<'a> { depth_maps: Mutex::new(Vec::new()), gradients: Mutex::default(), coverage: OnceLock::new(), - whole_stack: true, + session_stack: false, } } - /// These inputs evaluating a project cut below an effect: it reads the anchor heights the whole stack prepared - pub(super) fn below_a_cut(self) -> Self { - Self { whole_stack: false, ..self } + /// These inputs evaluating the session's own stack: they keep the anchor heights the stack reads and drop the rest + pub(super) fn of_the_session_stack(self) -> Self { + Self { session_stack: true, ..self } } - /// Whether the project evaluated is the session's whole stack - pub(super) fn whole_stack(&self) -> bool { - self.whole_stack + /// Whether the project evaluated is the session's own stack (see [`EvaluationInputs::of_the_session_stack`]) + pub(super) fn is_session_stack(&self) -> bool { + self.session_stack } /// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`]) diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index 4120d0ed..74c098b7 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -62,7 +62,7 @@ const OCCLUSION_STRENGTH: f32 = 0.3232; const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; -/// The anchor heights prepared last, one per mesh maps, texture set and anchor +/// The anchor heights prepared last, one per mesh maps, texture set and anchor: a working-size atlas each, kept while the session's stack reads it and its mesh maps live static ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); /// The mesh maps (by address) and texture sets whose anchor heights are being built: the build composites the stack, which prepares them again diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 3b5c8c2d..38eaf6d5 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -94,9 +94,10 @@ fn global_blur_applies_as_one_undo_step() { #[test] fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { + const SET_FACTOR: i8 = -2; let (mut harness, effect) = harness(false); assert!(harness.get_by_role_and_label(Role::Button, "Restore defaults").accesskit_node().is_disabled(), "at its defaults it does nothing"); - let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); + let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": SET_FACTOR, "seed": 99}); execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); harness.run_steps(3); @@ -104,7 +105,7 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { // Resolution has its own band: restoring the parameters leaves it as set let restored = generator(&harness, effect); - assert_eq!(restored.resolution.factor, -2); + assert_eq!(restored.resolution.factor, SET_FACTOR); assert_eq!(Generator { resolution: Generator::new(GeneratorKind::Curvature).resolution, ..restored }, Generator::new(GeneratorKind::Curvature)); } From eda6f834deb991127489fb4aec1d55d49c77a7a4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:42:35 +0000 Subject: [PATCH 151/153] Generators: a whole-map field's sampled mesh map is a type of its own (clippy type_complexity) --- crates/compose/src/field_cache.rs | 7 +++++-- crates/compose/src/field_cache_key.rs | 25 ++++--------------------- crates/compose/src/lib.rs | 1 + crates/compose/src/sampled_map.rs | 14 ++++++++++++++ 4 files changed, 24 insertions(+), 23 deletions(-) create mode 100644 crates/compose/src/sampled_map.rs diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index e03fcc94..42ad9ebc 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -6,6 +6,7 @@ use texturecraft_geom::UvGBuffer; use crate::eval::Inputs; use crate::field_cache_key::FieldCacheKey; +use crate::sampled_map::SampledMap; use crate::working_field::working_block; /// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) @@ -47,7 +48,9 @@ impl FieldCache { ) -> Arc> { let gbuf = inp.gbuf; let block = working_block(inp); - let read = maps.iter().filter_map(|map| inp.baked.maps.get(map).map(|data| (Arc::downgrade(data), (inp.baked.resolution, inp.baked.height(*map))))); + let read = maps.iter().filter_map(|map| { + inp.baked.maps.get(map).map(|data| SampledMap { data: Arc::downgrade(data), baked_size: (inp.baked.resolution, inp.baked.height(*map)) }) + }); let key = FieldCacheKey { layout: gbuf.tri.as_ptr() as usize, size: (gbuf.width, gbuf.height), @@ -63,7 +66,7 @@ impl FieldCache { // A hit moves to the most recently used end let cached = { let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.maps.iter().all(|(map, _)| map.strong_count() > 0)); + entries.retain(|(key, _)| key.maps.iter().all(|map| map.data.strong_count() > 0)); let hit = entries.iter().position(|(cached, _)| *cached == key).map(|index| entries.remove(index)); hit.map(|(cached, field)| { entries.push((cached, field.clone())); diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs index 1010ac97..2f44ab4f 100644 --- a/crates/compose/src/field_cache_key.rs +++ b/crates/compose/src/field_cache_key.rs @@ -1,9 +1,9 @@ -use std::sync::Weak; - use texturecraft_core::BlockScales; +use crate::sampled_map::SampledMap; + /// What a field was built from: the working layout (the g-buffer's address, size, coverage, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub(crate) struct FieldCacheKey { pub(crate) layout: usize, pub(crate) size: (u32, u32), @@ -14,23 +14,6 @@ pub(crate) struct FieldCacheKey { /// The mesh's positions and UVs, each by address and length: a UV edit changes island fields pub(crate) positions: (usize, usize), pub(crate) uvs: (usize, usize), - /// The mesh maps it samples, each with the size it was baked at: one allocation read as another layout reads other texels - pub(crate) maps: Vec<(Weak>, (u32, u32))>, + pub(crate) maps: Vec, pub(crate) settings: Vec, } - -impl PartialEq for FieldCacheKey { - fn eq(&self, other: &FieldCacheKey) -> bool { - let same_maps = self.maps.len() == other.maps.len() - && self.maps.iter().zip(&other.maps).all(|((a, a_size), (b, b_size))| a.strong_count() > 0 && a.ptr_eq(b) && a_size == b_size); - same_maps - && self.layout == other.layout - && self.size == other.size - && self.coverage == other.coverage - && self.block == other.block - && self.scales == other.scales - && self.positions == other.positions - && self.uvs == other.uvs - && self.settings == other.settings - } -} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e7d72fe8..724cf4ad 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -43,6 +43,7 @@ pub mod projector_cover; pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; +mod sampled_map; mod sections; mod shape_distance; mod slope_texel; diff --git a/crates/compose/src/sampled_map.rs b/crates/compose/src/sampled_map.rs new file mode 100644 index 00000000..1583f3f6 --- /dev/null +++ b/crates/compose/src/sampled_map.rs @@ -0,0 +1,14 @@ +use std::sync::Weak; + +/// A mesh map a whole-map field samples: its allocation and the size it was baked at (one allocation read as another layout reads other texels) +#[derive(Clone)] +pub(crate) struct SampledMap { + pub(crate) data: Weak>, + pub(crate) baked_size: (u32, u32), +} + +impl PartialEq for SampledMap { + fn eq(&self, other: &SampledMap) -> bool { + self.data.strong_count() > 0 && self.data.ptr_eq(&other.data) && self.baked_size == other.baked_size + } +} From a8538b761a116e51946e685705f30b8e1bf3c97a Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 13:31:26 +0000 Subject: [PATCH 152/153] Dependencies keep line tables in dev and test builds --- .cargo/config.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.cargo/config.toml b/.cargo/config.toml index 5592118f..acb86eae 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,7 @@ [alias] xtask = "run -p xtask --" + +# An explicit level for dependencies: Cargo drops the profile's default debug level from crates only build scripts and +# macros use, and then clippy and test each build their own copy of them. +[profile.dev.package."*"] +debug = "line-tables-only" From dcf91a4f055b60c48ce353603de4205205a9e5a4 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Wed, 25 Nov 2026 16:17:41 -0600 Subject: [PATCH 153/153] Use the shared nightly launcher template (#835) Renders the plain nightly tar's launcher from craft-common-actions' shared template. Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5. --- docs/nightly-release-preparation.md | 9 ++- packaging/linux/nightly-launch-test.sh | 78 +++++++++++++++++--------- packaging/linux/nightly-launch.sh | 29 ++++------ 3 files changed, 68 insertions(+), 48 deletions(-) diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 2b504a7e..28114854 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -95,11 +95,14 @@ those values in the same reviewed change that promotes the policy to `release`. ## App-side producer scripts (Windows and macOS) **Every Linux Nightly format starts the app the flavor's way.** The `.deb`/`.rpm` wrapper, the -Arch launcher, the Flatpak wrapper, the AppImage's `AppRun` and the launcher inside the plain -`nightly.tar.gz` all exec the real GUI with the literal +Arch launcher, the Flatpak wrapper and the AppImage's `AppRun` all exec the real GUI with the literal `--launch-profile nightly-v1 --profile-root <${XDG_DATA_HOME:-~/.local/share}/TextureCraft-Nightly> --`, and pass a Launcher protocol or a `--version`/`-V` query through untouched (so the smoke checks and -`texturecraft-nightly --version` still answer). The profile is outside stable's folders and outside +`texturecraft-nightly --version` still answer). The plain `nightly.tar.gz` (and `package.sh`'s tree tarball, which installs the same file) uses craft-common-actions' +shared launcher template (#363, rendered for this app) instead: its `texturecraft` adds its own +tokens unless the first argument is already a `--launch-profile` pair, execs `texturecraft-bin` beside it with +`--profile-root <${XDG_DATA_HOME:-~/.local/share}/ai.storyteller.texturecraft.nightly> --`, and asks a +bare `--version`/`-V` in the Launcher's own form. The profile is outside stable's folders and outside the unpacked or installed copy, which the flavor's fence would otherwise refuse. Every Nightly Linux format is GUI only. `texturecraft-cli` stays in the Stable packages: a headless diff --git a/packaging/linux/nightly-launch-test.sh b/packaging/linux/nightly-launch-test.sh index 4da17cd3..608de4b0 100755 --- a/packaging/linux/nightly-launch-test.sh +++ b/packaging/linux/nightly-launch-test.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash -# The launcher inside the plain Nightly tarball (packaging/linux/nightly-launch.sh): a launch adds -# the Launcher's private profile, a version query or an existing protocol passes through, and the -# fence's shape holds (absolute root, no parent traversal, outside this copy). +# The launcher inside the plain Nightly tarball (packaging/linux/nightly-launch.sh): craft-common-actions' +# template rendered for TextureCraft. Every argument follows the profile tokens, the profile root is the +# package identity under the XDG data home (or HOME), and a version query is asked in the Launcher's +# own form so the GUI answers before any profile is read. set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -16,42 +17,63 @@ printf '<%s>\n' "$@" RECORDER chmod 755 "$work/tree/texturecraft-bin" cp "$HERE/nightly-launch.sh" "$work/tree/texturecraft" +chmod 755 "$work/tree/texturecraft" -profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" -# The profile must be something the app's fence accepts: absolute, no parent traversal, and not -# inside the unpacked copy (the running install). -case "$profile" in - /*) ;; - *) echo "FAIL: the launcher profile is not absolute: $profile" >&2; exit 1 ;; -esac -case "/$profile/" in - */../*) echo "FAIL: the launcher profile contains parent traversal" >&2; exit 1 ;; -esac -case "$profile/" in - "$work/tree/"*) echo "FAIL: the launcher profile is inside the unpacked copy" >&2; exit 1 ;; -esac +# The bytes are the shared template rendered for this app, not a local script. +sha256sum "$HERE/nightly-launch.sh" | cut -d' ' -f1 | grep -qx \ + 8941ee4947ef4c3fc4a663600569d985b41c0b9ce6f9833d0c6777aa2b4d6acf || { + echo "FAIL: nightly-launch.sh is not the shared template rendered for texturecraft" >&2 + exit 1 +} +head -n 1 "$work/tree/texturecraft" | grep -qx '#!/bin/sh' || { echo "FAIL: texturecraft is not a script" >&2; exit 1; } -expect_launch() { - expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")" +# A hand-unpacked tar has to start the private profile even when nobody passes a flag. +export HOME="$work/home with space" +unset XDG_DATA_HOME +identity="ai.storyteller.texturecraft.nightly" + +expect() { + local root="$1" + shift + expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$root" -- "$@")" actual=$("$work/tree/texturecraft" "$@") + [[ "$actual" == "$expected" ]] || { + printf 'profile root %s\nexpected:\n%s\nactual:\n%s\n' "$root" "$expected" "$actual" >&2 + exit 1 + } +} + +expect_query() { + local root="$1" + expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$root" --version)" + actual=$("$work/tree/texturecraft" --version) [[ "$actual" == "$expected" ]] || { printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 exit 1 } -} -expect_forwarded() { - expected="$(printf '<%s>\n' "$@")" - actual=$("$work/tree/texturecraft" "$@") + actual=$("$work/tree/texturecraft" -V) [[ "$actual" == "$expected" ]] || { printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 exit 1 } } -expect_launch -expect_launch 'model with spaces.glb' '--other-name.tcraft' -expect_forwarded --version -expect_forwarded -V -expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version +expect "$HOME/.local/share/$identity" +expect "$HOME/.local/share/$identity" 'model with spaces.glb' '--other-name.tcraft' +export XDG_DATA_HOME="$work/xdg with space" +expect "$XDG_DATA_HOME/$identity" 'model.glb' +expect_query "$XDG_DATA_HOME/$identity" +unset XDG_DATA_HOME +expect_query "$HOME/.local/share/$identity" -echo "PASS: tarball Nightly launcher starts the GUI with the Launcher profile and forwards files" +# The ArtCraft Launcher names its own profile and per-install root: the argv goes through unchanged. +actual=$("$work/tree/texturecraft" --launch-profile nightly-v1 --profile-root "$work/launcher profile with space" -- file.doc) +[[ "$actual" == "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher profile with space" -- file.doc)" ]] || { + printf 'expected the Launcher argv unchanged\nactual:\n%s\n' "$actual" >&2 + exit 1 +} + +# The launcher itself writes nothing: the profile folder is the GUI's to create. +[[ ! -e "$HOME/.local/share/$identity" ]] || { echo "FAIL: the launcher created the profile" >&2; exit 1; } + +echo "PASS: the tarball launcher is the shared template and starts the GUI through the channel's profile" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh index 77fa7d9c..ef4361a8 100755 --- a/packaging/linux/nightly-launch.sh +++ b/packaging/linux/nightly-launch.sh @@ -1,21 +1,16 @@ #!/bin/sh -# The entry point inside the Nightly tarball (packaging/linux/nightly.sh installs it as -# `texturecraft`, beside the GUI as `texturecraft-bin`). -# -# A Nightly build only starts with its private profile, and every package format passes the -# Launcher's literal protocol: `--launch-profile nightly-v1 --profile-root -- `. The -# profile sits outside stable's folders (its own settings, ui.json, crash log, autosaves, smart -# materials, layouts, templates and presets) and outside this unpacked copy, which the app's own -# fence would refuse. +# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in. Do not edit: +# the shared nightly producer accepts this file only byte for byte as rendered for the app. set -eu - -here="$(dirname "$(readlink -f "$0")")" -bin="$here/texturecraft-bin" -profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" - -# The Launcher's protocol, and a bare version query, pass through untouched: the first already -# names its profile, and the second must answer without one. +dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P) +readonly dir +target="$dir/texturecraft-bin" +readonly target +profile_root="${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller.texturecraft.nightly" +readonly profile_root case "${1-}" in - --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; + # The ArtCraft Launcher passes its own profile and per-install root; the app validates the pair. + --launch-profile) exec "$target" "$@" ;; + --version | -V) exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" --version ;; esac -exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" +exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@"

N0)J+Lba0DhnU77})7<$1Tc)I-7K`?()rB9&tWyT}sJKh= z#Vr8*#G2I>s6JfEIk&gW#xV}3w2FJ@UIr>f2X%qzJ7*_r|qgPon6_h}8mILEea zQ)=*El60j-PLlOr$m+KI9~)LJjz(+jLh5zK0{TiE=poxCw}+al0XLRB#*|a0I0;(t zo7j~3!#(-7H0h-{xTjJq%ac<858eJuJAc zS-E!fNR`78zxd`>7fIAwmV+~CbG-h8#eZ!~y4y3-8OoL2W|m8HXG==j zT;T_4&tcE<1m{}slgZ9oRi0G^zt&JuYFt~6{}E%OuT`JH)Y*KCr2QgX>3rt1;{F*- z)N<{A17yN#LbMLMRC6p{m!N#67q<_KqmMLQCXx+Tr8`BIphw7ts#eE3?m zOmR9W34+DGPa%dxqM}{^QuM^Ft%G{jP6v!PCaj%)emSaLPvuhcBA7<(X>-GQ;Wdm@ zLolXp&wz!q3ehHs?cpuVysR_R>+G@`c?Axh{IAqD@p^Mv!Y4l?|F-pp1FNE@{c{?G zieS;CpqUIk;Nl8?_5sW}Ccp=N=-ghCxA?tuM%(ru=7Rx^oIe<$VMZ{(N}ED;wmT?y zY6r#}{nrj(K2Pe>1-~7pjLEH{&ray}6x91}NmA9_DJA7kQzBO6zpa)M1FXi^+I$MjFJzgiDU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{w8_V6*7 zcs}5{)R9U-tR3D_pC<~%ZSiM-&%8U#xhcHDfwKr?fwP3^%9|A@EVO>d00NxQgkx*% zHd_&-Fr-h;2FFi$&WeKCs=1SId+FB`WqDa=j{KH!a2y-Km1q;SoZg8U*JOFp*4a)Y VIX&Gjv)JEkOH*4DoRLT3{{X6)$+!Rj literal 0 HcmV?d00001 diff --git a/assets/app-icon/texturecraft-nightly.icns b/assets/app-icon/texturecraft-nightly.icns new file mode 100644 index 0000000000000000000000000000000000000000..9d96db5fac1d7ae3fba861559b85a23006c6a0fc GIT binary patch literal 358850 zcmeFYS5#EN_bzz48=4GFkeoqKP-&8qyU8d>5)_dP5+x%!G#Mldk~2tEZvMI}dl}u63Vg%{=_ps#Eo{*E&_T&sX19d+%dmY~u)EyR}&u+X(;w=zFND zvOEz!Ej|DML@yO&)bB^we?7R+`=03-V|Z_5@=``p!*$x&Ad{oJDn3C$@S77lSkkiG zQkgdY z;2FbihfyS;QlYWk)$cAd(kYJhb#-@r^pvkK(?7`Iy0jZ%Mt}mzTL`k2{ozqdQYfz$ z+axwpL{$9HNADA}Aq3y^DVo**ifSaKSR}}kyfN|N1Vgc={L`AOSMcHDj+RWb59W3w zFzsNk13GxtBg$e}E-06#16l`|Pd_YhpaIte_X(HeGW;xc`UD6M zh+8VYModoJ`Y4r?hzaIh&a^jyM+viwSW``gV~@a3UY_|VCyEL!B9jf4)Dp<5P@8=k zr0a{Z57ucQNBrGW)X(4G1F0KwiR3}k4ENg(yp&azDU~wtyLXZx06>!d7fxcnH)H;9 zCpo&ipWGX1{hvHcUadQ;N(y&nc6>vG#KI$0Y1{k~$>NuxhN z_n+Lc;P{xyyOKysHv}IwS+=PHyEdJXCSKffwfa`h_qyyOmtbk2^E6(EGJH z?oJOZSu-IH_J0QKhOBM|y!#nB_&U`ck@ZwoChho1CQnz$ReqaOk>kb!*v4KclRMO?u+y2}R>TzT? z*{_jE%VeOEDh#$bxSs(YU{Fzc{!00qfmneSi+br>T&x>$Ik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