From c25c984395ad379a51bef33871bbd77b6e97f197 Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:13:17 +0100 Subject: [PATCH 01/80] i18n: offer Russian MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LANGUAGES gains ru (Русский); ru-RU, ru-SK and ru_RU.UTF-8 resolve to it. Its texturecraft.tsv catalog comes from craft-i18n; Cyrillic is drawn by egui's built-in fonts. Docs list eleven languages. --- ROADMAP.md | 5 +++-- crates/ui-egui/src/fonts.rs | 6 ++++-- crates/ui-egui/src/i18n.rs | 5 +++-- docs/features.md | 4 ++-- docs/localization-parity.md | 1 + 5 files changed, 13 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 759dfde7..4ff0ad33 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,7 +95,7 @@ incomplete validation; they are not measured success rates or speed comparisons. | UI/UX fidelity | ~65% | 20 | TBD | Current editing/bake/export UI checked; [gaps](docs/ui-parity.md), ArtCraft UI adoption and revalidation after refactoring remain | | File formats / interchange | ~60% | 10 | TBD | Current native save and basic exports exercised; possible `.tcraft`/output-package reworks, unfinished upstream `.mcmat`, `.spp` and consumer validation remain | | Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete | -| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement | +| Localization | ~35% | 4 | TBD | Eleven picker languages in source; optional shared catalogs/fonts and native-language review need current measurement | | Performance | ~40% | 10 | TBD | Dirty-tile/budgeted architecture and benchmark code exist; no matched performance budgets or large-project results from this review | | Stability | ~55% | 10 | TBD | Small save/reopen and undo/redo passed; recovery, large projects and long sessions need coverage, including after format/library migrations | | Platforms | ~65% | 3 | TBD | Desktop/web build and packaging paths exist; this review ran Windows only | @@ -158,7 +158,7 @@ exist; older reports must not turn them into fresh missing-feature claims. ## Languages -The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at +The [picker](crates/ui-egui/src/i18n.rs) contains eleven languages. Shared catalogs are optional at build time; missing entries fall back to English, and builds without catalogs offer English only. The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%” rows are not a current measurement. This audit ran an English build without external catalogs. @@ -170,6 +170,7 @@ rows are not a current measurement. This audit ran an English build without exte | Spanish | `es` | Not remeasured | Catalog dependent; native review pending | | Hindi | `hi` | No picker entry | Not offered | | Arabic | `ar` | Not remeasured | Catalog/font dependent; shaping/layout needs current review | +| Russian | `ru` | Catalog dependent | Added with the craft-i18n `ru/texturecraft.tsv` catalog; reviewed by a native speaker | | French | `fr` | Not remeasured | Catalog dependent; native review pending | | Portuguese (Brazil) | `pt-BR` | Not remeasured | Catalog dependent; native review pending | | Indonesian | `id` | No picker entry | Not offered | diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b31b423a..6f11efec 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -278,9 +278,11 @@ mod tests { assert_eq!(Script::of_language("ko"), Some(Script::Korean)); assert_eq!(Script::of_language("ar"), Some(Script::Arabic)); assert_eq!(Script::of_language("de"), None); + assert_eq!(Script::of_language("ru"), None); for l in &crate::i18n::LANGUAGES { - // Past the Latin blocks and their diacritics. - let other_script = l.name.chars().any(|c| c > '\u{036F}'); + // Past the Latin blocks and their diacritics. Cyrillic needs no fallback: the UI fonts + // themselves carry it (egui's Ubuntu and craft-fonts' Inter). + let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index bbbea0ec..fe1cca17 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -37,7 +37,7 @@ pub struct Language { pub english: &'static str, } -const COUNT: usize = 10; +const COUNT: usize = 11; pub static LANGUAGES: [Language; COUNT] = [ Language { code: "en", name: "English", english: "English" }, @@ -46,6 +46,7 @@ pub static LANGUAGES: [Language; COUNT] = [ Language { code: "es", name: "Español", english: "Spanish" }, Language { code: "pt-BR", name: "Português (Brasil)", english: "Portuguese (Brazil)" }, Language { code: "it", name: "Italiano", english: "Italian" }, + Language { code: "ru", name: "Русский", english: "Russian" }, Language { code: "ja", name: "日本語", english: "Japanese" }, Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" }, Language { code: "ko", name: "한국어", english: "Korean" }, @@ -386,7 +387,7 @@ mod tests", assert_eq!(trf("{a} of {b} {c}", &[("a", &1), ("b", &2)]), "1 of 2 {c}"); assert_eq!(trf("{unclosed", &[]), "{unclosed"); for (locale, code) in - [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("nl-NL", "en"), ("", "en")] + [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("ru-SK", "ru"), ("ru_RU.UTF-8", "ru"), ("nl-NL", "en"), ("", "en")] { assert_eq!(language_for_locale(locale), code, "{locale}"); } diff --git a/docs/features.md b/docs/features.md index 79bae167..1a66c200 100644 --- a/docs/features.md +++ b/docs/features.md @@ -260,8 +260,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel to a text file with each entry's recorded UTC time, severity and source. The desktop app asks for a destination, and the browser downloads the file. - A **History** panel: click any step to go back to it, or forward again to an undone one. -- **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, - Korean and Arabic, switchable live. +- **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese, + Chinese, Korean and Arabic, switchable live. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch navigation and project open, save and download. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index fb6a8a49..3625d0cd 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -29,6 +29,7 @@ generator, filter and brush alpha names (**KEYS** strings, counted by the | Arabic | `ar` | KEYS (100%) | yes | Arabic glyphs: craft-fonts (Noto Sans Arabic) or system fonts on desktop; egui shapes the text and orders it right to left (panels keep the left-to-right layout) | yes | full | 0 h | | French | `fr` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | | Portuguese (Brazil) | `pt-BR` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | +| Russian | `ru` | KEYS (~99%) | yes | Cyrillic: egui's built-in fonts | yes | full with the craft-i18n `ru/texturecraft.tsv` catalog | 0 h | | Indonesian | `id` | 0 | no | Latin | no | none | 3 h | | Japanese | `ja` | KEYS (100%) | yes | CJK glyphs: craft-fonts (BIZ UDPGothic) or system fonts on desktop | no | full | 2 h (review) | | German | `de` | KEYS (100%) | yes | Latin | no | full | 1 h (review) | From ab13dc9870bdd5251497031c37a98a72937b8926 Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:09:28 +0100 Subject: [PATCH 02/80] i18n: format the locale test; features.md says a build without catalogs offers English only --- crates/ui-egui/src/i18n.rs | 15 ++++++++++++--- docs/features.md | 3 ++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index fe1cca17..a0697be5 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -386,9 +386,18 @@ mod tests", assert_eq!(trf("Saved {path}", &[("path", &"a.tcraft")]), "Saved a.tcraft"); assert_eq!(trf("{a} of {b} {c}", &[("a", &1), ("b", &2)]), "1 of 2 {c}"); assert_eq!(trf("{unclosed", &[]), "{unclosed"); - for (locale, code) in - [("de-AT", "de"), ("pt_PT.UTF-8", "pt-BR"), ("zh-Hant-TW", "zh-Hans"), ("ja", "ja"), ("ko_KR", "ko"), ("ar-EG", "ar"), ("ru-SK", "ru"), ("ru_RU.UTF-8", "ru"), ("nl-NL", "en"), ("", "en")] - { + for (locale, code) in [ + ("de-AT", "de"), + ("pt_PT.UTF-8", "pt-BR"), + ("zh-Hant-TW", "zh-Hans"), + ("ja", "ja"), + ("ko_KR", "ko"), + ("ar-EG", "ar"), + ("ru-SK", "ru"), + ("ru_RU.UTF-8", "ru"), + ("nl-NL", "en"), + ("", "en"), + ] { assert_eq!(language_for_locale(locale), code, "{locale}"); } set_language("de"); diff --git a/docs/features.md b/docs/features.md index 1a66c200..220eadf2 100644 --- a/docs/features.md +++ b/docs/features.md @@ -261,7 +261,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA for a destination, and the browser downloads the file. - A **History** panel: click any step to go back to it, or forward again to an undone one. - **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese, - Chinese, Korean and Arabic, switchable live. + Chinese, Korean and Arabic, switchable live. A build without the shared craft-i18n catalogs + offers English only. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch navigation and project open, save and download. From 025aff43182c6b0c3fc3795a9d91739c0856c50e Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:09:29 +0100 Subject: [PATCH 03/80] tests: pin the UI harnesses to English The app starts in the system language and these tests find controls by their English labels, so on a machine whose language TextureCraft offers they failed. Each harness built around TextureCraftApp now sets prefs.language to en right after it is built, as rail.rs and settings_window.rs already did; the toolbar-only harnesses, which never run a full frame, set the language directly. ui_state_persistence keeps the saved state it tests. --- crates/ui-egui/tests/bake_preview.rs | 2 ++ crates/ui-egui/tests/brush_cursor_2d.rs | 2 ++ crates/ui-egui/tests/it/bake_job_mesh.rs | 2 ++ crates/ui-egui/tests/it/bake_mode.rs | 4 ++++ crates/ui-egui/tests/it/bake_presets.rs | 3 +++ crates/ui-egui/tests/it/brush_drag.rs | 3 +++ crates/ui-egui/tests/it/camera_views.rs | 3 +++ crates/ui-egui/tests/it/clone_source_view.rs | 2 ++ crates/ui-egui/tests/it/close_unsaved.rs | 2 ++ crates/ui-egui/tests/it/color_selection_editor.rs | 3 +++ crates/ui-egui/tests/it/curvature_generator.rs | 2 ++ crates/ui-egui/tests/it/effect_rows.rs | 4 ++++ crates/ui-egui/tests/it/effect_sliders.rs | 3 +++ crates/ui-egui/tests/it/export_template_guards.rs | 2 ++ crates/ui-egui/tests/it/file_dialogs.rs | 2 ++ crates/ui-egui/tests/it/filter_picker.rs | 3 +++ crates/ui-egui/tests/it/frame_selection.rs | 2 ++ crates/ui-egui/tests/it/generator_panel.rs | 2 ++ crates/ui-egui/tests/it/history_panel.rs | 3 +++ crates/ui-egui/tests/it/import_resources.rs | 1 + crates/ui-egui/tests/it/inactive_set_hint.rs | 2 ++ crates/ui-egui/tests/it/layer_blending_options.rs | 2 ++ crates/ui-egui/tests/it/layer_clipboard.rs | 3 +++ crates/ui-egui/tests/it/layer_multi_select.rs | 2 ++ crates/ui-egui/tests/it/layer_rename.rs | 2 ++ crates/ui-egui/tests/it/layers_panel.rs | 3 +++ crates/ui-egui/tests/it/levels_editor.rs | 2 ++ crates/ui-egui/tests/it/mask_export.rs | 2 ++ crates/ui-egui/tests/it/mask_value_swap.rs | 2 ++ crates/ui-egui/tests/it/named_layouts.rs | 2 ++ crates/ui-egui/tests/it/nav_buttons.rs | 2 ++ crates/ui-egui/tests/it/new_project_baked_maps.rs | 3 +++ crates/ui-egui/tests/it/path_in_view.rs | 4 ++++ crates/ui-egui/tests/it/path_list.rs | 2 ++ crates/ui-egui/tests/it/pen_pressure.rs | 2 ++ crates/ui-egui/tests/it/polygon_fill.rs | 3 +++ crates/ui-egui/tests/it/project_config.rs | 1 + crates/ui-egui/tests/it/properties_popup.rs | 2 ++ crates/ui-egui/tests/it/shelf_click.rs | 2 ++ crates/ui-egui/tests/it/shelf_drop.rs | 2 ++ crates/ui-egui/tests/it/shelf_hover_preview.rs | 2 ++ crates/ui-egui/tests/it/shelf_panel.rs | 2 ++ crates/ui-egui/tests/it/shift_lines_2d.rs | 3 +++ crates/ui-egui/tests/it/shift_lines_3d.rs | 2 ++ crates/ui-egui/tests/it/shortcut_keys.rs | 2 ++ crates/ui-egui/tests/it/skew_paint.rs | 2 ++ crates/ui-egui/tests/it/smudge_channels.rs | 2 ++ crates/ui-egui/tests/it/snapped_lines.rs | 2 ++ crates/ui-egui/tests/it/split_divider.rs | 2 ++ crates/ui-egui/tests/it/symmetry.rs | 2 ++ crates/ui-egui/tests/it/symmetry_2d.rs | 2 ++ crates/ui-egui/tests/it/tool_availability.rs | 4 ++++ crates/ui-egui/tests/it/tool_settings_saved.rs | 2 ++ crates/ui-egui/tests/it/toolbar.rs | 7 +++++++ crates/ui-egui/tests/it/user_smart_mask.rs | 2 ++ crates/ui-egui/tests/list_panels.rs | 3 +++ 56 files changed, 136 insertions(+) diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 1703abde..9e00f082 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -20,6 +20,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { session.view = ViewMode::UvChecker; let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(3); harness diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 6c54d052..323b7924 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout}; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 60f6f03e..6d166d46 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { 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)); + // 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); let progress = Arc::new(Progress::new()); let (tx, receiver) = std::sync::mpsc::channel(); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 787f8645..4144b903 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -13,6 +13,8 @@ fn harness(map: Option) -> Harness<'static, TextureCraftApp> { session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R64; session.doc.project.texture_sets[0].bake.maps.select(map); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); @@ -222,6 +224,7 @@ fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { ) .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.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); let before = harness.state().session.doc.project.clone(); @@ -273,6 +276,7 @@ fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); let before = session.doc.project.clone(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/bake_presets.rs b/crates/ui-egui/tests/it/bake_presets.rs index 5adef4ea..081ea242 100644 --- a/crates/ui-egui/tests/it/bake_presets.rs +++ b/crates/ui-egui/tests/it/bake_presets.rs @@ -18,6 +18,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { } let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); @@ -175,6 +177,7 @@ fn a_partial_bake_does_not_count_preserved_unchecked_maps() { set.bake.maps.select([BakedMap::Id]); set.bake_excluded_tiles.insert(1002); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.state_mut().start_bake(vec![0]); diff --git a/crates/ui-egui/tests/it/brush_drag.rs b/crates/ui-egui/tests/it/brush_drag.rs index ecc5393f..fe565535 100644 --- a/crates/ui-egui/tests/it/brush_drag.rs +++ b/crates/ui-egui/tests/it/brush_drag.rs @@ -23,6 +23,8 @@ fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { 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)); + // 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); let c = h.state().viewport_rect.center(); let (brush, yaw, history) = { @@ -51,6 +53,7 @@ fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { fn app(layout: texturecraft_ui_egui::state::ViewLayout) -> 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.state_mut().ui.layout = layout; h.run_steps(4); h diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs index 83e05d2c..f2c04225 100644 --- a/crates/ui-egui/tests/it/camera_views.rs +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::TextureCraftApp; 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)); + // 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); h } @@ -105,6 +107,7 @@ fn alt_shift_drag_orbits_in_quarter_turns() { fn slow_glide_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)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h } diff --git a/crates/ui-egui/tests/it/clone_source_view.rs b/crates/ui-egui/tests/it/clone_source_view.rs index 16297442..376391ef 100644 --- a/crates/ui-egui/tests/it/clone_source_view.rs +++ b/crates/ui-egui/tests/it/clone_source_view.rs @@ -16,6 +16,8 @@ const MARKER_STROKE: f32 = 1.2; fn clone_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 labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; execute(&mut harness.state_mut().session, "tool.clone", &serde_json::Value::Null).unwrap(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/close_unsaved.rs b/crates/ui-egui/tests/it/close_unsaved.rs index e1b74688..978e91f5 100644 --- a/crates/ui-egui/tests/it/close_unsaved.rs +++ b/crates/ui-egui/tests/it/close_unsaved.rs @@ -11,6 +11,8 @@ fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.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); h } diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 4278b0b3..8e596a4c 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -44,6 +44,8 @@ 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)); + // 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, effect) } @@ -274,6 +276,7 @@ fn color_selection_snapshots_and_quick_mask_pick() { app.ui.layout = texturecraft_ui_egui::state::ViewLayout::Only3D; app }); + harness.state_mut().ui.prefs.language = "en".into(); let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); eprintln!("Offscreen adapter: {adapter:?}"); diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index a5b321bc..cb85de57 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -19,6 +19,8 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let builder = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)); let builder = if render { builder.wgpu() } else { builder }; let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.state_mut().ui.dock.focus(Panel::Properties); diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index fdd04351..1b2447fb 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -33,6 +33,8 @@ fn dragging_an_effect_row_reorders_its_stack() { let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + // 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); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); @@ -59,6 +61,7 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); 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.state_mut().ui.prefs.language = "en".into(); 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); @@ -96,6 +99,7 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { execute(&mut session, "effect.set", &json!({"effect": effect, "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.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index 3a4a2e63..858f5816 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -22,6 +22,8 @@ fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, 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, effect) } @@ -93,6 +95,7 @@ fn content_levels_pick_the_histogram_channel() { 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.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); channel_picker(&harness).click(); diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 9cfc0071..67eb2c93 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -15,6 +15,8 @@ use library::Library; fn harness(library: &Library) -> 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)); + // 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); h.state_mut().session.load_export_presets(library.0.clone()); let base = texturecraft_engine::formats::builtin_presets().remove(0); diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index a8876e9e..b92d7a1d 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -14,6 +14,8 @@ fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.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); h } diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 36abe572..536664f7 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -18,6 +18,8 @@ fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { 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)); + // 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, effect) } @@ -174,6 +176,7 @@ fn filter_picker_snapshots_and_frame_timings() { eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info()); TextureCraftApp::new(cc, session) }); + harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(20); let start = std::time::Instant::now(); open_picker(&mut harness); diff --git a/crates/ui-egui/tests/it/frame_selection.rs b/crates/ui-egui/tests/it/frame_selection.rs index f93c8b51..d17976b9 100644 --- a/crates/ui-egui/tests/it/frame_selection.rs +++ b/crates/ui-egui/tests/it/frame_selection.rs @@ -11,6 +11,8 @@ o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0 fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.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); h } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 796051e8..6a3846bf 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -23,6 +23,8 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); let builder = if render { builder.wgpu() } else { builder }; let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.state_mut().ui.dock.focus(Panel::Properties); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 7103161b..e1f823e0 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -11,6 +11,8 @@ use texturecraft_ui_egui::docking::Panel; /// Show document history so row clicks exercise the same command dispatch as the application fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.focus(Panel::History); harness.run_steps(4); harness @@ -168,6 +170,7 @@ fn clicking_a_history_step_returns_to_it() { } let done = session.history_labels().len(); 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.state_mut().ui.dock.focus(Panel::History); h.run_steps(4); let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone(); diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs index 173a3dc9..32df131d 100644 --- a/crates/ui-egui/tests/it/import_resources.rs +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -259,6 +259,7 @@ fn import_resources_snapshot() { let dir = TempDir::new("import-resources-snapshot"); let session = Session::new_project("Resources", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); invoke(&mut h); diff --git a/crates/ui-egui/tests/it/inactive_set_hint.rs b/crates/ui-egui/tests/it/inactive_set_hint.rs index c6f1f8f1..fd884628 100644 --- a/crates/ui-egui/tests/it/inactive_set_hint.rs +++ b/crates/ui-egui/tests/it/inactive_set_hint.rs @@ -13,6 +13,8 @@ const SEARCH_STEP: f32 = 8.0; fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // 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); assert_eq!(harness.state().session.ts(), 0); assert_eq!(harness.state().session.tool.tool, Tool::Paint); diff --git a/crates/ui-egui/tests/it/layer_blending_options.rs b/crates/ui-egui/tests/it/layer_blending_options.rs index d20dc7b4..534495a1 100644 --- a/crates/ui-egui/tests/it/layer_blending_options.rs +++ b/crates/ui-egui/tests/it/layer_blending_options.rs @@ -9,6 +9,8 @@ use texturecraft_ui_egui::TextureCraftApp; 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)); + // 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); h } diff --git a/crates/ui-egui/tests/it/layer_clipboard.rs b/crates/ui-egui/tests/it/layer_clipboard.rs index efcf40c0..c6b0d32b 100644 --- a/crates/ui-egui/tests/it/layer_clipboard.rs +++ b/crates/ui-egui/tests/it/layer_clipboard.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { 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)); + // 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); let layer = h.state().session.selected_layer().unwrap(); let name = h.state().session.doc.project.layers[&layer].name.clone(); @@ -80,6 +82,7 @@ fn layer_shortcuts_act_on_a_selected_effect() { let p = serde_json::json!({"target": "content", "filter": "invert"}); let effect = id(texturecraft_engine::execute(&mut session, "effect.add.filter", &p).unwrap(), "effect"); 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 effects = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers.get(&layer).map(|l| l.content_effects.len()); h.event(egui::Event::Copy); diff --git a/crates/ui-egui/tests/it/layer_multi_select.rs b/crates/ui-egui/tests/it/layer_multi_select.rs index 92201b7c..08e09b12 100644 --- a/crates/ui-egui/tests/it/layer_multi_select.rs +++ b/crates/ui-egui/tests/it/layer_multi_select.rs @@ -16,6 +16,8 @@ fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) { let rows = ["Row A", "Row B", "Row C", "Row D"] .map(|name| LayerId(execute(&mut session, "layer.add.paint", &json!({ "name": name })).unwrap()["layer"].as_u64().unwrap())); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.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); (h, rows) } diff --git a/crates/ui-egui/tests/it/layer_rename.rs b/crates/ui-egui/tests/it/layer_rename.rs index 55b47bd9..5a5d40d2 100644 --- a/crates/ui-egui/tests/it/layer_rename.rs +++ b/crates/ui-egui/tests/it/layer_rename.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn harness() -> (Harness<'static, TextureCraftApp>, u64) { 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)); + // 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); let layer = h.state().session.selected_layer().unwrap().0; (h, layer) diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index ccbd9074..b57a1d65 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -23,6 +23,8 @@ fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.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); (h, layer) } @@ -140,6 +142,7 @@ fn hidpi_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Active one"})).unwrap(); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_pixels_per_point(2.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); (h, layer) } diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs index 3fef7357..9a08e0ad 100644 --- a/crates/ui-egui/tests/it/levels_editor.rs +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -39,6 +39,8 @@ fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraft // 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)); + // 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, effect) } diff --git a/crates/ui-egui/tests/it/mask_export.rs b/crates/ui-egui/tests/it/mask_export.rs index 808c4055..fce6ba7f 100644 --- a/crates/ui-egui/tests/it/mask_export.rs +++ b/crates/ui-egui/tests/it/mask_export.rs @@ -23,6 +23,8 @@ fn harness(mask: bool) -> Harness<'static, TextureCraftApp> { execute(&mut session, "effect.add.fill", &json!({"value": 0.5})).unwrap(); } let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.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); h } diff --git a/crates/ui-egui/tests/it/mask_value_swap.rs b/crates/ui-egui/tests/it/mask_value_swap.rs index d5f22ebc..54c7c088 100644 --- a/crates/ui-egui/tests/it/mask_value_swap.rs +++ b/crates/ui-egui/tests/it/mask_value_swap.rs @@ -10,6 +10,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { texturecraft_engine::execute(&mut session, "mask.add.white", &serde_json::Value::Null).unwrap(); session.target = StackTarget::Mask; let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, 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 diff --git a/crates/ui-egui/tests/it/named_layouts.rs b/crates/ui-egui/tests/it/named_layouts.rs index 18264949..d63c4017 100644 --- a/crates/ui-egui/tests/it/named_layouts.rs +++ b/crates/ui-egui/tests/it/named_layouts.rs @@ -11,6 +11,8 @@ fn 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)).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(4); harness } diff --git a/crates/ui-egui/tests/it/nav_buttons.rs b/crates/ui-egui/tests/it/nav_buttons.rs index 9138d0e9..edaae448 100644 --- a/crates/ui-egui/tests/it/nav_buttons.rs +++ b/crates/ui-egui/tests/it/nav_buttons.rs @@ -18,6 +18,8 @@ const WINDOW: egui::Vec2 = vec2(1280.0, 800.0); fn app(layout: ViewLayout) -> (Harness<'static, TextureCraftApp>, Rect) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(WINDOW).with_pixels_per_point(1.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.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; harness.state_mut().ui.layout = ViewLayout::Only3D; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs index d171b8ef..e964a609 100644 --- a/crates/ui-egui/tests/it/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -20,6 +20,8 @@ fn harness_for(dir: &Path) -> Harness<'static, TextureCraftApp> { std::fs::write(&mesh, TWO_MATERIALS).unwrap(); 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)); + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); h.state_mut().ui.windows.new_project = true; h.state_mut().ui.new_project.resolution = 256; h.state_mut().ui.new_project.file = Some(mesh.display().to_string()); @@ -134,6 +136,7 @@ fn new_project_baked_maps_snapshots() { eprintln!("snapshot adapter: {adapter:?}"); TextureCraftApp::new(cc, session) }); + h.state_mut().ui.prefs.language = "en".into(); let dir = TempDir::new("new-project-baked-maps-snapshots"); let mesh = dir.join("Ball.obj"); std::fs::write(&mesh, TWO_MATERIALS).unwrap(); diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index f24e6b46..59d6eb1f 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -23,6 +23,8 @@ fn harness() -> AppHarness<'static> { execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); // Tall enough that the 2D view's texture square takes A, B and C let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.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.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); h @@ -157,6 +159,7 @@ fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { let path = session.tool.path.clone(); let history = session.history_labels(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Split; harness.run_steps(4); let view_3d = harness.state().viewport_rect; @@ -214,6 +217,7 @@ fn split_harness() -> (AppHarness<'static>, Pos2, Pos2) { execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Split; harness.run_steps(4); let view_3d = harness.state().viewport_rect; diff --git a/crates/ui-egui/tests/it/path_list.rs b/crates/ui-egui/tests/it/path_list.rs index 799ba000..eadf8fd9 100644 --- a/crates/ui-egui/tests/it/path_list.rs +++ b/crates/ui-egui/tests/it/path_list.rs @@ -15,6 +15,8 @@ fn path_rows_edit_and_remove_paths() { let eid = LayerId(r["committed"]["effect"].as_u64().unwrap()); execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).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); let editing = |h: &Harness<'_, TextureCraftApp>| h.state().session.tool.path.editing; let count = |h: &Harness<'_, TextureCraftApp>| h.state().session.paths(eid).map_or(0, <[_]>::len); diff --git a/crates/ui-egui/tests/it/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs index 36b67d2b..68ce339d 100644 --- a/crates/ui-egui/tests/it/pen_pressure.rs +++ b/crates/ui-egui/tests/it/pen_pressure.rs @@ -25,6 +25,8 @@ fn frame(harness: &mut Harness<'_, TextureCraftApp>, pen: Option<(TouchPhase, Op fn paint_2d(input: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) -> f64 { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.state_mut().session.tool.brush.min_size = 0.0; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index ab50cb53..d24e3c0b 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::TextureCraftApp; fn polygon_fill_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.tool = Tool::PolygonFill; harness.run_steps(4); harness @@ -132,6 +134,7 @@ fn polygon_fill_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info(); eprintln!("Offscreen adapter: {} ({:?}), driver {} {}", adapter.name, adapter.backend, adapter.driver, adapter.driver_info); harness.state_mut().session.tool.tool = Tool::PolygonFill; diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 1371e05b..b8511f20 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -815,6 +815,7 @@ fn project_config_snapshots() { let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); session.doc.project.mesh_path = file.display().to_string(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); h.run_steps(6); open_window(&mut h); h.run_steps(6); diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 8d3b413f..8addb99a 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::state::{Mode, ViewLayout}; fn harness() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // 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 } diff --git a/crates/ui-egui/tests/it/shelf_click.rs b/crates/ui-egui/tests/it/shelf_click.rs index bc11cfdb..bc3708dc 100644 --- a/crates/ui-egui/tests/it/shelf_click.rs +++ b/crates/ui-egui/tests/it/shelf_click.rs @@ -13,6 +13,8 @@ const SMART_TYPE: usize = 1; fn shelf(tab: usize, label: &str) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1920.0, 1032.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.state_mut().ui.shelf_tab = tab; harness.state_mut().ui.shelf_filter = label.to_lowercase(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 56e57f62..747e7883 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -20,6 +20,8 @@ const MENU_REACH: f32 = 60.0; fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // 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); assert_eq!(harness.state().session.ts(), 0); harness diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index 237de107..215d5dd2 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -28,6 +28,8 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static .with_step_dt(step_seconds) .with_pixels_per_point(pixels_per_point) .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.state_mut().ui.shelf_tab = MATERIALS_TAB; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index d8b7a30c..926b80d3 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -30,6 +30,8 @@ const REFERENCE_COLUMNS: usize = 4; fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).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.state_mut().ui.shelf_tab = MATERIALS_TYPE; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/shift_lines_2d.rs b/crates/ui-egui/tests/it/shift_lines_2d.rs index 08537f4f..11192e0a 100644 --- a/crates/ui-egui/tests/it/shift_lines_2d.rs +++ b/crates/ui-egui/tests/it/shift_lines_2d.rs @@ -31,6 +31,8 @@ const BESIDE_LINE_IN_RADII: f32 = 3.0; fn uv_view_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness @@ -254,6 +256,7 @@ fn shift_line_snapshots() { eprintln!("Shift-line snapshot adapter: {:?}", adapter.get_info()); TextureCraftApp::new(context, session) }); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); click(&mut harness, FIRST_CLICK, false); diff --git a/crates/ui-egui/tests/it/shift_lines_3d.rs b/crates/ui-egui/tests/it/shift_lines_3d.rs index 2c009a9b..0f181c1a 100644 --- a/crates/ui-egui/tests/it/shift_lines_3d.rs +++ b/crates/ui-egui/tests/it/shift_lines_3d.rs @@ -23,6 +23,8 @@ const SEARCH_REACH: f32 = 300.0; fn view_3d_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 labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only3D; harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs index 3d10749b..b3776540 100644 --- a/crates/ui-egui/tests/it/shortcut_keys.rs +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -10,6 +10,8 @@ use texturecraft_ui_egui::state::ViewLayout; 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)); + // 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); h } diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index dd3b5d02..def255aa 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -15,6 +15,8 @@ fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.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.state_mut().ui.mode = Mode::Baking; h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs index 63826cd1..badd1c8c 100644 --- a/crates/ui-egui/tests/it/smudge_channels.rs +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -13,6 +13,8 @@ use texturecraft_ui_egui::state::PropsTab; fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, 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); run(&mut harness, "tool.smudge", Value::Null); harness diff --git a/crates/ui-egui/tests/it/snapped_lines.rs b/crates/ui-egui/tests/it/snapped_lines.rs index 44a37b86..992eb26c 100644 --- a/crates/ui-egui/tests/it/snapped_lines.rs +++ b/crates/ui-egui/tests/it/snapped_lines.rs @@ -28,6 +28,8 @@ const MAX_DIFFERENCE: f32 = 0.01; fn app(layout: ViewLayout) -> 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 labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = layout; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/split_divider.rs b/crates/ui-egui/tests/it/split_divider.rs index 98a6c39c..e869d1c6 100644 --- a/crates/ui-egui/tests/it/split_divider.rs +++ b/crates/ui-egui/tests/it/split_divider.rs @@ -37,6 +37,8 @@ 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 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 } diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index 030e709a..7a64389d 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -26,6 +26,8 @@ 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)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.tool = Tool::Paint; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/symmetry_2d.rs b/crates/ui-egui/tests/it/symmetry_2d.rs index 29025dcd..6336eaaa 100644 --- a/crates/ui-egui/tests/it/symmetry_2d.rs +++ b/crates/ui-egui/tests/it/symmetry_2d.rs @@ -14,6 +14,8 @@ const CLICK: Pos2 = pos2(700.0, 420.0); fn uv_view_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.layout = ViewLayout::Only2D; harness.run_steps(4); harness diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index cc6d97ff..63fa59b6 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -25,6 +25,8 @@ fn select_nothing(session: &mut Session) { fn app_harness() -> 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(|context| TextureCraftApp::new(context, 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 } @@ -139,6 +141,7 @@ fn bake_painting_turns_on_the_shelf_paint_tool() { 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, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); assert!(shelf_button_disabled(&harness, "Paint (1)"), "nothing is being painted yet"); @@ -189,6 +192,7 @@ fn tool_availability_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { for (brightness, suffix) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; diff --git a/crates/ui-egui/tests/it/tool_settings_saved.rs b/crates/ui-egui/tests/it/tool_settings_saved.rs index b5c5fd73..597f98e1 100644 --- a/crates/ui-egui/tests/it/tool_settings_saved.rs +++ b/crates/ui-egui/tests/it/tool_settings_saved.rs @@ -11,6 +11,8 @@ use memory_storage::MemoryStorage; fn saving_the_app_stores_the_current_brush_and_tool_settings() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, 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(2); let tool = &mut harness.state_mut().session.tool; tool.brush.size = 0.37; diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs index 23fa3e40..02eab838 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -19,6 +19,10 @@ fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> theme::apply(context, theme::Brightness::default(), theme::Accent::default()); }) .build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + // Only the toolbar is painted, so no frame applies the preference: set the language itself + texturecraft_ui_egui::i18n::set_language("en"); harness.run_steps(4); harness } @@ -200,6 +204,9 @@ fn toolbar_window_snapshots() { std::fs::create_dir_all(&directory).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + // Only the toolbar is painted, so no frame applies the preference: set the language itself + texturecraft_ui_egui::i18n::set_language("en"); harness.state_mut().session.tool.tool = Tool::Path; harness.state_mut().session.tool.brush.lazy = 20.0; for (width, scale) in [(1600.0, 1.0), (960.0, 1.0), (960.0, 1.5)] { diff --git a/crates/ui-egui/tests/it/user_smart_mask.rs b/crates/ui-egui/tests/it/user_smart_mask.rs index da94ccda..4b7d186d 100644 --- a/crates/ui-egui/tests/it/user_smart_mask.rs +++ b/crates/ui-egui/tests/it/user_smart_mask.rs @@ -16,6 +16,8 @@ fn harness(prepare: impl FnOnce(&mut texturecraft_engine::Session)) -> Harness<' let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); prepare(&mut session); 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(4); harness } diff --git a/crates/ui-egui/tests/list_panels.rs b/crates/ui-egui/tests/list_panels.rs index afec1051..e0c7a4a9 100644 --- a/crates/ui-egui/tests/list_panels.rs +++ b/crates/ui-egui/tests/list_panels.rs @@ -51,6 +51,8 @@ fn the_history_list_fills_a_tall_panel() { } 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(); dock_in_left_column(&mut harness, "History"); harness.run_steps(STARTUP_FRAMES); @@ -63,6 +65,7 @@ fn the_history_list_fills_a_tall_panel() { fn the_log_list_fills_a_tall_panel() { 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)); + harness.state_mut().ui.prefs.language = "en".into(); for line in 0..ROWS { harness.state_mut().session.log.push(format!("Log line {line}")); } From 088aa4eb069783a4bed320883a6a3452f731d27c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 21 Nov 2026 22:00:14 +0100 Subject: [PATCH 04/80] feat(render): add IOR-based dielectric reflection Let Metallic/Roughness projects opt into dielectric F0 derived from the index of refraction. Share the Specular Level multiplier across the viewport, CPU and GPU path tracing, and the derived F0 texture export. Store the choice with projects and templates. Keep the legacy factor for existing projects and authored RGB F0 in Specular/Glossiness. --- crates/core/src/project.rs | 18 ++++++++++++++++++ crates/engine/src/template_cmds.rs | 7 ++++++- crates/engine/src/view_cmds.rs | 5 ++++- crates/formats/src/export/mod.rs | 6 ++++-- crates/render/src/gpu_trace.rs | 4 +++- crates/render/src/renderer.rs | 7 ++++++- crates/render/src/shaders/mesh.wgsl | 5 +++-- crates/render/src/shaders/trace.wgsl | 4 ++-- crates/render/src/trace.rs | 8 ++++++-- crates/ui-egui/src/shader_settings.rs | 13 ++++++++++--- docs/control-protocol.md | 2 ++ 11 files changed, 64 insertions(+), 15 deletions(-) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ce14606b..8b2c70f1 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -312,6 +312,8 @@ pub struct DisplaySettings { pub scatter_radius: f32, /// Index of refraction of transmissive surfaces (where the Transmission channel is painted). pub ior: f32, + /// Use IOR to determine dielectric reflectance at normal incidence in Metallic/Roughness. + pub ior_specular: bool, /// Depth of field of the viewport and the path tracer (thin lens). pub dof: DepthOfField, } @@ -367,11 +369,26 @@ pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast /// Prefix of [`DisplaySettings::environment`] naming an image resource. pub const ENV_RESOURCE_PREFIX: &str = "resource:"; +/// Original dielectric F0 multiplier for the Specular Level channel. +pub const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; + impl DisplaySettings { /// The image resource used as the environment, if any. pub fn environment_resource(&self) -> Option<&str> { self.environment.strip_prefix(ENV_RESOURCE_PREFIX) } + + /// Multiplier for Specular Level in the Metallic/Roughness model. + pub fn dielectric_f0_scale(&self) -> f32 { + if self.ior_specular && !self.spec_gloss && self.ior.is_finite() { + let ior = self.ior.clamp(1.0, 3.0); + let fresnel = (ior - 1.0) / (ior + 1.0); + // Specular Level 0.5 represents OpenPBR's default specular weight of 1. + 2.0 * fresnel * fresnel + } else { + LEGACY_DIELECTRIC_F0_SCALE + } + } } impl Default for DisplaySettings { @@ -402,6 +419,7 @@ impl Default for DisplaySettings { scatter_color: [1.0, 0.4, 0.25], scatter_radius: 0.1, ior: 1.5, + ior_specular: false, dof: DepthOfField::default(), } } diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index 27de192d..3c227b01 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -36,6 +36,7 @@ pub struct ProjectTemplate { pub spec_gloss: bool, pub parallax: bool, pub ior: f32, + pub ior_specular: bool, pub scatter_color: [f32; 3], pub scatter_radius: f32, } @@ -51,6 +52,7 @@ impl Default for ProjectTemplate { spec_gloss: d.spec_gloss, parallax: d.parallax, ior: d.ior, + ior_specular: d.ior_specular, scatter_color: d.scatter_color, scatter_radius: d.scatter_radius, } @@ -116,7 +118,7 @@ pub fn specs() -> Vec { "Project templates", [], None, - "{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss}]", + "{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss, iorSpecular}]", always, list ), @@ -196,6 +198,7 @@ impl Session { p.normal_format = t.normal_format; let d = &mut p.display; (d.spec_gloss, d.parallax, d.ior, d.scatter_color, d.scatter_radius) = (t.spec_gloss, t.parallax, t.ior, t.scatter_color, t.scatter_radius); + d.ior_specular = t.ior_specular; for ts in 0..p.texture_sets.len() { if let Some(set) = p.texture_sets.get_mut(ts) { set.channels = t.channels.clone(); @@ -277,6 +280,7 @@ fn list(s: &mut Session, _: &Value) -> Result { "normalFormat": if t.normal_format == NormalFormat::DirectX { "directX" } else { "openGl" }, "channels": t.channels.iter().map(|(c, _)| c.id()).collect::>(), "specGloss": t.spec_gloss, + "iorSpecular": t.ior_specular, }) }; Ok(json!(builtin_templates().iter().map(|t| entry(t, true)).chain(s.templates.list.iter().map(|t| entry(t, false))).collect::>())) @@ -296,6 +300,7 @@ fn save(session: &mut Session, params: &Value) -> Result { spec_gloss: display.spec_gloss, parallax: display.parallax, ior: display.ior, + ior_specular: display.ior_specular, scatter_color: display.scatter_color, scatter_radius: display.scatter_radius, }; diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index e8161c8e..e1d01fd7 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -68,7 +68,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), iorSpecular? (use IOR for dielectric reflectance at normal incidence in Metallic Roughness), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}", always, display ), @@ -297,6 +297,7 @@ fn display(s: &mut Session, p: &Value) -> Result { let scatter_color = color_param("display.set", p, "scatterColor")?; let d = &mut s.doc.project.display; + let (old_ior, old_ior_specular, old_spec_gloss) = (d.ior, d.ior_specular, d.spec_gloss); if let Some(e) = env { d.environment = e; } @@ -349,6 +350,7 @@ fn display(s: &mut Session, p: &Value) -> Result { ("postEffects", &mut d.post_effects), ("taa", &mut d.taa), ("specGloss", &mut d.spec_gloss), + ("iorSpecular", &mut d.ior_specular), ("parallax", &mut d.parallax), ("displacement", &mut d.displacement), ("soloUnlit", &mut d.solo_unlit), @@ -358,6 +360,7 @@ fn display(s: &mut Session, p: &Value) -> Result { } } + s.modified |= d.ior_specular != old_ior_specular || (d.ior_specular && (d.ior != old_ior || d.spec_gloss != old_spec_gloss)); // The field of view applies to the view only when set (a saved camera keeps its own) if f32p(p, "fov").is_some() { s.camera.fov = s.doc.project.display.fov; diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index cdcb9c36..31b8b626 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -196,7 +196,7 @@ pub enum VirtualMap { Glossiness, /// Baked AO × AO channel (per the texture set's AO mixing). AoMixed, - /// Dielectric reflectance at normal incidence: 0.08 × specular level. + /// Dielectric reflectance at normal incidence: Specular Level scaled by the project's shader settings. F0, /// 1 − glossiness (specular/glossiness projects). Roughness, @@ -742,6 +742,7 @@ struct Sampler<'a> { /// Normal convention overriding every normal output. normal_override: Option, project_normal: NormalFormat, + dielectric_f0_scale: f32, } fn unpack(v: [f32; 3]) -> Vec3 { @@ -828,7 +829,7 @@ impl Sampler<'_> { VirtualMap::NormalOpenGl => self.normal(at, NormalFormat::OpenGl, cache), VirtualMap::NormalDirectX => self.normal(at, NormalFormat::DirectX, cache), VirtualMap::Glossiness => [1.0 - self.channel(Channel::Roughness, at)[0]; 3], - VirtualMap::F0 => [0.08 * self.channel(Channel::SpecularLevel, at)[0]; 3], + VirtualMap::F0 => [self.dielectric_f0_scale * self.channel(Channel::SpecularLevel, at)[0]; 3], VirtualMap::Roughness => [1.0 - self.channel(Channel::Glossiness, at)[0]; 3], VirtualMap::SheenTint => self.channel(Channel::SheenColor, at).map(|c| c * self.channel(Channel::SheenWeight, at)[0]), VirtualMap::HeightNormal => { @@ -900,6 +901,7 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result, ior: f32, + dielectric_f0_scale: f32, /// Focus depth (0: the orbit target) and lens radius in world units (0: pinhole). lens: [f32; 2], } @@ -418,6 +419,7 @@ impl GpuTracer { env_camera: scene.env_camera, heights: scene.sets.iter().map(|s| s.height_strength).collect(), ior: scene.ior, + dielectric_f0_scale: scene.dielectric_f0_scale, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), }); Ok(()) @@ -609,7 +611,7 @@ impl GpuTracer { env: [sin, cos, 0.0, 0.0], sigma: sc.sigma.extend(0.0).to_array(), eye: cam.eye().extend(1.0).to_array(), - lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, 0.0], + lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, sc.dielectric_f0_scale], }; let mut sets = [[0.0f32; 4]; 256]; for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() { diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 5e0561af..a1717936 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -25,6 +25,7 @@ use std::collections::HashMap; use bytemuck::{Pod, Zeroable}; use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_core::project::LEGACY_DIELECTRIC_F0_SCALE; use texturecraft_core::{Channel, DisplaySettings, EnvAlignment, Project, ToneMapping}; use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; @@ -206,6 +207,8 @@ pub struct Shade { pub scatter: [f32; 3], /// Index of refraction of the Transmission channel. pub ior: f32, + /// Multiplier for Specular Level when shading a dielectric in Metallic/Roughness. + pub dielectric_f0_scale: f32, /// Depth of field (3D material view): focus depth along the view axis (0: the orbit /// target) and lens radius as a fraction of the mesh's bounding radius. pub dof: Option<[f32; 2]>, @@ -258,6 +261,7 @@ impl Shade { taa: d.taa, scatter: scatter_wrap(d), ior: d.ior, + dielectric_f0_scale: d.dielectric_f0_scale(), dof: d.dof.enabled.then_some([d.dof.focus_distance, d.dof.aperture]), displacement: d.displacement, solo_lit: !d.solo_unlit, @@ -313,6 +317,7 @@ impl Default for Shade { taa: false, scatter: scatter_wrap(&DisplaySettings::default()), ior: 1.5, + dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE, dof: None, sss_blur: None, refraction: false, @@ -2124,7 +2129,7 @@ impl Renderer { scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }], fwd: [fwd.x, fwd.y, fwd.z, 0.0], disp, - refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], + refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, s.dielectric_f0_scale], highlight: highlight_globals(s, data), highlight_shift: highlight_shift(frame.size), ..bake_globals(s.bake) diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 31fd19df..9dde8ff3 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -23,7 +23,7 @@ struct Globals { scatter: vec4, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1) fwd: vec4, // xyz camera view direction (unit), w - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - - refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - + refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w dielectric F0 scale highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - bake_high: vec4, // bake mode: rgb high poly color, a - @@ -529,7 +529,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let rough = clamp(orm.g, SPECULAR_ROUGHNESS_FLOOR, 1.0); let metal = orm.b; let nov = clamp(abs(dot(n, v)), GRAZING_COSINE_FLOOR, 1.0); - var f0 = mix(vec3(0.08 * orm.a), albedo, metal); + let dielectric_f0_scale = select(g.refr.w, 0.08, solo_lit); + var f0 = mix(vec3(dielectric_f0_scale * orm.a), albedo, metal); var diffuse_col = albedo * (1.0 - metal); if (g.material.x > 0.5 && !solo_lit) { // Specular color gives F0 (a solo-lit channel view keeps its neutral material); remove its energy from diffuse diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index 5f6258e0..b4a4bba2 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -17,7 +17,7 @@ struct Params { env: vec4, // sin and cos of the environment rotation sigma: vec4, // subsurface extinction per color channel eye: vec4, // camera position - lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR + lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR, dielectric F0 scale // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds, height strength. sets: array, MAX_SETS>, }; @@ -332,7 +332,7 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { metallic = clamp(orm.b, 0.0, 1.0); let level = clamp(orm.a, 0.0, 1.0); diffuse = base * (1.0 - metallic); - f0 = mix(vec3(0.08 * level), base, metallic); + f0 = mix(vec3(P.lens.w * level), base, metallic); } // The coat normal packs x and y around 128 so flat stays exact diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 034330b0..1cfaf68f 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -23,7 +23,7 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_compose::{Composite, ImageRes}; use texturecraft_core::Channel; -use texturecraft_core::project::{DisplaySettings, EnvAlignment, ToneMapping}; +use texturecraft_core::project::{DisplaySettings, EnvAlignment, LEGACY_DIELECTRIC_F0_SCALE, ToneMapping}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera}; @@ -63,6 +63,8 @@ pub struct TraceScene { pub(crate) radius: f32, /// Index of refraction of the Transmission channel. pub ior: f32, + /// Multiplier for Specular Level in the Metallic/Roughness model. + pub(crate) dielectric_f0_scale: f32, /// Thin lens: focus depth along the view axis (0: the camera's orbit target) and lens radius /// as a fraction of the mesh's bounding radius (the viewport's depth of field). pub lens: Option<[f32; 2]>, @@ -103,6 +105,7 @@ impl TraceScene { scatter_sigma: Vec3::ONE, radius, ior: 1.5, + dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE, lens: None, }; let d = DisplaySettings::default(); @@ -137,6 +140,7 @@ impl TraceScene { scene.spec_gloss = display.spec_gloss; scene.set_scatter(display.scatter_color, display.scatter_radius); scene.ior = display.ior; + scene.dielectric_f0_scale = display.dielectric_f0_scale(); scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]); scene @@ -606,7 +610,7 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 } else { let metallic = ch(Channel::Metallic, 0, 0)[0].clamp(0.0, 1.0); let level = ch(Channel::SpecularLevel, 0, 0)[0].clamp(0.0, 1.0); - (base * (1.0 - metallic), Vec3::splat(0.08 * level).lerp(base, metallic), metallic) + (base * (1.0 - metallic), Vec3::splat(scene.dielectric_f0_scale * level).lerp(base, metallic), metallic) }; let coat_base = if n_geo.dot(-d) > 0.0 { n_geo } else { geo }; let coat_n = match set { diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index ba00a046..42018c2d 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -70,8 +70,9 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { header(ui); let mut display = app.session.doc.project.display.clone(); + let mut ior_specular = display.ior_specular; section_page::show(ui, "shader_settings", &SECTIONS, |ui, index| match index { - 0 => shader_parameters(ui, &mut display), + 0 => shader_parameters(ui, &mut display, &mut ior_specular), _ => displacement(ui, &mut display), }); @@ -80,6 +81,9 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { app.session.modified = true; app.session.revision = app.session.revision.wrapping_add(1); } + if ior_specular != app.session.doc.project.display.ior_specular { + app.run("display.set", serde_json::json!({"iorSpecular": ior_specular})); + } } /// Undo and Redo of the shader's settings, the shader button and the instance name @@ -139,7 +143,7 @@ pub fn matches_query(name: &str, query: &str) -> bool { } /// Base Surface, Specular, Transmission and Subsurface -fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) { +fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings, ior_specular: &mut bool) { let tokens = Tokens::get(ui.ctx()); section(ui, "shader_base_surface", tr("Base Surface"), true, |ui| { shader_model(ui, display); @@ -148,8 +152,11 @@ fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) { section(ui, "shader_specular", tr("Specular"), true, |ui| { unavailable::checkbox(ui, false, tr("Enable anisotropy")); slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( - "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "Controls how strongly transmissive surfaces bend light. When the checkbox below is on, it also controls dielectric reflectance.", )); + ui.add_enabled(!display.spec_gloss, egui::Checkbox::new(ior_specular, tr("Use IOR for specular reflection"))) + .on_hover_text(tr("Uses the index of refraction for dielectric reflectance at normal incidence. Specular level adjusts its strength.")) + .on_disabled_hover_text(tr("Specular Glossiness uses the Specular color channel for reflectance.")); unavailable::checkbox(ui, false, tr("Enable specular color")); }); section(ui, "shader_transmission", tr("Transmission"), true, |ui| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bd11cb2d..fcb7b5e2 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -549,6 +549,8 @@ None is an undo step. `display.set` also takes `alignment` (`world` or `camera`: the environment, and the key light with it, turns with the camera about the vertical axis), `shadowMode` (`intensive`, `average` or `lightweight`, the default: the shadow map's resolution) and `shadowOpacity` (0 to 1, default 1: how dark the shadows are). +Set `iorSpecular` to true to use `ior` for dielectric reflectance at normal incidence in the +Metallic Roughness model. The setting defaults to false and is saved with the project and its templates. `viewport.view {mode: "image", image: }` shows a project image as it is, stretched over the UV square, on the mesh and in the 2D view (the view picker's "Other..."). `display.set {soloUnlit}` From ead50b5e8756b602de2a340ae95d1d6c9a4dbb8c Mon Sep 17 00:00:00 2001 From: supersfera Date: Sat, 21 Nov 2026 19:42:25 -0800 Subject: [PATCH 05/80] Add Russian translation (ru). Register Russian in LANGUAGES and add Russian strings to the Linux desktop, AppStream, and MIME metadata. Copyright (c) 2026 SuperSfera LLC, MIT OR Apache-2.0. --- crates/ui-egui/src/i18n.rs | 3 ++- .../linux/ai.storyteller.texturecraft.desktop | 5 +++++ .../ai.storyteller.texturecraft.metainfo.xml.in | 15 +++++++++++++++ .../linux/ai.storyteller.texturecraft.mime.xml | 13 +++++++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index bbbea0ec..a08fe1a2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -37,7 +37,7 @@ pub struct Language { pub english: &'static str, } -const COUNT: usize = 10; +const COUNT: usize = 11; pub static LANGUAGES: [Language; COUNT] = [ Language { code: "en", name: "English", english: "English" }, @@ -50,6 +50,7 @@ pub static LANGUAGES: [Language; COUNT] = [ Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" }, Language { code: "ko", name: "한국어", english: "Korean" }, Language { code: "ar", name: "العربية", english: "Arabic" }, + Language { code: "ru", name: "Русский", english: "Russian" }, ]; static CURRENT: AtomicUsize = AtomicUsize::new(0); diff --git a/packaging/linux/ai.storyteller.texturecraft.desktop b/packaging/linux/ai.storyteller.texturecraft.desktop index ded29c5d..e1cb409a 100644 --- a/packaging/linux/ai.storyteller.texturecraft.desktop +++ b/packaging/linux/ai.storyteller.texturecraft.desktop @@ -1,8 +1,12 @@ +# Russian translation © 2026 SuperSfera LLC, MIT OR Apache-2.0 [Desktop Entry] Type=Application Name=TextureCraft +Name[ru]=TextureCraft GenericName=3D Texture Painter +GenericName[ru]=Рисование 3D-текстур Comment=Paint PBR textures directly on 3D meshes +Comment[ru]=Рисование PBR-текстур прямо на 3D-моделях Exec=texturecraft %F TryExec=texturecraft Icon=ai.storyteller.texturecraft @@ -11,4 +15,5 @@ StartupNotify=true StartupWMClass=texturecraft Categories=Graphics;3DGraphics; Keywords=texture;paint;pbr;material;3d;mesh;bake;gltf;fbx;usd; +Keywords[ru]=текстура;рисование;pbr;материал;3d;сетка;меш;запекание;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/ai.storyteller.texturecraft.metainfo.xml.in b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in index e04f156c..9b14d960 100644 --- a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in +++ b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in @@ -7,6 +7,7 @@ MIT OR Apache-2.0 TextureCraft Paint PBR textures directly on 3D meshes + Рисование PBR-текстур прямо на 3D-моделях Learning Machines LLC @@ -16,11 +17,21 @@ expect: familiar menus, shortcuts, panels and tools, with texture sets, layers, masks, fills and effects painted straight onto the model.

+

+ TextureCraft — открытая нативная программа для рисования 3D-текстур, устроенная так, + как привыкли художники по текстурам: знакомые меню, сочетания клавиш, панели и + инструменты, а наборы текстур, слои, маски, заливки и эффекты наносятся прямо на + модель. +

  • Open glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY and STL meshes and save projects as .tcraft
  • +
  • Открытие сеток glTF/GLB, FBX, COLLADA, USD (USDA/USDC/USDZ), Alembic, OBJ, PLY и STL и сохранение проектов в .tcraft
  • Paint base colour, roughness, metallic, normal and height together with PBR brushes
  • +
  • Рисование базового цвета, шероховатости, металличности, нормалей и высоты одновременно с помощью PBR-кистей
  • Bake mesh maps and export texture sets as PNG, EXR, TGA, JPEG or TIFF
  • +
  • Запекание карт сетки и экспорт наборов текстур в PNG, EXR, TGA, JPEG или TIFF
  • Every action is a command, scriptable from a CLI and a JSON control channel
  • +
  • Каждое действие — это команда, которую можно вызывать из CLI и через управляющий канал JSON
ai.storyteller.texturecraft.desktop @@ -36,9 +47,13 @@ texture painting + рисование текстур pbr + pbr 3d + 3d mesh + сетка #f0c39c diff --git a/packaging/linux/ai.storyteller.texturecraft.mime.xml b/packaging/linux/ai.storyteller.texturecraft.mime.xml index cf5204b3..2b1b811e 100644 --- a/packaging/linux/ai.storyteller.texturecraft.mime.xml +++ b/packaging/linux/ai.storyteller.texturecraft.mime.xml @@ -1,16 +1,19 @@ + TextureCraft project + Проект TextureCraft glTF binary model + Двоичная модель glTF @@ -18,11 +21,13 @@ glTF model + Модель glTF FBX model + Модель FBX @@ -30,11 +35,13 @@ COLLADA model + Модель COLLADA Universal Scene Description + Universal Scene Description @@ -44,17 +51,20 @@ Universal Scene Description (text) + Universal Scene Description (текст) Universal Scene Description package + Пакет Universal Scene Description Alembic model + Модель Alembic @@ -62,11 +72,13 @@ Wavefront OBJ model + Модель Wavefront OBJ PLY model + Модель PLY @@ -75,6 +87,7 @@ STL model + Модель STL From e4585fb2b34234e7a5f4b58ee0db1f744e500048 Mon Sep 17 00:00:00 2001 From: supersfera Date: Sat, 21 Nov 2026 20:23:02 -0800 Subject: [PATCH 06/80] ru: update language-script test for Cyrillic --- crates/ui-egui/src/fonts.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b31b423a..5a5eb801 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -279,8 +279,9 @@ mod tests { assert_eq!(Script::of_language("ar"), Some(Script::Arabic)); assert_eq!(Script::of_language("de"), None); for l in &crate::i18n::LANGUAGES { - // Past the Latin blocks and their diacritics. - let other_script = l.name.chars().any(|c| c > '\u{036F}'); + // Past the Latin blocks and their diacritics. Cyrillic is already in the + // interface font (Inter / Ubuntu-Light), so Russian needs no fallback script. + let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } } From 03169492d7dc5cb44522ad407e96e556eed9dd2a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 13:10:17 +0100 Subject: [PATCH 07/80] Toggle layer effects from their thumbnails --- crates/ui-egui/src/dock.rs | 177 ++++++++++++----------- crates/ui-egui/src/layer_panel.rs | 26 ++-- crates/ui-egui/tests/it/effect_rows.rs | 5 + crates/ui-egui/tests/it/layers_panel.rs | 121 +++++++++++----- crates/ui-egui/tests/it/rename_anchor.rs | 20 ++- 5 files changed, 220 insertions(+), 129 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 7f8cebfe..9136689f 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -209,6 +209,12 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { 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); app.layer_panel.begin(&app.session, now); + let selected_stack = app.session.selected_layer().map(|layer| (layer, !targets_content(app))); + if matches!(app.session.target, StackTarget::Effect(_)) { + app.layer_panel.expanded_effects = selected_stack; + } else if app.layer_panel.expanded_effects != selected_stack { + app.layer_panel.expanded_effects = None; + } egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { let mut count = 0; for id in stack { @@ -241,6 +247,15 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { } }); select_all_layers(app, ui); + // A thumbnail or selection can close the editor before its TextEdit sees lost focus. + if let Some((id, _)) = &app.ui.rename + && let Some((owner, _)) = app.session.doc.project.effect(LayerId(*id)) + && app.layer_panel.expanded_effects.is_none_or(|(layer, in_mask)| { + layer != owner || !app.session.doc.project.layers.get(&layer).is_some_and(|l| stack_effects(l, in_mask).iter().any(|e| e.id.0 == *id)) + }) + { + finish_effect_rename(app); + } } /// Ctrl+A (Cmd+A on macOS) with the pointer over the Layers panel selects every row shown in the @@ -382,6 +397,7 @@ const EYE_CHIP_ROUNDING: f32 = 4.0; /// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. const THUMBNAIL_ROUNDING: f32 = 2.0; const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; +const EFFECT_DISCLOSURE_SIZE: f32 = 13.0; const HIDDEN_STRIKE_WIDTH: f32 = 1.5; const DROP_LINE_WIDTH: f32 = 2.0; /// The eye's size and the column it sits in (the eye and a gap before the thumbnail). @@ -442,23 +458,12 @@ const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; /// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. const EFFECT_BLEND_WIDTH: f32 = 82.0; const EFFECT_OPACITY_WIDTH: f32 = 36.0; -/// Height of the "Content effects" / "Mask effects" header rows. -const GROUP_HEADER_H: f32 = 20.0; - -// Group header spacing leaves room for the label and effect count -const GROUP_HEADER_CARET_OFFSET: f32 = 15.0; -const GROUP_HEADER_LABEL_GAP: f32 = 10.0; -const GROUP_HEADER_LABEL_RESERVE: f32 = 28.0; -const GROUP_HEADER_COUNT_PADDING: f32 = 8.0; -const GROUP_HEADER_LABEL_FONT_SIZE: f32 = 10.5; /// Hover tint of alternating layer rows const ALTERNATE_LAYER_SHADE: f32 = 0.45; /// Maximum layer-tree nesting shown by the dock const MAX_LAYER_TREE_DEPTH: usize = 12; /// Checkerboard cells along each thumbnail edge const THUMB_CHECKER_CELLS: usize = 4; -/// Keep the group label and count readable when the panel is narrow -const GROUP_HEADER_MIN_REMAINING_WIDTH: f32 = 90.0; /// Keep both thumbnail targets inside the row before spending space on indentation fn layer_thumbnail_layout(width: f32, depth: usize, folder: bool, preferred_size: f32) -> (f32, f32) { @@ -492,18 +497,23 @@ fn level_x(left: f32, level: usize) -> f32 { left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5 } +fn stack_effects(layer: &Layer, in_mask: bool) -> &[Effect] { + if in_mask { layer.mask.as_ref().map_or(&[], |mask| &mask.effects) } else { &layer.content_effects } +} + fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) { let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; let index = *count; *count += 1; layer_row(app, ui, &layer, depth, index); - let mask_effects = layer.mask.as_ref().map_or(0, |mask| mask.effects.len()); - if !layer.content_effects.is_empty() { - effect_group(app, ui, &layer, depth, false, mask_effects > 0); - } - if mask_effects > 0 { - effect_group(app, ui, &layer, depth, true, false); + if let Some((open_layer, in_mask)) = app.layer_panel.expanded_effects + && open_layer == id + { + let stack = stack_effects(&layer, in_mask); + for (index, effect) in stack.iter().rev().enumerate() { + effect_row(app, ui, &layer, stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask); + } } // A line under the layer and its effects separates it from the next layer. @@ -558,7 +568,8 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let content_target = selected && targets_content(app); let preferred_size = layer_preview_size(app); let row_height = layer_row_height(preferred_size); - let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); + let (_, rect) = ui.allocate_space(vec2(ui.available_width(), row_height)); + let row = ui.interact(rect, ui.scope_id().with(("layer_row", layer.id.0)), Sense::click_and_drag()); row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name)); // Background, folder lines, the selected rows' accent edge and the colour tag @@ -659,9 +670,14 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } 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")); + let content_stack = (!layer.content_effects.is_empty()).then_some((layer.id, false)); + effect_stack_thumbnail(app, &painter, &tokens, &content_response, (tr("Select the layer content"), &layer.name), content_target, content_stack); if content_response.clicked() { let modifiers = ui.input(|input| input.modifiers); click_layer(app, modifiers, layer.id.0, Some("content")); + if !modifiers.shift && !modifiers.command { + app.layer_panel.toggle_effects(content_stack); + } } x = thumbnail.right() + THUMBNAIL_SPACING; @@ -699,12 +715,24 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize 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_stack = layer.mask.as_ref().filter(|mask| !mask.effects.is_empty()).map(|_| (layer.id, true)); + effect_stack_thumbnail( + app, + &painter, + &tokens, + &mask_response, + (tr("Select the mask (Alt+click: show it in the viewport)"), &layer.name), + mask_target, + mask_stack, + ); if mask_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); if ui.input(|input| input.modifiers.alt) { let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; app.run("viewport.view", view); + } else { + app.layer_panel.toggle_effects(mask_stack); } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { @@ -820,6 +848,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let modifiers = ui.input(|input| input.modifiers); if row.clicked() && !on_control && !renaming { click_layer(app, modifiers, layer.id.0, None); + app.layer_panel.expanded_effects = None; } if row.double_clicked() && !on_control && !renaming && show_name && !modifiers.shift && !modifiers.command { app.ui.rename = Some((layer.id.0, layer.name.clone())); @@ -918,69 +947,45 @@ fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) { } } -/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows -/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on. -fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) { - let tokens = Tokens::get(ui.ctx()); - let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |layer_mask| &layer_mask.effects) } else { &layer.content_effects }; - let key = (layer.id.0, mask); - let folded = app.layer_panel.folded.contains(&key); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click()); - let label = if mask { tr("Mask effects") } else { tr("Content effects") }; - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); - let painter = ui.painter().clone(); - painter.rect_filled(rect, 0.0, if response.hovered() { tokens.row_hover } else { tokens.panel }); - let indent = ((depth + 1) as f32 * INDENT).min((rect.width() - GROUP_HEADER_MIN_REMAINING_WIDTH).max(0.0)); - tree_lines(&painter, &tokens, rect, indent, &[], more_below); - let x = rect.left() + GROUP_HEADER_CARET_OFFSET + indent; - painter.text( - pos2(x, rect.center().y), - egui::Align2::CENTER_CENTER, - if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, - egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE), - tokens.text_dim, - ); - let galley = elided( - &painter, - label.to_string(), - GROUP_HEADER_LABEL_FONT_SIZE, - tokens.text_dim, - (rect.right() - GROUP_HEADER_LABEL_RESERVE - x - GROUP_HEADER_LABEL_GAP).max(0.0), - ); - painter.galley(pos2(x + GROUP_HEADER_LABEL_GAP, rect.center().y - galley.size().y * 0.5), galley, tokens.text_dim); - painter.text( - pos2(rect.right() - GROUP_HEADER_COUNT_PADDING, rect.center().y), - egui::Align2::RIGHT_CENTER, - stack.len().to_string(), - egui::FontId::proportional(LAYER_SUBTITLE_FONT_SIZE), - tokens.text_dim, - ); - if response.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) { - app.layer_panel.folded.insert(key); +/// Draw the effect disclosure on its thumbnail and expose the same state to AccessKit. +fn effect_stack_thumbnail( + app: &TextureCraftApp, + painter: &egui::Painter, + tokens: &Tokens, + response: &egui::Response, + (label, name): (&str, &str), + selected: bool, + stack: Option<(LayerId, bool)>, +) { + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, format!("{label} ({name})"))); + if response.has_focus() { + painter.rect_stroke(response.rect.shrink(2.0), THUMBNAIL_ROUNDING, Stroke::new(1.0, tokens.text_strong), egui::StrokeKind::Inside); } - if folded { - return; - } - - let trunks: Vec = if more_below { vec![depth] } else { Vec::new() }; - for (row_index, effect) in stack.iter().rev().enumerate() { - effect_row(app, ui, layer, stack, effect, row_index, depth + 2, &trunks, row_index + 1 == stack.len(), mask); + if let Some(stack) = stack { + let expanded = app.layer_panel.expanded_effects == Some(stack); + response.ctx.accesskit_node_builder(response.id, |node| node.set_expanded(expanded)); + if response.rect.width() < EFFECT_DISCLOSURE_SIZE { + return; + } + let size = vec2(EFFECT_DISCLOSURE_SIZE, EFFECT_DISCLOSURE_SIZE); + let badge = Rect::from_min_size(response.rect.max - size, size); + painter.rect_filled(badge, THUMBNAIL_ROUNDING, tokens.button); + painter.text( + badge.center(), + egui::Align2::CENTER_CENTER, + if expanded { ic::CARET_DOWN } else { ic::CARET_RIGHT }, + egui::FontId::proportional(EFFECT_DISCLOSURE_SIZE - 3.0), + tokens.text_strong, + ); } } -/// Tree connector of a row at the clamped `indent`: a line down from the parent's column (to the middle -/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with -/// lines straight through for the `trunks` of ancestors that continue. -fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: &[usize], more: bool) { +/// Draw the line along the open effect stack and a branch to this row. +fn effect_tree_line(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, more: bool) { if indent < INDENT { return; } let stroke = Stroke::new(1.0, tk.button_border); - for t in trunks { - if *t as f32 * INDENT + 8.0 < indent { - p.vline(level_x(rect.left(), *t), rect.y_range(), stroke); - } - } let x = rect.left() + 15.0 + indent - INDENT; let end = if more { rect.bottom() } else { rect.center().y }; p.vline(x, rect.top()..=end, stroke); @@ -1067,7 +1072,6 @@ fn effect_row( effect: &Effect, row_index: usize, level: usize, - trunks: &[usize], last: bool, in_mask: bool, ) { @@ -1076,7 +1080,8 @@ fn effect_row( let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id); let layer_preview = layer_preview_size(app); let preview_size = effect_preview_size(layer_preview); - let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview)), Sense::click_and_drag()); + let (_, rect) = ui.allocate_space(vec2(ui.available_width(), effect_row_height(layer_preview))); + let row = ui.interact(rect, ui.scope_id().with(("effect_row", effect_id.0)), Sense::click_and_drag()); row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name)); // Background, tree lines and the selected row's accent edge @@ -1092,7 +1097,7 @@ fn effect_row( }; painter.rect_filled(rect, 0.0, background); let indent = effect_row_indent(rect.width(), level, preview_size); - tree_lines(&painter, &tokens, rect, indent, trunks, !last); + effect_tree_line(&painter, &tokens, rect, indent, !last); if selected { painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent); } @@ -1124,7 +1129,7 @@ fn effect_row( if renaming { let half_height = EFFECT_NAME_EDIT_HEIGHT * 0.5; let name_rect = Rect::from_min_max(pos2(name_left, rect.center().y - half_height), pos2(name_right, rect.center().y + half_height)); - effect_rename_editor(app, ui, name_rect, effect); + effect_rename_editor(app, ui, name_rect); } else { let name_width = (name_right - name_left).max(MIN_NAME_WIDTH); if text_is_cut(&painter, &effect.name, EFFECT_NAME_FONT_SIZE, name_width) { @@ -1212,8 +1217,8 @@ fn effect_row( }); } -/// The name editor of `effect` in `rect`: Enter or a click elsewhere renames, Escape cancels. -fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effect: &Effect) { +/// The effect name editor: Enter or a click elsewhere renames, Escape cancels. +fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center))); let Some((_, name_buffer)) = app.ui.rename.as_mut() else { return }; @@ -1224,17 +1229,21 @@ fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, effe if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; } else if response.lost_focus() { - let name = name_buffer.trim().to_string(); - app.ui.rename = None; - if !name.is_empty() && name != effect.name { - app.run("effect.set", json!({"effect": effect.id.0, "name": name})); - } + finish_effect_rename(app); } else if !response.has_focus() { // Only until the field has focus (see the layer rename editor) response.request_focus(); } } +fn finish_effect_rename(app: &mut TextureCraftApp) { + let Some((id, name)) = app.ui.rename.take() else { return }; + let name = name.trim(); + if !name.is_empty() && app.session.doc.project.effect(LayerId(id)).is_some_and(|(_, effect)| name != effect.name) { + app.run("effect.set", json!({"effect": id, "name": name})); + } +} + /// The Geometry mask tool: what a click does, and the selected layer's parts. fn geometry_tool_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index d5390546..554161f3 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -1,12 +1,13 @@ //! State behind the Layers panel: the thumbnail service, the GPU textures made from its pictures, -//! which effect groups are folded, and the one place the preview size is decided. +//! which effect stack is open, and the one place the preview size is decided. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::time::Duration; use egui::{Context, TextureHandle, TextureId, TextureOptions}; use texturecraft_engine::Session; use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::LayerId; use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; use crate::TextureCraftApp; @@ -42,20 +43,23 @@ pub struct LayerPanel { frame: u64, /// Whether this frame's pictures are begun and not yet finished by [`LayerPanel::end`] pictures_begun: bool, - /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. - pub(crate) folded: HashSet<(u64, bool)>, + /// The open stack, with `true` for a layer's mask. This belongs to the panel view. + pub(crate) expanded_effects: Option<(LayerId, bool)>, } /// How soon to look again for pictures still rendering (milliseconds) const POLL_INTERVAL_MS: u64 = 40; impl LayerPanel { + pub(crate) fn toggle_effects(&mut self, stack: Option<(LayerId, bool)>) { + self.expanded_effects = stack.filter(|stack| Some(*stack) != self.expanded_effects); + } + /// Start drawing the panel for this frame. pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.begin_pictures(session, now); - // Deleted layer IDs must not accumulate in panel state - self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); + self.expanded_effects = self.expanded_effects.filter(|(layer, _)| session.doc.project.layers.contains_key(layer)); } /// Advance the picture frame once, whether the panel or a picture outside it asks first @@ -115,22 +119,22 @@ impl LayerPanel { #[cfg(test)] mod tests { use super::*; - use texturecraft_engine::core::{Channel, LayerId}; + use texturecraft_engine::core::Channel; use texturecraft_engine::geom::primitives; #[test] - fn deleted_layers_release_their_fold_state() { + fn deleted_layers_close_their_effect_stack() { let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); let layer = session.selected_layer().unwrap(); let mut panel = LayerPanel::default(); - panel.folded.extend([(layer.0, false), (layer.0, true)]); + panel.expanded_effects = Some((layer, false)); panel.begin(&session, 0.0); - assert_eq!(panel.folded.len(), 2, "existing layers keep their view settings"); + assert_eq!(panel.expanded_effects, Some((layer, false)), "existing layers keep their view settings"); texturecraft_engine::execute(&mut session, "layer.remove", &serde_json::json!({"layer": layer.0})).unwrap(); panel.begin(&session, 1.0); - assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state"); + assert_eq!(panel.expanded_effects, None, "the deleted layer leaves no open stack"); } #[test] diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index fdd04351..b8afbe42 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -7,6 +7,8 @@ use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; use texturecraft_ui_egui::TextureCraftApp; +use super::layers_panel::click_selected_content_thumbnail; + fn id(v: Value, key: &str) -> u64 { v[key].as_u64().unwrap() } @@ -34,6 +36,7 @@ fn dragging_an_effect_row_reorders_its_stack() { 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); + click_selected_content_thumbnail(&mut harness); let order = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); assert_eq!(order(&harness), [a, b, c]); @@ -60,6 +63,7 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { 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); + click_selected_content_thumbnail(&mut harness); 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); @@ -97,6 +101,7 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { 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); + click_selected_content_thumbnail(&mut harness); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); let history = harness.state().session.history_labels().len(); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 0a88c260..4deeadc6 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -1,8 +1,8 @@ -//! The Layers panel rows: content and mask thumbnails select their own target, effect groups -//! fold without touching the document, and the thumbnails arrive from the worker. +//! The Layers panel rows: thumbnails select and disclose their own effects without editing the +//! document, and the thumbnail images arrive from the worker. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{Channel, LayerId}; @@ -35,11 +35,12 @@ fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2 egui::pos2(x, row.center().y) } -/// The `label` header that follows the "Masked fill" row (other layers have groups too). -fn header(h: &mut Harness<'_, TextureCraftApp>, label: &str) { - let top = h.get_by_label("Masked fill").rect().top(); - let at = h.get_all_by_label(label).map(|n| n.rect()).filter(|r| r.top() > top).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap().center(); - click(h, at); +/// Toggle the effect rows through the selected layer's content thumbnail. +pub(super) fn click_selected_content_thumbnail(h: &mut Harness<'_, TextureCraftApp>) { + let layer = h.state().session.selected_layer().unwrap(); + let name = &h.state().session.doc.project.layers[&layer].name; + h.get_by_label(&format!("Select the layer content ({name})")).click(); + h.run_steps(3); } fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { @@ -49,35 +50,84 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { } #[test] -fn mask_and_content_thumbnails_select_their_own_target() { +fn mask_and_content_thumbnails_toggle_their_own_stacks() { let (mut h, layer) = harness(); - let at = thumb(&h, "Masked fill", true); - click(&mut h, at); + let content = thumb(&h, "Masked fill", false); + let mask = thumb(&h, "Masked fill", true); + assert!(h.query_by_label("Effect A").is_none() && h.query_by_label("Effect M").is_none(), "stacks start closed"); + + click(&mut h, mask); assert_eq!(h.state().session.selected_layer(), Some(layer)); - assert_eq!(h.state().session.target, StackTarget::Mask, "the mask thumbnail routes to the mask"); - let at = thumb(&h, "Masked fill", false); - click(&mut h, at); - assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); - // Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity) + assert_eq!(h.state().session.target, StackTarget::Mask); + assert!(h.query_by_label("Effect M").is_some()); + click(&mut h, mask); + assert!(h.query_by_label("Effect M").is_none(), "the same mask thumbnail closes its stack"); + click(&mut h, mask); + assert!(h.query_by_label("Effect M").is_some()); + + click(&mut h, content); + assert_eq!(h.state().session.target, StackTarget::Content); + assert!(h.query_by_label("Effect M").is_none(), "switching thumbnails closes the mask stack"); + assert!(h.query_by_label("Effect A").is_some()); + click(&mut h, content); + assert!(h.query_by_label("Effect A").is_none(), "the same content thumbnail closes its stack"); + click(&mut h, content); let row = h.get_by_label("Effect A").rect(); click(&mut h, row.center()); assert!(matches!(h.state().session.target, StackTarget::Effect(_))); + assert!(h.query_by_label("Effect A").is_some(), "selecting an effect leaves its stack open"); } #[test] -fn folding_an_effect_group_hides_its_rows_without_changing_the_document() { - let (mut h, _) = harness(); - let (project, undo) = (h.state().session.doc.project.clone(), h.state().session.revision); - assert!(h.query_by_label("Effect A").is_some() && h.query_by_label("Effect M").is_some()); - header(&mut h, "Content effects"); - assert!(h.query_by_label("Effect A").is_none(), "folded content effects are hidden"); - assert!(h.query_by_label("Effect M").is_some(), "the mask group stays open"); - header(&mut h, "Mask effects"); - assert!(h.query_by_label("Effect M").is_none()); - assert_eq!(h.state().session.doc.project, project); - assert_eq!(h.state().session.revision, undo, "folding is not an edit"); - header(&mut h, "Content effects"); - assert!(h.query_by_label("Effect A").is_some(), "unfolds again"); +fn keyboard_toggles_effects_without_editing_the_document() { + let (mut h, layer) = harness(); + let session = &h.state().session; + let (project, history, modified) = (session.doc.project.clone(), session.history_labels(), session.modified); + let content = "Select the layer content (Masked fill)"; + assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(false)); + + // Move focus to the thumbnail and activate it with the standard button keys. + h.get_by_label(content).focus(); + h.run_steps(3); + assert!(h.get_by_label(content).is_focused()); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.query_by_label("Effect A").is_some()); + h.key_press(egui::Key::Space); + h.run_steps(3); + assert!(h.query_by_label("Effect A").is_none()); + assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(false)); + + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.get_by_label(content).is_focused()); + assert_eq!(h.get_by_label(content).accesskit_node().data().is_expanded(), Some(true)); + + let session = &h.state().session; + let empty = session.doc.project.texture_sets[session.ts()] + .stack + .iter() + .rev() + .find_map(|id| { + let layer = session.doc.project.layers.get(id)?; + (layer.mask.is_none() && layer.content_effects.is_empty()).then(|| (*id, layer.name.clone())) + }) + .expect("sample contains an empty paint layer"); + let empty_thumbnail = format!("Select the layer content ({})", empty.1); + h.get_by_label(&empty_thumbnail).focus(); + h.run_steps(3); + assert!(h.get_by_label(&empty_thumbnail).is_focused()); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(h.state().session.selected_layer(), Some(empty.0)); + assert_ne!(empty.0, layer); + assert!(h.query_by_label("Effect A").is_none() && h.query_by_label("Effect M").is_none(), "switching layers closes the old stack"); + assert_eq!(h.get_by_label(&empty_thumbnail).accesskit_node().data().is_expanded(), None); + + let session = &h.state().session; + assert_eq!(session.doc.project, project); + assert_eq!(session.history_labels(), history); + assert_eq!(session.modified, modified); } #[test] @@ -85,14 +135,15 @@ fn visible_rows_get_their_thumbnails() { let (mut h, layer) = harness(); let content = ThumbTarget::Content { layer, channel: Channel::BaseColor }; let mask = ThumbTarget::Mask { layer }; + let effect = h.state().session.doc.project.layers[&layer].content_effects[0].id; + let stage = ThumbTarget::Stage { effect, channel: Channel::BaseColor }; + click_selected_content_thumbnail(&mut h); let t0 = std::time::Instant::now(); - while !(h.state().layer_panel.service().is_fresh(content) && h.state().layer_panel.service().is_fresh(mask)) { + while ![content, mask, stage].iter().all(|target| h.state().layer_panel.service().is_fresh(*target)) { assert!(t0.elapsed().as_secs() < 60, "thumbnails never arrived"); h.run_steps(1); std::thread::sleep(std::time::Duration::from_millis(5)); } - // Rows, mask, and every effect stage on screen were asked for: well under the cache size. - assert!(h.state().layer_panel.service().cached() >= 4); } #[test] @@ -121,6 +172,9 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties); harness.run_steps(4); + harness.state_mut().run("layer.select", json!({"layer": layer.0})).unwrap(); + harness.run_steps(3); + click_selected_content_thumbnail(&mut harness); let row = harness.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); @@ -297,12 +351,13 @@ const LONG_EFFECT_NAME: &str = "Edge wear from curvature with dirt accumulation" fn an_effect_name_cut_short_shows_in_full_on_hover() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); - execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": LONG_EFFECT_NAME})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); + click_selected_content_thumbnail(&mut h); let row = h.get_by_label(LONG_EFFECT_NAME).rect(); let before = h.query_all_by_label_contains(LONG_EFFECT_NAME).count(); h.hover_at(egui::pos2(row.left() + 75.0, row.center().y)); diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index f8ee1763..9287725b 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -12,6 +12,8 @@ use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, StackTarget}; use texturecraft_ui_egui::TextureCraftApp; + +use super::layers_panel::click_selected_content_thumbnail; use texturecraft_ui_egui::file_dialogs::Answer; const BLACK: [f32; 3] = [0.0; 3]; @@ -69,7 +71,9 @@ fn effect_harness() -> (Harness<'static, TextureCraftApp>, u64) { "effect", ); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); - (harness_for(session), effect) + let mut h = harness_for(session); + click_selected_content_thumbnail(&mut h); + (h, effect) } /// Choose Rename effect from the row's context menu and type `text` over the old name. @@ -116,10 +120,24 @@ fn renaming_an_effect_row_undoes_redoes_and_survives_save_and_reopen() { let layer = h.state().session.doc.project.effect(LayerId(effect)).unwrap().0; h.state_mut().run("layer.select", json!({"layer": layer.0})); h.run_steps(3); + assert!(h.query_by_label("Pitted rust").is_none(), "the reopened stack starts closed"); + click_selected_content_thumbnail(&mut h); assert!(h.query_by_label("Pitted rust").is_some(), "the reopened stack shows the name"); std::fs::remove_dir_all(file.parent().unwrap()).unwrap(); } +#[test] +fn collapsing_an_effect_stack_finishes_its_rename() { + let (mut h, effect) = effect_harness(); + rename_from_the_menu(&mut h, "Effect A", "Pitted rust"); + click_selected_content_thumbnail(&mut h); + assert!(h.state().ui.rename.is_none(), "the hidden editor has committed the name"); + assert_eq!(effect_name(&h, effect), "Pitted rust"); + assert!(h.query_by_label("Pitted rust").is_none(), "the effect stack closed"); + click_selected_content_thumbnail(&mut h); + assert!(h.query_by_label("Pitted rust").is_some()); +} + #[test] fn escape_in_the_effect_editor_keeps_the_name() { let (mut h, effect) = effect_harness(); From 857fb1e3d08aa8e4f8fdd21697809693e662cbb3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 17:15:46 +0100 Subject: [PATCH 08/80] Save projects in the background and show progress --- crates/engine/src/bake/mesh_map_command.rs | 24 +-- crates/engine/src/file_cmds.rs | 165 +++++++++++++----- crates/engine/src/painting.rs | 3 +- crates/engine/src/path_tool.rs | 3 +- crates/engine/src/session.rs | 37 +++- crates/formats/src/project_file/mod.rs | 14 +- .../src/project_file/ram_reservation.rs | 12 +- .../formats/src/project_file/save_progress.rs | 69 ++++++++ crates/ui-egui/src/control.rs | 4 + crates/ui-egui/src/display_settings.rs | 3 +- crates/ui-egui/src/lib.rs | 29 ++- crates/ui-egui/src/manual_save.rs | 88 ++++++++++ crates/ui-egui/src/menus.rs | 4 + crates/ui-egui/src/shader_settings.rs | 3 +- crates/ui-egui/src/toolbar.rs | 5 + crates/ui-egui/src/windows.rs | 59 ++++--- crates/ui-egui/tests/it/file_dialogs.rs | 77 ++++++-- 17 files changed, 468 insertions(+), 131 deletions(-) create mode 100644 crates/formats/src/project_file/save_progress.rs create mode 100644 crates/ui-egui/src/manual_save.rs diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef27ea3..4e219bd1 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -56,7 +56,7 @@ pub(super) fn specs() -> Vec { 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; + s.mark_modified(); Ok(meshes_json(s)) }), ] @@ -274,7 +274,7 @@ impl Session { for set in &mut self.doc.project.texture_sets { set.bake.high_poly.use_low_as_high = false; } - self.modified = true; + self.mark_modified(); Ok(name) } @@ -285,7 +285,7 @@ impl Session { } let removed = self.bake_meshes.high.remove(index); self.bake_meshes.rebuild(); - self.modified = true; + self.mark_modified(); Ok(removed) } @@ -303,7 +303,7 @@ impl Session { m.base_color.clear(); let name = m.name.clone(); self.bake_meshes.cage = Some(m); - self.modified = true; + self.mark_modified(); Ok(name) } @@ -347,20 +347,6 @@ impl Session { } } } - - pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> { - self.doc - .bake_paint - .iter() - .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() })) - .collect() - } - - /// 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)) - } } /// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`). @@ -392,7 +378,7 @@ 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; + s.mark_modified(); return Ok(meshes_json(s)); } let index = match (u64p(p, "index"), strp(p, "name")) { diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f493093b..fdc29bf1 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -16,6 +16,47 @@ use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p} use crate::session::{Document, Session}; use crate::{EngineError, Result, cmd}; +fn project_with_resources( + doc: &Document, + mesh: Option<&(String, Arc>)>, + bake_meshes: &crate::BakeMeshes, + resources: BTreeMap, +) -> ProjectFile { + let mut pixels = doc.pixels.clone(); + + // Drop pixel images whose size no longer matches their texture set + let size_of = |id: texturecraft_core::LayerId| { + doc.project.locate(id).and_then(|(ts, _, _)| doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| { + doc.project + .effect(id) + .and_then(|(owner, _)| doc.project.locate(owner)) + .and_then(|(ts, _, _)| doc.project.texture_sets.get(ts)) + .map(TextureSet::size) + }) + }; + pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height()))); + pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); + + let bake_mesh = |mesh: &crate::BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone()); + let bake_paint = doc + .bake_paint + .iter() + .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() })) + .collect(); + ProjectFile { + project: doc.project.clone(), + pixels, + baked: doc.baked.clone(), + mesh: mesh.map(|(extension, bytes)| (extension.clone(), bytes.as_ref().clone())), + high_poly: bake_meshes.high.iter().map(bake_mesh).collect(), + cage: bake_meshes.cage.as_ref().map(bake_mesh), + bake_paint, + thumbnail: None, + resources, + warnings: Vec::new(), + } +} + pub fn specs() -> Vec { vec![ cmd!( @@ -171,7 +212,7 @@ impl Session { // Packed mesh files can have spare capacity that the project would otherwise retain let mut source = bytes.into_owned(); source.shrink_to_fit(); - session.mesh_source = Some((extension, source)); + session.mesh_source = Some((extension, Arc::new(source))); session.doc.project.mesh_file = leaf_of(file_name); session.doc.project.cameras = imported.cameras; @@ -204,7 +245,7 @@ impl Session { }; check_materials(&pf.project, &mesh)?; - let source = pf.mesh.clone(); + let source = pf.mesh; 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)?; @@ -220,44 +261,12 @@ impl Session { /// The project with independently owned resource bytes. pub fn project_file(&self) -> ProjectFile { let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect(); - self.project_with_resources(resources) + project_with_resources(&self.doc, self.mesh_source.as_ref(), &self.bake_meshes, resources) } /// A save snapshot that shares immutable resource payloads with the document. pub fn project_snapshot(&self) -> ProjectFile>> { - self.project_with_resources(self.doc.resources.clone()) - } - - fn project_with_resources(&self, resources: BTreeMap) -> ProjectFile { - let mut pixels = self.doc.pixels.clone(); - - // Drop pixel images whose size no longer matches their texture set - let size_of = |id: texturecraft_core::LayerId| { - self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| { - self.doc - .project - .effect(id) - .and_then(|(owner, _)| self.doc.project.locate(owner)) - .and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)) - .map(TextureSet::size) - }) - }; - pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height()))); - pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); - - let (high_poly, cage) = self.saved_bake_meshes(); - ProjectFile { - project: self.doc.project.clone(), - pixels, - baked: self.doc.baked.clone(), - mesh: self.mesh_source.clone(), - high_poly, - cage, - bake_paint: self.saved_bake_paint(), - thumbnail: None, - resources, - warnings: Vec::new(), - } + project_with_resources(&self.doc, self.mesh_source.as_ref(), &self.bake_meshes, self.doc.resources.clone()) } pub fn to_project_bytes(&self) -> Result> { @@ -449,6 +458,7 @@ fn plan(session: &mut Session, params: &Value) -> Result { mod native { use super::*; use std::path::Path; + use texturecraft_formats::project_file::SaveProgress; pub fn path_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> { strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required"))) @@ -484,21 +494,82 @@ mod native { } pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result { - let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") }; - let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?; - reservation.save(Path::new(&path), &s.project_snapshot()).map_err(fe)?; + let output = s.save_task(path, adopt).run(None)?; + output.apply(s); + Ok(json!({ "path": output.path })) + } - if adopt { - s.path = Some(path.clone()); - s.modified = false; + struct SaveTarget { + project_id: u64, + revision: u64, + adopt: bool, + path: String, + } + + /// A manual save of the document at the moment it was requested. Large payloads are shared + /// until the worker assembles the archive. + pub struct SaveTask { + target: SaveTarget, + doc: Document, + mesh: Option<(String, Arc>)>, + bake_meshes: crate::BakeMeshes, + } + + impl Session { + pub fn save_task(&self, path: &str, adopt: bool) -> SaveTask { + let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") }; + SaveTask { + target: SaveTarget { project_id: self.project_id, revision: self.save_revision, adopt, path }, + doc: self.doc.clone(), + mesh: self.mesh_source.clone(), + bake_meshes: self.bake_meshes.clone(), + } + } + } + + impl SaveTask { + /// Complete the atomic write on the worker. Waiting for a previous save to release the + /// RAM allowance also happens here. + pub fn run(self, progress: Option<&SaveProgress>) -> Result { + let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?; + let snapshot = project_with_resources(&self.doc, self.mesh.as_ref(), &self.bake_meshes, self.doc.resources.clone()); + let path = Path::new(&self.target.path); + match progress { + Some(progress) => reservation.save_with_progress(path, &snapshot, progress), + None => reservation.save(path, &snapshot), + } + .map_err(fe)?; + Ok(SaveOutput { path: self.target.path, project_id: self.target.project_id, revision: self.target.revision, adopt: self.target.adopt }) + } + } + + /// An archive that was written successfully. Only the same project can adopt its path. + pub struct SaveOutput { + pub path: String, + project_id: u64, + revision: u64, + adopt: bool, + } + + impl SaveOutput { + /// Apply the saved path without clearing edits made since the snapshot. + pub fn apply(&self, session: &mut Session) { + if session.project_id != self.project_id { + return; + } + if self.adopt { + session.path = Some(self.path.clone()); + if session.save_revision == self.revision && !session.stroke_active() { + session.modified = false; + } + } + session.log.info("Project", format!("Saved {}", self.path)); } - s.log.info("Project", format!("Saved {path}")); - Ok(json!({ "path": path })) } } #[cfg(not(target_arch = "wasm32"))] -pub use native::{absolute, open_path, read_mesh}; +pub use native::{SaveOutput, SaveTask, absolute, open_path, read_mesh}; /// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the /// mesh file `mesh`, remembering its path for Reimport mesh. @@ -597,7 +668,7 @@ impl Session { let (mesh, source, warnings, mesh_file) = match file { Some(f) => { let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh; - (m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name)) + (m, Some((ext_of(&f.name), Arc::new(f.bytes))), f.warnings, leaf_of(&f.name)) } None => match &self.mesh_source { Some((ext, bytes)) => { @@ -612,7 +683,7 @@ impl Session { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; } - let mut next = Session::new(doc, mesh, source)?; + let mut next = Session::new_with_source(doc, mesh, source)?; next.log.warnings("Importer", warnings); next.path = self.path.clone(); next.sync_images(); diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 62010b50..9ca5836a 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -576,8 +576,7 @@ impl Session { self.undo.remove(0); } self.redo.clear(); - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); // 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. self.mark_settle(st.ts, st.target, st.canvas.dirty.iter().copied()); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 5398501f..63d047b2 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -922,8 +922,7 @@ impl Session { } else { self.invalidate_changed(&before); } - self.revision = self.revision.wrapping_add(1); - self.modified = true; + self.mark_modified(); Ok((painted, before)) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index b493a8b6..4f2c8b77 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -418,7 +418,7 @@ pub struct Session { pub(crate) source: Arc, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. - pub mesh_source: Option<(String, Vec)>, + pub mesh_source: Option<(String, Arc>)>, /// High-definition meshes and cage for baking (saved inside the project). pub bake_meshes: crate::BakeMeshes, pub caches: Vec, @@ -467,6 +467,9 @@ pub struct Session { /// (see [`crate::commands::check_enabled`]). pub project_open: bool, pub modified: bool, + /// Edits to saved data, independent of viewport and tool changes. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) save_revision: u64, /// Bumps on every document change. pub revision: u64, /// Messages for the UI (status bar / toasts). @@ -492,6 +495,10 @@ pub struct Session { impl Session { /// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`]) pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec)>) -> Result { + Self::new_with_source(doc, mesh, mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes)))) + } + + pub(crate) fn new_with_source(doc: Document, mesh: Mesh, mesh_source: Option<(String, Arc>)>) -> Result { mesh.validate().map_err(|error| EngineError::Other(error.to_string()))?; let source = Arc::new(mesh); @@ -539,6 +546,8 @@ impl Session { path: None, project_open: true, modified: false, + #[cfg(not(target_arch = "wasm32"))] + save_revision: 0, revision: 1, log: crate::log::SessionLog::new(), log_id: next_mesh_id(), @@ -567,6 +576,10 @@ impl Session { pub fn switch_to(&mut self, mut next: Session) { // Invalidate caches even when both projects were loaded with the same revision next.revision = self.revision.wrapping_add(1); + #[cfg(not(target_arch = "wasm32"))] + { + next.save_revision = self.save_revision.wrapping_add(1); + } next.viewport = self.viewport; next.export_presets = std::mem::take(&mut self.export_presets); @@ -711,8 +724,7 @@ impl Session { self.path_steps = Default::default(); } - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { self.undo.push((label.to_string(), before)); } @@ -723,8 +735,7 @@ impl Session { /// A change from `other` to the current document that is not an undo step (a path preview) pub(crate) fn changed_without_history(&mut self, other: &Document) { - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); self.invalidate_changed(other); } @@ -835,14 +846,23 @@ impl Session { /// Mark the document changed and every texture set dirty. pub fn touched(&mut self) { - self.modified = true; - self.revision = self.revision.wrapping_add(1); + self.mark_modified(); self.sync_caches(); for c in &mut self.caches { c.invalidate_all(); } } + /// Mark saved data changed without invalidating the texture sets. + pub fn mark_modified(&mut self) { + self.modified = true; + self.revision = self.revision.wrapping_add(1); + #[cfg(not(target_arch = "wasm32"))] + { + self.save_revision = self.save_revision.wrapping_add(1); + } + } + /// Make caches agree with the project's texture sets (resolution or channel changes). pub fn sync_caches(&mut self) { let sets = self.doc.project.texture_sets.clone(); @@ -953,11 +973,10 @@ impl Session { fn after_history(&mut self, other: &Document) { // Pending operations may still hold layer IDs from the discarded snapshot self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id); - self.modified = true; + self.mark_modified(); // Layers picked together belong to the stack they were picked in self.multi.clear(); - self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); // An undone add or duplicate takes the selected effect away diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index c5bf3bdb..06a504ca 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -38,10 +38,12 @@ mod load_budget; mod project_open_limit; mod ram_operation; mod ram_reservation; +mod save_progress; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources}; pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; pub use ram_reservation::RamReservation; +pub use save_progress::SaveProgress; const KIND: &str = "project file"; #[cfg(test)] @@ -109,11 +111,11 @@ pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Resul } #[cfg(not(target_arch = "wasm32"))] -fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> { +fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile>>, progress: Option<&SaveProgress>) -> Result<()> { let (temporary_path, file) = crate::create_temp(path)?; let result = (|| -> Result<()> { let mut file = std::io::BufWriter::new(file); - write_project(&mut file, project_file)?; + write_project(&mut file, project_file, progress)?; file.into_inner().map_err(|error| error.into_error())?.sync_all()?; std::fs::rename(&temporary_path, path)?; Ok(()) @@ -276,9 +278,13 @@ fn entries(pf: &ProjectFile>>) -> Result>> { Ok(out) } -fn write_project(out: W, pf: &ProjectFile>>) -> Result<()> { +fn write_project(out: W, pf: &ProjectFile>>, progress: Option<&SaveProgress>) -> Result<()> { let mut zip = ZipWriter::new(out); - entries::write_entries(&mut zip, entries(pf)?)?; + let mut entries = entries(pf)?; + if let Some(progress) = progress { + progress.track(&mut entries); + } + entries::write_entries(&mut zip, entries)?; zip.finish().map_err(zip_err)?; Ok(()) } diff --git a/crates/formats/src/project_file/ram_reservation.rs b/crates/formats/src/project_file/ram_reservation.rs index 72857c15..caff4af1 100644 --- a/crates/formats/src/project_file/ram_reservation.rs +++ b/crates/formats/src/project_file/ram_reservation.rs @@ -2,6 +2,8 @@ use std::borrow::Borrow; use std::io::Cursor; use std::sync::{Condvar, Mutex}; +#[cfg(not(target_arch = "wasm32"))] +use super::SaveProgress; use super::{ProjectFile, ram_operation::RamOperation, write_project}; use crate::{FormatError, Result}; @@ -57,14 +59,20 @@ impl RamReservation { pub fn save_bytes(&mut self, project_file: &ProjectFile>>) -> Result> { self.check_save()?; let mut out = Cursor::new(Vec::new()); - write_project(&mut out, project_file)?; + write_project(&mut out, project_file, None)?; Ok(out.into_inner()) } #[cfg(not(target_arch = "wasm32"))] pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile>>) -> Result<()> { self.check_save()?; - super::write_project_atomic(path, project_file) + super::write_project_atomic(path, project_file, None) + } + + #[cfg(not(target_arch = "wasm32"))] + pub fn save_with_progress(&mut self, path: &std::path::Path, project_file: &ProjectFile>>, progress: &SaveProgress) -> Result<()> { + self.check_save()?; + super::write_project_atomic(path, project_file, Some(progress)) } fn check_save(&self) -> Result<()> { diff --git a/crates/formats/src/project_file/save_progress.rs b/crates/formats/src/project_file/save_progress.rs new file mode 100644 index 00000000..4e7c1810 --- /dev/null +++ b/crates/formats/src/project_file/save_progress.rs @@ -0,0 +1,69 @@ +use std::io::{self, Write}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::entries::Entry; + +/// Estimated archive progress, based on the payload processed by the entry writers. +/// Completing the archive, syncing it to disk, and replacing the destination can take longer. +#[derive(Default)] +pub struct SaveProgress { + total: AtomicU64, + processed: AtomicU64, +} + +impl SaveProgress { + pub fn fraction(&self) -> f32 { + let total = self.total.load(Ordering::Relaxed); + if total == 0 { + return 0.0; + } + let processed = self.processed.load(Ordering::Relaxed).min(total); + // Leave room for the final write and atomic replacement. + 0.95 * (processed as f64 / total as f64) as f32 + } + + pub(super) fn track<'a>(&'a self, entries: &mut [Entry<'a>]) { + self.processed.store(0, Ordering::Relaxed); + self.total.store(entries.iter().fold(0u64, |sum, entry| sum.saturating_add(entry.weight)), Ordering::Relaxed); + for entry in entries { + let body = std::mem::replace(&mut entry.body, Box::new(|_| Ok(()))); + let remaining = entry.weight; + entry.body = Box::new(move |target| { + let mut writer = ProgressWriter { target, progress: self, remaining, pending: 0 }; + body(&mut writer)?; + writer.report(); + Ok(()) + }); + } + } +} + +struct ProgressWriter<'a> { + target: &'a mut dyn Write, + progress: &'a SaveProgress, + remaining: u64, + pending: u64, +} + +impl ProgressWriter<'_> { + fn report(&mut self) { + self.progress.processed.fetch_add(std::mem::take(&mut self.pending), Ordering::Relaxed); + } +} + +impl Write for ProgressWriter<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let written = self.target.write(bytes)?; + let counted = (written as u64).min(self.remaining); + self.remaining -= counted; + self.pending += counted; + if self.pending >= 64 << 10 { + self.report(); + } + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + self.target.flush() + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6b471ff5..6e999d7d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -141,6 +141,10 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para }, "command.run" => { let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") }; + #[cfg(not(target_arch = "wasm32"))] + if app.save_job.is_some() && crate::manual_save::is_save(id) { + return err("A manual project save is already running"); + } let command_params = params.get("params").cloned().unwrap_or(Value::Null); let before = app.session.camera; match texturecraft_engine::execute(&mut app.session, id, &command_params) { diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs index 7c0bc14d..6a8e56b2 100644 --- a/crates/ui-egui/src/display_settings.rs +++ b/crates/ui-egui/src/display_settings.rs @@ -57,8 +57,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } app.session.doc.project.display = display; - app.session.modified = true; - app.session.revision = app.session.revision.wrapping_add(1); + app.session.mark_modified(); } if import_hdr { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1a8508eb..f6b25860 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -50,6 +50,8 @@ mod levels_properties; mod line_snap; mod list_action; pub mod log_panel; +#[cfg(not(target_arch = "wasm32"))] +mod manual_save; mod mask_preview_image; mod material_preview_image; pub mod menus; @@ -189,6 +191,7 @@ pub struct Toast { pub error: bool, pub until: f64, pub show_log: bool, + announce: bool, } pub struct TextureCraftApp { @@ -267,10 +270,13 @@ pub struct TextureCraftApp { /// Native file dialogs and their continuations (desktop only). #[cfg(not(target_arch = "wasm32"))] pub file_dialogs: file_dialogs::FileDialogs, - /// The unsaved-changes dialog's Save is waiting on the Save dialog's answer. + /// A manual save running on the desktop archive writer. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) save_job: Option, + /// The unsaved-changes dialog's Save is waiting for a path or a save result. #[cfg(not(target_arch = "wasm32"))] pub(crate) saving_for_prompt: bool, - /// That Save dialog saved the project; the prompt goes on at its next frame. + /// The requested save completed; the prompt goes on at its next frame. #[cfg(not(target_arch = "wasm32"))] pub(crate) prompt_saved: bool, /// The resolved keymap and its key dispatcher. @@ -364,6 +370,8 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), #[cfg(not(target_arch = "wasm32"))] + save_job: None, + #[cfg(not(target_arch = "wasm32"))] saving_for_prompt: false, #[cfg(not(target_arch = "wasm32"))] prompt_saved: false, @@ -504,13 +512,13 @@ impl TextureCraftApp { } pub fn toast(&mut self, text: impl Into, error: bool) { - self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false }); + self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, announce: false }); } /// An error toast that stays until the user dismisses it (for a problem that persists and /// is reported once, like a texture set the GPU could not hold). pub fn toast_sticky(&mut self, text: impl Into) { - self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); + self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, announce: false }); } /// Start baking texture sets in the background, one after another. Invalid set indices @@ -871,6 +879,9 @@ impl TextureCraftApp { /// and written on a worker thread; the project data is shared copy-on-write). #[cfg(not(target_arch = "wasm32"))] fn autosave(&mut self, now: f64) { + if self.save_job.is_some() { + return; + } let period = autosave_period_seconds(self.ui.prefs.autosave_minutes); // The clock starts at the first unsaved change @@ -1023,7 +1034,10 @@ impl eframe::App for TextureCraftApp { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] - self.autosave(now); + { + self.poll_save(ctx); + self.autosave(now); + } i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] { @@ -1198,7 +1212,10 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| { ui.set_max_width(width); - ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + let label = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap()); + if t.announce { + ui.ctx().accesskit_node_builder(label.id, |node| node.set_live(egui::accesskit::Live::Polite)); + } }); if t.show_log && ui.link(i18n::tr("Open Log")).clicked() { show_log = true; diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs new file mode 100644 index 00000000..c2481678 --- /dev/null +++ b/crates/ui-egui/src/manual_save.rs @@ -0,0 +1,88 @@ +//! Manual desktop saves share the atomic archive writer with autosave and headless saves. + +use std::sync::{Arc, mpsc}; +use std::time::Duration; + +use texturecraft_engine::{Result, file_cmds::SaveOutput, formats::project_file::SaveProgress}; + +use crate::{ + TextureCraftApp, + i18n::{tr, trf}, +}; + +pub(crate) struct SaveJob { + progress: Arc, + output: mpsc::Receiver>, + project_id: u64, + for_prompt: bool, + remember: bool, + pub(crate) quit_after_save: bool, +} + +pub(crate) fn is_save(id: &str) -> bool { + matches!(id, "file.save" | "file.saveAs" | "file.saveCopy") +} + +impl TextureCraftApp { + pub(crate) fn start_save(&mut self, path: &str, adopt: bool, for_prompt: bool, remember: bool) -> bool { + if self.save_job.is_some() { + self.toast(tr("A project save is already running"), true); + return false; + } + if let Err(error) = self.session.end_stroke() { + self.toast(error.to_string(), true); + return false; + } + + let task = self.session.save_task(path, adopt); + let progress = Arc::new(SaveProgress::default()); + let worker_progress = progress.clone(); + let output = crate::spawn_worker("texturecraft-save", move || task.run(Some(&worker_progress))); + self.save_job = Some(SaveJob { progress, output, project_id: self.session.project_id, for_prompt, remember, quit_after_save: false }); + true + } + + pub(crate) fn save_progress(&self) -> Option { + self.save_job.as_ref().map(|job| job.progress.fraction()) + } + + pub(crate) fn poll_save(&mut self, ctx: &egui::Context) { + let Some(job) = &self.save_job else { return }; + let result = match job.output.try_recv() { + Ok(result) => result.map_err(|error| error.to_string()), + Err(mpsc::TryRecvError::Empty) => { + ctx.request_repaint_after(Duration::from_millis(80)); + return; + } + Err(mpsc::TryRecvError::Disconnected) => Err(tr("The project save worker stopped").into()), + }; + let Some(job) = self.save_job.take() else { return }; + let same_project = job.project_id == self.session.project_id; + let continue_prompt = job.for_prompt && self.saving_for_prompt; + if job.for_prompt { + self.saving_for_prompt = false; + } + + match result { + Ok(output) => { + output.apply(&mut self.session); + if job.remember { + crate::windows::remember(self, &output.path); + } + self.prompt_saved = continue_prompt && same_project && !self.session.modified && !self.session.stroke_active(); + self.toast(trf("Saved {path}", &[("path", &output.path)]), false); + if job.quit_after_save && same_project { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + Err(error) => { + let message = trf("Could not save project: {error}", &[("error", &error)]); + self.session.log.warn("Project", message.clone()); + self.toast(message, true); + } + } + if let Some(toast) = self.toasts.last_mut() { + toast.announce = true; + } + } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7ec42c75..8aea36c1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -175,6 +175,10 @@ fn tooltip_of(id: &str) -> Option<&'static str> { /// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if app.save_job.is_some() && crate::manual_save::is_save(id) { + return false; + } if UNAVAILABLE.contains(&id) { return false; } diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index ba00a046..88dd9ae4 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -77,8 +77,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { if display != app.session.doc.project.display { app.session.doc.project.display = display; - app.session.modified = true; - app.session.revision = app.session.revision.wrapping_add(1); + app.session.mark_modified(); } } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index dc2f3453..a28a5360 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -536,6 +536,11 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { .frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(10, 0))) .show(ui, |ui| { ui.horizontal_centered(|ui| { + #[cfg(not(target_arch = "wasm32"))] + if let Some(progress) = app.save_progress() { + ui.add(egui::ProgressBar::new(progress).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Saving project")).size(10.0))); + ui.separator(); + } if let Some(p) = app.bake_progress() { ui.add(egui::ProgressBar::new(p).desired_width(160.0).desired_height(10.0).text(RichText::new(tr("Baking")).size(10.0))); if ui.small_button(tr("Cancel")).clicked() { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0624e1be..8473de9a 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -92,7 +92,19 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { { app.toast(error.to_string(), true); } - if closing && ask_to_save(app, crate::state::Unsaved::Quit) { + #[cfg(not(target_arch = "wasm32"))] + let waiting_for_save = if closing + && !app.session.modified + && let Some(job) = &mut app.save_job + { + job.quit_after_save = true; + true + } else { + false + }; + #[cfg(target_arch = "wasm32")] + let waiting_for_save = false; + if closing && (waiting_for_save || ask_to_save(app, crate::state::Unsaved::Quit)) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); if ctx.input(|i| i.viewport().minimized == Some(true)) { ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); @@ -110,7 +122,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(pending) = app.ui.windows.unsaved.clone() else { return }; #[cfg(not(target_arch = "wasm32"))] - let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt, std::mem::take(&mut app.prompt_saved)); + let (waiting_for_save, saved_by_dialog) = (app.saving_for_prompt || app.save_job.is_some(), std::mem::take(&mut app.prompt_saved)); #[cfg(target_arch = "wasm32")] let (waiting_for_save, saved_by_dialog) = (false, false); @@ -129,7 +141,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { // One row keeps the window to its contents; a bare right-to-left layout fills the screen height ui.horizontal(|ui| { - // The answers wait while the Save dialog is open + // Wait for the path picker or an active save to finish. ui.add_enabled_ui(!waiting_for_save, |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Save"))).clicked() { @@ -156,11 +168,13 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { let discard_after_create = matches!(pending, Unsaved::CreateProject(_)) && save_first == Some(false) && app.session.modified; match save_first { Some(true) => { - // An untitled project is saved from a dialog that answers on a later frame #[cfg(not(target_arch = "wasm32"))] { - app.saving_for_prompt = app.session.path.is_none(); + app.saving_for_prompt = true; + file_action(app, ctx, "file.save"); + return; } + #[cfg(target_arch = "wasm32")] file_action(app, ctx, "file.save"); } // Going ahead anyway: the changes are let go @@ -484,15 +498,16 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> }); true } - "file.save" if app.session.path.is_some() => { - if let Some(result) = app.run("file.save", json!({})) { - let saved_path = result["path"].as_str().unwrap_or_default(); - app.toast(trf("Saved {path}", &[("path", &saved_path)]), false); - } - true - } "file.save" | "file.saveAs" => { - ask_save_project(app, "file.saveAs"); + if id == "file.save" + && let Some(path) = app.session.path.clone() + { + if !app.start_save(&path, true, app.saving_for_prompt, false) { + app.saving_for_prompt = false; + } + } else { + ask_save_project(app, "file.saveAs"); + } true } "file.saveCopy" => { @@ -568,7 +583,7 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } } -/// Asks where to save the project and runs `cmd` with the answer. Each caller is its own dialog +/// Asks where to save the project and starts the worker with the answer. Each caller is its own dialog /// request, so Save As and Save a Copy queue separately. #[cfg(not(target_arch = "wasm32"))] #[track_caller] @@ -578,19 +593,11 @@ fn ask_save_project(app: &mut TextureCraftApp, cmd: &'static str) { // Save a Copy leaves the project unsaved, so it never answers the unsaved-changes prompt. let for_prompt = app.saving_for_prompt && cmd == "file.saveAs"; let asked = app.ask_file(dialog, Bound::Project, move |app, paths| { - let mut saved = false; - if let Some(p) = paths.first() { - let path = p.display().to_string(); - saved = app.run(cmd, json!({"path": path})).is_some(); - if saved { - remember(app, &path); - app.toast(trf("Saved {path}", &[("path", &path)]), false); - } - } - // The answer ends the wait. A canceled or failed save leaves the prompt open for an answer. - if for_prompt { + let for_prompt = for_prompt && app.saving_for_prompt; + let started = paths.first().is_some_and(|p| app.start_save(&p.display().to_string(), cmd != "file.saveCopy", for_prompt, true)); + // Canceled dialogs and failures leave the prompt open for another answer. + if for_prompt && !started { app.saving_for_prompt = false; - app.prompt_saved = saved && !app.session.modified; } }); // A Save As already on its way answers for itself: the prompt's buttons stay usable. diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index a8876e9e..d9ff167b 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -1,6 +1,7 @@ //! Native file dialogs answer on a later frame; the tests answer them without a window. use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; use egui::{ViewportCommand, ViewportEvent, ViewportId}; use egui_kittest::Harness; @@ -10,6 +11,8 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; use texturecraft_ui_egui::state::Unsaved; +use super::temp_dir::TempDir; + fn harness(modified: bool) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.modified = modified; @@ -198,7 +201,7 @@ fn a_mesh_change_keeps_the_answer_for_the_same_project() { answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); invoke(&mut h, "file.saveAs"); h.state_mut().session.mesh_id += 1; - h.run_steps(3); + wait_for(&mut h, |h| h.state().session.path.as_deref() == file.to_str()); assert!(file.exists(), "a reimport or a UV layout change is still the same project"); } @@ -217,6 +220,15 @@ fn sends(h: &mut Harness<'_, TextureCraftApp>, frames: usize, cmd: &ViewportComm }) } +fn wait_for(h: &mut Harness<'_, TextureCraftApp>, ready: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) { + let deadline = Instant::now() + Duration::from_secs(10); + while !ready(h) { + assert!(Instant::now() < deadline, "save did not finish"); + h.step(); + std::thread::yield_now(); + } +} + fn untitled_with_prompt(h: &mut Harness<'_, TextureCraftApp>) { h.state_mut().session.path = None; request_close(h); @@ -236,16 +248,61 @@ fn closing_during_a_stroke_finishes_it_and_asks() { #[test] fn save_in_the_prompt_goes_on_once_the_dialog_has_saved() { - let file = temp_file("prompt-save", "saved.tcraft"); + let temp = TempDir::new("prompt-save"); + for untitled in [true, false] { + let file = temp.join(if untitled { "new.tcraft" } else { "existing.tcraft" }); + let mut h = harness(true); + h.state_mut().session.path = (!untitled).then(|| file.display().to_string()); + request_close(&mut h); + let path = file.clone(); + answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); + h.get_by_label("Save").click(); + wait_for(&mut h, |h| h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close))); + assert!(file.exists()); + assert!(!h.state().session.modified); + assert!(h.state().ui.windows.unsaved.is_none()); + } +} + +#[test] +fn a_background_save_preserves_edits_made_while_the_file_is_written() { + let temp = TempDir::new("save-edits"); + let file = temp.join("project.tcraft"); let mut h = harness(true); - untitled_with_prompt(&mut h); - let path = file.clone(); - answer(&mut h, move |_| Answer::Paths(vec![path.clone()])); - h.get_by_label("Save").click(); - assert!(sends(&mut h, 5, &ViewportCommand::Close), "the close goes on after the save"); - assert!(file.exists()); - assert!(!h.state().session.modified); - assert!(h.state().ui.windows.unsaved.is_none()); + h.state_mut().session.path = Some(file.display().to_string()); + let original = h.state().session.doc.project.texture_sets[0].name.clone(); + invoke(&mut h, "file.save"); + assert!(!texturecraft_ui_egui::menus::enabled(h.state(), "file.save"), "the save returns with a worker still to collect"); + let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"})); + assert!(rename.is_some(), "editing remains available"); + + wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save")); + let saved = texturecraft_engine::formats::load_project(&file).unwrap(); + assert_eq!(saved.project.texture_sets[0].name, original, "the first save writes the snapshot it started with"); + assert_eq!(h.state().session.doc.project.texture_sets[0].name, "Edited while saving"); + assert!(h.state().session.modified, "the later edit still needs to be saved"); + + invoke(&mut h, "file.save"); + h.state_mut().run("camera.view.front", serde_json::Value::Null); + wait_for(&mut h, |h| texturecraft_ui_egui::menus::enabled(h.state(), "file.save")); + let saved = texturecraft_engine::formats::load_project(&file).unwrap(); + assert_eq!(saved.project.texture_sets[0].name, "Edited while saving"); + assert!(!h.state().session.modified, "moving the camera alone does not create an unsaved edit"); +} + +#[test] +fn a_failed_background_save_keeps_the_project_and_its_path() { + let temp = TempDir::new("save-failure"); + let file = temp.join("current.tcraft"); + let missing_parent = temp.join("missing").join("as.tcraft"); + let mut h = harness(true); + h.state_mut().session.path = Some(file.display().to_string()); + answer(&mut h, move |_| Answer::Paths(vec![missing_parent.clone()])); + invoke(&mut h, "file.saveAs"); + wait_for(&mut h, |h| h.state().toasts.iter().any(|toast| toast.error)); + assert!(h.state().session.modified); + assert_eq!(h.state().session.path.as_deref(), file.to_str()); + assert!(texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs")); } #[test] From 2e551bbd60861756ad55b7ed198df05786ea6514 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 23:21:13 +0100 Subject: [PATCH 09/80] Wait for the background save in the rename anchor tests --- crates/ui-egui/tests/it/rename_anchor.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index f8ee1763..3f0b57c3 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -42,7 +42,14 @@ fn save_to(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![path.clone()])))); let ctx = h.ctx.clone(); texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.saveAs"); - h.run_steps(3); + // The save runs on a worker: step frames until the app has collected it, as the app does + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + h.step(); + while h.state().session.modified || !texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs") { + assert!(std::time::Instant::now() < deadline, "the save did not finish"); + h.step(); + std::thread::yield_now(); + } assert!(file.exists(), "Save as wrote the project"); assert!(!h.state().session.modified, "the project counts as saved"); } From 34e8bb0d92107bdd7110ff11e5567b40e2de2004 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 23:22:49 +0100 Subject: [PATCH 10/80] Open the inherited mask effects from an instance's mask thumbnail --- crates/engine/src/layer_cmds.rs | 11 +++++++-- crates/ui-egui/src/dock.rs | 22 +++++++++++------- crates/ui-egui/tests/it/layers_panel.rs | 30 +++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 56d2fc2e..b7b38f76 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -297,8 +297,9 @@ fn select(s: &mut Session, p: &Value) -> Result { } Some(Value::String(t)) if t == "content" => StackTarget::Content, Some(v) => match v.as_u64() { - Some(e) if s.doc.project.effect(LayerId(e)).is_some_and(|(owner, _)| owner == id) => StackTarget::Effect(LayerId(e)), - _ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer")), + // An instance without a mask of its own edits the effects of the mask it draws with, as it edits that mask + Some(e) if selectable_effect(&s.doc.project, id, LayerId(e)) => StackTarget::Effect(LayerId(e)), + _ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer or of the mask it draws with")), }, None => StackTarget::Content, }; @@ -307,6 +308,12 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] })) } +/// Whether effect `effect` can be selected on layer `id`: one of its own, or one in the mask it draws with. +fn selectable_effect(project: &texturecraft_core::Project, id: LayerId, effect: LayerId) -> bool { + let Some((owner, _)) = project.effect(effect) else { return false }; + owner == id || (owner == project.mask_owner(id) && project.layers.get(&owner).and_then(|l| l.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|e| e.id == effect))) +} + fn rename(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.rename", p)?; let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.rename", "`name` is required"))?.to_string(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 9136689f..d3262ea4 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -7,7 +7,7 @@ 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, + MaterialLink, Project, Projection, Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; @@ -249,9 +249,10 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { select_all_layers(app, ui); // A thumbnail or selection can close the editor before its TextEdit sees lost focus. if let Some((id, _)) = &app.ui.rename - && let Some((owner, _)) = app.session.doc.project.effect(LayerId(*id)) + && app.session.doc.project.effect(LayerId(*id)).is_some() && app.layer_panel.expanded_effects.is_none_or(|(layer, in_mask)| { - layer != owner || !app.session.doc.project.layers.get(&layer).is_some_and(|l| stack_effects(l, in_mask).iter().any(|e| e.id.0 == *id)) + let project = &app.session.doc.project; + !project.layers.get(&layer).is_some_and(|l| stack_effects(project, l, in_mask).iter().any(|e| e.id.0 == *id)) }) { finish_effect_rename(app); @@ -497,8 +498,13 @@ fn level_x(left: f32, level: usize) -> f32 { left + ROW_LEFT_PADDING + level as f32 * INDENT + EYE_SIZE * 0.5 } -fn stack_effects(layer: &Layer, in_mask: bool) -> &[Effect] { - if in_mask { layer.mask.as_ref().map_or(&[], |mask| &mask.effects) } else { &layer.content_effects } +/// The effects `layer` lists in its mask (the mask it draws with, so an instance without its own shows its source's) or content. +fn stack_effects(project: &Project, layer: &Layer, in_mask: bool) -> Vec { + if in_mask { + project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()).map_or_else(Vec::new, |mask| mask.effects.clone()) + } else { + layer.content_effects.clone() + } } fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) { @@ -510,9 +516,9 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, if let Some((open_layer, in_mask)) = app.layer_panel.expanded_effects && open_layer == id { - let stack = stack_effects(&layer, in_mask); + let stack = stack_effects(&app.session.doc.project, &layer, in_mask); for (index, effect) in stack.iter().rev().enumerate() { - effect_row(app, ui, &layer, stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask); + effect_row(app, ui, &layer, &stack, effect, index, depth + 2, index + 1 == stack.len(), in_mask); } } @@ -715,7 +721,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize 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_stack = layer.mask.as_ref().filter(|mask| !mask.effects.is_empty()).map(|_| (layer.id, true)); + let mask_stack = (!mask.effects.is_empty()).then_some((layer.id, true)); effect_stack_thumbnail( app, &painter, diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 4deeadc6..5955a4a5 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -49,6 +49,36 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { h.run_steps(3); } +/// An instance without a mask of its own shows its source's mask thumbnail with the effect badge, so +/// that thumbnail opens the source mask's effects and each of those rows can be selected from the instance. +#[test] +fn an_instance_mask_thumbnail_opens_the_inherited_mask_effects() { + let (mut h, source) = harness(); + let instance = LayerId(id(execute(&mut h.state_mut().session, "layer.instance", &json!({"layer": source.0})).unwrap(), "layer")); + execute(&mut h.state_mut().session, "layer.rename", &json!({"layer": instance.0, "name": "Instance row"})).unwrap(); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap(); + h.run_steps(4); + assert!(h.state().session.doc.project.layers[&instance].mask.is_none(), "the instance draws with its source's mask"); + assert!(h.query_by_label("Effect M").is_none(), "stacks start closed"); + + let mask = thumb(&h, "Instance row", true); + click(&mut h, mask); + assert_eq!(h.state().session.selected_layer(), Some(instance)); + assert_eq!(h.state().session.target, StackTarget::Mask); + assert!(h.query_by_label("Effect M").is_some(), "the inherited mask effect is listed"); + click(&mut h, mask); + assert!(h.query_by_label("Effect M").is_none(), "the same thumbnail closes the stack"); + click(&mut h, mask); + + // Selecting the inherited effect through the instance keeps the instance selected and the stack open + let row = h.get_by_label("Effect M").rect(); + click(&mut h, row.center()); + let StackTarget::Effect(effect) = h.state().session.target else { panic!("{:?}", h.state().session.target) }; + assert_eq!(h.state().session.doc.project.effect(effect).map(|(owner, _)| owner), Some(source)); + assert_eq!(h.state().session.selected_layer(), Some(instance)); + assert!(h.query_by_label("Effect M").is_some(), "selecting an effect leaves its stack open"); +} + #[test] fn mask_and_content_thumbnails_toggle_their_own_stacks() { let (mut h, layer) = harness(); From 04e835fcf47b1145e95b689ff922ad6f6173310f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 23:32:05 +0100 Subject: [PATCH 11/80] Fail the save wait on an error toast and wait for the saved path --- crates/ui-egui/tests/it/rename_anchor.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index 3f0b57c3..7ff9dfac 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -45,7 +45,11 @@ fn save_to(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { // The save runs on a worker: step frames until the app has collected it, as the app does let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); h.step(); - while h.state().session.modified || !texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs") { + let target = file.display().to_string(); + while !(file.exists() && h.state().session.path.as_deref() == Some(target.as_str()) && texturecraft_ui_egui::menus::enabled(h.state(), "file.saveAs")) { + if let Some(toast) = h.state().toasts.iter().find(|toast| toast.error) { + panic!("the save failed: {}", toast.text); + } assert!(std::time::Instant::now() < deadline, "the save did not finish"); h.step(); std::thread::yield_now(); From 7d2e1523a84ed1f3da82e52b0de2f5c379b27671 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 23:40:09 +0100 Subject: [PATCH 12/80] Test inherited mask effect selection from an instance and document it --- crates/engine/src/layer_cmds.rs | 4 ++- crates/engine/tests/it/content_effects.rs | 34 +++++++++++++++++++++++ crates/ui-egui/tests/it/layers_panel.rs | 18 ++++++++++++ docs/control-protocol.md | 2 +- 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index b7b38f76..8823112f 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -311,7 +311,9 @@ fn select(s: &mut Session, p: &Value) -> Result { /// Whether effect `effect` can be selected on layer `id`: one of its own, or one in the mask it draws with. fn selectable_effect(project: &texturecraft_core::Project, id: LayerId, effect: LayerId) -> bool { let Some((owner, _)) = project.effect(effect) else { return false }; - owner == id || (owner == project.mask_owner(id) && project.layers.get(&owner).and_then(|l| l.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|e| e.id == effect))) + owner == id + || (owner == project.mask_owner(id) + && project.layers.get(&owner).and_then(|l| l.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|e| e.id == effect))) } fn rename(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index 4b761fc8..47c6b8fe 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -179,6 +179,40 @@ fn anchor_effects_added_through_instance_validate_against_source() { assert!(session.doc.project.layer(LayerId(source)).unwrap().mask.is_none()); } +#[test] +fn an_instance_selects_the_effects_of_the_mask_it_draws_with() { + let mut s = session(); + let source = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let source_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + let source_content = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let other = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let other_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": source})).unwrap(), "layer"); + let select = |s: &mut Session, effect: u64| execute(s, "layer.select", &json!({"layer": instance, "target": effect})); + + // Without a mask of its own the instance draws with the source's, so it selects that mask's effects + select(&mut s, source_mask).unwrap(); + assert_eq!(s.selected_layer(), Some(LayerId(instance))); + assert_eq!(s.target, StackTarget::Effect(LayerId(source_mask))); + + // Content effects of the source and effects of unrelated layers stay out of reach + for effect in [source_content, other_mask] { + let error = select(&mut s, effect).unwrap_err().to_string(); + assert!(error.contains("an effect id of this layer or of the mask it draws with"), "{error}"); + } + assert_ne!(other, instance); + + // An instance with its own mask draws with that one: the source's mask effects are not its own + execute(&mut s, "layer.select", &json!({"layer": instance})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let own = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + assert!(select(&mut s, source_mask).is_err()); + select(&mut s, own).unwrap(); + assert_eq!(s.target, StackTarget::Effect(LayerId(own))); +} + #[test] fn painting_into_a_content_paint_effect() { let mut s = session(); diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 5955a4a5..d3bde0a3 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -79,6 +79,24 @@ fn an_instance_mask_thumbnail_opens_the_inherited_mask_effects() { assert!(h.query_by_label("Effect M").is_some(), "selecting an effect leaves its stack open"); } +/// An instance with a mask of its own lists that mask's effects, not its source's. +#[test] +fn an_instance_with_its_own_mask_opens_its_own_mask_effects() { + let (mut h, source) = harness(); + let instance = LayerId(id(execute(&mut h.state_mut().session, "layer.instance", &json!({"layer": source.0})).unwrap(), "layer")); + execute(&mut h.state_mut().session, "layer.rename", &json!({"layer": instance.0, "name": "Instance row"})).unwrap(); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap(); + execute(&mut h.state_mut().session, "mask.add.black", &Value::Null).unwrap(); + execute(&mut h.state_mut().session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Own effect"})).unwrap(); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": instance.0})).unwrap(); + h.run_steps(4); + + let mask = thumb(&h, "Instance row", true); + click(&mut h, mask); + assert!(h.query_by_label("Own effect").is_some(), "the instance's own mask effect is listed"); + assert!(h.query_by_label("Effect M").is_none(), "the source's mask effect is not"); +} + #[test] fn mask_and_content_thumbnails_toggle_their_own_stacks() { let (mut h, layer) = harness(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bd11cb2d..cb29d5ba 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -20,7 +20,7 @@ one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. `layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer` is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and -Ctrl+click do in the Layers panel. `layer.select {all: true}` (Ctrl+A with the pointer over the +Ctrl+click do in the Layers panel. `layer.select {layer, target}` takes `content`, `mask` or an effect id: one of the layer, or of the mask it draws with. `layer.select {all: true}` (Ctrl+A with the pointer over the Layers panel) selects every shown row of the active texture set: the folder rows and the layers of open folders, not the layers of collapsed ones. `{layer, toggle: true}` on the only selected layer leaves nothing selected. `layer.visible {layers, layer}` gives every listed layer the From 3fc5d23b9f428321d65fb69ffb9df0487cfe5c95 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 22 Nov 2026 23:42:58 +0100 Subject: [PATCH 13/80] Expect an instance to select its source mask effect in the decal frame test --- crates/ui-egui/src/viewport.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 97edafed..6e81eed8 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2920,8 +2920,9 @@ mod tests { let session = &mut harness.state_mut().session; let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); - // The source effect remains a valid inherited target when selection changes to its instance - assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + // The source effect is a valid inherited target when selection changes to its instance + execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).unwrap(); + assert_eq!(session.target, texturecraft_engine::StackTarget::Effect(effect)); assert_eq!(session.ts(), 1); assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); From 7f6375bf98716f0c93d1d422dcf7edc41c9962ca Mon Sep 17 00:00:00 2001 From: supersfera Date: Tue, 24 Nov 2026 07:10:16 -0800 Subject: [PATCH 14/80] ru: state CC0-1.0 for Russian metainfo strings --- packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in | 1 + 1 file changed, 1 insertion(+) diff --git a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in index 9b14d960..65088b0f 100644 --- a/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in +++ b/packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in @@ -1,4 +1,5 @@ + From 3a444c1136d8a3ca2ad6fd07d33fb5a56039302c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 23:08:01 +0100 Subject: [PATCH 15/80] Quit after a running save when Close arrives during it --- crates/ui-egui/src/manual_save.rs | 142 +++++++++++++++++++++++++++++- crates/ui-egui/src/windows.rs | 13 +-- 2 files changed, 148 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs index c2481678..1aa3f479 100644 --- a/crates/ui-egui/src/manual_save.rs +++ b/crates/ui-egui/src/manual_save.rs @@ -8,6 +8,7 @@ use texturecraft_engine::{Result, file_cmds::SaveOutput, formats::project_file:: use crate::{ TextureCraftApp, i18n::{tr, trf}, + state::Unsaved, }; pub(crate) struct SaveJob { @@ -63,15 +64,19 @@ impl TextureCraftApp { self.saving_for_prompt = false; } + let mut quitting = false; match result { Ok(output) => { output.apply(&mut self.session); if job.remember { crate::windows::remember(self, &output.path); } - self.prompt_saved = continue_prompt && same_project && !self.session.modified && !self.session.stroke_active(); + let clean = same_project && !self.session.modified && !self.session.stroke_active(); + quitting = job.quit_after_save && clean; + self.prompt_saved = continue_prompt && clean && !quitting; self.toast(trf("Saved {path}", &[("path", &output.path)]), false); - if job.quit_after_save && same_project { + if quitting { + self.ui.windows.unsaved = None; ctx.send_viewport_cmd(egui::ViewportCommand::Close); } } @@ -81,8 +86,141 @@ impl TextureCraftApp { self.toast(message, true); } } + + // A close that the save could not finish asks about the changes it left + if job.quit_after_save && !quitting { + crate::windows::ask_to_save(self, Unsaved::Quit); + } if let Some(toast) = self.toasts.last_mut() { toast.announce = true; } } } + +#[cfg(test)] +mod tests { + use egui::{ViewportCommand, ViewportEvent, ViewportId}; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT as _, Queryable as _}; + use texturecraft_engine::file_cmds::SaveTask; + + use super::*; + + fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.modified = true; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // Match English labels independently of the system locale + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(2); + h + } + + fn temp_file(test: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("tc-manual-save-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir.join("project.tcraft") + } + + /// A save the test finishes by hand, so the close lands while it is still running + fn start_held_save(h: &mut Harness<'_, TextureCraftApp>, path: &std::path::Path, adopt: bool) -> (SaveTask, mpsc::Sender>) { + let app = h.state_mut(); + let task = app.session.save_task(&path.display().to_string(), adopt); + let (sender, output) = mpsc::channel(); + app.save_job = + Some(SaveJob { progress: Arc::default(), output, project_id: app.session.project_id, for_prompt: false, remember: false, quit_after_save: false }); + (task, sender) + } + + fn request_close(h: &mut Harness<'_, TextureCraftApp>) { + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.push(ViewportEvent::Close); + h.step(); + h.input_mut().viewports.entry(ViewportId::ROOT).or_default().events.clear(); + h.run_steps(2); + } + + /// Hands the worker's result over and reports whether the app asked to close in the next frames + fn finish(h: &mut Harness<'_, TextureCraftApp>, task: SaveTask, sender: &mpsc::Sender>) -> bool { + sender.send(task.run(None)).unwrap(); + (0..3).any(|_| { + h.step(); + h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close)) + }) + } + + fn prompt_is_usable(h: &Harness<'_, TextureCraftApp>) -> bool { + ["Save", "Don't save", "Cancel"].iter().all(|label| !h.get_by_label(label).accesskit_node().is_disabled()) + } + + #[test] + fn closing_during_a_regular_save_quits_once_it_has_saved() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-saved"); + let mut h = harness(); + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + + request_close(&mut h); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the changes are not written yet"); + assert!(h.get_by_label("Save").accesskit_node().is_disabled(), "the prompt waits for the running save"); + let closed = finish(&mut h, task, &sender); + + assert!(closed, "the close goes on after the save"); + assert!(file.exists()); + assert!(!h.state().session.modified); + assert!(h.state().ui.windows.unsaved.is_none(), "no question is left once the changes are saved"); + } + + #[test] + fn closing_during_a_failed_save_keeps_a_usable_prompt() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-failed").with_file_name("missing").join("project.tcraft"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, true); + + request_close(&mut h); + let closed = finish(&mut h, task, &sender); + + assert!(!closed); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); + assert!(prompt_is_usable(&h), "the prompt answers again after the failed write"); + } + + #[test] + fn closing_during_a_save_a_copy_keeps_the_prompt() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-copied"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, false); + + request_close(&mut h); + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "a copy leaves the project's own changes unsaved"); + assert!(file.exists()); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); + assert!(prompt_is_usable(&h)); + } + + #[test] + fn closing_during_a_save_keeps_the_prompt_for_later_edits() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-edited"); + let mut h = harness(); + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"})); + assert!(rename.is_some()); + + request_close(&mut h); + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "the edit made after the snapshot is not in the file"); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); + assert!(prompt_is_usable(&h)); + } +} diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 96d7ca0a..8f83610c 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -95,12 +95,10 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { app.toast(error.to_string(), true); } #[cfg(not(target_arch = "wasm32"))] - let waiting_for_save = if closing - && !app.session.modified - && let Some(job) = &mut app.save_job - { + let waiting_for_save = if closing && let Some(job) = &mut app.save_job { + // The running save carries the quit; unsaved changes still open the prompt meanwhile job.quit_after_save = true; - true + !app.session.modified } else { false }; @@ -164,6 +162,11 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { app.saving_for_prompt = false; + if pending == Unsaved::Quit + && let Some(job) = &mut app.save_job + { + job.quit_after_save = false; + } } } From 5b4b082c83a97e28f3f926600055d87e5c545742 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 23:26:07 +0100 Subject: [PATCH 16/80] Ask about edits made after a clean close while the save runs --- crates/ui-egui/src/manual_save.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs index 1aa3f479..2ccb9ae7 100644 --- a/crates/ui-egui/src/manual_save.rs +++ b/crates/ui-egui/src/manual_save.rs @@ -223,4 +223,25 @@ mod tests { assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit)); assert!(prompt_is_usable(&h)); } + + #[test] + fn an_edit_after_a_clean_close_asks_once_the_save_returns() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("clean-close-then-edited"); + let mut h = harness(); + h.state_mut().session.modified = false; + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + + request_close(&mut h); + assert!(h.state().ui.windows.unsaved.is_none(), "nothing to ask while the project is clean"); + let rename = h.state_mut().run("textureSet.rename", serde_json::json!({"ts": 0, "name": "Edited while saving"})); + assert!(rename.is_some()); + let closed = finish(&mut h, task, &sender); + + assert!(!closed); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the edit instead of being dropped"); + assert!(prompt_is_usable(&h)); + } } From 65af076fd6129eae114207da176aad1056badc60 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:43:08 +0100 Subject: [PATCH 17/80] Keep a close during a save pending until an open stroke ends --- crates/ui-egui/src/lib.rs | 5 +++ crates/ui-egui/src/manual_save.rs | 74 ++++++++++++++++++++++++++++++- crates/ui-egui/src/windows.rs | 8 ++++ 3 files changed, 85 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 84c103f6..2f981d6b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -332,6 +332,9 @@ pub struct TextureCraftApp { /// The unsaved-changes dialog's Save is waiting for a path or a save result. #[cfg(not(target_arch = "wasm32"))] pub(crate) saving_for_prompt: bool, + /// A close the finished save left waiting for an open stroke; decided once the stroke ends. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) quit_after_stroke: bool, /// The requested save completed; the prompt goes on at its next frame. #[cfg(not(target_arch = "wasm32"))] pub(crate) prompt_saved: bool, @@ -453,6 +456,8 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] saving_for_prompt: false, #[cfg(not(target_arch = "wasm32"))] + quit_after_stroke: false, + #[cfg(not(target_arch = "wasm32"))] prompt_saved: false, bindings: keymap::Bindings::default(), settings_bindings: keymap::Bindings::default(), diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs index 2ccb9ae7..b7eed0fe 100644 --- a/crates/ui-egui/src/manual_save.rs +++ b/crates/ui-egui/src/manual_save.rs @@ -87,9 +87,13 @@ impl TextureCraftApp { } } - // A close that the save could not finish asks about the changes it left + // A close that the save could not finish asks about the changes it left, once an open stroke ends if job.quit_after_save && !quitting { - crate::windows::ask_to_save(self, Unsaved::Quit); + if self.session.stroke_active() { + self.quit_after_stroke = true; + } else { + crate::windows::ask_to_save(self, Unsaved::Quit); + } } if let Some(toast) = self.toasts.last_mut() { toast.announce = true; @@ -143,6 +147,11 @@ mod tests { /// Hands the worker's result over and reports whether the app asked to close in the next frames fn finish(h: &mut Harness<'_, TextureCraftApp>, task: SaveTask, sender: &mpsc::Sender>) -> bool { sender.send(task.run(None)).unwrap(); + sends_close(h) + } + + /// Whether the app asks to close in the next frames + fn sends_close(h: &mut Harness<'_, TextureCraftApp>) -> bool { (0..3).any(|_| { h.step(); h.output().viewport_output.get(&ViewportId::ROOT).is_some_and(|v| v.commands.contains(&ViewportCommand::Close)) @@ -244,4 +253,65 @@ mod tests { assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the edit instead of being dropped"); assert!(prompt_is_usable(&h)); } + + /// A clean project closed during its save, with paint still held down when the save returns + fn stroke_open_when_the_save_returns(test: &str) -> Harness<'static, TextureCraftApp> { + let file = temp_file(test); + let mut h = harness(); + h.state_mut().session.modified = false; + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + request_close(&mut h); + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "the open stroke may still change the project"); + assert!(h.state().session.stroke_active()); + assert!(h.state().ui.windows.unsaved.is_none()); + h + } + + #[test] + fn a_stroke_open_when_the_save_returns_asks_once_it_is_painted() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = stroke_open_when_the_save_returns("stroke-painted"); + + h.state_mut().session.end_stroke().unwrap(); + let closed = sends_close(&mut h); + + assert!(!closed); + assert!(h.state().session.modified); + assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit), "the close asks about the painted stroke"); + } + + #[test] + fn a_stroke_open_when_the_save_returns_quits_once_it_is_canceled() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = stroke_open_when_the_save_returns("stroke-canceled"); + + h.state_mut().session.cancel_stroke(); + let closed = sends_close(&mut h); + + assert!(closed, "nothing is left to save, so the close goes on"); + assert!(h.state().ui.windows.unsaved.is_none()); + } + + #[test] + fn dismissing_the_prompt_during_a_save_cancels_the_quit() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-then-dismissed"); + let mut h = harness(); + h.state_mut().session.path = Some(file.display().to_string()); + let (task, sender) = start_held_save(&mut h, &file, true); + request_close(&mut h); + h.get_by_label("Close window").click(); + h.run_steps(2); + assert!(h.state().ui.windows.unsaved.is_none(), "the prompt is dismissed while the save runs"); + + let closed = finish(&mut h, task, &sender); + + assert!(!closed, "a dismissed prompt keeps the app open"); + assert!(!h.state().session.modified); + } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8f83610c..1c4681e7 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -94,6 +94,14 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { { app.toast(error.to_string(), true); } + #[cfg(not(target_arch = "wasm32"))] + if app.quit_after_stroke && !app.session.stroke_active() { + app.quit_after_stroke = false; + if !ask_to_save(app, crate::state::Unsaved::Quit) { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + #[cfg(not(target_arch = "wasm32"))] let waiting_for_save = if closing && let Some(job) = &mut app.save_job { // The running save carries the quit; unsaved changes still open the prompt meanwhile From 6120bdd79de129bfb712262feba6353cf64b3369 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:48:58 +0100 Subject: [PATCH 18/80] Resources Updater: find changed resource files on disk and update or relink them Image resources imported from a file remember its path and modification time. resource.status lists each resource as outdated, missing, up to date or without a file; resource.update reads changed files again and resource.relink points a resource at another file, each as one undo step that recomposites every layer using the resource. Undo and redo drop pixels decoded from bytes they replace under the same name. The shelf's Resources Updater button opens a window with the project's resources (outdated first), status and name filters, Update, Select new resource, Show in folder, Refresh and Update All. When the app gets the focus back after files changed, a notice offers to update them. Automation refuses the three commands, since they read host paths the project names. --- crates/automation/src/workspace.rs | 6 + crates/core/src/lib.rs | 2 + crates/core/src/project.rs | 5 + crates/core/src/resource_source.rs | 17 + crates/engine/src/commands.rs | 4 +- crates/engine/src/lib.rs | 8 + crates/engine/src/link_cmds.rs | 1 + crates/engine/src/reloaded_file.rs | 28 ++ crates/engine/src/resource_cmds.rs | 24 +- crates/engine/src/resource_state.rs | 15 + crates/engine/src/resource_status.rs | 39 ++ crates/engine/src/resource_update_cmds.rs | 241 +++++++++++ crates/engine/src/session.rs | 2 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/resource_updater.rs | 227 +++++++++++ crates/ui-egui/src/lib.rs | 29 +- crates/ui-egui/src/menus.rs | 3 + crates/ui-egui/src/resources_updater.rs | 383 ++++++++++++++++++ .../src/resources_updater/row_request.rs | 9 + crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/state/resources_updater.rs | 19 + crates/ui-egui/src/toast_action.rs | 34 ++ crates/ui-egui/src/toolbar.rs | 28 +- crates/ui-egui/src/windows.rs | 1 + crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/resources_updater.rs | 137 +++++++ docs/control-protocol.md | 22 +- docs/features.md | 7 + 28 files changed, 1287 insertions(+), 11 deletions(-) create mode 100644 crates/core/src/resource_source.rs create mode 100644 crates/engine/src/reloaded_file.rs create mode 100644 crates/engine/src/resource_state.rs create mode 100644 crates/engine/src/resource_status.rs create mode 100644 crates/engine/src/resource_update_cmds.rs create mode 100644 crates/engine/tests/it/resource_updater.rs create mode 100644 crates/ui-egui/src/resources_updater.rs create mode 100644 crates/ui-egui/src/resources_updater/row_request.rs create mode 100644 crates/ui-egui/src/state/resources_updater.rs create mode 100644 crates/ui-egui/src/toast_action.rs create mode 100644 crates/ui-egui/tests/it/resources_updater.rs diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index a1f18ab9..2e590e15 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -138,6 +138,9 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, + + // The Resources Updater reads the files a project names, which may lie outside the read root + "resource.status" | "resource.update" | "resource.relink" => false, _ => !id.starts_with("file.") && !has_path, }; if allowed { @@ -245,6 +248,9 @@ mod tests { assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err()); assert!(authorize_command("file.reimportMesh", &json!({})).is_ok()); assert!(authorize_command("file.close", &json!({})).is_ok()); + for id in ["resource.status", "resource.update", "resource.relink"] { + assert!(authorize_command(id, &json!({})).is_err(), "{id} reads the host paths a project names"); + } assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 88ee96d1..2c5db23b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -51,6 +51,7 @@ pub mod project; pub mod projector; pub mod ramp_curve; pub mod randomized_seed; +pub mod resource_source; mod saved_decal; mod saved_projection; pub mod selection_background; @@ -133,6 +134,7 @@ pub use project::{ pub use projector::Projector; pub use ramp_curve::RampCurve; pub use randomized_seed::RandomizedSeed; +pub use resource_source::ResourceSource; pub use selection_background::SelectionBackground; pub use shape_crop::ShapeCrop; pub use slope_blending::SlopeBlending; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 649f4f6d..a4e004ec 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -445,6 +445,10 @@ pub struct Project { /// 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]>, + /// The files image resources were imported from, by resource name (the Resources Updater + /// reads them again). Resources made in the app or imported without a file path have none. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub resource_sources: BTreeMap, } impl Project { @@ -462,6 +466,7 @@ impl Project { display: DisplaySettings::default(), cameras: Vec::new(), swatches: Vec::new(), + resource_sources: BTreeMap::new(), } } diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs new file mode 100644 index 00000000..793122cf --- /dev/null +++ b/crates/core/src/resource_source.rs @@ -0,0 +1,17 @@ +//! Where an image resource was imported from, so the Resources Updater can read it again + +use serde::{Deserialize, Serialize}; + +/// The file an image resource was read from and its modification time then. +/// +/// The resource's stored bytes are the file's bytes at that time, so a file whose size or +/// contents differ from them has changed on disk. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResourceSource { + /// Path of the file on the machine that imported it. + pub path: String, + /// The file's modification time when it was read, in milliseconds since the Unix epoch + /// (0 when unknown). An unchanged time and size skip reading the file again. + #[serde(default)] + pub modified_ms: u64, +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..bb177191 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -31,7 +31,7 @@ impl CommandSpec { /// that only return data or do nothing without parameters, and the ones that replace the /// open project (the menu asks to save first). pub fn bindable(&self) -> bool { - const NOT_FROM_A_KEY: [&str; 13] = [ + const NOT_FROM_A_KEY: [&str; 14] = [ "project.inspect", "project.templates", "project.new", @@ -45,6 +45,7 @@ impl CommandSpec { "bake.preview", "camera.set", "textureSet.settings", + "resource.status", ]; const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"]; !(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params) @@ -143,6 +144,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); v.extend(crate::resource_cmds::specs()); + v.extend(crate::resource_update_cmds::specs()); v.extend(crate::material_lib::specs()); v.extend(crate::link_cmds::specs()); v.extend(crate::smart_masks::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..0d2f8d3c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -68,7 +68,13 @@ pub mod preview; mod procedural_params; pub mod project_cmds; pub mod quick_mask; +// Reloading resource files reads paths on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod reloaded_file; pub mod resource_cmds; +pub mod resource_state; +pub mod resource_status; +pub mod resource_update_cmds; pub mod session; mod session_log; pub mod set_cmds; @@ -97,6 +103,8 @@ pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; +pub use resource_state::ResourceState; +pub use resource_status::ResourceStatus; pub use project_cmds::sample_session; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index a20182f6..1312aedd 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -623,6 +623,7 @@ impl Session { for name in old_names.iter().filter(|name| !used_names.contains(name)) { session.doc.resources.remove(name); + session.doc.project.resource_sources.remove(name); } Ok(names) diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs new file mode 100644 index 00000000..b65582d2 --- /dev/null +++ b/crates/engine/src/reloaded_file.rs @@ -0,0 +1,28 @@ +//! An image file read again for a resource, checked before the project changes + +use texturecraft_core::ResourceSource; +use texturecraft_formats::DecodedImage; + +use crate::Result; + +/// A resource's new bytes, their decoded pixels and the file they came from +pub(crate) struct ReloadedFile { + pub name: String, + pub bytes: Vec, + pub image: DecodedImage, + pub source: ResourceSource, +} + +impl ReloadedFile { + /// Read and decode `path` for resource `name` within the resource limits (`cmd` names errors) + pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result { + let file_path = std::path::Path::new(path); + + // Taken before reading, so a write during the read still shows as a change later + let modified_ms = crate::resource_update_cmds::modified_ms_of(file_path); + let bytes = crate::resource_cmds::read_resource_file(cmd, file_path, crate::resource_cmds::MAX_BYTES as u64)?; + let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{path}: {error}")))?; + + Ok(ReloadedFile { name, bytes, image, source: ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms } }) + } +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 39d9fb6c..d20cb60e 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -146,6 +146,16 @@ impl Session { self.drop_missing_image_view(); } + /// Undo and redo restore resource bytes under the same name (the Resources Updater replaces + /// them in place): the pixels decoded from the bytes `other` held are stale + pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) { + for (name, bytes) in &self.doc.resources { + if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) { + self.images.remove(name); + } + } + } + /// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back pub(crate) fn drop_missing_image_view(&mut self) { if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) { @@ -172,8 +182,18 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; + let prefix = strp(p, "prefix").unwrap_or(""); + + // Taken before reading, so a write during the read still shows as a change in the Resources Updater + let modified_ms = crate::resource_update_cmds::modified_ms_of(std::path::Path::new(path)); let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; + let source = texturecraft_core::ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms }; + + let name = s.edit("Import resource", |session| { + let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?; + session.doc.project.resource_sources.insert(name.clone(), source); + Ok(name) + })?; Ok(json!({ "name": name })) } @@ -255,6 +275,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { s.edit("Remove resource", |s| { s.doc.resources.remove(&name); + s.doc.project.resource_sources.remove(&name); Ok(()) })?; s.sync_images(); @@ -277,6 +298,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { if !unused.is_empty() { s.edit("Remove unused resources", |s| { s.doc.resources.retain(|k, _| !unused.contains(k)); + s.doc.project.resource_sources.retain(|k, _| !unused.contains(k)); Ok(()) })?; s.sync_images(); diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs new file mode 100644 index 00000000..1a3e427c --- /dev/null +++ b/crates/engine/src/resource_state.rs @@ -0,0 +1,15 @@ +//! One row of the Resources Updater: an image resource, its file and how they compare + +use crate::resource_status::ResourceStatus; + +/// An image resource, the file it came from and whether that file changed on disk +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResourceState { + /// The resource's name in the project. + pub name: String, + pub status: ResourceStatus, + /// The file it was imported from or relinked to (None: made in the app or imported without a path). + pub path: Option, + /// Why the file could not be checked (with [`ResourceStatus::Missing`]). + pub error: Option, +} diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs new file mode 100644 index 00000000..8e8efc70 --- /dev/null +++ b/crates/engine/src/resource_status.rs @@ -0,0 +1,39 @@ +//! Whether an image resource still matches the file it was imported from + +/// How an image resource compares with its file on disk. The order is the Resources Updater's +/// list order: what needs attention first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ResourceStatus { + /// The file changed since it was read: Update reads it again. + Outdated, + /// The file is gone, or cannot be read. + Missing, + /// The file still holds the resource's bytes. + UpToDate, + /// Made in the app or imported without a file path: there is nothing to compare with. + NoSource, +} + +impl ResourceStatus { + pub const ALL: [ResourceStatus; 4] = [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource]; + + /// The id used by the control protocol + pub fn id(self) -> &'static str { + match self { + ResourceStatus::Outdated => "outdated", + ResourceStatus::Missing => "missing", + ResourceStatus::UpToDate => "upToDate", + ResourceStatus::NoSource => "noSource", + } + } + + /// The name shown in the Resources Updater (English; the shell translates it) + pub fn label(self) -> &'static str { + match self { + ResourceStatus::Outdated => "Outdated", + ResourceStatus::Missing => "Missing", + ResourceStatus::UpToDate => "Up to date", + ResourceStatus::NoSource => "No source file", + } + } +} diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs new file mode 100644 index 00000000..ea69042d --- /dev/null +++ b/crates/engine/src/resource_update_cmds.rs @@ -0,0 +1,241 @@ +//! The Resources Updater: compare image resources with the files they came from, read changed +//! files again and point a resource at another file. Each change is one undo step, and every +//! layer, mask and view using a changed resource recomposites. + +use serde_json::{Value, json}; +use texturecraft_core::ResourceSource; + +use crate::commands::{CommandSpec, always, bad}; +use crate::resource_state::ResourceState; +use crate::resource_status::ResourceStatus; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "resource.status", + "Check resources on disk", + [], + None, + "{} → {resources: [{name, status: outdated|missing|upToDate|noSource, path?, error?}] (outdated first), total, outdated}", + always, + |s, _| Ok(status(s)) + ), + cmd!( + "resource.update", + "Update resources", + [], + None, + "{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step", + always, + update + ), + cmd!( + "resource.relink", + "Relink resource", + [], + None, + "{name, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", + always, + relink + ), + ] +} + +impl Session { + /// The image resources with their files and how they compare, outdated first, then by name. + /// Reads a file only when its size matches the stored bytes but its modification time does not. + pub fn resource_states(&self) -> Vec { + let sources = &self.doc.project.resource_sources; + let mut states: Vec = self + .doc + .resources + .iter() + .filter(|(name, _)| self.images.contains_key(*name) || sources.contains_key(*name)) + .map(|(name, bytes)| { + let source = sources.get(name); + let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(source, bytes)); + ResourceState { name: name.clone(), status, path: source.map(|source| source.path.clone()), error } + }) + .collect(); + + states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); + states + } + + /// Put reloaded files in place of their resources' bytes and pixels as one undo step + #[cfg(not(target_arch = "wasm32"))] + fn install_reloaded(&mut self, label: &str, files: Vec) -> Result> { + if files.is_empty() { + return Ok(Vec::new()); + } + + let decoded = self.edit(label, |session| { + let mut decoded = Vec::with_capacity(files.len()); + for file in files { + session.doc.resources.insert(file.name.clone(), std::sync::Arc::new(file.bytes)); + session.doc.project.resource_sources.insert(file.name.clone(), file.source); + decoded.push((file.name, file.image)); + } + + Ok(decoded) + })?; + + // The edit marked every set using a replaced resource for recompositing; the new pixels are read then + let mut names = Vec::with_capacity(decoded.len()); + for (name, image) in decoded { + if crate::fill_alpha::matches_saved_picture(&name, &image) { + self.library_alphas.insert(name.clone()); + } else { + self.library_alphas.remove(&name); + } + + self.images.insert(name.clone(), crate::resource_cmds::decoded(image)); + names.push(name); + } + + Ok(names) + } +} + +/// How `stored` (a resource's bytes) compares with the file `source` names now +#[cfg(not(target_arch = "wasm32"))] +fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Option) { + let path = std::path::Path::new(&source.path); + let metadata = match std::fs::metadata(path) { + Ok(metadata) if metadata.is_file() => metadata, + Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))), + Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))), + }; + + if metadata.len() != stored.len() as u64 { + return (ResourceStatus::Outdated, None); + } + + let modified_ms = modified_ms(&metadata); + if modified_ms != 0 && modified_ms == source.modified_ms { + return (ResourceStatus::UpToDate, None); + } + + // A newer time alone is not a change: the file may have been saved again unchanged + match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { + Ok(bytes) if bytes == stored => (ResourceStatus::UpToDate, None), + Ok(_) => (ResourceStatus::Outdated, None), + Err(error) => (ResourceStatus::Missing, Some(error.to_string())), + } +} + +#[cfg(target_arch = "wasm32")] +fn compare_with_file(_: &ResourceSource, _: &[u8]) -> (ResourceStatus, Option) { + (ResourceStatus::Missing, Some("file paths are not available in the browser".to_string())) +} + +/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none) +#[cfg(not(target_arch = "wasm32"))] +fn modified_ms(metadata: &std::fs::Metadata) -> u64 { + let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok()); + since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) +} + +/// [`modified_ms`] of the file at `path` (0 when it cannot be read) +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn modified_ms_of(path: &std::path::Path) -> u64 { + std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)) +} + +/// `path` made absolute against the working folder, so the record does not depend on where the app started +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn absolute_path(path: &str) -> String { + std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()) +} + +fn status(s: &Session) -> Value { + let states = s.resource_states(); + let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count(); + let resources: Vec = states + .iter() + .map(|state| { + let mut row = json!({"name": state.name, "status": state.status.id()}); + if let Some(path) = &state.path { + row["path"] = json!(path); + } + if let Some(error) = &state.error { + row["error"] = json!(error); + } + + row + }) + .collect(); + + json!({"resources": resources, "total": states.len(), "outdated": outdated}) +} + +#[cfg(not(target_arch = "wasm32"))] +fn update(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.update"; + + let names: Vec = match p.get("names") { + None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(), + Some(Value::Array(names)) => { + names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::>()? + } + Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")), + }; + + // Every name is checked before any file is read + for name in &names { + if !s.doc.resources.contains_key(name) { + return Err(bad(CMD, format!("no resource `{name}`"))); + } + if !s.doc.project.resource_sources.contains_key(name) { + return Err(bad(CMD, format!("`{name}` has no source file: relink it to a file first"))); + } + } + + // A file that cannot be read fails alone; the others still update + let (mut files, mut failed) = (Vec::new(), Vec::new()); + for name in names { + let Some(path) = s.doc.project.resource_sources.get(&name).map(|source| source.path.clone()) else { continue }; + match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &path) { + // Unchanged contents need no undo step + Ok(file) if s.doc.resources.get(&name).is_some_and(|stored| **stored == file.bytes) => {} + Ok(file) => files.push(file), + Err(error) => failed.push(json!({"name": name, "error": error.to_string()})), + } + } + + if files.is_empty() && !failed.is_empty() { + let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect(); + return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; ")))); + } + + let updated = s.install_reloaded("Update resources", files)?; + Ok(json!({"updated": updated, "failed": failed})) +} + +#[cfg(not(target_arch = "wasm32"))] +fn relink(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "resource.relink"; + + let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string(); + let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; + if !s.doc.resources.contains_key(&name) { + return Err(bad(CMD, format!("no resource `{name}`"))); + } + + let file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + let path = file.source.path.clone(); + s.install_reloaded("Relink resource", vec![file])?; + + Ok(json!({"name": name, "path": path})) +} + +#[cfg(target_arch = "wasm32")] +fn update(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.update", "file paths are not available in the browser")) +} + +#[cfg(target_arch = "wasm32")] +fn relink(_: &mut Session, _: &Value) -> Result { + Err(bad("resource.relink", "file paths are not available in the browser")) +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..beb20ab0 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -957,6 +957,7 @@ impl Session { let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; let current = std::mem::replace(&mut self.doc, restored); self.after_history(¤t); + self.forget_replaced_images(¤t); self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) @@ -977,6 +978,7 @@ impl Session { let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; let current = std::mem::replace(&mut self.doc, restored); self.after_history(¤t); + self.forget_replaced_images(¤t); self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ce9f1614..5010e30f 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -55,6 +55,7 @@ mod pbr_import; mod perf; mod polygon_fill; mod project_recovery; +mod resource_updater; mod resources_used; mod sample; mod solo; diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs new file mode 100644 index 00000000..c0d0f1dc --- /dev/null +++ b/crates/engine/tests/it/resource_updater.rs @@ -0,0 +1,227 @@ +//! The Resources Updater: image resources remember their files, a changed file shows as outdated, +//! Update reads it again (one undo step, recompositing its layers) and Relink follows another file + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{ResourceStatus, Session, execute}; + +const RESOLUTION: u32 = 64; +const SAMPLE_STRIDE: usize = 4; +const RED: [u8; 4] = [255, 0, 0, 255]; +const GREEN: [u8; 4] = [0, 255, 0, 255]; + +/// A test folder removed when dropped +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> TempDir { + let path = std::env::temp_dir().join(format!("tc-resource-updater-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + TempDir(path) + } + + fn file(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap() +} + +/// Write a `size` × `size` PNG of one colour (sizes differ between versions, so the file size changes too) +fn write_png(path: &Path, size: u32, color: [u8; 4]) { + image::RgbaImage::from_pixel(size, size, image::Rgba(color)).save(path).unwrap(); +} + +fn text(path: &Path) -> &str { + path.to_str().unwrap() +} + +/// Import `path` and show it as a base colour fill; returns the resource name +fn import_as_fill(s: &mut Session, path: &Path) -> String { + let name = execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string(); + execute(s, "layer.add.image", &json!({"name": name})).unwrap(); + s.update(); + name +} + +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() +} + +fn status_of(s: &Session, name: &str) -> ResourceStatus { + s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status +} + +#[test] +fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() { + let dir = TempDir::new("update"); + let file = dir.file("bricks.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + let before = base_colors(&s); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + + write_png(&file, 8, GREEN); + let status = execute(&mut s, "resource.status", &Value::Null).unwrap(); + + assert_eq!(status["outdated"], json!(1)); + assert_eq!(status["resources"][0]["name"], json!(name)); + assert_eq!(status["resources"][0]["status"], json!("outdated")); + + let steps = s.history_labels().len(); + let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); + s.update(); + let after = base_colors(&s); + + assert_eq!(updated["updated"], json!([name])); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(s.images[&name].width, 8, "the new pixels are decoded"); + assert_ne!(after, before, "the fill using the resource recomposited"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name"); + assert_eq!(base_colors(&s), before); + assert_eq!(status_of(&s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); + + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + s.update(); + + assert_eq!(s.images[&name].width, 8); + assert_eq!(base_colors(&s), after); +} + +#[test] +fn nothing_outdated_adds_no_undo_step() { + let dir = TempDir::new("unchanged"); + let file = dir.file("same.png"); + write_png(&file, 4, RED); + let mut s = session(); + import_as_fill(&mut s, &file); + let steps = s.history_labels().len(); + + let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); + + assert_eq!(updated["updated"], json!([])); + assert_eq!(s.history_labels().len(), steps); +} + +#[test] +fn a_missing_file_is_reported_and_updating_it_changes_nothing() { + let dir = TempDir::new("missing"); + let file = dir.file("gone.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = import_as_fill(&mut s, &file); + std::fs::remove_file(&file).unwrap(); + let steps = s.history_labels().len(); + + let state = s.resource_states().into_iter().find(|state| state.name == name).unwrap(); + let error = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap_err(); + + assert_eq!(state.status, ResourceStatus::Missing); + assert!(state.error.is_some(), "the reason is shown"); + assert!(error.to_string().contains("nothing was updated"), "{error}"); + assert_eq!(s.history_labels().len(), steps); + assert_eq!(s.images[&name].width, 4, "the resource keeps its pixels"); +} + +#[test] +fn an_unreadable_file_fails_alone_while_the_others_update() { + let dir = TempDir::new("partial"); + let (kept, gone) = (dir.file("kept.png"), dir.file("gone.png")); + write_png(&kept, 4, RED); + write_png(&gone, 4, RED); + let mut s = session(); + let kept_name = import_as_fill(&mut s, &kept); + let gone_name = import_as_fill(&mut s, &gone); + write_png(&kept, 8, GREEN); + std::fs::remove_file(&gone).unwrap(); + + let result = execute(&mut s, "resource.update", &json!({"names": [kept_name, gone_name]})).unwrap(); + + assert_eq!(result["updated"], json!([kept_name])); + assert_eq!(result["failed"][0]["name"], json!(gone_name)); + assert_eq!(s.images[&kept_name].width, 8); +} + +#[test] +fn relink_reads_another_file_and_follows_it_from_then_on() { + let dir = TempDir::new("relink"); + let (first, second) = (dir.file("first.png"), dir.file("second.png")); + write_png(&first, 4, RED); + write_png(&second, 8, GREEN); + let mut s = session(); + let name = import_as_fill(&mut s, &first); + let before = base_colors(&s); + let steps = s.history_labels().len(); + + execute(&mut s, "resource.relink", &json!({"name": name, "path": text(&second)})).unwrap(); + s.update(); + + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + assert_eq!(s.images[&name].width, 8, "the resource keeps its name and takes the new file's pixels"); + assert_ne!(base_colors(&s), before); + assert!(s.doc.project.resource_sources[&name].path.ends_with("second.png")); + + // The old file no longer matters, the new one does + write_png(&first, 16, GREEN); + assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + write_png(&second, 16, RED); + assert_eq!(status_of(&s, &name), ResourceStatus::Outdated); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link"); +} + +#[test] +fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() { + let dir = TempDir::new("reopen"); + let file = dir.file("kept.png"); + write_png(&file, 4, RED); + let mut s = session(); + let linked = import_as_fill(&mut s, &file); + let png = std::fs::read(&file).unwrap(); + let unlinked = s.import_resource_bytes("made.png", png).unwrap(); + + assert_eq!(status_of(&s, &unlinked), ResourceStatus::NoSource); + assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err()); + + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + write_png(&file, 8, GREEN); + + assert_eq!(status_of(&reopened, &linked), ResourceStatus::Outdated); +} + +#[test] +fn a_removed_resource_forgets_its_file() { + let dir = TempDir::new("remove"); + let file = dir.file("old.png"); + write_png(&file, 4, RED); + let mut s = session(); + let name = execute(&mut s, "resource.import", &json!({"path": text(&file)})).unwrap()["name"].as_str().unwrap().to_string(); + + execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); + let png = std::fs::read(&file).unwrap(); + let reused = s.import_resource_bytes("old.png", png).unwrap(); + + assert_eq!(reused, name, "the name is free again"); + assert_eq!(status_of(&s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..100d07a5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -124,6 +124,8 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; +#[cfg(not(target_arch = "wasm32"))] +mod resources_updater; mod round_gizmo; mod running_bake; pub mod saved_search; @@ -156,6 +158,7 @@ pub mod thumbs; mod tile_edits; mod tile_picture; pub mod titlebar; +pub mod toast_action; pub mod toolbar; pub mod ui_state_store; pub mod unavailable; @@ -235,6 +238,8 @@ pub struct Toast { pub error: bool, pub until: f64, pub show_log: bool, + /// A button after the text that acts on the notice + pub action: Option, } pub struct TextureCraftApp { @@ -317,6 +322,9 @@ pub struct TextureCraftApp { styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. focused: bool, + /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_notified: std::collections::BTreeSet, /// The update check and prompt (desktop only). #[cfg(not(target_arch = "wasm32"))] pub(crate) updates_rt: updates_ui::Runtime, @@ -439,6 +447,8 @@ impl TextureCraftApp { styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] + resources_notified: std::collections::BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), @@ -590,13 +600,13 @@ impl TextureCraftApp { } pub fn toast(&mut self, text: impl Into, error: bool) { - self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false }); + self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, action: None }); } /// An error toast that stays until the user dismisses it (for a problem that persists and /// is reported once, like a texture set the GPU could not hold). pub fn toast_sticky(&mut self, text: impl Into) { - self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); + self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, action: None }); } /// Start baking texture sets in the background, one after another. Invalid set indices @@ -1117,6 +1127,10 @@ impl eframe::App for TextureCraftApp { let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; + + // Files may have been edited in another app meanwhile + #[cfg(not(target_arch = "wasm32"))] + resources_updater::check_on_focus(self); } self.focused = focused; @@ -1292,6 +1306,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = theme::Tokens::get(ctx); let mut dismissed = None; let mut show_log = false; + let mut clicked_action = None; // Limit toast dimensions so the dismiss button stays visible let screen = ctx.content_rect().size(); @@ -1320,6 +1335,12 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { show_log = true; dismissed = Some(i); } + if let Some(action) = t.action + && ui.button(i18n::tr(action.label())).clicked() + { + clicked_action = Some(action); + dismissed = Some(i); + } }); if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { dismissed = Some(i); @@ -1337,4 +1358,8 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.log_channel = log_panel::LogChannel::General; crate::rail_popup::open(app, crate::docking::Panel::Log); } + + if let Some(action) = clicked_action { + action.run(app); + } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..a0fd80de 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,6 +526,9 @@ 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 app.ui.windows.resources_updater.is_some() && !popup_open && input.key_pressed(Key::Escape) { + #[cfg(not(target_arch = "wasm32"))] + crate::resources_updater::keys_in(app, input); } 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) { diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs new file mode 100644 index 00000000..4bb9ce60 --- /dev/null +++ b/crates/ui-egui/src/resources_updater.rs @@ -0,0 +1,383 @@ +//! The Resources Updater: the project's image resources and whether the files they were imported +//! from changed on disk. Update reads a changed file again, Select new resource points a resource +//! at another file, and a notice offers to update when the app gets the focus back after files +//! changed. Everything runs through `resource.status`, `resource.update` and `resource.relink`. + +mod row_request; + +use std::collections::BTreeSet; + +use egui::{Key, Modifiers}; +use serde_json::json; +use texturecraft_engine::{ResourceState, ResourceStatus}; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::ResourcesUpdater; +use crate::theme::Tokens; +use crate::toast_action::ToastAction; +use crate::web_files::IMAGE_EXTS; +use crate::widgets::primary_button; +use row_request::RowRequest; + +/// Width of the window +const WINDOW_WIDTH_POINTS: f32 = 640.0; +/// Height of the resource list +const LIST_HEIGHT_POINTS: f32 = 360.0; +// Initial space for the header, tabs, filters and footer +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0; +/// Side of a row's thumbnail +const THUMBNAIL_POINTS: f32 = 40.0; +/// Width of the name filter field +const NAME_FILTER_WIDTH_POINTS: f32 = 160.0; +/// Width of the status dropdown +const STATUS_WIDTH_POINTS: f32 = 120.0; +/// Space inside a row's frame +const ROW_MARGIN: egui::Margin = egui::Margin::same(4); +/// Strength of the danger tint behind an outdated row (the status text says it too) +const OUTDATED_TINT: f32 = 0.18; +/// How long the "changed on disk" notice stays, in seconds: long enough to reach its button +const NOTICE_SECONDS: f64 = 12.0; + +/// Opens the window, or closes it when it is open (the shelf button) +pub(crate) fn toggle(app: &mut TextureCraftApp) { + if app.ui.windows.resources_updater.take().is_none() { + open(app); + } +} + +/// Opens the window with the resources checked now (an open window is checked again) +pub(crate) fn open(app: &mut TextureCraftApp) { + let window = app.ui.windows.resources_updater.take().unwrap_or_default(); + app.ui.windows.resources_updater = Some(ResourcesUpdater { + rows: app.session.resource_states(), + project: app.session.project_id, + checked_revision: app.session.revision, + ..window + }); +} + +/// The app has the focus back: check the files again and, when other resources than last time +/// are outdated, show a notice whose button updates them +pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { + if !app.session.project_open { + return; + } + + let rows = app.session.resource_states(); + let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect(); + if let Some(window) = app.ui.windows.resources_updater.as_mut() { + window.rows = rows; + window.checked_revision = app.session.revision; + } + + if !outdated.is_empty() && outdated != app.resources_notified { + let text = if outdated.len() == 1 { + tr("1 resource changed on disk").to_string() + } else { + trf("{count} resources changed on disk", &[("count", &outdated.len())]) + }; + app.toast(text, false); + if let Some(toast) = app.toasts.last_mut() { + toast.until = app.last_time + NOTICE_SECONDS; + toast.action = Some(ToastAction::UpdateResources); + } + } + app.resources_notified = outdated; +} + +/// Read the files of `names` again (every outdated resource when None), one undo step, and say +/// what happened +pub(crate) fn update(app: &mut TextureCraftApp, names: Option>) { + let params = match names { + Some(names) => json!({ "names": names }), + None => json!({}), + }; + let Some(result) = app.run("resource.update", params) else { return }; + + let updated = result["updated"].as_array().map_or(0, Vec::len); + let failed: Vec = result["failed"] + .as_array() + .into_iter() + .flatten() + .map(|failure| format!("{}: {}", failure["name"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default())) + .collect(); + if failed.is_empty() { + app.toast(trf("Updated {count} resources", &[("count", &updated)]), false); + } else { + app.toast(trf("Updated {count} resources; could not update {failed}", &[("count", &updated), ("failed", &failed.join("; "))]), true); + } + + // What was announced is handled; a later change is announced again + app.resources_notified.clear(); +} + +/// Ask for another file for resource `name`; the resource takes its pixels and follows it +fn select_new_resource(app: &mut TextureCraftApp, name: String) { + let dialog = FileDialog::open().filter(tr("Images"), IMAGE_EXTS); + app.ask_file(dialog, Bound::Project, move |app, paths| { + let Some(path) = paths.first() else { return }; + let Some(path) = path.to_str() else { + app.toast(trf("Could not use a path that is not UTF-8: {path}", &[("path", &path.display())]), true); + return; + }; + + if app.run("resource.relink", json!({ "name": name, "path": path })).is_some() { + app.toast(trf("{name} now reads {path}", &[("name", &name), ("path", &path)]), false); + } + }); +} + +/// Show the folder holding `path` in the system's file manager +fn show_in_folder(app: &mut TextureCraftApp, path: &str) { + let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default(); + if let Err(error) = app.file_dialogs.show_folder(&folder) { + app.toast(trf("Could not show {folder}: {error}", &[("folder", &folder.display()), ("error", &error)]), true); + } +} + +/// The keys of the open window: Escape closes it (an open dropdown takes it first, see `menus`) +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { + if input.consume_key(Modifiers::NONE, Key::Escape) { + app.ui.windows.resources_updater = None; + } +} + +/// Whether `row` passes the window's status and name filters +fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool { + let name_filter = window.name_filter.trim().to_lowercase(); + window.status_filter.is_none_or(|status| row.status == status) && (name_filter.is_empty() || row.name.to_lowercase().contains(&name_filter)) +} + +/// "(N resources, M outdated)" +fn summary(rows: &[ResourceState]) -> String { + let outdated = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).count(); + trf("({count} resources, {outdated} outdated)", &[("count", &rows.len()), ("outdated", &outdated)]) +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut window) = app.ui.windows.resources_updater.take() else { return }; + + // Resources of another project are not this one's + if window.project != app.session.project_id || !app.session.project_open { + return; + } + + // Every change (an update, undo, redo, a removed resource) is checked again + if window.checked_revision != app.session.revision { + window.rows = app.session.resource_states(); + window.checked_revision = app.session.revision; + } + + let tokens = Tokens::get(ctx); + let mut open = true; + let (mut refresh, mut update_all) = (false, false); + let mut request = None; + + crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut open) + .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) + .show(ctx, |ui| { + ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name)); + + // Shader resources have no equivalent here: the one tab lists image resources + let tab = ui.add(egui::Button::selectable(true, tr("Resources"))); + tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, true, tr("Resources"))); + ui.separator(); + + ui.horizontal(|ui| { + let status_label = ui.label(tr("Status:")); + let selected = window.status_filter.map_or(tr("All"), |status| tr(status.label())); + egui::ComboBox::from_id_salt("resources_updater_status") + .width(STATUS_WIDTH_POINTS) + .selected_text(selected) + .show_ui(ui, |ui| { + ui.selectable_value(&mut window.status_filter, None, tr("All")); + for status in ResourceStatus::ALL { + ui.selectable_value(&mut window.status_filter, Some(status), tr(status.label())); + } + }) + .response + .labelled_by(status_label.id); + + let name_label = ui.label(tr("Name filter:")); + ui.add(egui::TextEdit::singleline(&mut window.name_filter).desired_width(NAME_FILTER_WIDTH_POINTS)).labelled_by(name_label.id); + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Bottom")).clicked() { + window.jump = Some(egui::Align::Max); + } + if ui.button(tr("Top")).clicked() { + window.jump = Some(egui::Align::Min); + } + }); + }); + ui.add_space(4.0); + + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + refresh = ui.button(tr("Refresh")).clicked(); + ui.label(summary(&window.rows)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated); + let button = ui.add_enabled(outdated, primary_button(ui, tr("Update All"))); + update_all = button.on_disabled_hover_text(tr("No resource is outdated")).clicked(); + }); + }); + ui.separator(); + + let list_height = ui.available_height().max(0.0); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, false]).show(ui, |ui| { + let jump = window.jump.take(); + if jump == Some(egui::Align::Min) { + ui.scroll_to_cursor(Some(egui::Align::Min)); + } + + let visible: Vec<&ResourceState> = window.rows.iter().filter(|row| shown(&window, row)).collect(); + if visible.is_empty() { + ui.label(tr("No resources match the filters")); + } + for (index, row) in visible.into_iter().enumerate() { + if let Some(asked) = row_ui(app, ui, &tokens, index + 1, row) { + request = Some(asked); + } + } + + if jump == Some(egui::Align::Max) { + ui.scroll_to_cursor(Some(egui::Align::Max)); + } + }); + }); + }); + }); + + if !open { + return; + } + + app.ui.windows.resources_updater = Some(window); + + if refresh { + open(app); + } + if update_all { + update(app, None); + } + match request { + Some(RowRequest::Update(name)) => update(app, Some(vec![name])), + Some(RowRequest::SelectNew(name)) => select_new_resource(app, name), + Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path), + None => {} + } +} + +/// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are +/// tinted, and their status says so in words too. +fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: usize, row: &ResourceState) -> Option { + let outdated = row.status == ResourceStatus::Outdated; + let (fill, stroke) = if outdated { + (tokens.danger.gamma_multiply(OUTDATED_TINT), egui::Stroke::new(1.0, tokens.danger)) + } else { + (egui::Color32::TRANSPARENT, egui::Stroke::NONE) + }; + let mut request = None; + + egui::Frame::NONE.fill(fill).stroke(stroke).inner_margin(ROW_MARGIN).corner_radius(crate::theme::CARD_RADIUS).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + match app.session.images.get(&row.name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), &row.name, image); + ui.add(egui::Image::new(&texture).fit_to_exact_size(egui::vec2(THUMBNAIL_POINTS, THUMBNAIL_POINTS))); + } + + // A file that could not be decoded has no picture; the row keeps its place + None => ui.add_space(THUMBNAIL_POINTS), + } + ui.label(number.to_string()); + + // Buttons take their room on the right first, so the texts truncate in what is left + // Each button's accessible name says which resource it acts on + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let update = ui.add_enabled(outdated, egui::Button::new(tr("Update"))); + let update_name = format!("{} {}", tr("Update"), row.name); + update.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, outdated, &update_name)); + if update.clicked() { + request = Some(RowRequest::Update(row.name.clone())); + } + + let select = ui.button(tr("Select new resource")); + let select_name = format!("{} {}", tr("Select new resource"), row.name); + select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); + if select.clicked() { + request = Some(RowRequest::SelectNew(row.name.clone())); + } + + if let Some(path) = &row.path { + let folder = ui.button(tr("Show in folder")); + let folder_name = format!("{} {}", tr("Show in folder"), row.name); + folder.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &folder_name)); + if folder.clicked() { + request = Some(RowRequest::ShowFolder(path.clone())); + } + } + + ui.vertical(|ui| { + ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate()); + let file = row.path.as_deref().unwrap_or(tr("No source file")); + ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file); + let status = ui.label(tr(row.status.label())); + if let Some(error) = &row.error { + status.on_hover_text(error); + } + }); + }); + }); + }); + + request +} + +#[cfg(test)] +mod tests { + use std::sync::PoisonError; + + use egui_kittest::Harness; + use texturecraft_engine::Session; + + use super::*; + + fn write_png(path: &std::path::Path, size: u32) { + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap(); + } + + fn notices(app: &TextureCraftApp) -> usize { + app.toasts.iter().filter(|toast| toast.action == Some(ToastAction::UpdateResources)).count() + } + + #[test] + fn a_changed_file_is_announced_once_and_the_notice_updates_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner); + let path = std::env::temp_dir().join(format!("texturecraft-resources-notice-{}.png", std::process::id())); + write_png(&path, 4); + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); + + check_on_focus(app); + assert_eq!(notices(app), 0, "nothing changed yet"); + + write_png(&path, 8); + check_on_focus(app); + check_on_focus(app); + assert_eq!(notices(app), 1, "the same change is announced once"); + + ToastAction::UpdateResources.run(app); + std::fs::remove_file(&path).ok(); + + assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource"); + assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources")); + } +} diff --git a/crates/ui-egui/src/resources_updater/row_request.rs b/crates/ui-egui/src/resources_updater/row_request.rs new file mode 100644 index 00000000..75f0626c --- /dev/null +++ b/crates/ui-egui/src/resources_updater/row_request.rs @@ -0,0 +1,9 @@ +/// What a Resources Updater row's buttons asked for, run after the window is drawn +pub(super) enum RowRequest { + /// Update: read the resource's file again + Update(String), + /// Select new resource: ask for another file for the resource + SelectNew(String), + /// Show in folder: the folder holding this file + ShowFolder(String), +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..9f49b2e7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -14,11 +14,13 @@ mod import_row; mod library_location; mod project_config; mod resource_usage; +mod resources_updater; pub use import_resources::ImportResources; pub use import_row::ImportRow; pub use library_location::LibraryLocation; pub use project_config::ProjectConfig; pub use resource_usage::ResourceUsage; +pub use resources_updater::ResourcesUpdater; mod console_line; mod export_job; @@ -115,6 +117,9 @@ pub struct Windows { /// File > Import resources: the files added so far, imported by Import. #[serde(skip)] pub import_resources: Option, + /// The Resources Updater: the project's image resources and whether their files changed on disk. + #[serde(skip)] + pub resources_updater: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs new file mode 100644 index 00000000..46fb9d12 --- /dev/null +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -0,0 +1,19 @@ +use texturecraft_engine::{ResourceState, ResourceStatus}; + +/// The Resources Updater window: the project's image resources as last checked, and the filters +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ResourcesUpdater { + /// The resources and how they compare with their files, outdated first (checked on opening, + /// Refresh, every change and when the app gets the focus back) + pub rows: Vec, + /// The status the list is narrowed to (None: all) + pub status_filter: Option, + /// Shows only resources whose name contains this, ignoring case + pub name_filter: String, + /// Top or Bottom asked the list to scroll to that end in the next frame + pub jump: Option, + /// The project that was open when this window opened + pub project: u64, + /// The session revision the rows were checked at + pub(crate) checked_revision: u64, +} diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs new file mode 100644 index 00000000..d360fd7b --- /dev/null +++ b/crates/ui-egui/src/toast_action.rs @@ -0,0 +1,34 @@ +//! A button on a toast that acts on what the toast says + +use crate::TextureCraftApp; + +/// What a toast's button does +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToastAction { + /// "Update": read every outdated resource file again (the "changed on disk" notice) + #[cfg(not(target_arch = "wasm32"))] + UpdateResources, +} + +impl ToastAction { + /// The button's text (English; translated where it is drawn) + pub fn label(self) -> &'static str { + match self { + #[cfg(not(target_arch = "wasm32"))] + ToastAction::UpdateResources => "Update", + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn run(self, app: &mut TextureCraftApp) { + match self { + ToastAction::UpdateResources => crate::resources_updater::update(app, None), + } + } + + /// The browser's toasts carry no action yet + #[cfg(target_arch = "wasm32")] + pub(crate) fn run(self, _: &mut TextureCraftApp) { + match self {} + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 27274a1d..d36f3197 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -499,15 +499,33 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { ui.add_space(SHELF_GROUP_GAP); } - 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)); - } + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::HOURGLASS, tr("Snooze Autosave"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); + resources_updater_button(app, ui); }); }); } +/// The shelf's Resources Updater button: opens or closes its window while a project is open +#[cfg(not(target_arch = "wasm32"))] +fn resources_updater_button(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let open = app.ui.windows.resources_updater.is_some(); + let label = tr("Resources Updater"); + let button = ui.add_enabled_ui(app.session.project_open, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, label, open, SHELF_BUTTON_SIZE)).inner; + if button.on_disabled_hover_text(tr("Open a project to check its resources")).clicked() { + crate::resources_updater::toggle(app); + } +} + +/// The browser reads no files from disk, so there is nothing to update +#[cfg(target_arch = "wasm32")] +fn resources_updater_button(_: &mut TextureCraftApp, ui: &mut egui::Ui) { + ui.add_enabled_ui(false, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Resources Updater"), false, SHELF_BUTTON_SIZE)) + .inner + .on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE)); +} + /// Width of the icon rail beside the dock const RAIL_WIDTH: f32 = 38.0; diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9e8fa5c..5080d2bd 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -23,6 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { { crate::project_config::show(app, ctx); crate::import_resources::show(app, ctx); + crate::resources_updater::show(app, ctx); } crate::keymap::window(app, ctx); crate::export_window::show(app, ctx); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c8d7f0f3..82c21fcc 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -77,6 +77,7 @@ mod rail; mod reference_order; mod rename_anchor; mod reset_ui; +mod resources_updater; mod settings_window; mod shelf_click; mod shelf_drop; diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs new file mode 100644 index 00000000..298c1130 --- /dev/null +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -0,0 +1,137 @@ +//! The Resources Updater window, driven from the keyboard: the shelf button opens it, outdated +//! resources come first, Update reads a changed file again as one undo step and Select new resource +//! follows another file. File pickers are answered by the override, never shown. + +use std::path::{Path, PathBuf}; + +use egui::{Key, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +use super::temp_dir::TempDir; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).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 +} + +/// Write a `size` × `size` PNG (each size is a different file size, so a change is seen at once) +fn png(dir: &Path, name: &str, size: u32) -> PathBuf { + let file = dir.join(name); + image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(&file).unwrap(); + + file +} + +fn import(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { + h.state_mut().run("resource.import", json!({ "path": file.to_str().unwrap() })).unwrap(); + h.run_steps(2); +} + +fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) { + h.key_press(key); + h.run_steps(3); +} + +/// Move the keyboard focus to button `label` and press Enter +fn activate(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_role_and_label(Role::Button, label).focus(); + h.run_steps(2); + press(h, Key::Enter); +} + +fn shows(h: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + h.query_by_label(text).is_some() +} + +fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 { + h.state().session.images[name].width +} + +#[test] +fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() { + let dir = TempDir::new("resources-updater-update"); + let (kept, changed) = (png(&dir, "kept.png", 4), png(&dir, "changed.png", 4)); + let mut h = app(); + import(&mut h, &kept); + import(&mut h, &changed); + png(&dir, "changed.png", 8); + + activate(&mut h, "Resources Updater"); + + let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows; + assert_eq!(rows[0].name, "changed.png", "outdated resources come first"); + assert!(shows(&h, "Project : Test")); + assert!(shows(&h, "(2 resources, 1 outdated)")); + assert!(shows(&h, "Outdated"), "the status is written out, not only coloured"); + assert!(h.get_by_role_and_label(Role::Button, "Update kept.png").accesskit_node().is_disabled(), "only outdated resources update"); + + let steps = h.state().session.history_labels().len(); + activate(&mut h, "Update changed.png"); + + assert_eq!(width_of(&h, "changed.png"), 8, "the new file's pixels are in the project"); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step"); + assert!(shows(&h, "(2 resources, 0 outdated)")); + + // Undo brings the old pixels back, so the list shows the file as changed again + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + + assert_eq!(width_of(&h, "changed.png"), 4); + assert!(shows(&h, "(2 resources, 1 outdated)")); + + activate(&mut h, "Update All"); + assert_eq!(width_of(&h, "changed.png"), 8); + + press(&mut h, Key::Escape); + assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window"); +} + +#[test] +fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_list() { + let dir = TempDir::new("resources-updater-relink"); + let (first, second) = (png(&dir, "first.png", 4), png(&dir, "second.png", 4)); + let other = png(&dir, "other.png", 16); + let mut h = app(); + import(&mut h, &first); + import(&mut h, &second); + activate(&mut h, "Resources Updater"); + + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![other.clone()])))); + activate(&mut h, "Select new resource first.png"); + h.run_steps(3); + + assert_eq!(width_of(&h, "first.png"), 16, "the resource keeps its name and takes the chosen file's pixels"); + assert!(h.state().session.doc.project.resource_sources["first.png"].path.ends_with("other.png")); + + h.get_by_role_and_label(Role::TextInput, "Name filter:").focus(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Name filter:").type_text("SEC"); + h.run_steps(3); + + assert!(h.query_by_label("Update first.png").is_none(), "the filter hides other names"); + assert!(h.query_by_label("Update second.png").is_some(), "names match ignoring case"); +} + +#[test] +fn show_in_folder_shows_the_folder_of_the_resource_file() { + let dir = TempDir::new("resources-updater-folder"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + activate(&mut h, "Resources Updater"); + + activate(&mut h, "Show in folder bricks.png"); + + let shown = h.state().file_dialogs.shown_folders().to_vec(); + assert_eq!(shown.len(), 1); + assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..0cf55589 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -222,7 +222,7 @@ 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 ("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}` | 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 button and the Resources Updater button (enabled while a project is open) 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) | @@ -348,7 +348,8 @@ with `ui.inspect`, update that field and send the full `prefs` object to `ui.set File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +`file.reimportMesh` without a `path`) is refused, and so are `resource.status`, `resource.update` and `resource.relink` (they read +the files a project names) and any command given a `path` or `dir`, at the top level or in a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. @@ -465,6 +466,23 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para '{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve ``` +## Resources Updater + +An image resource imported with `resource.import {path}` remembers that file (its absolute path and +modification time, saved with the project). The shelf's Resources Updater window lists the project's +image resources through these commands and checks them again when it opens, on Refresh, after every +change and when the app gets the focus back; then a notice ("N resources changed on disk", with an +Update button) appears when the set of outdated resources changed since the last notice. + +| Command | Params and result | +|---|---| +| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | +| `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | +| `resource.relink` | `{name, path}` → `{name, path}`: the resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | + +These commands read host paths stored in the project, so MCP and `serve` refuse them through +`command_run`; the desktop app's control channel and the trusted local CLI run them. + ## PBR texture folders `file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer diff --git a/docs/features.md b/docs/features.md index 04702ee9..a3692d83 100644 --- a/docs/features.md +++ b/docs/features.md @@ -98,6 +98,13 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and alpha images become the brush alpha. Filter by role or remove selected rows before importing. Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are unavailable. The browser imports images straight from its file picker. +- **Resources Updater:** the shelf button under the tools lists the project's image resources with + their files, outdated ones first. An imported image remembers its file; when that file changes on + disk, *Update* (or *Update All*) reads it again and every layer using it recomposites, as one undo + step. *Select new resource* points a resource at another file, *Show in folder* opens its folder, + and the list filters by status and name. When the app gets the focus back after files changed, a + notice offers *Update*. Desktop only; there is no Shaders tab, since TextureCraft has no shader + resources. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under From e016ba2f1034bf29119fffff96e5ed2b3552141a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:51:25 +0100 Subject: [PATCH 19/80] Bring the Settings window in line with the reference (#823) Defaults follow the reference: the system language, Show keyboard helper, Show world axes and the baking options on, and GPU raytracing on and checkable only with a GPU. Show world axes now hides the 3D view's axes. The Iray, Appearance and Folders sections are gone, Temporary Files is Files and holds the Data folder, Recent projects limit sits in Resources, the CPU and RAM limits are sliders in steps of 1 with the core count beside them, and the section hints are removed. The Local cache directory is editable and defaults to the system's temporary folder. The shortcut list adds the reference's manipulator rows after Export Textures, listed as not available yet. --- crates/ui-egui/src/control.rs | 6 + crates/ui-egui/src/keymap.rs | 9 +- crates/ui-egui/src/lib.rs | 23 ++- crates/ui-egui/src/settings_window.rs | 211 +++++++++++---------- crates/ui-egui/src/state.rs | 24 ++- crates/ui-egui/src/viewport.rs | 4 +- crates/ui-egui/tests/it/settings_window.rs | 162 ++++++++++++---- crates/ui-egui/tests/it/shortcut_list.rs | 27 ++- crates/ui-egui/tests/project_limits.rs | 4 +- docs/ui-parity.md | 2 +- 10 files changed, 315 insertions(+), 157 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 79050e12..ab03dc37 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -111,6 +111,12 @@ fn refresh_draft_preferences(draft: &mut Prefs, previous: &Prefs, current: &Pref gpu_raytracing, libraries, background, + show_world_axes, + show_keyboard_helper, + only_selected_material_when_painting, + save_preprocessed_scene_files, + live_preview_baking, + local_cache_directory, ); } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index ee29ac48..17f8acec 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -36,7 +36,14 @@ pub struct Binding { /// /// They are not in [`bindings`], so no key runs them, but another item given their key is reported /// as sharing it. -pub static NOT_AVAILABLE_ACTIONS: [(&str, Binding); 2] = [ +pub static NOT_AVAILABLE_ACTIONS: [(&str, Binding); 9] = [ + ("file.reimportMesh", Binding { id: "ui.manipulator.toggle", group: "Viewport", label: "Show/Hide manipulator", default: Some("Q") }), + ("file.reimportMesh", Binding { id: "ui.manipulator.grow", group: "Viewport", label: "Increase the manipulator size", default: None }), + ("file.reimportMesh", Binding { id: "ui.manipulator.shrink", group: "Viewport", label: "Decrease the manipulator size", default: Some("-") }), + ("file.reimportMesh", Binding { id: "ui.manipulator.space", group: "Viewport", label: "Cycle through manipulation spaces", default: Some("T") }), + ("file.reimportMesh", Binding { id: "ui.warpEdit", group: "Viewport", label: "Toggle warp edition mode", default: Some("Shift+V") }), + ("file.reimportMesh", Binding { id: "ui.manipulator.translate", group: "Viewport", label: "Translate tool", default: Some("W") }), + ("file.reimportMesh", Binding { id: "ui.manipulator.rotate", group: "Viewport", label: "Rotate tool", default: Some("E") }), ("file.reimportMesh", Binding { id: "ui.pauseEngine", group: "Commands", label: "Pause Engine Computation", default: Some("Shift+Esc") }), ("viewport.frame", Binding { id: "ui.toggleAnimation", group: "Viewport", label: "Toggle animation", default: Some("Space") }), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..f6b25a0f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -342,11 +342,8 @@ pub(crate) fn start_ui(saved: Option, session: &mut Session) -> UiState ui.tool_settings.apply(&mut session.tool); ui } - None => { - let mut ui = UiState::default(); - ui.prefs.language = i18n::SYSTEM_LANGUAGE.into(); - ui - } + // The default language follows the operating system + None => UiState::default(), } } @@ -1228,13 +1225,25 @@ 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 folder for a `Prefs::local_cache_directory` value: that path when it is absolute, +/// otherwise the system's temporary folder. +#[cfg(not(target_arch = "wasm32"))] +pub fn local_cache_folder(pref: &str) -> std::path::PathBuf { + let chosen = std::path::Path::new(pref.trim()); + if chosen.is_absolute() { + return chosen.to_path_buf(); + } + + std::env::temp_dir() +} + +/// The data folder in use (Settings › Files › Data folder). #[cfg(not(target_arch = "wasm32"))] pub fn data_dir() -> std::path::PathBuf { DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder("")) } -/// `` in the data folder in use (Settings › Folders › Data folder). +/// `` in the data folder in use (Settings › Files › Data folder). #[cfg(not(target_arch = "wasm32"))] pub fn user_dir(sub: &str) -> std::path::PathBuf { data_dir().join(sub) diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index 8fda17b0..7da312bc 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -9,7 +9,7 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{LANGUAGES, SYSTEM_LANGUAGE, n_, tr, trf}; use crate::state::{CAMERA_SPEED_RANGE, LibraryLocation, MAX_RECENT_PROJECTS, Prefs}; -use crate::theme::{Accent, Brightness, Tokens, caption}; +use crate::theme::{Tokens, caption}; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; @@ -274,9 +274,17 @@ fn section(ui: &mut Ui, title: &str) { ui.add_space(2.0); } -/// A disabled check box in the right column of a row labelled `label`. -fn disabled_check(ui: &mut Ui, label: egui::Id, mut checked: bool) { - not_available(ui.add_enabled(false, egui::Checkbox::without_text(&mut checked)).labelled_by(label)); +/// A check box in the right column of a row labelled `label`. +fn check(ui: &mut Ui, label: egui::Id, checked: &mut bool) { + ui.add(egui::Checkbox::without_text(checked)).labelled_by(label); +} + +/// A check box with its text. +fn text_check(ui: &mut Ui, text: &str, checked: &mut bool) { + ui.horizontal(|ui| { + ui.add_space(12.0); + ui.checkbox(checked, tr(text)); + }); } /// A disabled check box with its text. @@ -306,6 +314,35 @@ pub fn gpu_note_shown(adapter: Option<&str>) -> bool { adapter.is_none() || cfg!(target_arch = "wasm32") } +/// The Enable GPU raytracing check box for the hardware and the stored choice: whether it can be +/// changed and whether it shows ticked. Without a GPU to trace on it is off and disabled; the +/// stored choice is kept for a machine that has one. +pub fn gpu_raytracing_check(adapter: Option<&str>, stored: bool) -> (bool, bool) { + let supported = !gpu_note_shown(adapter); + (supported, supported && stored) +} + +/// The Max CPU threads slider's position for a stored `work_threads`: 0 (every thread) is the +/// slider's end, the core count. +#[cfg(not(target_arch = "wasm32"))] +fn work_threads_shown(work_threads: u32, cores: u32) -> u32 { + if work_threads == 0 { cores } else { work_threads.min(cores).max(1) } +} + +/// The stored `work_threads` for the slider at `threads`: its end keeps 0, so every thread works +/// on any machine. +#[cfg(not(target_arch = "wasm32"))] +fn work_threads_stored(threads: u32, cores: u32) -> u32 { + if threads >= cores { 0 } else { threads } +} + +/// The note right of a core slider: how many cores this machine has. +#[cfg(not(target_arch = "wasm32"))] +fn cores_in_total(ui: &mut Ui, cores: u32) { + let tk = Tokens::get(ui.ctx()); + ui.label(RichText::new(trf("{count} cores in total", &[("count", &cores)])).color(tk.text_dim)); +} + /// The General page. fn general( ui: &mut Ui, @@ -339,8 +376,8 @@ fn general( .response .labelled_by(label); }); - row(ui, tr("Show keyboard helper"), |ui, label| disabled_check(ui, label, true)); - row(ui, tr("Show world axes"), |ui, label| disabled_check(ui, label, true)); + row(ui, tr("Show keyboard helper"), |ui, label| check(ui, label, &mut p.show_keyboard_helper)); + row(ui, tr("Show world axes"), |ui, label| check(ui, label, &mut p.show_world_axes)); row(ui, tr("Background color"), |ui, _| { for (index, side, name) in [(0, "top", "Top background"), (1, "bottom", "Bottom background")] { let id = format!("settings_background_{side}"); @@ -352,20 +389,17 @@ fn general( ui.add_space(10.0); } }); - row(ui, tr("Only display the selected material when painting"), |ui, label| disabled_check(ui, label, false)); + row(ui, tr("Only display the selected material when painting"), |ui, label| check(ui, label, &mut p.only_selected_material_when_painting)); row(ui, tr("Viewport Scaling"), |ui, label| { - ui.add_enabled_ui(false, |ui| { - not_available( - egui::ComboBox::from_id_salt("settings_viewport_scaling").width(CONTROL_WIDTH).selected_text(tr("Auto")).show_ui(ui, |_| {}).response, - ) + // Auto is the one scaling the views have + egui::ComboBox::from_id_salt("settings_viewport_scaling") + .width(CONTROL_WIDTH) + .selected_text(tr("Auto")) + .show_ui(ui, |ui| { + ui.add(egui::Button::selectable(true, tr("Auto"))); + }) + .response .labelled_by(label); - }); - }); - - row(ui, tr("Recent projects limit"), |ui, label| { - 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.")); }); section(ui, n_("LAYER STACK OPTIONS")); @@ -397,12 +431,17 @@ fn general( } section(ui, n_("BAKING OPTIONS")); - disabled_text_check(ui, n_("Save preprocessed scene files"), true); - disabled_text_check(ui, n_("Enable live preview baking process"), true); + text_check(ui, n_("Save preprocessed scene files"), &mut p.save_preprocessed_scene_files); + text_check(ui, n_("Enable live preview baking process"), &mut p.live_preview_baking); + let (gpu_raytracing_enabled, mut gpu_raytracing_ticked) = gpu_raytracing_check(gpu, p.gpu_raytracing); ui.horizontal(|ui| { ui.add_space(12.0); - ui.checkbox(&mut p.gpu_raytracing, tr("Enable GPU raytracing")) + let gpu_raytracing = ui + .add_enabled(gpu_raytracing_enabled, egui::Checkbox::new(&mut gpu_raytracing_ticked, tr("Enable GPU raytracing"))) .on_hover_text(tr("Bakes cast their rays on the graphics card when one is available. Off, they run on the CPU.")); + if gpu_raytracing.changed() { + p.gpu_raytracing = gpu_raytracing_ticked; + } }); if gpu_note_shown(gpu) { ui.horizontal(|ui| { @@ -413,6 +452,17 @@ fn general( section(ui, n_("PREVIEW OPTIONS")); row(ui, tr("Local cache directory"), |ui, label| { + #[cfg(not(target_arch = "wasm32"))] + { + let default = crate::local_cache_folder("").display().to_string(); + ui.add(egui::TextEdit::singleline(&mut p.local_cache_directory).hint_text(default).desired_width(CONTROL_WIDTH - 24.0)).labelled_by(label); + if ui.add(egui::Button::new("R").frame(false)).on_hover_text(tr("Reset to the default folder")).clicked() { + p.local_cache_directory.clear(); + } + } + + // The browser has no folders + #[cfg(target_arch = "wasm32")] ui.add_enabled_ui(false, |ui| { let mut path = String::new(); not_available(ui.add(egui::TextEdit::singleline(&mut path).desired_width(CONTROL_WIDTH - 24.0))).labelled_by(label); @@ -431,7 +481,7 @@ fn general( not_available(ui.add_enabled(false, egui::Button::new(text).min_size(vec2(CONTROL_WIDTH, 40.0)))); }); - section(ui, n_("TEMPORARY FILES")); + section(ui, n_("FILES")); row(ui, tr("Cache directory"), |ui, label| { #[cfg(not(target_arch = "wasm32"))] let mut path = std::env::temp_dir().display().to_string(); @@ -442,57 +492,19 @@ fn general( not_available(ui.add(egui::Button::new("R").frame(false))); }); }); + #[cfg(not(target_arch = "wasm32"))] + row(ui, tr("Data folder"), |ui, label| { + 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() { + *pick = Some(SettingsFolder::DataFolder); + } + }); section(ui, n_("SPARSE VIRTUAL TEXTURE")); disabled_text_check(ui, n_("Hardware support acceleration"), true); - section(ui, n_("IRAY HARDWARE")); - disabled_text_check(ui, gpu.unwrap_or(n_("no GPU")), true); - disabled_text_check(ui, n_("CPU"), false); - // TextureCraft's own settings, after the reference sections - section(ui, n_("APPEARANCE")); - row(ui, tr("Interface scale"), |ui, label| { - ui.add(egui::Slider::new(&mut p.ui_scale, 0.75..=2.0).fixed_decimals(2)).labelled_by(label); - }); - row(ui, tr("Brightness"), |ui, label| { - egui::ComboBox::from_id_salt("settings_brightness") - .width(140.0) - .selected_text(tr(p.brightness.label())) - .show_ui(ui, |ui| { - for b in Brightness::ALL { - ui.selectable_value(&mut p.brightness, b, tr(b.label())); - } - }) - .response - .labelled_by(label); - }); - row(ui, tr("Accent color"), |ui, _| { - for a in Accent::ALL { - let (rect, resp) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, p.accent == a, tr(a.label()))); - let ring = if p.accent == a { - tk.text_strong - } else if resp.hovered() { - tk.text_dim - } else { - Color32::TRANSPARENT - }; - ui.painter().circle(rect.center(), 6.5, a.colors(tk.dark).0, egui::Stroke::NONE); - ui.painter().circle_stroke(rect.center(), 9.0, egui::Stroke::new(1.5, ring)); - if resp.on_hover_text(tr(a.label())).clicked() { - p.accent = a; - } - } - }); - #[cfg(not(target_arch = "wasm32"))] - { - row(ui, tr("Title bar"), |ui, _| { - ui.checkbox(&mut p.system_title_bar, tr("System title bar (applies on restart)")) - .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); - }); - } - section(ui, n_("VIEWPORT")); row(ui, tr("Texture resolution"), |ui, _| { ui.horizontal(|ui| { @@ -510,15 +522,22 @@ fn general( #[cfg(not(target_arch = "wasm32"))] { row(ui, tr("Max CPU threads for work"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.work_threads).range(0..=available_cores)) + let mut threads = work_threads_shown(p.work_threads, available_cores); + let slider = ui + .add(egui::Slider::new(&mut threads, 1..=available_cores.max(1)).step_by(1.0)) .labelled_by(label) - .on_hover_text(tr("Threads that paint, bake and export. 0 uses every CPU thread. Applies on restart.")); + .on_hover_text(tr("Threads that paint, bake and export. Applies on restart.")); + if slider.changed() { + p.work_threads = work_threads_stored(threads, available_cores); + } + cores_in_total(ui, available_cores); }); row(ui, tr("Cores kept for the UI"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label); + ui.add(egui::Slider::new(&mut p.reserved_cores, 0..=available_cores).step_by(1.0)).labelled_by(label); + cores_in_total(ui, available_cores); }); row(ui, tr("Max RAM while saving"), |ui, label| { - ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label); + ui.add(egui::Slider::new(&mut p.save_ram_percent, 0..=100).step_by(1.0).suffix(" %")).labelled_by(label); let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); }); @@ -528,10 +547,11 @@ fn general( .labelled_by(label) .on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects.")); }); - #[cfg(not(target_arch = "wasm32"))] - { - note(ui, tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")); - } + row(ui, tr("Recent projects limit"), |ui, label| { + 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.")); + }); #[cfg(not(target_arch = "wasm32"))] { @@ -539,38 +559,9 @@ fn general( row(ui, tr("Autosave every"), |ui, label| { ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))).labelled_by(label); }); - note(ui, &trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])); - - section(ui, n_("FOLDERS")); - row(ui, tr("Data folder"), |ui, label| { - 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() { - *pick = Some(SettingsFolder::DataFolder); - } - }); - for (label, dir) in [(tr("Smart materials"), crate::library_dir()), (tr("UI layouts"), crate::user_dir("layouts"))] { - row(ui, label, |ui, _| ui.label(RichText::new(dir.display().to_string()).small().color(tk.text_dim))); - } - 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.", - ), - ); } } -/// A small dim note under a section's rows. -#[cfg(not(target_arch = "wasm32"))] -fn note(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.add_space(12.0); - ui.add(egui::Label::new(RichText::new(text).small().color(tk.text_dim)).wrap()); - }); -} - /// The built-in library locations as (name, path): the user's assets in the data folder, the /// assets built into TextureCraft, and the font folders text alphas read. pub fn built_in_locations() -> Vec<(String, String)> { @@ -797,6 +788,16 @@ mod tests { assert_eq!(app.next_autosave, 70.0, "an unchanged interval keeps the deadline"); } + #[test] + fn max_cpu_threads_shows_every_thread_at_the_slider_end_and_keeps_it_as_every_thread() { + let cores = 8; + + assert_eq!(work_threads_shown(0, cores), cores, "every thread is the slider's end"); + assert_eq!(work_threads_shown(64, cores), cores, "a larger machine's choice stays inside this one"); + assert_eq!(work_threads_stored(cores, cores), 0, "the end follows any machine's core count"); + assert_eq!(work_threads_stored(work_threads_shown(3, cores), cores), 3); + } + #[test] fn a_folder_answer_cannot_edit_a_reopened_settings_window() { let session = texturecraft_engine::Session::closed().unwrap(); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..9d97f54d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -187,6 +187,22 @@ pub struct Prefs { /// The plain background of the 3D and 2D views at Environment Opacity 0 (Settings > General > /// Background color): the color at the top and at the bottom, linear RGB. pub background: [[f32; 3]; 2], + /// The 3D view draws the X, Y and Z axes in its corner. + pub show_world_axes: bool, + /// Settings > General > Show keyboard helper. Stored only: TextureCraft has no keyboard helper yet. + pub show_keyboard_helper: bool, + /// Settings > General > Only display the selected material when painting. Stored only: the + /// views always show every texture set. + pub only_selected_material_when_painting: bool, + /// Settings > Baking options > Save preprocessed scene files. Stored only: bakes keep no + /// preprocessed scene files. + pub save_preprocessed_scene_files: bool, + /// Settings > Baking options > Enable live preview baking process. Stored only: the live bake + /// preview always runs. + pub live_preview_baking: bool, + /// Settings > Preview options > Local cache directory (desktop). Empty or relative: the + /// system's temporary folder. Stored only: TextureCraft writes no preview cache yet. + pub local_cache_directory: String, } /// The orbit speed the built-in navigation runs at. @@ -200,7 +216,7 @@ impl Default for Prefs { ui_scale: 1.0, autosave_minutes: 10, recent_projects_limit: 10, - language: "en".into(), + language: crate::i18n::SYSTEM_LANGUAGE.into(), viewport_texture: 0, brightness: crate::theme::Brightness::default(), accent: crate::theme::Accent::default(), @@ -218,6 +234,12 @@ impl Default for Prefs { gpu_raytracing: true, libraries: Vec::new(), background: texturecraft_render::DEFAULT_BACKGROUND, + show_world_axes: true, + show_keyboard_helper: true, + only_selected_material_when_painting: false, + save_preprocessed_scene_files: true, + live_preview_baking: true, + local_cache_directory: String::new(), } } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..7a83ccf6 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1101,7 +1101,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin solo_notice(app, ui, rect); view_header(app, ui, rect, "v3d"); mask_view_badge(app, ui, rect); - axis_gizmo(ui, rect, app, None); + if app.ui.prefs.show_world_axes { + axis_gizmo(ui, rect, app, None); + } crate::nav_buttons::show(app, ui, rect, crate::nav_buttons::NavView::Scene); } diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index 4e8508b1..7ca014c9 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -4,8 +4,10 @@ use egui::{Event, Key, Modifiers, Role}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::Session; -use texturecraft_ui_egui::settings_window::{DEFAULT_LIBRARY_NOTE, GPU_RAYTRACING_UNAVAILABLE, PROJECT_OPEN_NOTE, SHORTCUT_ERRORS, SettingsPage}; -use texturecraft_ui_egui::state::{LibraryLocation, UiState}; +use texturecraft_ui_egui::settings_window::{ + DEFAULT_LIBRARY_NOTE, GPU_RAYTRACING_UNAVAILABLE, PROJECT_OPEN_NOTE, SHORTCUT_ERRORS, SettingsPage, gpu_raytracing_check, +}; +use texturecraft_ui_egui::state::{LibraryLocation, Prefs, UiState}; use texturecraft_ui_egui::unavailable::NOT_AVAILABLE; use texturecraft_ui_egui::{TextureCraftApp, menus}; @@ -84,47 +86,126 @@ fn the_left_column_switches_between_the_three_pages() { fn the_general_page_starts_at_the_reference_defaults() { let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); open_settings(&mut h); - h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs.language = texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE.into(); + + // A reset puts the defaults in the window; the app itself keeps English for the exact-text checks + h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs = Prefs::default(); h.run_steps(3); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Language").value().as_deref(), Some("Default (System Language)")); - assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Viewport Scaling").value().as_deref(), Some("Auto")); + let scaling = h.get_by_role_and_label(Role::ComboBox, "Viewport Scaling"); + assert_eq!(scaling.value().as_deref(), Some("Auto")); + assert!(!scaling.accesskit_node().is_disabled(), "Viewport Scaling can be opened"); assert_eq!(h.get_by_role_and_label(Role::SpinButton, "Local cache budget (in MB)").accesskit_node().numeric_value(), Some(4000.0)); - for label in [ - "Show keyboard helper", - "Show world axes", - "Use simplified thumbnails (improves performance)", - "Save preprocessed scene files", - "Enable live preview baking process", - "Enable GPU raytracing", - "Hardware support acceleration", - ] { + for label in ["Show keyboard helper", "Show world axes", "Save preprocessed scene files", "Enable live preview baking process"] { + assert!(toggled(&h, label), "{label} is ticked"); + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} can be changed"); + } + for label in ["Use simplified thumbnails (improves performance)", "Hardware support acceleration"] { assert!(toggled(&h, label), "{label} is ticked"); } - for label in ["Only display the selected material when painting", "CPU"] { - assert!(!toggled(&h, label), "{label} is not ticked"); - } + let only_selected = "Only display the selected material when painting"; + assert!(!toggled(&h, only_selected) && !h.get_by_label(only_selected).accesskit_node().is_disabled()); assert!(h.query_all_by_label("Inverse direction").all(|node| node.accesskit_node().toggled() == Some(egui::accesskit::Toggled::False))); - let prefs = texturecraft_ui_egui::state::Prefs::default(); + let local_cache = h.get_by_role_and_label(Role::TextInput, "Local cache directory"); + assert!(!local_cache.accesskit_node().is_disabled(), "the local cache directory can be edited"); + assert_eq!(texturecraft_ui_egui::local_cache_folder(&Prefs::default().local_cache_directory), std::env::temp_dir()); + + let prefs = Prefs::default(); + assert_eq!(prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE, "a reset follows the system language"); assert_eq!((prefs.rotation_speed, prefs.zoom_speed, prefs.wheel_speed), (2.0, 1.0, 1.0)); } +#[test] +fn the_general_page_keeps_the_reference_sections_and_moves_data_folder_and_recent_projects() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + + for gone in ["TEMPORARY FILES", "IRAY HARDWARE", "APPEARANCE", "FOLDERS", "PRIVACY", "Interface scale", "Accent color"] { + assert!(h.query_by_label(gone).is_none(), "{gone} is not on the page"); + } + for hint in ["Saving uses the other cores", "0 turns autosave off", "A new folder applies on restart"] { + assert!(h.query_by_label_contains(hint).is_none(), "the hint \"{hint}\" is gone"); + } + + let top = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_by_label(label).rect().top(); + let data_folder = h.get_by_role_and_label(Role::TextInput, "Data folder").rect().top(); + assert!(top(&h, "FILES") < data_folder && data_folder < top(&h, "SPARSE VIRTUAL TEXTURE"), "Data folder is in Files"); + let recent = h.get_by_role_and_label(Role::SpinButton, "Recent projects limit").rect().top(); + assert!(top(&h, "RESOURCES") < recent && recent < top(&h, "AUTOSAVE"), "Recent projects limit is in Resources"); + assert!(top(&h, "INTERFACE OPTIONS") < top(&h, "RESOURCES")); +} + +#[test] +fn the_resource_sliders_step_by_one_and_follow_the_arrow_keys() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + + let threads = h.get_by_role_and_label(Role::Slider, "Max CPU threads for work").accesskit_node(); + let cores = threads.max_numeric_value().unwrap(); + assert_eq!(threads.numeric_value(), Some(cores), "every thread works by default"); + assert_eq!(threads.min_numeric_value(), Some(1.0)); + let reserved = h.get_by_role_and_label(Role::Slider, "Cores kept for the UI").accesskit_node(); + assert_eq!((reserved.min_numeric_value(), reserved.max_numeric_value()), (Some(0.0), Some(cores))); + let ram = h.get_by_role_and_label(Role::Slider, "Max RAM while saving").accesskit_node(); + assert_eq!((ram.min_numeric_value(), ram.max_numeric_value()), (Some(0.0), Some(100.0))); + for label in ["Max CPU threads for work", "Cores kept for the UI", "Max RAM while saving"] { + assert_eq!(h.get_by_role_and_label(Role::Slider, label).accesskit_node().numeric_value_step(), Some(1.0), "{label} moves in steps of 1"); + } + assert_eq!(h.query_all_by_label(&format!("{cores} cores in total")).count(), 2, "both core sliders name the total"); + + let ram_percent = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.save_ram_percent; + let before = ram_percent(&h); + h.get_by_role_and_label(Role::Slider, "Max RAM while saving").focus(); + h.run_steps(2); + press_key(&mut h, Key::ArrowRight); + assert_eq!(ram_percent(&h), before + 1, "the right arrow adds one percent"); + press_key(&mut h, Key::ArrowLeft); + press_key(&mut h, Key::ArrowLeft); + assert_eq!(ram_percent(&h), before - 1, "the left arrow takes one percent"); +} + +#[test] +fn the_enabled_interface_options_answer_the_keyboard() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + let draft = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.clone(); + let before = draft(&h); + + for label in ["Show keyboard helper", "Show world axes", "Only display the selected material when painting"] { + h.get_by_label(label).focus(); + h.run_steps(2); + press_key(&mut h, Key::Space); + } + + let after = draft(&h); + assert_ne!(after.show_keyboard_helper, before.show_keyboard_helper); + assert_ne!(after.show_world_axes, before.show_world_axes); + assert_ne!(after.only_selected_material_when_painting, before.only_selected_material_when_painting); +} + +#[test] +fn the_local_cache_directory_takes_a_folder_and_r_goes_back_to_the_default() { + let mut h = harness(Session::closed().unwrap()); + open_settings(&mut h); + let folder = std::env::temp_dir().join("tc-settings-local-cache").display().to_string(); + let stored = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.local_cache_directory.clone(); + + type_into(&mut h, "Local cache directory", &folder); + assert_eq!(stored(&h), folder); + + h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().click(); + h.run_steps(3); + assert!(stored(&h).is_empty(), "R goes back to the default folder"); +} + #[test] fn a_control_the_app_lacks_is_disabled_and_says_so_on_hover() { let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); h.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); open_settings(&mut h); let away = h.get_by_role_and_label(Role::Tab, "Libraries").rect().center(); - for label in [ - "Show keyboard helper", - "Show world axes", - "Only display the selected material when painting", - "Use simplified thumbnails (improves performance)", - "Save preprocessed scene files", - "Enable live preview baking process", - "Hardware support acceleration", - "CPU", - ] { + for label in ["Use simplified thumbnails (improves performance)", "Hardware support acceleration"] { h.hover_at(away); h.run_steps(3); assert!(h.query_by_label(NOT_AVAILABLE).is_none(), "no hint before hovering {label}"); @@ -139,7 +220,6 @@ fn a_control_the_app_lacks_is_disabled_and_says_so_on_hover() { for step in ["−", "+"] { assert!(h.query_all_by_label(step).any(|node| node.accesskit_node().is_disabled()), "the cache budget's {step} is disabled"); } - assert!(!h.get_by_label("Enable GPU raytracing").accesskit_node().is_disabled(), "GPU raytracing switches bakes to the CPU"); for label in ["Rotation speed", "Zoom speed", "Wheel speed"] { assert!(h.query_by_label(label).is_some(), "{label} is shown"); } @@ -151,7 +231,7 @@ fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() { let before = h.state().ui.prefs.clone(); open_settings(&mut h); h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0); - click(&mut h, "Enable GPU raytracing"); + click(&mut h, "Show world axes"); h.run_steps(2); assert_eq!(h.state().ui.prefs, before, "edits wait for OK"); click(&mut h, "Cancel"); @@ -165,20 +245,20 @@ fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() { "a new window starts from the settings in use" ); h.get_by_role_and_label(Role::SpinButton, "Autosave every").set_value_accesskit(25.0); - h.get_by_role_and_label(Role::SpinButton, "Max CPU threads for work").set_value_accesskit(1.0); + h.get_by_role_and_label(Role::Slider, "Max CPU threads for work").set_value_accesskit(1.0); h.get_by_role_and_label(Role::SpinButton, "Max project size on open").set_value_accesskit(12.0); h.run_steps(2); h.query_all_by_label("Inverse direction").next().unwrap().scroll_to_me(); h.run_steps(3); h.query_all_by_label("Inverse direction").next().unwrap().click(); h.run_steps(2); - click(&mut h, "Enable GPU raytracing"); + click(&mut h, "Show world axes"); click(&mut h, "OK"); let prefs = h.state().ui.prefs.clone(); assert!(!h.state().ui.windows.settings, "OK closes the window"); assert_eq!((prefs.autosave_minutes, prefs.work_threads, prefs.project_open_limit_gib), (25, 1, 12)); - assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.gpu_raytracing); + assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.show_world_axes); assert!(prefs.drag_zoom_scale() < 0.0, "inverted zoom runs the other way"); let mut storage = MemoryStorage::default(); @@ -434,16 +514,22 @@ fn the_libraries_page_hides_the_add_row_with_a_project_open_and_explains_the_def } #[test] -fn the_baking_options_say_when_there_is_no_gpu_to_trace_on() { - // The condition, with and without an adapter (the harness's own adapter is not under test) +fn gpu_raytracing_is_on_and_checkable_with_a_gpu_and_off_and_disabled_without() { + let with_gpu = !cfg!(target_arch = "wasm32"); + assert_eq!(gpu_raytracing_check(Some("Some GPU"), true), (with_gpu, with_gpu), "a GPU keeps it on and checkable"); + assert_eq!(gpu_raytracing_check(Some("Some GPU"), false), (with_gpu, false), "a GPU shows the stored choice"); + assert_eq!(gpu_raytracing_check(None, true), (false, false), "without a GPU it is off and disabled"); assert!(texturecraft_ui_egui::settings_window::gpu_note_shown(None)); - assert_eq!(texturecraft_ui_egui::settings_window::gpu_note_shown(Some("Some GPU")), cfg!(target_arch = "wasm32")); - // The page shows the note exactly when the harness has no adapter (the IRAY HARDWARE row says "no GPU") + // The page follows the harness's own adapter, whichever it has let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); open_settings(&mut h); - 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"); + let supported = h.state().render_state.is_some() && with_gpu; + let check = h.get_by_label("Enable GPU raytracing"); + assert_eq!(!check.accesskit_node().is_disabled(), supported, "it can be changed exactly when there is a GPU"); + assert_eq!(toggled(&h, "Enable GPU raytracing"), supported, "it is on exactly when there is a GPU"); + assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), !supported, "the note shows with no GPU and only then"); + assert!(h.state().ui.prefs.gpu_raytracing, "the stored choice stays for a machine with a GPU"); } #[test] diff --git a/crates/ui-egui/tests/it/shortcut_list.rs b/crates/ui-egui/tests/it/shortcut_list.rs index c603cbde..0be5b044 100644 --- a/crates/ui-egui/tests/it/shortcut_list.rs +++ b/crates/ui-egui/tests/it/shortcut_list.rs @@ -29,7 +29,7 @@ fn no_two_default_shortcuts_are_the_same() { } } for (_, row) in &NOT_AVAILABLE_ACTIONS { - let key = row.default.unwrap(); + let Some(key) = row.default else { continue }; assert!(!seen.contains_key(key), "{} shows {key}, which another item has", row.label); } } @@ -83,3 +83,28 @@ 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_manipulator_rows_follow_export_textures_in_the_reference_order() { + 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); + + let rows = [ + "Export Textures...", + "Show/Hide manipulator", + "Increase the manipulator size", + "Decrease the manipulator size", + "Cycle through manipulation spaces", + "Toggle warp edition mode", + "Translate tool", + "Rotate tool", + "Reimport mesh", + ]; + let tops: Vec = rows.iter().map(|label| h.get_by_label(label).rect().top()).collect(); + + assert!(tops.windows(2).all(|pair| pair[0] < pair[1]), "{rows:?} run top to bottom: {tops:?}"); +} diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs index c6c3e34a..69e67067 100644 --- a/crates/ui-egui/tests/project_limits.rs +++ b/crates/ui-egui/tests/project_limits.rs @@ -33,11 +33,11 @@ fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() harness.run_steps(3); let edited = |harness: &Harness<'_, TextureCraftApp>| harness.state().ui.windows.settings_draft.as_ref().unwrap().prefs.clone(); assert_eq!(edited(&harness).reserved_cores, available_cores, "preferences from a larger machine are clamped"); - harness.get_by_role_and_label(egui::Role::SpinButton, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX)); + harness.get_by_role_and_label(egui::Role::Slider, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX)); harness.run_steps(3); assert_eq!(edited(&harness).reserved_cores, available_cores, "editing cannot exceed this machine's CPU count"); assert!(harness.query_by_label("≈ 8.00 GiB").is_some(), "50% of 16 GiB is shown beside the percentage"); - harness.get_by_role_and_label(egui::Role::SpinButton, "Max RAM while saving").set_value_accesskit(25.0); + harness.get_by_role_and_label(egui::Role::Slider, "Max RAM while saving").set_value_accesskit(25.0); harness.run_steps(3); assert!(harness.query_by_label("≈ 4.00 GiB").is_some(), "the byte estimate follows the edited percentage"); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1e45c49d..1bd95040 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -154,7 +154,7 @@ that closes it back onto the bar; the float is saved with the UI state. | UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | | UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged | | UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid | -| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (with Default (System Language)), the camera rotation, zoom and wheel speeds with Inverse direction, Enable GPU raytracing, the Shortcuts page and adding or removing library locations work. Show keyboard helper, Show world axes, Background color, Only display the selected material when painting, Viewport Scaling, Default UV scale for materials, simplified thumbnails, the other baking options, the preview cache and shader, the temporary cache directory, sparse virtual texture and the IRAY HARDWARE choices are shown disabled with "Not available yet". A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. TextureCraft's own settings (appearance, viewport textures, resources, autosave, folders) follow the reference sections | Run the window in the native app; wire each disabled control as its function lands | +| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (Default (System Language) by default and after a reset), the camera rotation, zoom and wheel speeds with Inverse direction, Show world axes (the 3D view's X, Y and Z corner), the Shortcuts page and adding or removing library locations work. Enable GPU raytracing is on and can be changed when there is a GPU, and off and disabled without one ([#823](https://github.com/storytold/texturecraft/issues/823)). Show keyboard helper and Save preprocessed scene files (on), Only display the selected material when painting (off), Enable live preview baking process (on), Viewport Scaling (only Auto) and the Local cache directory (empty is the system's temporary folder; R goes back to it) can be changed and are kept, but have no effect yet. Default UV scale for materials, simplified thumbnails, the preview cache budget and shader, the Files cache directory and sparse virtual texture are shown disabled with "Not available yet". There is no IRAY HARDWARE section. A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Show/Hide manipulator" Q to "Rotate tool" E after "Export Textures...", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Show/Hide manipulator", "Increase the manipulator size", "Decrease the manipulator size", "Cycle through manipulation spaces", "Toggle warp edition mode", "Translate tool", "Rotate tool", "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. The reference's TEMPORARY FILES section is called FILES and also holds the Data folder. TextureCraft's own settings follow the reference sections: VIEWPORT (texture resolution), RESOURCES (Max CPU threads for work, default every thread, and Cores kept for the UI as sliders in steps of 1 with the core count beside them, Max RAM while saving as a 0-100% slider, Max project size on open, Recent projects limit) and AUTOSAVE. There is no appearance, folders or analytics section: interface scale, brightness, accent colour and the system title bar stay in the saved settings and `ui.set` | Run the window in the native app; wire each disabled control as its function lands | Bake workflow (issue [#651](https://github.com/storytold/texturecraft/issues/651)): Mesh Map Bakers has a Presets menu (save, load, delete named bake settings; Apply to All Texture Sets) and a finished From af296eb5bc8256bad0c7af6effed4ff62f59c62c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:56:44 +0100 Subject: [PATCH 20/80] Scroll to R before clicking it and document the new settings fields --- crates/ui-egui/src/state.rs | 3 ++- crates/ui-egui/tests/it/settings_window.rs | 5 +++++ docs/control-protocol.md | 6 +++++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 9d97f54d..bfd72af9 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -167,7 +167,8 @@ pub struct Prefs { pub reserved_cores: u32, /// Maximum decompressed project size accepted on open, in GiB (at least one). pub project_open_limit_gib: u32, - /// Percent of the free RAM a project save may hold at once (desktop; 1 to 100). + /// Percent of the free RAM a project save may hold at once (desktop; 0 to 100, a save holds + /// at least 1). pub save_ram_percent: u8, /// Worker threads for painting, baking and export (desktop; 0: one per logical CPU). Read at /// startup, before the first parallel job. diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index 7ca014c9..d3040990 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -156,6 +156,8 @@ fn the_resource_sliders_step_by_one_and_follow_the_arrow_keys() { let ram_percent = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.save_ram_percent; let before = ram_percent(&h); + h.get_by_role_and_label(Role::Slider, "Max RAM while saving").scroll_to_me(); + h.run_steps(3); h.get_by_role_and_label(Role::Slider, "Max RAM while saving").focus(); h.run_steps(2); press_key(&mut h, Key::ArrowRight); @@ -194,6 +196,9 @@ fn the_local_cache_directory_takes_a_folder_and_r_goes_back_to_the_default() { type_into(&mut h, "Local cache directory", &folder); assert_eq!(stored(&h), folder); + // The Files cache directory's R stays disabled; the local cache's R is the one that works + h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().scroll_to_me(); + h.run_steps(3); h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().click(); h.run_steps(3); assert!(stored(&h).is_empty(), "R goes back to the default folder"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..e2d4b3ca 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -326,7 +326,11 @@ Other preferences set through `ui.set {"prefs": {...}}`: `language` (`""` follow language), `work_threads` (worker threads for painting, baking and export; 0 uses every logical CPU; read at startup), `rotation_speed` (default 2), `zoom_speed` and `wheel_speed` (default 1, each from 0.1 to 10) with `zoom_inverse` and `wheel_inverse`, `gpu_raytracing` (false keeps bake -rays on the CPU) and `libraries` (the folders the shelf scans for saved smart materials and masks). +rays on the CPU), `show_world_axes` (the 3D view's X, Y and Z corner, default true) and `libraries` +(the folders the shelf scans for saved smart materials and masks). `show_keyboard_helper`, +`only_selected_material_when_painting`, `save_preprocessed_scene_files`, `live_preview_baking` and +`local_cache_directory` (empty: the system's temporary folder) are kept for Settings but have no +effect yet. For example, the `libraries` field can contain `[{"name": "Studio", "path": "/assets/studio"}]`. Use an absolute path on the host running TextureCraft. To change one preference, read `state.prefs` with `ui.inspect`, update that field and send the full `prefs` object to `ui.set`. From 2c6222ecde671efa66734bcccf51c8fc4e4e2f9c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 01:18:07 +0100 Subject: [PATCH 21/80] Move texture resolution to Display Settings and apply review fixes Remove the Viewport section from Settings; the texture resolution is in Display Settings > Render settings and the GPU memory toasts point there. Add hovers to the Data folder and RAM slider, name the R button for screen readers, test that Show world axes hides the 3D axes, and fix the docs that still named the removed sections. --- crates/ui-egui/src/display_settings.rs | 16 ++++++-- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/settings_window.rs | 26 +++++------- crates/ui-egui/src/viewport.rs | 4 +- crates/ui-egui/tests/it/settings_window.rs | 46 +++++++++++++++------- crates/ui-egui/tests/ui_snapshots.rs | 3 ++ docs/control-protocol.md | 1 + docs/features.md | 6 +-- docs/ui-parity.md | 2 +- 9 files changed, 66 insertions(+), 40 deletions(-) diff --git a/crates/ui-egui/src/display_settings.rs b/crates/ui-egui/src/display_settings.rs index 7c0bc14d..92b8e13c 100644 --- a/crates/ui-egui/src/display_settings.rs +++ b/crates/ui-egui/src/display_settings.rs @@ -43,7 +43,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { 0 => import_hdr = environment(app, ui, &mut display), 1 => camera(app, ui, &mut display), 2 => post_effects(ui, &mut display), - 3 => render_settings(ui, &mut display), + 3 => render_settings(app, ui, &mut display), _ => visualization(app, ui, &mut display), }); @@ -255,9 +255,19 @@ fn post_effects(ui: &mut Ui, display: &mut DisplaySettings) { } } -/// Temporal anti-aliasing -fn render_settings(ui: &mut Ui, display: &mut DisplaySettings) { +/// Temporal anti-aliasing and the viewport texture resolution (an app setting, not the project's) +fn render_settings(app: &mut TextureCraftApp, ui: &mut Ui, display: &mut DisplaySettings) { ui.checkbox(&mut display.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)")); + ui.horizontal(|ui| { + ui.label(tr("Texture resolution")); + for (value, label) in [(0_u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] { + ui.selectable_value(&mut app.ui.prefs.viewport_texture, value, label); + } + }) + .response + .on_hover_text(tr( + "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", + )); } /// The mesh wireframe and the single-channel views diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f6b25a0f..8cddbbc7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1014,7 +1014,7 @@ 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 +/// The interface scale applied (`prefs.ui_scale`, set through `ui.set`; Settings has no control for it), clamped to a usable range 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; diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index 7da312bc..2227a7d8 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -456,7 +456,12 @@ fn general( { let default = crate::local_cache_folder("").display().to_string(); ui.add(egui::TextEdit::singleline(&mut p.local_cache_directory).hint_text(default).desired_width(CONTROL_WIDTH - 24.0)).labelled_by(label); - if ui.add(egui::Button::new("R").frame(false)).on_hover_text(tr("Reset to the default folder")).clicked() { + let reset = ui.add(egui::Button::new("R").frame(false)).on_hover_text(tr("Reset to the default folder")); + + // Screen readers hear what the single letter does + let name = format!("R, {}", tr("Reset to the default folder")); + reset.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + if reset.clicked() { p.local_cache_directory.clear(); } } @@ -495,7 +500,9 @@ fn general( #[cfg(not(target_arch = "wasm32"))] row(ui, tr("Data folder"), |ui, label| { 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); + ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)) + .labelled_by(label) + .on_hover_text(tr("Applies on restart.")); if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() { *pick = Some(SettingsFolder::DataFolder); } @@ -505,19 +512,6 @@ fn general( disabled_text_check(ui, n_("Hardware support acceleration"), true); // TextureCraft's own settings, after the reference sections - section(ui, n_("VIEWPORT")); - row(ui, tr("Texture resolution"), |ui, _| { - ui.horizontal(|ui| { - for (v, l) in [(0u8, tr("Full")), (1, tr("Half")), (2, tr("Quarter"))] { - ui.selectable_value(&mut p.viewport_texture, v, l); - } - }) - .response - .on_hover_text(tr( - "Size of the textures the viewport shows: lower uses less GPU memory with large texture sets. Painting and export keep full resolution.", - )); - }); - section(ui, n_("RESOURCES")); #[cfg(not(target_arch = "wasm32"))] { @@ -537,7 +531,7 @@ fn general( cores_in_total(ui, available_cores); }); row(ui, tr("Max RAM while saving"), |ui, label| { - ui.add(egui::Slider::new(&mut p.save_ram_percent, 0..=100).step_by(1.0).suffix(" %")).labelled_by(label); + ui.add(egui::Slider::new(&mut p.save_ram_percent, 0..=100).step_by(1.0).suffix(" %")).labelled_by(label).on_hover_text(tr("0 % uses at least 1 %")); let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); }); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 7a83ccf6..c7f65f95 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -405,7 +405,7 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) } let text = match sets.as_slice() { [one] => trf( - "Not enough GPU memory to show texture set \"{name}\" fully: lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Not enough GPU memory to show texture set \"{name}\" fully: lower the Texture resolution in Display Settings › Render settings. Painting and export are not affected.", &[("name", one)], ), many => { @@ -418,7 +418,7 @@ fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) list.push_str(", ..."); } trf( - "Not enough GPU memory to show {count} texture sets fully ({names}): lower the viewport Texture resolution in Settings. Painting and export are not affected.", + "Not enough GPU memory to show {count} texture sets fully ({names}): lower the Texture resolution in Display Settings › Render settings. Painting and export are not affected.", &[("count", &many.len()), ("names", &list)], ) } diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index d3040990..c89a8347 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -87,7 +87,7 @@ fn the_general_page_starts_at_the_reference_defaults() { let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); open_settings(&mut h); - // A reset puts the defaults in the window; the app itself keeps English for the exact-text checks + // The defaults of a first start, in the window; the app itself keeps English for the exact-text checks h.state_mut().ui.windows.settings_draft.as_mut().unwrap().prefs = Prefs::default(); h.run_steps(3); @@ -112,7 +112,7 @@ fn the_general_page_starts_at_the_reference_defaults() { assert_eq!(texturecraft_ui_egui::local_cache_folder(&Prefs::default().local_cache_directory), std::env::temp_dir()); let prefs = Prefs::default(); - assert_eq!(prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE, "a reset follows the system language"); + assert_eq!(prefs.language, texturecraft_ui_egui::i18n::SYSTEM_LANGUAGE, "the default follows the system language"); assert_eq!((prefs.rotation_speed, prefs.zoom_speed, prefs.wheel_speed), (2.0, 1.0, 1.0)); } @@ -121,7 +121,7 @@ fn the_general_page_keeps_the_reference_sections_and_moves_data_folder_and_recen let mut h = harness(Session::closed().unwrap()); open_settings(&mut h); - for gone in ["TEMPORARY FILES", "IRAY HARDWARE", "APPEARANCE", "FOLDERS", "PRIVACY", "Interface scale", "Accent color"] { + for gone in ["TEMPORARY FILES", "IRAY HARDWARE", "APPEARANCE", "FOLDERS", "VIEWPORT", "Interface scale", "Accent color"] { assert!(h.query_by_label(gone).is_none(), "{gone} is not on the page"); } for hint in ["Saving uses the other cores", "0 turns autosave off", "A new folder applies on restart"] { @@ -160,11 +160,32 @@ fn the_resource_sliders_step_by_one_and_follow_the_arrow_keys() { h.run_steps(3); h.get_by_role_and_label(Role::Slider, "Max RAM while saving").focus(); h.run_steps(2); + press_key(&mut h, Key::ArrowRight); - assert_eq!(ram_percent(&h), before + 1, "the right arrow adds one percent"); + let after_right = ram_percent(&h); press_key(&mut h, Key::ArrowLeft); press_key(&mut h, Key::ArrowLeft); - assert_eq!(ram_percent(&h), before - 1, "the left arrow takes one percent"); + let after_left = ram_percent(&h); + + assert_eq!(after_right, before + 1, "the right arrow adds one percent"); + assert_eq!(after_left, before - 1, "the left arrow takes one percent"); +} + +#[test] +fn show_world_axes_draws_the_3d_view_axes_and_off_hides_them() { + let mut h = harness(texturecraft_engine::sample_session(128, 32).unwrap()); + let painted_z = |h: &Harness<'_, TextureCraftApp>| { + h.output().shapes.iter().filter(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Z")).count() + }; + + h.state_mut().ui.prefs.show_world_axes = true; + h.run_steps(3); + let shown = painted_z(&h); + h.state_mut().ui.prefs.show_world_axes = false; + h.run_steps(3); + let hidden = painted_z(&h); + + assert_eq!(shown, hidden + 1, "the 3D view's Z axis letter is drawn only while Show world axes is on"); } #[test] @@ -179,8 +200,8 @@ fn the_enabled_interface_options_answer_the_keyboard() { h.run_steps(2); press_key(&mut h, Key::Space); } - let after = draft(&h); + assert_ne!(after.show_keyboard_helper, before.show_keyboard_helper); assert_ne!(after.show_world_axes, before.show_world_axes); assert_ne!(after.only_selected_material_when_painting, before.only_selected_material_when_painting); @@ -194,14 +215,12 @@ fn the_local_cache_directory_takes_a_folder_and_r_goes_back_to_the_default() { let stored = |h: &Harness<'_, TextureCraftApp>| h.state().ui.windows.settings_draft.as_ref().unwrap().prefs.local_cache_directory.clone(); type_into(&mut h, "Local cache directory", &folder); - assert_eq!(stored(&h), folder); + let typed = stored(&h); + click(&mut h, "R, Reset to the default folder"); + let reset = stored(&h); - // The Files cache directory's R stays disabled; the local cache's R is the one that works - h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().scroll_to_me(); - h.run_steps(3); - h.query_all_by_label("R").find(|node| !node.accesskit_node().is_disabled()).unwrap().click(); - h.run_steps(3); - assert!(stored(&h).is_empty(), "R goes back to the default folder"); + assert_eq!(typed, folder); + assert!(reset.is_empty(), "R goes back to the default folder"); } #[test] @@ -534,7 +553,6 @@ fn gpu_raytracing_is_on_and_checkable_with_a_gpu_and_off_and_disabled_without() assert_eq!(!check.accesskit_node().is_disabled(), supported, "it can be changed exactly when there is a GPU"); assert_eq!(toggled(&h, "Enable GPU raytracing"), supported, "it is on exactly when there is a GPU"); assert_eq!(h.query_by_label(GPU_RAYTRACING_UNAVAILABLE).is_some(), !supported, "the note shows with no GPU and only then"); - assert!(h.state().ui.prefs.gpu_raytracing, "the stored choice stays for a machine with a GPU"); } #[test] diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..7181557a 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -83,6 +83,9 @@ fn empty_start_snapshot() { harness.get_by_label("Edit").click(); harness.run_steps(3); harness.get_by_label("Settings").click(); + harness.run_steps(3); + harness.get_by_label("Recent projects limit").scroll_to_me(); + harness.run_steps(3); save(&mut harness, &output_dir, "settings-recent-project-limit"); assert!(!harness.get_by_label("Recent projects limit").accesskit_node().is_disabled()); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e2d4b3ca..35cbd0d3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -334,6 +334,7 @@ effect yet. For example, the `libraries` field can contain `[{"name": "Studio", "path": "/assets/studio"}]`. Use an absolute path on the host running TextureCraft. To change one preference, read `state.prefs` with `ui.inspect`, update that field and send the full `prefs` object to `ui.set`. +A `prefs` object without `language` sets the system language (`""`), the default. ## MCP server diff --git a/docs/features.md b/docs/features.md index 04702ee9..1106571b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -250,10 +250,10 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Swap 3D/2D** (F4, Viewport menu and the layout dropdown, rebindable) puts the 2D view on the left and the 3D view on the right in the split layout. Painting, the divider and the views' headers work on both sides, and the choice is kept with the UI state. - A modern look in **four brightness levels** (dark, medium dark, medium light and light) with - **seven accent colors**, set in Settings › General › Appearance. + **seven accent colors**, set for now only through `ui.set` (`prefs.brightness`, `prefs.accent`). - **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same - strip, and Settings › General › Appearance › System title bar for the system's frame instead. + strip, and the system's frame instead with `prefs.system_title_bar` through `ui.set` (for now). - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar. @@ -273,7 +273,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **No project at launch**: empty views, panels and toolbars until you create or open one (File › New project, Open, Recent projects, Open sample project); File › Close returns to that state. - A **data folder** of your choice for autosaves, smart materials, presets, templates and UI - layouts, on any drive (Settings › General › Folders; `Documents/TextureCraft` by default). + layouts, on any drive (Settings › General › Files › Data folder; `Documents/TextureCraft` by default). - A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1bd95040..4e6a3f45 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -154,7 +154,7 @@ that closes it back onto the bar; the float is saved with the UI state. | UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | | UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart. Since then: the Layers toolbar stays on one row at 1280 × 800 (its channel box shrinks), and a cut-short layer name or type shows in full on hover. Properties scrolling and restart persistence are unchanged | | UI-14 | Assets panel filters | **UI + source.** The type dropdown lists the reference entries in its order, Fonts and Show all included. Saved searches and Filter by path are separate scrollable panes with a divider that supports pointer and keyboard resizing and saves its position with the UI state ([#640](https://github.com/storytold/texturecraft/issues/640)). Fonts, the built-in saved searches Favorites, 3D Assets and Flattened layers, and the System fonts and User fonts libraries are listed but greyed with "Not available yet" | Give fonts, favorites, 3D assets and flattened layers real assets, then enable those rows and check that each one filters the grid | -| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (Default (System Language) by default and after a reset), the camera rotation, zoom and wheel speeds with Inverse direction, Show world axes (the 3D view's X, Y and Z corner), the Shortcuts page and adding or removing library locations work. Enable GPU raytracing is on and can be changed when there is a GPU, and off and disabled without one ([#823](https://github.com/storytold/texturecraft/issues/823)). Show keyboard helper and Save preprocessed scene files (on), Only display the selected material when painting (off), Enable live preview baking process (on), Viewport Scaling (only Auto) and the Local cache directory (empty is the system's temporary folder; R goes back to it) can be changed and are kept, but have no effect yet. Default UV scale for materials, simplified thumbnails, the preview cache budget and shader, the Files cache directory and sparse virtual texture are shown disabled with "Not available yet". There is no IRAY HARDWARE section. A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Show/Hide manipulator" Q to "Rotate tool" E after "Export Textures...", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Show/Hide manipulator", "Increase the manipulator size", "Decrease the manipulator size", "Cycle through manipulation spaces", "Toggle warp edition mode", "Translate tool", "Rotate tool", "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. The reference's TEMPORARY FILES section is called FILES and also holds the Data folder. TextureCraft's own settings follow the reference sections: VIEWPORT (texture resolution), RESOURCES (Max CPU threads for work, default every thread, and Cores kept for the UI as sliders in steps of 1 with the core count beside them, Max RAM while saving as a 0-100% slider, Max project size on open, Recent projects limit) and AUTOSAVE. There is no appearance, folders or analytics section: interface scale, brightness, accent colour and the system title bar stay in the saved settings and `ui.set` | Run the window in the native app; wire each disabled control as its function lands | +| UI-15 | Edit > Settings ([#637](https://github.com/storytold/texturecraft/issues/637)) | **Source + headless UI tests.** The window has the reference's General, Shortcuts and Libraries pages with OK and Cancel, and the General sections in its order (no Privacy section: TextureCraft sends no usage data). Language (Default (System Language) by default and after a reset), the camera rotation, zoom and wheel speeds with Inverse direction, Show world axes (the 3D view's X, Y and Z corner), the Shortcuts page and adding or removing library locations work. Enable GPU raytracing is on and can be changed when there is a GPU, and off and disabled without one ([#823](https://github.com/storytold/texturecraft/issues/823)). Show keyboard helper (on), Only display the selected material when painting (off), Save preprocessed scene files (on), Enable live preview baking process (on) and the Local cache directory (empty is the system's temporary folder; R goes back to it) can be changed and are kept, but have no effect yet. Viewport Scaling opens but lists only Auto, so there is nothing to change. Default UV scale for materials, simplified thumbnails, the preview cache budget and shader, the Files cache directory and sparse virtual texture are shown disabled with "Not available yet". There is no IRAY HARDWARE section. A location's Default choice is fixed to your_assets. The Shortcuts page has the sections Actions, Mouse shortcuts and Modifiers shortcuts and a Reset all to default button; Delete clears a binding; a shared shortcut shows a warning naming the other action, a warning on the page icon and the footer "One or several errors have been found in Shortcuts settings", and OK stays disabled until it is gone (the mouse and modifier rows are shown disabled, the viewports read those gestures from code). The shortcut list uses the reference's action names, order and default keys ("Open project", "Save as project", "Switch to baking mode" Ctrl+Shift+B, "Switch to edition mode" F9, "Camera projection: Perspective view" F5, "Show entire mesh/path", "Select next camera" `>`, "Select previous camera" `<`, "Viewers layout: 3D/2D" F1 to "Viewers layout: Swap 3D/2D" F4 and so on); Quit keeps Ctrl+Q and the menus keep their own texts. "Show mesh wireframe" is a new bindable command without a key; "Pause Engine Computation" (Shift+Esc) and "Toggle animation" (Space) are listed disabled with "Not available yet". The reference's rows after "Export Textures..." are listed the same way, in its order: "Show/Hide manipulator" (Q), "Increase the manipulator size", "Decrease the manipulator size" (-), "Cycle through manipulation spaces" (T), "Toggle warp edition mode" (Shift+V), "Translate tool" (W) and "Rotate tool" (E). The window reopens on the page it was closed on. With a project open the Libraries page hides the add row and shows "Library locations can't be added/removed when a project is opened."; the default library's "−" says "Cannot remove the default library.". "GPU raytracing not available for your hardware." shows under the Baking options when there is no GPU. The reference's TEMPORARY FILES section is called FILES and also holds the Data folder. TextureCraft's own settings follow the reference sections: RESOURCES (Max CPU threads for work, default every thread, and Cores kept for the UI as sliders in steps of 1 with the core count beside them, Max RAM while saving as a 0-100% slider, Max project size on open, Recent projects limit) and AUTOSAVE. There is no appearance, viewport, folders or analytics section: the viewport texture resolution (Full, Half, Quarter) is in Display Settings › Render settings, and interface scale, brightness, accent color and the system title bar stay in the saved settings and `ui.set` | Run the window in the native app; wire each disabled control as its function lands | Bake workflow (issue [#651](https://github.com/storytold/texturecraft/issues/651)): Mesh Map Bakers has a Presets menu (save, load, delete named bake settings; Apply to All Texture Sets) and a finished From 263b2b24fb03ba10f8469953694dabf9051dacfd Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 10:37:22 +0100 Subject: [PATCH 22/80] Derive the expected work threads in the settings test from the core count --- crates/ui-egui/tests/it/settings_window.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/settings_window.rs b/crates/ui-egui/tests/it/settings_window.rs index c89a8347..4cbde681 100644 --- a/crates/ui-egui/tests/it/settings_window.rs +++ b/crates/ui-egui/tests/it/settings_window.rs @@ -281,7 +281,11 @@ fn cancel_drops_the_changes_and_ok_applies_and_keeps_them() { let prefs = h.state().ui.prefs.clone(); assert!(!h.state().ui.windows.settings, "OK closes the window"); - assert_eq!((prefs.autosave_minutes, prefs.work_threads, prefs.project_open_limit_gib), (25, 1, 12)); + + // The slider's end stores 0, which is the only step on a one-core machine + let (cores, _) = texturecraft_engine::formats::available_save_resources(); + let expected_work_threads = if cores <= 1 { 0 } else { 1 }; + assert_eq!((prefs.autosave_minutes, prefs.work_threads, prefs.project_open_limit_gib), (25, expected_work_threads, 12)); assert!(prefs.zoom_inverse && !prefs.wheel_inverse && !prefs.show_world_axes); assert!(prefs.drag_zoom_scale() < 0.0, "inverted zoom runs the other way"); From a436007e7e0d8aeec36497e24b145121881e04ef Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 10:41:21 +0100 Subject: [PATCH 23/80] Drop a close that waited for a stroke when another project replaces the project --- crates/ui-egui/src/lib.rs | 7 ++++--- crates/ui-egui/src/manual_save.rs | 15 ++++++++++++++- crates/ui-egui/src/windows.rs | 10 +++++++--- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2f981d6b..e0e9bb10 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -332,9 +332,10 @@ pub struct TextureCraftApp { /// The unsaved-changes dialog's Save is waiting for a path or a save result. #[cfg(not(target_arch = "wasm32"))] pub(crate) saving_for_prompt: bool, - /// A close the finished save left waiting for an open stroke; decided once the stroke ends. + /// A close the finished save left waiting for an open stroke, with the id of the project it + /// belongs to; decided once the stroke ends, dropped when another project replaced that one. #[cfg(not(target_arch = "wasm32"))] - pub(crate) quit_after_stroke: bool, + pub(crate) quit_after_stroke: Option, /// The requested save completed; the prompt goes on at its next frame. #[cfg(not(target_arch = "wasm32"))] pub(crate) prompt_saved: bool, @@ -456,7 +457,7 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] saving_for_prompt: false, #[cfg(not(target_arch = "wasm32"))] - quit_after_stroke: false, + quit_after_stroke: None, #[cfg(not(target_arch = "wasm32"))] prompt_saved: false, bindings: keymap::Bindings::default(), diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs index b7eed0fe..4a3d7008 100644 --- a/crates/ui-egui/src/manual_save.rs +++ b/crates/ui-egui/src/manual_save.rs @@ -90,7 +90,7 @@ impl TextureCraftApp { // A close that the save could not finish asks about the changes it left, once an open stroke ends if job.quit_after_save && !quitting { if self.session.stroke_active() { - self.quit_after_stroke = true; + self.quit_after_stroke = Some(self.session.project_id); } else { crate::windows::ask_to_save(self, Unsaved::Quit); } @@ -297,6 +297,19 @@ mod tests { assert!(h.state().ui.windows.unsaved.is_none()); } + #[test] + fn opening_another_project_drops_the_close_that_waited_for_a_stroke() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut h = stroke_open_when_the_save_returns("stroke-replaced"); + + h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + let closed = sends_close(&mut h); + + assert!(!closed, "the old project's close does not quit the new one"); + assert!(h.state().ui.windows.unsaved.is_none()); + assert!(h.state().quit_after_stroke.is_none()); + } + #[test] fn dismissing_the_prompt_during_a_save_cancels_the_quit() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 1c4681e7..431dac8d 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -95,9 +95,13 @@ pub(crate) fn close_request(app: &mut TextureCraftApp, ctx: &egui::Context) { app.toast(error.to_string(), true); } #[cfg(not(target_arch = "wasm32"))] - if app.quit_after_stroke && !app.session.stroke_active() { - app.quit_after_stroke = false; - if !ask_to_save(app, crate::state::Unsaved::Quit) { + if let Some(project_id) = app.quit_after_stroke + && (project_id != app.session.project_id || !app.session.stroke_active()) + { + app.quit_after_stroke = None; + + // A close that belonged to a replaced project is gone with it + if project_id == app.session.project_id && !ask_to_save(app, crate::state::Unsaved::Quit) { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } } From ce2718a13908690b0f219e95d429bb649c16d3ba Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 10:51:24 +0100 Subject: [PATCH 24/80] Test the IOR specular setting across projects, templates, export and shading Round-trips cover project save and reopen, older projects and templates without the field, and template save and apply. The F0 export is checked against the CPU tracer's Metallic/Roughness F0 at IOR 1.8 in both modes; the GPU tracer is compared with the CPU tracer and the viewport with and without the setting. Specular/Glossiness export and shading stay identical with the setting on. --- Cargo.lock | 1 + crates/engine/tests/it/ior_specular.rs | 87 +++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/formats/src/export/tests.rs | 39 +++++++++ crates/render/Cargo.toml | 1 + crates/render/src/gpu_trace.rs | 27 ++++++ crates/render/src/trace.rs | 112 +++++++++++++++++++++++++ crates/render/tests/headless.rs | 26 ++++++ 8 files changed, 294 insertions(+) create mode 100644 crates/engine/tests/it/ior_specular.rs diff --git a/Cargo.lock b/Cargo.lock index f9292a97..6f89ed9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4785,6 +4785,7 @@ dependencies = [ "texturecraft-bake", "texturecraft-compose", "texturecraft-core", + "texturecraft-formats", "texturecraft-geom", "texturecraft-texel", "wasm-bindgen-futures", diff --git a/crates/engine/tests/it/ior_specular.rs b/crates/engine/tests/it/ior_specular.rs new file mode 100644 index 00000000..8422abf7 --- /dev/null +++ b/crates/engine/tests/it/ior_specular.rs @@ -0,0 +1,87 @@ +//! The "Use IOR for specular reflection" shader setting persists with projects and templates +//! and stays off for projects and templates without it (texturecraft #749). + +use std::io::{Cursor, Write}; + +use serde_json::json; +use texturecraft_engine::{Session, execute, geom::primitives}; +use zip::{ZipWriter, write::SimpleFileOptions}; + +const IOR: f32 = 1.8; + +fn session() -> Session { + Session::new_project("Ior", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +fn opt_in(session: &mut Session) { + execute(session, "display.set", &json!({"iorSpecular": true, "ior": IOR})).unwrap(); +} + +fn new_project_uses_ior_specular(session: &mut Session, template: &str) -> bool { + execute(session, "project.new", &json!({"template": template})).unwrap(); + session.doc.project.display.ior_specular +} + +#[test] +fn the_opt_in_survives_save_and_reopen() { + let mut session = session(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("ior.tcraft"); + opt_in(&mut session); + + execute(&mut session, "file.saveAs", &json!({"path": path})).unwrap(); + execute(&mut session, "project.new", &json!({})).unwrap(); + let new_project_uses_it = session.doc.project.display.ior_specular; + execute(&mut session, "file.open", &json!({"path": path})).unwrap(); + + assert!(!new_project_uses_it, "a new project starts with the setting off"); + let display = &session.doc.project.display; + assert!(display.ior_specular); + assert_eq!(display.ior, IOR); +} + +#[test] +fn a_project_saved_before_the_setting_opens_with_it_off() { + let mut session = session(); + opt_in(&mut session); + let mut project = serde_json::to_value(&session.doc.project).unwrap(); + let removed = project["display"].as_object_mut().unwrap().remove("ior_specular"); + let mut archive = ZipWriter::new(Cursor::new(Vec::new())); + archive.start_file("project.json", SimpleFileOptions::default()).unwrap(); + archive.write_all(&serde_json::to_vec(&project).unwrap()).unwrap(); + let bytes = archive.finish().unwrap().into_inner(); + + let older = Session::from_project_bytes(&bytes).unwrap(); + + assert_eq!(removed, Some(json!(true)), "the stripped field is the saved setting"); + let display = &older.doc.project.display; + assert!(!display.ior_specular); + assert_eq!(display.ior, IOR, "the other shader settings still load"); +} + +#[test] +fn the_opt_in_survives_a_template_and_other_templates_leave_it_off() { + let library = tempfile::tempdir().unwrap(); + let mut author = session(); + author.load_templates(library.path().to_path_buf()); + opt_in(&mut author); + execute(&mut author, "project.template.save", &json!({"name": "Glass"})).unwrap(); + + // A template written before the setting existed + let older = json!({"name": "Older", "resolution": 128, "ior": IOR}); + std::fs::write(library.path().join("Older.json"), serde_json::to_vec(&older).unwrap()).unwrap(); + + let mut user = session(); + let warnings = user.load_templates(library.path().to_path_buf()); + let listed = execute(&mut user, "project.templates", &json!({})).unwrap(); + + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(new_project_uses_ior_specular(&mut user, "Glass")); + assert_eq!(user.doc.project.display.ior, IOR); + assert!(!new_project_uses_ior_specular(&mut user, "Older")); + for template in listed.as_array().unwrap() { + let name = template["name"].as_str().unwrap(); + assert_eq!(template["iorSpecular"], json!(name == "Glass"), "{name}"); + assert_eq!(new_project_uses_ior_specular(&mut user, name), name == "Glass", "{name}"); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11a5b7f0..9aba988b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -23,6 +23,7 @@ mod generator_inputs; mod gradient_map; mod high_poly_missed; mod instances; +mod ior_specular; mod layer_multi_select; mod mask_clone_smudge; mod mask_export; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 8a8ca682..d07efeae 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1329,3 +1329,42 @@ fn diffusion_padding_fills_beyond_the_dilation_smoothly() { } } } + +#[test] +fn specular_glossiness_exports_ignore_the_ior_specular_setting() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::SpecularLevel]); + fx.set_all(Channel::Specular, |_, _| [0.3, 0.2, 0.1]); + fx.set_all(Channel::Glossiness, |_, _| [0.7; 3]); + fx.set_all(Channel::SpecularLevel, |_, _| [0.5; 3]); + (fx.project.display.spec_gloss, fx.project.display.ior) = (true, 1.8); + let channel = |channel| SourceRef::Channel { channel, component: 0 }; + let virt = |map| SourceRef::Virtual { map, component: 0 }; + let specular = MapSpec { + file: "specular".into(), + format: FileFormat::Png, + bit_depth: 16, + channels: [Dest::R, Dest::G, Dest::B] + .into_iter() + .zip(0u8..) + .map(|(dest, component)| (dest, SourceRef::Channel { channel: Channel::Specular, component })) + .collect(), + inverted: Vec::new(), + }; + let preset = ExportPreset { + name: "spec gloss".into(), + maps: vec![ + specular, + gray_map("gloss", channel(Channel::Glossiness)), + gray_map("rough", virt(VirtualMap::Roughness)), + gray_map("f0", virt(VirtualMap::F0)), + ], + }; + let options = ExportOptions::new(preset); + + let off = fx.render(&options); + fx.project.display.ior_specular = true; + let on = fx.render(&options); + + assert!(off.iter().any(|file| file.name.starts_with("f0")), "the F0 map is part of the comparison"); + assert_eq!(on, off, "Specular/Glossiness takes reflectance from the Specular color, not the IOR"); +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index ee15b556..83624635 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -30,3 +30,4 @@ wasm-bindgen-futures = "0.4" [dev-dependencies] image = { workspace = true } +texturecraft-formats = { workspace = true } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 2fb2c058..50ab5f5c 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -1019,6 +1019,33 @@ mod tests { assert_region_means_match("varying roughness, default base color", &gpu, &cpu.rgba8(&d), 48, 36, 3.0); } + #[test] + fn gpu_matches_cpu_with_ior_specular_reflectance() { + use Channel::*; + let Some((mut h, mut t)) = gpu() else { return }; + + // A dark, glossy dielectric shows mostly its F0 + let values = [(BaseColor, [0.02; 3]), (Metallic, [0.0; 3]), (Roughness, [0.15; 3]), (SpecularLevel, [1.0; 3])]; + let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false, background: crate::DEFAULT_BACKGROUND }; + let settings = TraceSettings { bounces: 4 }; + let mut sphere_brightness = Vec::new(); + + for ior_specular in [false, true] { + let display = texturecraft_core::DisplaySettings { ior: 1.8, ior_specular, ..Default::default() }; + let mut scene = sphere_scene(&mut h, crate::ibl::environment("Studio Contrast", 256), &values); + (scene.ior, scene.dielectric_f0_scale) = (display.ior, display.dielectric_f0_scale()); + let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); + let mut cpu = Tracer::new(48, 36); + for _ in 0..1024 { + cpu.pass(&scene, &camera(), &settings); + } + assert_region_means_match(&format!("IOR specular {ior_specular}"), &gpu, &cpu.rgba8(&d), 48, 36, 3.0); + sphere_brightness.push(gpu.as_chunks::<4>().0.iter().map(|pixel| pixel[..3].iter().map(|v| u32::from(*v)).sum::()).sum::()); + } + + assert!(sphere_brightness[1] > sphere_brightness[0], "IOR 1.8 reflects more than the legacy F0: {sphere_brightness:?}"); + } + /// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels. fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) { let lum = |img: &[u8], x: usize, y: usize| { diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 1cfaf68f..a70e09cd 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -1416,4 +1416,116 @@ mod tests { assert!(blurred > 3 * pinhole.max(10), "out of focus: {pinhole} -> {blurred} edge pixels"); assert!(focused < pinhole + pinhole / 2 + 10, "the silhouette (about the focus depth) stays sharp: {pinhole} -> {focused}"); } + + /// Specular Level 0.5 stands for OpenPBR's default specular weight of 1 + const OPENPBR_DEFAULT_SPECULAR_LEVEL: f32 = 0.5; + /// A non-default IOR for the opt-in comparisons + const DENSE_IOR: f32 = 1.8; + /// The 32-bit export and the shading read the same 16-bit texel: only float rounding separates them + const F0_TOLERANCE: f32 = 1e-5; + + /// One texture set holding a uniform dielectric with both shader models' channels. + fn dielectric_composite() -> Composite { + use Channel::*; + let values = [ + (BaseColor, [0.1; 3]), + (Metallic, [0.0; 3]), + (Roughness, [0.3; 3]), + (SpecularLevel, [OPENPBR_DEFAULT_SPECULAR_LEVEL; 3]), + (Specular, [0.3, 0.2, 0.1]), + (Glossiness, [0.7; 3]), + ]; + let channels: Vec = values.iter().map(|(channel, _)| *channel).collect(); + let mut composite = Composite::new(&channels, 8); + for (channel, value) in values { + let raw: Vec = value[..channel.components()].iter().map(|v| texturecraft_texel::to_u16(*v)).collect(); + let image = composite.channels.get_mut(&channel).unwrap(); + for y in 0..8 { + for x in 0..8 { + image.set(x, y, &raw); + } + } + } + composite + } + + /// A sphere covered by [`dielectric_composite`] under `display`. + fn dielectric_scene(display: &DisplaySettings) -> TraceScene { + let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); + let bvh = Arc::new(Bvh::new(&mesh)); + let sets = vec![TraceSet { material: 0, composite: dielectric_composite(), height_strength: 0.0 }]; + TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(crate::ibl::environment("Studio Soft", 32))) + } + + /// The F0 the CPU tracer shades the sphere's front with. + fn shaded_f0(display: &DisplaySettings) -> Vec3 { + let scene = dielectric_scene(display); + let (origin, direction) = (Vec3::new(0.0, 0.0, 4.0), Vec3::NEG_Z); + let hit = scene.bvh.closest(origin, direction, f32::MAX).unwrap(); + surface(&scene, hit.tri, hit.u, hit.v, origin, direction, hit.t).unwrap().f0 + } + + /// The F0 map a 32-bit float export writes for [`dielectric_composite`] under `display`. + fn exported_f0(display: &DisplaySettings) -> f32 { + use texturecraft_formats::{Dest, ExportInput, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap}; + + let composite = dielectric_composite(); + let mut project = texturecraft_core::Project::new("F0", "builtin:sphere"); + let mut set = texturecraft_core::TextureSet::new("Set", 0, composite.resolution); + set.channels = composite.channels.keys().map(|channel| (*channel, texturecraft_core::ChannelFormat::default_for(*channel))).collect(); + project.texture_sets.push(set); + project.display = display.clone(); + let coverage = vec![true; (composite.resolution * composite.resolution) as usize]; + let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &Default::default(), coverage: &coverage, mesh_name: "sphere" }; + let f0 = |component| SourceRef::Virtual { map: VirtualMap::F0, component }; + let channels = vec![(Dest::R, f0(0)), (Dest::G, f0(1)), (Dest::B, f0(2))]; + let map = MapSpec { file: "f0".into(), format: FileFormat::Exr, bit_depth: 32, channels, inverted: Vec::new() }; + let options = ExportOptions::new(ExportPreset { name: "F0".into(), maps: vec![map] }); + + let files = texturecraft_formats::render_maps(&input, &options).unwrap(); + + let image = image::load_from_memory_with_format(&files[0].bytes, image::ImageFormat::OpenExr).unwrap().to_rgb32f(); + image.get_pixel(4, 4)[0] + } + + fn ior_display(ior: f32, ior_specular: bool, spec_gloss: bool) -> DisplaySettings { + DisplaySettings { ior, ior_specular, spec_gloss, ..DisplaySettings::default() } + } + + #[test] + fn exported_f0_matches_the_metallic_roughness_shading_in_both_modes() { + let (legacy, opt_in) = (ior_display(DENSE_IOR, false, false), ior_display(DENSE_IOR, true, false)); + + // OpenPBR: at specular weight 1 the dielectric F0 is the Fresnel reflectance of the IOR + let fresnel = ((DENSE_IOR - 1.0) / (DENSE_IOR + 1.0)).powi(2); + + let (legacy_shaded, legacy_exported) = (shaded_f0(&legacy), exported_f0(&legacy)); + let (opt_in_shaded, opt_in_exported) = (shaded_f0(&opt_in), exported_f0(&opt_in)); + let default_ior_shaded = shaded_f0(&ior_display(1.5, true, false)); + + for (mode, shaded, exported) in [("legacy", legacy_shaded, legacy_exported), ("IOR", opt_in_shaded, opt_in_exported)] { + assert!(shaded.abs_diff_eq(Vec3::splat(exported), F0_TOLERANCE), "{mode}: shaded {shaded}, exported {exported}"); + } + assert!((legacy_exported - LEGACY_DIELECTRIC_F0_SCALE * OPENPBR_DEFAULT_SPECULAR_LEVEL).abs() < F0_TOLERANCE, "legacy {legacy_exported}"); + assert!((opt_in_exported - fresnel).abs() < F0_TOLERANCE, "IOR {DENSE_IOR}: {opt_in_exported}, Fresnel {fresnel}"); + assert!(opt_in_exported > legacy_exported, "IOR {DENSE_IOR} reflects more than the legacy 1.5 equivalent"); + assert!(default_ior_shaded.abs_diff_eq(legacy_shaded, F0_TOLERANCE), "IOR 1.5 keeps the legacy reflectance: {default_ior_shaded}"); + } + + #[test] + fn specular_glossiness_shading_ignores_the_ior_specular_setting() { + let (off, on) = (ior_display(DENSE_IOR, false, true), ior_display(DENSE_IOR, true, true)); + let render = |display: &DisplaySettings| { + let (scene, mut tracer) = (dielectric_scene(display), Tracer::new(24, 16)); + for _ in 0..2 { + tracer.pass(&scene, &camera(), &TraceSettings::default()); + } + tracer.rgba8(&TraceDisplay::from_display(display)) + }; + + let (off_f0, on_f0) = (shaded_f0(&off), shaded_f0(&on)); + + assert_eq!(on_f0, off_f0, "the Specular color gives F0"); + assert_eq!(render(&on), render(&off)); + } } diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 042a59c9..d928b988 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,4 +1,5 @@ use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_core::DisplaySettings; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; @@ -789,6 +790,31 @@ fn specular_glossiness_takes_f0_from_the_specular_color() { assert!(sg.mean(200, 100, 280, 180) > 20.0); } +#[test] +fn ior_specular_changes_dielectric_reflections_in_the_viewport_only_for_metallic_roughness() { + let Some((mut h, frame)) = setup() else { return }; + + // A dark, glossy dielectric at full Specular Level shows mostly its F0 + fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[5, 5, 5, 255]); + fill(&mut h, &[0, 1], DisplayKind::Orm, &[255, 38, 0, 255]); + let mut view = |ior: f32, ior_specular: bool, spec_gloss: bool, name: &str| { + // Without temporal anti-aliasing each frame is the same still image + let display = DisplaySettings { ior, ior_specular, spec_gloss, taa: false, ..DisplaySettings::default() }; + render(&mut h, &Frame { shade: Shade::from_display(&display), ..frame.clone() }, name) + }; + + let legacy = view(1.8, false, false, "ior_specular_off"); + let opt_in = view(1.8, true, false, "ior_specular_on"); + let default_ior = view(1.5, true, false, "ior_specular_default_ior"); + let spec_gloss_off = view(1.8, false, true, "ior_specular_spec_gloss_off"); + let spec_gloss_on = view(1.8, true, true, "ior_specular_spec_gloss_on"); + + let (brighter, darker) = (opt_in.mean(200, 100, 280, 180), legacy.mean(200, 100, 280, 180)); + assert!(brighter > darker + 2.0, "IOR 1.8 reflects more than the legacy F0 ({brighter} vs {darker})"); + assert_same(&default_ior, &legacy, "IOR 1.5 keeps the legacy reflectance"); + assert_eq!(spec_gloss_on.px, spec_gloss_off.px, "Specular/Glossiness takes F0 from the Specular color"); +} + #[test] fn a_lit_metallic_view_ignores_the_specular_channel() { let Some((mut h, frame)) = setup() else { return }; From cf54cc20de92861e246975e760d1595fd7c07dd7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 11:16:41 +0100 Subject: [PATCH 25/80] Resources Updater: review fixes Remember file verdicts per size and time so an unchanged file is read once; recheck the open window at most twice a second; outdated rows first. Record image files from PBR folder, MaterialX and mesh map imports too, and resample an imported mesh map from its changed file while it still holds that file's pixels. Relink only image resources; decode updated bytes the way undo and reopening do. Notices carry their project and are reset when another project opens, which is checked once. Escape closes the window only while it has the keyboard. Keep the reference's Shelf line and show the file on its own line. A dedicated automation refusal message, translated status labels, tempfile in tests. --- Cargo.lock | 1 + crates/automation/src/workspace.rs | 13 +- crates/core/src/lib.rs | 2 + crates/core/src/mesh_map_slot.rs | 15 ++ crates/core/src/resource_source.rs | 4 + crates/engine/src/lib.rs | 5 +- crates/engine/src/materialx_cmds.rs | 21 +- crates/engine/src/meshmap_cmds.rs | 17 +- crates/engine/src/meshmap_import_cmds.rs | 5 +- crates/engine/src/pbr_cmds.rs | 39 ++- crates/engine/src/pbr_cmds/native/found.rs | 10 + crates/engine/src/reloaded_file.rs | 9 +- crates/engine/src/resource_check.rs | 23 ++ crates/engine/src/resource_cmds.rs | 4 +- crates/engine/src/resource_state.rs | 1 + crates/engine/src/resource_update_cmds.rs | 203 ++++++++++----- crates/engine/src/session.rs | 5 + crates/engine/tests/it/resource_updater.rs | 232 +++++++++++++----- crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/src/i18n.rs | 3 + crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/menus.rs | 3 - crates/ui-egui/src/resources_updater.rs | 103 +++++--- crates/ui-egui/src/state/resources_updater.rs | 4 + crates/ui-egui/src/toast_action.rs | 33 ++- crates/ui-egui/tests/it/resources_updater.rs | 57 ++++- docs/control-protocol.md | 17 +- docs/features.md | 16 +- 28 files changed, 637 insertions(+), 231 deletions(-) create mode 100644 crates/core/src/mesh_map_slot.rs create mode 100644 crates/engine/src/resource_check.rs diff --git a/Cargo.lock b/Cargo.lock index 59d9a90a..45aedc2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5313,6 +5313,7 @@ dependencies = [ "skera", "skrifa 0.48.0", "sys-locale", + "tempfile", "texturecraft-engine", "texturecraft-render", "wasm-bindgen", diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2e590e15..64897380 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -132,15 +132,19 @@ const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; /// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { + // The Resources Updater reads the files a project names, which may lie outside the read root + if matches!(id, "resource.status" | "resource.update" | "resource.relink") { + return Err(bad(format!( + "`{id}` reads the image files the project names on this machine, so it is disabled for automation; re-import changed files with resource_import" + ))); + } + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, - - // The Resources Updater reads the files a project names, which may lie outside the read root - "resource.status" | "resource.update" | "resource.relink" => false, _ => !id.starts_with("file.") && !has_path, }; if allowed { @@ -249,7 +253,8 @@ mod tests { assert!(authorize_command("file.reimportMesh", &json!({})).is_ok()); assert!(authorize_command("file.close", &json!({})).is_ok()); for id in ["resource.status", "resource.update", "resource.relink"] { - assert!(authorize_command(id, &json!({})).is_err(), "{id} reads the host paths a project names"); + let error = authorize_command(id, &json!({})).unwrap_err().to_string(); + assert!(error.contains("reads the image files"), "{id}: {error}"); } assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2c5db23b..e6f7a5ce 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -39,6 +39,7 @@ pub mod image_input; pub mod layer; pub mod lighting_output; pub mod mask_outline; +pub mod mesh_map_slot; pub mod mirror; pub mod mirror_corner; pub mod mirror_mode; @@ -120,6 +121,7 @@ pub use layer::{ }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; +pub use mesh_map_slot::MeshMapSlot; pub use mirror::Mirror; pub use mirror_corner::MirrorCorner; pub use mirror_mode::MirrorMode; diff --git a/crates/core/src/mesh_map_slot.rs b/crates/core/src/mesh_map_slot.rs new file mode 100644 index 00000000..7cade977 --- /dev/null +++ b/crates/core/src/mesh_map_slot.rs @@ -0,0 +1,15 @@ +//! The mesh map an imported image file was resampled into + +use serde::{Deserialize, Serialize}; + +use crate::BakedMap; + +/// A mesh map of a texture set, and the UV tile one image of it covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct MeshMapSlot { + /// Index of the texture set. + pub texture_set: usize, + pub map: BakedMap, + /// The UV tile the image covers (1001 on a set without UV tiles). + pub tile: u32, +} diff --git a/crates/core/src/resource_source.rs b/crates/core/src/resource_source.rs index 793122cf..6a8627ed 100644 --- a/crates/core/src/resource_source.rs +++ b/crates/core/src/resource_source.rs @@ -14,4 +14,8 @@ pub struct ResourceSource { /// (0 when unknown). An unchanged time and size skip reading the file again. #[serde(default)] pub modified_ms: u64, + /// The mesh map the file was imported as (`textureSet.meshMap.import`): an update resamples it + /// again while the map still holds what this file gave it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mesh_map: Option, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0d2f8d3c..0a87537a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -71,6 +71,9 @@ pub mod quick_mask; // Reloading resource files reads paths on native targets only #[cfg(not(target_arch = "wasm32"))] mod reloaded_file; +// Remembered file comparisons exist on native targets only +#[cfg(not(target_arch = "wasm32"))] +mod resource_check; pub mod resource_cmds; pub mod resource_state; pub mod resource_status; @@ -103,9 +106,9 @@ pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; +pub use project_cmds::sample_session; pub use resource_state::ResourceState; pub use resource_status::ResourceStatus; -pub use project_cmds::sample_session; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label, stroke_template, diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 68792d5c..5529b778 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -31,8 +31,9 @@ pub fn specs() -> Vec { )] } -/// Loads an image file named in the document (relative to it): its bytes, or why not. -pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; +/// Loads an image file named in the document (relative to it): its bytes and the file they were +/// read from (for the Resources Updater; None when not read from disk), or why not. +pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<(Vec, Option), String>; impl Session { /// Add `material` as a fill layer on the active texture set, loading its images with `load`. @@ -45,6 +46,7 @@ impl Session { // Resources to add (name and encoded bytes), and their decoded images for the session. let mut added: Vec<(String, Arc>)> = Vec::new(); let mut decoded = Vec::new(); + let mut sources = Vec::new(); let mut names: BTreeMap = BTreeMap::new(); let mut channels: Vec = Vec::new(); for (channel, value) in &material.channels { @@ -58,9 +60,10 @@ impl Session { let resource = match names.get(file) { Some(n) => n.clone(), None => { - let loaded = - load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string())); - let (bytes, image) = match loaded { + let loaded = load(file).and_then(|(bytes, source)| { + texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image, source)).map_err(|e| e.to_string()) + }); + let (bytes, image, source) = match loaded { Ok(v) => v, Err(e) => { warnings.push(format!("{} was skipped: {file}: {e}", channel.id())); @@ -74,6 +77,7 @@ impl Session { unique = format!("{n}_{base}"); n += 1; } + sources.extend(source.map(|source| (unique.clone(), source))); added.push((unique.clone(), Arc::new(bytes))); decoded.push((unique.clone(), crate::resource_cmds::decoded(image))); names.insert(file.clone(), unique.clone()); @@ -96,6 +100,7 @@ impl Session { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels)) })?; @@ -123,7 +128,7 @@ fn import(s: &mut Session, p: &Value) -> Result { let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?; let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?; - let load = |file: &str| -> std::result::Result, String> { + let load = |file: &str| -> std::result::Result<(Vec, Option), String> { // `` stands for a tile number; the first tile is read. let file = file.replace("", "1001"); let rel = Path::new(&file); @@ -144,7 +149,9 @@ fn import(s: &mut Session, p: &Value) -> Result { if len > crate::resource_cmds::MAX_BYTES as u64 { return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20)); } - std::fs::read(&full).map_err(|e| e.to_string()) + let source = full.to_str().map(crate::resource_update_cmds::file_source); + let bytes = std::fs::read(&full).map_err(|e| e.to_string())?; + Ok((bytes, source)) }; s.import_material(material, strp(p, "name"), &load) } diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..4b2a209b 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -54,6 +54,17 @@ pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let (width, data) = resampled(s, cmd, ts, map, images)?; + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = width; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(width) +} + +/// The pixels [`use_images`] would give mesh map `map` of set `ts`, and their width +pub(crate) fn resampled(s: &Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result<(u32, Vec)> { let texture_set = s.doc.project.texture_set(ts)?; let grid = texture_set.tile_grid(); if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { @@ -74,11 +85,7 @@ pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, i }), }; - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = width; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(width) + Ok((width, data)) } /// Dimensions shared by imported mesh maps, checked before allocating the resampled pixels diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 20913de2..2c9f9b56 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -4,12 +4,13 @@ use std::collections::BTreeMap; use std::path::Path; use serde_json::{Value, json}; -use texturecraft_core::BakedMap; +use texturecraft_core::{BakedMap, MeshMapSlot, ResourceSource}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images}; use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; use crate::resource_cmds::read_image_file; +use crate::resource_update_cmds::file_source; use crate::{Result, Session, cmd}; const CMD: &str = "textureSet.meshMap.import"; @@ -84,11 +85,13 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result() as u64; let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + s.doc.project.resource_sources.insert(name.clone(), source); let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; images.insert(*tile, image.clone()); diff --git a/crates/engine/src/pbr_cmds.rs b/crates/engine/src/pbr_cmds.rs index d5b3d4aa..09a0a9e9 100644 --- a/crates/engine/src/pbr_cmds.rs +++ b/crates/engine/src/pbr_cmds.rs @@ -80,6 +80,9 @@ pub fn specs() -> Vec { pub type FileList = Vec<(String, u64)>; /// Reads a file of the list by name. pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result, String>; +/// The file on disk a file of the list is read from (None: an archive entry or bytes in memory), +/// asked right before reading it. +type Locator<'a> = &'a dyn Fn(&str) -> Option; mod pbr_options; mod take; @@ -137,10 +140,16 @@ impl Session { /// Import the maps found among `files` as one fill layer on the active texture set; `load` /// reads a file by name. Returns the reply of `file.importPbrFolder`. pub fn import_pbr(&mut self, files: &FileList, load: Loader, options: &PbrOptions) -> Result { - self.import_pbr_with_budget(files, load, options, import_memory_budget()) + self.import_pbr_with_budget(files, load, &|_| None, options, import_memory_budget()) } - fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, options: &PbrOptions, memory_budget: u64) -> Result { + /// [`Session::import_pbr`] that records the disk files `locate` names, so the Resources Updater can read them again + #[cfg(not(target_arch = "wasm32"))] + fn import_pbr_located(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions) -> Result { + self.import_pbr_with_budget(files, load, locate, options, import_memory_budget()) + } + + fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions, memory_budget: u64) -> Result { let set = detect_with(files, &options.choose)?; if set.is_empty() { return Err(EngineError::Other(format!( @@ -193,6 +202,10 @@ impl Session { let mut fill = Fill { projection: options.projection.clone(), ..Fill::default() }; let mut added: Vec<(String, Arc>)> = Vec::new(); let mut decoded = Vec::new(); + + // Disk files read by name, and the resources that hold one of them unchanged + let mut file_sources: BTreeMap = BTreeMap::new(); + let mut resource_sources: Vec<(String, texturecraft_core::ResourceSource)> = Vec::new(); let mut channels: Vec = Vec::new(); let mut total_texels = 0u64; let mut retained_bytes = 0u64; @@ -231,6 +244,9 @@ impl Session { let loaded = if allowed_texels == 0 { Err("not enough memory is available to import more textures".to_string()) } else { + if let Some(source) = locate(&file) { + file_sources.insert(file.clone(), source); + } load(&file).and_then(|bytes| { if bytes.len() as u64 > MAX_FILE_BYTES { return Err(format!("the file is over {} MB", MAX_FILE_BYTES >> 20)); @@ -294,6 +310,13 @@ impl Session { suffix_index += 1; } + // Only a resource holding the file's own bytes can be compared with it later + if take == Take::Whole + && let Some(source) = file_sources.get(&file) + { + resource_sources.push((unique.clone(), source.clone())); + } + added.push((unique.clone(), resource_bytes)); decoded.push((unique.clone(), crate::resource_cmds::decoded(resource_image))); made.insert((file.clone(), take), unique.clone()); @@ -316,6 +339,7 @@ impl Session { for (n, bytes) in &added { s.doc.resources.insert(n.clone(), bytes.clone()); } + s.doc.project.resource_sources.extend(resource_sources); let id = s.doc.project.alloc_id(); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name.clone(), LayerKind::Fill(fill), &channels)) })?; @@ -420,7 +444,12 @@ fn import(s: &mut Session, p: &Value) -> Result { if options.name.is_none() { options.name = found.name.clone(); } - s.import_pbr(&found.files, &|name| found.load(name), &options) + s.import_pbr_located( + &found.files, + &|name| found.load(name), + &|name| found.disk_path(name).map(|path| crate::resource_update_cmds::file_source(&path)), + &options, + ) } #[cfg(not(target_arch = "wasm32"))] @@ -462,7 +491,7 @@ mod tests { let mut session = Session::new_project("test", crate::geom::primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); let load = |_: &str| Ok(bytes.clone()); - let result = session.import_pbr_with_budget(&files, &load, &PbrOptions::default(), 64); + let result = session.import_pbr_with_budget(&files, &load, &|_| None, &PbrOptions::default(), 64); assert!(result.unwrap_err().to_string().contains("more than 1 texels")); assert!(session.doc.resources.is_empty()); @@ -471,7 +500,7 @@ mod tests { assert_eq!(allowed_source_texels(256, 64, 3), 2); let never_load = |_: &str| -> std::result::Result, String> { panic!("no source should load after the budget is spent") }; - let result = session.import_pbr_with_budget(&files, &never_load, &PbrOptions::default(), 0); + let result = session.import_pbr_with_budget(&files, &never_load, &|_| None, &PbrOptions::default(), 0); assert!(result.unwrap_err().to_string().contains("not enough memory")); } diff --git a/crates/engine/src/pbr_cmds/native/found.rs b/crates/engine/src/pbr_cmds/native/found.rs index 454203a6..4f056d92 100644 --- a/crates/engine/src/pbr_cmds/native/found.rs +++ b/crates/engine/src/pbr_cmds/native/found.rs @@ -13,6 +13,16 @@ pub(in crate::pbr_cmds) struct Found { impl Found { /// Reads one file of the list. Archive entries are read through a limit, since their /// declared size can lie. + /// The file on disk `name` is read from (None for an archive entry or a name not in the list) + pub(in crate::pbr_cmds) fn disk_path(&self, name: &str) -> Option { + let path = match &self.source { + Origin::Folder { root } => root.join(name), + Origin::Files(paths) => paths.iter().find(|p| p.file_name().is_some_and(|n| n.to_string_lossy() == name))?.clone(), + Origin::Zip(_) => return None, + }; + path.to_str().map(str::to_string) + } + pub(in crate::pbr_cmds) fn load(&self, name: &str) -> std::result::Result, String> { match &self.source { Origin::Folder { root } => read_regular(&root.join(name), MAX_FILE_BYTES), diff --git a/crates/engine/src/reloaded_file.rs b/crates/engine/src/reloaded_file.rs index b65582d2..048161c1 100644 --- a/crates/engine/src/reloaded_file.rs +++ b/crates/engine/src/reloaded_file.rs @@ -16,13 +16,10 @@ pub(crate) struct ReloadedFile { impl ReloadedFile { /// Read and decode `path` for resource `name` within the resource limits (`cmd` names errors) pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result { - let file_path = std::path::Path::new(path); - - // Taken before reading, so a write during the read still shows as a change later - let modified_ms = crate::resource_update_cmds::modified_ms_of(file_path); - let bytes = crate::resource_cmds::read_resource_file(cmd, file_path, crate::resource_cmds::MAX_BYTES as u64)?; + let source = crate::resource_update_cmds::file_source(path); + let bytes = crate::resource_cmds::read_resource_file(cmd, std::path::Path::new(path), crate::resource_cmds::MAX_BYTES as u64)?; let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{path}: {error}")))?; - Ok(ReloadedFile { name, bytes, image, source: ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms } }) + Ok(ReloadedFile { name, bytes, image, source }) } } diff --git a/crates/engine/src/resource_check.rs b/crates/engine/src/resource_check.rs new file mode 100644 index 00000000..f7505daa --- /dev/null +++ b/crates/engine/src/resource_check.rs @@ -0,0 +1,23 @@ +//! A remembered comparison of a resource with its file, so an unchanged file is not read again + +use std::sync::{Arc, Weak}; + +use crate::resource_status::ResourceStatus; + +/// What reading a resource's file found, kept while the file's size and time stay the same +#[derive(Clone, Debug)] +pub(crate) struct ResourceCheck { + pub path: String, + pub size: u64, + pub modified_ms: u64, + /// The resource bytes the file was compared with (an update or undo replaces them) + pub bytes: Weak>, + pub status: ResourceStatus, +} + +impl ResourceCheck { + /// Whether this verdict still holds for the file and the resource's bytes + pub(crate) fn holds_for(&self, path: &str, size: u64, modified_ms: u64, bytes: &Arc>) -> bool { + self.path == path && self.size == size && self.modified_ms == modified_ms && std::ptr::eq(self.bytes.as_ptr(), Arc::as_ptr(bytes)) + } +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index d20cb60e..2c708501 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -184,10 +184,8 @@ fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let prefix = strp(p, "prefix").unwrap_or(""); - // Taken before reading, so a write during the read still shows as a change in the Resources Updater - let modified_ms = crate::resource_update_cmds::modified_ms_of(std::path::Path::new(path)); + let source = crate::resource_update_cmds::file_source(path); let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let source = texturecraft_core::ResourceSource { path: crate::resource_update_cmds::absolute_path(path), modified_ms }; let name = s.edit("Import resource", |session| { let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?; diff --git a/crates/engine/src/resource_state.rs b/crates/engine/src/resource_state.rs index 1a3e427c..2e33cb63 100644 --- a/crates/engine/src/resource_state.rs +++ b/crates/engine/src/resource_state.rs @@ -7,6 +7,7 @@ use crate::resource_status::ResourceStatus; pub struct ResourceState { /// The resource's name in the project. pub name: String, + /// How the resource compares with its file now. pub status: ResourceStatus, /// The file it was imported from or relinked to (None: made in the app or imported without a path). pub path: Option, diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs index ea69042d..0fc56e7d 100644 --- a/crates/engine/src/resource_update_cmds.rs +++ b/crates/engine/src/resource_update_cmds.rs @@ -1,6 +1,7 @@ //! The Resources Updater: compare image resources with the files they came from, read changed //! files again and point a resource at another file. Each change is one undo step, and every -//! layer, mask and view using a changed resource recomposites. +//! layer, mask and view using a changed resource recomposites; a mesh map imported from a changed +//! file is resampled while it still holds what the file gave it. use serde_json::{Value, json}; use texturecraft_core::ResourceSource; @@ -35,7 +36,7 @@ pub fn specs() -> Vec { "Relink resource", [], None, - "{name, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", + "{name: image resource, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on", always, relink ), @@ -44,63 +45,134 @@ pub fn specs() -> Vec { impl Session { /// The image resources with their files and how they compare, outdated first, then by name. - /// Reads a file only when its size matches the stored bytes but its modification time does not. - pub fn resource_states(&self) -> Vec { - let sources = &self.doc.project.resource_sources; - let mut states: Vec = self - .doc - .resources - .iter() - .filter(|(name, _)| self.images.contains_key(*name) || sources.contains_key(*name)) - .map(|(name, bytes)| { - let source = sources.get(name); - let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(source, bytes)); - ResourceState { name: name.clone(), status, path: source.map(|source| source.path.clone()), error } - }) - .collect(); - + /// A file is read only when its size matches the stored bytes but its modification time does + /// not, and that verdict is kept until the file's size or time changes again. + pub fn resource_states(&mut self) -> Vec { + let mut states = self.compare_resources(); states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); states } - /// Put reloaded files in place of their resources' bytes and pixels as one undo step + /// Whether `name` is an image resource the Resources Updater lists + fn is_image_resource(&self, name: &str) -> bool { + self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name)) + } + + #[cfg(not(target_arch = "wasm32"))] + fn compare_resources(&mut self) -> Vec { + let mut checks = std::mem::take(&mut self.resource_checks); + let names: Vec = self.doc.resources.keys().filter(|name| self.is_image_resource(name)).cloned().collect(); + let mut states = Vec::with_capacity(names.len()); + for name in names { + let (Some(bytes), source) = (self.doc.resources.get(&name), self.doc.project.resource_sources.get(&name)) else { continue }; + let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(&name, source, bytes, &mut checks)); + states.push(ResourceState { path: source.map(|source| source.path.clone()), name, status, error }); + } + + checks.retain(|name, _| self.doc.resources.contains_key(name)); + self.resource_checks = checks; + states + } + + #[cfg(target_arch = "wasm32")] + fn compare_resources(&mut self) -> Vec { + let sources = &self.doc.project.resource_sources; + let browser = "file paths are not available in the browser"; + let names = self.doc.resources.keys().filter(|name| self.is_image_resource(name)); + names + .map(|name| match sources.get(name) { + Some(source) => { + ResourceState { name: name.clone(), status: ResourceStatus::Missing, path: Some(source.path.clone()), error: Some(browser.into()) } + } + None => ResourceState { name: name.clone(), status: ResourceStatus::NoSource, path: None, error: None }, + }) + .collect() + } + + /// Put reloaded files in place of their resources' bytes as one undo step, resample the mesh + /// maps imported from them, then decode the stored bytes as undo, redo and reopening do #[cfg(not(target_arch = "wasm32"))] fn install_reloaded(&mut self, label: &str, files: Vec) -> Result> { + use std::collections::{BTreeMap, BTreeSet}; + if files.is_empty() { return Ok(Vec::new()); } - let decoded = self.edit(label, |session| { - let mut decoded = Vec::with_capacity(files.len()); + let names: Vec = files.iter().map(|file| file.name.clone()).collect(); + self.edit(label, |session| { + let mut fresh = BTreeMap::new(); + let mut slots = BTreeSet::new(); for file in files { + slots.extend(file.source.mesh_map.map(|slot| (slot.texture_set, slot.map))); session.doc.resources.insert(file.name.clone(), std::sync::Arc::new(file.bytes)); session.doc.project.resource_sources.insert(file.name.clone(), file.source); - decoded.push((file.name, file.image)); + fresh.insert(file.name, crate::resource_cmds::decoded(file.image)); } - Ok(decoded) + for (texture_set, map) in slots { + session.refresh_mesh_map(texture_set, map, &fresh)?; + } + + Ok(()) })?; - // The edit marked every set using a replaced resource for recompositing; the new pixels are read then - let mut names = Vec::with_capacity(decoded.len()); - for (name, image) in decoded { - if crate::fill_alpha::matches_saved_picture(&name, &image) { - self.library_alphas.insert(name.clone()); - } else { - self.library_alphas.remove(&name); - } + for name in &names { + self.images.remove(name); + } + self.sync_images(); + Ok(names) + } - self.images.insert(name.clone(), crate::resource_cmds::decoded(image)); - names.push(name); + /// Resample mesh map `map` of set `texture_set` from the new pixels of the files it was + /// imported from, unless a bake or another image has replaced it since (it no longer equals + /// what the old pixels give) + #[cfg(not(target_arch = "wasm32"))] + fn refresh_mesh_map( + &mut self, + texture_set: usize, + map: texturecraft_core::BakedMap, + fresh: &std::collections::BTreeMap>, + ) -> Result<()> { + const CMD: &str = "resource.update"; + + let tiles: Vec<(u32, String)> = self + .doc + .project + .resource_sources + .iter() + .filter_map(|(name, source)| { + source.mesh_map.filter(|slot| slot.texture_set == texture_set && slot.map == map).map(|slot| (slot.tile, name.clone())) + }) + .collect(); + let (mut before, mut after) = (std::collections::BTreeMap::new(), std::collections::BTreeMap::new()); + for (tile, name) in tiles { + let Some(old) = self.images.get(&name) else { return Ok(()) }; + + before.insert(tile, old.clone()); + after.insert(tile, fresh.get(&name).unwrap_or(old).clone()); } - Ok(names) + let current = self.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)); + let unchanged = crate::meshmap_cmds::resampled(self, CMD, texture_set, map, &before).ok(); + let from_these_files = current.zip(unchanged).is_some_and(|(current, (_, unchanged))| current.as_slice() == unchanged.as_slice()); + if from_these_files { + crate::meshmap_cmds::use_images(self, CMD, texture_set, map, &after)?; + } + + Ok(()) } } -/// How `stored` (a resource's bytes) compares with the file `source` names now +/// How `stored` (a resource's bytes) compares with the file `source` names now, reusing the +/// remembered verdict in `checks` while the file's size and time stay the same #[cfg(not(target_arch = "wasm32"))] -fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Option) { +fn compare_with_file( + name: &str, + source: &ResourceSource, + stored: &std::sync::Arc>, + checks: &mut std::collections::HashMap, +) -> (ResourceStatus, Option) { let path = std::path::Path::new(&source.path); let metadata = match std::fs::metadata(path) { Ok(metadata) if metadata.is_file() => metadata, @@ -108,7 +180,8 @@ fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))), }; - if metadata.len() != stored.len() as u64 { + let size = metadata.len(); + if size != stored.len() as u64 { return (ResourceStatus::Outdated, None); } @@ -117,17 +190,21 @@ fn compare_with_file(source: &ResourceSource, stored: &[u8]) -> (ResourceStatus, return (ResourceStatus::UpToDate, None); } - // A newer time alone is not a change: the file may have been saved again unchanged - match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { - Ok(bytes) if bytes == stored => (ResourceStatus::UpToDate, None), - Ok(_) => (ResourceStatus::Outdated, None), - Err(error) => (ResourceStatus::Missing, Some(error.to_string())), + if let Some(check) = checks.get(name) + && check.holds_for(&source.path, size, modified_ms, stored) + { + return (check.status, None); } -} -#[cfg(target_arch = "wasm32")] -fn compare_with_file(_: &ResourceSource, _: &[u8]) -> (ResourceStatus, Option) { - (ResourceStatus::Missing, Some("file paths are not available in the browser".to_string())) + // A newer time alone is not a change: the file may have been saved again unchanged + let status = match crate::resource_cmds::read_resource_file("resource.status", path, crate::resource_cmds::MAX_BYTES as u64) { + Ok(bytes) if bytes == **stored => ResourceStatus::UpToDate, + Ok(_) => ResourceStatus::Outdated, + Err(error) => return (ResourceStatus::Missing, Some(error.to_string())), + }; + let bytes = std::sync::Arc::downgrade(stored); + checks.insert(name.to_string(), crate::resource_check::ResourceCheck { path: source.path.clone(), size, modified_ms, bytes, status }); + (status, None) } /// A file's modification time in milliseconds since the Unix epoch (0 when the system has none) @@ -137,19 +214,22 @@ fn modified_ms(metadata: &std::fs::Metadata) -> u64 { since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) } -/// [`modified_ms`] of the file at `path` (0 when it cannot be read) +/// The record for an image about to be read from `path`: its absolute path and its current +/// modification time, taken before reading so a write during the read still shows as a change #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn modified_ms_of(path: &std::path::Path) -> u64 { - std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)) +pub(crate) fn file_source(path: &str) -> ResourceSource { + let absolute = std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()); + let modified_ms = std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata)); + ResourceSource { path: absolute, modified_ms, mesh_map: None } } -/// `path` made absolute against the working folder, so the record does not depend on where the app started -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn absolute_path(path: &str) -> String { - std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string()) +/// The browser reads no paths; the record keeps the name it was given +#[cfg(target_arch = "wasm32")] +pub(crate) fn file_source(path: &str) -> ResourceSource { + ResourceSource { path: path.to_string(), modified_ms: 0, mesh_map: None } } -fn status(s: &Session) -> Value { +fn status(s: &mut Session) -> Value { let states = s.resource_states(); let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count(); let resources: Vec = states @@ -195,11 +275,14 @@ fn update(s: &mut Session, p: &Value) -> Result { // A file that cannot be read fails alone; the others still update let (mut files, mut failed) = (Vec::new(), Vec::new()); for name in names { - let Some(path) = s.doc.project.resource_sources.get(&name).map(|source| source.path.clone()) else { continue }; - match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &path) { + let Some(previous) = s.doc.project.resource_sources.get(&name).cloned() else { continue }; + match crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), &previous.path) { // Unchanged contents need no undo step Ok(file) if s.doc.resources.get(&name).is_some_and(|stored| **stored == file.bytes) => {} - Ok(file) => files.push(file), + Ok(mut file) => { + file.source.mesh_map = previous.mesh_map; + files.push(file); + } Err(error) => failed.push(json!({"name": name, "error": error.to_string()})), } } @@ -219,11 +302,13 @@ fn relink(s: &mut Session, p: &Value) -> Result { let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string(); let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; - if !s.doc.resources.contains_key(&name) { - return Err(bad(CMD, format!("no resource `{name}`"))); + if !s.is_image_resource(&name) { + return Err(bad(CMD, format!("no image resource `{name}`"))); } - let file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + // A relinked mesh map file still feeds its mesh map + let mut file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?; + file.source.mesh_map = s.doc.project.resource_sources.get(&name).and_then(|source| source.mesh_map); let path = file.source.path.clone(); s.install_reloaded("Relink resource", vec![file])?; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index beb20ab0..4bce1792 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -462,6 +462,9 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Resource names whose decoded pixels match a library alpha. pub(crate) library_alphas: BTreeSet, + /// Resources whose file was read for the Resources Updater, by name: the verdict stays while the file's size and time do + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resource_checks: std::collections::HashMap, /// Temporary texel mask limiting paint strokes (not saved, not in the history). pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). @@ -547,6 +550,8 @@ impl Session { blending_clipboard: None, images: Default::default(), library_alphas: BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] + resource_checks: std::collections::HashMap::new(), quick_mask: Default::default(), painting_paths: false, path_cache: None, diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index c0d0f1dc..93b26908 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -1,40 +1,20 @@ //! The Resources Updater: image resources remember their files, a changed file shows as outdated, //! Update reads it again (one undo step, recompositing its layers) and Relink follows another file -use std::path::{Path, PathBuf}; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{BakedMap, Channel}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{ResourceStatus, Session, execute}; -const RESOLUTION: u32 = 64; -const SAMPLE_STRIDE: usize = 4; +const RESOLUTION: u32 = 128; +const SAMPLE_STRIDE: usize = 8; const RED: [u8; 4] = [255, 0, 0, 255]; const GREEN: [u8; 4] = [0, 255, 0, 255]; -/// A test folder removed when dropped -struct TempDir(PathBuf); - -impl TempDir { - fn new(test: &str) -> TempDir { - let path = std::env::temp_dir().join(format!("tc-resource-updater-{test}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - TempDir(path) - } - - fn file(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - fn session() -> Session { Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap() } @@ -48,9 +28,22 @@ fn text(path: &Path) -> &str { path.to_str().unwrap() } +/// Give the file at `path` the modification time `time` without changing its contents +fn set_modified(path: &Path, time: SystemTime) { + std::fs::File::options().write(true).open(path).unwrap().set_modified(time).unwrap(); +} + +fn modified(path: &Path) -> SystemTime { + std::fs::metadata(path).unwrap().modified().unwrap() +} + +fn import(s: &mut Session, path: &Path) -> String { + execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string() +} + /// Import `path` and show it as a base colour fill; returns the resource name fn import_as_fill(s: &mut Session, path: &Path) -> String { - let name = execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string(); + let name = import(s, path); execute(s, "layer.add.image", &json!({"name": name})).unwrap(); s.update(); name @@ -62,19 +55,19 @@ fn base_colors(s: &Session) -> Vec<[f32; 3]> { samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() } -fn status_of(s: &Session, name: &str) -> ResourceStatus { +fn status_of(s: &mut Session, name: &str) -> ResourceStatus { s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status } #[test] fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() { - let dir = TempDir::new("update"); - let file = dir.file("bricks.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("bricks.png"); write_png(&file, 4, RED); let mut s = session(); let name = import_as_fill(&mut s, &file); let before = base_colors(&s); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); write_png(&file, 8, GREEN); let status = execute(&mut s, "resource.status", &Value::Null).unwrap(); @@ -90,7 +83,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() assert_eq!(updated["updated"], json!([name])); assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); assert_eq!(s.images[&name].width, 8, "the new pixels are decoded"); assert_ne!(after, before, "the fill using the resource recomposited"); @@ -99,7 +92,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name"); assert_eq!(base_colors(&s), before); - assert_eq!(status_of(&s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated, "the file on disk is still the new one"); execute(&mut s, "edit.redo", &Value::Null).unwrap(); s.update(); @@ -109,24 +102,60 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() } #[test] -fn nothing_outdated_adds_no_undo_step() { - let dir = TempDir::new("unchanged"); - let file = dir.file("same.png"); +fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { + let dir = tempfile::tempdir().unwrap(); + let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name)); + for file in [&fine, &gone, &changed] { + write_png(file, 4, RED); + } + let mut s = session(); + let png = std::fs::read(&fine).unwrap(); + s.import_resource_bytes("a_unlinked.png", png).unwrap(); + for file in [&fine, &gone, &changed] { + import(&mut s, file); + } + std::fs::remove_file(&gone).unwrap(); + write_png(&changed, 8, GREEN); + + let order: Vec = s.resource_states().into_iter().map(|state| state.name).collect(); + + assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png"], "by status first, against the name order"); +} + +#[test] +fn a_same_size_file_is_compared_by_contents_once_per_time() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("same.png"); write_png(&file, 4, RED); let mut s = session(); - import_as_fill(&mut s, &file); + let name = import(&mut s, &file); + let original = std::fs::read(&file).unwrap(); + let later = modified(&file) + Duration::from_secs(10); + + // Saved again unchanged: a new time alone is no change, and updating adds no step + set_modified(&file, later); let steps = s.history_labels().len(); - - let updated = execute(&mut s, "resource.update", &json!({})).unwrap(); - - assert_eq!(updated["updated"], json!([])); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); + assert_eq!(execute(&mut s, "resource.update", &json!({})).unwrap()["updated"], json!([])); assert_eq!(s.history_labels().len(), steps); + + // Different bytes of the same size and time are not read again: the verdict for that size and time stands + let mut edited = original.clone(); + let last = edited.len() - 1; + edited[last] ^= 0xff; + std::fs::write(&file, &edited).unwrap(); + set_modified(&file, later); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate, "the remembered verdict is used"); + + // Another time reads the file, and its bytes differ + set_modified(&file, later + Duration::from_secs(10)); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); } #[test] fn a_missing_file_is_reported_and_updating_it_changes_nothing() { - let dir = TempDir::new("missing"); - let file = dir.file("gone.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("gone.png"); write_png(&file, 4, RED); let mut s = session(); let name = import_as_fill(&mut s, &file); @@ -145,8 +174,8 @@ fn a_missing_file_is_reported_and_updating_it_changes_nothing() { #[test] fn an_unreadable_file_fails_alone_while_the_others_update() { - let dir = TempDir::new("partial"); - let (kept, gone) = (dir.file("kept.png"), dir.file("gone.png")); + let dir = tempfile::tempdir().unwrap(); + let (kept, gone) = (dir.path().join("kept.png"), dir.path().join("gone.png")); write_png(&kept, 4, RED); write_png(&gone, 4, RED); let mut s = session(); @@ -164,8 +193,8 @@ fn an_unreadable_file_fails_alone_while_the_others_update() { #[test] fn relink_reads_another_file_and_follows_it_from_then_on() { - let dir = TempDir::new("relink"); - let (first, second) = (dir.file("first.png"), dir.file("second.png")); + let dir = tempfile::tempdir().unwrap(); + let (first, second) = (dir.path().join("first.png"), dir.path().join("second.png")); write_png(&first, 4, RED); write_png(&second, 8, GREEN); let mut s = session(); @@ -183,45 +212,132 @@ fn relink_reads_another_file_and_follows_it_from_then_on() { // The old file no longer matters, the new one does write_png(&first, 16, GREEN); - assert_eq!(status_of(&s, &name), ResourceStatus::UpToDate); + assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate); write_png(&second, 16, RED); - assert_eq!(status_of(&s, &name), ResourceStatus::Outdated); + assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link"); } +#[test] +fn relink_refuses_resources_that_are_not_images() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("picture.png"); + write_png(&file, 4, RED); + let mut s = session(); + s.doc.resources.insert("material.mcmat".to_string(), Arc::new(vec![1, 2, 3])); + let steps = s.history_labels().len(); + + let error = execute(&mut s, "resource.relink", &json!({"name": "material.mcmat", "path": text(&file)})).unwrap_err(); + + assert!(error.to_string().contains("no image resource"), "{error}"); + assert_eq!(*s.doc.resources["material.mcmat"], vec![1, 2, 3]); + assert_eq!(s.history_labels().len(), steps); +} + #[test] fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() { - let dir = TempDir::new("reopen"); - let file = dir.file("kept.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("kept.png"); write_png(&file, 4, RED); let mut s = session(); let linked = import_as_fill(&mut s, &file); let png = std::fs::read(&file).unwrap(); let unlinked = s.import_resource_bytes("made.png", png).unwrap(); - assert_eq!(status_of(&s, &unlinked), ResourceStatus::NoSource); + assert_eq!(status_of(&mut s, &unlinked), ResourceStatus::NoSource); assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err()); - let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); write_png(&file, 8, GREEN); - assert_eq!(status_of(&reopened, &linked), ResourceStatus::Outdated); + assert_eq!(status_of(&mut reopened, &linked), ResourceStatus::Outdated); } #[test] fn a_removed_resource_forgets_its_file() { - let dir = TempDir::new("remove"); - let file = dir.file("old.png"); + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("old.png"); write_png(&file, 4, RED); let mut s = session(); - let name = execute(&mut s, "resource.import", &json!({"path": text(&file)})).unwrap()["name"].as_str().unwrap().to_string(); + let name = import(&mut s, &file); execute(&mut s, "resource.remove", &json!({"name": name})).unwrap(); let png = std::fs::read(&file).unwrap(); let reused = s.import_resource_bytes("old.png", png).unwrap(); assert_eq!(reused, name, "the name is free again"); - assert_eq!(status_of(&s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); + assert_eq!(status_of(&mut s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file"); +} + +/// The material ball: texture sets "Ball" and "Base" +fn ball() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +fn ambient_occlusion(s: &Session) -> Vec { + s.doc.baked[&0].maps[&BakedMap::AmbientOcclusion].as_ref().clone() +} + +#[test] +fn an_imported_mesh_map_follows_its_changed_file_until_something_else_replaces_it() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + write_png(&file, 4, [60, 60, 60, 255]); + let mut s = ball(); + execute(&mut s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let name = s.doc.project.resource_sources.keys().next().expect("the file is remembered").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 8, [200, 200, 200, 255]); + execute(&mut s, "resource.update", &json!({})).unwrap(); + let updated = ambient_occlusion(&s); + + assert_ne!(updated, imported, "the mesh map is resampled from the new file"); + + // Another image in the slot is not overwritten by a later change of the file + let other = dir.path().join("other.png"); + write_png(&other, 4, [10, 10, 10, 255]); + let other_name = import(&mut s, &other); + execute(&mut s, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": other_name})).unwrap(); + let replaced = ambient_occlusion(&s); + write_png(&file, 16, [120, 120, 120, 255]); + let result = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap(); + + assert_eq!(result["updated"], json!([name]), "the resource itself still updates"); + assert_eq!(ambient_occlusion(&s), replaced, "the mesh map keeps the image set over it"); +} + +#[test] +fn pbr_folder_and_materialx_imports_remember_their_image_files() { + let dir = tempfile::tempdir().unwrap(); + let color = dir.path().join("moss_col.png"); + write_png(&color, 4, RED); + std::fs::create_dir(dir.path().join("tex")).unwrap(); + let base = dir.path().join("tex").join("base.png"); + write_png(&base, 4, GREEN); + let mtlx = dir.path().join("m.mtlx"); + let document = r#" + + + + +"#; + std::fs::write(&mtlx, document).unwrap(); + let mut s = session(); + + let pbr = execute(&mut s, "file.importPbrFolder", &json!({"files": [text(&color)]})).unwrap(); + let materialx = execute(&mut s, "file.importMaterialX", &json!({"path": text(&mtlx)})).unwrap(); + let pbr_name = pbr["resources"][0].as_str().unwrap().to_string(); + let materialx_name = materialx["resources"][0].as_str().unwrap().to_string(); + + assert!(s.doc.project.resource_sources[&pbr_name].path.ends_with("moss_col.png")); + assert!(s.doc.project.resource_sources[&materialx_name].path.ends_with("base.png")); + + write_png(&color, 8, GREEN); + write_png(&base, 8, RED); + + assert_eq!(status_of(&mut s, &pbr_name), ResourceStatus::Outdated); + assert_eq!(status_of(&mut s, &materialx_name), ResourceStatus::Outdated); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9abb472c..50481899 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -82,3 +82,5 @@ egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } pollster = "0.4" image = { workspace = true } craft-image-codecs = { workspace = true } +# Test folders removed when the test ends +tempfile = "3" diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 235ebc5e..435aac1c 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -237,6 +237,9 @@ mod tests { keys.extend(BlendMode::all().map(|mode| mode.label())); keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label())); keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label())); + keys.extend(texturecraft_engine::ResourceStatus::ALL.iter().map(|status| status.label())); + let notice = crate::toast_action::ToastAction::UpdateResources { project: 0 }; + keys.extend([notice.label(), notice.accessible_name()]); keys.extend(texturecraft_engine::HISTORY_TEMPLATES); keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 100d07a5..b10af608 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -325,6 +325,9 @@ pub struct TextureCraftApp { /// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again #[cfg(not(target_arch = "wasm32"))] pub(crate) resources_notified: std::collections::BTreeSet, + /// The project the Resources Updater last checked on opening (see `resources_updater::follow_project`) + #[cfg(not(target_arch = "wasm32"))] + pub(crate) resources_project: Option, /// The update check and prompt (desktop only). #[cfg(not(target_arch = "wasm32"))] pub(crate) updates_rt: updates_ui::Runtime, @@ -449,6 +452,8 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] resources_notified: std::collections::BTreeSet::new(), #[cfg(not(target_arch = "wasm32"))] + resources_project: None, + #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()), @@ -1130,9 +1135,11 @@ impl eframe::App for TextureCraftApp { // Files may have been edited in another app meanwhile #[cfg(not(target_arch = "wasm32"))] - resources_updater::check_on_focus(self); + resources_updater::check_files(self); } self.focused = focused; + #[cfg(not(target_arch = "wasm32"))] + resources_updater::follow_project(self); 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 { @@ -1335,11 +1342,13 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) { show_log = true; dismissed = Some(i); } - if let Some(action) = t.action - && ui.button(i18n::tr(action.label())).clicked() - { - clicked_action = Some(action); - dismissed = Some(i); + if let Some(action) = t.action { + let button = ui.button(i18n::tr(action.label())); + button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, i18n::tr(action.accessible_name()))); + if button.clicked() { + clicked_action = Some(action); + dismissed = Some(i); + } } }); if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a0fd80de..1d4588ea 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,9 +526,6 @@ 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 app.ui.windows.resources_updater.is_some() && !popup_open && input.key_pressed(Key::Escape) { - #[cfg(not(target_arch = "wasm32"))] - crate::resources_updater::keys_in(app, input); } 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) { diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 4bb9ce60..c0de777d 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -7,7 +7,6 @@ mod row_request; use std::collections::BTreeSet; -use egui::{Key, Modifiers}; use serde_json::json; use texturecraft_engine::{ResourceState, ResourceStatus}; @@ -25,7 +24,7 @@ use row_request::RowRequest; const WINDOW_WIDTH_POINTS: f32 = 640.0; /// Height of the resource list const LIST_HEIGHT_POINTS: f32 = 360.0; -// Initial space for the header, tabs, filters and footer +/// Initial space for the header, tabs, filters and footer const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0; /// Side of a row's thumbnail const THUMBNAIL_POINTS: f32 = 40.0; @@ -39,6 +38,8 @@ const ROW_MARGIN: egui::Margin = egui::Margin::same(4); const OUTDATED_TINT: f32 = 0.18; /// How long the "changed on disk" notice stays, in seconds: long enough to reach its button const NOTICE_SECONDS: f64 = 12.0; +/// Shortest time between two checks after document changes, in seconds (each check looks at every file) +const RECHECK_SECONDS: f64 = 0.5; /// Opens the window, or closes it when it is open (the shelf button) pub(crate) fn toggle(app: &mut TextureCraftApp) { @@ -54,13 +55,26 @@ pub(crate) fn open(app: &mut TextureCraftApp) { rows: app.session.resource_states(), project: app.session.project_id, checked_revision: app.session.revision, + checked_at: app.last_time, ..window }); } -/// The app has the focus back: check the files again and, when other resources than last time -/// are outdated, show a notice whose button updates them -pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { +/// Check once when another project is open (files may have changed while it was closed), and +/// forget what was announced for the last one +pub(crate) fn follow_project(app: &mut TextureCraftApp) { + if !app.session.project_open || app.resources_project == Some(app.session.project_id) { + return; + } + + app.resources_project = Some(app.session.project_id); + app.resources_notified.clear(); + check_files(app); +} + +/// Check the files again (the app has the focus back, or a project opened) and, when other +/// resources than last time are outdated, show a notice whose button updates them +pub(crate) fn check_files(app: &mut TextureCraftApp) { if !app.session.project_open { return; } @@ -70,6 +84,7 @@ pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { if let Some(window) = app.ui.windows.resources_updater.as_mut() { window.rows = rows; window.checked_revision = app.session.revision; + window.checked_at = app.last_time; } if !outdated.is_empty() && outdated != app.resources_notified { @@ -81,7 +96,7 @@ pub(crate) fn check_on_focus(app: &mut TextureCraftApp) { app.toast(text, false); if let Some(toast) = app.toasts.last_mut() { toast.until = app.last_time + NOTICE_SECONDS; - toast.action = Some(ToastAction::UpdateResources); + toast.action = Some(ToastAction::UpdateResources { project: app.session.project_id }); } } app.resources_notified = outdated; @@ -137,13 +152,6 @@ fn show_in_folder(app: &mut TextureCraftApp, path: &str) { } } -/// The keys of the open window: Escape closes it (an open dropdown takes it first, see `menus`) -pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { - if input.consume_key(Modifiers::NONE, Key::Escape) { - app.ui.windows.resources_updater = None; - } -} - /// Whether `row` passes the window's status and name filters fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool { let name_filter = window.name_filter.trim().to_lowercase(); @@ -164,18 +172,31 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // Every change (an update, undo, redo, a removed resource) is checked again + // Every change (an update, undo, redo, a removed resource) is checked again, at most twice a second if window.checked_revision != app.session.revision { - window.rows = app.session.resource_states(); - window.checked_revision = app.session.revision; + let wait = window.checked_at + RECHECK_SECONDS - app.last_time; + if wait <= 0.0 { + window.rows = app.session.resource_states(); + window.checked_revision = app.session.revision; + window.checked_at = app.last_time; + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } + } + + // Escape closes the window only while one of its controls had the keyboard (egui takes the focus away on it); otherwise it cancels a stroke as usual + // egui consumes that Escape to take the focus away, so the raw events are read + let escape = ctx.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if window.had_keyboard && escape && !egui::Popup::is_any_open(ctx) { + return; } let tokens = Tokens::get(ctx); - let mut open = true; + let mut window_open = true; let (mut refresh, mut update_all) = (false, false); let mut request = None; - crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut open) + let shown = crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut window_open) .default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS)) .show(ctx, |ui| { ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name)); @@ -216,7 +237,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { ui.horizontal(|ui| { - refresh = ui.button(tr("Refresh")).clicked(); + let refresh_button = ui.button(tr("Refresh")); + refresh_button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Refresh resources"))); + refresh = refresh_button.clicked(); ui.label(summary(&window.rows)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated); @@ -252,15 +275,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); - if !open { + let focused = ctx.memory(|memory| memory.focused()).and_then(|id| ctx.read_response(id)); + window.had_keyboard = shown.as_ref().zip(focused.as_ref()).is_some_and(|(shown, focused)| focused.layer_id == shown.response.layer_id); + if !window_open { return; } app.ui.windows.resources_updater = Some(window); - if refresh { - open(app); - } + // Its own changes and Refresh show at once + let check_now = refresh || update_all || matches!(request, Some(RowRequest::Update(_))); if update_all { update(app, None); } @@ -270,6 +294,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path), None => {} } + + if check_now { + open(app); + } } /// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are @@ -297,8 +325,7 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: } ui.label(number.to_string()); - // Buttons take their room on the right first, so the texts truncate in what is left - // Each button's accessible name says which resource it acts on + // Buttons go first, so the texts truncate in what is left; each accessible name names its resource ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let update = ui.add_enabled(outdated, egui::Button::new(tr("Update"))); let update_name = format!("{} {}", tr("Update"), row.name); @@ -325,6 +352,7 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: ui.vertical(|ui| { ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate()); + ui.label(format!("{} {}", tr("Shelf :"), tr("project"))); let file = row.path.as_deref().unwrap_or(tr("No source file")); ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file); let status = ui.label(tr(row.status.label())); @@ -352,30 +380,35 @@ mod tests { image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap(); } - fn notices(app: &TextureCraftApp) -> usize { - app.toasts.iter().filter(|toast| toast.action == Some(ToastAction::UpdateResources)).count() + fn notices(app: &TextureCraftApp) -> Vec { + app.toasts.iter().filter_map(|toast| toast.action).collect() } #[test] fn a_changed_file_is_announced_once_and_the_notice_updates_it() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner); - let path = std::env::temp_dir().join(format!("texturecraft-resources-notice-{}.png", std::process::id())); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("notice.png"); write_png(&path, 4); let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); - check_on_focus(app); - assert_eq!(notices(app), 0, "nothing changed yet"); + check_files(app); + assert!(notices(app).is_empty(), "nothing changed yet"); write_png(&path, 8); - check_on_focus(app); - check_on_focus(app); - assert_eq!(notices(app), 1, "the same change is announced once"); + check_files(app); + check_files(app); + let announced = notices(app); + assert_eq!(announced, [ToastAction::UpdateResources { project: app.session.project_id }], "the same change is announced once"); - ToastAction::UpdateResources.run(app); - std::fs::remove_file(&path).ok(); + // A notice about another project does nothing + ToastAction::UpdateResources { project: app.session.project_id + 1 }.run(app); + assert_eq!(app.session.images[&name].width, 4); + + announced[0].run(app); assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource"); assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources")); diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs index 46fb9d12..805ef0b8 100644 --- a/crates/ui-egui/src/state/resources_updater.rs +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -16,4 +16,8 @@ pub struct ResourcesUpdater { pub project: u64, /// The session revision the rows were checked at pub(crate) checked_revision: u64, + /// When the rows were checked, in app seconds + pub(crate) checked_at: f64, + /// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it) + pub(crate) had_keyboard: bool, } diff --git a/crates/ui-egui/src/toast_action.rs b/crates/ui-egui/src/toast_action.rs index d360fd7b..e7d05308 100644 --- a/crates/ui-egui/src/toast_action.rs +++ b/crates/ui-egui/src/toast_action.rs @@ -5,30 +5,37 @@ use crate::TextureCraftApp; /// What a toast's button does #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ToastAction { - /// "Update": read every outdated resource file again (the "changed on disk" notice) - #[cfg(not(target_arch = "wasm32"))] - UpdateResources, + /// "Update": read every outdated resource file of `project` again (the desktop's "changed on disk" notice) + UpdateResources { + /// The project the notice is about; the button does nothing once another one is open + project: u64, + }, } impl ToastAction { /// The button's text (English; translated where it is drawn) pub fn label(self) -> &'static str { match self { - #[cfg(not(target_arch = "wasm32"))] - ToastAction::UpdateResources => "Update", + ToastAction::UpdateResources { .. } => "Update", + } + } + + /// The button's accessible name, which says what it acts on (English; translated where it is drawn) + pub fn accessible_name(self) -> &'static str { + match self { + ToastAction::UpdateResources { .. } => "Update resources", } } - #[cfg(not(target_arch = "wasm32"))] pub(crate) fn run(self, app: &mut TextureCraftApp) { match self { - ToastAction::UpdateResources => crate::resources_updater::update(app, None), + // Another project's notice is stale + ToastAction::UpdateResources { project } if project != app.session.project_id => {} + #[cfg(not(target_arch = "wasm32"))] + ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None), + // The browser has no files to read again + #[cfg(target_arch = "wasm32")] + ToastAction::UpdateResources { .. } => {} } } - - /// The browser's toasts carry no action yet - #[cfg(target_arch = "wasm32")] - pub(crate) fn run(self, _: &mut TextureCraftApp) { - match self {} - } } diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 298c1130..534bd7b1 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -4,13 +4,14 @@ use std::path::{Path, PathBuf}; -use egui::{Key, Role}; +use egui::{Key, Role, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; +use texturecraft_ui_egui::state::ViewLayout; use super::temp_dir::TempDir; @@ -59,40 +60,44 @@ fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 { #[test] fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() { let dir = TempDir::new("resources-updater-update"); - let (kept, changed) = (png(&dir, "kept.png", 4), png(&dir, "changed.png", 4)); + let (kept, changed) = (png(&dir, "aa_kept.png", 4), png(&dir, "zz_changed.png", 4)); let mut h = app(); import(&mut h, &kept); import(&mut h, &changed); - png(&dir, "changed.png", 8); + png(&dir, "zz_changed.png", 8); activate(&mut h, "Resources Updater"); let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows; - assert_eq!(rows[0].name, "changed.png", "outdated resources come first"); + assert_eq!(rows[0].name, "zz_changed.png", "outdated resources come first, before names that sort earlier"); assert!(shows(&h, "Project : Test")); + assert_eq!(h.get_all_by_label("Shelf : project").count(), 2, "the reference's shelf line, one per row"); assert!(shows(&h, "(2 resources, 1 outdated)")); assert!(shows(&h, "Outdated"), "the status is written out, not only coloured"); - assert!(h.get_by_role_and_label(Role::Button, "Update kept.png").accesskit_node().is_disabled(), "only outdated resources update"); + assert!(h.get_by_role_and_label(Role::Button, "Update aa_kept.png").accesskit_node().is_disabled(), "only outdated resources update"); let steps = h.state().session.history_labels().len(); - activate(&mut h, "Update changed.png"); + activate(&mut h, "Update zz_changed.png"); - assert_eq!(width_of(&h, "changed.png"), 8, "the new file's pixels are in the project"); + assert_eq!(width_of(&h, "zz_changed.png"), 8, "the new file's pixels are in the project"); assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step"); assert!(shows(&h, "(2 resources, 0 outdated)")); - // Undo brings the old pixels back, so the list shows the file as changed again + // Undo brings the old pixels back, so Refresh shows the file as changed again h.state_mut().run("edit.undo", json!({})).unwrap(); - h.run_steps(3); + activate(&mut h, "Refresh resources"); - assert_eq!(width_of(&h, "changed.png"), 4); + assert_eq!(width_of(&h, "zz_changed.png"), 4); assert!(shows(&h, "(2 resources, 1 outdated)")); activate(&mut h, "Update All"); - assert_eq!(width_of(&h, "changed.png"), 8); + assert_eq!(width_of(&h, "zz_changed.png"), 8); + // Update All went grey with nothing left to update; the keyboard moves on to another button of the window + h.get_by_role_and_label(Role::Button, "Select new resource aa_kept.png").focus(); + h.run_steps(2); press(&mut h, Key::Escape); - assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window"); + assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window while it has the keyboard"); } #[test] @@ -135,3 +140,31 @@ fn show_in_folder_shows_the_folder_of_the_resource_file() { assert_eq!(shown.len(), 1); assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); } + +#[test] +fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() { + const FRAMES_PER_DRAG_EVENT: usize = 2; + + let mut h = app(); + h.state_mut().run("layer.add.paint", json!({})).unwrap(); + h.state_mut().ui.layout = ViewLayout::Only3D; + h.run_steps(3); + let center = h.state().viewport_rect.center(); + h.drag_at(center); + h.run_steps(FRAMES_PER_DRAG_EVENT); + h.hover_at(center + vec2(20.0, 0.0)); + h.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(h.state().session.stroke_active()); + + // Opened from the shelf mid-stroke, the keyboard stays on the shelf button + activate(&mut h, "Resources Updater"); + assert!(h.state().ui.windows.resources_updater.is_some()); + assert!(h.state().session.stroke_active()); + + press(&mut h, Key::Escape); + + assert!(!h.state().session.stroke_active(), "Escape cancels the stroke"); + assert!(h.state().ui.windows.resources_updater.is_some(), "the window keeps open: its controls do not have the keyboard"); + h.drop_at(center + vec2(30.0, 0.0)); + h.run_steps(3); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0cf55589..ce32a426 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -468,17 +468,22 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para ## Resources Updater -An image resource imported with `resource.import {path}` remembers that file (its absolute path and -modification time, saved with the project). The shelf's Resources Updater window lists the project's -image resources through these commands and checks them again when it opens, on Refresh, after every -change and when the app gets the focus back; then a notice ("N resources changed on disk", with an -Update button) appears when the set of outdated resources changed since the last notice. +An image resource read from a file remembers that file (its absolute path and modification time, +saved with the project): `resource.import {path}`, the images `file.importPbrFolder` stores unchanged +(not ORM channels split out, not archive entries), the images of `file.importMaterialX` and the files of +`textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the +old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater +window lists the project's image resources through these commands and checks them when it opens, on +Refresh, after changes (at most twice a second), once after a project opens and when the app gets the +focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of +outdated resources differs from the last notice. A file whose size matches but whose time changed is +read once; its verdict is kept until its size or time changes again. | Command | Params and result | |---|---| | `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | | `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | -| `resource.relink` | `{name, path}` → `{name, path}`: the resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | +| `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | These commands read host paths stored in the project, so MCP and `serve` refuse them through `command_run`; the desktop app's control channel and the trusted local CLI run them. diff --git a/docs/features.md b/docs/features.md index a3692d83..8a25b66a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -98,13 +98,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and alpha images become the brush alpha. Filter by role or remove selected rows before importing. Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are unavailable. The browser imports images straight from its file picker. -- **Resources Updater:** the shelf button under the tools lists the project's image resources with - their files, outdated ones first. An imported image remembers its file; when that file changes on - disk, *Update* (or *Update All*) reads it again and every layer using it recomposites, as one undo - step. *Select new resource* points a resource at another file, *Show in folder* opens its folder, - and the list filters by status and name. When the app gets the focus back after files changed, a - notice offers *Update*. Desktop only; there is no Shaders tab, since TextureCraft has no shader - resources. +- **Resources Updater:** the shelf button under the tools lists the project's image resources, + outdated ones first: name, *Shelf : project* as in the reference, and an extra *File :* line with + the file it came from. An image read from a file (Import resources, PBR folders, MaterialX, imported + mesh maps) remembers it; when the file changes on disk, *Update* (or *Update All*) reads it again + and every layer and imported mesh map using it follows, as one undo step. *Select new resource* + points a resource at another file, *Show in folder* opens its folder, and the list filters by status + and name. After a project opens and when the app gets the focus back after files changed, a notice + offers *Update*. Desktop only; there is no Shaders tab (TextureCraft has no shader resources), no + Pin window and no × to clear a link. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. *Create smart mask* in the same menu saves just the layer's mask (all its effects, painted pixels and images); it appears under From 95fac86e4e4b6d1962b79526305c0ae66692965c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 13:43:31 +0100 Subject: [PATCH 26/80] Resources Updater: recheck files while the window stays open; a mesh map follows its latest imported file --- crates/engine/src/meshmap_import_cmds.rs | 8 ++++- crates/engine/tests/it/resource_updater.rs | 21 +++++++++++++ crates/ui-egui/src/resources_updater.rs | 30 +++++++------------ crates/ui-egui/src/state/resources_updater.rs | 4 +-- crates/ui-egui/tests/it/resources_updater.rs | 18 +++++++++++ docs/control-protocol.md | 2 +- 6 files changed, 59 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 2c9f9b56..0f69659e 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -85,12 +85,18 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result() as u64; let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?; + + // The slot follows only its latest file: an earlier import into it no longer feeds it + for earlier in s.doc.project.resource_sources.values_mut().filter(|earlier| earlier.mesh_map == Some(slot)) { + earlier.mesh_map = None; + } s.doc.project.resource_sources.insert(name.clone(), source); let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?; reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?; diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index 93b26908..43a9120b 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -341,3 +341,24 @@ fn pbr_folder_and_materialx_imports_remember_their_image_files() { assert_eq!(status_of(&mut s, &pbr_name), ResourceStatus::Outdated); assert_eq!(status_of(&mut s, &materialx_name), ResourceStatus::Outdated); } + +#[test] +fn a_mesh_map_imported_twice_follows_the_latest_file() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("Ball_ao.png"); + let import_file = |s: &mut Session| execute(s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap(); + let mut s = ball(); + write_png(&file, 4, [60, 60, 60, 255]); + import_file(&mut s); + let first = s.doc.project.resource_sources.keys().next().unwrap().clone(); + write_png(&file, 8, [200, 200, 200, 255]); + import_file(&mut s); + let latest = s.doc.project.resource_sources.keys().find(|name| **name != first).expect("a second resource").clone(); + let imported = ambient_occlusion(&s); + + write_png(&file, 16, [10, 10, 10, 255]); + execute(&mut s, "resource.update", &json!({"names": [latest]})).unwrap(); + + assert_ne!(ambient_occlusion(&s), imported, "the mesh map follows the file imported last"); + assert!(s.doc.project.resource_sources[&first].mesh_map.is_none(), "the earlier import no longer feeds the slot"); +} diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index c0de777d..95840c26 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -38,7 +38,7 @@ const ROW_MARGIN: egui::Margin = egui::Margin::same(4); const OUTDATED_TINT: f32 = 0.18; /// How long the "changed on disk" notice stays, in seconds: long enough to reach its button const NOTICE_SECONDS: f64 = 12.0; -/// Shortest time between two checks after document changes, in seconds (each check looks at every file) +/// Time between two checks while the window is open, in seconds (each check looks at every file; an unchanged one is not read) const RECHECK_SECONDS: f64 = 0.5; /// Opens the window, or closes it when it is open (the shelf button) @@ -51,13 +51,8 @@ pub(crate) fn toggle(app: &mut TextureCraftApp) { /// Opens the window with the resources checked now (an open window is checked again) pub(crate) fn open(app: &mut TextureCraftApp) { let window = app.ui.windows.resources_updater.take().unwrap_or_default(); - app.ui.windows.resources_updater = Some(ResourcesUpdater { - rows: app.session.resource_states(), - project: app.session.project_id, - checked_revision: app.session.revision, - checked_at: app.last_time, - ..window - }); + app.ui.windows.resources_updater = + Some(ResourcesUpdater { rows: app.session.resource_states(), project: app.session.project_id, checked_at: app.last_time, ..window }); } /// Check once when another project is open (files may have changed while it was closed), and @@ -83,7 +78,6 @@ pub(crate) fn check_files(app: &mut TextureCraftApp) { let outdated: BTreeSet = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect(); if let Some(window) = app.ui.windows.resources_updater.as_mut() { window.rows = rows; - window.checked_revision = app.session.revision; window.checked_at = app.last_time; } @@ -172,16 +166,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // Every change (an update, undo, redo, a removed resource) is checked again, at most twice a second - if window.checked_revision != app.session.revision { - let wait = window.checked_at + RECHECK_SECONDS - app.last_time; - if wait <= 0.0 { - window.rows = app.session.resource_states(); - window.checked_revision = app.session.revision; - window.checked_at = app.last_time; - } else { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); - } + // Files changed on disk and document changes (undo, a removed resource) show while the window stays open + let wait = window.checked_at + RECHECK_SECONDS - app.last_time; + if wait <= 0.0 { + window.rows = app.session.resource_states(); + window.checked_at = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK_SECONDS)); + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } // Escape closes the window only while one of its controls had the keyboard (egui takes the focus away on it); otherwise it cancels a stroke as usual diff --git a/crates/ui-egui/src/state/resources_updater.rs b/crates/ui-egui/src/state/resources_updater.rs index 805ef0b8..3b515d32 100644 --- a/crates/ui-egui/src/state/resources_updater.rs +++ b/crates/ui-egui/src/state/resources_updater.rs @@ -4,7 +4,7 @@ use texturecraft_engine::{ResourceState, ResourceStatus}; #[derive(Clone, Debug, PartialEq, Default)] pub struct ResourcesUpdater { /// The resources and how they compare with their files, outdated first (checked on opening, - /// Refresh, every change and when the app gets the focus back) + /// Refresh, twice a second while open and when the app gets the focus back) pub rows: Vec, /// The status the list is narrowed to (None: all) pub status_filter: Option, @@ -14,8 +14,6 @@ pub struct ResourcesUpdater { pub jump: Option, /// The project that was open when this window opened pub project: u64, - /// The session revision the rows were checked at - pub(crate) checked_revision: u64, /// When the rows were checked, in app seconds pub(crate) checked_at: f64, /// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it) diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 534bd7b1..980102a9 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -168,3 +168,21 @@ fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() { h.drop_at(center + vec2(30.0, 0.0)); h.run_steps(3); } + +#[test] +fn a_file_changed_while_the_window_stays_open_shows_without_refresh() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + + let dir = TempDir::new("resources-updater-idle"); + let file = png(&dir, "bricks.png", 4); + let mut h = app(); + import(&mut h, &file); + activate(&mut h, "Resources Updater"); + assert!(shows(&h, "(1 resources, 0 outdated)")); + + png(&dir, "bricks.png", 8); + h.run_steps(FRAMES); + + assert!(shows(&h, "(1 resources, 1 outdated)"), "no document change, no focus change and no Refresh"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ce32a426..50825541 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -474,7 +474,7 @@ saved with the project): `resource.import {path}`, the images `file.importPbrFol `textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater window lists the project's image resources through these commands and checks them when it opens, on -Refresh, after changes (at most twice a second), once after a project opens and when the app gets the +Refresh, twice a second while it stays open, once after a project opens and when the app gets the focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of outdated resources differs from the last notice. A file whose size matches but whose time changed is read once; its verdict is kept until its size or time changes again. From e26002d230ed7be816860a36bccbb39ea14b8ef2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 16:49:07 +0100 Subject: [PATCH 27/80] Open the window through Xwayland for a pen on Wayland winit 0.30 doesn't bind the Wayland tablet protocol, so on compositors that don't emulate a pointer for the pen (KWin) the pen did nothing in the window. With a pen attached on a Wayland desktop, and Xwayland able to run the window, the app now opens on X11, where the pen works as the pointer. TEXTURECRAFT_NATIVE_WAYLAND=1 keeps native Wayland. Adapted from PhotoCraft. Fixes #816. --- ATTRIBUTION.md | 1 + apps/texturecraft/Cargo.toml | 5 + apps/texturecraft/src/main.rs | 10 ++ apps/texturecraft/src/xwayland_pen.rs | 150 ++++++++++++++++++++++++++ docs/features.md | 3 + 5 files changed, 169 insertions(+) create mode 100644 apps/texturecraft/src/xwayland_pen.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a136498a..1cf696d9 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -26,6 +26,7 @@ licensed and keep their license file next to them. | `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) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/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`) | +| `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 | ## Third-party assets compiled into the binary diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 7f5ee538..39fb3c7c 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -35,6 +35,11 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s # The update helper is a copy of this program (`main`). craft-update = { workspace = true } +# Opening the window through Xwayland for a pen on Wayland (src/xwayland_pen.rs): winit's +# `EventLoopBuilderExtX11`. Already in Cargo.lock through eframe. +[target.'cfg(target_os = "linux")'.dependencies] +winit = { version = "0.30", default-features = false, features = ["x11"] } + # Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not. [target.'cfg(target_os = "macos")'.dependencies] craft-menu = { workspace = true } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 349b9275..e7bf7a7b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -15,6 +15,8 @@ mod nightly_session; mod process_identity; mod profile_root; mod window_frame; +#[cfg(target_os = "linux")] +mod xwayland_pen; use std::ffi::OsString; @@ -398,6 +400,14 @@ fn main() { } let viewport = title_bar.viewport(viewport); let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; + // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; a pen works only through Xwayland there + #[cfg(target_os = "linux")] + if xwayland_pen::opens_through_xwayland() { + use winit::platform::x11::EventLoopBuilderExtX11 as _; + options.event_loop_builder = Some(Box::new(|builder| { + builder.with_x11(); + })); + } if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) { fatal(&e.to_string(), true); std::process::exit(2); diff --git a/apps/texturecraft/src/xwayland_pen.rs b/apps/texturecraft/src/xwayland_pen.rs new file mode 100644 index 00000000..6c3f7d3a --- /dev/null +++ b/apps/texturecraft/src/xwayland_pen.rs @@ -0,0 +1,150 @@ +//! A pen on a Wayland desktop opens the window through Xwayland (#816). +//! +//! Wayland compositors give a pen only to clients that bind the tablet protocol (`zwp_tablet_v2`), +//! which winit 0.30 doesn't (and binding it on winit's connection needs `unsafe`, which this app +//! forbids). Some compositors (KWin) then send the window nothing from the pen: no cursor, no +//! painting. Xwayland binds the protocol and serves the pen as an X11 pointer, so with a pen +//! attached the window opens there. `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland. +//! +//! Adapted from PhotoCraft (storytold/photocraft `830316b7`, MIT OR Apache-2.0): +//! `apps/photocraft/src/tablet.rs` (`display_session`, `pen_needs_xwayland`, `has_pen`, `bit_set`) +//! and `apps/photocraft/src/linux_libs.rs` (`session_from_env`, `ldconfig_has`, the library +//! search), reduced to the pen decision. Replace it with a shared craft-libs crate once one exists +//! (AGENTS.md rule 9). + +use std::path::{Path, PathBuf}; + +/// Set (and not `0`) to keep native Wayland with a pen attached +const NATIVE_WAYLAND_VARIABLE: &str = "TEXTURECRAFT_NATIVE_WAYLAND"; + +/// `BTN_TOOL_PEN` (linux/input-event-codes.h): the key a tablet's stylus, a pen display's or a +/// pen-enabled touchscreen's pen reports +const BTN_TOOL_PEN: u32 = 0x140; + +/// `ABS_X` and `ABS_Y` (linux/input-event-codes.h): the absolute axes every pen reports +const ABS_X: u32 = 0x00; +const ABS_Y: u32 = 0x01; + +/// What winit 0.30 loads at run time for an X11 window: Xlib, Xlib-xcb, xcb, Xcursor, XInput2 and +/// xkbcommon with its X11 part +const X11_LIBRARIES: &[&str] = + &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; + +/// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland +/// can run the window. Says so on stderr when it does. +pub fn opens_through_xwayland() -> bool { + let var = |name: &str| std::env::var(name).ok(); + let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)); + if !pen_needs_xwayland(var, pen, x11_libraries_available) { + return false; + } + + eprintln!("texturecraft: opening the window through Xwayland for the pen ({NATIVE_WAYLAND_VARIABLE}=1 keeps Wayland)"); + true +} + +/// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or +/// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland. +fn pen_needs_xwayland(var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool, x11_libraries: impl FnOnce() -> bool) -> bool { + let set = |name: &str| var(name).is_some_and(|value| !value.is_empty()); + let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET"); + let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0"); + wayland && !keeps_wayland && set("DISPLAY") && pen() && x11_libraries() +} + +/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has +/// `BTN_TOOL_PEN` and its `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as libinput asks of a tablet +/// tool. The key alone isn't enough: a virtual keyboard made with uinput claims every key code. +fn has_pen(devices: &str) -> bool { + devices.split("\n\n").any(|device| { + let bitmap = |name: &str| device.lines().find_map(|line| line.strip_prefix(name)); + bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)) + }) +} + +/// Bit `bit` of a `/proc/bus/input/devices` bitmap: hex words of the kernel's `long`, most +/// significant first. Short or malformed bitmaps have no bits set. +fn bit_set(bitmap: &str, bit: u32) -> bool { + let word_bits = usize::BITS; + let word = usize::try_from(bit / word_bits).unwrap_or(usize::MAX); + bitmap.split_whitespace().rev().nth(word).and_then(|hex| u64::from_str_radix(hex, 16).ok()).is_some_and(|value| (value >> (bit % word_bits)) & 1 == 1) +} + +/// Are the libraries an X11 window needs installed? The linker cache (`ldconfig -p`) or the usual +/// library directories must list each; one that can't be found counts as missing. +fn x11_libraries_available() -> bool { + let cache = linker_cache(); + let dirs = library_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref()); + X11_LIBRARIES.iter().all(|soname| cache.as_deref().is_some_and(|cache| ldconfig_has(cache, soname)) || dirs.iter().any(|dir| dir.join(soname).exists())) +} + +/// `ldconfig -p` in English (it is parsed), from where distributions put it +fn linker_cache() -> Option { + ["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"].into_iter().find_map(|command| { + let output = std::process::Command::new(command).arg("-p").env("LC_ALL", "C").output().ok()?; + output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned()) + }) +} + +/// Does an `ldconfig -p` listing have `soname` for this build's architecture? Lines look like +/// `\tlibXi.so.6 (libc6,x86-64) => /lib/x86_64-linux-gnu/libXi.so.6`. +fn ldconfig_has(cache: &str, soname: &str) -> bool { + let architecture = if cfg!(target_arch = "x86_64") { + Some("x86-64") + } else if cfg!(target_arch = "aarch64") { + Some("AArch64") + } else { + None + }; + + cache.lines().any(|line| { + let Some((name, rest)) = line.trim_start().split_once(' ') else { return false }; + let flags = rest.split_once('(').and_then(|(_, after)| after.split_once(')')).map_or("", |(flags, _)| flags); + name == soname && architecture.is_none_or(|tag| flags.split(',').any(|flag| flag.trim() == tag)) + }) +} + +/// `LD_LIBRARY_PATH`, then the usual system and Flatpak library directories +fn library_dirs(ld_library_path: Option<&str>) -> Vec { + let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else { "x86_64-linux-gnu" }; + let mut dirs: Vec = ld_library_path.into_iter().flat_map(|value| value.split(':')).filter(|dir| !dir.is_empty()).map(PathBuf::from).collect(); + dirs.extend(["/app/lib", "/usr/local/lib", "/usr/lib64", "/lib64", "/usr/lib", "/lib"].map(PathBuf::from)); + dirs.extend([Path::new("/usr/lib").join(triplet), Path::new("/lib").join(triplet)]); + dirs +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A touchpad (`BTN_TOOL_FINGER`, no pen) and a Wacom pen, from `/proc/bus/input/devices` + const TOUCHPAD: &str = "N: Name=\"SYNA2B33:00 06CB:CE26 Touchpad\"\nB: KEY=e520 10000 0 0 0 0\nB: ABS=2e0800000000003\n"; + const PEN: &str = "N: Name=\"Wacom Intuos Pro M Pen\"\nB: KEY=1c03 0 0 0 0 0\nB: ABS=1000f000003\n"; + + /// A uinput keyboard (RustDesk's) claims every key, `BTN_TOOL_PEN` included, with no axes + const VIRTUAL_KEYBOARD: &str = "N: Name=\"RustDesk UInput Keyboard\"\nB: EV=20013\nB: KEY=ffffffffff 0 7ffffff000301ff 1000f7fffffff 7fe001fffff000f 7ffffffffffffff ffffffff0003fdff 7fff8fff00ff03ff 1ffffffffffff07 ffffffffffffffff ffffffffffefffff fffffffffffffffe\n"; + + #[test] + fn a_pen_is_a_device_with_the_pen_key_and_absolute_axes() { + assert!(has_pen(&format!("{TOUCHPAD}\n{PEN}"))); + assert!(!has_pen(TOUCHPAD), "a touchpad is no pen"); + assert!(!has_pen(&format!("{VIRTUAL_KEYBOARD}\n{TOUCHPAD}")), "a keyboard claiming the pen key has no pen axes"); + assert!(!has_pen("B: KEY=zz 0 0 0 0 0\nB: ABS=3\n"), "a malformed bitmap is no pen"); + } + + #[test] + fn a_pen_on_wayland_opens_the_window_through_xwayland() { + fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string()) + } + const WAYLAND: &[(&str, &str)] = &[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]; + + assert!(pen_needs_xwayland(env(WAYLAND), || true, || true)); + assert!(!pen_needs_xwayland(env(WAYLAND), || false, || true), "no pen"); + assert!(!pen_needs_xwayland(env(WAYLAND), || true, || false), "no X11 libraries"); + assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, || true), "no Xwayland"); + assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, || true), "kept"); + assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, || true)); + assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), || panic!("probed off Wayland")), "X11 already has the pen"); + } +} diff --git a/docs/features.md b/docs/features.md index 42ea07a6..e08582dc 100644 --- a/docs/features.md +++ b/docs/features.md @@ -255,6 +255,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same strip, and Settings › General › Appearance › System title bar for the system's frame instead. +- **A pen on a Linux Wayland desktop** opens the window through Xwayland, where the pen moves the + cursor and paints (some compositors send a pen nothing in a native Wayland window); + `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland. - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar. From fbff8906f4a1f3ea442304138998e780712dbd3b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 18:40:24 +0100 Subject: [PATCH 28/80] Resources Updater: row ids follow the resource name, so the keyboard focus stays with its row --- crates/ui-egui/src/resources_updater.rs | 5 +++- crates/ui-egui/tests/it/resources_updater.rs | 24 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 95840c26..21cf648b 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -254,7 +254,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(tr("No resources match the filters")); } for (index, row) in visible.into_iter().enumerate() { - if let Some(asked) = row_ui(app, ui, &tokens, index + 1, row) { + // Ids from the name alone, so the keyboard focus stays with its resource when a check reorders the rows + let row_scope = egui::UiBuilder::new().scope_id(ui.scope_id().with(("resources_updater_row", &row.name))); + let asked = ui.scope_builder(row_scope, |ui| row_ui(app, ui, &tokens, index + 1, row)).inner; + if let Some(asked) = asked { request = Some(asked); } } diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 980102a9..20609aec 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -186,3 +186,27 @@ fn a_file_changed_while_the_window_stays_open_shows_without_refresh() { assert!(shows(&h, "(1 resources, 1 outdated)"), "no document change, no focus change and no Refresh"); } + +#[test] +fn the_keyboard_focus_stays_with_its_resource_when_the_rows_reorder() { + /// Steps of the harness's quarter second: over the window's half-second check + const FRAMES: usize = 4; + const SELECT_LATER: &str = "Select new resource zz_later.png"; + + let dir = TempDir::new("resources-updater-focus"); + let (earlier, later) = (png(&dir, "aa_earlier.png", 4), png(&dir, "zz_later.png", 4)); + let mut h = app(); + import(&mut h, &earlier); + import(&mut h, &later); + activate(&mut h, "Resources Updater"); + h.get_by_role_and_label(Role::Button, SELECT_LATER).focus(); + h.run_steps(2); + + // The changed file moves to the top of the list + png(&dir, "zz_later.png", 8); + h.run_steps(FRAMES); + + let rows = &h.state().ui.windows.resources_updater.as_ref().unwrap().rows; + assert_eq!(rows[0].name, "zz_later.png", "the outdated resource moved up"); + assert!(h.get_by_role_and_label(Role::Button, SELECT_LATER).accesskit_node().is_focused(), "the focus moved with it"); +} From 8700efc30c2d1e6b50b16d5e007ad55ba26b46b0 Mon Sep 17 00:00:00 2001 From: ATOM Date: Wed, 25 Nov 2026 22:45:46 -0600 Subject: [PATCH 29/80] feat(mesh): make normal recomputation a real export option --- crates/automation/src/headless.rs | 4 +- crates/automation/src/rpc.rs | 4 +- crates/automation/src/server.rs | 3 + crates/engine/src/file_cmds.rs | 87 ++++++++++++++++++++--- crates/ui-egui/src/mesh_export_options.rs | 19 +++-- crates/ui-egui/src/state.rs | 13 ++++ crates/ui-egui/src/web_files.rs | 6 +- crates/ui-egui/src/windows.rs | 3 +- crates/ui-egui/tests/it/side_panels.rs | 25 +++++++ docs/control-protocol.md | 4 +- 10 files changed, 144 insertions(+), 24 deletions(-) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 6f86119e..94e4924f 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -225,9 +225,9 @@ impl Headless { /// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the /// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it. - pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result { + pub fn export_mesh(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { self.require_project()?; - let out = self.session.mesh_export(path, format)?; + let out = self.session.mesh_export_with_normals(path, format, recompute_normals)?; let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or("."); self.create_dir_all(dir)?; let mut textures = Vec::new(); diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index d159bc80..b0a21e77 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -5,7 +5,7 @@ //! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`, //! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`, //! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?, -//! preserveStrokes?}`, `mesh.export {path, format?}`, `bake.mesh.add {path, cage?}`, +//! `preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`, `bake.mesh.add {path, cage?}`, //! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}` //! (workspace-scoped versions of the engine commands), //! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the @@ -94,7 +94,7 @@ impl Headless { "project.save" => self.save(str_of(p, "path")), "mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")), "mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?), - "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")), + "mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format"), bool_of(p, "recomputeNormals")?), "bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?), "resource.import" => self.import_resource(required(p, "path")?), "material.save" => self.material_save(p), diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0ce54f55..f870ad9a 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -141,6 +141,9 @@ pub struct MeshExportParams { /// written next to it) or usdz (textures packaged); default: from the extension, else obj. #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, + /// Replace stored normals with smooth area-weighted normals on the exported copy (default false). + #[serde(default, rename = "recomputeNormals", skip_serializing_if = "Option::is_none")] + pub recompute_normals: Option, } #[derive(Debug, Deserialize, Serialize, JsonSchema)] diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 28595a1f..e827ef0e 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -69,7 +69,7 @@ pub fn specs() -> Vec { "Export Mesh...", ["File"], None, - "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", + "{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj), recomputeNormals?: bool (default false: smooth area-weighted normals replace the stored normals on the exported copy only); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}", always, export_mesh ), @@ -115,15 +115,32 @@ fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Op impl Session { /// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included). pub fn mesh_obj_bytes(&self) -> Result> { - texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe) + self.mesh_obj_bytes_with_normals(false) + } + + /// [`Session::mesh_obj_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result> { + let mut mesh = self.source_mesh(); + if recompute_normals { + mesh.compute_normals(); + } + texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe) } /// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like /// [`Session::mesh_usd`]'s), to write next to it, named after `stem` (the OBJ file's). pub fn mesh_obj_with_mtl(&mut self, stem: &str) -> Result<(Vec, texturecraft_formats::NamedFiles)> { + self.mesh_obj_with_mtl_and_normals(stem, false) + } + + /// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only. + pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec, texturecraft_formats::NamedFiles)> { // shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is // one image); their tiles export through Export textures with `$udim` names. let mut mesh = self.source_mesh(); + if recompute_normals { + mesh.compute_normals(); + } // A mesh without materials has one implicit material (and texture set). if mesh.materials.is_empty() { mesh.materials.push("default".into()); @@ -136,16 +153,34 @@ impl Session { /// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a /// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space. pub fn mesh_glb_bytes(&mut self) -> Result> { + self.mesh_glb_bytes_with_normals(false) + } + + /// [`Session::mesh_glb_bytes`], optionally replacing normals on the exported copy only. + pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result> { let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?; let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect(); - texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe) + let mut mesh = self.mesh.as_ref().clone(); + if recompute_normals { + mesh.compute_normals(); + } + texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe) } /// The working mesh as USD with a UsdPreviewSurface per material (textures like /// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside. pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result { + self.mesh_usd_with_normals(format, false) + } + + /// [`Session::mesh_usd`], optionally replacing normals on the exported copy only. + pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result { let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?; - texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe) + let mut mesh = self.mesh.as_ref().clone(); + if recompute_normals { + mesh.compute_normals(); + } + texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe) } /// The texture sets of the first `materials` materials rendered with `opts` (as a tile atlas @@ -1159,7 +1194,7 @@ fn write_materialx( #[cfg(not(target_arch = "wasm32"))] fn export_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.exportMesh")?; - let out = s.mesh_export(path, strp(p, "format"))?; + let out = s.mesh_export_with_normals(path, strp(p, "format"), crate::commands::boolp(p, "recomputeNormals").unwrap_or(false))?; let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new("")); let texture_paths: Vec = out.textures.iter().map(|(name, _)| dir.join(name)).collect(); let main_path = std::path::PathBuf::from(&out.path); @@ -1196,6 +1231,12 @@ impl Session { /// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default: /// from the extension, else OBJ). The extension is appended when it doesn't match. pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result { + self.mesh_export_with_normals(path, format, false) + } + + /// [`Session::mesh_export`], optionally computing smooth area-weighted normals on the + /// exported copy. The project's source and render meshes are never changed. + pub fn mesh_export_with_normals(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result { let ext = match format { Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(), Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))), @@ -1204,12 +1245,12 @@ impl Session { }; let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") }; let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) { - ("glb", _) => (self.mesh_glb_bytes()?, Vec::new()), + ("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()), (_, Some(format)) => { - let usd = self.mesh_usd(format)?; + let usd = self.mesh_usd_with_normals(format, recompute_normals)?; (usd.bytes, usd.textures) } - _ => self.mesh_obj_with_mtl(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"))?, + _ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?, }; Ok(MeshExport { path, bytes, textures }) } @@ -1402,6 +1443,36 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn mesh_export_can_recompute_normals_without_changing_the_project() { + let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y); + std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y); + let mut expected = s.source_mesh(); + expected.compute_normals(); + let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] { + let path = dir.join(format!("cube-{format}.{suffix}")); + let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap(); + let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap(); + let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh; + assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex"); + for (actual, wanted) in back.normals.iter().zip(&expected.normals) { + assert!((*actual - *wanted).length() < 1e-4, "{format}: stored normals were exported instead of recomputed ones"); + } + } + assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged"); + assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged"); + let stored_path = dir.join("stored.obj"); + let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap(); + let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap(); + let stored = texturecraft_formats::import_mesh_bytes("stored.obj", &stored).unwrap().mesh; + assert!(stored.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the default keeps stored normals for compatibility"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() { let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 8458db61..822962b3 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -31,6 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut export, mut cancel) = (false, false); + let mut triangulated = true; crate::windows::dialog(ctx, "mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { ui.set_width(DIALOG_WIDTH); @@ -38,7 +39,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); option( ui, - true, + &mut triangulated, + false, tr("Apply triangulation"), &[ tr("Splits every face with more than three corners into triangles; triangles stay as they are."), @@ -49,11 +51,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); option( ui, + &mut app.ui.mesh_recompute_normals, true, tr("Recompute vertex normals"), &[ 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."), + tr("On: smooth area-weighted normals from the exported geometry. Off: the project's stored normals. The project itself is not changed."), ], ); ui.add_space(8.0); @@ -76,12 +79,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// 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]) { +/// An option under a choice, greyed when `enabled` is false, with an info icon at the row's right +/// end whose tooltip has the paragraphs `info`. +fn option(ui: &mut Ui, checked: &mut bool, enabled: bool, label: &str, info: &[&str]) { ui.horizontal(|ui| { ui.add_space(OPTION_INDENT); - unavailable::checkbox(ui, checked, label); + if enabled { + ui.checkbox(checked, label); + } else { + 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| { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index dd814ef7..fe313410 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -566,6 +566,9 @@ pub struct UiState { /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, + /// Mesh Export Options: compute smooth normals on the exported copy, not the project. + #[serde(default = "default_true")] + pub mesh_recompute_normals: bool, pub uv_zoom: f32, pub uv_pan: [f32; 2], /// The 2D view's turn, counter-clockwise on screen in radians (Alt+left drag) @@ -770,6 +773,7 @@ impl Default for UiState { selected_baked_map: None, hide_ui: false, windows: Windows::default(), + mesh_recompute_normals: true, uv_zoom: 1.0, uv_pan: [0.0, 0.0], uv_rotation: 0.0, @@ -851,6 +855,15 @@ mod tests { assert_eq!(crate::start_ui(None, &mut session).prefs.language, crate::i18n::SYSTEM_LANGUAGE); } + #[test] + fn mesh_export_normal_choice_defaults_on_for_older_saved_states() { + assert!(UiState::default().mesh_recompute_normals); + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + saved.as_object_mut().unwrap().remove("mesh_recompute_normals"); + let loaded: UiState = serde_json::from_value(saved).unwrap(); + assert!(loaded.mesh_recompute_normals, "older states keep the dialog's checked default"); + } + #[test] fn adopting_a_layout_keeps_recent_files_export_settings_and_shortcuts() { let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() }; diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 5687f5db..89c86600 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -337,9 +337,9 @@ mod web { pub fn export_mesh(app: &mut TextureCraftApp, ext: &str) { let name = format!("{}.{ext}", sanitize_file_stem(&app.session.doc.project.name)); let bytes = match ext { - "glb" => app.session.mesh_glb_bytes(), - "usdz" => app.session.mesh_usd(texturecraft_engine::formats::UsdFormat::Usdz).map(|u| u.bytes), - _ => app.session.mesh_obj_bytes(), + "glb" => app.session.mesh_glb_bytes_with_normals(app.ui.mesh_recompute_normals), + "usdz" => app.session.mesh_usd_with_normals(texturecraft_engine::formats::UsdFormat::Usdz, app.ui.mesh_recompute_normals).map(|u| u.bytes), + _ => app.session.mesh_obj_bytes_with_normals(app.ui.mesh_recompute_normals), }; match bytes.map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) { Ok(()) => app.toast(trf("Downloaded {name}", &[("name", &name)]), false), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index a172926a..1ea09b80 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -609,7 +609,8 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> .file_name(name); app.ask_file(dialog, Bound::Project, |app, paths| { if let Some(path) = paths.first() - && let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()})) + && let Some(result) = + app.run("file.exportMesh", json!({"path": path.display().to_string(), "recomputeNormals": app.ui.mesh_recompute_normals})) { let saved_path = result["path"].as_str().unwrap_or_default(); app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false); diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index aab7c36d..f3a31394 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -174,6 +174,31 @@ fn export_mesh_asks_the_options_then_the_file() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn recompute_normals_is_an_enabled_keyboard_operable_checkbox() { + let mut harness = app(); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "file.exportMesh"); + harness.run_steps(SETTLE_FRAMES); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); + assert!(!checkbox.accesskit_node().is_disabled(), "the option is really available"); + assert!(is_on(&checkbox), "it starts checked, as the dialog always showed it"); + assert!(harness.state().ui.mesh_recompute_normals); + + checkbox.focus(); + harness.key_press(egui::Key::Space); + harness.run_steps(SETTLE_FRAMES); + assert!(!harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export"); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); + assert!(!is_on(&checkbox), "the accessibility tree reports the unchecked state"); + assert_eq!(checkbox.accesskit_node().label().as_deref(), Some("Recompute vertex normals")); + + checkbox.click(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.mesh_recompute_normals, "a pointer click turns it back on"); + assert!(is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"))); +} + /// Whether the Log lists `line` (the status bar under it repeats the last message) fn log_lists(harness: &Harness<'_, TextureCraftApp>, line: &str) -> bool { harness.query_all_by_label(line).any(|node| node.rect().bottom() < STATUS_BAR_TOP) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 71c95e6f..e3179022 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -382,7 +382,7 @@ With `rebuildUvs: true`, the project file saves the generated layout. Reopening | `project_save` | `{path?}` | `.tcraft` (appended if missing), relative to the write root | | `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl; a .gltf's buffers and images and a loose USD layer's textures are read from its folder | | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | -| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | +| `mesh_export` | `{path, format?, recomputeNormals?}` | The mesh as obj, glb, usda, usdc or usdz below the write root; `recomputeNormals: true` writes smooth area-weighted normals on the exported copy (default false) (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | | `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | @@ -457,7 +457,7 @@ File access follows `--read-root` / `--write-root` as for MCP. | `project.save` | `{path?}` | | `mesh.import` | `{path, resolution?, name?}` | | `mesh.reimport` | `{path?, preserveStrokes?}` | -| `mesh.export` | `{path, format?}` | +| `mesh.export` | `{path, format?, recomputeNormals?}` | | `bake.mesh.add` | `{path, cage?}` | | `resource.import` | `{path}` | | `material.save` | `{path, layer?, name?}` | From 23d3f9ae71380b60b33ee97e232c19646357472c Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 00:27:10 -0500 Subject: [PATCH 30/80] Autosave: give each project its own copy The copy was named after the project, whose name comes from the mesh file, so projects made from one mesh overwrote each other's autosave. It is now `-.tcraft`: from the saved file and its path, or a suffix of its own while the project is unsaved. A project opened from its copy keeps writing to it. Fixes #851 --- crates/ui-egui/src/autosave_name.rs | 156 +++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 13 ++- crates/ui-egui/tests/autosave_files.rs | 65 +++++++++++ docs/features.md | 3 + 4 files changed, 232 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/autosave_name.rs create mode 100644 crates/ui-egui/tests/autosave_files.rs diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs new file mode 100644 index 00000000..477b17d8 --- /dev/null +++ b/crates/ui-egui/src/autosave_name.rs @@ -0,0 +1,156 @@ +//! Where a project's autosave copy goes. Each project has a file of its own, `-.tcraft`: a project's +//! name comes from its mesh file, so the name alone would let projects made from one mesh overwrite each other's copy + +use std::path::{Path, PathBuf}; + +use texturecraft_engine::core::PROJECT_EXT; +use texturecraft_engine::formats::export::sanitize_file_stem; + +use crate::TextureCraftApp; + +/// Hex digits of a copy's suffix +const SUFFIX_DIGITS: usize = 8; + +/// The longest stem kept, so the suffix and the temporary files of a save still fit a file name +const MAX_STEM_CHARS: usize = 180; + +impl TextureCraftApp { + /// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the + /// same across restarts; an unsaved project gets one that no other open project or running instance shares + pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf { + let Some(saved) = self.session.path.as_deref() else { + let project = self.session.project_id; + let suffix = match self.unsaved_autosave_suffix { + Some((owner, suffix)) if owner == project => suffix, + _ => { + let suffix = new_suffix(project); + self.unsaved_autosave_suffix = Some((project, suffix)); + suffix + } + }; + return folder.join(file_name(&self.session.doc.project.name, suffix)); + }; + + let saved = absolute(Path::new(saved)); + + // A project opened from its autosave copy keeps writing there, rather than chaining suffixes + if is_copy_in(&saved, &absolute(folder)) { + return saved; + } + + let stem = saved.file_stem().map_or_else(|| self.session.doc.project.name.clone(), |stem| stem.to_string_lossy().into_owned()); + folder.join(file_name(&stem, hash(saved.as_os_str().as_encoded_bytes()))) + } +} + +fn file_name(stem: &str, suffix: u32) -> String { + let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect(); + format!("{stem}-{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}") +} + +/// `path` made absolute, as given when that fails +fn absolute(path: &Path) -> PathBuf { + std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()) +} + +/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in a suffix +fn is_copy_in(path: &Path, folder: &Path) -> bool { + let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once('-')).map(|(_, suffix)| suffix); + path.parent() == Some(folder) + && path.extension().is_some_and(|extension| extension == PROJECT_EXT) + && suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit())) +} + +/// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run +/// takes a different one +fn new_suffix(project: u64) -> u32 { + let now = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(); + let mut seed = Vec::new(); + seed.extend_from_slice(&std::process::id().to_le_bytes()); + seed.extend_from_slice(&now.to_le_bytes()); + seed.extend_from_slice(&project.to_le_bytes()); + hash(&seed) +} + +/// 32-bit FNV-1a: the same bytes give the same suffix in every release, which the standard hasher does not promise +fn hash(bytes: &[u8]) -> u32 { + bytes.iter().fold(0x811c_9dc5, |hash, byte| (hash ^ u32::from(*byte)).wrapping_mul(0x0100_0193)) +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives; + + use super::*; + + fn project(name: &str) -> Session { + Session::new_project(name, primitives::cube(1.0), "builtin:cube", None, 128).unwrap() + } + + fn app(session: Session) -> TextureCraftApp { + TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session) + } + + fn name_of(path: &Path) -> &str { + path.file_name().and_then(|name| name.to_str()).unwrap() + } + + #[test] + fn unsaved_projects_with_one_name_get_different_copies_that_stay_put() { + let folder = Path::new("autosave"); + let mut first = app(project("hero")); + let mut second = app(project("hero")); + + let (one, other) = (first.autosave_path(folder), second.autosave_path(folder)); + + assert_ne!(one, other, "another instance never writes the same file"); + assert!(name_of(&one).starts_with("hero-") && name_of(&one).ends_with(".tcraft"), "{one:?}"); + assert_eq!(one.parent(), Some(folder)); + assert_eq!(first.autosave_path(folder), one, "the next autosave replaces this project's copy"); + + first.session.switch_to(project("hero")); + assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy"); + } + + #[test] + fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() { + let folder = Path::new("autosave"); + let copy_of = |saved: &str| { + let mut app = app(project("hero")); + app.session.path = Some(saved.to_string()); + app.autosave_path(folder) + }; + + let first = copy_of("work/Hero_v1.tcraft"); + let second = copy_of("work/Hero_v2.tcraft"); + let same_name_elsewhere = copy_of("backup/Hero_v1.tcraft"); + + assert!(name_of(&first).starts_with("Hero_v1-"), "{first:?}"); + assert_ne!(first, second); + assert_ne!(first, same_name_elsewhere, "files of one name in two folders keep two copies"); + assert_eq!(copy_of("work/Hero_v1.tcraft"), first, "a later run finds the same copy"); + } + + #[test] + fn a_project_opened_from_its_copy_keeps_writing_to_it() { + let folder = std::env::temp_dir().join("tc-autosave"); + let mut app = app(project("hero")); + let copy = app.autosave_path(&folder); + + app.session.path = Some(copy.display().to_string()); + assert_eq!(app.autosave_path(&folder), copy); + + // A file there that is not a copy is the user's own: autosave leaves it alone + let own = folder.join("hero.tcraft"); + app.session.path = Some(own.display().to_string()); + assert_ne!(app.autosave_path(&folder), own); + } + + #[test] + fn suffixes_have_a_fixed_width_and_long_names_are_cut() { + assert_eq!(file_name("hero", 0x2a), "hero-0000002a.tcraft"); + assert_eq!(hash(b"hero"), hash(b"hero")); + assert!(file_name(&"a".repeat(500), 1).len() < 200); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ed85f4fc..15b2e84c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,8 @@ mod anchor_properties; mod angle_dial; mod ask; +#[cfg(not(target_arch = "wasm32"))] +mod autosave_name; mod bake_job; pub mod bake_mode; mod bake_preset; @@ -344,6 +346,9 @@ pub struct TextureCraftApp { /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, + /// The unsaved project (its id) and the suffix of its autosave copy. + #[cfg(not(target_arch = "wasm32"))] + unsaved_autosave_suffix: Option<(u64, u32)>, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. @@ -475,6 +480,8 @@ impl TextureCraftApp { title_bar: titlebar::TitleBar::default(), last_time: 0.0, next_autosave, + #[cfg(not(target_arch = "wasm32"))] + unsaved_autosave_suffix: None, styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] @@ -1034,11 +1041,7 @@ impl TextureCraftApp { self.next_autosave = now + period; let dir = user_dir("autosave"); - let path = dir.join(format!( - "{}.{}", - texturecraft_engine::formats::export::sanitize_file_stem(&self.session.doc.project.name), - texturecraft_engine::core::PROJECT_EXT - )); + let path = self.autosave_path(&dir); let snapshot = self.session.project_snapshot(); let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || { let result = diff --git a/crates/ui-egui/tests/autosave_files.rs b/crates/ui-egui/tests/autosave_files.rs new file mode 100644 index 00000000..01211191 --- /dev/null +++ b/crates/ui-egui/tests/autosave_files.rs @@ -0,0 +1,65 @@ +//! The desktop autosave writes each project's copy to a file of its own. This is a test binary of its own because it +//! points the process's data folder at a temporary one + +#![cfg(not(target_arch = "wasm32"))] + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// App time each frame advances by, so a few frames pass any autosave interval +const FRAME_SECONDS: f32 = 600.0; + +/// How long the worker thread gets to write a copy +const WRITE_TIMEOUT: Duration = Duration::from_secs(60); + +/// A project named as one made from `hero.fbx` would be, with `layers` paint layers added since it was saved +fn unsaved_hero(layers: usize) -> Session { + let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + for _ in 0..layers { + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + } + session +} + +fn copies(folder: &Path) -> Vec { + let files = std::fs::read_dir(folder).map(|entries| entries.flatten().map(|entry| entry.path()).collect::>()).unwrap_or_default(); + files.into_iter().filter(|path| path.extension().is_some_and(|extension| extension == "tcraft")).collect() +} + +/// Runs an app on `session` until the autosave folder holds `count` copies +fn autosave(session: Session, folder: &Path, count: usize) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let started = Instant::now(); + while copies(folder).len() < count { + harness.step(); + assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote {:?}", copies(folder)); + std::thread::sleep(Duration::from_millis(20)); + } + harness +} + +#[test] +fn two_projects_of_one_name_keep_two_autosave_copies() { + let data = std::env::temp_dir().join(format!("tc-autosave-files-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&data); + texturecraft_ui_egui::set_data_root(data.clone()); + let folder = data.join("autosave"); + + let first = autosave(unsaved_hero(1), &folder, 1); + let second = autosave(unsaved_hero(2), &folder, 2); + drop((first, second)); + + // Each copy opens as the project that wrote it + let mut layers: Vec = + copies(&folder).iter().map(|path| texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap().doc.project.layers.len()).collect(); + layers.sort_unstable(); + assert_eq!(layers[1], layers[0] + 1, "{layers:?}"); + + std::fs::remove_dir_all(&data).unwrap(); +} diff --git a/docs/features.md b/docs/features.md index 520ff678..38ff4a65 100644 --- a/docs/features.md +++ b/docs/features.md @@ -278,6 +278,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA New project, Open, Recent projects, Open sample project); File › Close returns to that state. - A **data folder** of your choice for autosaves, smart materials, presets, templates and UI layouts, on any drive (Settings › General › Folders; `Documents/TextureCraft` by default). +- **Autosave**: each project keeps its own copy in the data folder's `autosave`, named + `-.tcraft` after its saved file (or, until it is saved, the project), so projects made from + one mesh never overwrite each other's copy. - A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits From 14deaa61de145f560de5a36642b9e13676ed5f5b Mon Sep 17 00:00:00 2001 From: ATOM Date: Wed, 25 Nov 2026 23:34:31 -0600 Subject: [PATCH 31/80] fix(ui): preserve normal export choice across layouts --- crates/ui-egui/src/state.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index fe313410..24c5f7a4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -735,6 +735,7 @@ impl UiState { } self.export = keep.export; + self.mesh_recompute_normals = keep.mesh_recompute_normals; self.recent = keep.recent; self.last_template = keep.last_template; self.prefs = keep.prefs; @@ -869,7 +870,9 @@ mod tests { let mut ui = UiState { recent: vec!["a.tcraft".into()], ..UiState::default() }; ui.export.preset = "Mine".into(); ui.keymap.insert("file.save".into(), "F5".into()); + ui.mesh_recompute_normals = false; let mut layout = UiState::default(); + assert!(layout.mesh_recompute_normals); layout.dock.close(crate::docking::Panel::Assets); ui.adopt_layout(layout); @@ -878,6 +881,7 @@ mod tests { assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); assert_eq!(ui.export.preset, "Mine"); assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); + assert!(!ui.mesh_recompute_normals, "a layout does not change the user's export setting"); } #[test] From eda265b470f27a59c3058ea455b01186f271be84 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:21:04 +0000 Subject: [PATCH 32/80] Apply requested fixes - crates/ui-egui/src/autosave_name.rs - docs/features.md --- crates/ui-egui/src/autosave_name.rs | 20 ++++++++++++++------ docs/features.md | 2 +- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index 477b17d8..04df5543 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -1,4 +1,4 @@ -//! Where a project's autosave copy goes. Each project has a file of its own, `-.tcraft`: a project's +//! Where a project's autosave copy goes. Each project has a file of its own, `-copy-.tcraft`: a project's //! name comes from its mesh file, so the name alone would let projects made from one mesh overwrite each other's copy use std::path::{Path, PathBuf}; @@ -11,6 +11,9 @@ use crate::TextureCraftApp; /// Hex digits of a copy's suffix const SUFFIX_DIGITS: usize = 8; +/// Between a copy's stem and its suffix, so a user's own file named like `report-20240115` is not taken for a copy +const COPY_MARK: &str = "-copy-"; + /// The longest stem kept, so the suffix and the temporary files of a save still fit a file name const MAX_STEM_CHARS: usize = 180; @@ -45,7 +48,7 @@ impl TextureCraftApp { fn file_name(stem: &str, suffix: u32) -> String { let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect(); - format!("{stem}-{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}") + format!("{stem}{COPY_MARK}{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}") } /// `path` made absolute, as given when that fails @@ -53,9 +56,9 @@ fn absolute(path: &Path) -> PathBuf { std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()) } -/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in a suffix +/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in the copy mark and a suffix fn is_copy_in(path: &Path, folder: &Path) -> bool { - let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once('-')).map(|(_, suffix)| suffix); + let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once(COPY_MARK)).map(|(_, suffix)| suffix); path.parent() == Some(folder) && path.extension().is_some_and(|extension| extension == PROJECT_EXT) && suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit())) @@ -145,12 +148,17 @@ mod tests { let own = folder.join("hero.tcraft"); app.session.path = Some(own.display().to_string()); assert_ne!(app.autosave_path(&folder), own); + + let dated = folder.join("hero-20240115.tcraft"); + app.session.path = Some(dated.display().to_string()); + assert_ne!(app.autosave_path(&folder), dated); } #[test] fn suffixes_have_a_fixed_width_and_long_names_are_cut() { - assert_eq!(file_name("hero", 0x2a), "hero-0000002a.tcraft"); - assert_eq!(hash(b"hero"), hash(b"hero")); + let narrow = file_name("hero", 1); + let wide = file_name("hero", u32::MAX); + assert_eq!(narrow.len(), wide.len(), "every suffix has the same width"); assert!(file_name(&"a".repeat(500), 1).len() < 200); } } diff --git a/docs/features.md b/docs/features.md index 38ff4a65..8ddd6133 100644 --- a/docs/features.md +++ b/docs/features.md @@ -279,7 +279,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - A **data folder** of your choice for autosaves, smart materials, presets, templates and UI layouts, on any drive (Settings › General › Folders; `Documents/TextureCraft` by default). - **Autosave**: each project keeps its own copy in the data folder's `autosave`, named - `-.tcraft` after its saved file (or, until it is saved, the project), so projects made from + `-copy-.tcraft` after its saved file (or, until it is saved, the project), so projects made from one mesh never overwrite each other's copy. - A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's From f9d29d9ccfbfe56a2ec7f8ce6f5e77c50c6b797a Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:33:47 +0000 Subject: [PATCH 33/80] Apply review fixes - crates/ui-egui/src/autosave_name.rs --- crates/ui-egui/src/autosave_name.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index 04df5543..fa188ad8 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -15,7 +15,7 @@ const SUFFIX_DIGITS: usize = 8; const COPY_MARK: &str = "-copy-"; /// The longest stem kept, so the suffix and the temporary files of a save still fit a file name -const MAX_STEM_CHARS: usize = 180; +const MAX_STEM_CHARS: usize = 170; impl TextureCraftApp { /// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the From 3695db1d44205e74be60ea6ad9b8cbc050324271 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:50:40 +0700 Subject: [PATCH 34/80] Warp toolbar test: install the headless runtime on its harness Main's CI has failed since #837 merged: place_on_surface_keeps_a_warp_on_its_own_texture_set builds its harness without framework::install_headless, which the framework runtime needs since #800, and panics with "the runtime plugin's hooks did not run". Every other harness already installs it. --- crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs index 042f4f39..6bb7d226 100644 --- a/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs +++ b/crates/ui-egui/src/frame_gizmo/warp_toolbar/mod.rs @@ -253,7 +253,10 @@ mod tests { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mesh = texturecraft_engine::geom::primitives::material_ball(); let session = texturecraft_engine::Session::new_project("Warp placement", mesh, "builtin:material_ball", None, 128).unwrap(); - let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(vec2(1600.0, 960.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); let layer = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); harness.state_mut().run("layer.fill.projection", json!({"layer": layer, "projection": "warp"})).unwrap(); harness.run_steps(2); From 82e81e518b80530492da461067911f67dc55b1e7 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 10:09:18 -0500 Subject: [PATCH 35/80] Autosave test: install the headless runtime on its harness --- crates/ui-egui/tests/autosave_files.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/autosave_files.rs b/crates/ui-egui/tests/autosave_files.rs index 01211191..9b8b7548 100644 --- a/crates/ui-egui/tests/autosave_files.rs +++ b/crates/ui-egui/tests/autosave_files.rs @@ -34,7 +34,10 @@ fn copies(folder: &Path) -> Vec { /// Runs an app on `session` until the autosave folder holds `count` copies fn autosave(session: Session, folder: &Path, count: usize) -> Harness<'static, TextureCraftApp> { - let mut harness = Harness::builder().with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); let started = Instant::now(); while copies(folder).len() < count { harness.step(); From 1f78ba35781f40c0d10f33f778abf583bc596238 Mon Sep 17 00:00:00 2001 From: ViktorBystrov72 Date: Thu, 26 Nov 2026 20:54:16 +0500 Subject: [PATCH 36/80] Isolate TextureCraft UI language on each thread (#797) Co-authored-by: ViktorBystrov72 <18964918+ViktorBystrov72@users.noreply.github.com> --- crates/ui-egui/src/i18n.rs | 38 +++++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 235ebc5e..2210638e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,8 +1,8 @@ //! UI text lookup over the optional shared craft-i18n catalogs. //! Missing translations and builds without catalogs use the English source text. +use std::cell::Cell; use std::fmt::Display; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{LazyLock, OnceLock}; include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); @@ -52,7 +52,10 @@ pub static LANGUAGES: [Language; COUNT] = [ Language { code: "ar", name: "العربية", english: "Arabic" }, ]; -static CURRENT: AtomicUsize = AtomicUsize::new(0); +// Rendering and preferences use the UI thread, including independent test harnesses. +thread_local! { + static CURRENT: Cell = const { Cell::new(0) }; +} /// How a fill reads its images, as the Filtering combo names it pub(crate) fn filtering_label(filtering: texturecraft_engine::core::Filtering) -> &'static str { @@ -96,20 +99,20 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta /// The saved language that follows the operating system's (Settings > Language > Default (System Language)). pub const SYSTEM_LANGUAGE: &str = ""; -/// Switch the UI language ([`SYSTEM_LANGUAGE`] follows the system; unknown codes fall back to English). +/// Switch the calling UI thread's language. [`SYSTEM_LANGUAGE`] follows the system. pub fn set_language(code: &str) { let code = if code == SYSTEM_LANGUAGE { system_language() } else { code }; - CURRENT.store(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0), Ordering::Relaxed); + CURRENT.set(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0)); } /// The current UI language. pub fn current() -> &'static Language { - LANGUAGES.get(CURRENT.load(Ordering::Relaxed)).unwrap_or(&LANGUAGES[0]) + LANGUAGES.get(CURRENT.get()).unwrap_or(&LANGUAGES[0]) } /// `text` in the current language (unchanged when it has no translation). pub fn tr(text: &str) -> &str { - let lang = shared_languages().get(CURRENT.load(Ordering::Relaxed)).copied().unwrap_or(craft_i18n::Lang::EN); + let lang = shared_languages().get(CURRENT.get()).copied().unwrap_or(craft_i18n::Lang::EN); I18N.t(lang, text) } @@ -182,7 +185,7 @@ fn system_language() -> &'static str { SYSTEM.get_or_init(os_language) } -/// Tests that switch the global UI language, or draw the UI under it, run one at a time. +/// Shared guard used by language fixture tests. #[cfg(test)] pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -192,6 +195,27 @@ mod tests { use super::*; use std::collections::{BTreeSet, HashMap}; + #[test] + fn a_parallel_ui_language_context_keeps_its_own_language() { + set_language("en"); + let french = LANGUAGES.iter().position(|language| language.code == "fr").unwrap(); + let barrier = std::sync::Barrier::new(2); + let (first, second) = std::thread::scope(|scope| { + let other = scope.spawn(|| { + // Exercise the resolved language selection even when the French catalog is absent. + CURRENT.set(french); + barrier.wait(); + barrier.wait(); + current().code + }); + barrier.wait(); + let first = current().code; + barrier.wait(); + (first, other.join().unwrap()) + }); + assert_eq!((first, second), ("en", "fr")); + } + /// Every key the UI looks up: `tr("…")` / `trf("…"` literals in the sources, plus the /// static catalogs whose labels are translated where they are shown. fn keys() -> Vec { From 59860919689cb11ab061c927b9f3e66e0081e64b Mon Sep 17 00:00:00 2001 From: chasse20 Date: Thu, 26 Nov 2026 16:19:15 +0000 Subject: [PATCH 37/80] Auto: Fix close after a prior save fails and isolate UI language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Let an unmodified replacement project finish closing once the previous project’s save ends, even if the write fails. Add a regression test for that sequence. Keep each UI thread’s language selection independent and add a test that selects different languages on two concurrent threads. --- crates/ui-egui/src/manual_save.rs | 36 ++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/manual_save.rs b/crates/ui-egui/src/manual_save.rs index 843a0e01..9243482a 100644 --- a/crates/ui-egui/src/manual_save.rs +++ b/crates/ui-egui/src/manual_save.rs @@ -93,7 +93,7 @@ impl TextureCraftApp { self.saving_for_prompt = false; } - let mut quitting = false; + let save_succeeded = result.is_ok(); match result { Ok(output) => { output.apply(&mut self.session); @@ -101,17 +101,11 @@ impl TextureCraftApp { crate::windows::remember(self, &output.path); } - let clean = !self.session.modified && !self.session.stroke_active(); - quitting = quit_requested && clean; if continue_prompt { - self.prompt_saved = clean && !quitting; + self.prompt_saved = !self.session.modified && !self.session.stroke_active() && !quit_requested; } self.toast(trf("Saved {path}", &[("path", &output.path)]), false); - if quitting { - self.ui.windows.unsaved = None; - ctx.send_viewport_cmd(egui::ViewportCommand::Close); - } } Err(error) => { let message = trf("Could not save project: {error}", &[("error", &error)]); @@ -120,10 +114,13 @@ impl TextureCraftApp { } } - // An open stroke settles before the pending close checks for unsaved edits - if quit_requested && !quitting { + if quit_requested { if self.session.stroke_active() { self.quit_after_stroke = Some(self.session.project_id); + } else if !self.session.modified && (save_succeeded || !same_project) { + // A replacement project's own close only needs the previous writer to finish + self.ui.windows.unsaved = None; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); } else { crate::windows::ask_to_save(self, Unsaved::Quit); } @@ -415,6 +412,25 @@ mod tests { assert!(h.state().ui.windows.unsaved.is_none()); } + #[test] + fn closing_the_replacement_resumes_after_the_original_save_fails() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let file = temp_file("close-replacement-after-failure").with_file_name("missing").join("project.tcraft"); + let mut h = harness(); + let (task, sender) = start_held_save(&mut h, &file, true); + let replacement = texturecraft_engine::sample_session(256, 64).unwrap(); + h.state_mut().session.switch_to(replacement); + + request_close(&mut h); + assert!(!sends_close(&mut h), "the replacement waits for the original save"); + let result = task.run(None); + assert!(result.is_err(), "the original write fails"); + sender.send(result).unwrap(); + + assert!(sends_close(&mut h), "the replacement's own close resumes after the failed write"); + assert!(h.state().ui.windows.unsaved.is_none()); + } + #[test] fn canceling_a_stroke_after_a_successful_save_leaves_the_saved_edits_clean() { let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); From ac4454bb38825b72d12436d43501fe6945b4575c Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:21:07 -0600 Subject: [PATCH 38/80] Geom: check indices before computing tangents (#386) Mesh::from_parts computed normals and tangents before validate(). An index past the last vertex reads as the origin in the MikkTSpace callbacks, but the all-degenerate guard compares positions.get() and counts a missing vertex as different. So two positions with indices [0, 1, 2] passed the guard while MikkTSpace saw every triangle as degenerate and underflowed at generated.rs:1100: a panic in debug, an out-of-bounds walk in release. compute_tangents now also skips MikkTSpace (using the per-triangle fallback, which reads with get()) when an index is out of range, and from_parts refuses such indices before building the mesh, with the same error validate() gives. --- crates/geom/src/mesh.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 03d47845..e00ed374 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -315,8 +315,11 @@ impl Mesh { if self.uvs.len() != self.positions.len() { self.uvs = vec![Vec2::ZERO; self.positions.len()]; } - // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. - if crate::unwrap::all_triangles_degenerate(self) { + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. Its + // callbacks read a missing vertex as the origin, which the degenerate check cannot see, so + // an index past the last vertex skips it too. + let n = self.positions.len(); + if !self.indices.iter().all(|&i| (i as usize) < n) || crate::unwrap::all_triangles_degenerate(self) { self.simple_tangents(); } else { let faces = self.tangent_faces(); @@ -497,6 +500,9 @@ impl Mesh { /// A single-material mesh from raw attributes; computes missing normals and tangents. pub fn from_parts(positions: Vec, normals: Option>, uvs: Vec, indices: Vec, material: &str) -> Result { + if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) { + return Err(GeomError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len()))); + } let count = indices.len() as u32; let mut m = Mesh { normals: normals.unwrap_or_default(), @@ -910,4 +916,30 @@ mod tests { assert_eq!(m.uv_tiles(1).into_iter().collect::>(), vec![(1, 0)]); assert_eq!(m.uv_tiles(0).into_iter().collect::>(), vec![(0, 0)]); } + + /// An index past the last vertex reads as the origin in MikkTSpace's callbacks. With two + /// positions at the origin and one missing, the degenerate-mesh guard (which sees the missing + /// vertex as different) let it through while MikkTSpace saw every triangle as degenerate and + /// underflowed: a panic in debug builds, an out-of-bounds walk in release. + #[test] + fn from_parts_refuses_an_out_of_range_index_without_crashing() { + let positions = vec![Vec3::ZERO, Vec3::X]; + let uvs = vec![Vec2::ZERO, Vec2::X]; + let e = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2], "M").unwrap_err(); + assert!(e.to_string().contains("out of range"), "{e}"); + } + + #[test] + fn tangents_of_a_mesh_with_an_out_of_range_index_fall_back_without_crashing() { + for indices in [vec![0, 1, 2], vec![0, 0, 2], vec![0, 1, 5, 0, 1, 1]] { + let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::ZERO, Vec2::X, Vec2::Y], vec![0, 1, 2], "M").unwrap(); + m.positions.truncate(2); + m.normals.truncate(2); + m.uvs.truncate(2); + m.indices = indices; + m.compute_tangents(); + assert_eq!(m.tangents.len(), 2); + assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents); + } + } } From 0fbfec1c3d732dc9ba18c9f55f8bc7cd5dc6a7a9 Mon Sep 17 00:00:00 2001 From: ATOM Date: Thu, 26 Nov 2026 10:36:05 -0600 Subject: [PATCH 39/80] fix(mesh): weld recomputed normals and make export opt-in --- crates/automation/src/rpc.rs | 5 +-- crates/engine/src/file_cmds.rs | 44 +++++++++++++++++++---- crates/formats/src/mesh_import/mod.rs | 21 ++--------- crates/geom/src/mesh.rs | 21 +++++++++++ crates/ui-egui/src/mesh_export_options.rs | 4 +-- crates/ui-egui/src/state.rs | 13 +++---- crates/ui-egui/tests/it/side_panels.rs | 12 +++---- 7 files changed, 78 insertions(+), 42 deletions(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index b0a21e77..aefb4919 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -4,8 +4,9 @@ //! //! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`, //! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`, -//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?, -//! `preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`, `bake.mesh.add {path, cage?}`, +//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, +//! `mesh.reimport {path?, preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`, +//! `bake.mesh.add {path, cage?}`, //! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}` //! (workspace-scoped versions of the engine commands), //! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index e827ef0e..553f6ffa 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -122,7 +122,7 @@ impl Session { pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result> { let mut mesh = self.source_mesh(); if recompute_normals { - mesh.compute_normals(); + mesh.compute_smooth_normals(); } texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe) } @@ -139,7 +139,7 @@ impl Session { // one image); their tiles export through Export textures with `$udim` names. let mut mesh = self.source_mesh(); if recompute_normals { - mesh.compute_normals(); + mesh.compute_smooth_normals(); } // A mesh without materials has one implicit material (and texture set). if mesh.materials.is_empty() { @@ -162,7 +162,7 @@ impl Session { let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect(); let mut mesh = self.mesh.as_ref().clone(); if recompute_normals { - mesh.compute_normals(); + mesh.compute_smooth_normals(); } texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe) } @@ -178,7 +178,7 @@ impl Session { let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?; let mut mesh = self.mesh.as_ref().clone(); if recompute_normals { - mesh.compute_normals(); + mesh.compute_smooth_normals(); } texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe) } @@ -1449,7 +1449,7 @@ f 1/1 2/2 3/3 std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y); std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y); let mut expected = s.source_mesh(); - expected.compute_normals(); + expected.compute_smooth_normals(); let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); @@ -1459,8 +1459,14 @@ f 1/1 2/2 3/3 let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap(); let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh; assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex"); - for (actual, wanted) in back.normals.iter().zip(&expected.normals) { - assert!((*actual - *wanted).length() < 1e-4, "{format}: stored normals were exported instead of recomputed ones"); + for (position, actual) in back.positions.iter().zip(&back.normals) { + let wanted = expected + .positions + .iter() + .zip(&expected.normals) + .find_map(|(expected_position, normal)| ((*expected_position - *position).length() < 1e-4).then_some(*normal)) + .unwrap_or_else(|| panic!("{format}: exported position {position:?} is missing from the source")); + assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}"); } } assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged"); @@ -1473,6 +1479,30 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn recomputed_normals_weld_uv_seams_in_exported_mesh() { + use texturecraft_geom::glam::Vec3; + + // Two triangles meet along 0--2, but their UV island split duplicates that edge as 3--4. + let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)]; + let mesh = Mesh::from_parts( + positions, + Some(vec![Vec3::Y; 6]), + vec![Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.5), Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.5, 1.0)], + vec![0, 1, 2, 3, 4, 5], + "Default", + ) + .unwrap(); + let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap(); + let bytes = s.mesh_glb_bytes_with_normals(true).unwrap(); + let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh; + for point in [Vec3::ZERO, Vec3::Y] { + let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect(); + assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices"); + assert!(normals.windows(2).all(|pair| (pair[0] - pair[1]).length() < 1e-5), "{point:?}: UV split normals disagree: {normals:?}"); + } + } + #[test] fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() { let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 6450878b..5e0d2468 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -25,7 +25,7 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4}; -use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids}; +use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap}; use texturecraft_geom::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh, UvGBuffer}; use crate::{FormatError, Result}; @@ -508,7 +508,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { mesh.normals = match normals { Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(), - _ => smooth_normals(&mesh), + _ => mesh.smooth_normals(), }; if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) { mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect(); @@ -641,23 +641,6 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { - let welded_vertices = weld_ids(&mesh.positions); - let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; - for triangle in mesh.indices.as_chunks::<3>().0 { - let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default(); - let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); - for v in triangle { - if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) { - *a += face; - } - } - } - - welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() -} - /// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings). pub fn mesh_report(mesh: &Mesh) -> MeshReport { report(mesh, false, Vec::new()) diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 03d47845..3bae99f4 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -245,6 +245,27 @@ impl Mesh { self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } + /// Area-weighted smooth normals over welded positions, so UV and material seams do not split shading. + pub fn smooth_normals(&self) -> Vec { + let welded_vertices = crate::unwrap::weld_ids(&self.positions); + let mut normals = vec![Vec3::ZERO; self.positions.len()]; + for triangle in self.indices.as_chunks::<3>().0 { + let p = |i: u32| self.positions.get(i as usize).copied().unwrap_or_default(); + let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); + for v in triangle { + if let Some(accumulated) = welded_vertices.get(*v as usize).and_then(|welded| normals.get_mut(*welded as usize)) { + *accumulated += face; + } + } + } + welded_vertices.iter().map(|welded| normals.get(*welded as usize).and_then(|normal| normal.try_normalize()).unwrap_or(Vec3::Y)).collect() + } + + /// Replace normals with [`Mesh::smooth_normals`] on this mesh. + pub fn compute_smooth_normals(&mut self) { + self.normals = self.smooth_normals(); + } + /// The faces MikkTSpace sees: each importer quad (a fan pair marked in [`Mesh::diagonals`]) /// as one four-corner face, like Blender hands it over, and every other triangle as a /// triangle. Polygons with more than four corners stay fan triangles. The vertex and index diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 822962b3..7d5cb5c2 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -47,8 +47,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."), ], ); - ui.add_space(GROUP_GAP); - unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); option( ui, &mut app.ui.mesh_recompute_normals, @@ -59,6 +57,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { tr("On: smooth area-weighted normals from the exported geometry. Off: the project's stored normals. The project itself is not changed."), ], ); + ui.add_space(GROUP_GAP); + unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); ui.add_space(8.0); // One row keeps the window to its contents; a bare right-to-left layout fills the screen height diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c1fe25e5..1f447556 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -567,7 +567,8 @@ pub struct UiState { pub hide_ui: bool, pub windows: Windows, /// Mesh Export Options: compute smooth normals on the exported copy, not the project. - #[serde(default = "default_true")] + /// Off by default so an export keeps the project's authored normals unless the user opts in. + #[serde(default)] pub mesh_recompute_normals: bool, pub uv_zoom: f32, pub uv_pan: [f32; 2], @@ -778,7 +779,7 @@ impl Default for UiState { selected_baked_map: None, hide_ui: false, windows: Windows::default(), - mesh_recompute_normals: true, + mesh_recompute_normals: false, uv_zoom: 1.0, uv_pan: [0.0, 0.0], uv_rotation: 0.0, @@ -862,12 +863,12 @@ mod tests { } #[test] - fn mesh_export_normal_choice_defaults_on_for_older_saved_states() { - assert!(UiState::default().mesh_recompute_normals); + fn mesh_export_normal_choice_defaults_off_for_older_saved_states() { + assert!(!UiState::default().mesh_recompute_normals); let mut saved = serde_json::to_value(UiState::default()).unwrap(); saved.as_object_mut().unwrap().remove("mesh_recompute_normals"); let loaded: UiState = serde_json::from_value(saved).unwrap(); - assert!(loaded.mesh_recompute_normals, "older states keep the dialog's checked default"); + assert!(!loaded.mesh_recompute_normals, "older states keep the project's stored normals unless the user opts in"); } #[test] @@ -881,7 +882,7 @@ mod tests { ui.keymap.insert("file.save".into(), "F5".into()); ui.mesh_recompute_normals = false; let mut layout = UiState::default(); - assert!(layout.mesh_recompute_normals); + layout.mesh_recompute_normals = true; layout.dock.close(crate::docking::Panel::Assets); ui.adopt_layout(layout); diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 62362f74..399a5161 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -185,21 +185,21 @@ fn recompute_normals_is_an_enabled_keyboard_operable_checkbox() { harness.run_steps(SETTLE_FRAMES); let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); assert!(!checkbox.accesskit_node().is_disabled(), "the option is really available"); - assert!(is_on(&checkbox), "it starts checked, as the dialog always showed it"); - assert!(harness.state().ui.mesh_recompute_normals); + assert!(!is_on(&checkbox), "stored normals are kept until the user opts in"); + assert!(!harness.state().ui.mesh_recompute_normals); checkbox.focus(); harness.key_press(egui::Key::Space); harness.run_steps(SETTLE_FRAMES); - assert!(!harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export"); + assert!(harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export"); let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"); - assert!(!is_on(&checkbox), "the accessibility tree reports the unchecked state"); + assert!(is_on(&checkbox), "the accessibility tree reports the checked state"); assert_eq!(checkbox.accesskit_node().label().as_deref(), Some("Recompute vertex normals")); checkbox.click(); harness.run_steps(SETTLE_FRAMES); - assert!(harness.state().ui.mesh_recompute_normals, "a pointer click turns it back on"); - assert!(is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"))); + assert!(!harness.state().ui.mesh_recompute_normals, "a pointer click turns it back off"); + assert!(!is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals"))); } /// Whether the Log lists `line` (the status bar under it repeats the last message) From cfdb0e57d54ad13ae8216c9044cab160500fb0cc Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 11:49:41 -0500 Subject: [PATCH 40/80] Autosave: widen the copy suffix to 64 bits --- crates/ui-egui/src/autosave_name.rs | 15 ++++++++------- crates/ui-egui/src/lib.rs | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index fa188ad8..a15e2b79 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -9,7 +9,7 @@ use texturecraft_engine::formats::export::sanitize_file_stem; use crate::TextureCraftApp; /// Hex digits of a copy's suffix -const SUFFIX_DIGITS: usize = 8; +const SUFFIX_DIGITS: usize = 16; /// Between a copy's stem and its suffix, so a user's own file named like `report-20240115` is not taken for a copy const COPY_MARK: &str = "-copy-"; @@ -46,7 +46,7 @@ impl TextureCraftApp { } } -fn file_name(stem: &str, suffix: u32) -> String { +fn file_name(stem: &str, suffix: u64) -> String { let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect(); format!("{stem}{COPY_MARK}{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}") } @@ -66,7 +66,7 @@ fn is_copy_in(path: &Path, folder: &Path) -> bool { /// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run /// takes a different one -fn new_suffix(project: u64) -> u32 { +fn new_suffix(project: u64) -> u64 { let now = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(); let mut seed = Vec::new(); seed.extend_from_slice(&std::process::id().to_le_bytes()); @@ -75,9 +75,10 @@ fn new_suffix(project: u64) -> u32 { hash(&seed) } -/// 32-bit FNV-1a: the same bytes give the same suffix in every release, which the standard hasher does not promise -fn hash(bytes: &[u8]) -> u32 { - bytes.iter().fold(0x811c_9dc5, |hash, byte| (hash ^ u32::from(*byte)).wrapping_mul(0x0100_0193)) +/// 64-bit FNV-1a: the same bytes give the same suffix in every release, which the standard hasher does not promise. +/// Wide enough that two paths are very unlikely to share one +fn hash(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3)) } #[cfg(test)] @@ -157,7 +158,7 @@ mod tests { #[test] fn suffixes_have_a_fixed_width_and_long_names_are_cut() { let narrow = file_name("hero", 1); - let wide = file_name("hero", u32::MAX); + let wide = file_name("hero", u64::MAX); assert_eq!(narrow.len(), wide.len(), "every suffix has the same width"); assert!(file_name(&"a".repeat(500), 1).len() < 200); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 38f5161b..611d4f8d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -363,7 +363,7 @@ pub struct TextureCraftApp { next_autosave: f64, /// The unsaved project (its id) and the suffix of its autosave copy. #[cfg(not(target_arch = "wasm32"))] - unsaved_autosave_suffix: Option<(u64, u32)>, + unsaved_autosave_suffix: Option<(u64, u64)>, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. From c7a896d0789dd8f6654dbac39bd163678374e264 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:01:46 +0100 Subject: [PATCH 41/80] Resources Updater tests: install the headless framework runtime in their harnesses Main's ui-contract runtime panics when a harness does not set it up; the notice unit test and the integration tests now use framework::install_headless like main's harness tests. --- crates/ui-egui/src/resources_updater.rs | 2 +- crates/ui-egui/tests/it/resources_updater.rs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 21cf648b..75b5a8fc 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -386,7 +386,7 @@ mod tests { let path = dir.path().join("notice.png"); write_png(&path, 4); let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); - let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string(); diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 20609aec..27209132 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -17,7 +17,10 @@ use super::temp_dir::TempDir; fn app() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).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(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); From f2205d559188c4cc43d6d1c0af16897840ddc6e3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:18:37 +0100 Subject: [PATCH 42/80] Resources Updater: list linked MaterialCraft materials as rows without a file resource.status gains the status material for the package of every linked MaterialCraft material (fill layers and material effects); such a row cannot be updated or relinked from disk, and its status tooltip says it updates when MaterialCraft cooks it again. Tests also check that an environment map and a brush alpha are tracked like other images. --- crates/engine/src/resource_status.rs | 12 +++++++--- crates/engine/src/resource_update_cmds.rs | 25 +++++++++++++++++++- crates/engine/tests/it/resource_updater.rs | 24 ++++++++++++++++--- crates/ui-egui/src/resources_updater.rs | 16 +++++++++---- crates/ui-egui/tests/it/resources_updater.rs | 15 +++++++++++- docs/control-protocol.md | 2 +- 6 files changed, 80 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/resource_status.rs b/crates/engine/src/resource_status.rs index 8e8efc70..b2ae9961 100644 --- a/crates/engine/src/resource_status.rs +++ b/crates/engine/src/resource_status.rs @@ -1,6 +1,6 @@ -//! Whether an image resource still matches the file it was imported from +//! Whether a resource still matches the file it was imported from -/// How an image resource compares with its file on disk. The order is the Resources Updater's +/// How a resource compares with its file on disk (materials have none). The order is the Resources Updater's /// list order: what needs attention first. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ResourceStatus { @@ -12,10 +12,14 @@ pub enum ResourceStatus { UpToDate, /// Made in the app or imported without a file path: there is nothing to compare with. NoSource, + /// A linked MaterialCraft material's package: it has no file to compare with and updates by + /// cooking it again (`material.link.cook`). + Material, } impl ResourceStatus { - pub const ALL: [ResourceStatus; 4] = [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource]; + pub const ALL: [ResourceStatus; 5] = + [ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource, ResourceStatus::Material]; /// The id used by the control protocol pub fn id(self) -> &'static str { @@ -24,6 +28,7 @@ impl ResourceStatus { ResourceStatus::Missing => "missing", ResourceStatus::UpToDate => "upToDate", ResourceStatus::NoSource => "noSource", + ResourceStatus::Material => "material", } } @@ -34,6 +39,7 @@ impl ResourceStatus { ResourceStatus::Missing => "Missing", ResourceStatus::UpToDate => "Up to date", ResourceStatus::NoSource => "No source file", + ResourceStatus::Material => "Material", } } } diff --git a/crates/engine/src/resource_update_cmds.rs b/crates/engine/src/resource_update_cmds.rs index 0fc56e7d..665516e3 100644 --- a/crates/engine/src/resource_update_cmds.rs +++ b/crates/engine/src/resource_update_cmds.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Check resources on disk", [], None, - "{} → {resources: [{name, status: outdated|missing|upToDate|noSource, path?, error?}] (outdated first), total, outdated}", + "{} → {resources: [{name, status: outdated|missing|upToDate|noSource|material, path?, error?}] (outdated first; material: a linked MaterialCraft package, updated by material.link.cook), total, outdated}", always, |s, _| Ok(status(s)) ), @@ -49,10 +49,33 @@ impl Session { /// not, and that verdict is kept until the file's size or time changes again. pub fn resource_states(&mut self) -> Vec { let mut states = self.compare_resources(); + let materials = self.material_packages().into_iter(); + states.extend(materials.map(|name| ResourceState { name, status: ResourceStatus::Material, path: None, error: None })); states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name))); states } + /// The packages of linked MaterialCraft materials (fill layers and material effects) the project holds + fn material_packages(&self) -> std::collections::BTreeSet { + use texturecraft_core::{EffectKind, Fill, LayerKind}; + + let package_of = |fill: &Fill| fill.link.as_ref().map(|link| link.package.clone()); + let mut packages = std::collections::BTreeSet::new(); + for layer in self.doc.project.layers.values() { + if let LayerKind::Fill(fill) = &layer.kind { + packages.extend(package_of(fill)); + } + for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { + if let EffectKind::Material(fill) = &effect.kind { + packages.extend(package_of(fill)); + } + } + } + + packages.retain(|name| self.doc.resources.contains_key(name)); + packages + } + /// Whether `name` is an image resource the Resources Updater lists fn is_image_resource(&self, name: &str) -> bool { self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name)) diff --git a/crates/engine/tests/it/resource_updater.rs b/crates/engine/tests/it/resource_updater.rs index 43a9120b..aa306838 100644 --- a/crates/engine/tests/it/resource_updater.rs +++ b/crates/engine/tests/it/resource_updater.rs @@ -102,7 +102,7 @@ fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() } #[test] -fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { +fn outdated_resources_come_first_then_missing_up_to_date_unlinked_and_materials() { let dir = tempfile::tempdir().unwrap(); let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name)); for file in [&fine, &gone, &changed] { @@ -114,12 +114,30 @@ fn outdated_resources_come_first_then_missing_up_to_date_and_unlinked() { for file in [&fine, &gone, &changed] { import(&mut s, file); } + + // The environment map and the brush alpha are image resources like any other + let environment = format!("{}b_fine.png", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX); + execute(&mut s, "display.set", &json!({"environment": environment})).unwrap(); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "d_changed.png"}})).unwrap(); + + // A linked MaterialCraft material keeps its package as a resource without a file + s.doc.resources.insert("a_brick.mcmat".to_string(), Arc::new(b"package".to_vec())); + let layer = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let link = serde_json::from_value(json!({"name": "Brick", "package": "a_brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut s.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind { + fill.link = Some(link); + } + std::fs::remove_file(&gone).unwrap(); write_png(&changed, 8, GREEN); - let order: Vec = s.resource_states().into_iter().map(|state| state.name).collect(); + let states = s.resource_states(); + let order: Vec<&str> = states.iter().map(|state| state.name.as_str()).collect(); + let statuses: Vec<&str> = states.iter().map(|state| state.status.id()).collect(); - assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png"], "by status first, against the name order"); + assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png", "a_brick.mcmat"], "by status first, against the name order"); + assert_eq!(statuses, ["outdated", "missing", "upToDate", "noSource", "material"], "the alpha's and the environment's files are checked too"); + assert!(execute(&mut s, "resource.update", &json!({"names": ["a_brick.mcmat"]})).is_err(), "a material has no file to read again"); } #[test] diff --git a/crates/ui-egui/src/resources_updater.rs b/crates/ui-egui/src/resources_updater.rs index 75b5a8fc..5cf20018 100644 --- a/crates/ui-egui/src/resources_updater.rs +++ b/crates/ui-egui/src/resources_updater.rs @@ -329,11 +329,15 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: request = Some(RowRequest::Update(row.name.clone())); } - let select = ui.button(tr("Select new resource")); - let select_name = format!("{} {}", tr("Select new resource"), row.name); - select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); - if select.clicked() { - request = Some(RowRequest::SelectNew(row.name.clone())); + // A material is no image file, so it cannot point at one + let material = row.status == ResourceStatus::Material; + if !material { + let select = ui.button(tr("Select new resource")); + let select_name = format!("{} {}", tr("Select new resource"), row.name); + select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name)); + if select.clicked() { + request = Some(RowRequest::SelectNew(row.name.clone())); + } } if let Some(path) = &row.path { @@ -353,6 +357,8 @@ fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: let status = ui.label(tr(row.status.label())); if let Some(error) = &row.error { status.on_hover_text(error); + } else if material { + status.on_hover_text(tr("A MaterialCraft material has no file on disk: it updates when MaterialCraft cooks it again")); } }); }); diff --git a/crates/ui-egui/tests/it/resources_updater.rs b/crates/ui-egui/tests/it/resources_updater.rs index 27209132..050fedb4 100644 --- a/crates/ui-egui/tests/it/resources_updater.rs +++ b/crates/ui-egui/tests/it/resources_updater.rs @@ -130,11 +130,21 @@ fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_l } #[test] -fn show_in_folder_shows_the_folder_of_the_resource_file() { +fn show_in_folder_shows_the_folder_of_the_resource_file_and_materials_have_no_file() { let dir = TempDir::new("resources-updater-folder"); let file = png(&dir, "bricks.png", 4); let mut h = app(); import(&mut h, &file); + + // A linked MaterialCraft material keeps its package as a resource without a file + let layer = h.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap(); + let session = &mut h.state_mut().session; + session.doc.resources.insert("brick.mcmat".to_string(), std::sync::Arc::new(b"package".to_vec())); + let link = serde_json::from_value(json!({"name": "Brick", "package": "brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap(); + if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut session.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind + { + fill.link = Some(link); + } activate(&mut h, "Resources Updater"); activate(&mut h, "Show in folder bricks.png"); @@ -142,6 +152,9 @@ fn show_in_folder_shows_the_folder_of_the_resource_file() { let shown = h.state().file_dialogs.shown_folders().to_vec(); assert_eq!(shown.len(), 1); assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder"); + assert!(shows(&h, "Name : brick.mcmat"), "the material is listed"); + assert!(h.query_by_label("Select new resource brick.mcmat").is_none(), "a material cannot point at an image file"); + assert!(h.query_by_label("Show in folder brick.mcmat").is_none(), "it has no file"); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3db7a106..4bc4d42f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -506,7 +506,7 @@ read once; its verdict is kept until its size or time changes again. | Command | Params and result | |---|---| -| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate` or `noSource` (made in the app or imported without a path); outdated first, then by name. A file is read only when its size matches but its modification time does not | +| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate`, `noSource` (made in the app or imported without a path) or `material` (the package of a linked MaterialCraft material: it has no file and updates with `material.link.cook`); outdated first, then by name. A file is read only when its size matches but its modification time does not | | `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused | | `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step | From ed5bb4ed697a72c8333209f0826d7488d7aa9ba9 Mon Sep 17 00:00:00 2001 From: supersfera Date: Thu, 26 Nov 2026 12:58:03 -0800 Subject: [PATCH 43/80] ru: remove the per-file translation notices The translation is under the repository's licence, and authorship is in git history. --- packaging/linux/ai.storyteller.texturecraft.desktop | 1 - packaging/linux/ai.storyteller.texturecraft.mime.xml | 1 - 2 files changed, 2 deletions(-) diff --git a/packaging/linux/ai.storyteller.texturecraft.desktop b/packaging/linux/ai.storyteller.texturecraft.desktop index e1cb409a..07ebda06 100644 --- a/packaging/linux/ai.storyteller.texturecraft.desktop +++ b/packaging/linux/ai.storyteller.texturecraft.desktop @@ -1,4 +1,3 @@ -# Russian translation © 2026 SuperSfera LLC, MIT OR Apache-2.0 [Desktop Entry] Type=Application Name=TextureCraft diff --git a/packaging/linux/ai.storyteller.texturecraft.mime.xml b/packaging/linux/ai.storyteller.texturecraft.mime.xml index 2b1b811e..cb7c1b99 100644 --- a/packaging/linux/ai.storyteller.texturecraft.mime.xml +++ b/packaging/linux/ai.storyteller.texturecraft.mime.xml @@ -1,5 +1,4 @@ - From c54e1eb75eed104d6bb7c9db42e31705ee2c18c1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 26 Nov 2026 21:58:59 +0100 Subject: [PATCH 44/80] Xwayland for the pen only when its X server answers; hand the chosen backend to the title bar and UI runtime A DISPLAY left over from another session could force X11 with no X server to connect to, and winit can't fall back to Wayland then. The title bar decision and the UI runtime read the backend from the environment and saw Wayland while the window opened on Xwayland. --- Cargo.lock | 1 + apps/texturecraft/Cargo.toml | 2 ++ apps/texturecraft/src/main.rs | 13 +++++++---- apps/texturecraft/src/xwayland_pen.rs | 31 ++++++++++++++++++++++----- crates/ui-egui/src/framework.rs | 6 +++--- crates/ui-egui/src/titlebar.rs | 6 +++--- 6 files changed, 44 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index acafef1d..a80cac9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5819,6 +5819,7 @@ dependencies = [ name = "texturecraft" version = "0.6.1" dependencies = [ + "craft-host", "craft-image-codecs", "craft-menu", "craft-update", diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index 39fb3c7c..52626627 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -23,6 +23,8 @@ serde_json = { workspace = true } log = { workspace = true } # The message box for errors that end the app (a Windows release build has no console). rfd = { workspace = true } +# The window's backend (Xwayland for a pen, src/xwayland_pen.rs) for the title bar and the UI runtime. +craft-host = { workspace = true } # Reads the saved System title bar setting before the window opens (eframe's settings format). ron = "0.12" diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index d0c26efc..04d3b23a 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -395,7 +395,13 @@ fn main() { prefs.apply_work_threads(); prefs.apply_resource_limits(); let session = initial_session(&args); - let frame_decision = TitleBar::decide(prefs.system_title_bar); + // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; a pen works only through Xwayland there + #[cfg(target_os = "linux")] + let pen_needs_x11 = xwayland_pen::opens_through_xwayland(); + #[cfg(not(target_os = "linux"))] + let pen_needs_x11 = false; + let backend = if pen_needs_x11 { craft_host::target::Backend::X11 } else { craft_host::target::Backend::from_env() }; + let frame_decision = TitleBar::decide(prefs.system_title_bar, backend); let title_bar = TitleBar::of(&frame_decision.frame); let mut viewport = egui::ViewportBuilder::default() .with_app_id(os_window::app_id()) @@ -407,9 +413,8 @@ fn main() { } let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport); let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; - // winit picks Wayland whenever `WAYLAND_DISPLAY` is set; a pen works only through Xwayland there #[cfg(target_os = "linux")] - if xwayland_pen::opens_through_xwayland() { + if pen_needs_x11 { use winit::platform::x11::EventLoopBuilderExtX11 as _; options.event_loop_builder = Some(Box::new(|builder| { builder.with_x11(); @@ -460,7 +465,7 @@ fn main() { 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}"); } - texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?; + texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision, backend)?; let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; diff --git a/apps/texturecraft/src/xwayland_pen.rs b/apps/texturecraft/src/xwayland_pen.rs index 6c3f7d3a..10d44314 100644 --- a/apps/texturecraft/src/xwayland_pen.rs +++ b/apps/texturecraft/src/xwayland_pen.rs @@ -31,11 +31,13 @@ const X11_LIBRARIES: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; /// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland -/// can run the window. Says so on stderr when it does. +/// can run the window (the X11 libraries are installed and the X server answers). Says so on +/// stderr when it does. pub fn opens_through_xwayland() -> bool { let var = |name: &str| std::env::var(name).ok(); let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)); - if !pen_needs_xwayland(var, pen, x11_libraries_available) { + let xwayland_ready = || x11_libraries_available() && var("DISPLAY").is_some_and(|display| x_server_answers(&display)); + if !pen_needs_xwayland(var, pen, xwayland_ready) { return false; } @@ -45,11 +47,29 @@ pub fn opens_through_xwayland() -> bool { /// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or /// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland. -fn pen_needs_xwayland(var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool, x11_libraries: impl FnOnce() -> bool) -> bool { +fn pen_needs_xwayland(var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool, xwayland_ready: impl FnOnce() -> bool) -> bool { let set = |name: &str| var(name).is_some_and(|value| !value.is_empty()); let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET"); let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0"); - wayland && !keeps_wayland && set("DISPLAY") && pen() && x11_libraries() + wayland && !keeps_wayland && set("DISPLAY") && pen() && xwayland_ready() +} + +/// Does the X server `display` names accept a connection? winit can't fall back to Wayland once +/// X11 is chosen, so a `DISPLAY` left over from another session must keep the window on Wayland. +/// Only a local display is tried, by its socket path or the abstract socket of the same name. +fn x_server_answers(display: &str) -> bool { + use std::os::linux::net::SocketAddrExt as _; + use std::os::unix::net::{SocketAddr, UnixStream}; + + let Some(socket) = local_x_socket(display) else { return false }; + UnixStream::connect(&socket).is_ok() || SocketAddr::from_abstract_name(socket.as_bytes()).and_then(|address| UnixStream::connect_addr(&address)).is_ok() +} + +/// The socket of a local X display (`:0`, `:0.0`, `unix:0`); `None` for a remote one +fn local_x_socket(display: &str) -> Option { + let number = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?; + let number: u32 = number.split('.').next()?.parse().ok()?; + Some(format!("/tmp/.X11-unix/X{number}")) } /// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has @@ -141,10 +161,11 @@ mod tests { assert!(pen_needs_xwayland(env(WAYLAND), || true, || true)); assert!(!pen_needs_xwayland(env(WAYLAND), || false, || true), "no pen"); - assert!(!pen_needs_xwayland(env(WAYLAND), || true, || false), "no X11 libraries"); + assert!(!pen_needs_xwayland(env(WAYLAND), || true, || false), "Xwayland can't run the window"); assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, || true), "no Xwayland"); assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, || true), "kept"); assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, || true)); assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), || panic!("probed off Wayland")), "X11 already has the pen"); + assert_eq!([":1.0", "unix:0", "remote:0"].map(local_x_socket), [Some("/tmp/.X11-unix/X1".into()), Some("/tmp/.X11-unix/X0".into()), None]); } } diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 187d0de6..f617d398 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -52,10 +52,10 @@ fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc Result<(), String> { - let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env()); +pub fn install(ctx: &egui::Context, frame: Decision, backend: craft_host::target::Backend) -> Result<(), String> { + let shell = ShellInfo::default().backend(backend); install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows), Some(frame)) } diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 024675b1..5817e7a8 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -68,12 +68,12 @@ const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [ impl TitleBar { /// Decide who draws the title bar; call once at startup, before the window is created, and /// hand the decision to the window ([`viewport`]) and the runtime (`framework::install`). - /// `system` is Settings › Interface › System title bar. - pub fn decide(system: bool) -> Decision { + /// `system` is Settings › Interface › System title bar; `backend` is the one the window opens on. + pub fn decide(system: bool, backend: craft_host::target::Backend) -> Decision { let choice = craft_window::Choice::probe(PREFIX); let wanted = Self::from_choice(choice.frame(), choice.overridden(), system); let pref = if wanted == TitleBar::System { TitleBarPref::System } else { TitleBarPref::Integrated }; - craft_window::policy::decide_for(PREFIX, craft_host::target::Backend::from_env(), pref) + craft_window::policy::decide_for(PREFIX, backend, pref) } /// The bar a decided `frame` gives. From 448d22aa26904396d22d007d9f6209e2be117f82 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:31:02 +0000 Subject: [PATCH 45/80] Apply review fixes - docs/ui-parity.md --- docs/ui-parity.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1e45c49d..26198df6 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -71,8 +71,10 @@ that closes it back onto the bar; the float is saved with the UI state. 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"). *Export MaterialX* beside them 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. + export. The prompt's *With displacement/tessellation* choice and *Apply triangulation* are greyed + (TextureCraft exports the mesh as it is, triangulated). *Recompute vertex normals* works and sits under + *Without displacement/tessellation*, off by default: it writes smooth area-weighted normals to the + exported copy only. - **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 - ", From 5ddec31f804ebfdb0409d97824c4dae3ce1506b8 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Thu, 26 Nov 2026 22:56:27 +0100 Subject: [PATCH 46/80] fix(engine): inspect direction on earlier-model generators (#873) --- crates/engine/src/inspect.rs | 5 ++++- crates/engine/tests/it/generator_sections.rs | 23 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 14863420..a4258463 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, Sampling, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, NormalFormat, Projection, Sampling, Source}; use crate::Session; use crate::session::StackTarget; @@ -162,6 +162,9 @@ fn generator_json(generator: &Generator) -> Value { if let Some(light) = &generator.light { out["light"] = json!(light); } + if generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction) { + out["direction"] = json!(generator.direction); + } if let Some(texture) = &generator.texture { out["texture"] = json!(texture); } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 29311091..399355f3 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -167,3 +167,26 @@ fn inspect_reports_the_reference_controls_set() { assert!(inspected.contains(&format!("\"{key}\"")) && inspected.contains(value), "{key} with {value} in {inspected}"); } } + +#[test] +fn inspect_reports_direction_only_on_the_earlier_model() { + let mut session = session(); + let earlier_dir = add(&mut session, json!({"generator": "direction", "direction": [1.0, 0.0, 0.0]})); + let light_dir = add(&mut session, json!({"generator": "direction", "lightHorizontal": 90.0})); + let earlier_pos = add(&mut session, json!({"generator": "position", "direction": [0.0, 0.0, 1.0]})); + let section_pos = add(&mut session, json!({"generator": "position", "sectionContrast": 0.25})); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap(); + let effects = inspected["layers"][0]["mask"]["effects"].as_array().unwrap(); + let gen_of = |effect_id: u64| &effects.iter().find(|entry| entry["id"] == effect_id).unwrap()["generator"]; + + assert_eq!(gen_of(earlier_dir)["direction"], json!([1.0, 0.0, 0.0])); + assert!(gen_of(earlier_dir).get("light").is_none()); + assert!(gen_of(light_dir).get("direction").is_none()); + assert!(gen_of(light_dir).get("light").is_some()); + + assert_eq!(gen_of(earlier_pos)["direction"], json!([0.0, 0.0, 1.0])); + assert!(gen_of(earlier_pos).get("section").is_none()); + assert!(gen_of(section_pos).get("direction").is_none()); + assert!(gen_of(section_pos).get("section").is_some()); +} From 5591288d89b46155b12f0c83754a2c9033a2631b Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:55:53 +0000 Subject: [PATCH 47/80] Apply review fixes - crates/ui-egui/src/autosave_name.rs --- crates/ui-egui/src/autosave_name.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index a15e2b79..69d0ab4d 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -56,10 +56,15 @@ fn absolute(path: &Path) -> PathBuf { std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()) } +/// `path` with links and, on Windows, the verbatim prefix resolved so two spellings of one folder compare equal; made absolute when that fails +fn resolved(path: &Path) -> PathBuf { + std::fs::canonicalize(path).unwrap_or_else(|_| absolute(path)) +} + /// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in the copy mark and a suffix fn is_copy_in(path: &Path, folder: &Path) -> bool { let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once(COPY_MARK)).map(|(_, suffix)| suffix); - path.parent() == Some(folder) + path.parent().is_some_and(|parent| resolved(parent) == resolved(folder)) && path.extension().is_some_and(|extension| extension == PROJECT_EXT) && suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit())) } From 9e2917098f7ecdc200afeb48741179c6a85e0a43 Mon Sep 17 00:00:00 2001 From: a2 Date: Thu, 26 Nov 2026 19:54:14 -0500 Subject: [PATCH 48/80] chore(i18n): leave the language registration to #691; keep the Russian packaging metadata Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/fonts.rs | 5 ++--- crates/ui-egui/src/i18n.rs | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index b9f5530f..95080619 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -279,9 +279,8 @@ mod tests { assert_eq!(Script::of_language("ar"), Some(Script::Arabic)); assert_eq!(Script::of_language("de"), None); for l in &crate::i18n::LANGUAGES { - // Past the Latin blocks and their diacritics. Cyrillic is already in the - // interface font (Inter / Ubuntu-Light), so Russian needs no fallback script. - let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c)); + // Past the Latin blocks and their diacritics. + let other_script = l.name.chars().any(|c| c > '\u{036F}'); assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code); } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index be1da30c..2210638e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -37,7 +37,7 @@ pub struct Language { pub english: &'static str, } -const COUNT: usize = 11; +const COUNT: usize = 10; pub static LANGUAGES: [Language; COUNT] = [ Language { code: "en", name: "English", english: "English" }, @@ -50,7 +50,6 @@ pub static LANGUAGES: [Language; COUNT] = [ Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" }, Language { code: "ko", name: "한국어", english: "Korean" }, Language { code: "ar", name: "العربية", english: "Arabic" }, - Language { code: "ru", name: "Русский", english: "Russian" }, ]; // Rendering and preferences use the UI thread, including independent test harnesses. From beea46c9e22126681df3ddbc7884fb424fb979b5 Mon Sep 17 00:00:00 2001 From: a2 Date: Thu, 26 Nov 2026 21:00:18 -0500 Subject: [PATCH 49/80] fix(engine): Open in MaterialCraft stages its package in a private folder The button wrote /.mcraft with a plain fs::write. On a shared temp folder another local user could plant a file or link at that guessable name first, and the write went through it. The package now goes into a new random folder made exclusively (0700 on Unix), as a create_new file; folders over a week old are swept. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 130 +++++++++++++++++++++++++++++++++ crates/ui-egui/src/dock.rs | 6 +- 2 files changed, 133 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index a20182f6..f22b0f6e 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -344,6 +344,59 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Prefix of the folders [`stage_handoff_package`] makes in the temp folder. +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_PREFIX: &str = "texturecraft-open-"; + +/// Folders from earlier hand-offs older than this are removed (MaterialCraft may still have a young one open). +#[cfg(not(target_arch = "wasm32"))] +const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600); + +/// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the +/// file's path (for [`open_in_materialcraft`]). A fixed `/` is guessable: on a shared `/tmp` another user +/// could plant a file or link there first and the write would go through it. The folder name is random, is created +/// exclusively (mode `0700` on Unix) and the file is created with `create_new`, so nothing planted is ever written through. +/// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go. +#[cfg(not(target_arch = "wasm32"))] +pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result { + stage_handoff_package_in(&std::env::temp_dir(), file_name, package) +} + +#[cfg(not(target_arch = "wasm32"))] +fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[u8]) -> Result { + use std::io::Write; + let io = |e: std::io::Error| EngineError::Other(format!("cannot stage the package for MaterialCraft: {e}")); + if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) { + return Err(EngineError::Other(format!("`{file_name}` is not a plain file name"))); + } + sweep_old_handoffs(base, HANDOFF_MAX_AGE); + // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind. + let dir = tempfile::Builder::new().prefix(HANDOFF_PREFIX).tempdir_in(base).map_err(io)?; + let path = dir.path().join(file_name); + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(io)?; + file.write_all(package).map_err(io)?; + file.sync_all().map_err(io)?; + let _ = dir.keep(); + Ok(path) +} + +/// Remove hand-off folders in `base` last changed more than `max_age` ago. Only real folders with our prefix are +/// touched (never a link), and every failure is ignored: a leftover folder costs disk space, not work. +#[cfg(not(target_arch = "wasm32"))] +fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) { + let Ok(entries) = std::fs::read_dir(base) else { return }; + for entry in entries.flatten() { + if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age); + if meta.is_dir() && old { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + /// Source file extensions are chosen from the linked resource name, never an untrusted path. pub fn source_extension(name: &str) -> &'static str { if name.to_ascii_lowercase().ends_with(".mcmat") { @@ -711,4 +764,81 @@ mod tests { assert_eq!(typed(&p, &json!("#+f+f+f")), None); assert!(typed(&p, &json!("#ff8000")).is_some()); } + + #[cfg(not(target_arch = "wasm32"))] + fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A file another user planted at the old, guessable `/` is never written through. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_is_not_written_through_a_planted_link() { + let base = scratch("planted"); + let victim = base.join("victim.txt"); + std::fs::write(&victim, b"precious").unwrap(); + // The old code wrote `/` with `fs::write`; a hard link there reaches the victim on every platform. + std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap(); + + let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap(); + + assert_eq!(std::fs::read(&victim).unwrap(), b"precious"); + assert_eq!(std::fs::read(&path).unwrap(), b"package"); + assert_ne!(path.parent().unwrap(), base, "the file is inside a folder of its own"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Every hand-off gets its own empty-until-written folder, even when the name repeats. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_packages_get_distinct_folders() { + let base = scratch("distinct"); + let a = super::stage_handoff_package_in(&base, "m.mcraft", b"a").unwrap(); + let b = super::stage_handoff_package_in(&base, "m.mcraft", b"b").unwrap(); + assert_ne!(a.parent(), b.parent()); + assert_eq!((std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()), (b"a".to_vec(), b"b".to_vec())); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + } + std::fs::remove_dir_all(&base).unwrap(); + } + + /// A name with a path in it cannot leave the new folder. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_package_rejects_names_that_are_paths() { + let base = scratch("names"); + for bad in ["", "..", "a/b.mcraft", "../x.mcraft"] { + assert!(super::stage_handoff_package_in(&base, bad, b"x").is_err(), "{bad}"); + } + assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "a rejected name leaves nothing behind"); + std::fs::remove_dir_all(&base).unwrap(); + } + + /// Old hand-off folders are swept; young ones, other folders and files stay. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn handoff_sweep_removes_only_old_handoff_folders() { + let base = scratch("sweep"); + let old = base.join("texturecraft-open-old"); + let other = base.join("somebody-elses-folder"); + let file = base.join("texturecraft-open-file"); + for dir in [&old, &other] { + std::fs::create_dir(dir).unwrap(); + } + std::fs::write(&file, b"x").unwrap(); + // Zero age limit: everything with the prefix that is a folder counts as old. + super::sweep_old_handoffs(&base, std::time::Duration::ZERO); + assert!(!old.exists() && other.exists() && file.exists()); + let young = base.join("texturecraft-open-young"); + std::fs::create_dir(&young).unwrap(); + super::sweep_old_handoffs(&base, std::time::Duration::from_secs(3600)); + assert!(young.exists()); + std::fs::remove_dir_all(&base).unwrap(); + } } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index a59a5f4d..9d79bf30 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2787,12 +2787,12 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { #[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 file_name = 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)); + .and_then(|package| texturecraft_engine::link_cmds::stage_handoff_package(&file_name, package.as_slice())) + .and_then(|path| 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), From 89a906a5c1b817a50a8b9f19b3fc1dbec090835c Mon Sep 17 00:00:00 2001 From: a2 Date: Thu, 26 Nov 2026 21:17:04 -0500 Subject: [PATCH 50/80] fix(engine): hand-off folder and file get explicit 0700 and 0600 on Unix tempfile creates folders with the default mode (0755 under the usual umask), so the 0700 the first version asserted was not what Linux produced. Ask for it, and for 0600 on the package file. Found by CodeRabbit. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/link_cmds.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index f22b0f6e..f3cd84ad 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -355,7 +355,7 @@ const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * /// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the /// file's path (for [`open_in_materialcraft`]). A fixed `/` is guessable: on a shared `/tmp` another user /// could plant a file or link there first and the write would go through it. The folder name is random, is created -/// exclusively (mode `0700` on Unix) and the file is created with `create_new`, so nothing planted is ever written through. +/// exclusively (mode `0700` on Unix) and the file is created with `create_new` (mode `0600`), so nothing planted is ever written through. /// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go. #[cfg(not(target_arch = "wasm32"))] pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result { @@ -371,9 +371,18 @@ fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[ } sweep_old_handoffs(base, HANDOFF_MAX_AGE); // Dropped (and removed) on any early return, so a failed write leaves no empty folder behind. - let dir = tempfile::Builder::new().prefix(HANDOFF_PREFIX).tempdir_in(base).map_err(io)?; + let mut builder = tempfile::Builder::new(); + builder.prefix(HANDOFF_PREFIX); + // tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly. + #[cfg(unix)] + builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)); + let dir = builder.tempdir_in(base).map_err(io)?; let path = dir.path().join(file_name); - let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(io)?; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(&path).map_err(io)?; file.write_all(package).map_err(io)?; file.sync_all().map_err(io)?; let _ = dir.keep(); @@ -804,6 +813,7 @@ mod tests { { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700); + assert_eq!(std::fs::metadata(&a).unwrap().permissions().mode() & 0o777, 0o600); } std::fs::remove_dir_all(&base).unwrap(); } From d9926733a984dbf5fc8d670e99af63412048c9e1 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 27 Nov 2026 04:53:09 +0000 Subject: [PATCH 51/80] Auto: Preserve IOR edits across background saves Track IOR-related display changes in the save revision and preserve the exact legacy reflectance scale at IOR 1.5. Improve the shader checkbox outline and cover its contrast and keyboard behavior. Reuse wrapped CPU trace coordinates, shorten tracer staging lifetimes, and avoid per-set template channel ID allocations. Document the separate glass-interface Fresnel calculation. Verified with local workspace gate coverage, affected release suites, software rendering, and the shader rail snapshot. --- crates/core/src/project.rs | 47 +++++-- crates/engine/src/template_cmds.rs | 43 +++--- crates/engine/src/view_cmds.rs | 19 ++- crates/engine/tests/it/ior_specular.rs | 20 +++ crates/render/src/gpu_trace.rs | 38 ++--- crates/render/src/shaders/mesh.wgsl | 5 +- crates/render/src/trace.rs | 186 +++++++++++++++---------- crates/ui-egui/src/shader_settings.rs | 22 ++- crates/ui-egui/tests/it/side_panels.rs | 64 +++++++++ docs/control-protocol.md | 6 +- 10 files changed, 319 insertions(+), 131 deletions(-) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 85f8f52a..0a4bf868 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -316,7 +316,7 @@ pub struct DisplaySettings { pub scatter_color: [f32; 3], /// Subsurface scattering mean free path as a fraction of the mesh's bounding radius. pub scatter_radius: f32, - /// Index of refraction of transmissive surfaces (where the Transmission channel is painted). + /// Index of refraction for transmission and, when enabled, dielectric reflectance. pub ior: f32, /// Use IOR to determine dielectric reflectance at normal incidence in Metallic/Roughness. pub ior_specular: bool, @@ -386,6 +386,10 @@ pub const ENV_RESOURCE_PREFIX: &str = "resource:"; /// Original dielectric F0 multiplier for the Specular Level channel. pub const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; +/// Project limits for the index of refraction. +pub const MIN_INDEX_OF_REFRACTION: f32 = 1.0; +pub const MAX_INDEX_OF_REFRACTION: f32 = 3.0; + impl DisplaySettings { /// The image resource used as the environment, if any. pub fn environment_resource(&self) -> Option<&str> { @@ -394,14 +398,19 @@ impl DisplaySettings { /// Multiplier for Specular Level in the Metallic/Roughness model. pub fn dielectric_f0_scale(&self) -> f32 { - if self.ior_specular && !self.spec_gloss && self.ior.is_finite() { - let ior = self.ior.clamp(1.0, 3.0); - let fresnel = (ior - 1.0) / (ior + 1.0); - // Specular Level 0.5 represents OpenPBR's default specular weight of 1. - 2.0 * fresnel * fresnel - } else { - LEGACY_DIELECTRIC_F0_SCALE + if !self.ior_specular || self.spec_gloss || !self.ior.is_finite() { + return LEGACY_DIELECTRIC_F0_SCALE; } + + const AIR_INDEX_OF_REFRACTION: f32 = 1.0; + // Specular Level 0.5 corresponds to OpenPBR specular weight 1 + const SPECULAR_LEVEL_TO_WEIGHT_SCALE: f32 = 2.0; + let ior = self.ior.clamp(MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION); + let contrast = ior - AIR_INDEX_OF_REFRACTION; + let index_sum = ior + AIR_INDEX_OF_REFRACTION; + + // Square before dividing so IOR 1.5 rounds to the legacy multiplier + SPECULAR_LEVEL_TO_WEIGHT_SCALE * contrast.powi(2) / index_sum.powi(2) } } @@ -835,6 +844,28 @@ mod tests { p } + #[test] + fn enabling_ior_at_the_default_preserves_legacy_reflectance() { + let mut display = DisplaySettings::default(); + let legacy = display.dielectric_f0_scale(); + + display.ior_specular = true; + + assert_eq!(display.dielectric_f0_scale(), legacy); + } + + #[test] + fn dielectric_reflectance_clamps_ior_and_falls_back_for_non_finite_values() { + let scale_at = |ior| DisplaySettings { ior, ior_specular: true, ..DisplaySettings::default() }.dielectric_f0_scale(); + + assert_eq!(scale_at(0.5), scale_at(1.0)); + assert_eq!(scale_at(1.0), 0.0); + assert!(scale_at(1.5) < scale_at(3.0)); + assert_eq!(scale_at(4.0), scale_at(3.0)); + assert_eq!(scale_at(f32::NAN), LEGACY_DIELECTRIC_F0_SCALE); + assert_eq!(scale_at(f32::INFINITY), LEGACY_DIELECTRIC_F0_SCALE); + } + #[test] fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() { let group = BakeSyncGroup::Common; diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index 69c3d7c7..e07370fc 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -191,29 +191,36 @@ impl Session { matches.next().is_none().then(|| template.clone()) } - /// Start this (new, unpainted) project from template `t`: its channels on every texture set - /// and layer, normal format and shader settings. The resolution is the caller's choice. - pub fn apply_template(&mut self, t: &ProjectTemplate) { - let p = &mut self.doc.project; - p.normal_format = t.normal_format; - let d = &mut p.display; - (d.spec_gloss, d.parallax, d.ior, d.scatter_color, d.scatter_radius) = (t.spec_gloss, t.parallax, t.ior, t.scatter_color, t.scatter_radius); - d.ior_specular = t.ior_specular; - for ts in 0..p.texture_sets.len() { - if let Some(set) = p.texture_sets.get_mut(ts) { - set.channels = t.channels.clone(); + /// Apply the template's channels and shader settings to a new, unpainted project. + /// The caller chooses the texture set resolution. + pub fn apply_template(&mut self, template: &ProjectTemplate) { + let project = &mut self.doc.project; + project.normal_format = template.normal_format; + + let display = &mut project.display; + display.spec_gloss = template.spec_gloss; + display.parallax = template.parallax; + display.ior = template.ior; + display.ior_specular = template.ior_specular; + display.scatter_color = template.scatter_color; + display.scatter_radius = template.scatter_radius; + + for set_index in 0..project.texture_sets.len() { + if let Some(set) = project.texture_sets.get_mut(set_index) { + set.channels = template.channels.clone(); } - let wanted: Vec = t.channels.iter().map(|(c, _)| *c).collect(); - for (id, _) in p.walk(ts) { - if let Ok(l) = p.layer_mut(id) { - let mode = if l.is_group() { texturecraft_core::BlendMode::Passthrough } else { texturecraft_core::BlendMode::Normal }; - l.channels.retain(|c, _| wanted.contains(c)); - for c in &wanted { - l.channels.entry(*c).or_insert(ChannelBlend { mode, opacity: 1.0 }); + + for (id, _) in project.walk(set_index) { + if let Ok(layer) = project.layer_mut(id) { + let mode = if layer.is_group() { texturecraft_core::BlendMode::Passthrough } else { texturecraft_core::BlendMode::Normal }; + layer.channels.retain(|channel, _| template.channels.iter().any(|(wanted, _)| channel == wanted)); + for &(channel, _) in &template.channels { + layer.channels.entry(channel).or_insert(ChannelBlend { mode, opacity: 1.0 }); } } } } + self.touched(); self.modified = false; } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index e4f3f276..9d102c13 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -1,7 +1,7 @@ //! Edit, viewport and display commands. use serde_json::{Value, json}; -use texturecraft_core::project::ENVIRONMENTS; +use texturecraft_core::project::{ENVIRONMENTS, MAX_INDEX_OF_REFRACTION, MIN_INDEX_OF_REFRACTION}; use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping}; use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p, vec3}; @@ -314,7 +314,8 @@ 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; - let (old_ior, old_ior_specular, old_spec_gloss) = (settings.ior, settings.ior_specular, settings.spec_gloss); + let (ior_before, ior_specular_before, spec_gloss_before) = (settings.ior, settings.ior_specular, settings.spec_gloss); + if let Some(picked) = environment { settings.environment = picked; } @@ -330,7 +331,7 @@ fn display(s: &mut Session, p: &Value) -> Result { ("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), + ("ior", &mut settings.ior, MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION), ("shadowOpacity", &mut settings.shadow_opacity, 0.0, 1.0), ] { if let Some(value) = f32p(p, key) { @@ -378,8 +379,9 @@ fn display(s: &mut Session, p: &Value) -> Result { } } - let settings = &s.doc.project.display; - s.modified |= settings.ior_specular != old_ior_specular || (settings.ior_specular && (settings.ior != old_ior || settings.spec_gloss != old_spec_gloss)); + let saved_settings_changed = + settings.ior_specular != ior_specular_before || (settings.ior_specular && (settings.ior != ior_before || settings.spec_gloss != spec_gloss_before)); + // The field of view applies to the view only when set (a saved camera keeps its own) if f32p(p, "fov").is_some() { s.camera.fov = s.doc.project.display.fov; @@ -392,7 +394,12 @@ fn display(s: &mut Session, p: &Value) -> Result { cache.invalidate_all(); } } - s.revision = s.revision.wrapping_add(1); + if saved_settings_changed { + s.mark_modified(); + } else { + s.revision = s.revision.wrapping_add(1); + } + Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null)) } diff --git a/crates/engine/tests/it/ior_specular.rs b/crates/engine/tests/it/ior_specular.rs index 8422abf7..239e6c0e 100644 --- a/crates/engine/tests/it/ior_specular.rs +++ b/crates/engine/tests/it/ior_specular.rs @@ -40,6 +40,26 @@ fn the_opt_in_survives_save_and_reopen() { assert_eq!(display.ior, IOR); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_older_save_cannot_clear_ior_specular_changes() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("ior.tcraft"); + + for params in [json!({"iorSpecular": false}), json!({"ior": 2.0}), json!({"specGloss": true})] { + let mut session = session(); + opt_in(&mut session); + let save = session.save_task(path.to_str().unwrap(), true); + + execute(&mut session, "display.set", ¶ms).unwrap(); + save.run(None).unwrap().apply(&mut session); + + assert!(session.modified, "the archive predates the edit {params}"); + let archived = texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap(); + assert_ne!(archived.doc.project.display, session.doc.project.display); + } +} + #[test] fn a_project_saved_before_the_setting_opens_with_it_off() { let mut session = session(); diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 50ab5f5c..5d092a0f 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -349,8 +349,8 @@ impl GpuTracer { }; let same_geometry = self.geometry.as_ref().is_some_and(|g| Arc::ptr_eq(&g.mesh, &scene.mesh) && g.tri_set == scene.tri_set); if !same_geometry { - let nodes: Vec<(Vec3, Vec3, u32, u32)> = scene.bvh.nodes().collect(); - if bvh_depth(&nodes).is_none_or(|d| d >= STACK) { + let depth = bvh_depth(&scene.bvh.nodes().collect::>()); + if depth.is_none_or(|depth| depth >= STACK) { return Err("the mesh's BVH is too deep for GPU traversal".into()); } @@ -368,24 +368,23 @@ impl GpuTracer { })?); self.bind = None; } + if !self.env.as_ref().is_some_and(|e| Arc::ptr_eq(&e.image, &scene.env)) { let img = &scene.env; let (w, h) = (img.width as usize, img.height as usize); - let valid = w > 0 && h > 0 && img.data.len() >= w * h && img.width.max(img.height) <= limits.max_texture_dimension_2d; - let (tw, th, rgba): (u32, u32, Vec<[f32; 4]>) = - if valid { (img.width, img.height, img.data.iter().take(w * h).map(|c| [c[0], c[1], c[2], 1.0]).collect()) } else { (1, 1, vec![[0.0; 4]]) }; - let mut cdf = Vec::new(); - if let Some(l) = scene.light.as_ref().filter(|l| valid && l.width == w && l.height == h) { - cdf.extend_from_slice(&l.rows); - cdf.extend_from_slice(&l.cols); - cdf.extend_from_slice(&l.prob); - } - fits("environment table", cdf.len() * 4)?; - let light = !cdf.is_empty(); - if !light { - cdf.push(0.0); - } + let valid = w > 0 && h > 0 && img.width.max(img.height) <= limits.max_texture_dimension_2d && img.data.len() >= w * h; + let sampler = scene.light.as_ref().filter(|table| valid && table.width == w && table.height == h); + + // The shader binds one zero when importance sampling is disabled + let parts = sampler.map_or([&[0.0][..], &[], &[]], |table| [table.rows.as_slice(), table.cols.as_slice(), table.prob.as_slice()]); + fits("environment table", parts.iter().map(|part| std::mem::size_of_val(*part)).sum())?; + let env = scoped(device, "GPU path tracing: environment upload", || { + let (tw, th, rgba): (u32, u32, Vec<[f32; 4]>) = if valid { + (img.width, img.height, img.data.iter().take(w * h).map(|c| [c[0], c[1], c[2], 1.0]).collect()) + } else { + (1, 1, vec![[0.0; 4]]) + }; let tex = device.create_texture_with_data( queue, &wgpu::TextureDescriptor { @@ -401,16 +400,19 @@ impl GpuTracer { wgpu::util::TextureDataOrder::LayerMajor, bytemuck::cast_slice(&rgba), ); + drop(rgba); + EnvGpu { image: scene.env.clone(), view: tex.create_view(&Default::default()), - cdf: buffer(device, "tc_trace_cdf", bytemuck::cast_slice(&cdf)), - light, + cdf: buffer(device, "tc_trace_cdf", bytemuck::cast_slice(&parts.concat())), + light: sampler.is_some(), } })?; self.env = Some(env); self.bind = None; } + self.scene = Some(SceneConst { spec_gloss: scene.spec_gloss, eps: scene.eps, diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index dcb43583..490ed2d5 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -430,6 +430,9 @@ const UV_CHECKER_FINE_CELLS: f32 = 256.0; // Offset alpha dithering between accumulated frames const DITHER_FRAME_STEP: vec2 = vec2(17.0, 59.0); +// Lit single-channel views keep the legacy specular level multiplier +const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; + fn shade_mesh(i: VOut, front: bool) -> Shaded { var n_geo = normalize(i.nrm); if (!front) { @@ -548,7 +551,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let rough = clamp(orm.g, SPECULAR_ROUGHNESS_FLOOR, 1.0); let metal = orm.b; let nov = clamp(abs(dot(n, v)), GRAZING_COSINE_FLOOR, 1.0); - let dielectric_f0_scale = select(g.refr.w, 0.08, solo_lit); + let dielectric_f0_scale = select(g.refr.w, LEGACY_DIELECTRIC_F0_SCALE, solo_lit); var f0 = mix(vec3(dielectric_f0_scale * orm.a), albedo, metal); var diffuse_col = albedo * (1.0 - metal); if (g.material.x > 0.5 && !solo_lit) { diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index a70e09cd..a3f2780c 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -205,16 +205,22 @@ impl EnvSampler { if w == 0 || h == 0 || env.data.len() < w * h { return None; } - let mut weight: Vec = env.data.iter().take(w * h).map(|c| luminance(Vec3::from(*c)).max(0.0)).collect(); - for (y, row) in weight.chunks_mut(w).enumerate() { + + let mut prob: Vec = env.data.iter().take(w * h).map(|c| luminance(Vec3::from(*c)).max(0.0)).collect(); + for (y, row) in prob.chunks_mut(w).enumerate() { let sin = (PI * (y as f32 + 0.5) / h as f32).sin(); row.iter_mut().for_each(|v| *v = (*v + 1e-4) * sin); } - let total: f32 = weight.iter().sum(); + + let total: f32 = prob.iter().sum(); if !total.is_finite() || total <= 0.0 { return None; } - let prob: Vec = weight.iter().map(|v| v / total).collect(); + + for probability in &mut prob { + *probability /= total; + } + let mut rows = Vec::with_capacity(h); let mut cols = Vec::with_capacity(w * h); let mut acc_rows = 0.0; @@ -228,6 +234,7 @@ impl EnvSampler { cols.push(acc); } } + Some(EnvSampler { width: w, height: h, rows, cols, prob }) } @@ -543,100 +550,115 @@ fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) - u * t.z).normalize_or(Vec3::Z) } -fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f32) -> Option { - let m = &scene.mesh; - let i = tri as usize * 3; - let idx = [*m.indices.get(i)? as usize, *m.indices.get(i + 1)? as usize, *m.indices.get(i + 2)? as usize]; - let p = idx.map(|k| m.positions.get(k).copied().unwrap_or(Vec3::ZERO)); - let mut geo = (p[1] - p[0]).cross(p[2] - p[0]).normalize_or(Vec3::Y); - let nrm = idx.map(|k| m.normals.get(k).copied().unwrap_or(geo)); - let mut n_geo = lerp3(nrm[0], nrm[1], nrm[2], u, v).normalize_or(geo); - let front = geo.dot(d) <= 0.0; +fn surface(scene: &TraceScene, triangle: u32, u: f32, v: f32, origin: Vec3, direction: Vec3, distance: f32) -> Option { + // Match the minimum roughness in the GPU tracer + const SPECULAR_ROUGHNESS_FLOOR: f32 = 0.045; + const SHEEN_ROUGHNESS_FLOOR: f32 = 0.07; + const HEIGHT_SLOPE_UV_DIVISOR: f32 = 16.0; + + let mesh = &scene.mesh; + let first_index = triangle as usize * 3; + let indices = [*mesh.indices.get(first_index)? as usize, *mesh.indices.get(first_index + 1)? as usize, *mesh.indices.get(first_index + 2)? as usize]; + let points = indices.map(|index| mesh.positions.get(index).copied().unwrap_or(Vec3::ZERO)); + let mut geo = (points[1] - points[0]).cross(points[2] - points[0]).normalize_or(Vec3::Y); + let normals = indices.map(|index| mesh.normals.get(index).copied().unwrap_or(geo)); + let mut interpolated_normal = lerp3(normals[0], normals[1], normals[2], u, v).normalize_or(geo); + + let front = geo.dot(direction) <= 0.0; if !front { geo = -geo; } - if n_geo.dot(geo) < 0.0 { - n_geo = -n_geo; + if interpolated_normal.dot(geo) < 0.0 { + interpolated_normal = -interpolated_normal; } - let uvs = idx.map(|k| m.uvs.get(k).copied().unwrap_or(Vec2::ZERO)); - let uv = uvs[0] * (1.0 - u - v) + uvs[1] * u + uvs[2] * v; - let tan = idx.map(|k| m.tangents.get(k).copied().unwrap_or(texturecraft_geom::glam::Vec4::X)); - let tw = lerp3(tan[0].truncate(), tan[1].truncate(), tan[2].truncate(), u, v); - let sign = if tan[0].w < 0.0 { -1.0 } else { 1.0 }; - let set = scene.tri_set.get(tri as usize).and_then(|s| scene.sets.get(*s)); - // The composite texel at offset (dx, dy) from the hit. - let texel = |s: &TraceSet, dx: i32, dy: i32| { - let (w, h) = (s.composite.resolution.max(1) as i32, s.composite.height.max(1) as i32); - (((uv.x * w as f32).floor() as i32 + dx).rem_euclid(w) as u32, ((uv.y * h as f32).floor() as i32 + dy).rem_euclid(h) as u32) - }; - let ch = |c: Channel, dx: i32, dy: i32| -> [f32; 3] { - let Some(s) = set else { return c.default_value() }; - let (x, y) = texel(s, dx, dy); - s.composite.value(c, x, y) - }; - let base = Vec3::from(ch(Channel::BaseColor, 0, 0)); - // A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink. - let k = set.map_or(0.0, |s| { - let (x, y) = texel(s, 0, 0); - s.height_strength * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) + let uvs = indices.map(|index| mesh.uvs.get(index).copied().unwrap_or(Vec2::ZERO)); + let uv = uvs[0] * (1.0 - u - v) + uvs[1] * u + uvs[2] * v; + let tangents = indices.map(|index| mesh.tangents.get(index).copied().unwrap_or(texturecraft_geom::glam::Vec4::X)); + let mesh_tangent = lerp3(tangents[0].truncate(), tangents[1].truncate(), tangents[2].truncate(), u, v); + let sign = if tangents[0].w < 0.0 { -1.0 } else { 1.0 }; + + let surface_texel = scene.tri_set.get(triangle as usize).and_then(|index| scene.sets.get(*index)).map(|set| { + let width = set.composite.resolution.max(1); + let height = set.composite.height.max(1); + let x = ((uv.x * width as f32).floor() as i32).rem_euclid(width as i32) as u32; + let y = ((uv.y * height as f32).floor() as i32).rem_euclid(height as i32) as u32; + (set, [width, height], [x, y]) }); - let n_height = if k != 0.0 { - let h = |dx, dy| ch(Channel::Height, dx, dy)[0]; - Vec3::new(-(h(1, 0) - h(-1, 0)) * 0.5 * k, (h(0, 1) - h(0, -1)) * 0.5 * k, 1.0).normalize_or(Vec3::Z) - } else { - Vec3::Z - }; - let detail = (Vec3::from(ch(Channel::Normal, 0, 0)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); - let n_ts = rnm(n_height, detail); - let tt = (tw - n_geo * n_geo.dot(tw)).normalize_or(n_geo.any_orthonormal_vector()); - let b = n_geo.cross(tt) * sign; - let mut n = (tt * n_ts.x + b * n_ts.y + n_geo * n_ts.z).normalize_or(n_geo); - if n.dot(-d) <= 0.0 { - n = n_geo; + let sample_channel = |channel: Channel| surface_texel.map_or_else(|| channel.default_value(), |(set, _, [x, y])| set.composite.value(channel, x, y)); + let base = Vec3::from(sample_channel(Channel::BaseColor)); + + // A unit height across one sixteenth of the UV width tilts 45° + // A smaller tile reduces the number of texels across that span + let height_normal = surface_texel.map_or(Vec3::Z, |(set, [width, height], [x, y])| { + let strength = set.height_strength * set.composite.resolution as f32 / HEIGHT_SLOPE_UV_DIVISOR * set.composite.block_scales.at(x, y); + if strength == 0.0 { + return Vec3::Z; + } + + // Neighbors wrap independently across each axis + let previous = |position, size| if position == 0 { size - 1 } else { position - 1 }; + let next = |position, size| if position + 1 == size { 0 } else { position + 1 }; + let height_at = |x, y| set.composite.value(Channel::Height, x, y)[0]; + let slope_x = height_at(next(x, width), y) - height_at(previous(x, width), y); + let slope_y = height_at(x, next(y, height)) - height_at(x, previous(y, height)); + Vec3::new(-slope_x * 0.5 * strength, slope_y * 0.5 * strength, 1.0).normalize_or(Vec3::Z) + }); + + let detail = (Vec3::from(sample_channel(Channel::Normal)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); + let tangent_normal = rnm(height_normal, detail); + let base_tangent = (mesh_tangent - interpolated_normal * interpolated_normal.dot(mesh_tangent)).normalize_or(interpolated_normal.any_orthonormal_vector()); + let bitangent = interpolated_normal.cross(base_tangent) * sign; + let mut normal = + (base_tangent * tangent_normal.x + bitangent * tangent_normal.y + interpolated_normal * tangent_normal.z).normalize_or(interpolated_normal); + if normal.dot(-direction) <= 0.0 { + normal = interpolated_normal; } - let scalar = |c: Channel| ch(c, 0, 0)[0].clamp(0.0, 1.0); + + let scalar = |channel| sample_channel(channel)[0].clamp(0.0, 1.0); let (sin, cos) = (scalar(Channel::AnisotropyAngle) * PI).sin_cos(); - let turned = tt * cos + b * sin; - let tangent = (turned - n * n.dot(turned)).normalize_or(n.any_orthonormal_vector()); - // Glossiness replaces roughness wherever a set has it (as in the viewport). - let roughness = match set { - Some(s) if s.composite.channels.contains_key(&Channel::Glossiness) => 1.0 - ch(Channel::Glossiness, 0, 0)[0], - _ => ch(Channel::Roughness, 0, 0)[0], + let turned_tangent = base_tangent * cos + bitangent * sin; + let tangent = (turned_tangent - normal * normal.dot(turned_tangent)).normalize_or(normal.any_orthonormal_vector()); + + // Match the viewport's preference for Glossiness when both channels exist + let roughness = match surface_texel { + Some((set, _, _)) if set.composite.channels.contains_key(&Channel::Glossiness) => 1.0 - sample_channel(Channel::Glossiness)[0], + _ => sample_channel(Channel::Roughness)[0], }; let (diffuse, f0, metallic) = if scene.spec_gloss { - let f0 = Vec3::from(ch(Channel::Specular, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE); + let f0 = Vec3::from(sample_channel(Channel::Specular)).clamp(Vec3::ZERO, Vec3::ONE); (base * (1.0 - f0.max_element()), f0, 0.0) } else { - let metallic = ch(Channel::Metallic, 0, 0)[0].clamp(0.0, 1.0); - let level = ch(Channel::SpecularLevel, 0, 0)[0].clamp(0.0, 1.0); + let metallic = sample_channel(Channel::Metallic)[0].clamp(0.0, 1.0); + let level = sample_channel(Channel::SpecularLevel)[0].clamp(0.0, 1.0); (base * (1.0 - metallic), Vec3::splat(scene.dielectric_f0_scale * level).lerp(base, metallic), metallic) }; - let coat_base = if n_geo.dot(-d) > 0.0 { n_geo } else { geo }; - let coat_n = match set { - Some(s) if s.composite.channels.contains_key(&Channel::CoatNormal) => { - let c = (Vec3::from(ch(Channel::CoatNormal, 0, 0)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); - let turned = (tt * c.x + b * c.y + coat_base * c.z).normalize_or(coat_base); - if turned.dot(-d) > 0.0 { turned } else { coat_base } + let coat_base = if interpolated_normal.dot(-direction) > 0.0 { interpolated_normal } else { geo }; + let coat_n = match surface_texel { + Some((set, _, _)) if set.composite.channels.contains_key(&Channel::CoatNormal) => { + let detail = (Vec3::from(sample_channel(Channel::CoatNormal)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); + let tilted = (base_tangent * detail.x + bitangent * detail.y + coat_base * detail.z).normalize_or(coat_base); + if tilted.dot(-direction) > 0.0 { tilted } else { coat_base } } _ => coat_base, }; + Some(Surface { - pos: o + d * t, + pos: origin + direction * distance, geo, - n, + n: normal, tangent, diffuse, f0, - roughness: roughness.clamp(0.045, 1.0), - emissive: Vec3::from(ch(Channel::Emissive, 0, 0)), - opacity: ch(Channel::Opacity, 0, 0)[0].clamp(0.0, 1.0), + roughness: roughness.clamp(SPECULAR_ROUGHNESS_FLOOR, 1.0), + emissive: Vec3::from(sample_channel(Channel::Emissive)), + opacity: sample_channel(Channel::Opacity)[0].clamp(0.0, 1.0), anisotropy: scalar(Channel::AnisotropyLevel), coat: scalar(Channel::CoatWeight), - coat_roughness: scalar(Channel::CoatRoughness).max(0.045), + coat_roughness: scalar(Channel::CoatRoughness).max(SPECULAR_ROUGHNESS_FLOOR), coat_n, - sheen: Vec3::from(ch(Channel::SheenColor, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE) * scalar(Channel::SheenWeight), - sheen_roughness: scalar(Channel::SheenRoughness).max(0.07), + sheen: Vec3::from(sample_channel(Channel::SheenColor)).clamp(Vec3::ZERO, Vec3::ONE) * scalar(Channel::SheenWeight), + sheen_roughness: scalar(Channel::SheenRoughness).max(SHEEN_ROUGHNESS_FLOOR), scatter: scalar(Channel::ScatterWeight), transmission: scalar(Channel::Transmission) * (1.0 - metallic), base: base.clamp(Vec3::ZERO, Vec3::ONE), @@ -1465,6 +1487,24 @@ mod tests { surface(&scene, hit.tri, hit.u, hit.v, origin, direction, hit.t).unwrap().f0 } + #[test] + fn height_normals_sample_across_both_texture_edges() { + let mut mesh = primitives::plane(1.0, 1); + mesh.uvs.fill(Vec2::ZERO); + let mesh = Arc::new(mesh); + let bvh = Arc::new(Bvh::new(&mesh)); + let mut composite = Composite::with_size(&[Channel::Height], 4, 5); + let height = composite.channels.get_mut(&Channel::Height).unwrap(); + height.set(3, 0, &[u16::MAX]); + height.set(0, 4, &[u16::MAX]); + let sets = vec![TraceSet { material: 0, composite, height_strength: 1.0 }]; + let scene = TraceScene::new(mesh, bvh, sets, Arc::new(crate::ibl::environment("Studio Soft", 8)), 0.0); + + let normal = surface(&scene, 0, 0.25, 0.25, Vec3::Y, Vec3::NEG_Y, 1.0).unwrap().n; + + assert!(normal.x.abs() > f32::EPSILON && normal.z.abs() > f32::EPSILON, "the opposite edges tilt both axes: {normal}"); + } + /// The F0 map a 32-bit float export writes for [`dielectric_composite`] under `display`. fn exported_f0(display: &DisplaySettings) -> f32 { use texturecraft_formats::{Dest, ExportInput, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap}; diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index cf72347a..1e7cd39e 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -2,7 +2,7 @@ use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as ic; -use texturecraft_engine::core::project::DisplaySettings; +use texturecraft_engine::core::project::{DisplaySettings, MAX_INDEX_OF_REFRACTION, MIN_INDEX_OF_REFRACTION}; use crate::TextureCraftApp; use crate::i18n::tr; @@ -52,7 +52,7 @@ const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; const SCATTER_SWATCH_WIDTH: f32 = 44.0; /// Index of refraction slider range: air to well past diamond (2.42) -const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = 1.0..=3.0; +const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = MIN_INDEX_OF_REFRACTION..=MAX_INDEX_OF_REFRACTION; /// Values the reference's panel shows for controls TextureCraft lacks const SCATTER_ANISOTROPY_SHOWN: f32 = 0.1; @@ -80,6 +80,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { app.session.doc.project.display = display; app.session.mark_modified(); } + if ior_specular != app.session.doc.project.display.ior_specular { app.run("display.set", serde_json::json!({"iorSpecular": ior_specular})); } @@ -153,9 +154,20 @@ fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings, ior_specular: & slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( "Controls how strongly transmissive surfaces bend light. When the checkbox below is on, it also controls dielectric reflectance.", )); - ui.add_enabled(!display.spec_gloss, egui::Checkbox::new(ior_specular, tr("Use IOR for specular reflection"))) - .on_hover_text(tr("Uses the index of refraction for dielectric reflectance at normal incidence. Specular level adjusts its strength.")) - .on_disabled_hover_text(tr("Specular Glossiness uses the Specular color channel for reflectance.")); + + ui.add_enabled_ui(!display.spec_gloss, |ui| { + let widgets = &mut ui.visuals_mut().widgets; + widgets.inactive.bg_stroke.color = tokens.text_dim; + widgets.hovered.bg_stroke.color = tokens.text; + widgets.active.bg_stroke.color = tokens.text_strong; + + ui.checkbox(ior_specular, tr("Use IOR for specular reflection")) + .on_hover_text(tr( + "Uses the index of refraction for dielectric reflectance at normal incidence. Specular level adjusts the surface reflection.", + )) + .on_disabled_hover_text(tr("Specular Glossiness uses the Specular color channel for reflectance.")); + }); + unavailable::checkbox(ui, false, tr("Enable specular color")); }); section(ui, "shader_transmission", tr("Transmission"), true, |ui| { diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 76962df4..9b1050ab 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -289,6 +289,70 @@ fn shader_settings_show_the_reference_rows_and_the_shader_choice() { assert!(harness.get_by_label(&tiles[1]).accesskit_node().is_disabled(), "the others are not available yet"); } +#[test] +fn the_unchecked_ior_control_is_visible_at_each_brightness() { + use craft_theme::{Contrast, Rgba, contrast_ratio, non_text_contrast_min}; + use texturecraft_ui_egui::theme::{Brightness, Tokens}; + + let mut harness = app(); + click_rail(&mut harness, "Shader Settings"); + let minimum_contrast = non_text_contrast_min(Contrast::Standard); + + for brightness in Brightness::ALL { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(SETTLE_FRAMES); + + let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Use IOR for specular reflection"); + let bounds = checkbox.rect(); + let panel = Tokens::get(&harness.ctx).panel; + let indicator = harness + .output() + .shapes + .iter() + .filter_map(|painted| match &painted.shape { + egui::Shape::Rect(frame) if painted.clip_rect.contains_rect(frame.rect) && bounds.contains_rect(frame.rect) => Some(frame), + _ => None, + }) + .find(|frame| frame.fill.a() > 0 || !frame.stroke.is_empty()) + .expect("the unchecked indicator is painted inside its accessibility bounds"); + let fill = panel.blend(indicator.fill); + let outline = if indicator.stroke.width > 0.0 { fill.blend(indicator.stroke.color) } else { fill }; + let contrast = |color: egui::Color32| contrast_ratio(Rgba(color.to_array()), Rgba(panel.to_array())); + let ratio = contrast(fill).max(contrast(outline)); + + assert!(ratio >= minimum_contrast, "{brightness:?}: the unchecked box has {ratio:.2}:1 contrast against the panel"); + } +} + +#[test] +fn keyboard_toggles_ior_reflectance_only_in_metallic_roughness() { + let mut harness = app(); + let label = "Use IOR for specular reflection"; + harness.state_mut().ui.dock.focus(Panel::Shader); + harness.state_mut().session.modified = false; + harness.run_steps(SETTLE_FRAMES); + let checkbox = harness.get_by_role_and_label(Role::CheckBox, label); + assert_eq!(checkbox.accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); + checkbox.focus(); + harness.run_steps(SETTLE_FRAMES); + + harness.key_press(egui::Key::Space); + harness.run_steps(SETTLE_FRAMES); + + let checkbox = harness.get_by_role_and_label(Role::CheckBox, label); + assert!(checkbox.is_focused()); + assert!(is_on(&checkbox)); + assert!(harness.state().session.doc.project.display.ior_specular); + assert!(harness.state().session.modified); + + harness.state_mut().run("display.set", serde_json::json!({"specGloss": true})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + + let checkbox = harness.get_by_role_and_label(Role::CheckBox, label); + assert!(checkbox.accesskit_node().is_disabled()); + assert!(is_on(&checkbox), "the current preference is retained"); +} + #[test] fn a_shader_edit_marks_the_project_modified() { let mut harness = app(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 14114cb7..88fdb5a3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -634,8 +634,10 @@ None is an undo step. `display.set` also takes `alignment` (`world` or `camera`: the environment, and the key light with it, turns with the camera about the vertical axis), `shadowMode` (`intensive`, `average` or `lightweight`, the default: the shadow map's resolution) and `shadowOpacity` (0 to 1, default 1: how dark the shadows are). -Set `iorSpecular` to true to use `ior` for dielectric reflectance at normal incidence in the -Metallic Roughness model. The setting defaults to false and is saved with the project and its templates. +Set `iorSpecular` to true to derive the Metallic Roughness surface reflectance at normal incidence +from `ior` (clamped to 1–3). Specular Level scales this reflectance in the viewport, both path +tracers and F0 map export. Path-traced transmission uses its own Fresnel calculation for glass +interfaces. The setting defaults to false and is saved with the project and its templates. `viewport.view {mode: "image", image: }` shows a project image as it is, stretched over the UV square, on the mesh and in the 2D view (the view picker's "Other..."). `display.set {soloUnlit}` From 3f38644c9145044126514f265f2230b8a69ae74d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:49:58 +0000 Subject: [PATCH 52/80] Dock the Baking Log at the bottom of the bake layout The default bake layout put the general Log under the settings columns; the Baking Log now takes that place (the Log stays in Window > Views). The bake layout version moves to 3 so saved bake docks pick up the new layout. --- crates/ui-egui/src/docking.rs | 10 +++++----- crates/ui-egui/src/state.rs | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 6c4f5f97..85edb126 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -308,7 +308,7 @@ impl Dock { self.replaced_unreadable } - /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport + /// Texture sets over the bakers, the two settings tabs, the Baking Log under both, then the viewport pub(crate) fn for_baking() -> Self { let painting = default_workspace(); let mut hidden = painting.hidden().to_vec(); @@ -318,14 +318,14 @@ impl Dock { } } - let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; + let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::BakingLog]; hidden.retain(|(panel, _)| !bake_panels.contains(panel)); let gutter_width = f32::from(crate::theme::GUTTER); let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); let columns = split(Axis::X, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); - let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::BakingLog])); let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec()); @@ -759,12 +759,12 @@ mod tests { } #[test] - fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { + fn the_bake_dock_round_trips_with_the_baking_log_under_both_settings_columns() { let dock = Dock::for_baking(); assert!(validate(dock.workspace()).is_ok()); assert_eq!( panels_of(dock.workspace()), - [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::Log, Panel::Viewport] + [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::BakingLog, Panel::Viewport] ); assert!(dock.is_visible(Panel::CommonSettings) && !dock.is_visible(Panel::MeshMapSettings)); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 54daa752..ff897d80 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -543,7 +543,7 @@ fn default_true() -> bool { } /// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` -const BAKE_LAYOUT_VERSION: u32 = 2; +const BAKE_LAYOUT_VERSION: u32 = 3; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { @@ -1018,6 +1018,24 @@ mod tests { } } + #[test] + fn a_saved_bake_dock_with_the_log_at_the_bottom_gets_the_baking_log_there() { + use crate::docking::Panel; + + let mut ui = UiState { mode: Mode::Baking, ..UiState::default() }; + ui.sync_mode_dock(); + ui.dock.close(Panel::BakingLog); + ui.dock.focus(Panel::Log); + let mut saved = serde_json::to_value(&ui).unwrap(); + saved["bake_layout_version"] = serde_json::json!(2); + + let mut loaded: UiState = serde_json::from_value(saved).unwrap(); + loaded.sync_mode_dock(); + + assert!(loaded.dock.is_visible(Panel::BakingLog), "the Baking Log takes the bottom of the bake layout"); + assert!(!loaded.dock.is_open(Panel::Log), "the general Log stays in Window > Views"); + } + #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { From 03600e447a7c1a0338d14f9da293ab54e4714fb7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:52:36 +0000 Subject: [PATCH 53/80] Record each bake map by map for the Baking Log The session keeps the latest bake as one row per texture set and map (waiting, baking, baked, failed, canceled), filled from the bake's own state by the app's background bake and by bake.run, never from Log lines. --- crates/engine/src/bake/bake_log.rs | 81 ++++++++++++++++++++++ crates/engine/src/bake/bake_log_map.rs | 15 ++++ crates/engine/src/bake/bake_map_state.rs | 26 +++++++ crates/engine/src/bake/mesh_map_command.rs | 34 +++++++-- crates/engine/src/bake/mod.rs | 6 ++ crates/engine/src/session.rs | 3 + crates/engine/tests/it/bake_log.rs | 50 +++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/lib.rs | 11 ++- 9 files changed, 220 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/bake/bake_log.rs create mode 100644 crates/engine/src/bake/bake_log_map.rs create mode 100644 crates/engine/src/bake/bake_map_state.rs create mode 100644 crates/engine/tests/it/bake_log.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs new file mode 100644 index 00000000..2f263cf2 --- /dev/null +++ b/crates/engine/src/bake/bake_log.rs @@ -0,0 +1,81 @@ +use serde::Serialize; +use texturecraft_core::{BakedMap, Project}; + +use super::{BakeLogMap, BakeMapState}; + +/// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct BakeLog { + pub maps: Vec, +} + +impl BakeLog { + /// Start over for a bake of `sets`: every checked map of each set, waiting, in bake order + pub fn begin(&mut self, project: &Project, sets: &[usize]) { + self.maps = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .flat_map(|(index, set)| { + set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting }) + }) + .collect(); + } + + /// `set` starts baking: its first map is the one in progress + pub fn set_started(&mut self, set: usize) { + self.start_next(set); + } + + /// `map` of `set` is baked; the set's next map starts + pub fn map_baked(&mut self, set: usize, map: BakedMap) { + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) { + row.state = BakeMapState::Baked; + } + self.start_next(set); + } + + /// `set`'s bake was kept: a map it did not hand over is not baked + pub fn set_finished(&mut self, set: usize) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) { + row.state = BakeMapState::Canceled; + } + } + + /// Nothing of `set` was kept: every one of its maps failed for `reason` + pub fn set_failed(&mut self, set: usize, reason: &str) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set) { + row.state = BakeMapState::Failed(reason.to_owned()); + } + } + + /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled + pub fn cancel(&mut self, current: Option) { + for row in &mut self.maps { + if row.state.is_pending() || (Some(row.texture_set) == current && row.state == BakeMapState::Baked) { + row.state = BakeMapState::Canceled; + } + } + } + + /// The whole bake was rolled back: every map that did not fail is canceled + pub fn discard(&mut self) { + for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) { + row.state = BakeMapState::Canceled; + } + } + + /// Whether a map is still waiting or baking + pub fn is_running(&self) -> bool { + self.maps.iter().any(|row| row.state.is_pending()) + } + + fn start_next(&mut self, set: usize) { + if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) { + return; + } + + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.state == BakeMapState::Waiting) { + row.state = BakeMapState::Baking; + } + } +} diff --git a/crates/engine/src/bake/bake_log_map.rs b/crates/engine/src/bake/bake_log_map.rs new file mode 100644 index 00000000..4a04bd7d --- /dev/null +++ b/crates/engine/src/bake/bake_log_map.rs @@ -0,0 +1,15 @@ +use serde::Serialize; +use texturecraft_core::BakedMap; + +use super::BakeMapState; + +/// One row of the Baking Log's process list: a map of a texture set in the latest bake +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeLogMap { + pub texture_set: usize, + pub set_name: String, + pub map: BakedMap, + #[serde(flatten)] + pub state: BakeMapState, +} diff --git a/crates/engine/src/bake/bake_map_state.rs b/crates/engine/src/bake/bake_map_state.rs new file mode 100644 index 00000000..fec7583b --- /dev/null +++ b/crates/engine/src/bake/bake_map_state.rs @@ -0,0 +1,26 @@ +use serde::Serialize; + +/// Where one map of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeMapState { + Waiting, + Baking, + Baked, + /// The bake of its texture set failed; the reason is the error + Failed(String), + /// The bake stopped before this map was kept + Canceled, +} + +impl BakeMapState { + /// Whether the map can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Baking) + } + + /// Whether the map counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 844c533a..a76561fb 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,16 +843,21 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } + session.bake_log.begin(&session.doc.project, &sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { - let mut task = session.bake_task(index)?; - if cpu { - task.tracer = None; + session.bake_log.set_started(index); + let baked = bake_one_set(session, index, cpu); + match baked { + Ok(tracer) => tracers.push(tracer), + Err(error) => { + session.bake_log.set_failed(index, &error.to_string()); + // The edit rolls back the sets baked before this one too + session.bake_log.discard(); + return Err(error); + } } - let output = task.run(&Progress::new())?; - tracers.push(output.tracer.clone()); - session.store_bake(index, output)?; } Ok(tracers) })?; @@ -863,6 +868,23 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { Ok(json!({ "baked": sets, "tracer": tracers })) } +/// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log +fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result { + let mut task = session.bake_task(index)?; + if cpu { + task.tracer = None; + } + + let maps = task.maps(); + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + session.store_bake(index, output)?; + for map in maps { + session.bake_log.map_baked(index, map); + } + Ok(tracer) +} + #[cfg(test)] mod named_tracer; diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 1be548db..736b00bb 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -2,6 +2,9 @@ mod bake_cage_inputs; mod bake_checks; +mod bake_log; +mod bake_log_map; +mod bake_map_state; mod bake_mesh; mod bake_meshes; mod bake_task; @@ -19,6 +22,9 @@ mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; +pub use bake_log::BakeLog; +pub use bake_log_map::BakeLogMap; +pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e1d83ead..f0a8df58 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -451,6 +451,8 @@ pub struct Session { pub solo: Option, /// The live bake preview while the app bakes (see [`crate::bake_preview`]). pub bake_preview: Option, + /// The latest bake, map by map (the Baking Log) + pub bake_log: crate::bake::BakeLog, /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, @@ -543,6 +545,7 @@ impl Session { view_image: None, solo: None, bake_preview: None, + bake_log: Default::default(), viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs new file mode 100644 index 00000000..965295e1 --- /dev/null +++ b/crates/engine/tests/it/bake_log.rs @@ -0,0 +1,50 @@ +//! The Baking Log's record of the latest bake, map by map + +use std::collections::BTreeSet; + +use serde_json::json; +use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute, sample_session}; + +#[test] +fn bake_run_lists_every_checked_map_of_the_set_as_baked() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let set_name = &session.doc.project.texture_sets[0].name; + let rows = &session.bake_log.maps; + let maps: BTreeSet = rows.iter().map(|row| row.map).collect(); + assert_eq!(maps, BTreeSet::from([BakedMap::Position, BakedMap::Opacity])); + assert!(rows.iter().all(|row| row.state == BakeMapState::Baked && &row.set_name == set_name), "{rows:?}"); + assert!(!session.bake_log.is_running()); +} + +#[test] +fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { + let mut session = sample_session(256, 64).unwrap(); + for set in &mut session.doc.project.texture_sets { + set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]); + } + let log = &mut session.bake_log; + log.begin(&session.doc.project, &[0, 1]); + + log.set_started(0); + log.map_baked(0, BakedMap::Normal); + log.map_baked(0, BakedMap::Curvature); + log.set_finished(0); + log.set_started(1); + log.map_baked(1, BakedMap::Normal); + let baking: Vec<_> = log.maps.iter().filter(|row| row.state == BakeMapState::Baking).map(|row| (row.texture_set, row.map)).collect(); + assert_eq!(baking, [(1, BakedMap::Curvature)], "the next map of the running set is the one in progress"); + + log.cancel(Some(1)); + + let state_of = |set: usize| log.maps.iter().filter(move |row| row.texture_set == set).map(|row| row.state.clone()).collect::>(); + assert!(state_of(0).iter().all(|state| *state == BakeMapState::Baked), "{:?}", log.maps); + assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps); + assert!(!log.is_running()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b1879df3..11b199c9 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,6 +4,7 @@ mod add_mask_items; mod bake; mod bake_checks; +mod bake_log; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9f0b6d70..16cbee1e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -706,6 +706,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); + self.session.bake_log.begin(&self.session.doc.project, &sets); 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, only }); } @@ -824,6 +825,7 @@ impl TextureCraftApp { if let Some(running) = &job.current { running.progress.cancel.store(true, Ordering::Relaxed); } + self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); self.bake = None; return; } @@ -835,6 +837,7 @@ impl TextureCraftApp { // Wait for the sender to close so the last map also gets a preview frame match running.maps.try_recv() { Ok(map) => { + self.session.bake_log.map_baked(set_index, map.map); self.session.bake_preview_map(set_index, map); return; } @@ -848,7 +851,10 @@ impl TextureCraftApp { job.current = None; match self.session.apply_streamed_bake(set_index, output) { - Ok(()) => self.bake_report.map_count += maps_baked, + Ok(()) => { + self.session.bake_log.set_finished(set_index); + self.bake_report.map_count += maps_baked; + } Err(error) => self.bake_failed(set_index, &error.to_string()), } } @@ -882,6 +888,7 @@ impl TextureCraftApp { let only = job.only; self.session.bake_preview_set_current(set_index); + self.session.bake_log.set_started(set_index); let task = match only { Some(map) => self.session.bake_task_only(set_index, map), None => self.session.bake_task(set_index), @@ -914,6 +921,7 @@ impl TextureCraftApp { /// Note a texture set whose bake failed: one Log line, counted in the summary fn bake_failed(&mut self, set_index: usize, error: &str) { self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}")); + self.session.bake_log.set_failed(set_index, error); self.bake_report.failed_set_count += 1; } @@ -937,6 +945,7 @@ impl TextureCraftApp { pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; + self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); if let Some(running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); } From e24f4e28d89abc09bb654a701ae880e6b31e2302 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:55:44 +0000 Subject: [PATCH 54/80] Show the latest bake in the Baking Log's tabs The Baking Log gets the three tabs from the issue's mock-ups (Baking Process, High Poly Parameters, Matching by Name) in the Properties section-tab look. Baking Process lists one row per texture set and map: a tick when baked, orange dots and bold for the map being baked (kept in view), dim while waiting, a red cross or a warning when not kept, with the reason on hover. The tab's icon turns into orange dots while a bake runs. --- crates/ui-egui/src/baking_log.rs | 146 ++++++++++++++++++ .../ui-egui/src/baking_log/baking_log_tab.rs | 36 +++++ crates/ui-egui/src/docking.rs | 8 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/property_sheet/mod.rs | 3 +- .../src/property_sheet/section_tabs.rs | 2 +- .../src/property_sheet/switch_control.rs | 2 +- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/it/baking_log.rs | 60 +++++++ crates/ui-egui/tests/it/main.rs | 1 + 10 files changed, 253 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/baking_log.rs create mode 100644 crates/ui-egui/src/baking_log/baking_log_tab.rs create mode 100644 crates/ui-egui/tests/it/baking_log.rs diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs new file mode 100644 index 00000000..bacf194e --- /dev/null +++ b/crates/ui-egui/src/baking_log.rs @@ -0,0 +1,146 @@ +//! The Baking Log panel: the latest bake under three tabs, read from the session's bake record + +use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr}; +use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box}; +use crate::theme::{Tokens, semibold}; + +mod baking_log_tab; + +pub use baking_log_tab::BakingLogTab; + +/// Height of the tab strip, as the Properties section tabs +const STRIP_HEIGHT: f32 = 30.0; + +/// How far the first tab reaches left of the rows' side padding, as the Properties section tabs +const FIRST_TAB_OUTDENT: f32 = 4.0; + +/// Height of one row of a list +const ROW_HEIGHT: f32 = 24.0; + +/// Air above the first row +const LIST_TOP: f32 = 4.0; + +/// How far a hovered row's fill stays inside the panel's sides +const HOVER_INSET: f32 = 3.0; + +/// From the panel's left edge to a row's glyph centre, and to its name +const GLYPH_CENTER: f32 = SIDE_PADDING_POINTS + 6.0; +const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0; + +/// Size of a row's glyph and of its name +const GLYPH_SIZE: f32 = 13.0; +const NAME_SIZE: f32 = 12.0; + +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let running = app.session.bake_log.is_running(); + if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { + app.ui.baking_log_tab = tab; + } + + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.add_space(LIST_TOP); + if app.ui.baking_log_tab == BakingLogTab::BakingProcess { + baking_process(ui, &app.session.bake_log.maps); + } + }); +} + +/// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); + + let mut picked = None; + let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; + for tab in BakingLogTab::ALL { + let name = tr(tab.name()); + let on = tab == shown; + let width = ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING; + 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(("baking_log_tab", tab)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); + if response.clicked() { + picked = Some(tab); + } + + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, rect); + } + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let in_progress = running && tab == BakingLogTab::BakingProcess; + let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); + } + + left += width + TAB_GAP; + } + picked +} + +/// One row per texture set and map, in bake order; the map being baked stays in view +fn baking_process(ui: &mut Ui, maps: &[BakeLogMap]) { + let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); + let follow_id = Id::unique("baking_log_followed_map"); + let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); + ui.data_mut(|data| data.insert_temp(follow_id, followed)); + + for (index, row) in maps.iter().enumerate() { + let rect = map_row(ui, row); + if newly_followed && followed == Some(index) { + ui.scroll_to_rect(rect, None); + } + } +} + +/// A map's row: its state's glyph, then " "; a map that was not baked tells why on hover +fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map))); + let (glyph, glyph_color, state) = match &row.state { + BakeMapState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeMapState::Baking => (ic::DOTS_THREE, tokens.accent, tr("Baking")), + BakeMapState::Baked => (ic::CHECK, tokens.text, tr("Baked")), + BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")), + BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeMapState::Baking => (semibold(NAME_SIZE), tokens.text), + BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + + let reason = match &row.state { + BakeMapState::Failed(reason) => Some(reason.as_str()), + BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } + rect +} diff --git a/crates/ui-egui/src/baking_log/baking_log_tab.rs b/crates/ui-egui/src/baking_log/baking_log_tab.rs new file mode 100644 index 00000000..ccff71b0 --- /dev/null +++ b/crates/ui-egui/src/baking_log/baking_log_tab.rs @@ -0,0 +1,36 @@ +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::i18n::n_; + +/// The Baking Log panel's tabs +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum BakingLogTab { + /// Every map of the latest bake and how it went + #[default] + BakingProcess, + /// The high poly files each texture set bakes from + HighPolyParameters, + /// Which low poly part bakes from which high poly part + MatchingByName, +} + +impl BakingLogTab { + pub const ALL: [BakingLogTab; 3] = [BakingLogTab::BakingProcess, BakingLogTab::HighPolyParameters, BakingLogTab::MatchingByName]; + + pub fn name(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => n_("Baking Process"), + BakingLogTab::HighPolyParameters => n_("High Poly Parameters"), + BakingLogTab::MatchingByName => n_("Matching by Name"), + } + } + + pub(crate) fn icon(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => ic::LIST_CHECKS, + BakingLogTab::HighPolyParameters => ic::CUBE, + BakingLogTab::MatchingByName => ic::ARROWS_LEFT_RIGHT, + } + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 85edb126..f1acd9e7 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -612,13 +612,7 @@ 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::BakingLog => crate::baking_log::body(app, ui), 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/lib.rs b/crates/ui-egui/src/lib.rs index 16cbee1e..a786eef7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -14,6 +14,7 @@ mod ask; mod autosave_name; mod bake_job; pub mod bake_mode; +pub mod baking_log; mod bake_preset; pub mod bake_presets; mod bake_report; diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 51c6ecfb..def4354d 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -75,13 +75,14 @@ pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection}; pub(crate) use row_lead::RowLead; 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, in_scope, - room_past_end, section_tabs, + 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; pub(crate) use stacked_rows::{CHECK_SIZE, paint_check}; +pub(crate) use switch_control::paint_focus_outline; pub(crate) fn paint_keyboard_focus(ui: &egui::Ui, response: &egui::Response, tokens: &crate::theme::Tokens) { if response.has_focus() { diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 595116ca..754c3fd2 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -110,7 +110,7 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { } /// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip -fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { +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/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 8f700a6d..c6b8fa18 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -63,7 +63,7 @@ pub(super) fn untinted(_index: usize) -> &'static [Color32] { &[] } -pub(super) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { +pub(crate) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(FOCUS_OUTLINE_WIDTH, color), StrokeKind::Inside); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ff897d80..6afa5c9b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -681,6 +681,9 @@ pub struct UiState { /// The Log panel's shown channel tab #[serde(default)] pub log_channel: crate::log_panel::LogChannel, + /// The Baking Log panel's shown tab + #[serde(default)] + pub baking_log_tab: crate::baking_log::BakingLogTab, /// The project template the last New project was created from (name or label) #[serde(default)] pub last_template: String, @@ -844,6 +847,7 @@ impl Default for UiState { bake_preset_name: String::new(), layout_dialog: None, log_channel: crate::log_panel::LogChannel::default(), + baking_log_tab: crate::baking_log::BakingLogTab::default(), last_template: String::new(), log_selection: Default::default(), log_anchor: None, diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs new file mode 100644 index 00000000..c69c2fcc --- /dev/null +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -0,0 +1,60 @@ +//! The Baking Log panel: the latest bake, map by map + +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; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.select([BakedMap::Id, BakedMap::Position]); + } + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..4000 { + harness.run_steps(1); + if harness.state().bake.is_none() { + harness.run_steps(2); + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { + let mut harness = harness(); + { + // Set 1 has no tile left to bake, so its bake fails + let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; + set.uv_tiles = vec![1001]; + set.bake_excluded_tiles.insert(1001); + set.bake.maps.select([BakedMap::Id]); + } + assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log"); + + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(&mut harness); + + let names: Vec = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + for map in ["ID", "Position"] { + assert!(harness.query_by_label(&format!("{} {map}, Baked", names[0])).is_some(), "set 0's {map} row is ticked"); + } + assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0129eb7a..045d3d57 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -10,6 +10,7 @@ mod bake_mode; mod bake_presets; mod bake_reset_menus; mod bake_sync; +mod baking_log; mod brush_drag; mod brush_section_reset; mod camera_views; From d908c4a49e7d40a221ab5c4c666df43f2f137b96 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:04:36 +0000 Subject: [PATCH 55/80] Open a not-baked map's settings from its Baking Log row A failed or canceled row shows an arrow at its right end while hovered or focused; it makes the row's texture set active and shows the map in Mesh Map Settings, as picking it in Mesh Map Bakers does. --- crates/ui-egui/src/baking_log.rs | 85 ++++++++++++++++++++++----- crates/ui-egui/tests/it/baking_log.rs | 46 ++++++++++++--- 2 files changed, 107 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index bacf194e..7d59cd29 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -2,10 +2,13 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; +use serde_json::json; use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; -use crate::i18n::{baked_map_label, tr}; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr, trf}; use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box}; use crate::theme::{Tokens, semibold}; @@ -36,18 +39,43 @@ const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0; const GLYPH_SIZE: f32 = 13.0; const NAME_SIZE: f32 = 12.0; +/// Size of the open-settings arrow at an issue row's right end, and of the square it answers clicks in +const OPEN_ICON_SIZE: f32 = 14.0; +const OPEN_BUTTON_SIZE: f32 = 20.0; + pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let running = app.session.bake_log.is_running(); if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { app.ui.baking_log_tab = tab; } - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.add_space(LIST_TOP); - if app.ui.baking_log_tab == BakingLogTab::BakingProcess { - baking_process(ui, &app.session.bake_log.maps); - } - }); + let opened = egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_space(LIST_TOP); + match app.ui.baking_log_tab { + BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps), + _ => None, + } + }) + .inner; + if let Some((texture_set, map)) = opened { + open_map_settings(app, texture_set, map); + } +} + +/// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does +fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + // The set may have been deleted since the bake + if texture_set >= app.session.set_count() { + return; + } + + if texture_set != app.session.ts() { + app.run("textureSet.select", json!({ "ts": texture_set })); + } + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); } /// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon @@ -89,23 +117,28 @@ fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option Option<(usize, BakedMap)> { let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); let follow_id = Id::unique("baking_log_followed_map"); let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); ui.data_mut(|data| data.insert_temp(follow_id, followed)); + let mut opened = None; for (index, row) in maps.iter().enumerate() { - let rect = map_row(ui, row); + let (rect, open_clicked) = map_row(ui, row); if newly_followed && followed == Some(index) { ui.scroll_to_rect(rect, None); } + if open_clicked { + opened = Some((row.texture_set, row.map)); + } } + opened } -/// A map's row: its state's glyph, then " "; a map that was not baked tells why on hover -fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { +/// A map's row: glyph, then " "; a map not baked tells why on hover and has an arrow to its settings; returns the row and whether the arrow was clicked +fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { let tokens = Tokens::get(ui.ctx()); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map))); @@ -117,9 +150,11 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + let open = row.state.is_issue().then(|| open_settings_button(ui, rect, &name)); + let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); let painter = ui.painter(); - if response.hovered() { + if row_hovered { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); } let center_y = rect.center().y; @@ -129,7 +164,16 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), _ => (FontId::proportional(NAME_SIZE), tokens.text), }; - painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, &name, font, color); + if let Some(open) = &open + && (row_hovered || open.has_focus()) + { + let color = if open.hovered() || open.has_focus() { tokens.text } else { tokens.text_dim }; + painter.text(open.rect.center(), Align2::CENTER_CENTER, ic::ARROW_SQUARE_OUT, FontId::proportional(OPEN_ICON_SIZE), color); + if open.has_focus() { + crate::property_sheet::paint_focus_outline(painter, open.rect, tokens.text_strong); + } + } let reason = match &row.state { BakeMapState::Failed(reason) => Some(reason.as_str()), @@ -142,5 +186,16 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); }); } - rect + let open_clicked = open.is_some_and(|open| open.clicked()); + (rect, open_clicked) +} + +/// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus +fn open_settings_button(ui: &mut Ui, row: Rect, name: &str) -> egui::Response { + let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); + let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE)); + let label = trf("Open the {name} settings", &[("name", &name)]); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", name)), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); + response.on_hover_text(label) } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index c69c2fcc..d10d63cc 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -37,20 +37,23 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { panic!("the bake did not finish"); } +/// Bake sets 0 and 1, where set 1 has no tile left to bake, so its bake fails +fn bake_with_set_1_failing(harness: &mut Harness<'static, TextureCraftApp>, set_1_maps: &[BakedMap]) { + let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; + set.uv_tiles = vec![1001]; + set.bake_excluded_tiles.insert(1001); + set.bake.maps.select(set_1_maps.iter().copied()); + + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(harness); +} + #[test] fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { let mut harness = harness(); - { - // Set 1 has no tile left to bake, so its bake fails - let set = &mut harness.state_mut().session.doc.project.texture_sets[1]; - set.uv_tiles = vec![1001]; - set.bake_excluded_tiles.insert(1001); - set.bake.maps.select([BakedMap::Id]); - } assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log"); - harness.state_mut().start_bake(vec![0, 1]); - run_to_the_end(&mut harness); + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); let names: Vec = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); for map in ["ID", "Position"] { @@ -58,3 +61,28 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { } assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } + +#[test] +fn a_failed_maps_arrow_opens_its_settings() { + let mut harness = harness(); + + // Three rows fit the docked log without scrolling + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Id]); + bake_with_set_1_failing(&mut harness, &[BakedMap::Id, BakedMap::Position]); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + assert_eq!(harness.state().session.ts(), 0); + assert!(harness.query_by_label("Normalization Scale").is_none(), "Position's settings are not shown yet"); + + let set_name = harness.state().session.doc.project.texture_sets[1].name.clone(); + harness.get_by_label(&format!("Open the {set_name} Position settings")).click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.ts(), 1, "the failed map's texture set is the active one"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "the arrow fronts Mesh Map Settings"); + harness.get_by_label("Normalization Scale"); + assert!( + harness.query_by_label(&format!("Open the {} ID settings", harness.state().session.doc.project.texture_sets[0].name)).is_none(), + "a baked map has no arrow" + ); +} From ec17def3375aa78e0e2d697c4d44512c9f8456f1 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:06:33 +0000 Subject: [PATCH 56/80] Keep only the issues in the Baking Log on demand A warning toggle at the right end of the tab strip counts the shown tab's issues and, while pressed, keeps only the rows with one. With no issue left the tab says so in one line, with how to see every row under it. --- crates/ui-egui/src/baking_log.rs | 111 +++++++++++++++++++++++--- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/it/baking_log.rs | 41 ++++++++++ 3 files changed, 143 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 7d59cd29..1688d940 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -1,6 +1,6 @@ //! The Baking Log panel: the latest bake under three tabs, read from the session's bake record -use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; @@ -43,18 +43,56 @@ const NAME_SIZE: f32 = 12.0; const OPEN_ICON_SIZE: f32 = 14.0; const OPEN_BUTTON_SIZE: f32 = 20.0; +/// Height of the issues filter toggle, and its width without a count +const FILTER_HEIGHT: f32 = 22.0; +const FILTER_BUTTON_WIDTH: f32 = 30.0; + +/// How far the issues filter sits below the strip's centre, and how far it reaches past the side padding +const FILTER_DROP: f32 = 1.0; +const FILTER_OUTDENT: f32 = 4.0; + +/// Corner rounding of the issues filter's pressed and hovered fill +const FILTER_ROUNDING: f32 = 5.0; + +/// From the issues filter's left edge to its glyph's centre and to its count, and the glyph's size +const FILTER_GLYPH_CENTER: f32 = 15.0; +const FILTER_COUNT_LEFT: f32 = 26.0; +const FILTER_GLYPH_SIZE: f32 = 14.0; + +/// Air between the issue count and the toggle's right end +const FILTER_COUNT_GAP: f32 = 4.0; + +/// Height of the two lines the issues filter leaves when nothing is wrong, to centre them +const EMPTY_TEXT_HEIGHT: f32 = 40.0; + pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let running = app.session.bake_log.is_running(); - if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); + if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, app.session.bake_log.is_running()) { app.ui.baking_log_tab = tab; } + let tab = app.ui.baking_log_tab; + let issue_count = match tab { + BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), + _ => 0, + }; + if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { + app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; + } + + let issues_only = app.ui.baking_log_issues_only; + if issues_only && issue_count == 0 { + no_issues(ui, tab); + return; + } let opened = egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { ui.add_space(LIST_TOP); - match app.ui.baking_log_tab { - BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps), + match tab { + BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), _ => None, } }) @@ -78,12 +116,9 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa app.ui.dock.focus(Panel::MeshMapSettings); } -/// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon -fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option { +/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option { let tokens = Tokens::get(ui.ctx()); - let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); - ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - let mut picked = None; let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; for tab in BakingLogTab::ALL { @@ -117,15 +152,65 @@ fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option Option<(usize, BakedMap)> { +/// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are +fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let count = (issue_count > 0).then(|| issue_count.to_string()); + let count_width = + count.as_ref().map_or(0.0, |count| ui.painter().layout_no_wrap(count.clone(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP); + let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT; + let center_y = strip.center().y + FILTER_DROP; + let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); + + let name = match &count { + Some(count) => trf("{count}, Show Only Issues", &[("count", count)]), + None => tr("Show Only Issues").to_owned(), + }; + let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name)); + + let painter = ui.painter(); + if on { + painter.rect(rect, FILTER_ROUNDING, tokens.tool_active, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, FILTER_ROUNDING, tokens.row_hover); + } + let glyph_color = if count.is_some() { tokens.warning } else { tokens.text_dim }; + painter.text(pos2(rect.left() + FILTER_GLYPH_CENTER, center_y), Align2::CENTER_CENTER, ic::WARNING, FontId::proportional(FILTER_GLYPH_SIZE), glyph_color); + if let Some(count) = count { + painter.text(pos2(rect.left() + FILTER_COUNT_LEFT, center_y), Align2::LEFT_CENTER, count, semibold(NAME_SIZE), tokens.text); + } + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + response.on_hover_text(tr("Show Only Issues")).clicked() +} + +/// What the issues filter leaves when `tab` has no issue: the reference's words for that tab, and how to see every row +fn no_issues(ui: &mut Ui, tab: BakingLogTab) { + let tokens = Tokens::get(ui.ctx()); + let message = match tab { + BakingLogTab::BakingProcess => tr("All textures baked successfully so far."), + BakingLogTab::HighPolyParameters => tr("No issues encountered so far."), + BakingLogTab::MatchingByName => tr("No matching issues encountered"), + }; + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0); + child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text)); + child.label(egui::RichText::new(tr("Deselect filter to view.")).size(NAME_SIZE).color(tokens.text_dim)); + ui.allocate_rect(area, Sense::hover()); +} + +/// One row per texture set and map (with an issue, if `issues_only`) in bake order, following the map being baked; returns the map to open +fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option<(usize, BakedMap)> { let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); let follow_id = Id::unique("baking_log_followed_map"); let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); ui.data_mut(|data| data.insert_temp(follow_id, followed)); let mut opened = None; - for (index, row) in maps.iter().enumerate() { + for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { let (rect, open_clicked) = map_row(ui, row); if newly_followed && followed == Some(index) { ui.scroll_to_rect(rect, None); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6afa5c9b..c30cb883 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -684,6 +684,9 @@ pub struct UiState { /// The Baking Log panel's shown tab #[serde(default)] pub baking_log_tab: crate::baking_log::BakingLogTab, + /// Whether the Baking Log keeps only the rows with an issue + #[serde(default)] + pub baking_log_issues_only: bool, /// The project template the last New project was created from (name or label) #[serde(default)] pub last_template: String, @@ -848,6 +851,7 @@ impl Default for UiState { layout_dialog: None, log_channel: crate::log_panel::LogChannel::default(), baking_log_tab: crate::baking_log::BakingLogTab::default(), + baking_log_issues_only: false, last_template: String::new(), log_selection: Default::default(), log_anchor: None, diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index d10d63cc..9f56d585 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,6 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; +use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -86,3 +87,43 @@ fn a_failed_maps_arrow_opens_its_settings() { "a baked map has no arrow" ); } + +/// Put a finished bake of set 0's ID and Position maps in the log, the Position map ending as `position` +fn log_a_bake(harness: &mut Harness<'static, TextureCraftApp>, position: BakeMapState) -> String { + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + let row = |map, state| BakeLogMap { texture_set: 0, set_name: set_name.clone(), map, state }; + harness.state_mut().session.bake_log.maps = vec![row(BakedMap::Id, BakeMapState::Baked), row(BakedMap::Position, position)]; + harness.run_steps(3); + set_name +} + +#[test] +fn the_issues_filter_keeps_only_the_maps_with_a_problem() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into())); + harness.get_by_label(&format!("{set_name} ID, Baked")); + + harness.get_by_label("1, Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out"); + harness.get_by_label(&format!("{set_name} Position, Not baked")); + assert!(harness.query_by_label("Deselect filter to view.").is_none(), "an issue left: no empty text"); +} + +#[test] +fn the_issues_filter_says_so_when_nothing_went_wrong() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + harness.get_by_label("Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none()); + harness.get_by_label("All textures baked successfully so far."); + harness.get_by_label("Deselect filter to view."); + + harness.get_by_label("Show Only Issues").click(); + harness.run_steps(3); + harness.get_by_label(&format!("{set_name} ID, Baked")); + assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); +} From dfafec43c14e0738ca12c28cb094df48a6b5aa66 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:09:06 +0000 Subject: [PATCH 57/80] Report the Baking Log's rows through bake.log Automation gets the latest bake map by map with each map's state and the error of a failed one, the same rows the Baking Log shows. --- crates/engine/src/bake/bake_log.rs | 3 +-- crates/engine/src/bake/bake_log_map.rs | 5 +--- crates/engine/src/bake_log_cmds.rs | 36 ++++++++++++++++++++++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/tests/it/bake_log.rs | 17 ++++++++++++ docs/control-protocol.md | 8 ++++++ 7 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/bake_log_cmds.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 2f263cf2..d8705039 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,10 +1,9 @@ -use serde::Serialize; use texturecraft_core::{BakedMap, Project}; use super::{BakeLogMap, BakeMapState}; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines -#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct BakeLog { pub maps: Vec, } diff --git a/crates/engine/src/bake/bake_log_map.rs b/crates/engine/src/bake/bake_log_map.rs index 4a04bd7d..6f5d714a 100644 --- a/crates/engine/src/bake/bake_log_map.rs +++ b/crates/engine/src/bake/bake_log_map.rs @@ -1,15 +1,12 @@ -use serde::Serialize; use texturecraft_core::BakedMap; use super::BakeMapState; /// One row of the Baking Log's process list: a map of a texture set in the latest bake -#[derive(Clone, Debug, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] +#[derive(Clone, Debug, PartialEq)] pub struct BakeLogMap { pub texture_set: usize, pub set_name: String, pub map: BakedMap, - #[serde(flatten)] pub state: BakeMapState, } diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs new file mode 100644 index 00000000..dc8e243e --- /dev/null +++ b/crates/engine/src/bake_log_cmds.rs @@ -0,0 +1,36 @@ +//! The `bake.log` query: the Baking Log's rows for automation + +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "bake.log", + "Baking log", + [], + None, + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, as the Baking Log shows it; `reason` says why a map failed. Empty before the first bake", + always, + log + )] +} + +fn log(session: &mut Session, _: &Value) -> Result { + let maps = session + .bake_log + .maps + .iter() + .map(|row| { + let mut entry = serde_json::to_value(&row.state).map_err(|error| bad("bake.log", error.to_string()))?; + if let Some(fields) = entry.as_object_mut() { + fields.insert("textureSet".into(), json!(row.texture_set)); + fields.insert("setName".into(), json!(row.set_name)); + fields.insert("map".into(), json!(row.map.id())); + } + Ok(entry) + }) + .collect::>>()?; + Ok(json!({ "running": session.bake_log.is_running(), "maps": maps })) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 49cead62..41e7d619 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -139,6 +139,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::project_cmds::specs()); v.extend(crate::bake::specs()); v.extend(crate::bake_preview::specs()); + v.extend(crate::bake_log_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::pbr_cmds::specs()); v.extend(crate::file_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 148af463..ab6319f7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod add_mask_cmds; mod anchored_micro_edit; pub mod bake; +pub mod bake_log_cmds; pub mod bake_preview; pub mod brush_preset_cmds; pub mod camera_cmds; diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 965295e1..955d5561 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -48,3 +48,20 @@ fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps); assert!(!log.is_running()); } + +#[test] +fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["running"], false); + let maps: BTreeSet<&str> = log["maps"].as_array().unwrap().iter().map(|row| row["map"].as_str().unwrap()).collect(); + assert_eq!(maps, BTreeSet::from(["opacity", "position"])); + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "baked" && row["textureSet"] == 0 && row.get("reason").is_none()), "{log}"); + + session.bake_log.set_failed(0, "The high poly file could not be read."); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3abb3a97..feb3627f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -305,6 +305,14 @@ also `session.inspect`'s `bakePreview`: "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} ``` +`bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). +`state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`: + +```json +{"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}]} +``` + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From c0839e873e26ec920b7a8368d3cb8eeea37327bf Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:21:07 +0000 Subject: [PATCH 58/80] List each set's high poly files in the Baking Log --- crates/engine/src/bake/bake_high_state.rs | 27 +++++ crates/engine/src/bake/bake_log.rs | 50 +++++++++- crates/engine/src/bake/bake_log_high.rs | 11 +++ crates/engine/src/bake/mesh_map_command.rs | 3 +- crates/engine/src/bake/mod.rs | 4 + crates/engine/src/bake_log_cmds.rs | 32 +++--- crates/engine/tests/it/bake_log.rs | 37 ++++++- crates/ui-egui/src/baking_log.rs | 22 +++-- .../ui-egui/src/baking_log/high_poly_list.rs | 98 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/tests/it/baking_log.rs | 35 ++++++- docs/control-protocol.md | 7 +- 12 files changed, 296 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/bake/bake_high_state.rs create mode 100644 crates/engine/src/bake/bake_log_high.rs create mode 100644 crates/ui-egui/src/baking_log/high_poly_list.rs diff --git a/crates/engine/src/bake/bake_high_state.rs b/crates/engine/src/bake/bake_high_state.rs new file mode 100644 index 00000000..8ecbd0a5 --- /dev/null +++ b/crates/engine/src/bake/bake_high_state.rs @@ -0,0 +1,27 @@ +use serde::Serialize; + +/// Where one high poly file of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeHighState { + /// Its texture set has not started baking + Waiting, + Loading, + Loaded, + /// Its texture set's bake failed while getting the high polys ready; the reason is the error + Failed(String), + /// The bake stopped before the file was loaded + Canceled, +} + +impl BakeHighState { + /// Whether the file can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Loading) + } + + /// Whether the file counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index d8705039..82f63c90 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,16 +1,18 @@ use texturecraft_core::{BakedMap, Project}; -use super::{BakeLogMap, BakeMapState}; +use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState, BakeMesh}; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines #[derive(Clone, Debug, Default, PartialEq)] pub struct BakeLog { pub maps: Vec, + /// Each high poly file of each texture set that bakes from the high polys, in bake order + pub highs: Vec, } impl BakeLog { - /// Start over for a bake of `sets`: every checked map of each set, waiting, in bake order - pub fn begin(&mut self, project: &Project, sets: &[usize]) { + /// Start over for a bake of `sets`: every checked map of each set and the `high_polys` of each set that bakes from them, waiting, in bake order + pub fn begin(&mut self, project: &Project, high_polys: &[BakeMesh], sets: &[usize]) { self.maps = sets .iter() .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) @@ -18,13 +20,36 @@ impl BakeLog { set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting }) }) .collect(); + self.highs = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .filter(|(_, set)| !set.bake.high_poly.use_low_as_high) + .flat_map(|(index, set)| { + high_polys.iter().map(move |high| BakeLogHigh { + texture_set: index, + set_name: set.name.clone(), + file: high.name.clone(), + state: BakeHighState::Waiting, + }) + }) + .collect(); } - /// `set` starts baking: its first map is the one in progress + /// `set` starts baking: its high polys load and its first map is the one in progress pub fn set_started(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Waiting) { + row.state = BakeHighState::Loading; + } self.start_next(set); } + /// `set`'s bake has its high polys ready + pub fn high_polys_loaded(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Loading) { + row.state = BakeHighState::Loaded; + } + } + /// `map` of `set` is baked; the set's next map starts pub fn map_baked(&mut self, set: usize, map: BakedMap) { if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) { @@ -45,6 +70,10 @@ impl BakeLog { for row in self.maps.iter_mut().filter(|row| row.texture_set == set) { row.state = BakeMapState::Failed(reason.to_owned()); } + // A file that loaded is not what failed + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) { + row.state = BakeHighState::Failed(reason.to_owned()); + } } /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled @@ -54,6 +83,7 @@ impl BakeLog { row.state = BakeMapState::Canceled; } } + self.cancel_pending_highs(); } /// The whole bake was rolled back: every map that did not fail is canceled @@ -61,6 +91,7 @@ impl BakeLog { for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) { row.state = BakeMapState::Canceled; } + self.cancel_pending_highs(); } /// Whether a map is still waiting or baking @@ -68,6 +99,17 @@ impl BakeLog { self.maps.iter().any(|row| row.state.is_pending()) } + /// Whether a high poly file is still waiting or loading + pub fn is_loading_high_polys(&self) -> bool { + self.highs.iter().any(|row| row.state.is_pending()) + } + + fn cancel_pending_highs(&mut self) { + for row in self.highs.iter_mut().filter(|row| row.state.is_pending()) { + row.state = BakeHighState::Canceled; + } + } + fn start_next(&mut self, set: usize) { if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) { return; diff --git a/crates/engine/src/bake/bake_log_high.rs b/crates/engine/src/bake/bake_log_high.rs new file mode 100644 index 00000000..7c6de83d --- /dev/null +++ b/crates/engine/src/bake/bake_log_high.rs @@ -0,0 +1,11 @@ +use super::BakeHighState; + +/// One row of the Baking Log's high poly list: a high poly file a texture set bakes from in the latest bake +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogHigh { + pub texture_set: usize, + pub set_name: String, + /// The file's name as the project keeps it (the project carries the file itself, not where it came from) + pub file: String, + pub state: BakeHighState, +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index a76561fb..e3f16c22 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,7 +843,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } - session.bake_log.begin(&session.doc.project, &sets); + session.bake_log.begin(&session.doc.project, &session.bake_meshes.high, &sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { @@ -871,6 +871,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { /// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result { let mut task = session.bake_task(index)?; + session.bake_log.high_polys_loaded(index); if cpu { task.tracer = None; } diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 736b00bb..873c2f35 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -2,7 +2,9 @@ mod bake_cage_inputs; mod bake_checks; +mod bake_high_state; mod bake_log; +mod bake_log_high; mod bake_log_map; mod bake_map_state; mod bake_mesh; @@ -22,7 +24,9 @@ mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; +pub use bake_high_state::BakeHighState; pub use bake_log::BakeLog; +pub use bake_log_high::BakeLogHigh; pub use bake_log_map::BakeLogMap; pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs index dc8e243e..edfbd15a 100644 --- a/crates/engine/src/bake_log_cmds.rs +++ b/crates/engine/src/bake_log_cmds.rs @@ -11,26 +11,26 @@ pub fn specs() -> Vec { "Baking log", [], None, - "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, as the Baking Log shows it; `reason` says why a map failed. Empty before the first bake", + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, and the high poly files each set bakes from, as the Baking Log shows them; `reason` says why a map or file failed. Empty before the first bake", always, log )] } fn log(session: &mut Session, _: &Value) -> Result { - let maps = session - .bake_log - .maps - .iter() - .map(|row| { - let mut entry = serde_json::to_value(&row.state).map_err(|error| bad("bake.log", error.to_string()))?; - if let Some(fields) = entry.as_object_mut() { - fields.insert("textureSet".into(), json!(row.texture_set)); - fields.insert("setName".into(), json!(row.set_name)); - fields.insert("map".into(), json!(row.map.id())); - } - Ok(entry) - }) - .collect::>>()?; - Ok(json!({ "running": session.bake_log.is_running(), "maps": maps })) + let log = &session.bake_log; + let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::>>()?; + let highs = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::>>()?; + Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs })) +} + +/// One row: its `state` (and `reason`), its texture set, and what it is under `key` +fn entry(state: &impl serde::Serialize, texture_set: usize, set_name: &str, key: &str, what: Value) -> Result { + let mut entry = serde_json::to_value(state).map_err(|error| bad("bake.log", error.to_string()))?; + if let Some(fields) = entry.as_object_mut() { + fields.insert("textureSet".into(), json!(texture_set)); + fields.insert("setName".into(), json!(set_name)); + fields.insert(key.into(), what); + } + Ok(entry) } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 955d5561..36ce7772 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -3,7 +3,7 @@ use std::collections::BTreeSet; use serde_json::json; -use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::bake::{BakeHighState, BakeMapState}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -30,7 +30,7 @@ fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]); } let log = &mut session.bake_log; - log.begin(&session.doc.project, &[0, 1]); + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); log.set_started(0); log.map_baked(0, BakedMap::Normal); @@ -65,3 +65,36 @@ fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() { let log = execute(&mut session, "bake.log", &json!({})).unwrap(); assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}"); } + +#[test] +fn a_bake_lists_the_high_polys_each_set_loads_and_skips_a_set_baking_from_its_low_poly() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + session.doc.project.texture_sets[1].bake.high_poly.use_low_as_high = true; + + execute(&mut session, "bake.run", &json!({ "ts": [0, 1], "resolution": 64, "maps": ["opacity"], "dilation": 0 })).unwrap(); + + let highs: Vec<_> = session.bake_log.highs.iter().map(|row| (row.texture_set, row.file.as_str(), row.state.clone())).collect(); + assert_eq!(highs, [(0, "ball_high.obj", BakeHighState::Loaded)]); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["highPolys"][0]["state"], "loaded", "{log}"); +} + +#[test] +fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_cancel_the_rest_canceled() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let log = &mut session.bake_log; + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + + log.set_started(0); + assert_eq!(log.highs[0].state, BakeHighState::Loading); + assert!(log.is_loading_high_polys()); + log.set_failed(0, "The cage file could not be read."); + log.set_started(1); + log.cancel(Some(1)); + + assert_eq!(log.highs[0].state, BakeHighState::Failed("The cage file could not be read.".into())); + assert_eq!(log.highs[1].state, BakeHighState::Canceled); + assert!(!log.is_loading_high_polys()); +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 1688d940..9b2e0257 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -3,7 +3,7 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeMapState}; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; @@ -13,6 +13,7 @@ use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_I use crate::theme::{Tokens, semibold}; mod baking_log_tab; +mod high_poly_list; pub use baking_log_tab::BakingLogTab; @@ -69,13 +70,14 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, app.session.bake_log.is_running()) { + if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, &app.session.bake_log) { app.ui.baking_log_tab = tab; } let tab = app.ui.baking_log_tab; let issue_count = match tab { BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), - _ => 0, + BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::MatchingByName => 0, }; if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; @@ -93,7 +95,11 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(LIST_TOP); match tab { BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), - _ => None, + BakingLogTab::HighPolyParameters => { + high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only); + None + } + BakingLogTab::MatchingByName => None, } }) .inner; @@ -117,7 +123,7 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa } /// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon -fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option { +fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option { let tokens = Tokens::get(ui.ctx()); let mut picked = None; let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; @@ -137,7 +143,11 @@ fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option< shown_tab_box(painter, &tokens, rect); } let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; - let in_progress = running && tab == BakingLogTab::BakingProcess; + let in_progress = match tab { + BakingLogTab::BakingProcess => log.is_running(), + BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), + BakingLogTab::MatchingByName => false, + }; let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; let center_y = strip.center().y + TAB_TOP / 2.0; painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); diff --git a/crates/ui-egui/src/baking_log/high_poly_list.rs b/crates/ui-egui/src/baking_log/high_poly_list.rs new file mode 100644 index 00000000..5f4f5977 --- /dev/null +++ b/crates/ui-egui/src/baking_log/high_poly_list.rs @@ -0,0 +1,98 @@ +//! The Baking Log's High Poly Parameters tab: each texture set of the latest bake and the high poly files it loads + +use egui::{Align2, CornerRadius, FontId, Id, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh}; + +use super::{GLYPH_CENTER, GLYPH_SIZE, HOVER_INSET, NAME_LEFT, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::theme::{Tokens, semibold}; + +/// How far a file's row sits right of its texture set's row +const FILE_INDENT: f32 = 22.0; + +/// A row per texture set that loads high polys, folding open onto a row per file (with an issue, if `issues_only`) +pub(super) fn high_poly_list(ui: &mut Ui, highs: &[BakeLogHigh], issues_only: bool) { + let mut start = 0; + while start < highs.len() { + let set = highs[start].texture_set; + let end = highs[start..].iter().position(|row| row.texture_set != set).map_or(highs.len(), |length| start + length); + let files: Vec<&BakeLogHigh> = highs[start..end].iter().filter(|row| !issues_only || row.state.is_issue()).collect(); + start = end; + if files.is_empty() { + continue; + } + + if set_row(ui, set, &files[0].set_name) { + for row in files { + file_row(ui, row); + } + } + } +} + +/// A texture set's row: a caret and its name in SemiBold, named for what it holds; a click folds it. Returns whether it is open +fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool { + let tokens = Tokens::get(ui.ctx()); + let id = Id::unique(("baking_log_high_poly_set", set)); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, trf("{set}, High poly files", &[("set", &name)]))); + let mut open = ui.data(|data| data.get_temp::(id)).unwrap_or(true); + if response.clicked() { + open = !open; + ui.data_mut(|data| data.insert_temp(id, open)); + } + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + let caret = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, caret, FontId::proportional(GLYPH_SIZE), tokens.text_dim); + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, semibold(NAME_SIZE), tokens.text); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + open +} + +/// A high poly file's row under its texture set: glyph and file name; a file not loaded tells why on hover +fn file_row(ui: &mut Ui, row: &BakeLogHigh) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let (glyph, glyph_color, state) = match &row.state { + BakeHighState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeHighState::Loading => (ic::DOTS_THREE, tokens.accent, tr("Loading")), + BakeHighState::Loaded => (ic::CHECK, tokens.text, tr("Loaded")), + BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")), + BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file))); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER + FILE_INDENT, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeHighState::Loading => (semibold(NAME_SIZE), tokens.text), + BakeHighState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color); + + let reason = match &row.state { + BakeHighState::Failed(reason) => Some(reason.as_str()), + BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a786eef7..f825ba7e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -707,7 +707,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.bake_log.begin(&self.session.doc.project, &sets); + self.session.bake_log.begin(&self.session.doc.project, &self.session.bake_meshes.high, &sets); 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, only }); } @@ -896,6 +896,7 @@ impl TextureCraftApp { }; match task { Ok(task) => { + self.session.bake_log.high_polys_loaded(set_index); let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 9f56d585..837e3403 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,7 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -127,3 +127,36 @@ fn the_issues_filter_says_so_when_nothing_went_wrong() { harness.get_by_label(&format!("{set_name} ID, Baked")); assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); } + +#[test] +fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() { + let mut harness = harness(); + harness.state_mut().session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + harness.get_by_label("ball_high.obj, Loaded"); + + harness.get_by_label(&format!("{set_name}, High poly files")).click(); + harness.run_steps(3); + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files"); +} + +#[test] +fn the_high_poly_tab_counts_and_keeps_its_own_issues() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + let row = |file: &str, state| BakeLogHigh { texture_set: 0, set_name: set_name.clone(), file: file.into(), state }; + harness.state_mut().session.bake_log.highs = vec![row("ball_high.obj", BakeHighState::Loaded), row("bolt_high.obj", BakeHighState::Canceled)]; + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + + harness.get_by_label("1, Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out"); + harness.get_by_label("bolt_high.obj, Canceled"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index feb3627f..d97cd2bf 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -306,11 +306,14 @@ also `session.inspect`'s `bakePreview`: ``` `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). -`state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`: +A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. +`highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, +`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, - {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}]} + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], + "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}]} ``` `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with From 373159ec5ebccb0eefb2078a8dbeed36cdc9cba3 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:38:32 +0000 Subject: [PATCH 59/80] List how the bake paired parts by name in the Baking Log --- crates/engine/src/bake/bake_log.rs | 49 +++++++++++- crates/engine/src/bake/bake_log_matching.rs | 18 +++++ crates/engine/src/bake/mesh_map_command.rs | 2 +- crates/engine/src/bake/mod.rs | 3 + crates/engine/src/bake_log_cmds.rs | 8 +- crates/engine/tests/it/bake_log.rs | 39 +++++++-- crates/ui-egui/src/baking_log.rs | 62 +++++++++++---- .../ui-egui/src/baking_log/matching_list.rs | 79 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/it/baking_log.rs | 51 +++++++++--- docs/control-protocol.md | 8 +- 11 files changed, 286 insertions(+), 35 deletions(-) create mode 100644 crates/engine/src/bake/bake_log_matching.rs create mode 100644 crates/ui-egui/src/baking_log/matching_list.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 82f63c90..7203b7c1 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,6 +1,10 @@ +use std::collections::HashSet; + +use texturecraft_bake::NamePair; use texturecraft_core::{BakedMap, Project}; -use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState, BakeMesh}; +use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh}; +use crate::Session; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines #[derive(Clone, Debug, Default, PartialEq)] @@ -8,6 +12,8 @@ pub struct BakeLog { pub maps: Vec, /// Each high poly file of each texture set that bakes from the high polys, in bake order pub highs: Vec, + /// How the parts paired by name; `None` when no set of the bake matches "By Mesh Name" + pub matching: Option, } impl BakeLog { @@ -33,6 +39,7 @@ impl BakeLog { }) }) .collect(); + self.matching = None; } /// `set` starts baking: its high polys load and its first map is the one in progress @@ -120,3 +127,43 @@ impl BakeLog { } } } + +impl Session { + /// Start the Baking Log over for a bake of `sets` ([`BakeLog::begin`]), with how their parts pair by name + pub fn begin_bake_log(&mut self, sets: &[usize]) { + let matching = self.bake_log_matching(sets); + self.bake_log.begin(&self.doc.project, &self.doc.bake_meshes.high, sets); + self.bake_log.matching = matching; + } + + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it + fn bake_log_matching(&self, sets: &[usize]) -> Option { + let mut matching: Option = None; + let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new()); + for &set in sets { + let (Ok(Some(pairs)), Ok(texture_set)) = (self.bake_name_pairs(set), self.doc.project.texture_set(set)) else { continue }; + let settings = &texture_set.bake.high_poly; + let matching = matching.get_or_insert_with(|| BakeLogMatching { + low_suffix: settings.low_suffix.clone(), + high_suffix: settings.high_suffix.clone(), + pairs: Vec::new(), + }); + for pair in pairs { + match (&pair.low, &pair.high) { + (None, Some(high)) if !unpaired_highs.contains(high) => unpaired_highs.push(high.clone()), + (None, _) => {} + (Some(_), high) => { + paired_highs.extend(high.clone()); + matching.pairs.push(pair); + } + } + } + } + + if let Some(matching) = &mut matching { + let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high)); + matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) })); + } + matching + } +} diff --git a/crates/engine/src/bake/bake_log_matching.rs b/crates/engine/src/bake/bake_log_matching.rs new file mode 100644 index 00000000..9e0ef379 --- /dev/null +++ b/crates/engine/src/bake/bake_log_matching.rs @@ -0,0 +1,18 @@ +use texturecraft_bake::NamePair; + +/// The Baking Log's matching list: how the latest bake paired low poly parts with high poly parts by name +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogMatching { + /// The suffixes the first set matching by name strips, for the column captions + pub low_suffix: String, + pub high_suffix: String, + /// Each low poly part with the high poly part it bakes from, then the high poly parts no set of the bake pairs with + pub pairs: Vec, +} + +impl BakeLogMatching { + /// How many parts found no partner + pub fn issue_count(&self) -> usize { + self.pairs.iter().filter(|pair| pair.unpaired()).count() + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index e3f16c22..fef806b1 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,7 +843,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } - session.bake_log.begin(&session.doc.project, &session.bake_meshes.high, &sets); + session.begin_bake_log(&sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 873c2f35..e5edcc07 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -6,6 +6,7 @@ mod bake_high_state; mod bake_log; mod bake_log_high; mod bake_log_map; +mod bake_log_matching; mod bake_map_state; mod bake_mesh; mod bake_meshes; @@ -28,6 +29,7 @@ pub use bake_high_state::BakeHighState; pub use bake_log::BakeLog; pub use bake_log_high::BakeLogHigh; pub use bake_log_map::BakeLogMap; +pub use bake_log_matching::BakeLogMatching; pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; @@ -39,6 +41,7 @@ pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, pub use model_patch::settings_patch; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; +pub use texturecraft_bake::NamePair; pub use texturecraft_bake::*; use crate::CommandSpec; diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs index edfbd15a..4be8c268 100644 --- a/crates/engine/src/bake_log_cmds.rs +++ b/crates/engine/src/bake_log_cmds.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Baking log", [], None, - "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, and the high poly files each set bakes from, as the Baking Log shows them; `reason` says why a map or file failed. Empty before the first bake", + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}], matching: null | {lowSuffix, highSuffix, pairs: [{low: name | null, high: name | null}]}}. The latest bake map by map in bake order, the high poly files each set bakes from, and how parts paired by name, as the Baking Log shows them; `reason` says why a map or file failed; a `null` side of a pair is a part with no partner; `matching` is null when no set matched by mesh name. Empty before the first bake", always, log )] @@ -21,7 +21,11 @@ fn log(session: &mut Session, _: &Value) -> Result { let log = &session.bake_log; let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::>>()?; let highs = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::>>()?; - Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs })) + let matching = log.matching.as_ref().map(|matching| { + let pairs: Vec = matching.pairs.iter().map(|pair| json!({ "low": pair.low, "high": pair.high })).collect(); + json!({ "lowSuffix": matching.low_suffix, "highSuffix": matching.high_suffix, "pairs": pairs }) + }); + Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs, "matching": matching })) } /// One row: its `state` (and `reason`), its texture set, and what it is under `key` diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 36ce7772..419ce6b4 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -3,8 +3,8 @@ use std::collections::BTreeSet; use serde_json::json; -use texturecraft_engine::bake::{BakeHighState, BakeMapState}; -use texturecraft_engine::core::BakedMap; +use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair}; +use texturecraft_engine::core::{BakedMap, MeshMatchMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -86,15 +86,44 @@ fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_canc session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let log = &mut session.bake_log; log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + let state = |log: &BakeLog, set: usize| log.highs.iter().find(|high| high.texture_set == set).map(|high| high.state.clone()); log.set_started(0); - assert_eq!(log.highs[0].state, BakeHighState::Loading); + assert_eq!(state(log, 0), Some(BakeHighState::Loading)); assert!(log.is_loading_high_polys()); log.set_failed(0, "The cage file could not be read."); log.set_started(1); log.cancel(Some(1)); - assert_eq!(log.highs[0].state, BakeHighState::Failed("The cage file could not be read.".into())); - assert_eq!(log.highs[1].state, BakeHighState::Canceled); + assert_eq!(state(log, 0), Some(BakeHighState::Failed("The cage file could not be read.".into()))); + assert_eq!(state(log, 1), Some(BakeHighState::Canceled)); assert!(!log.is_loading_high_polys()); } + +#[test] +fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_with() { + let obj = "o Box_low\nusemtl Body\nv 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\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.begin_bake_log(&[0, 1]); + assert_eq!(session.bake_log.matching, None, "matching \"Always\" lists no pairs"); + + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + } + session.begin_bake_log(&[0, 1]); + + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + let matching = session.bake_log.matching.clone().unwrap(); + assert_eq!( + matching.pairs, + [pair(Some("Box_low"), Some("Box_high")), pair(Some("Lid_low"), None), pair(None, Some("Extra_high"))], + "Box_high is paired by the other set" + ); + assert_eq!(matching.issue_count(), 2); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 9b2e0257..1ee11974 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -14,6 +14,7 @@ use crate::theme::{Tokens, semibold}; mod baking_log_tab; mod high_poly_list; +mod matching_list; pub use baking_log_tab::BakingLogTab; @@ -77,13 +78,19 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let issue_count = match tab { BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::MatchingByName => 0, + BakingLogTab::MatchingByName => app.session.bake_log.matching.as_ref().map_or(0, |matching| matching.issue_count()), }; if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; } let issues_only = app.ui.baking_log_issues_only; + let log = &app.session.bake_log; + let baked = !log.maps.is_empty(); + if tab == BakingLogTab::MatchingByName && baked && log.matching.is_none() { + matching_not_enabled(ui); + return; + } if issues_only && issue_count == 0 { no_issues(ui, tab); return; @@ -92,6 +99,8 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let opened = egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { + // Rows sit edge to edge at ROW_HEIGHT, as the matching list's rules need + ui.spacing_mut().item_spacing.y = 0.0; ui.add_space(LIST_TOP); match tab { BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), @@ -99,7 +108,12 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only); None } - BakingLogTab::MatchingByName => None, + BakingLogTab::MatchingByName => { + if let Some(matching) = &app.session.bake_log.matching { + matching_list::matching_list(ui, matching, issues_only); + } + None + } } }) .inner; @@ -173,8 +187,8 @@ fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); let name = match &count { - Some(count) => trf("{count}, Show Only Issues", &[("count", count)]), - None => tr("Show Only Issues").to_owned(), + Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]), + None => tr("Show only rows with an issue").to_owned(), }; let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click()); response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name)); @@ -193,22 +207,41 @@ fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool if response.has_focus() { crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); } - response.on_hover_text(tr("Show Only Issues")).clicked() + response.on_hover_text(tr("Show only rows with an issue")).clicked() } -/// What the issues filter leaves when `tab` has no issue: the reference's words for that tab, and how to see every row +/// What the issues filter leaves when `tab` has no issue: one line for that tab, and how to see every row fn no_issues(ui: &mut Ui, tab: BakingLogTab) { let tokens = Tokens::get(ui.ctx()); let message = match tab { - BakingLogTab::BakingProcess => tr("All textures baked successfully so far."), - BakingLogTab::HighPolyParameters => tr("No issues encountered so far."), - BakingLogTab::MatchingByName => tr("No matching issues encountered"), + BakingLogTab::BakingProcess => tr("Every map so far baked without a problem."), + BakingLogTab::HighPolyParameters => tr("Every high poly file so far loaded."), + BakingLogTab::MatchingByName => tr("Every part so far has its partner."), }; let area = ui.available_rect_before_wrap(); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0); child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text)); - child.label(egui::RichText::new(tr("Deselect filter to view.")).size(NAME_SIZE).color(tokens.text_dim)); + child.label(egui::RichText::new(tr("Turn off the issues filter to see every row.")).size(NAME_SIZE).color(tokens.text_dim)); + ui.allocate_rect(area, Sense::hover()); +} + +/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting's name in SemiBold +fn matching_not_enabled(ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let mut text = egui::text::LayoutJob::default(); + let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; + // One sentence to translate, its setting kept apart to set it in SemiBold + let sentence = tr("{setting} was off for this bake."); + let (before, after) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + text.append(before, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("Matching by name"), 0.0, format(semibold(NAME_SIZE))); + text.append(after, 0.0, format(FontId::proportional(NAME_SIZE))); + + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT / 2.0).max(0.0) / 2.0); + child.label(text); ui.allocate_rect(area, Sense::hover()); } @@ -222,8 +255,9 @@ fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option let mut opened = None; for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { let (rect, open_clicked) = map_row(ui, row); + // Bring the next map into view too, so the list shows what comes after the map being baked if newly_followed && followed == Some(index) { - ui.scroll_to_rect(rect, None); + ui.scroll_to_rect(rect.with_max_y(rect.bottom() + ROW_HEIGHT), None); } if open_clicked { opened = Some((row.texture_set, row.map)); @@ -245,7 +279,7 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); - let open = row.state.is_issue().then(|| open_settings_button(ui, rect, &name)); + let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name)); let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); let painter = ui.painter(); @@ -286,11 +320,11 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { } /// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus -fn open_settings_button(ui: &mut Ui, row: Rect, name: &str) -> egui::Response { +fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response { let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE)); let label = trf("Open the {name} settings", &[("name", &name)]); - let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", name)), Sense::click()); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", set_map)), Sense::click()); response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); response.on_hover_text(label) } diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs new file mode 100644 index 00000000..22ad6c46 --- /dev/null +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -0,0 +1,79 @@ +//! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part + +use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeLogMatching, NamePair}; + +use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::property_sheet::SIDE_PADDING_POINTS; +use crate::theme::{Tokens, semibold}; + +/// Size of the column captions +const CAPTION_SIZE: f32 = 11.0; + +/// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below +pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)]; + for (left, caption) in columns(rect).into_iter().zip(captions) { + ui.painter().text(pos2(left, rect.center().y), Align2::LEFT_CENTER, caption, FontId::proportional(CAPTION_SIZE), tokens.text_dim); + } + rule(ui, rect); + + for pair in matching.pairs.iter().filter(|pair| !issues_only || pair.unpaired()) { + pair_row(ui, pair); + } +} + +/// A column caption in capitals, with the set's `suffix` kept as typed +fn caption(template: &str, suffix: &str) -> String { + template.split("{suffix}").map(str::to_uppercase).collect::>().join(suffix) +} + +/// The left edges of the low and high poly columns of `row` +fn columns(row: Rect) -> [f32; 2] { + [row.left() + SIDE_PADDING_POINTS, row.center().x] +} + +/// The hairline under `row`, inside the side padding +fn rule(ui: &Ui, row: Rect) { + let tokens = Tokens::get(ui.ctx()); + let x = row.left() + SIDE_PADDING_POINTS..=row.right() - SIDE_PADDING_POINTS; + ui.painter().hline(x, row.bottom() - 0.5, Stroke::new(1.0, tokens.separator)); +} + +/// A pair's row: the low poly part, then the high poly part; a side with no partner is a warning glyph that tells why on hover +fn pair_row(ui: &mut Ui, pair: &NamePair) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let no_match = tr("No match"); + let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match)); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + for (left, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { + match part { + Some(part) => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, part, FontId::proportional(NAME_SIZE), tokens.text), + None => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning), + }; + } + rule(ui, rect); + + let reason = match (&pair.low, &pair.high) { + (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), + (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f825ba7e..4346c304 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -707,7 +707,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.bake_log.begin(&self.session.doc.project, &self.session.bake_meshes.high, &sets); + self.session.begin_bake_log(&sets); 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, only }); } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 837e3403..3d098b6f 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,7 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -103,29 +103,29 @@ fn the_issues_filter_keeps_only_the_maps_with_a_problem() { let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into())); harness.get_by_label(&format!("{set_name} ID, Baked")); - harness.get_by_label("1, Show Only Issues").click(); + harness.get_by_label("1, Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out"); harness.get_by_label(&format!("{set_name} Position, Not baked")); - assert!(harness.query_by_label("Deselect filter to view.").is_none(), "an issue left: no empty text"); + assert!(harness.query_by_label("Turn off the issues filter to see every row.").is_none(), "an issue left: no empty text"); } #[test] fn the_issues_filter_says_so_when_nothing_went_wrong() { let mut harness = harness(); let set_name = log_a_bake(&mut harness, BakeMapState::Baked); - harness.get_by_label("Show Only Issues").click(); + harness.get_by_label("Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none()); - harness.get_by_label("All textures baked successfully so far."); - harness.get_by_label("Deselect filter to view."); + harness.get_by_label("Every map so far baked without a problem."); + harness.get_by_label("Turn off the issues filter to see every row."); - harness.get_by_label("Show Only Issues").click(); + harness.get_by_label("Show only rows with an issue").click(); harness.run_steps(3); harness.get_by_label(&format!("{set_name} ID, Baked")); - assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); + assert!(harness.query_by_label("Every map so far baked without a problem.").is_none(), "off again: every row is back"); } #[test] @@ -154,9 +154,42 @@ fn the_high_poly_tab_counts_and_keeps_its_own_issues() { harness.get_by_label("High Poly Parameters").click(); harness.run_steps(3); - harness.get_by_label("1, Show Only Issues").click(); + harness.get_by_label("1, Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out"); harness.get_by_label("bolt_high.obj, Canceled"); } + +#[test] +fn the_matching_tab_lists_the_pairs_and_its_filter_keeps_the_parts_with_no_partner() { + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![pair(Some("Barrel_low"), Some("Barrel_high")), pair(Some("Strap_low"), None)], + }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + harness.get_by_label("Barrel_low, Barrel_high"); + + harness.get_by_label("1, Show only rows with an issue").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("Barrel_low, Barrel_high").is_none(), "a pair is filtered out"); + harness.get_by_label("Strap_low, No match"); +} + +#[test] +fn the_matching_tab_says_when_no_set_matched_by_name() { + let mut harness = harness(); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + assert!(harness.query_by_label("Matching by name was off for this bake.").is_none(), "nothing baked yet: nothing to say"); + + log_a_bake(&mut harness, BakeMapState::Baked); + + harness.get_by_label("Matching by name was off for this bake."); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d97cd2bf..a682a901 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -308,12 +308,16 @@ also `session.inspect`'s `bakePreview`: `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. `highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, -`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`: +`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`. `matching` lists each low poly +part with the high poly part it bakes from, then the high poly parts no set paired with; a `null` side is a part +with no partner. It is `null` when no set of the bake matches by mesh name: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], - "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}]} + "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}], + "matching": {"lowSuffix": "_low", "highSuffix": "_high", + "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} ``` `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with From 530541a97a06a737b5aaaeb4b4bbf72555eef61e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:52:29 +0000 Subject: [PATCH 60/80] Remember what each baked map was baked from Each bake records, per map, fingerprints of the low poly geometry, the high poly and cage files, the settings every map shares (with the UV tiles baked) and the map's own settings, taken when the set's bake starts. A map whose inputs differ now is out of date, with what changed; project.inspect lists those per texture set as outOfDate. The record is saved with the project and left out when empty, so projects saved before it open unchanged and their maps never show out of date. Imported maps keep no record either. --- crates/core/src/bake.rs | 4 + crates/core/src/bake/bake_change.rs | 25 ++++ crates/core/src/bake/bake_source.rs | 69 +++++++++++ crates/core/src/bake/mesh_map_settings.rs | 16 +++ crates/core/src/lib.rs | 11 +- crates/core/src/project.rs | 19 ++- crates/engine/src/bake/bake_mesh.rs | 2 + crates/engine/src/bake/bake_sources.rs | 65 ++++++++++ crates/engine/src/bake/bake_task.rs | 11 +- crates/engine/src/bake/mesh_map_command.rs | 35 ++++-- crates/engine/src/bake/mod.rs | 1 + crates/engine/src/bake/streamed_bake.rs | 4 +- crates/engine/src/file_cmds.rs | 9 +- crates/engine/src/inspect.rs | 1 + crates/engine/src/meshmap_cmds.rs | 41 ++++--- crates/engine/src/session.rs | 3 + crates/engine/tests/it/bake_out_of_date.rs | 136 +++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/tests/it/bake_mode.rs | 2 +- docs/control-protocol.md | 6 + 20 files changed, 422 insertions(+), 39 deletions(-) create mode 100644 crates/core/src/bake/bake_change.rs create mode 100644 crates/core/src/bake/bake_source.rs create mode 100644 crates/engine/src/bake/bake_sources.rs create mode 100644 crates/engine/tests/it/bake_out_of_date.rs diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index a40f5ab0..8289ef42 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation; mod ambient_occlusion_settings; mod backface_mode; mod bake_antialiasing; +mod bake_change; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_source; mod bake_sync; mod bake_sync_group; mod mesh_match_mode; @@ -45,8 +47,10 @@ pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation; pub use ambient_occlusion_settings::AmbientOcclusionSettings; pub use backface_mode::BackfaceMode; pub use bake_antialiasing::BakeAntialiasing; +pub use bake_change::BakeChange; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_source::{BakeSource, fingerprint, fingerprint_words}; pub use bake_sync::BakeSync; pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; diff --git a/crates/core/src/bake/bake_change.rs b/crates/core/src/bake/bake_change.rs new file mode 100644 index 00000000..bb73b1f2 --- /dev/null +++ b/crates/core/src/bake/bake_change.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// What changed since a mesh map was baked, which makes it out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BakeChange { + LowPoly, + HighPoly, + Cage, + Settings, + MapSettings, +} + +impl BakeChange { + /// Identifier in automation replies + pub fn id(self) -> &'static str { + match self { + BakeChange::LowPoly => "lowPoly", + BakeChange::HighPoly => "highPoly", + BakeChange::Cage => "cage", + BakeChange::Settings => "settings", + BakeChange::MapSettings => "mapSettings", + } + } +} diff --git a/crates/core/src/bake/bake_source.rs b/crates/core/src/bake/bake_source.rs new file mode 100644 index 00000000..9cc59c44 --- /dev/null +++ b/crates/core/src/bake/bake_source.rs @@ -0,0 +1,69 @@ +use super::BakeChange; +use serde::{Deserialize, Serialize}; + +/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeSource { + /// The low poly's geometry + pub low_poly: u64, + /// The high poly files, in list order (0: none, the set bakes from the low poly) + pub high_poly: u64, + /// The cage file (0: none) + pub cage: u64, + /// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles + pub settings: u64, + /// The map's own settings + pub map_settings: u64, +} + +impl BakeSource { + /// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date) + pub fn changes(&self, current: &BakeSource) -> Vec { + [ + (self.low_poly != current.low_poly, BakeChange::LowPoly), + (self.high_poly != current.high_poly, BakeChange::HighPoly), + (self.cage != current.cage, BakeChange::Cage), + (self.settings != current.settings, BakeChange::Settings), + (self.map_settings != current.map_settings, BakeChange::MapSettings), + ] + .into_iter() + .filter_map(|(changed, change)| changed.then_some(change)) + .collect() + } +} + +/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`) +pub fn fingerprint(bytes: &[u8]) -> u64 { + let words = bytes.chunks(8).map(|chunk| { + let mut word_bytes = [0; 8]; + word_bytes[..chunk.len()].copy_from_slice(chunk); + u64::from_le_bytes(word_bytes) + }); + fingerprint_words(words.chain([bytes.len() as u64])) +} + +/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step +pub fn fingerprint_words(words: impl IntoIterator) -> u64 { + // FNV-1a 64-bit offset basis and prime + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + + words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_fingerprint_changes_with_any_byte_and_with_the_length() { + let bytes: Vec = (0..=20).collect(); + let mut changed = bytes.clone(); + changed[17] ^= 1; + + assert_ne!(fingerprint(&bytes), fingerprint(&changed)); + assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20])); + assert_ne!(fingerprint(&[]), fingerprint(&[0])); + } +} diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index 281d5c98..579141e7 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -84,6 +84,22 @@ impl MeshMapSettings { } } + /// `map`'s typed parameters as JSON + pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value { + let parameters = match map { + // These maps have no parameters of their own + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null, + BakedMap::Id => serde_json::to_value(self.id.parameters), + BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters), + BakedMap::Curvature => serde_json::to_value(self.curvature.parameters), + BakedMap::Position => serde_json::to_value(self.position.parameters), + BakedMap::Thickness => serde_json::to_value(self.thickness.parameters), + BakedMap::Height => serde_json::to_value(self.height.parameters), + BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters), + }; + parameters.unwrap_or_default() + } + 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 eedf93ec..772653e4 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -80,11 +80,12 @@ 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, 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, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings, + BakeSource, 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, fingerprint, + fingerprint_words, }; pub use bevel::Bevel; pub use bevel_blur::BevelBlur; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 0a4bf868..69437007 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, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -69,6 +69,9 @@ pub struct TextureSet { /// Mesh maps that have been baked (pixels live with the engine / project file). #[serde(default)] pub baked: BTreeSet, + /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub bake_sources: BTreeMap, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -171,6 +174,7 @@ impl TextureSet { height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), + bake_sources: BTreeMap::new(), visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), @@ -187,6 +191,19 @@ impl TextureSet { self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) } + /// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions) + pub fn bake_settings_fingerprint(&self) -> u64 { + let mut common = self.bake.common; + common.is_enabled = true; + let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles); + crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes()) + } + + /// Fingerprint of `map`'s own bake settings (not whether it is checked) + pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 { + crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes()) + } + /// Height strength for slopes measured over the whole texture width (the viewport shader, /// the path tracer): a UV tile atlas is one tile per column wide. pub fn atlas_height_strength(&self) -> f32 { diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index bcdb2bcc..d4dbfeeb 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -11,4 +11,6 @@ pub struct BakeMesh { pub bytes: Arc>, pub mesh: Arc, pub base_color: Vec>>, + /// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record + pub fingerprint: u64, } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs new file mode 100644 index 00000000..70f7665c --- /dev/null +++ b/crates/engine/src/bake/bake_sources.rs @@ -0,0 +1,65 @@ +//! What each baked map was baked from, and which maps are out of date since + +use std::collections::BTreeMap; + +use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, fingerprint_words}; + +use crate::{Result, Session}; + +impl Session { + /// What a bake of `map` on texture set `texture_set` would read now + pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result { + let set = self.doc.project.texture_set(texture_set)?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + let high_poly = match from_high { + true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)), + false => 0, + }; + let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile; + let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint); + + Ok(BakeSource { + low_poly: self.low_poly_fingerprint(), + high_poly, + cage, + settings: set.bake_settings_fingerprint(), + map_settings: set.map_settings_fingerprint(map), + }) + } + + /// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record + pub fn bake_changes(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return Vec::new() }; + let Some(record) = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map)) else { return Vec::new() }; + + self.bake_source(texture_set, map).map(|current| record.changes(¤t)).unwrap_or_default() + } + + /// The out-of-date maps of texture set `texture_set`, each with what changed + pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap> { + BakedMap::ALL.into_iter().map(|map| (map, self.bake_changes(texture_set, map))).filter(|(_, changes)| !changes.is_empty()).collect() + } + + /// Fingerprint of the low poly's own geometry (computed once per loaded mesh) + fn low_poly_fingerprint(&self) -> u64 { + *self.low_poly_fingerprint.get_or_init(|| { + let source = &self.source; + let floats = source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array())); + let words = floats.map(|float| u64::from(float.to_bits())).chain(source.indices.iter().map(|index| u64::from(*index))); + fingerprint_words(words) + }) + } + + /// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record + pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap>, stored: &[BakedMap]) -> Result<()> { + let set = self.doc.project.texture_set_mut(texture_set)?; + match sources { + Some(sources) => set.bake_sources.extend(sources), + None => set.bake_sources.retain(|map, _| !stored.contains(map)), + } + + let baked = &set.baked; + set.bake_sources.retain(|map, _| baked.contains(map)); + Ok(()) + } +} diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index a617d97b..3c0cb59e 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -26,6 +26,8 @@ pub struct BakeTask { pub previous_maps: BakedMaps, /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). pub tracer: Option>, + /// What each map this task makes is baked from, taken when the task was made + pub sources: std::collections::BTreeMap, } impl BakeTask { @@ -66,7 +68,13 @@ impl BakeTask { // A resized partial bake also returns unchecked maps that must survive application let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); retained.insert(map, data); - combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer }); + combined = Some(StreamedBake { + resolution: output.resolution, + height: output.height, + maps: retained, + tracer: output.tracer, + sources: self.sources.clone(), + }); } } } @@ -80,6 +88,7 @@ impl BakeTask { height: output.height, maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, + sources: self.sources.clone(), }) } } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef806b1..49ec4ec0 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -15,8 +15,8 @@ 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, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, - SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, + RaySettings, SelfOcclusion, }; use texturecraft_geom::Mesh; @@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); 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(imported.mesh), base_color }) + let fingerprint = texturecraft_core::fingerprint(&bytes); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint }) } impl Session { @@ -183,6 +184,7 @@ impl Session { let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed)); + let sources = set.bake.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; Ok(BakeTask { low_base_color, ts: texture_set, @@ -198,6 +200,7 @@ impl Session { excluded_tiles, previous_maps, tracer, + sources, }) } @@ -260,7 +263,7 @@ impl Session { /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?; + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } @@ -269,17 +272,26 @@ impl Session { /// preview that showed them holds the same ones) pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?; + self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + /// Store `output`, recording what its maps were baked from when `sources` are known + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap>) -> Result<()> { let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); - self.store_bake_maps(texture_set, output.resolution, output.height, maps) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources) } - fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap>>) -> Result<()> { + fn store_bake_maps( + &mut self, + texture_set: usize, + resolution: u32, + height: u32, + maps: BTreeMap>>, + sources: Option<&BTreeMap>, + ) -> Result<()> { + let stored: Vec = maps.keys().copied().collect(); let entry = self.doc.baked.entry(texture_set).or_default(); if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) { entry.maps.clear(); @@ -288,7 +300,7 @@ impl Session { entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); - Ok(()) + self.record_bake_sources(texture_set, sources, &stored) } /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. @@ -299,7 +311,8 @@ impl Session { } let out = task.run(&Progress::new())?; let tracer = out.tracer.clone(); - self.apply_bake(ts, out)?; + self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?; + self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); Ok(tracer) } @@ -879,7 +892,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result>>, pub tracer: String, + /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) + pub sources: BTreeMap, } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 9c447c3c..5cfc235b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1655,7 +1655,14 @@ f 1/1 2/2 3/3 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(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + let cage = crate::bake::BakeMesh { + name: "cage".into(), + folder: None, + bytes: Default::default(), + mesh: s.mesh.clone(), + base_color: Vec::new(), + fingerprint: 0, + }; s.doc.bake_meshes.cage = Some(cage); let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index a4258463..e9c3b2e5 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -276,6 +276,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), + "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..5736c5ca 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -53,19 +53,19 @@ fn set(s: &mut Session, p: &Value) -> Result { pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width -pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { - let texture_set = s.doc.project.texture_set(ts)?; +pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = session.doc.project.texture_set(ts)?; let grid = texture_set.tile_grid(); if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { - return Err(bad(cmd, format!("no image for UV tile {tile}"))); + return Err(bad(command, format!("no image for UV tile {tile}"))); } - let (width, height) = image_map_size(s, cmd, ts)?; + let (width, height) = image_map_size(session, command, ts)?; // Bent normals are tangent-space maps like the normal map, so both follow the project's normal format - let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && s.doc.project.normal_format == NormalFormat::DirectX; + let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX; let data = match (grid, images.values().next()) { - (_, None) => return Err(bad(cmd, "no image to use")), + (_, None) => return Err(bad(command, "no image to use")), (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { @@ -74,10 +74,13 @@ pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, i }), }; - let entry = s.doc.baked.entry(ts).or_default(); + let entry = session.doc.baked.entry(ts).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); + // An imported map is never out of date: nothing records what it was made from + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.insert(map); + set.bake_sources.remove(&map); Ok(width) } @@ -153,18 +156,20 @@ fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn( out } -fn clear(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.meshMap.clear"; - let ts = ts_param(s, p, CMD)?; - let map = map_param(p, CMD)?; - if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { - return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id()))); +fn clear(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.meshMap.clear"; + let ts = ts_param(session, params, COMMAND)?; + let map = map_param(params, COMMAND)?; + if !session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) { + return Err(bad(COMMAND, format!("texture set {ts} has no {} map", map.id()))); } - s.edit("Clear mesh map", |s| { - if let Some(b) = s.doc.baked.get_mut(&ts) { - b.maps.remove(&map); + session.edit("Clear mesh map", |session| { + if let Some(baked) = session.doc.baked.get_mut(&ts) { + baked.maps.remove(&map); } - s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.remove(&map); + set.bake_sources.remove(&map); Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index f0a8df58..05a0c779 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -425,6 +425,8 @@ pub struct Session { pub project_id: u64, /// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas). pub(crate) source: Arc, + /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it + pub(crate) low_poly_fingerprint: std::sync::OnceLock, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Arc>)>, @@ -527,6 +529,7 @@ impl Session { mesh_id: next_mesh_id(), project_id: next_mesh_id(), source, + low_poly_fingerprint: Default::default(), mesh, bvh: Arc::new(bvh), mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), diff --git a/crates/engine/tests/it/bake_out_of_date.rs b/crates/engine/tests/it/bake_out_of_date.rs new file mode 100644 index 00000000..9a5c1dcd --- /dev/null +++ b/crates/engine/tests/it/bake_out_of_date.rs @@ -0,0 +1,136 @@ +//! Out-of-date mesh maps: what each map was baked from, compared with what a bake would read now + +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeChange, BakedMap, CageType}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position map baked by `bake.run` +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + session +} + +fn changes(session: &Session) -> Vec { + session.bake_changes(0, BakedMap::Position) +} + +#[test] +fn a_map_goes_out_of_date_when_its_settings_or_the_shared_ones_change_and_a_bake_brings_it_back() { + let mut session = baked_plane(); + assert!(changes(&session).is_empty(), "fresh bake: {:?}", changes(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(changes(&session), [BakeChange::MapSettings]); + execute(&mut session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + assert_eq!(changes(&session), [BakeChange::Settings, BakeChange::MapSettings]); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["outOfDate"], json!({ "position": ["settings", "mapSettings"] })); + + execute(&mut session, "bake.run", &json!({})).unwrap(); + assert!(changes(&session).is_empty(), "rebaked: {:?}", changes(&session)); +} + +#[test] +fn the_record_is_saved_with_the_project() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(changes(&reopened), [BakeChange::MapSettings]); +} + +#[test] +fn maps_saved_before_records_existed_and_imported_maps_never_go_out_of_date() { + let mut old = baked_plane(); + old.doc.project.texture_sets[0].bake_sources.clear(); + let mut old = Session::from_project_bytes(&old.to_project_bytes().unwrap()).unwrap(); + execute(&mut old, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&old).is_empty(), "{:?}", changes(&old)); + + let mut imported = baked_plane(); + let mut png = Vec::new(); + image::RgbImage::from_pixel(4, 4, image::Rgb([128, 64, 32])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + imported.import_resource_bytes("position.png", png).unwrap(); + execute(&mut imported, "textureSet.meshMap.set", &json!({ "map": "position", "image": "position.png" })).unwrap(); + execute(&mut imported, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&imported).is_empty(), "{:?}", changes(&imported)); +} + +#[test] +fn adding_a_high_poly_puts_the_maps_out_of_date() { + let mut session = baked_plane(); + + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + + assert_eq!(changes(&session), [BakeChange::HighPoly]); +} + +#[test] +fn a_cage_file_counts_only_for_sets_that_bake_with_it() { + let mut session = baked_plane(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let cage: String = (0..session.mesh.triangle_count()).map(|_| "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n").collect(); + session.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + assert!(changes(&session).is_empty(), "the cage type is not Custom File: {:?}", changes(&session)); + + session.doc.project.texture_sets[0].bake.cage.kind = CageType::CustomFile; + assert!(changes(&session).contains(&BakeChange::Cage), "{:?}", changes(&session)); +} + +#[test] +fn a_setting_changed_while_the_bake_runs_leaves_the_new_map_out_of_date() { + let mut session = baked_plane(); + let task = session.bake_task(0).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let streamed_once = AtomicBool::new(false); + let output = task.run_streaming(&Progress::new(), &mut |_| streamed_once.store(true, Ordering::Relaxed)).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(streamed_once.load(Ordering::Relaxed)); + assert_eq!(changes(&session), [BakeChange::MapSettings]); +} + +/// Two quads side by side, one texture set each, lifted by `lift` where a high poly or cage stands off the low poly +fn two_parts(lift: f32) -> String { + let mut obj = String::new(); + for left in [0.0, 2.0] { + let right = left + 1.0; + obj += &format!("v {left} 0 {lift}\nv {right} 0 {lift}\nv {right} 1 {lift}\nv {left} 1 {lift}\n"); + } + obj += "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n"; + obj += "usemtl Left\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\nusemtl Right\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n"; + obj +} + +#[test] +fn a_reopened_project_keeps_every_sets_maps_up_to_date() { + let mut session = Session::from_mesh_bytes_with_uvs("parts.obj", two_parts(0.0).as_bytes(), 128, "parts", None, false).unwrap(); + session.add_high_poly_bytes("parts_high.obj", two_parts(0.05).into_bytes()).unwrap(); + session.set_cage_bytes("parts_cage.obj", two_parts(0.2).into_bytes()).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake.cage.kind = CageType::CustomFile; + } + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position", "normal"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 1, "map": "normal" })).unwrap(); + let records = |session: &Session| session.doc.project.texture_sets.iter().map(|set| set.bake_sources.clone()).collect::>(); + assert_eq!(session.set_count(), 2); + assert!(records(&session).iter().all(|sources| sources.len() == 2), "both maps of both sets are recorded"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(records(&reopened), records(&session), "the records are saved as they were"); + for texture_set in 0..reopened.set_count() { + assert!(reopened.out_of_date_maps(texture_set).is_empty(), "set {texture_set}: {:?}", reopened.out_of_date_maps(texture_set)); + } + assert!(reopened.auto_rebake_due().is_empty(), "opening the project starts no rebake"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11b199c9..f43035f4 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -5,6 +5,7 @@ mod add_mask_items; mod bake; mod bake_checks; mod bake_log; +mod bake_out_of_date; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 1f7253ac..720d4c49 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -595,7 +595,7 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { 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.doc.bake_meshes.cage = - Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new(), fingerprint: 0 }); 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); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a682a901..91fad894 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -320,6 +320,12 @@ with no partner. It is `null` when no set of the bake matches by mesh name: "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} ``` +Each texture set in `project.inspect` / `session.inspect` lists its out-of-date mesh maps as +`outOfDate`: map id → what changed since that map was baked, any of `lowPoly`, `highPoly`, `cage`, +`settings` (the bake settings every map shares, or the UV tiles baked) and `mapSettings` (the map's +own). Imported maps, and maps saved before this record existed, never show: +`"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From 5b4411ee9a5e1c5012f5670bd3558dc257ad23aa Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:20:12 +0000 Subject: [PATCH 61/80] Note a generator's missing or out-of-date mesh map A generator that reads a mesh map the active texture set has not baked, or baked before its mesh, files or settings changed, shows one line under its kind: what is wrong, the reasons on hover, and a Bake button that bakes the set in the background (turning the map on first when it is off). Nothing shows once the map is up to date, and nothing pops up. The line replaces the old warning at the end of the panel, which showed for every generator, even those that read no mesh map. --- crates/ui-egui/src/generator_panel.rs | 6 +- .../ui-egui/src/generator_panel/bake_note.rs | 107 ++++++++++++++++++ .../ui-egui/tests/it/generator_bake_note.rs | 75 ++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 4 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/generator_panel/bake_note.rs create mode 100644 crates/ui-egui/tests/it/generator_bake_note.rs diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 95d3fcd7..745d93fd 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -18,6 +18,8 @@ use crate::property_sheet::PropertySheet; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +mod bake_note; + /// 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; @@ -35,6 +37,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, PropertySheet::show(ui, ("generator_sheet", id), |sheet| { sheet.section(tr("Generator"), false); slot_card(app, sheet, id, generator); + bake_note::bake_notes(app, sheet, generator); let band = sheet.band(tr("Parameters"), true, Some(differs_from_defaults(generator)), None); if band.reset { @@ -68,9 +71,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, 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 for curvature, AO and thickness based generators.")); - } }); } diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs new file mode 100644 index 00000000..4953261d --- /dev/null +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -0,0 +1,107 @@ +//! One quiet line under a generator's kind when a mesh map it reads is not baked or out of date, with a Bake button + +use egui::{Align, Layout, RichText, Stroke, Ui, UiBuilder, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeChange, BakedMap, Generator}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS}; +use crate::theme::{Tokens, semibold}; + +/// Height of the note's line, in points (the mock's 28 px row) +const NOTE_HEIGHT: f32 = 28.0; + +/// Height of the Bake button, in points (the panels' 24 px controls) +const BUTTON_HEIGHT: f32 = 24.0; + +/// Size of the tooltip's title and reasons, in points +const TOOLTIP_TEXT_SIZE: f32 = 12.0; + +/// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date +pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) { + let texture_set = app.session.ts(); + for map in generator.inputs_in_use() { + if generator.inputs.contains_key(map) { + continue; + } + + let baked = app.session.baked(texture_set).is_some_and(|baked| baked.maps.contains_key(map)); + let changes = if baked { app.session.bake_changes(texture_set, *map) } else { Vec::new() }; + if baked && changes.is_empty() { + continue; + } + + // A full-width line inside the sheet's side padding + let (line, _) = sheet.ui.allocate_exact_size(vec2(sheet.ui.available_width(), NOTE_HEIGHT), egui::Sense::hover()); + let builder = UiBuilder::new().id_salt(map).max_rect(line.shrink2(vec2(SIDE_PADDING_POINTS, 0.0))).layout(Layout::left_to_right(Align::Center)); + sheet.ui.scope_builder(builder, |ui| note(app, ui, (texture_set, *map), &changes)); + } +} + +/// The line for `map` of `texture_set`: not baked when `changes` is empty, else out of date because of them +fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, BakedMap), changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let name = tr(baked_map_label(map)); + let (glyph, text, title) = match changes.is_empty() { + true => (ic::WARNING, trf("{map} map not baked", &[("map", &name)]), tr("Not baked")), + false => (ic::CLOCK, trf("{map} map out of date", &[("map", &name)]), tr("Out of date")), + }; + let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map)); + + ui.label(RichText::new(glyph).color(tokens.warning)); + ui.add(egui::Label::new(&text).truncate()).on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for reason in reasons(changes, checked) { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); + let bake = ui + .with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = egui::Button::new(tr("Bake")).stroke(Stroke::new(1.0, tokens.button_border)).min_size(vec2(0.0, BUTTON_HEIGHT)); + ui.add_enabled(app.bake.is_none(), button) + .on_hover_text(tr("Bake this texture set's mesh maps in the background")) + .on_disabled_hover_text(tr("A bake is already running")) + }) + .inner; + + if bake.clicked() { + bake_map(app, texture_set, map); + } +} + +/// Why the line shows: what changed since the bake, or what a missing map does to the generator +fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> { + if changes.is_empty() { + let mut reasons = vec![tr("The generator reads a flat value until this map is baked.")]; + if !checked { + reasons.push(tr("Bake turns this map on in the bake settings first.")); + } + return reasons; + } + + changes + .iter() + .map(|change| match change { + BakeChange::LowPoly => tr("The mesh changed after this bake."), + BakeChange::HighPoly => tr("The high poly files changed after this bake."), + BakeChange::Cage => tr("The cage changed after this bake."), + BakeChange::Settings => tr("The common bake settings changed after this bake."), + BakeChange::MapSettings => tr("This map's bake settings changed after this bake."), + }) + .collect() +} + +/// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off +fn bake_map(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + let Some(before) = app.session.doc.project.texture_sets.get(texture_set).map(|set| set.bake.clone()) else { return }; + + if !before.maps.is_enabled(map) { + let mut after = before.clone(); + after.maps.set_enabled(map, true); + app.run("bake.settings", json!({ "ts": texture_set, "patch": settings_patch(&before, &after) })); + } + app.start_bake(vec![texture_set]); +} diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs new file mode 100644 index 00000000..d26019c7 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -0,0 +1,75 @@ +//! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask +fn harness() -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + 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(); + execute(&mut session, "effect.add.generator", &json!({ "generator": "curvature" })).unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + harness +} + +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..4000 { + harness.run_steps(1); + if harness.state().bake.is_none() { + harness.run_steps(2); + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() { + let mut harness = harness(); + harness.get_by_label("Curvature map not baked"); + + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap(); + harness.run_steps(3); + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); + assert!(harness.query_by_label("Curvature map out of date").is_none(), "baked: no note"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + harness.get_by_label("Curvature map out of date"); +} + +#[test] +fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() { + let mut harness = harness(); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature)); + + harness.get_by_label("Bake").click(); + harness.run_steps(1); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature), "turned on"); + assert!(harness.state().bake.is_some(), "a background bake started"); + run_to_the_end(&mut harness); + + assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature))); + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 045d3d57..0abd9441 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -44,6 +44,7 @@ mod fill_symmetry_rows; mod filter_picker; mod folder_properties; mod frame_selection; +mod generator_bake_note; mod generator_panel; mod generator_picker; mod help_menu_664; From 9e36885648d969560d050f30704bff97c98ef6ef Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:41:02 +0000 Subject: [PATCH 62/80] Rebake the auto-rebake map when its settings change Each texture set can turn on Auto-rebake for one mesh map (bake.autoRebake, saved with the project; older projects have none). In Bake mode the app rebakes that map alone in the background once what it is baked from has stopped changing for half a second; a change during that bake cancels it and the newest settings bake instead. Only a failed rebake makes a toast. --- crates/core/src/project.rs | 4 + crates/engine/src/bake/auto_rebake.rs | 51 +++++++++++++ crates/engine/src/bake/bake_log.rs | 13 ++++ crates/engine/src/bake/mesh_map_command.rs | 15 ++-- crates/engine/src/bake/mod.rs | 2 + crates/engine/src/inspect.rs | 1 + crates/engine/tests/it/auto_rebake.rs | 68 +++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/auto_rebake.rs | 79 ++++++++++++++++++++ crates/ui-egui/src/bake_job.rs | 2 + crates/ui-egui/src/bake_report.rs | 6 +- crates/ui-egui/src/lib.rs | 27 +++++-- crates/ui-egui/src/updates_ui.rs | 2 +- crates/ui-egui/tests/bake_preview.rs | 1 + crates/ui-egui/tests/it/auto_rebake.rs | 87 ++++++++++++++++++++++ crates/ui-egui/tests/it/bake_job_mesh.rs | 2 +- crates/ui-egui/tests/it/baking_log.rs | 12 +++ crates/ui-egui/tests/it/main.rs | 1 + docs/control-protocol.md | 7 ++ 19 files changed, 365 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/bake/auto_rebake.rs create mode 100644 crates/engine/tests/it/auto_rebake.rs create mode 100644 crates/ui-egui/src/auto_rebake.rs create mode 100644 crates/ui-egui/tests/it/auto_rebake.rs diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 69437007..ca70f6ff 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -72,6 +72,9 @@ pub struct TextureSet { /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub bake_sources: BTreeMap, + /// The one mesh map the app rebakes by itself when what it is baked from changes + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_rebake: Option, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -175,6 +178,7 @@ impl TextureSet { bake: BakeSettings::default(), baked: BTreeSet::new(), bake_sources: BTreeMap::new(), + auto_rebake: None, visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs new file mode 100644 index 00000000..45831b82 --- /dev/null +++ b/crates/engine/src/bake/auto_rebake.rs @@ -0,0 +1,51 @@ +//! Auto-rebake: the one mesh map per texture set that is baked again whenever what it is baked from changes + +use serde_json::{Value, json}; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::commands::{CommandSpec, always, bad, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "bake.autoRebake", + "Auto-rebake", + [], + None, + "{ts?: index (default: the active set), map: id | null} → {ts, autoRebake: id | null}. Turn on Auto-rebake for one mesh map of the set (it replaces the set's previous one), or turn it off with null. The app then rebakes that map in the background once what it is baked from changes", + always, + set_auto_rebake + )] +} + +fn set_auto_rebake(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.autoRebake"; + let texture_set = match params.get("ts") { + None => session.ts(), + Some(_) => u64p(params, "ts").map(|index| index as usize).filter(|index| *index < session.set_count()).ok_or_else(|| bad(COMMAND, "invalid `ts`"))?, + }; + let map = match params.get("map") { + Some(Value::Null) => None, + Some(_) => Some(strp(params, "map").and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, "`map` must be a mesh map id or null"))?), + None => return Err(bad(COMMAND, "`map` is required (a mesh map id or null)")), + }; + + if session.doc.project.texture_set(texture_set)?.auto_rebake != map { + session.edit("Auto-rebake", |session| { + session.doc.project.texture_set_mut(texture_set)?.auto_rebake = map; + Ok(()) + })?; + } + Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) })) +} + +impl Session { + /// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now) + pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> { + let sets = self.doc.project.texture_sets.iter().enumerate(); + sets.filter_map(|(index, set)| Some((index, set.auto_rebake?))) + .filter(|(index, map)| !self.bake_changes(*index, *map).is_empty()) + .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) + .collect() + } +} diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 7203b7c1..18ab8e2a 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -136,6 +136,19 @@ impl Session { self.bake_log.matching = matching; } + /// Start the Baking Log for a bake of only `map` of each of `sets`, checked or not + pub fn begin_map_bake_log(&mut self, sets: &[usize], map: BakedMap) { + self.begin_bake_log(sets); + let project = &self.doc.project; + self.bake_log.maps = sets + .iter() + .filter_map(|&texture_set| { + let set_name = project.texture_sets.get(texture_set)?.name.clone(); + Some(BakeLogMap { texture_set, set_name, map, state: BakeMapState::Waiting }) + }) + .collect(); + } + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it fn bake_log_matching(&self, sets: &[usize]) -> Option { let mut matching: Option = None; diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 49ec4ec0..474a5266 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -131,9 +131,14 @@ impl Session { self.bake_task_of(texture_set, None) } + /// A task that bakes only `maps` of texture set `texture_set`, checked or not; its other baked maps stay as they are + pub fn bake_task_for(&self, texture_set: usize, maps: &[BakedMap]) -> Result { + self.bake_task_of(texture_set, Some(maps)) + } + /// 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)) + self.bake_task_of(texture_set, Some(&[map])) } /// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles @@ -143,15 +148,15 @@ impl Session { Ok(task) } - fn bake_task_of(&self, texture_set: usize, only: Option) -> Result { + fn bake_task_of(&self, texture_set: usize, only: Option<&[BakedMap]>) -> 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 mut settings = set.bake.clone(); - if let Some(map) = only { - settings.maps.select([map]); + if let Some(maps) = only { + settings.maps.select(maps.iter().copied()); } // Read from the maps that bake, so a map baked alone while unchecked still gets the colours @@ -184,7 +189,7 @@ impl Session { let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed)); - let sources = set.bake.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; + let sources = settings.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; Ok(BakeTask { low_base_color, ts: texture_set, diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index ee75d670..da0599bd 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,5 +1,6 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod auto_rebake; mod bake_cage_inputs; mod bake_checks; mod bake_high_state; @@ -52,6 +53,7 @@ type MaterialColors = std::sync::Arc Vec { let mut commands = mesh_map_command::specs(); commands.extend(paint_command::specs()); + commands.extend(auto_rebake::specs()); commands.extend(tile_command::specs()); commands.extend(sync_command::specs()); commands diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index e9c3b2e5..04af908b 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -277,6 +277,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), + "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs new file mode 100644 index 00000000..c424ef47 --- /dev/null +++ b/crates/engine/tests/it/auto_rebake.rs @@ -0,0 +1,68 @@ +//! Auto-rebake: one map per texture set, due when it goes out of date, rebaked alone + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position and ID maps baked +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + session +} + +fn due_maps(session: &Session) -> Vec<(usize, BakedMap)> { + session.auto_rebake_due().into_iter().map(|(set, map, _)| (set, map)).collect() +} + +#[test] +fn one_map_per_set_is_auto_rebaked_and_it_is_due_only_once_out_of_date() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "id" })).unwrap(); + let turned_on = execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert_eq!(turned_on, json!({ "ts": 0, "autoRebake": "position" }), "the second map replaces the first"); + assert!(due_maps(&session).is_empty(), "up to date: {:?}", due_maps(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(due_maps(&session), [(0, BakedMap::Position)]); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + assert!(due_maps(&session).is_empty(), "turned off: {:?}", due_maps(&session)); + assert!(execute(&mut session, "bake.autoRebake", &json!({ "map": "glow" })).is_err()); +} + +#[test] +fn the_auto_rebake_map_is_saved_with_the_project_and_undone_like_an_edit() { + let mut session = baked_plane(); + let before = session.to_project_bytes().unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position)); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["autoRebake"], json!("position")); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None); + assert_eq!(Session::from_project_bytes(&before).unwrap().doc.project.texture_sets[0].auto_rebake, None, "older projects have none"); +} + +#[test] +fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "maps": ["id"], "positionMode": "boundingBox" })).unwrap(); + let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + + let task = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + assert_eq!(task.maps(), [BakedMap::Position], "an unchecked map bakes when asked for"); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", session.bake_changes(0, BakedMap::Position)); + let baked = session.baked(0).unwrap(); + assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::>(), [BakedMap::Id], "the checks stay"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f43035f4..843ab3d3 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone session.rs target remains available. mod add_mask_items; +mod auto_rebake; mod bake; mod bake_checks; mod bake_log; diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs new file mode 100644 index 00000000..8f20e7b0 --- /dev/null +++ b/crates/ui-egui/src/auto_rebake.rs @@ -0,0 +1,79 @@ +//! Auto-rebake: a texture set's auto-rebake map is baked again in the background once what it is baked from has stopped changing + +use texturecraft_engine::core::{BakeSource, BakedMap}; + +use crate::{BakeJob, TextureCraftApp, bake_report, state}; + +/// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts +const SETTLE_SECONDS: f64 = 0.5; + +/// An out-of-date auto-rebake map: its texture set, the map and what a bake would read now +pub type Due = (usize, BakedMap, BakeSource); + +/// What the app has seen of the out-of-date auto-rebake maps +#[derive(Default)] +pub struct AutoRebake { + /// The due maps and the frame time they were first seen as they are + pending: Option<(Vec, f64)>, + /// The due maps when the last rebake started: a failed or canceled rebake is not tried again until something changes + started: Vec, +} + +/// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed +pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.ui.mode != state::Mode::Baking { + app.auto_rebake.pending = None; + return; + } + + let due = app.session.auto_rebake_due(); + if let Some(job) = &app.bake { + // Newest wins: a rebake whose map changed again while it ran starts over with the new settings + if job.rebake.is_some_and(|rebake| !due.contains(&rebake)) { + app.cancel_bake(); + } + return; + } + + if due.is_empty() || due == app.auto_rebake.started { + app.auto_rebake.pending = None; + return; + } + + let now = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); + match &app.auto_rebake.pending { + Some((seen, since)) if *seen == due && now - since >= SETTLE_SECONDS => {} + Some((seen, _)) if *seen == due => return, + _ => { + app.auto_rebake.pending = Some((due, now)); + return; + } + } + + app.auto_rebake.pending = None; + app.auto_rebake.started = due.clone(); + if let Some(rebake) = due.first().copied() { + start(app, rebake); + } +} + +/// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake +fn start(app: &mut TextureCraftApp, rebake: Due) { + let (set, map, _) = rebake; + let orders = match app.session.bake_preview_orders(&[set], Some(map)) { + Ok(orders) => orders, + Err(error) => { + app.toast(error.to_string(), true); + return; + } + }; + + // Restore the previous view before the rebake takes it over + app.live_preview.release(&mut app.session); + crate::id_color_pick::IdColorPick::end(app); + app.session.bake_preview_begin(orders); + app.session.begin_map_bake_log(&[set], map); + app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; + app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index 97dd4610..431999db 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -11,4 +11,6 @@ pub struct BakeJob { pub mesh_id: u64, /// The one map to bake (a row's quick bake) instead of the checked ones pub only: Option, + /// An auto-rebake: the set, the one map it bakes and what that map was baked from when it started; `None` bakes every checked map + pub rebake: Option, } diff --git a/crates/ui-egui/src/bake_report.rs b/crates/ui-egui/src/bake_report.rs index d0423de9..89e1ebf6 100644 --- a/crates/ui-egui/src/bake_report.rs +++ b/crates/ui-egui/src/bake_report.rs @@ -10,6 +10,8 @@ pub struct BakeReport { pub map_count: usize, /// Number of texture sets whose bake failed pub failed_set_count: usize, + /// A rebake the app started by itself (Auto-rebake): only a failure makes a toast + pub auto_rebake: bool, } impl BakeReport { @@ -57,7 +59,7 @@ mod tests { #[test] fn success_names_maps_and_time() { - let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0 }; + let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0, auto_rebake: false }; let (text, line, failed) = report.summary(22.34); @@ -68,7 +70,7 @@ mod tests { #[test] fn failures_are_counted_and_point_to_the_log() { - let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2 }; + let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2, auto_rebake: false }; let (text, _, failed) = report.summary(125.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4346c304..2816c247 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,15 +10,16 @@ mod anchor_properties; mod angle_dial; mod ask; +mod auto_rebake; #[cfg(not(target_arch = "wasm32"))] mod autosave_name; mod bake_job; pub mod bake_mode; -pub mod baking_log; mod bake_preset; pub mod bake_presets; mod bake_report; mod bake_scene; +pub mod baking_log; mod color_management; mod color_picker; mod color_selection_editor; @@ -290,6 +291,8 @@ pub struct TextureCraftApp { pub bake: Option, /// What the bake running now has done so far, for the summary when it ends pub bake_report: bake_report::BakeReport, + /// When the out-of-date auto-rebake maps are rebaked + auto_rebake: auto_rebake::AutoRebake, /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, @@ -466,6 +469,7 @@ impl TextureCraftApp { gpu_memory: (Vec::new(), None), bake: None, bake_report: Default::default(), + auto_rebake: Default::default(), pbr_import: None, resize: None, #[cfg(not(target_arch = "wasm32"))] @@ -707,9 +711,12 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.begin_bake_log(&sets); + match only { + Some(map) => self.session.begin_map_bake_log(&sets, map), + None => self.session.begin_bake_log(&sets), + } 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, only }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only, rebake: None }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -886,13 +893,14 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); - let only = job.only; + let (only, rebake) = (job.only, job.rebake); self.session.bake_preview_set_current(set_index); self.session.bake_log.set_started(set_index); - let task = match only { - Some(map) => self.session.bake_task_only(set_index, map), - None => self.session.bake_task(set_index), + let task = match (rebake, only) { + (Some((_, map, _)), _) => self.session.bake_task_for(set_index, &[map]), + (None, Some(map)) => self.session.bake_task_only(set_index, map), + (None, None) => self.session.bake_task(set_index), }; match task { Ok(task) => { @@ -936,6 +944,10 @@ impl TextureCraftApp { self.session.log.info("Baker", line); } + if self.bake_report.auto_rebake && !failed { + return; + } + self.toast(text, failed); if let Some(toast) = self.toasts.last_mut() { toast.show_log = failed; @@ -1223,6 +1235,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.bake_map_thumbnails.retain_mesh(self.session.mesh_id); bake_mode::poll_live_preview(self, ctx); + auto_rebake::poll(self, ctx); self.poll_resize(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_high_poly_job(ctx); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index aeaaea1f..ce719304 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -297,7 +297,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, only: None }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None, rebake: None }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6de467e4..9bb1eae2 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -134,6 +134,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { total: 1, mesh_id, only: None, + rebake: None, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs new file mode 100644 index 00000000..5358fcf1 --- /dev/null +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -0,0 +1,87 @@ +//! Auto-rebake in the app: a settings change rebakes the auto-rebake map alone, in the background + +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; + +/// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map +fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serde_json::Value) { + execute(&mut harness.state_mut().session, "bake.settings", ¶ms).unwrap(); +} + +/// Step frames until `done` holds, up to a generous limit +fn step_until(harness: &mut Harness<'static, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { + for _ in 0..4000 { + harness.run_steps(1); + if done(harness.state()) { + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("{what} did not happen"); +} + +#[test] +fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { + let mut harness = harness(64); + let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position)); + assert!(std::sync::Arc::ptr_eq(&app.session.baked(0).unwrap().maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} + +#[test] +fn nothing_is_rebaked_outside_bake_mode() { + let mut harness = harness(64); + harness.state_mut().ui.mode = Mode::Painting; + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + harness.run_steps(120); + + assert!(harness.state().bake.is_none()); + assert!(!harness.state().session.bake_changes(0, BakedMap::Position).is_empty()); +} + +#[test] +fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { + let mut harness = harness(64); + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["ambientOcclusion"], "ao": { "rays": 1 } })).unwrap(); + execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": "ambientOcclusion" })).unwrap(); + + // A slow rebake, so the next change lands while it runs + change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } })); + step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + change_settings(&mut harness, json!({ "ao": { "rays": 128 } })); + harness.run_steps(1); + + let app = harness.state(); + assert!(app.bake.is_none(), "the outdated rebake stopped"); + assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); + execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 309bb67e..f805bfc9 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 with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes let job_mesh_id = mesh_id(harness.state().session.mesh_id); let running = RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; - harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None }); + harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); harness.step(); check(&harness, &progress); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 3d098b6f..11251da2 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -63,6 +63,18 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } +#[test] +fn a_one_map_bake_lists_only_that_map() { + let mut harness = harness(); + + harness.state_mut().start_bake_of(vec![0], Some(BakedMap::Position)); + run_to_the_end(&mut harness); + + let name = harness.state().session.doc.project.texture_sets[0].name.clone(); + assert!(harness.query_by_label(&format!("{name} Position, Baked")).is_some(), "the baked map is ticked"); + assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row"); +} + #[test] fn a_failed_maps_arrow_opens_its_settings() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0abd9441..0aa4441d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -3,6 +3,7 @@ mod alpha_parameters; mod anchor_point; +mod auto_rebake; mod bake_job_mesh; mod bake_live_preview; mod bake_map_rows; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 91fad894..308849f3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -326,6 +326,13 @@ Each texture set in `project.inspect` / `session.inspect` lists its out-of-date own). Imported maps, and maps saved before this record existed, never show: `"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. +`bake.autoRebake` `{ts?, map: id | null}` turns on Auto-rebake for one mesh map of a texture set +(the active one by default), replacing its previous one, or turns it off with `null`; it is saved +with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web +app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the +background, alone, once its settings have stopped changing for half a second; a change during +that bake restarts it. The headless CLI does not rebake by itself: run `bake.run` there. + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From 4a56683bb9a5cadf297fcdfdfa856704e01dddc9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:03:40 +0000 Subject: [PATCH 63/80] Rebake the auto-rebake map inside a skew or cage stroke A skew or cage stroke on a set that bakes from a high poly marks its UV box; in Bake mode the app then bakes the set's auto-rebake map again only there (one texel wider, for the paint map's sampling), keeps the rest of the stored map and pads the whole map, so its pixels match a whole bake. Maps scaled by their whole range (curvature, height, thickness), UV-tiled sets and a map stored at another size bake whole. A stroke painted while that bake runs is baked by the next one. The bake crate gains bake_tiles_in with a texel box. --- crates/bake/src/bake_passes.rs | 19 +++++- crates/bake/src/lib.rs | 60 ++++++++++++++++-- crates/bake/src/progress.rs | 5 +- crates/bake/src/region_bake.rs | 12 ++++ crates/bake/src/test/tile_selection.rs | 2 +- crates/bake/src/tests.rs | 2 +- crates/bake/src/texel_box.rs | 27 ++++++++ crates/engine/src/bake/auto_rebake.rs | 12 ++++ crates/engine/src/bake/bake_log.rs | 10 +-- crates/engine/src/bake/bake_sources.rs | 19 ++++-- crates/engine/src/bake/bake_task.rs | 33 ++++++---- crates/engine/src/bake/mesh_map_command.rs | 30 +++++---- crates/engine/src/bake/mod.rs | 2 + crates/engine/src/bake/paint_command.rs | 9 +++ crates/engine/src/bake/painted_region.rs | 74 ++++++++++++++++++++++ crates/engine/src/bake/streamed_bake.rs | 2 + crates/engine/src/session.rs | 6 ++ crates/engine/tests/it/auto_rebake.rs | 73 +++++++++++++++++++++ crates/engine/tests/it/bake.rs | 2 +- crates/ui-egui/src/auto_rebake.rs | 33 ++++++---- crates/ui-egui/src/lib.rs | 11 ++-- crates/ui-egui/tests/it/auto_rebake.rs | 28 ++++++++ docs/control-protocol.md | 5 +- 23 files changed, 406 insertions(+), 70 deletions(-) create mode 100644 crates/bake/src/region_bake.rs create mode 100644 crates/bake/src/texel_box.rs create mode 100644 crates/engine/src/bake/painted_region.rs diff --git a/crates/bake/src/bake_passes.rs b/crates/bake/src/bake_passes.rs index eb7d5846..503bd45d 100644 --- a/crates/bake/src/bake_passes.rs +++ b/crates/bake/src/bake_passes.rs @@ -1,7 +1,7 @@ use crate::cage::RayFrame; use crate::map::BakeContext; use crate::tracing::{CpuTracer, Tracer}; -use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake}; use std::sync::atomic::Ordering::Relaxed; use texturecraft_core::{BakeSettings, BakedMap}; @@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> { progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>, + ) -> Result { + self.bake_map_in(map, progress, excluded_tiles, None, tracer) + } + + /// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does + pub fn bake_map_in( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, ) -> Result { let mut settings = self.request.settings.clone(); settings.maps.select([map]); - self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS) } pub(super) fn run( @@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> { settings: &BakeSettings, progress: &Progress, excluded_tiles: &[(u32, u32)], + region: Option, tracer: Option<&dyn Tracer>, strip_texels: usize, ) -> Result { @@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> { } }; let context = BakeContext::with_frame(&request, *extent, frame); - let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region); match tracer { Some(tracer) => match bake(tracer) { Err(BakeError::Tracer(error)) => { diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 5c8c3ba8..50f2f54c 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -12,6 +12,8 @@ mod high_poly; mod mesh_extent; mod name_pair; mod progress; +mod region_bake; +mod texel_box; pub use bake_error::BakeError; pub use bake_output::BakeOutput; @@ -22,6 +24,8 @@ pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; pub use name_pair::NamePair; pub use progress::Progress; +pub use region_bake::RegionBake; +pub use texel_box::{TexelBox, region_keeps_pixels}; mod map; mod skew; @@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24; const BATCH: usize = 1 << 18; // Curvature batches stay small so progress and cancellation remain responsive const CURVATURE_BATCH: usize = 1 << 15; +/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero +const MIN_MESH_EXTENT: f32 = 1e-6; fn validate(request: &BakeRequest) -> Result<(), BakeError> { let settings = request.settings; @@ -161,7 +167,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) /// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) + bake_tiles_in(request, progress, excluded_tiles, None, tracer) +} + +/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps +pub fn bake_tiles_in( + request: &BakeRequest, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, +) -> Result { + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; @@ -173,8 +190,9 @@ fn bake_in_strips( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels) } fn bake_prepared( @@ -184,6 +202,7 @@ fn bake_prepared( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); @@ -211,7 +230,7 @@ fn bake_prepared( let mut padding_map = None; let total_rows = height.max(1) as u64; let mut rows_done = 0u64; - let strip_error = || BakeError::Invalid("strip output of range".into()); + let strip_error = || BakeError::Invalid("strip output out of range".into()); let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis); let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height); @@ -250,6 +269,18 @@ fn bake_prepared( } }); + // Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled + if let Some(region) = region { + for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() { + let y = (sample_start_y + row_index) / samples_per_axis; + for (sample_x, triangle) in row.iter_mut().enumerate() { + if !region.texels.contains(sample_x / samples_per_axis, y) { + *triangle = NO_TRI; + } + } + } + } + let mut output_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect(); for (map, data) in maps.iter().zip(buffers.iter_mut()) { let component_count = map.components(); @@ -258,6 +289,7 @@ fn bake_prepared( row.push(chunk); } } + let mut bake_strip = || { for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() { if progress.cancel.load(Relaxed) { @@ -276,10 +308,11 @@ fn bake_prepared( (width, samples_per_axis, sample_start_y * sample_width), )?; rows_done += batch.len() as u64; - progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed); + progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed); } Ok(()) }; + if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) { bake_strip()?; } else { @@ -291,6 +324,19 @@ fn bake_prepared( } } + if let Some(region) = region { + for (map, pixels) in maps.iter().zip(buffers.iter_mut()) { + let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len()); + let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?; + let components = map.components(); + for (index, (pixel, kept)) in pixels.chunks_exact_mut(components).zip(previous.chunks_exact(components)).enumerate() { + if !region.texels.contains(index % width, index / width) { + pixel.copy_from_slice(kept); + } + } + } + } + let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { let world_normal = @@ -306,7 +352,8 @@ fn bake_prepared( } let (bounds_min, bounds_max) = request.mesh.bounds(); - map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6)); + map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT)); + if let Some(padding_map) = padding_map { for (map, data) in output.iter_mut() { padding_map.apply(data, map.components()); @@ -315,11 +362,12 @@ fn bake_prepared( } } } + if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } - progress.done.store(10_000, Relaxed); + progress.done.store(Progress::DONE, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } diff --git a/crates/bake/src/progress.rs b/crates/bake/src/progress.rs index 5bb924ec..4f0a740c 100644 --- a/crates/bake/src/progress.rs +++ b/crates/bake/src/progress.rs @@ -8,12 +8,15 @@ pub struct Progress { } impl Progress { + /// The basis points of a finished bake + pub const DONE: u32 = 10_000; + pub fn new() -> Self { Self::default() } pub fn fraction(&self) -> f32 { - self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 + self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32 } pub fn cancel(&self) { diff --git a/crates/bake/src/region_bake.rs b/crates/bake/src/region_bake.rs new file mode 100644 index 00000000..20a14849 --- /dev/null +++ b/crates/bake/src/region_bake.rs @@ -0,0 +1,12 @@ +use std::collections::BTreeMap; +use std::sync::Arc; +use texturecraft_core::BakedMap; + +use crate::TexelBox; + +/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size +#[derive(Clone, Copy, Debug)] +pub struct RegionBake<'a> { + pub texels: TexelBox, + pub previous: &'a BTreeMap>>, +} diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs index 18f13968..a1176668 100644 --- a/crates/bake/src/test/tile_selection.rs +++ b/crates/bake/src/test/tile_selection.rs @@ -31,7 +31,7 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() { let full = bake(&request, &Progress::new()).unwrap(); for excluded in [[(0, 0)], [(1, 0)]] { let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap(); - let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap(); + let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).unwrap(); let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap(); assert_eq!(strips.maps, partial.maps); assert_eq!(fallback.maps, partial.maps); diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 7d94031e..e0d63b05 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -390,7 +390,7 @@ fn strips_match_a_single_pass() { tiles: (1, 1), }; let whole = bake(&req, &Progress::new()).unwrap(); - let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap(); + let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[], None).unwrap(); for (map, a) in &whole.maps { let b = &strips.maps[map]; let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count(); diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs new file mode 100644 index 00000000..85be4fc0 --- /dev/null +++ b/crates/bake/src/texel_box.rs @@ -0,0 +1,27 @@ +/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TexelBox { + pub min: (u32, u32), + pub max: (u32, u32), +} + +impl TexelBox { + /// Whether texel (`x`, `y`) lies inside the box + pub fn contains(&self, x: usize, y: usize) -> bool { + (self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y) + } + + /// The box grown by `texels` on every side, kept inside a `width` x `height` image + pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox { + TexelBox { + min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)), + max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)), + } + } +} + +/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours +pub fn region_keeps_pixels(map: texturecraft_core::BakedMap) -> bool { + use texturecraft_core::BakedMap; + !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) +} diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index 45831b82..e1e3cb1f 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -48,4 +48,16 @@ impl Session { .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) .collect() } + + /// The maps an auto-rebake of `map` bakes: that map alone, or with every checked map once the output size changed (storing a new size drops the old maps) + pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] }; + let (width, height) = set.bake.common.output_size(); + let stored = self.doc.baked.get(&texture_set); + let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height)); + match resized { + true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(), + false => vec![map], + } + } } diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 18ab8e2a..90e8feaf 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -136,15 +136,15 @@ impl Session { self.bake_log.matching = matching; } - /// Start the Baking Log for a bake of only `map` of each of `sets`, checked or not - pub fn begin_map_bake_log(&mut self, sets: &[usize], map: BakedMap) { + /// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not + pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) { self.begin_bake_log(sets); let project = &self.doc.project; self.bake_log.maps = sets .iter() - .filter_map(|&texture_set| { - let set_name = project.texture_sets.get(texture_set)?.name.clone(); - Some(BakeLogMap { texture_set, set_name, map, state: BakeMapState::Waiting }) + .filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone()))) + .flat_map(|(texture_set, set_name)| { + maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting }) }) .collect(); } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs index 70f7665c..e835c97c 100644 --- a/crates/engine/src/bake/bake_sources.rs +++ b/crates/engine/src/bake/bake_sources.rs @@ -44,22 +44,31 @@ impl Session { fn low_poly_fingerprint(&self) -> u64 { *self.low_poly_fingerprint.get_or_init(|| { let source = &self.source; - let floats = source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array())); + let floats = + source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array())); let words = floats.map(|float| u64::from(float.to_bits())).chain(source.indices.iter().map(|index| u64::from(*index))); fingerprint_words(words) }) } - /// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record - pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap>, stored: &[BakedMap]) -> Result<()> { + /// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record + pub(super) fn record_bake_sources( + &mut self, + texture_set: usize, + recorded: Option<(&BTreeMap, u64)>, + stored: &[BakedMap], + ) -> Result<()> { let set = self.doc.project.texture_set_mut(texture_set)?; - match sources { - Some(sources) => set.bake_sources.extend(sources), + match recorded { + Some((sources, _)) => set.bake_sources.extend(sources), None => set.bake_sources.retain(|map, _| !stored.contains(map)), } let baked = &set.baked; set.bake_sources.retain(|map, _| baked.contains(map)); + if let Some((_, painted_stroke)) = recorded { + self.forget_painted_region(texture_set, stored, painted_stroke); + } Ok(()) } } diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 3c0cb59e..35bee3b4 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,12 +1,12 @@ use super::{MergedHigh, StreamedBake, StreamedMap}; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, tracing::Tracer}; use texturecraft_compose::BakedMaps; use texturecraft_core::{BakeSettings, BakedMap}; use texturecraft_geom::{Bvh, Mesh}; -/// A self-contained bake task that can run on another thread. +/// A self-contained bake task that can run on another thread pub struct BakeTask { pub low_base_color: super::MaterialColors, pub ts: usize, @@ -14,20 +14,24 @@ pub struct BakeTask { pub bvh: Arc, pub material: usize, pub settings: BakeSettings, - /// The merged high polys, unless the set bakes from the low poly. + /// The merged high polys, unless the set bakes from the low poly pub high: Option, pub cage: Option>, pub skew: Option>, pub cage_paint: Option>, - /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. + /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles pub tiles: (u32, u32), /// Snapshot of tile selection and pixels to retain while the worker runs pub excluded_tiles: Vec<(u32, u32)>, pub previous_maps: BakedMaps, - /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). + /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`) pub tracer: Option>, /// What each map this task makes is baked from, taken when the task was made pub sources: std::collections::BTreeMap, + /// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake + pub painted_stroke: u64, + /// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel + pub region: Option, } impl BakeTask { @@ -36,13 +40,7 @@ impl BakeTask { self.settings.maps.enabled().collect() } - /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded, - /// and return all of them together. Each map is a bake of its own, so with a high poly - /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several - /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s. - /// The handed-over buffers are the returned ones too (no copy is made), so a preview that - /// keeps them costs no second set of maps. A cancel or an error leaves the maps already - /// handed over whole. + /// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result { let maps = self.maps(); let total = maps.len(); @@ -50,7 +48,7 @@ impl BakeTask { let mut passes = BakePasses::new(self.request()); for (index, map) in maps.iter().copied().enumerate() { - let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; let Some(data) = output.maps.remove(&map) else { continue }; if combined.is_none() { @@ -74,6 +72,7 @@ impl BakeTask { maps: retained, tracer: output.tracer, sources: self.sources.clone(), + painted_stroke: self.painted_stroke, }); } } @@ -89,18 +88,24 @@ impl BakeTask { maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, sources: self.sources.clone(), + painted_stroke: self.painted_stroke, }) } } } pub fn run(&self, progress: &Progress) -> Result { - let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?; Ok(output) } + /// The texels to sample, with the stored maps to take the rest from; `None` samples every texel + fn region(&self) -> Option> { + self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps }) + } + fn request(&self) -> BakeRequest<'_> { let high = self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color }); diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 474a5266..49d25503 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -206,6 +206,8 @@ impl Session { previous_maps, tracer, sources, + painted_stroke: self.painted_strokes, + region: None, }) } @@ -273,19 +275,20 @@ impl Session { Ok(()) } - /// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the - /// preview that showed them holds the same ones) + /// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?; + self.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke))) + })?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - /// Store `output`, recording what its maps were baked from when `sources` are known - fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap>) -> Result<()> { + /// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`]) + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap, u64)>) -> Result<()> { let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); - self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded) } fn store_bake_maps( @@ -294,7 +297,7 @@ impl Session { resolution: u32, height: u32, maps: BTreeMap>>, - sources: Option<&BTreeMap>, + recorded: Option<(&BTreeMap, u64)>, ) -> Result<()> { let stored: Vec = maps.keys().copied().collect(); let entry = self.doc.baked.entry(texture_set).or_default(); @@ -305,18 +308,19 @@ impl Session { entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); - self.record_bake_sources(texture_set, sources, &stored) + self.record_bake_sources(texture_set, recorded, &stored) } - /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. + /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { let mut task = self.bake_task(ts)?; if cpu { task.tracer = None; } - let out = task.run(&Progress::new())?; - let tracer = out.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?; + + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + self.edit("Bake mesh maps", |session| session.store_bake(ts, output, Some((&task.sources, task.painted_stroke))))?; self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); Ok(tracer) } @@ -897,7 +901,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result Re session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); Ok(()) })?; + session.note_bake_paint(texture_set, None); Ok(super::meshes_json(session)) } @@ -75,6 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> session.doc.bake_paint.remove(&(texture_set, target)); Ok(()) })?; + session.note_bake_paint(texture_set, None); } Ok(super::meshes_json(session)) } @@ -123,6 +125,13 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string())) })?; + + // The dabs reach `radius` from each point, and the paint map's bilinear sampling one of its texels further + let paint_texel = session.doc.bake_paint.get(&(texture_set, target)).map_or(0.0, |map| 1.0 / map.width.min(map.height).max(1) as f32); + let reach = Vec2::splat(radius + paint_texel); + let low = points.iter().fold(Vec2::INFINITY, |low, point| low.min(*point)) - reach; + let high = points.iter().fold(Vec2::NEG_INFINITY, |high, point| high.max(*point)) + reach; + session.note_bake_paint(texture_set, Some((low, high))); Ok(super::meshes_json(session)) } diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs new file mode 100644 index 00000000..4c31b533 --- /dev/null +++ b/crates/engine/src/bake/painted_region.rs @@ -0,0 +1,74 @@ +//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked + +use texturecraft_bake::{TexelBox, region_keeps_pixels}; +use texturecraft_core::{BakeSource, BakedMap}; +use texturecraft_geom::glam::Vec2; + +use crate::{Result, Session}; + +/// The UV box painted since the last bake of a texture set's auto-rebake map +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PaintedRegion { + pub uv_min: Vec2, + pub uv_max: Vec2, + /// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes + pub stroke: u64, +} + +/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it +const MARGIN_TEXELS: u32 = 1; + +impl Session { + /// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`) + pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) { + let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE)); + let (uv_min, uv_max) = match self.painted_regions.get(&texture_set) { + Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)), + None => (uv_min, uv_max), + }; + self.painted_strokes += 1; + self.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); + } + + /// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke` + pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) { + let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake); + let painted_since = self.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); + if !painted_since && auto.is_none_or(|map| stored.contains(&map)) { + self.painted_regions.remove(&texture_set); + } + } + + /// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke) + pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> { + let regions = self.painted_regions.iter(); + regions + .filter_map(|(index, region)| { + let set = self.doc.project.texture_sets.get(*index)?; + let map = set.auto_rebake.filter(|map| set.baked.contains(map))?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + (from_high && self.bake_changes(*index, map).is_empty()).then_some(())?; + Some((*index, map, self.bake_source(*index, map).ok()?, region.stroke)) + }) + .collect() + } + + /// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map + pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result { + let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?; + let Some(region) = self.painted_regions.get(&texture_set) else { return Ok(task) }; + let (width, height) = task.settings.common.output_size(); + let stored = + self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map)); + let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) }; + + let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size); + let painted = TexelBox { + min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)), + max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)), + }; + task.previous_maps = stored.clone(); + task.region = Some(painted.grown(MARGIN_TEXELS, width, height)); + Ok(task) + } +} diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs index 67d9be30..4b2895df 100644 --- a/crates/engine/src/bake/streamed_bake.rs +++ b/crates/engine/src/bake/streamed_bake.rs @@ -13,4 +13,6 @@ pub struct StreamedBake { pub tracer: String, /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) pub sources: BTreeMap, + /// The task's [`crate::BakeTask::painted_stroke`] + pub painted_stroke: u64, } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 05a0c779..35922e64 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -427,6 +427,10 @@ pub struct Session { pub(crate) source: Arc, /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it pub(crate) low_poly_fingerprint: std::sync::OnceLock, + /// Where skew or cage painting changed each texture set since its auto-rebake map was baked + pub(crate) painted_regions: std::collections::BTreeMap, + /// Skew and cage strokes so far + pub(crate) painted_strokes: u64, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Arc>)>, @@ -530,6 +534,8 @@ impl Session { project_id: next_mesh_id(), source, low_poly_fingerprint: Default::default(), + painted_regions: Default::default(), + painted_strokes: 0, mesh, bvh: Arc::new(bvh), mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index c424ef47..e5f9978a 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -66,3 +66,76 @@ fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() { assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::>(), [BakedMap::Id], "the checks stay"); } + +#[test] +fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 128 })).unwrap(); + + let maps = session.auto_rebake_maps(0, BakedMap::Position); + let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let baked = session.baked(0).unwrap(); + assert!(baked.maps.contains_key(&BakedMap::Id), "the ID map survives the new size: {:?}", baked.maps.keys().collect::>()); + assert!(session.out_of_date_maps(0).is_empty(), "{:?}", session.out_of_date_maps(0)); +} + +#[test] +fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "nothing painted since the bake"); + let before = session.baked(0).unwrap().maps[&BakedMap::Position].clone(); + + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3], [0.4, 0.35]], "radius": 0.05, "size": 64 })).unwrap(); + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)]); + assert!(session.auto_rebake_due().is_empty(), "painting is not a settings change: {:?}", due_maps(&session)); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let region = task.region.expect("a stroke rebakes only its box"); + let mut whole = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + whole.tracer = None; + let whole = whole.run(&Progress::new()).unwrap().maps.remove(&BakedMap::Position).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + + let width = output.resolution as usize; + assert!(((region.max.0 - region.min.0) as usize) < width / 2, "the box is far smaller than the map: {region:?}"); + let components = BakedMap::Position.components(); + let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components)); + let mut changed = 0; + for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() { + if region.contains(index % width, index / width) { + assert_eq!(rebaked, baked_whole, "texel {index} inside the box"); + changed += usize::from(rebaked != kept); + } else { + assert_eq!(rebaked, kept, "texel {index} outside the box"); + } + } + assert!(changed > 0, "the stroke changed the map inside its box"); + + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); +} + +#[test] +fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + let stroke = |at: f32| json!({ "points": [[at, at]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.skew.paint", &stroke(0.3)).unwrap(); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + execute(&mut session, "bake.skew.paint", &stroke(0.7)).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); +} diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 4035c0f1..ef79a439 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -527,7 +527,7 @@ fn opacity_samples_textures_next_to_a_high_poly() { } /// A plane session whose vertex normals lean, with a high poly plane `dy` above it. -fn leaning_session(lean: bool) -> Session { +pub(super) fn leaning_session(lean: bool) -> Session { let mut mesh = primitives::builtin("plane").unwrap(); if lean { mesh.normals = vec![texturecraft_engine::geom::glam::Vec3::new(0.6, 0.8, 0.0); mesh.positions.len()]; diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 8f20e7b0..49221003 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -7,16 +7,16 @@ use crate::{BakeJob, TextureCraftApp, bake_report, state}; /// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts const SETTLE_SECONDS: f64 = 0.5; -/// An out-of-date auto-rebake map: its texture set, the map and what a bake would read now -pub type Due = (usize, BakedMap, BakeSource); +/// An out-of-date auto-rebake map: set, map, what a bake reads now, and the newest stroke when only painting changed it +pub type Due = (usize, BakedMap, BakeSource, Option); /// What the app has seen of the out-of-date auto-rebake maps #[derive(Default)] pub struct AutoRebake { /// The due maps and the frame time they were first seen as they are pending: Option<(Vec, f64)>, - /// The due maps when the last rebake started: a failed or canceled rebake is not tried again until something changes - started: Vec, + /// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes + tried: Vec, } /// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed @@ -26,16 +26,20 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - let due = app.session.auto_rebake_due(); + let stale = app.session.auto_rebake_due().into_iter().map(|(set, map, source)| (set, map, source, None)); + let painted = app.session.auto_rebake_painted().into_iter().map(|(set, map, source, stroke)| (set, map, source, Some(stroke))); + let due: Vec = stale.chain(painted).collect(); if let Some(job) = &app.bake { // Newest wins: a rebake whose map changed again while it ran starts over with the new settings - if job.rebake.is_some_and(|rebake| !due.contains(&rebake)) { + if job.rebake.as_ref().is_some_and(|rebake| !due.contains(rebake)) { app.cancel_bake(); } return; } - if due.is_empty() || due == app.auto_rebake.started { + app.auto_rebake.tried.retain(|tried| due.contains(tried)); + let waiting: Vec = due.into_iter().filter(|due| !app.auto_rebake.tried.contains(due)).collect(); + if waiting.is_empty() { app.auto_rebake.pending = None; return; } @@ -43,24 +47,24 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { let now = app.last_time; ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); match &app.auto_rebake.pending { - Some((seen, since)) if *seen == due && now - since >= SETTLE_SECONDS => {} - Some((seen, _)) if *seen == due => return, + Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} + Some((seen, _)) if *seen == waiting => return, _ => { - app.auto_rebake.pending = Some((due, now)); + app.auto_rebake.pending = Some((waiting, now)); return; } } app.auto_rebake.pending = None; - app.auto_rebake.started = due.clone(); - if let Some(rebake) = due.first().copied() { + if let Some(rebake) = waiting.first().copied() { + app.auto_rebake.tried.push(rebake); start(app, rebake); } } /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { - let (set, map, _) = rebake; + let (set, map) = (rebake.0, rebake.1); let orders = match app.session.bake_preview_orders(&[set], Some(map)) { Ok(orders) => orders, Err(error) => { @@ -73,7 +77,8 @@ fn start(app: &mut TextureCraftApp, rebake: Due) { app.live_preview.release(&mut app.session); crate::id_color_pick::IdColorPick::end(app); app.session.bake_preview_begin(orders); - app.session.begin_map_bake_log(&[set], map); + let maps = app.session.auto_rebake_maps(set, map); + app.session.begin_map_bake_log(&[set], &maps); app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2816c247..24373d2e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -712,7 +712,7 @@ impl TextureCraftApp { let total = sets.len(); match only { - Some(map) => self.session.begin_map_bake_log(&sets, map), + Some(map) => self.session.begin_map_bake_log(&sets, &[map]), None => self.session.begin_bake_log(&sets), } self.bake_report = bake_report::BakeReport::started(self.last_time); @@ -893,12 +893,14 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); - let (only, rebake) = (job.only, job.rebake); + let only = job.only; + let rebake = job.rebake.as_ref().map(|(_, map, _, stroke)| (*map, stroke.is_some())); self.session.bake_preview_set_current(set_index); self.session.bake_log.set_started(set_index); let task = match (rebake, only) { - (Some((_, map, _)), _) => self.session.bake_task_for(set_index, &[map]), + (Some((map, true)), _) => self.session.bake_painted_task(set_index, map), + (Some((map, false)), _) => self.session.bake_task_for(set_index, &self.session.auto_rebake_maps(set_index, map)), (None, Some(map)) => self.session.bake_task_only(set_index, map), (None, None) => self.session.bake_task(set_index), }; @@ -954,8 +956,7 @@ impl TextureCraftApp { } } - /// Cancel the active worker, discard queued sets and restore the view. The current set's - /// preview maps are discarded; previously applied sets keep their results and undo steps. + /// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 5358fcf1..af6062e2 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -85,3 +85,31 @@ fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); } + +#[test] +fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { + let mut harness = harness(64); + let plane = primitives::builtin("plane").unwrap(); + let mut high = String::from("o Part_high\n"); + for position in &plane.positions { + high += &format!("v {} {} {}\n", position.x, position.y + 0.1, position.z); + } + for triangle in plane.indices.as_chunks::<3>().0 { + high += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1); + } + let session = &mut harness.state_mut().session; + session.add_high_poly_bytes("high.obj", high.into_bytes()).unwrap(); + execute(session, "bake.run", &json!({ "maps": ["position"] })).unwrap(); + harness.run_steps(4); + assert!(harness.state().bake.is_none(), "up to date after the bake"); + + execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 308849f3..fa72d973 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -331,7 +331,10 @@ own). Imported maps, and maps saved before this record existed, never show: with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the background, alone, once its settings have stopped changing for half a second; a change during -that bake restarts it. The headless CLI does not rebake by itself: run `bake.run` there. +that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that +bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV +box, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked +whole. The headless CLI does not rebake by itself: run `bake.run` there. `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) From f39e99069c5dd436251b0a4c08bf4b2c430b1613 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:05:31 +0000 Subject: [PATCH 64/80] Turn Auto-rebake on for the Normal map when skew painting starts The first skew stroke of a texture set turns Auto-rebake on for its Normal map, unless the set already has an auto-rebake map; it is part of the stroke's undo step. --- crates/engine/src/bake/mesh_map_command.rs | 7 ++-- crates/engine/src/bake/paint_command.rs | 32 +++++++++++++---- crates/engine/tests/it/auto_rebake.rs | 40 +++++++++++++++++++++- docs/control-protocol.md | 16 +++++---- 4 files changed, 78 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 49d25503..70b9fe7d 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -861,7 +861,9 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { let next = with_sync_partners(&session.doc.project, next, "bake.run")?; let cpu = boolp(params, "cpu") == Some(true); - let tracers = session.edit("Bake mesh maps", |session| { + // The painted boxes are not in the document, so a rolled-back bake puts them back by hand + let painted_regions = session.painted_regions.clone(); + let baked = session.edit("Bake mesh maps", |session| { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } @@ -882,7 +884,8 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { } } Ok(tracers) - })?; + }); + let tracers = baked.inspect_err(|_| session.painted_regions = painted_regions)?; for (index, tracer) in sets.iter().zip(&tracers) { session.log.info("Baker", format!("Baked texture set {index} ({tracer})")); } diff --git a/crates/engine/src/bake/paint_command.rs b/crates/engine/src/bake/paint_command.rs index 2f6c6fc0..840b097e 100644 --- a/crates/engine/src/bake/paint_command.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -3,7 +3,7 @@ use crate::{Result, Session, cmd}; use serde_json::Value; use std::sync::Arc; use texturecraft_bake::BakePaintMap; -use texturecraft_core::BakePaintTarget; +use texturecraft_core::{BakePaintTarget, BakedMap}; use texturecraft_geom::glam::Vec2; pub(super) fn specs() -> Vec { @@ -81,14 +81,22 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Ok(super::meshes_json(session)) } +/// Most UV points one `bake.paint` call takes +const MAX_POINTS: usize = 100_000; +/// Brush radius in UV units: the default, and the smallest that still paints +const DEFAULT_RADIUS: f32 = 0.03; +const MIN_RADIUS: f32 = 0.00001; +/// Side of a new paint map in texels: the default, and the range a call may ask for +const DEFAULT_PAINT_SIZE: u64 = 1024; +const PAINT_SIZES: std::ops::RangeInclusive = 16..=4096; + fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { - const MAX_POINTS: usize = 100_000; let texture_set = texture_set(session, parameters)?; let points = parameters .get("points") .and_then(Value::as_array) .filter(|points| !points.is_empty() && points.len() <= MAX_POINTS) - .ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?; + .ok_or_else(|| bad("bake.paint", format!("points must contain 1 to {MAX_POINTS} UV coordinates")))?; let points = points .iter() .map(|point| { @@ -99,17 +107,19 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } }) .collect::>>()?; + let value = number(parameters, "value", 1.0, 0.0, 1.0)?; - let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?; + let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?; let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; let size = match parameters.get("size") { - None => 1024, + None => DEFAULT_PAINT_SIZE, Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?, }; - if !(16..=4096).contains(&size) { - return Err(bad("bake.paint", "size must be between 16 and 4096")); + if !PAINT_SIZES.contains(&size) { + return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZES.start(), PAINT_SIZES.end()))); } + let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0, @@ -118,7 +128,15 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> BakePaintTarget::Cage => "Paint Cage", BakePaintTarget::Skew => "Paint Skew Correction", }; + session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| { + // Skew painting starts with Auto-rebake on for the Normal map, which shows the skew best, unless the set picked one + let first_skew = target == BakePaintTarget::Skew && !session.doc.bake_paint.contains_key(&(texture_set, target)); + let set = session.doc.project.texture_set_mut(texture_set)?; + if first_skew && set.auto_rebake.is_none() { + set.auto_rebake = Some(BakedMap::Normal); + } + let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default))); if map.values.len() == 1 { *map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?); diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index e5f9978a..8dd1d80a 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -4,7 +4,7 @@ use serde_json::json; use texturecraft_engine::bake::Progress; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::{Session, execute, sample_session}; /// A plane with its position and ID maps baked fn baked_plane() -> Session { @@ -139,3 +139,41 @@ fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); } + +#[test] +fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 0, "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "ts": 0, "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + let second = &mut session.doc.project.texture_sets[1].bake.maps.ao; + second.is_enabled = true; + second.parameters.rays.rays = 0; + + assert!(execute(&mut session, "bake.run", &json!({ "ts": "all" })).is_err(), "set 1's AO has no rays to cast"); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "set 0's stroke is still waiting for its rebake"); +} + +#[test] +fn the_first_skew_stroke_turns_auto_rebake_on_for_the_normal_map_once() { + let mut session = super::bake::leaning_session(true); + let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.cage.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "cage painting leaves it alone"); + + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Normal)); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "undone with the stroke"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position), "a map picked before stays"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "turned off after skew painting started, it stays off"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index fa72d973..8c74d39a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -305,6 +305,10 @@ also `session.inspect`'s `bakePreview`: "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} ``` +`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with +`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) +until `baking` is `null`. + `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. `highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, @@ -314,7 +318,7 @@ with no partner. It is `null` when no set of the bake matches by mesh name: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, - {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "texture set Head has no UV tiles selected for baking"}], "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}], "matching": {"lowSuffix": "_low", "highSuffix": "_high", "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} @@ -330,15 +334,13 @@ own). Imported maps, and maps saved before this record existed, never show: (the active one by default), replacing its previous one, or turns it off with `null`; it is saved with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the -background, alone, once its settings have stopped changing for half a second; a change during +background, alone (with every checked map when the output size changed), once what it is baked from has stopped changing for half a second; a change during that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV box, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked -whole. The headless CLI does not rebake by itself: run `bake.run` there. - -`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with -`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) -until `baking` is `null`. +whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its +`normal` map when the set has none, in the stroke's undo step. The headless CLI does not rebake by +itself: run `bake.run` there. A minimal client (Python, for illustration): From 7f3b16d434552acd984d96b4c899254cd1cf939f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:32:34 +0000 Subject: [PATCH 65/80] Mark out-of-date maps in Mesh Map Bakers A baked map whose mesh, high poly, cage or settings changed after its bake gets a yellow clock at the right end of its row; hovering it lists what changed. The reasons are shared with the generator's bake note. --- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 52 ++++++++++++++----- .../ui-egui/src/generator_panel/bake_note.rs | 13 +---- crates/ui-egui/src/i18n.rs | 13 +++++ crates/ui-egui/tests/it/bake_mode.rs | 22 ++++++++ 4 files changed, 77 insertions(+), 23 deletions(-) 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 7ec44f70..d6a7d741 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,15 +1,15 @@ -use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; +use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::ViewMode; -use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use texturecraft_engine::core::{BakeChange, 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::i18n::{bake_change_reason, baked_map_label, tr, trf}; use crate::property_sheet::{CHECK_SIZE, paint_check}; use crate::theme::{Tokens, semibold}; @@ -46,6 +46,8 @@ const ROW_RADIUS: u8 = 4; const HOVER_FACE_OPACITY: f32 = 0.5; /// Air above and below the hairline under Check All const RULE_AIR: f32 = 4.0; +/// Size of a row icon's tooltip title and reasons +const TOOLTIP_TEXT_SIZE: f32 = 12.0; /// 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) { @@ -85,8 +87,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe 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)); + let out_of_date = app.session.out_of_date_maps(app.session.ts()); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, changes, &mut check_drag, drag_from)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } @@ -239,13 +243,14 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// 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 +/// One baker row, with a clock at its right end while `changes` make the map out of date (`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, + changes: &[BakeChange], check_drag: &mut Option, drag_from: Option, ) -> bool { @@ -253,7 +258,7 @@ fn row( 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)); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_selected, name)); let hovered = ui.rect_contains_pointer(rect); if is_selected { @@ -280,18 +285,17 @@ fn row( thumbnail(ui, thumbnail_rect, texture.as_ref()); let mut icons_left = rect.right(); + if !changes.is_empty() { + let clock = icon_slot(&mut icons_left, rect.center().y); + out_of_date_mark(ui, clock, name, changes); + } let focus_in_row = || { ui.memory(|memory| memory.focused()) .and_then(|id| ui.ctx().read_response(id)) .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) }; if is_selected || hovered || focus_in_row() { - 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 - }; + let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); if several_sets { let shares = settings.sync.shares(BakeSyncGroup::Map(map)); let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; @@ -430,3 +434,27 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); response } + +/// The yellow clock in `rect` of a map that `changes` made out of date since its bake; hover tells what changed +fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("out_of_date"), Sense::hover()); + let title = tr("Out of date"); + let label = trf("Out of date: {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(ROW_GLYPH_SIZE), tokens.warning); + + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for change in changes { + ui.label(RichText::new(tr(bake_change_reason(*change))).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); +} + +/// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it +fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect { + let slot = Rect::from_center_size(pos2(*icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, center_y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + *icons_left = slot.left() - ROW_INSET / 2.0; + slot +} diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 4953261d..2e46ef22 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -7,7 +7,7 @@ use texturecraft_engine::bake::settings_patch; use texturecraft_engine::core::{BakeChange, BakedMap, Generator}; use crate::TextureCraftApp; -use crate::i18n::{baked_map_label, tr, trf}; +use crate::i18n::{bake_change_reason, baked_map_label, tr, trf}; use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS}; use crate::theme::{Tokens, semibold}; @@ -82,16 +82,7 @@ fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> { return reasons; } - changes - .iter() - .map(|change| match change { - BakeChange::LowPoly => tr("The mesh changed after this bake."), - BakeChange::HighPoly => tr("The high poly files changed after this bake."), - BakeChange::Cage => tr("The cage changed after this bake."), - BakeChange::Settings => tr("The common bake settings changed after this bake."), - BakeChange::MapSettings => tr("This map's bake settings changed after this bake."), - }) - .collect() + changes.iter().map(|change| tr(bake_change_reason(*change))).collect() } /// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2210638e..0b94a4fe 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -96,6 +96,19 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta } } +/// Why a baked map is out of date: one sentence for what changed after its bake +pub(crate) fn bake_change_reason(change: texturecraft_engine::core::BakeChange) -> &'static str { + use texturecraft_engine::core::BakeChange; + + match change { + BakeChange::LowPoly => n_("The mesh changed after this bake."), + BakeChange::HighPoly => n_("The high poly files changed after this bake."), + BakeChange::Cage => n_("The cage changed after this bake."), + BakeChange::Settings => n_("The common bake settings changed after this bake."), + BakeChange::MapSettings => n_("This map's bake settings changed after this bake."), + } +} + /// The saved language that follows the operating system's (Settings > Language > Default (System Language)). pub const SYSTEM_LANGUAGE: &str = ""; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 720d4c49..ca4cede4 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -697,3 +697,25 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() { assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); } + +#[test] +fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { + use serde_json::json; + use texturecraft_engine::execute; + + let mesh = texturecraft_engine::geom::primitives::builtin("plane").unwrap(); + let mut session = texturecraft_engine::Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + assert!(harness.query_by_label("Out of date: Position").is_none(), "just baked"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + harness.get_by_label("Out of date: Position"); + assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); +} From 23f27ba16d22d9dbeac2c20addadb83192ccb4c4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:35:55 +0000 Subject: [PATCH 66/80] Toggle Auto-rebake from a Mesh Map Bakers row Each row gets an Auto-rebake icon at its right end. It stays shown and bright on the set's auto-rebake map; on the other rows it shows dim while the row is hovered, and bright while the icon is hovered or has focus. Clicking it makes that map the set's auto-rebake map, or turns Auto-rebake off. --- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 104 +++++++++++++----- crates/ui-egui/src/bake_mode/mod.rs | 1 + crates/ui-egui/src/bake_mode/row_click.rs | 5 + crates/ui-egui/src/baking_log.rs | 15 ++- crates/ui-egui/tests/it/auto_rebake.rs | 77 +++++++++---- crates/ui-egui/tests/it/bake_mode.rs | 18 +++ crates/ui-egui/tests/it/baking_log.rs | 17 +-- .../ui-egui/tests/it/generator_bake_note.rs | 13 +-- crates/ui-egui/tests/it/main.rs | 17 +++ 9 files changed, 193 insertions(+), 74 deletions(-) create mode 100644 crates/ui-egui/src/bake_mode/row_click.rs 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 d6a7d741..afea363c 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,10 +1,11 @@ use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; -use serde_json::json; +use serde_json::{Value, json}; use texturecraft_engine::ViewMode; use texturecraft_engine::core::{BakeChange, BakeSettings, BakeSyncGroup, BakedMap}; use super::glyph_look::GlyphLook; +use super::row_click::RowClick; use super::set_picker::SetPicker; use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; @@ -34,8 +35,13 @@ 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 +/// Side of the header icon slots and of the list menu button const ROW_BUTTON_SIZE: f32 = 20.0; +/// Side of a row's hover icons, and the air right of each: four icons stay right of the row's middle in the Bakers column, so a click there selects the row +const ROW_ICON_SIZE: f32 = 18.0; +const ROW_ICON_GAP: f32 = 1.0; +/// Radius of the out-of-date clock on a thumbnail's corner +const CLOCK_BADGE_RADIUS: f32 = 6.0; /// Size of a row's glyphs const ROW_GLYPH_SIZE: f32 = 14.0; /// Size of the map names @@ -49,7 +55,7 @@ const RULE_AIR: f32 = 4.0; /// Size of a row icon's tooltip title and reasons const TOOLTIP_TEXT_SIZE: f32 = 12.0; -/// 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) +/// 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, a hover icon toggles Auto-rebake) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { let several_sets = app.session.doc.project.texture_sets.len() > 1; ui.add_space(HEADER_AIR); @@ -87,12 +93,18 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe 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)); - let out_of_date = app.session.out_of_date_maps(app.session.ts()); + let texture_set = app.session.ts(); for map in BakedMap::ALL { - let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, changes, &mut check_drag, drag_from)).inner { - app.ui.selected_baked_map = Some(map); - app.ui.dock.focus(Panel::MeshMapSettings); + match ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + Some(RowClick::Row) => { + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); + } + Some(RowClick::AutoRebake) => { + let map = if auto_rebake_map(app, texture_set) == Some(map) { Value::Null } else { json!(map.id()) }; + app.run("bake.autoRebake", json!({ "ts": texture_set, "map": map })); + } + None => {} } } @@ -243,17 +255,16 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row, with a clock at its right end while `changes` make the map out of date (`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 +/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check fn row( app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, - changes: &[BakeChange], check_drag: &mut Option, drag_from: Option, -) -> bool { +) -> Option { let several_sets = app.session.doc.project.texture_sets.len() > 1; let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); @@ -284,27 +295,36 @@ fn row( 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()); - let mut icons_left = rect.right(); + let texture_set = app.session.ts(); + let changes = app.session.bake_changes(texture_set, map); if !changes.is_empty() { - let clock = icon_slot(&mut icons_left, rect.center().y); - out_of_date_mark(ui, clock, name, changes); + out_of_date_mark(ui, thumbnail_rect, name, &changes); } + + // From the right: sync (with several sets), Auto-rebake, bolt, eye; Auto-rebake alone stays while on let focus_in_row = || { ui.memory(|memory| memory.focused()) .and_then(|id| ui.ctx().read_response(id)) .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) }; - if is_selected || hovered || focus_in_row() { - let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); - if several_sets { + let is_active = is_selected || hovered || focus_in_row(); + let is_auto_rebake = auto_rebake_map(app, texture_set) == Some(map); + let mut icons_left = rect.right(); + let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); + let sync_slot = several_sets.then(&mut next_icon); + let toggle = next_icon(); + let mut toggled = false; + if is_active { + if let Some(slot) = sync_slot { let shares = settings.sync.shares(BakeSyncGroup::Map(map)); let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; let glyph = if shares { icon::LINK } else { icon::LINK_BREAK }; - let sync = glyph_button(ui, next_icon(), glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); + let sync = glyph_button(ui, slot, glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); if sync.clicked() { SetPicker::open(app, &sync, SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); } } + toggled = auto_rebake_toggle(ui, toggle, name, is_auto_rebake).clicked(); let baking = app.bake_progress().is_some(); let bolt = next_icon(); let bolt_label = trf("Bake {map} Only", &[("map", &name)]); @@ -318,6 +338,10 @@ fn row( let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) }; app.run("viewport.view", json!({ "mode": mode })); } + } else if is_auto_rebake { + toggled = auto_rebake_toggle(ui, toggle, name, true).clicked(); + } else { + icons_left = rect.right(); } let name_left = thumbnail_rect.right() + THUMBNAIL_AIR; @@ -360,7 +384,35 @@ fn row( response.request_focus(); } - response.clicked() + if toggled { + Some(RowClick::AutoRebake) + } else if response.clicked() { + Some(RowClick::Row) + } else { + None + } +} + +/// The map texture set `texture_set` rebakes on its own, if any +fn auto_rebake_map(app: &TextureCraftApp, texture_set: usize) -> Option { + app.session.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake) +} + +/// The Auto-rebake toggle in `rect`: bright while on or pointed at, dim while off +fn auto_rebake_toggle(ui: &mut Ui, rect: Rect, name: &str, is_on: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("auto_rebake"), Sense::click()); + let title = tr("Auto-rebake"); + let label = trf("Auto-rebake {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_on, &label)); + + let is_pointed = response.hovered() || response.has_focus(); + let color = if is_on || is_pointed { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::ARROWS_CLOCKWISE, FontId::proportional(ROW_GLYPH_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + }) } /// 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` @@ -435,14 +487,16 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { response } -/// The yellow clock in `rect` of a map that `changes` made out of date since its bake; hover tells what changed -fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) { +/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail tells what changed +fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) { let tokens = Tokens::get(ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with("out_of_date"), Sense::hover()); + let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover()); let title = tr("Out of date"); let label = trf("Out of date: {map}", &[("map", &name)]); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); - ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(ROW_GLYPH_SIZE), tokens.warning); + let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5; + ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel); + ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning); response.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); @@ -454,7 +508,7 @@ fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) /// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect { - let slot = Rect::from_center_size(pos2(*icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, center_y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); - *icons_left = slot.left() - ROW_INSET / 2.0; + let slot = Rect::from_center_size(pos2(*icons_left - ROW_ICON_SIZE / 2.0 - ROW_ICON_GAP, center_y), vec2(ROW_ICON_SIZE, ROW_ICON_SIZE)); + *icons_left = slot.left(); slot } diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 1efb19d3..cf81d8d1 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -23,6 +23,7 @@ mod map_settings; mod map_thumbnails; mod mesh_map_bakers; pub use map_thumbnails::MapThumbnails; +mod row_click; mod set_picker; mod set_picker_purpose; mod set_picker_row; diff --git a/crates/ui-egui/src/bake_mode/row_click.rs b/crates/ui-egui/src/bake_mode/row_click.rs new file mode 100644 index 00000000..5f77dfd0 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/row_click.rs @@ -0,0 +1,5 @@ +/// What a click on a Mesh Map Bakers row hit +pub(super) enum RowClick { + Row, + AutoRebake, +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 1ee11974..e490ff85 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -124,7 +124,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { - // The set may have been deleted since the bake + // A guard against a row naming a set the session no longer has if texture_set >= app.session.set_count() { return; } @@ -226,16 +226,19 @@ fn no_issues(ui: &mut Ui, tab: BakingLogTab) { ui.allocate_rect(area, Sense::hover()); } -/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting's name in SemiBold +/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting and its value in SemiBold fn matching_not_enabled(ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let mut text = egui::text::LayoutJob::default(); let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; - // One sentence to translate, its setting kept apart to set it in SemiBold - let sentence = tr("{setting} was off for this bake."); - let (before, after) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + // One sentence to translate, its setting and value kept apart to set them in SemiBold + let sentence = tr("Set {setting} to {value} to pair parts by name."); + let (before, rest) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + let (between, after) = rest.split_once("{value}").unwrap_or((rest, "")); text.append(before, 0.0, format(FontId::proportional(NAME_SIZE))); - text.append(tr("Matching by name"), 0.0, format(semibold(NAME_SIZE))); + text.append(tr("Match"), 0.0, format(semibold(NAME_SIZE))); + text.append(between, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("By Mesh Name"), 0.0, format(semibold(NAME_SIZE))); text.append(after, 0.0, format(FontId::proportional(NAME_SIZE))); let area = ui.available_rect_before_wrap(); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index af6062e2..027b3243 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -16,7 +16,10 @@ fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap(); execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness @@ -26,27 +29,14 @@ fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serd execute(&mut harness.state_mut().session, "bake.settings", ¶ms).unwrap(); } -/// Step frames until `done` holds, up to a generous limit -fn step_until(harness: &mut Harness<'static, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { - for _ in 0..4000 { - harness.run_steps(1); - if done(harness.state()) { - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("{what} did not happen"); -} - #[test] fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { let mut harness = harness(64); let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone(); change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); - step_until(&mut harness, "the rebake", |app| app.bake.is_some()); - step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); let app = harness.state(); assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position)); @@ -76,14 +66,36 @@ fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { // A slow rebake, so the next change lands while it runs change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } })); - step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); change_settings(&mut harness, json!({ "ao": { "rays": 128 } })); harness.run_steps(1); let app = harness.state(); assert!(app.bake.is_none(), "the outdated rebake stopped"); - assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); - execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + let ambient_occlusion = app.session.bake_log.maps.iter().find(|row| row.map == BakedMap::AmbientOcclusion).map(|row| row.state.clone()); + assert_eq!(ambient_occlusion, Some(BakeMapState::Canceled)); +} + +#[test] +fn a_canceled_rebake_holds_back_only_its_own_texture_set() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + for set in [0, 1] { + execute(&mut session, "bake.autoRebake", &json!({ "ts": set, "map": "position" })).unwrap(); + } + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let rebaking = |app: &TextureCraftApp, set: usize| app.bake.as_ref().and_then(|job| job.rebake.as_ref()).is_some_and(|rebake| rebake.0 == set); + + change_settings(&mut harness, json!({ "ts": "all", "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the first set's rebake", |app| rebaking(app, 0)); + harness.state_mut().cancel_bake(); + + super::step_until(&mut harness, "the second set's rebake", |app| rebaking(app, 1)); } #[test] @@ -104,8 +116,8 @@ fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { assert!(harness.state().bake.is_none(), "up to date after the bake"); execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); - step_until(&mut harness, "the rebake", |app| app.bake.is_some()); - step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); let app = harness.state(); assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); @@ -113,3 +125,26 @@ fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); } + +#[test] +fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() { + use egui_kittest::kittest::Queryable; + + let mut harness = harness(64); + let auto_rebake = |harness: &Harness<'static, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].auto_rebake; + assert_eq!(auto_rebake(&harness), Some(BakedMap::Position)); + + assert!(harness.query_by_label("Auto-rebake Normal").is_none(), "off: shown only on a hovered, focused or selected row"); + harness.get_by_role_and_label(egui::Role::Button, "Normal").hover(); + harness.run_steps(2); + harness.get_by_label("Auto-rebake Normal"); + + // ID is the selected row (the first checked map), which shows its icons + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), Some(BakedMap::Id), "one map per set: ID replaces Position"); + + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), None); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index ca4cede4..43096b28 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -698,6 +698,24 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() { assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); } +#[test] +fn a_click_on_the_middle_of_an_out_of_date_row_selects_its_map_and_bakes_nothing() { + use serde_json::json; + use texturecraft_engine::execute; + + // Two sets show every hover icon (sync, Auto-rebake, bolt, eye) and the changed settings add the out-of-date clock + let mut harness = harness(None); + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_label("Out of date: Ambient Occlusion"); + + select_map(&mut harness, "Ambient Occlusion"); + assert!(harness.state().bake_progress().is_none(), "the click landed on the row, not its Bake Only icon"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings"); + harness.get_by_label("Attenuation"); +} + #[test] fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { use serde_json::json; diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 11251da2..133ac592 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -25,17 +25,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } +/// Run frames until the bake ends, then a few more for its result to show fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { - for _ in 0..4000 { - harness.run_steps(1); - if harness.state().bake.is_none() { - harness.run_steps(2); - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("the bake did not finish"); + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); } /// Bake sets 0 and 1, where set 1 has no tile left to bake, so its bake fails @@ -199,9 +192,9 @@ fn the_matching_tab_says_when_no_set_matched_by_name() { let mut harness = harness(); harness.get_by_label("Matching by Name").click(); harness.run_steps(3); - assert!(harness.query_by_label("Matching by name was off for this bake.").is_none(), "nothing baked yet: nothing to say"); + assert!(harness.query_by_label("Set Match to By Mesh Name to pair parts by name.").is_none(), "nothing baked yet: nothing to say"); log_a_bake(&mut harness, BakeMapState::Baked); - harness.get_by_label("Matching by name was off for this bake."); + harness.get_by_label("Set Match to By Mesh Name to pair parts by name."); } diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index d26019c7..aa049fdc 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -31,17 +31,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } +/// Run frames until the bake ends, then a few more for its result to show fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { - for _ in 0..4000 { - harness.run_steps(1); - if harness.state().bake.is_none() { - harness.run_steps(2); - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("the bake did not finish"); + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0aa4441d..bdb3c483 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -196,6 +196,23 @@ fn assert_list_leaves_the_wheel_and_closes(harness: &mut Harness<'_, TextureCraf assert!(!egui::Popup::is_any_open(&harness.ctx), "a click outside closes the list"); } +/// Most frames [`step_until`] waits, and its pause between them for background work +const STEP_UNTIL_FRAMES: usize = 4000; +const STEP_UNTIL_PAUSE: std::time::Duration = std::time::Duration::from_millis(2); + +/// Step frames until `done` holds, up to a generous limit +fn step_until(harness: &mut Harness<'_, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { + for _ in 0..STEP_UNTIL_FRAMES { + harness.run_steps(1); + if done(harness.state()) { + return; + } + + std::thread::sleep(STEP_UNTIL_PAUSE); + } + panic!("{what} did not happen"); +} + /// 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); From ff513841646f362aebbd9db41e8a90b9aa35e1d7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:18:22 +0000 Subject: [PATCH 67/80] Keep a canceled bake's finished maps and name the rebaked map in the footer Cancelling a bake threw away the maps the running texture set had already finished, so the Baking Log turned their ticks into warnings. The set now keeps them as one undo step, also when the preview closed because Bake mode was left; only maps that had not finished warn, and a map it did not finish keeps its out-of-date mark. A bake at a new output size keeps none, since storing them would drop the set's other maps. An auto-rebake started its preview with every checked map of the set, so the progress footer named the set's first map ("Baking Normal (1/7)") while it rebaked AO. The preview now lists only the maps the rebake makes. --- crates/engine/src/bake/bake_log.rs | 6 +-- crates/engine/src/bake/canceled_bake.rs | 37 +++++++++++++++++ crates/engine/src/bake/mesh_map_command.rs | 2 +- crates/engine/src/bake/mod.rs | 1 + crates/engine/src/bake_preview.rs | 4 +- crates/engine/tests/bake_preview.rs | 4 +- crates/engine/tests/it/bake_log.rs | 31 ++++++++++++++ crates/ui-egui/src/auto_rebake.rs | 13 ++---- crates/ui-egui/src/lib.rs | 48 +++++++++++++++++----- crates/ui-egui/src/running_bake.rs | 5 +++ crates/ui-egui/tests/bake_preview.rs | 8 +++- crates/ui-egui/tests/it/auto_rebake.rs | 11 +++++ crates/ui-egui/tests/it/bake_job_mesh.rs | 14 ++++++- crates/ui-egui/tests/it/baking_log.rs | 30 ++++++++++++++ docs/control-protocol.md | 7 ++-- 15 files changed, 186 insertions(+), 35 deletions(-) create mode 100644 crates/engine/src/bake/canceled_bake.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 90e8feaf..2f7936c8 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -83,10 +83,10 @@ impl BakeLog { } } - /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled - pub fn cancel(&mut self, current: Option) { + /// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept) + pub fn cancel(&mut self, discarded: Option) { for row in &mut self.maps { - if row.state.is_pending() || (Some(row.texture_set) == current && row.state == BakeMapState::Baked) { + if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) { row.state = BakeMapState::Canceled; } } diff --git a/crates/engine/src/bake/canceled_bake.rs b/crates/engine/src/bake/canceled_bake.rs new file mode 100644 index 00000000..ed9d8a98 --- /dev/null +++ b/crates/engine/src/bake/canceled_bake.rs @@ -0,0 +1,37 @@ +//! A canceled bake keeps the maps it finished: the Baking Log ticked them and the 3D view may have shown them + +use std::collections::BTreeMap; + +use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::{Result, Session}; + +impl Session { + /// Store the maps the canceled bake of `texture_set` `finished` as one undo step and return them; none at a new output size, which would drop the set's other maps + pub fn keep_canceled_bake( + &mut self, + texture_set: usize, + finished: BakedMaps, + sources: &BTreeMap, + painted_stroke: u64, + ) -> Result> { + let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) }; + let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| { + !stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height)) + }); + if resized { + return Ok(Vec::new()); + } + + // A map the bake did not finish keeps the record of what its stored pixels were baked from + let kept_sources: BTreeMap = + sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect(); + let kept: Vec = finished.maps.keys().copied().collect(); + self.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke))) + })?; + self.log.info("Baker", format!("Kept {} baked maps of texture set {texture_set} from the canceled bake", kept.len())); + Ok(kept) + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 70b9fe7d..c4361180 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -291,7 +291,7 @@ impl Session { self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded) } - fn store_bake_maps( + pub(super) fn store_bake_maps( &mut self, texture_set: usize, resolution: u32, diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 8ee7bc98..6065034f 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -13,6 +13,7 @@ mod bake_mesh; mod bake_meshes; mod bake_sources; mod bake_task; +mod canceled_bake; mod high_poly_load; mod high_poly_missed; mod layout; diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index d8a03d8b..6835d13b 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,8 +1,8 @@ //! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon //! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in //! the document: nothing enters the undo history until a texture set's bake is applied -//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already -//! applied keep their results and undo steps. The preview shows one map at a time, raw on the +//! ([`Session::apply_streamed_bake`]). Cancellation keeps the maps the current set finished +//! ([`Session::keep_canceled_bake`], even when the preview closed); applied sets keep their results and undo steps. The preview shows one map at a time, raw on the //! model; maps and texture sets not baked yet show their neutral value. mod preview_set; diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs index d416e183..e4c6a031 100644 --- a/crates/engine/tests/bake_preview.rs +++ b/crates/engine/tests/bake_preview.rs @@ -1,5 +1,5 @@ //! Live bake preview: maps stream into the view while a bake runs, the view mode comes back, -//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it +//! painting is paused, ending the preview leaves the set it was baking alone (sets finished before it //! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the //! document share each map's buffer instead of holding two copies. @@ -215,7 +215,7 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { assert!(**data == full.maps[map], "{map:?}"); } - // What the app does on cancel: end the preview; the document keeps what it had + // Ending the preview alone leaves the document as it was; the app keeps finished maps through keep_canceled_bake session.bake_preview_end(); assert_eq!(session.doc.baked.get(&0).cloned(), before); diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 419ce6b4..d79d0430 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; use serde_json::json; use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair}; +use texturecraft_engine::compose::BakedMaps; use texturecraft_engine::core::{BakedMap, MeshMatchMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -127,3 +128,33 @@ fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_ let log = execute(&mut session, "bake.log", &json!({})).unwrap(); assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); } + +#[test] +fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() { + let mut session = sample_session(256, 64).unwrap(); + let before = session.baked(0).cloned().unwrap(); + let resolution = before.resolution * 2; + let data = std::sync::Arc::new(vec![0.5; (resolution * resolution) as usize * BakedMap::Normal.components()]); + let finished = BakedMaps { resolution, maps: [(BakedMap::Normal, data)].into() }; + + let kept = session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + assert!(kept.is_empty(), "{kept:?}"); + assert_eq!(session.baked(0).map(|baked| baked.maps.keys().copied().collect::>()), Some(before.maps.keys().copied().collect())); + assert_eq!(session.baked(0).map(|baked| baked.resolution), Some(before.resolution)); +} + +#[test] +fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() { + let mut session = sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["id", "position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + let task = session.bake_task_for(0, &[BakedMap::Id, BakedMap::Position]).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(BakedMap::Id, stored.maps[&BakedMap::Id].clone())].into() }; + + let kept = session.keep_canceled_bake(0, finished, &task.sources, task.painted_stroke).unwrap(); + + assert_eq!(kept, [BakedMap::Id]); + assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date"); +} diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 49221003..8d16ca41 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -65,20 +65,15 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { let (set, map) = (rebake.0, rebake.1); - let orders = match app.session.bake_preview_orders(&[set], Some(map)) { - Ok(orders) => orders, - Err(error) => { - app.toast(error.to_string(), true); - return; - } - }; // Restore the previous view before the rebake takes it over app.live_preview.release(&mut app.session); crate::id_color_pick::IdColorPick::end(app); - app.session.bake_preview_begin(orders); + + // The progress footer names the maps this rebake makes, not every checked map of the set let maps = app.session.auto_rebake_maps(set, map); + app.session.bake_preview_begin(vec![(set, maps.clone())]); app.session.begin_map_bake_log(&[set], &maps); app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; - app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); + app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) }); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 24373d2e..cb772815 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -839,12 +839,14 @@ impl TextureCraftApp { } ctx.request_repaint_after(BAKE_POLL_INTERVAL); - if let Some(running) = &job.current { + if let Some(running) = &mut job.current { let set_index = running.set_index; // Wait for the sender to close so the last map also gets a preview frame match running.maps.try_recv() { Ok(map) => { + running.finished.resolution = map.resolution; + running.finished.maps.insert(map.map, map.data.clone()); self.session.bake_log.map_baked(set_index, map.map); self.session.bake_preview_map(set_index, map); return; @@ -868,16 +870,12 @@ impl TextureCraftApp { } Ok(Err(error)) => { // The worker's error ends the whole bake; the maps of the sets before it stay - self.bake_failed(set_index, &error.to_string()); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, &error.to_string()); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.bake_failed(set_index, i18n::tr("The bake worker stopped")); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, i18n::tr("The bake worker stopped")); return; } } @@ -910,6 +908,7 @@ impl TextureCraftApp { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); + let (sources, painted_stroke) = (task.sources.clone(), task.painted_stroke); let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let worker_done = maps_done.clone(); let (sender, maps) = std::sync::mpsc::channel(); @@ -923,13 +922,25 @@ impl TextureCraftApp { }); if let Some(job) = self.bake.as_mut() { - job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); + job.current = + Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total, finished: Default::default(), sources, painted_stroke }); } } Err(error) => self.bake_failed(set_index, &error.to_string()), } } + /// End the bake at texture set `set_index`, whose worker failed: none of its maps are kept, the queued sets are canceled + fn end_failed_bake(&mut self, set_index: usize, error: &str) { + if let Some(job) = &mut self.bake { + job.current = None; + } + + self.bake_failed(set_index, error); + self.cancel_bake(); + self.finish_bake_report(); + } + /// Note a texture set whose bake failed: one Log line, counted in the summary fn bake_failed(&mut self, set_index: usize, error: &str) { self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}")); @@ -956,16 +967,31 @@ impl TextureCraftApp { } } - /// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps + /// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps, the running set keeps the maps it finished pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); + let mut discarded = None; if let Some(running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); + + // Maps baked for a mesh that has since been replaced are never kept + let same_mesh = job.mesh_id == self.session.mesh_id; + let kept = match same_mesh { + true => { + self.session.keep_canceled_bake(running.set_index, running.finished, &running.sources, running.painted_stroke).unwrap_or_else(|error| { + self.toast(error.to_string(), true); + Vec::new() + }) + } + false => Vec::new(), + }; + if kept.is_empty() { + discarded = Some(running.set_index); + } } - // Only the current set is uncommitted; completed sets remain applied + self.session.bake_log.cancel(discarded); self.session.bake_preview_end(); } diff --git a/crates/ui-egui/src/running_bake.rs b/crates/ui-egui/src/running_bake.rs index 512af28a..76427ad4 100644 --- a/crates/ui-egui/src/running_bake.rs +++ b/crates/ui-egui/src/running_bake.rs @@ -12,4 +12,9 @@ pub struct RunningBake { /// Maps finished so far, and how many the set makes. pub maps_done: Arc, pub maps_total: usize, + /// The maps received so far, kept when the bake is canceled even if the preview has closed + pub finished: texturecraft_engine::compose::BakedMaps, + /// What the task bakes from and the newest stroke it saw, recorded with the finished maps a cancel keeps + pub sources: std::collections::BTreeMap, + pub painted_stroke: u64, } diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 9bb1eae2..ce7be5e7 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -71,12 +71,13 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { } #[test] -fn cancelling_restores_the_view_and_leaves_the_document_alone() { +fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() { let mut harness = harness(); let before = harness.state().session.doc.baked.get(&0).cloned(); + // One frame starts the worker; a finished map shows only from the next one harness.state_mut().start_bake(vec![0]); - harness.run_steps(2); + harness.run_steps(1); assert!(harness.state().session.bake_preview_active()); let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0)); @@ -142,6 +143,9 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { maps, maps_done: Arc::new(AtomicUsize::new(MAPS.len())), maps_total: MAPS.len(), + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, }), }); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 027b3243..4e74f0be 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -46,6 +46,17 @@ fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); } +#[test] +fn the_progress_footer_names_the_map_the_rebake_makes() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + + let stage = harness.state().session.bake_preview.as_ref().and_then(|preview| preview.stage()); + assert_eq!(stage.map(|stage| (stage.map, stage.total)), Some((BakedMap::Position, 1)), "not the set's first checked map, not all its maps"); +} + #[test] fn nothing_is_rebaked_outside_bake_mode() { let mut harness = harness(64); diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index f805bfc9..c3292beb 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -20,8 +20,18 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes let (_result_sender, receiver) = std::sync::mpsc::channel(); let (_map_sender, maps) = std::sync::mpsc::channel(); let job_mesh_id = mesh_id(harness.state().session.mesh_id); - let running = - RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; + let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let running = RunningBake { + set_index: 0, + progress: progress.clone(), + receiver, + maps, + maps_done, + maps_total: 1, + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, + }; harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); harness.step(); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 133ac592..29099a64 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -68,6 +68,36 @@ fn a_one_map_bake_lists_only_that_map() { assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row"); } +#[test] +fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() { + let mut harness = harness(); + let before = harness.state().session.baked(0).cloned().unwrap_or_default(); + harness.state_mut().start_bake(vec![0, 1]); + + // Leaving Bake mode closes the preview; the bake and the maps it finishes go on + harness.state_mut().ui.mode = Mode::Painting; + let state = |app: &TextureCraftApp, set: usize, map: BakedMap| { + app.session.bake_log.maps.iter().find(|row| row.texture_set == set && row.map == map).map(|row| row.state.clone()) + }; + super::step_until(&mut harness, "set 0's first map", |app| state(app, 0, BakedMap::Id) == Some(BakeMapState::Baked)); + assert!(!harness.state().session.bake_preview_active()); + + harness.state_mut().cancel_bake(); + + let app = harness.state(); + assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick"); + for (set, map) in [(0, BakedMap::Position), (1, BakedMap::Id), (1, BakedMap::Position)] { + assert_eq!(state(app, set, map), Some(BakeMapState::Canceled), "set {set}'s unfinished {map:?} warns"); + } + let after = app.session.baked(0).cloned().unwrap_or_default(); + let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) { + (Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new), + (old, new) => old.is_some() != new.is_some(), + }; + assert!(changed(BakedMap::Id), "the ticked map is in the document"); + assert!(!changed(BakedMap::Position), "the unfinished map stays as it was"); +} + #[test] fn a_failed_maps_arrow_opens_its_settings() { let mut harness = harness(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c74d39a..b68a5c77 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -242,7 +242,7 @@ keeps its state in a throwaway file. | `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 settings and interface language without asking for confirmation. Other preferences 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.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it finished (one undo step), 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`, `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 | @@ -285,8 +285,9 @@ bake of its own, so with a high poly the transfer rays are cast once per map; th same as a single bake's. `bake.run` and the CLI bake all maps at once and never show a preview. The streamed maps are held by the session, not the document: nothing enters the undo history -until a texture set's bake is applied (one undo step); a cancelled bake leaves the set it was baking -as it was, while sets that finished before the cancel stay applied. When +until a texture set's bake is applied (one undo step); a cancelled bake applies the maps the set it was +baking had finished (one undo step; none when the bake had a new output size, since they would replace +the set's other maps), while sets that finished before the cancel stay applied. When the bake ends, is cancelled or Bake mode is left, the view mode that was in use comes back. Bake setup overlays are hidden during the preview so they cannot cover the maps; their visibility settings take effect again when the preview ends. From cb8a46deb7037525de9340c81d5ca1b9f313ce54 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:40:27 +0000 Subject: [PATCH 68/80] Name the set in a canceled bake's log line, make a bake setting drag one undo step and hold Auto-rebake while it is held A drag stays one undo step while a panel is open in its own floating window: the press is kept in egui memory, not in a frame cache that the floating window's own pass clears every frame. --- crates/engine/src/bake/canceled_bake.rs | 4 +++- crates/engine/tests/it/bake_log.rs | 14 ++++++++++++ crates/ui-egui/src/auto_rebake.rs | 6 ++++++ crates/ui-egui/src/bake_mode/mod.rs | 8 +++---- crates/ui-egui/src/property_sheet/tests.rs | 22 +++++++++++++++++++ crates/ui-egui/src/widgets.rs | 20 +++++++++++------ crates/ui-egui/tests/it/auto_rebake.rs | 15 +++++++++++++ crates/ui-egui/tests/it/bake_mode.rs | 25 ++++++++++++++++++++++ 8 files changed, 103 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/bake/canceled_bake.rs b/crates/engine/src/bake/canceled_bake.rs index ed9d8a98..08cc2bf9 100644 --- a/crates/engine/src/bake/canceled_bake.rs +++ b/crates/engine/src/bake/canceled_bake.rs @@ -31,7 +31,9 @@ impl Session { self.edit("Bake mesh maps", |session| { session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke))) })?; - self.log.info("Baker", format!("Kept {} baked maps of texture set {texture_set} from the canceled bake", kept.len())); + // Named like the Texture Set List and the progress footer, which count sets from 1 + let name = self.doc.project.texture_sets.get(texture_set).map_or_else(|| format!("{}", texture_set + 1), |set| set.name.clone()); + self.log.info("Baker", format!("Kept {} baked maps of texture set {name} from the canceled bake", kept.len())); Ok(kept) } } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index d79d0430..ee26594a 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -158,3 +158,17 @@ fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() { assert_eq!(kept, [BakedMap::Id]); assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date"); } + +#[test] +fn a_canceled_bakes_log_line_names_the_set_as_the_texture_set_list_does() { + let mut session = sample_session(256, 64).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let (map, data) = stored.maps.iter().next().map(|(map, data)| (*map, data.clone())).unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(map, data)].into() }; + + session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + let name = session.doc.project.texture_sets[0].name.clone(); + let line = session.log.iter().find(|line| line.contains("canceled bake")).map(|line| line.message.clone()).unwrap(); + assert!(line.contains(&format!("texture set {name} ")), "the first set is not numbered 0: {line}"); +} diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 8d16ca41..a18ffae0 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -46,6 +46,12 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { let now = app.last_time; ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); + + // A held press (a slider dragged and paused) is still editing: the wait starts once it is let go + if ctx.input(|input| input.pointer.any_down()) { + app.auto_rebake.pending = Some((waiting, now)); + return; + } match &app.auto_rebake.pending { Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} Some((seen, _)) if *seen == waiting => return, diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index cf81d8d1..07a5c544 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -231,15 +231,15 @@ fn edit_settings( 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 false; - } + + // One drag is one undo step: a press's later changes continue its first one + let Some(merge) = crate::widgets::press_edit(ui, ui.make_persistent_id((scroll_id, "press")), settings != before || reset.is_some()) else { return false }; let mut patch = settings_patch(&before, &settings); if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) { fields.extend(reset); } - app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); + app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch, "merge": merge })); true } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 10c7ecfd..d7d45b32 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1042,6 +1042,28 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening"); } +/// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step +#[test] +fn a_drag_stays_one_undo_step_while_another_window_draws() { + let context = egui::Context::default(); + let owner = egui::Id::unique("held editor"); + let edit = |events| { + let mut result = None; + let mut output = context.run_ui(egui::RawInput { events, ..Default::default() }, |ui| result = crate::widgets::press_edit(ui, owner, true)); + output.textures_delta.clear(); + result + }; + let press = egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + + assert_eq!(edit(vec![press]), Some(false), "the press starts an undo step"); + let viewport = egui::ViewportId::from_hash_of("floating History"); + let floating = + egui::RawInput { viewport_id: viewport, viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), ..Default::default() }; + context.run_ui(floating, |_| {}).textures_delta.clear(); + + assert_eq!(edit(Vec::new()), Some(true), "the held press continues its undo step"); +} + #[test] fn section_tabs_show_focus_before_a_keyboard_jump() { let mut harness = builder(Brightness::MediumDark).build_ui(|ui| { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 991585dc..b09f71d2 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -31,26 +31,34 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { return None; } - ui.memory_mut(|memory| { - let edits = memory.caches.cache::>(); + // Kept in memory, not a frame cache: a floating panel in its own OS window ends a pass of its own inside ours, which would clear it every frame + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|data| { let id = id.with("pointer edit"); - let previous = edits.get(&id).copied(); + let previous = data.get_temp::(id); let merge = match press { Some(start) => { - let continuing = previous == Some(start); + let continuing = previous.is_some_and(|previous| previous.press == start); if changed || continuing { - edits.set(id, start); + data.insert_temp(id, PressEdit { press: start, frame }); } continuing } // A final movement still belongs to the press that ended - None => release_only && previous.is_some(), + None => release_only && previous.is_some_and(|previous| previous.frame + 1 >= frame), }; changed.then_some(merge) }) } +/// The press an editor's last change belonged to, and the frame it was seen in +#[derive(Clone, Copy)] +struct PressEdit { + press: u64, + frame: u64, +} + /// [`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 diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 4e74f0be..faf87c78 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -159,3 +159,18 @@ fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() { harness.run_steps(2); assert_eq!(auto_rebake(&harness), None); } + +#[test] +fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_step() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + // Held still well past the settle time, as a hand pausing mid-drag + let corner = egui::pos2(1590.0, 990.0); + harness.drag_at(corner); + harness.run_steps(120); + assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts"); + + harness.drop_at(corner); + super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some()); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 43096b28..972dc919 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -737,3 +737,28 @@ fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { harness.get_by_label("Out of date: Position"); assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); } + +#[test] +fn dragging_secondary_rays_is_one_undo_step() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + select_map(&mut harness, "Ambient Occlusion"); + let rays_before = harness.state().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays; + let history_steps = harness.state().session.history_labels().len(); + + let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect(); + let at = |share: f32| egui::pos2(track.left() + track.width() * share, track.center().y); + harness.drag_at(at(0.2)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + for step in 1..=3 { + harness.hover_at(at(0.2 + 0.15 * step as f32)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + } + + // The release moves too, and that last change still belongs to the drag + harness.drop_at(at(0.8)); + harness.run_steps(crate::SETTLE_FRAMES); + + let session = &harness.state().session; + assert_ne!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays, rays_before, "the drag changed the rays"); + assert_eq!(session.history_labels().len(), history_steps + 1, "{:?}", session.history_labels()); +} From de7515bf1a2b1b199e9432c919330cc1f8336bcd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:54:13 +0000 Subject: [PATCH 69/80] Keep a stroke's box and the stroke count through undo and reimport, and give the bake rows' reasons to screen readers The painted box of an auto-rebake map now lives in the document, so undoing the rebake of a stroke makes the map due again (the stroke stays painted while the map goes back to its pixels from before it), and a rolled-back bake.run needs no hand-kept copy. A mesh reimport carries the stroke count on; before, a bake after a reimport saw every earlier stroke as newer and kept its box. The Baking Log rows, the out-of-date clock and the generator's bake note put their reasons in the accessibility tree, not only in a tooltip, and a folding high poly row exposes whether it is expanded. bake.log is kept off the shortcut list. PressEdit gets its own file, region_keeps_pixels moves beside RegionBake, and auto_rebake_due computes each map's source once. --- crates/bake/src/lib.rs | 4 +- crates/bake/src/region_bake.rs | 5 +++ crates/bake/src/texel_box.rs | 6 --- crates/engine/src/bake/auto_rebake.rs | 11 ++++-- crates/engine/src/bake/mesh_map_command.rs | 17 ++++----- crates/engine/src/bake/mod.rs | 1 - crates/engine/src/bake/paint_command.rs | 4 +- crates/engine/src/bake/painted_region.rs | 12 +++--- crates/engine/src/bake_preview.rs | 4 +- crates/engine/src/commands.rs | 16 +++++++- crates/engine/src/file_cmds.rs | 3 ++ crates/engine/src/inspect.rs | 4 +- crates/engine/src/material_lib.rs | 2 + crates/engine/src/meshmap_cmds.rs | 24 ++++++------ crates/engine/src/session.rs | 6 +-- crates/engine/src/smart_masks.rs | 1 + crates/engine/tests/it/auto_rebake.rs | 38 ++++++++++++++++++- crates/ui-egui/src/auto_rebake.rs | 2 +- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 8 ++-- crates/ui-egui/src/baking_log.rs | 18 ++++++--- .../ui-egui/src/baking_log/high_poly_list.rs | 12 +++--- .../ui-egui/src/baking_log/matching_list.rs | 11 +++--- .../ui-egui/src/generator_panel/bake_note.rs | 7 +++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/press_edit.rs | 8 ++++ crates/ui-egui/src/widgets.rs | 8 +--- crates/ui-egui/tests/it/auto_rebake.rs | 4 +- crates/ui-egui/tests/it/bake_mode.rs | 3 +- crates/ui-egui/tests/it/baking_log.rs | 21 +++++++++- .../ui-egui/tests/it/generator_bake_note.rs | 5 ++- docs/control-protocol.md | 4 +- 31 files changed, 182 insertions(+), 88 deletions(-) create mode 100644 crates/ui-egui/src/press_edit.rs diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 50f2f54c..73847b5b 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -24,8 +24,8 @@ pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; pub use name_pair::NamePair; pub use progress::Progress; -pub use region_bake::RegionBake; -pub use texel_box::{TexelBox, region_keeps_pixels}; +pub use region_bake::{RegionBake, region_keeps_pixels}; +pub use texel_box::TexelBox; mod map; mod skew; diff --git a/crates/bake/src/region_bake.rs b/crates/bake/src/region_bake.rs index 20a14849..224202f3 100644 --- a/crates/bake/src/region_bake.rs +++ b/crates/bake/src/region_bake.rs @@ -10,3 +10,8 @@ pub struct RegionBake<'a> { pub texels: TexelBox, pub previous: &'a BTreeMap>>, } + +/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours +pub fn region_keeps_pixels(map: BakedMap) -> bool { + !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) +} diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs index 85be4fc0..3dc062cf 100644 --- a/crates/bake/src/texel_box.rs +++ b/crates/bake/src/texel_box.rs @@ -19,9 +19,3 @@ impl TexelBox { } } } - -/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours -pub fn region_keeps_pixels(map: texturecraft_core::BakedMap) -> bool { - use texturecraft_core::BakedMap; - !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) -} diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index e1e3cb1f..3f50f672 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -43,10 +43,13 @@ impl Session { /// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now) pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> { let sets = self.doc.project.texture_sets.iter().enumerate(); - sets.filter_map(|(index, set)| Some((index, set.auto_rebake?))) - .filter(|(index, map)| !self.bake_changes(*index, *map).is_empty()) - .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) - .collect() + sets.filter_map(|(index, set)| { + let map = set.auto_rebake?; + let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?; + let current = self.bake_source(index, map).ok()?; + (!record.changes(¤t).is_empty()).then_some((index, map, current)) + }) + .collect() } /// The maps an auto-rebake of `map` bakes: that map alone, or with every checked map once the output size changed (storing a new size drops the old maps) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index c4361180..da66bdc2 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -311,17 +311,17 @@ impl Session { self.record_bake_sources(texture_set, recorded, &stored) } - /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran - pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { - let mut task = self.bake_task(ts)?; + /// Bake texture set `texture_set` now (blocking), on the CPU when `cpu`; returns where the rays ran + pub fn bake_now(&mut self, texture_set: usize, cpu: bool) -> Result { + let mut task = self.bake_task(texture_set)?; if cpu { task.tracer = None; } let output = task.run(&Progress::new())?; let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(ts, output, Some((&task.sources, task.painted_stroke))))?; - self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, Some((&task.sources, task.painted_stroke))))?; + self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(tracer) } @@ -861,9 +861,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { let next = with_sync_partners(&session.doc.project, next, "bake.run")?; let cpu = boolp(params, "cpu") == Some(true); - // The painted boxes are not in the document, so a rolled-back bake puts them back by hand - let painted_regions = session.painted_regions.clone(); - let baked = session.edit("Bake mesh maps", |session| { + let tracers = session.edit("Bake mesh maps", |session| { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } @@ -884,8 +882,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { } } Ok(tracers) - }); - let tracers = baked.inspect_err(|_| session.painted_regions = painted_regions)?; + })?; for (index, tracer) in sets.iter().zip(&tracers) { session.log.info("Baker", format!("Baked texture set {index} ({tracer})")); } diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 6065034f..54fa0faf 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -46,7 +46,6 @@ pub use model_patch::settings_patch; pub use painted_region::PaintedRegion; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; -pub use texturecraft_bake::NamePair; pub use texturecraft_bake::*; use crate::CommandSpec; diff --git a/crates/engine/src/bake/paint_command.rs b/crates/engine/src/bake/paint_command.rs index 840b097e..f8edd524 100644 --- a/crates/engine/src/bake/paint_command.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -86,6 +86,8 @@ const MAX_POINTS: usize = 100_000; /// Brush radius in UV units: the default, and the smallest that still paints const DEFAULT_RADIUS: f32 = 0.03; const MIN_RADIUS: f32 = 0.00001; +/// Brush hardness when a call gives none: halfway between a soft and a hard edge +const DEFAULT_HARDNESS: f32 = 0.5; /// Side of a new paint map in texels: the default, and the range a call may ask for const DEFAULT_PAINT_SIZE: u64 = 1024; const PAINT_SIZES: std::ops::RangeInclusive = 16..=4096; @@ -110,7 +112,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> let value = number(parameters, "value", 1.0, 0.0, 1.0)?; let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?; - let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; + let hardness = number(parameters, "hardness", DEFAULT_HARDNESS, 0.0, 1.0)?; let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; let size = match parameters.get("size") { None => DEFAULT_PAINT_SIZE, diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs index 4c31b533..c19db7a3 100644 --- a/crates/engine/src/bake/painted_region.rs +++ b/crates/engine/src/bake/painted_region.rs @@ -22,26 +22,26 @@ impl Session { /// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`) pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) { let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE)); - let (uv_min, uv_max) = match self.painted_regions.get(&texture_set) { + let (uv_min, uv_max) = match self.doc.painted_regions.get(&texture_set) { Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)), None => (uv_min, uv_max), }; self.painted_strokes += 1; - self.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); + self.doc.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); } /// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke` pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) { let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake); - let painted_since = self.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); + let painted_since = self.doc.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); if !painted_since && auto.is_none_or(|map| stored.contains(&map)) { - self.painted_regions.remove(&texture_set); + self.doc.painted_regions.remove(&texture_set); } } /// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke) pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> { - let regions = self.painted_regions.iter(); + let regions = self.doc.painted_regions.iter(); regions .filter_map(|(index, region)| { let set = self.doc.project.texture_sets.get(*index)?; @@ -56,7 +56,7 @@ impl Session { /// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result { let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?; - let Some(region) = self.painted_regions.get(&texture_set) else { return Ok(task) }; + let Some(region) = self.doc.painted_regions.get(&texture_set) else { return Ok(task) }; let (width, height) = task.settings.common.output_size(); let stored = self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map)); diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 6835d13b..b0a3eac8 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,8 +1,8 @@ //! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon //! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in //! the document: nothing enters the undo history until a texture set's bake is applied -//! ([`Session::apply_streamed_bake`]). Cancellation keeps the maps the current set finished -//! ([`Session::keep_canceled_bake`], even when the preview closed); applied sets keep their results and undo steps. The preview shows one map at a time, raw on the +//! ([`Session::apply_streamed_bake`]). Cancellation keeps the maps the current set finished; sets +//! already applied keep their results and undo steps. The preview shows one map at a time, raw on the //! model; maps and texture sets not baked yet show their neutral value. mod preview_set; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 41e7d619..0fb3959d 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -31,7 +31,7 @@ impl CommandSpec { /// that only return data or do nothing without parameters, and the ones that replace the /// open project (the menu asks to save first). pub fn bindable(&self) -> bool { - const NOT_FROM_A_KEY: [&str; 13] = [ + const NOT_FROM_A_KEY: [&str; 14] = [ "project.inspect", "project.templates", "project.new", @@ -43,6 +43,7 @@ impl CommandSpec { "textureSet.parts", "bake.settings", "bake.preview", + "bake.log", "camera.set", "textureSet.settings", ]; @@ -372,7 +373,18 @@ mod tests { ] { assert!(!bindable(id), "{id} needs a parameter"); } - for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] { + for id in [ + "layer.move", + "layer.list", + "project.inspect", + "edit.history", + "export.presets", + "tool.state", + "project.new", + "camera.set", + "layer.blend", + "bake.log", + ] { assert!(!bindable(id), "{id} is a query or has several forms"); } } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 5cfc235b..e5f0df92 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -289,6 +289,7 @@ impl Session { pixels: project_file.pixels, baked: project_file.baked, resources, + painted_regions: Default::default(), }, mesh, project_file.mesh, @@ -740,6 +741,8 @@ impl Session { next.modified = true; next.project_id = self.project_id; + // The painted boxes moved with the document, and a bake tells a newer stroke by this count + next.painted_strokes = self.painted_strokes; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); // Keep the stored source in the current session until reimport succeeds diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 04af908b..b914b4e7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -264,6 +264,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value { }) }) .collect(); + let out_of_date: std::collections::BTreeMap<_, Vec<_>> = + session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect())).collect(); json!({ "index": index, "name": texture_set.name, @@ -276,7 +278,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), - "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), + "outOfDate": out_of_date, "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, "active": index == session.ts(), diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 758ee3b6..da5b3ea6 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -77,6 +77,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), } } @@ -145,6 +146,7 @@ impl Session { project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), + painted_regions: Default::default(), resources, }; diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 5736c5ca..55b110e0 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -53,14 +53,14 @@ fn set(s: &mut Session, p: &Value) -> Result { pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width -pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { - let texture_set = session.doc.project.texture_set(ts)?; - let grid = texture_set.tile_grid(); - if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { +pub(crate) fn use_images(session: &mut Session, command: &str, texture_set: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let set = session.doc.project.texture_set(texture_set)?; + let grid = set.tile_grid(); + if let Some(tile) = set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { return Err(bad(command, format!("no image for UV tile {tile}"))); } - let (width, height) = image_map_size(session, command, ts)?; + let (width, height) = image_map_size(session, command, texture_set)?; // Bent normals are tangent-space maps like the normal map, so both follow the project's normal format let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX; @@ -74,11 +74,11 @@ pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: B }), }; - let entry = session.doc.baked.entry(ts).or_default(); + let entry = session.doc.baked.entry(texture_set).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); // An imported map is never out of date: nothing records what it was made from - let set = session.doc.project.texture_set_mut(ts)?; + let set = session.doc.project.texture_set_mut(texture_set)?; set.baked.insert(map); set.bake_sources.remove(&map); Ok(width) @@ -158,16 +158,16 @@ fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn( fn clear(session: &mut Session, params: &Value) -> Result { const COMMAND: &str = "textureSet.meshMap.clear"; - let ts = ts_param(session, params, COMMAND)?; + let texture_set = ts_param(session, params, COMMAND)?; let map = map_param(params, COMMAND)?; - if !session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) { - return Err(bad(COMMAND, format!("texture set {ts} has no {} map", map.id()))); + if !session.doc.baked.get(&texture_set).is_some_and(|baked| baked.maps.contains_key(&map)) { + return Err(bad(COMMAND, format!("texture set {texture_set} has no {} map", map.id()))); } session.edit("Clear mesh map", |session| { - if let Some(baked) = session.doc.baked.get_mut(&ts) { + if let Some(baked) = session.doc.baked.get_mut(&texture_set) { baked.maps.remove(&map); } - let set = session.doc.project.texture_set_mut(ts)?; + let set = session.doc.project.texture_set_mut(texture_set)?; set.baked.remove(&map); set.bake_sources.remove(&map); Ok(()) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 35922e64..670b0cfb 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -33,6 +33,8 @@ pub struct Document { pub resources: BTreeMap>>, /// High-definition meshes and cage for baking (saved inside the project) pub bake_meshes: crate::BakeMeshes, + /// Where skew or cage painting changed each texture set since its auto-rebake map was baked; undo brings a box back with the maps baked before it, and it is not saved + pub(crate) painted_regions: BTreeMap, } /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). @@ -427,8 +429,6 @@ pub struct Session { pub(crate) source: Arc, /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it pub(crate) low_poly_fingerprint: std::sync::OnceLock, - /// Where skew or cage painting changed each texture set since its auto-rebake map was baked - pub(crate) painted_regions: std::collections::BTreeMap, /// Skew and cage strokes so far pub(crate) painted_strokes: u64, pub bvh: Arc, @@ -534,7 +534,6 @@ impl Session { project_id: next_mesh_id(), source, low_poly_fingerprint: Default::default(), - painted_regions: Default::default(), painted_strokes: 0, mesh, bvh: Arc::new(bvh), @@ -656,6 +655,7 @@ impl Session { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }, mesh, mesh_source, diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index bbe0e243..f50026a8 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -243,6 +243,7 @@ impl Session { pixels: pf.pixels, baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }; let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index 8dd1d80a..9164a5ad 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -109,8 +109,8 @@ fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() { let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components)); let mut changed = 0; for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() { + assert_eq!(rebaked, baked_whole, "texel {index} matches a whole bake"); if region.contains(index % width, index / width) { - assert_eq!(rebaked, baked_whole, "texel {index} inside the box"); changed += usize::from(rebaked != kept); } else { assert_eq!(rebaked, kept, "texel {index} outside the box"); @@ -140,6 +140,42 @@ fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); } +#[test] +fn undoing_the_rebake_of_a_stroke_makes_its_box_due_again() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3]], "radius": 0.05, "size": 64 })).unwrap(); + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + + session.undo().unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the map is back to its pixels from before the stroke, which is still painted"); + session.redo().unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "redo brings the rebake back"); +} + +#[test] +fn a_bake_after_a_mesh_reimport_takes_the_strokes_painted_before_it() { + let quad = "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\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n"; + let mut session = Session::from_mesh_bytes_with_uvs("quad.obj", quad.as_bytes(), 128, "quad", None, false).unwrap(); + session.add_high_poly_bytes("quad_high.obj", quad.replace("v 1 1 0", "v 1 1 0.1").into_bytes()).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + + session.reimport_mesh(None, false).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert!(painted.is_empty(), "the bake after the reimport took the stroke: {painted:?}"); +} + #[test] fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() { let mut session = sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index a18ffae0..07bbcaab 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -70,7 +70,7 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { - let (set, map) = (rebake.0, rebake.1); + let (set, map, ..) = rebake; // Restore the previous view before the rebake takes it over app.live_preview.release(&mut app.session); 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 afea363c..fd58b9a4 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -487,21 +487,23 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { response } -/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail tells what changed +/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail, or its node's description, tells what changed fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) { let tokens = Tokens::get(ui.ctx()); let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover()); let title = tr("Out of date"); let label = trf("Out of date: {map}", &[("map", &name)]); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); + let reasons: Vec<&str> = changes.iter().map(|change| tr(bake_change_reason(*change))).collect(); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reasons.join(" "))); let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5; ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel); ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning); response.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); - for change in changes { - ui.label(RichText::new(tr(bake_change_reason(*change))).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + for reason in reasons { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); } }); } diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index e490ff85..db0db2a7 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -281,7 +281,13 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")), BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; + let reason = match &row.state { + BakeMapState::Failed(reason) => Some(reason.as_str()), + BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + describe(ui, &response, reason); let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name)); let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); @@ -307,11 +313,6 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { } } - let reason = match &row.state { - BakeMapState::Failed(reason) => Some(reason.as_str()), - BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); @@ -322,6 +323,13 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { (rect, open_clicked) } +/// Give a row's node the `reason` its tooltip shows, so a screen reader reads it without hovering +pub(super) fn describe(ui: &Ui, response: &egui::Response, reason: Option<&str>) { + if let Some(reason) = reason { + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reason)); + } +} + /// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response { let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); diff --git a/crates/ui-egui/src/baking_log/high_poly_list.rs b/crates/ui-egui/src/baking_log/high_poly_list.rs index 5f4f5977..ab6307ad 100644 --- a/crates/ui-egui/src/baking_log/high_poly_list.rs +++ b/crates/ui-egui/src/baking_log/high_poly_list.rs @@ -43,6 +43,7 @@ fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool { open = !open; ui.data_mut(|data| data.insert_temp(id, open)); } + ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); let painter = ui.painter(); if response.hovered() { @@ -69,7 +70,13 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) { BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")), BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; + let reason = match &row.state { + BakeHighState::Failed(reason) => Some(reason.as_str()), + BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file))); + super::describe(ui, &response, reason); let painter = ui.painter(); if response.hovered() { @@ -84,11 +91,6 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) { }; painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color); - let reason = match &row.state { - BakeHighState::Failed(reason) => Some(reason.as_str()), - BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs index 22ad6c46..b64565cb 100644 --- a/crates/ui-egui/src/baking_log/matching_list.rs +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -50,7 +50,13 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let no_match = tr("No match"); let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match)); + let reason = match (&pair.low, &pair.high) { + (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), + (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); + super::describe(ui, &response, reason.as_deref()); let painter = ui.painter(); if response.hovered() { @@ -65,11 +71,6 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { } rule(ui, rect); - let reason = match (&pair.low, &pair.high) { - (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), - (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 2e46ef22..44a9b4f7 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -52,9 +52,12 @@ fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, Bake let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map)); ui.label(RichText::new(glyph).color(tokens.warning)); - ui.add(egui::Label::new(&text).truncate()).on_hover_ui(|ui| { + let reasons = reasons(changes, checked); + let line = ui.add(egui::Label::new(&text).truncate()); + ui.ctx().accesskit_node_builder(line.id, |node| node.set_description(reasons.join(" "))); + line.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); - for reason in reasons(changes, checked) { + for reason in reasons { ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); } }); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cb772815..4d6ff3eb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -123,6 +123,7 @@ mod placed_fill_slot; mod placement; mod pointer_lock; mod popup_drag; +mod press_edit; mod preview_dots; mod preview_image; mod preview_request; diff --git a/crates/ui-egui/src/press_edit.rs b/crates/ui-egui/src/press_edit.rs new file mode 100644 index 00000000..22376088 --- /dev/null +++ b/crates/ui-egui/src/press_edit.rs @@ -0,0 +1,8 @@ +//! What [`crate::widgets::press_edit`] keeps of an editor's last change + +/// The press an editor's last change belonged to, and the frame it was seen in +#[derive(Clone, Copy)] +pub(crate) struct PressEdit { + pub(crate) press: u64, + pub(crate) frame: u64, +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b09f71d2..743f7fbe 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -5,6 +5,7 @@ use egui::{Color32, CornerRadius, Rect, Response, RichText, Sense, Stroke, Strok use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; +use crate::press_edit::PressEdit; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -52,13 +53,6 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { }) } -/// The press an editor's last change belonged to, and the frame it was seen in -#[derive(Clone, Copy)] -struct PressEdit { - press: u64, - frame: u64, -} - /// [`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 diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index faf87c78..398e93b8 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -165,8 +165,8 @@ fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_st let mut harness = harness(64); change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); - // Held still well past the settle time, as a hand pausing mid-drag - let corner = egui::pos2(1590.0, 990.0); + // Held still well past the settle time, as a hand pausing mid-drag, in the window's corner where no control takes the press + let corner = harness.ctx.content_rect().right_bottom() - egui::vec2(10.0, 10.0); harness.drag_at(corner); harness.run_steps(120); assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts"); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 972dc919..ad8fbe24 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -734,7 +734,8 @@ fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); harness.run_steps(3); - harness.get_by_label("Out of date: Position"); + let description = harness.get_by_label("Out of date: Position").accesskit_node().description(); + assert!(description.is_some_and(|reasons| !reasons.is_empty()), "what changed is read without hovering"); assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 29099a64..f52fe624 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -1,7 +1,7 @@ //! The Baking Log panel: the latest bake, map by map use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; @@ -56,6 +56,20 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } +#[test] +fn a_failed_rows_reason_is_read_without_hovering() { + let mut harness = harness(); + + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); + + let app = harness.state(); + let row = app.session.bake_log.maps.iter().find(|row| row.texture_set == 1).unwrap(); + let BakeMapState::Failed(reason) = &row.state else { panic!("set 1's bake failed: {:?}", row.state) }; + let label = format!("{} ID, Not baked", row.set_name); + let node = harness.get_by_label(&label); + assert_eq!(node.accesskit_node().description().as_deref(), Some(reason.as_str()), "the row's node carries its tooltip's reason"); +} + #[test] fn a_one_map_bake_lists_only_that_map() { let mut harness = harness(); @@ -174,10 +188,13 @@ fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() { harness.run_steps(3); let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); harness.get_by_label("ball_high.obj, Loaded"); + let set_row = format!("{set_name}, High poly files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(true)); - harness.get_by_label(&format!("{set_name}, High poly files")).click(); + harness.get_by_label(&set_row).click(); harness.run_steps(3); assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(false), "the row says it is folded"); } #[test] diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index aa049fdc..6c879100 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -1,7 +1,7 @@ //! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::{BakedMap, LayerId}; use texturecraft_engine::geom::primitives; @@ -40,7 +40,8 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { #[test] fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() { let mut harness = harness(); - harness.get_by_label("Curvature map not baked"); + let description = harness.get_by_label("Curvature map not baked").accesskit_node().description(); + assert!(description.is_some_and(|reasons| !reasons.is_empty()), "why the note shows is read without hovering"); execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap(); harness.run_steps(3); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b68a5c77..5c8c38a1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -335,8 +335,8 @@ own). Imported maps, and maps saved before this record existed, never show: (the active one by default), replacing its previous one, or turns it off with `null`; it is saved with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the -background, alone (with every checked map when the output size changed), once what it is baked from has stopped changing for half a second; a change during -that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that +background, alone (with every checked map when the output size changed), once what it is baked +from has stopped changing for half a second; a change during that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV box, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its From e3c299963bea5af7298d2ac38fe8caabd56a5f18 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:26:39 +0000 Subject: [PATCH 70/80] List the Baking Log, out-of-date mesh maps and Auto-rebake in the features --- docs/features.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/features.md b/docs/features.md index 2826868c..d2992ba1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -164,6 +164,16 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel with the summary and the message for each failed set. - **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. +- **Baking Log** at the bottom of Bake mode: the latest bake map by map (Baking Process), the high + poly files each set loads (High Poly Parameters) and how parts paired by name (Matching by Name), + with an issues filter; a failed or canceled map opens its settings. `bake.log` returns the same rows. +- **Out-of-date mesh maps:** each bake records what every map was baked from; a map whose mesh, high + poly, cage or settings changed since shows a clock in Mesh Map Bakers (`outOfDate` in + `project.inspect`), and a generator reading a missing or out-of-date map shows one line with a + Bake button. +- **Auto-rebake:** one map per texture set (`bake.autoRebake`, a row icon in Mesh Map Bakers) is + baked again in the background in Bake mode once what it is baked from stops changing; a skew or + cage stroke rebakes only the stroke's box. The first skew stroke turns it on for the Normal map. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), 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 From 67c8ec6470a4bfe9cf168b59cccb0f62c2a084d0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 71/80] Mask and restore a region bake's texels row by row instead of dividing per sample --- crates/bake/src/lib.rs | 15 ++++++++------- crates/bake/src/texel_box.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 73847b5b..d67c684c 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -273,10 +273,8 @@ fn bake_prepared( if let Some(region) = region { for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() { let y = (sample_start_y + row_index) / samples_per_axis; - for (sample_x, triangle) in row.iter_mut().enumerate() { - if !region.texels.contains(sample_x / samples_per_axis, y) { - *triangle = NO_TRI; - } + for outside in region.texels.outside_row(y, samples_per_axis, row.len()) { + row.get_mut(outside).unwrap_or_default().fill(NO_TRI); } } } @@ -329,9 +327,12 @@ fn bake_prepared( let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len()); let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?; let components = map.components(); - for (index, (pixel, kept)) in pixels.chunks_exact_mut(components).zip(previous.chunks_exact(components)).enumerate() { - if !region.texels.contains(index % width, index / width) { - pixel.copy_from_slice(kept); + let row_len = (width * components).max(1); + for (y, (row, kept)) in pixels.chunks_exact_mut(row_len).zip(previous.chunks_exact(row_len)).enumerate() { + for outside in region.texels.outside_row(y, components, row_len) { + if let (Some(row), Some(kept)) = (row.get_mut(outside.clone()), kept.get(outside)) { + row.copy_from_slice(kept); + } } } } diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs index 3dc062cf..306dd04b 100644 --- a/crates/bake/src/texel_box.rs +++ b/crates/bake/src/texel_box.rs @@ -1,3 +1,5 @@ +use std::ops::Range; + /// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TexelBox { @@ -11,6 +13,15 @@ impl TexelBox { (self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y) } + /// The items of texel row `y` outside the box, in a row of `len` items with `scale` items per texel: those before the box and those after it + pub fn outside_row(&self, y: usize, scale: usize, len: usize) -> [Range; 2] { + let (start, end) = match (self.min.1 as usize..self.max.1 as usize).contains(&y) { + true => ((self.min.0 as usize * scale).min(len), (self.max.0 as usize * scale).min(len)), + false => (len, len), + }; + [0..start, end.max(start)..len] + } + /// The box grown by `texels` on every side, kept inside a `width` x `height` image pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox { TexelBox { @@ -19,3 +30,28 @@ impl TexelBox { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_items_outside_a_row_are_the_ones_contains_leaves_out() { + let (width, scale) = (6, 2); + let boxes = [ + TexelBox { min: (1, 1), max: (4, 3) }, + TexelBox { min: (0, 0), max: (6, 4) }, + TexelBox { min: (3, 1), max: (9, 2) }, + TexelBox { min: (4, 1), max: (2, 3) }, + ]; + for texels in boxes { + for y in 0..4 { + let outside = texels.outside_row(y, scale, width * scale); + for item in 0..width * scale { + let is_outside = outside.iter().any(|range| range.contains(&item)); + assert_eq!(is_outside, !texels.contains(item / scale, y), "{texels:?} row {y} item {item}"); + } + } + } + } +} From 6399d008223af6b970efb5944ac7cd67abe6fccd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 72/80] Take a set's shared bake fingerprints once for all its maps, once per Mesh Map Bakers frame --- crates/engine/src/bake/bake_sources.rs | 22 ++++++++++++------- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 11 +++++----- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs index e835c97c..4235f5f8 100644 --- a/crates/engine/src/bake/bake_sources.rs +++ b/crates/engine/src/bake/bake_sources.rs @@ -9,6 +9,12 @@ use crate::{Result, Session}; impl Session { /// What a bake of `map` on texture set `texture_set` would read now pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result { + let map_settings = self.doc.project.texture_set(texture_set)?.map_settings_fingerprint(map); + Ok(BakeSource { map_settings, ..self.set_bake_source(texture_set)? }) + } + + /// What a bake of any map of texture set `texture_set` would read now, without the map's own settings (0) + fn set_bake_source(&self, texture_set: usize) -> Result { let set = self.doc.project.texture_set(texture_set)?; let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); let high_poly = match from_high { @@ -18,13 +24,7 @@ impl Session { let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile; let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint); - Ok(BakeSource { - low_poly: self.low_poly_fingerprint(), - high_poly, - cage, - settings: set.bake_settings_fingerprint(), - map_settings: set.map_settings_fingerprint(map), - }) + Ok(BakeSource { low_poly: self.low_poly_fingerprint(), high_poly, cage, settings: set.bake_settings_fingerprint(), map_settings: 0 }) } /// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record @@ -37,7 +37,13 @@ impl Session { /// The out-of-date maps of texture set `texture_set`, each with what changed pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap> { - BakedMap::ALL.into_iter().map(|map| (map, self.bake_changes(texture_set, map))).filter(|(_, changes)| !changes.is_empty()).collect() + let Ok(set) = self.doc.project.texture_set(texture_set) else { return BTreeMap::new() }; + let mut records = set.bake_sources.iter().filter(|(map, _)| set.baked.contains(map)).peekable(); + + // The fingerprints every map of the set shares are taken once + let Some(shared) = records.peek().and_then(|_| self.set_bake_source(texture_set).ok()) else { return BTreeMap::new() }; + let changes = records.map(|(map, record)| (*map, record.changes(&BakeSource { map_settings: set.map_settings_fingerprint(*map), ..shared }))); + changes.filter(|(_, changes)| !changes.is_empty()).collect() } /// Fingerprint of the low poly's own geometry (computed once per loaded mesh) 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 fd58b9a4..d2442917 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -94,8 +94,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe 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)); let texture_set = app.session.ts(); + let out_of_date = app.session.out_of_date_maps(texture_set); for map in BakedMap::ALL { - match ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); + match ui.push_id(map, |ui| row(app, ui, (map, changes), settings, map == selected, &mut check_drag, drag_from)).inner { Some(RowClick::Row) => { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); @@ -255,11 +257,11 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check +/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock naming its `changes` (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check fn row( app: &mut TextureCraftApp, ui: &mut Ui, - map: BakedMap, + (map, changes): (BakedMap, &[BakeChange]), settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option, @@ -296,9 +298,8 @@ fn row( thumbnail(ui, thumbnail_rect, texture.as_ref()); let texture_set = app.session.ts(); - let changes = app.session.bake_changes(texture_set, map); if !changes.is_empty() { - out_of_date_mark(ui, thumbnail_rect, name, &changes); + out_of_date_mark(ui, thumbnail_rect, name, changes); } // From the right: sync (with several sets), Auto-rebake, bolt, eye; Auto-rebake alone stays while on From 1ab2f153497c59e40290d25a0c311be12310d055 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 73/80] Read each auto-rebake map's bake source once per poll and compare it with its record directly --- crates/engine/src/bake/auto_rebake.rs | 2 +- crates/engine/src/bake/painted_region.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index 3f50f672..8f5704a2 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -47,7 +47,7 @@ impl Session { let map = set.auto_rebake?; let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?; let current = self.bake_source(index, map).ok()?; - (!record.changes(¤t).is_empty()).then_some((index, map, current)) + (*record != current).then_some((index, map, current)) }) .collect() } diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs index c19db7a3..0747cf0a 100644 --- a/crates/engine/src/bake/painted_region.rs +++ b/crates/engine/src/bake/painted_region.rs @@ -47,8 +47,12 @@ impl Session { let set = self.doc.project.texture_sets.get(*index)?; let map = set.auto_rebake.filter(|map| set.baked.contains(map))?; let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); - (from_high && self.bake_changes(*index, map).is_empty()).then_some(())?; - Some((*index, map, self.bake_source(*index, map).ok()?, region.stroke)) + from_high.then_some(())?; + let current = self.bake_source(*index, map).ok()?; + + // Only painting changed it: a map without a record is never out of date + let up_to_date = set.bake_sources.get(&map).is_none_or(|record| *record == current); + up_to_date.then_some((*index, map, current, region.stroke)) }) .collect() } From 8d8993aae4588a97b6f6a6d484f617d2c0b71bb0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:45:33 +0000 Subject: [PATCH 74/80] Forget the press records of earlier presses, so editors dragged once no longer stay in memory --- crates/ui-egui/src/property_sheet/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 6 ++++++ 2 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index d7d45b32..28b126c4 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1042,6 +1042,26 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening"); } +/// Editing one editor after another, a press at a time, keeps the record of the latest press only (it kept one per editor ever dragged) +#[test] +fn the_editors_of_earlier_presses_are_forgotten() { + const EDITOR_COUNT: usize = 12; + let context = egui::Context::default(); + let button = + |pressed| egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + + for editor in 0..EDITOR_COUNT { + let owner = egui::Id::unique(("distinct editor", editor)); + for pressed in [true, false] { + let input = egui::RawInput { events: vec![button(pressed)], ..Default::default() }; + context.run_ui(input, |ui| _ = crate::widgets::press_edit(ui, owner, pressed)).textures_delta.clear(); + } + } + + let kept = context.data(|data| data.count::()); + assert!(kept < 2, "{kept} editor records kept after {EDITOR_COUNT} presses"); +} + /// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step #[test] fn a_drag_stays_one_undo_step_while_another_window_draws() { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 743f7fbe..abba3370 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -41,6 +41,12 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { Some(start) => { let continuing = previous.is_some_and(|previous| previous.press == start); if changed || continuing { + // Only the latest press's editors can merge, so its first change forgets every editor of the older ones + let latest_press = egui::Id::unique("pointer edit press"); + if data.get_temp::(latest_press) != Some(start) { + data.remove_by_type::(); + data.insert_temp(latest_press, start); + } data.insert_temp(id, PressEdit { press: start, frame }); } continuing From b4e9c175754cd1e9ed9f5b2bcc529948be2eb810 Mon Sep 17 00:00:00 2001 From: Kirill M <176898419+JaffarSk24@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:16:23 +0100 Subject: [PATCH 75/80] docs: the CJK and Arabic picks need a font for their script The language picker greys out a language whose script no available font covers, so a web build with catalogs but without craft-fonts cannot pick Japanese, Chinese, Korean or Arabic. --- docs/features.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/features.md b/docs/features.md index 8c2e96d4..76d7ff01 100644 --- a/docs/features.md +++ b/docs/features.md @@ -297,7 +297,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - A **History** panel: click any step to go back to it, or forward again to an undone one. - **11 languages:** English, French, German, Spanish, Portuguese, Italian, Russian, Japanese, Chinese, Korean and Arabic, switchable live. A build without the shared craft-i18n catalogs - offers English only. + offers English only, and Japanese, Chinese, Korean and Arabic can be picked only where a font + for their script is available (craft-fonts or the system's); otherwise they show greyed out. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch navigation and project open, save and download. From fe0208f5d3db30f31a10589a1e7201f43e071bad Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:19:40 +0000 Subject: [PATCH 76/80] Count no high part as unused while a set matching "Always" bakes from it, note the occlusion Rust Runoff reads, and keep the maps still queued when a bake is canceled --- crates/core/src/layer.rs | 8 ++++ crates/engine/src/bake/bake_log.rs | 11 +++-- crates/engine/tests/it/bake_log.rs | 16 +++++++ .../ui-egui/src/generator_panel/bake_note.rs | 2 +- crates/ui-egui/src/lib.rs | 9 +++- crates/ui-egui/tests/it/bake_job_mesh.rs | 45 +++++++++++++++---- crates/ui-egui/tests/it/baking_log.rs | 14 ++++-- .../ui-egui/tests/it/generator_bake_note.rs | 13 +++++- 8 files changed, 99 insertions(+), 19 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 158a1b6a..56a8ebb0 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1268,6 +1268,14 @@ impl Generator { if reads_geometry { &[] } else { self.kind.inputs() } } + /// The mesh maps the generator reads that a bake makes: its inputs in use, and the occlusion Dripping Rust reads whole, which no input replaces + pub fn baked_maps_read(&self) -> &'static [BakedMap] { + match self.kind { + GeneratorKind::DrippingRust => &[BakedMap::AmbientOcclusion], + _ => self.inputs_in_use(), + } + } + /// 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_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 2f7936c8..c03315e7 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; use texturecraft_bake::NamePair; -use texturecraft_core::{BakedMap, Project}; +use texturecraft_core::{BakedMap, MeshMatchMode, Project}; use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh}; use crate::Session; @@ -149,13 +149,16 @@ impl Session { .collect(); } - /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it and no set matching "Always" bakes from every part fn bake_log_matching(&self, sets: &[usize]) -> Option { let mut matching: Option = None; let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new()); + let mut every_high_used = false; for &set in sets { - let (Ok(Some(pairs)), Ok(texture_set)) = (self.bake_name_pairs(set), self.doc.project.texture_set(set)) else { continue }; + let Ok(texture_set) = self.doc.project.texture_set(set) else { continue }; let settings = &texture_set.bake.high_poly; + every_high_used |= !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always; + let Ok(Some(pairs)) = self.bake_name_pairs(set) else { continue }; let matching = matching.get_or_insert_with(|| BakeLogMatching { low_suffix: settings.low_suffix.clone(), high_suffix: settings.high_suffix.clone(), @@ -173,7 +176,7 @@ impl Session { } } - if let Some(matching) = &mut matching { + if let Some(matching) = matching.as_mut().filter(|_| !every_high_used) { let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high)); matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) })); } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index ee26594a..2fbd461b 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -129,6 +129,22 @@ fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_ assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); } +#[test] +fn a_high_part_counts_as_unused_only_when_no_set_of_the_bake_matches_always() { + let obj = "o Box_low\nusemtl Body\nv 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\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + session.begin_bake_log(&[0, 1]); + + let matching = session.bake_log.matching.clone().unwrap(); + assert!(matching.pairs.iter().all(|pair| pair.low.is_some()), "the set matching \"Always\" bakes from Extra_high: {:?}", matching.pairs); + assert_eq!(matching.issue_count(), 0); +} + #[test] fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() { let mut session = sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 44a9b4f7..4d576753 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -23,7 +23,7 @@ const TOOLTIP_TEXT_SIZE: f32 = 12.0; /// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) { let texture_set = app.session.ts(); - for map in generator.inputs_in_use() { + for map in generator.baked_maps_read() { if generator.inputs.contains_key(map) { continue; } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4d6ff3eb..5e793a7c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -973,9 +973,16 @@ impl TextureCraftApp { let Some(job) = self.bake.take() else { return }; let mut discarded = None; - if let Some(running) = job.current { + if let Some(mut running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); + // The maps the worker sent that no frame has taken yet are finished too + while let Ok(map) = running.maps.try_recv() { + running.finished.resolution = map.resolution; + running.finished.maps.insert(map.map, map.data); + self.session.bake_log.map_baked(running.set_index, map.map); + } + // Maps baked for a mesh that has since been replaced are never kept let same_mesh = job.mesh_id == self.session.mesh_id; let kept = match same_mesh { diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index c3292beb..8b3971b2 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -1,15 +1,27 @@ -//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps -//! the mesh meanwhile, the job is cancelled and its result is dropped. +//! A bake job belongs to the mesh it started on: when `file.changeMesh` or a reimport swaps the mesh meanwhile, the job is cancelled and its result dropped; a cancel keeps the maps it finished use std::sync::Arc; use std::sync::atomic::Ordering; +use std::sync::mpsc::Sender; use egui_kittest::Harness; +use texturecraft_engine::StreamedMap; use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; -/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id` fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harness<'static, TextureCraftApp>, &Progress)) { + let (mut harness, progress, _senders) = running_job(mesh_id); + harness.step(); + check(&harness, &progress); +} + +/// The ends a test plays the bake worker with: its result (never sent) and its finished maps +type WorkerSenders = (Sender>, Sender); + +/// An app with a running bake job of set 0 started on mesh `mesh_id`, whose worker sends only what the test sends +fn running_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc, WorkerSenders) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder() .with_size(egui::vec2(1600.0, 960.0)) @@ -17,8 +29,8 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); let progress = Arc::new(Progress::new()); - let (_result_sender, receiver) = std::sync::mpsc::channel(); - let (_map_sender, maps) = std::sync::mpsc::channel(); + let (result_sender, receiver) = std::sync::mpsc::channel(); + let (map_sender, maps) = std::sync::mpsc::channel(); let job_mesh_id = mesh_id(harness.state().session.mesh_id); let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let running = RunningBake { @@ -33,9 +45,7 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes painted_stroke: 0, }; harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); - - harness.step(); - check(&harness, &progress); + (harness, progress, (result_sender, map_sender)) } #[test] @@ -59,3 +69,22 @@ fn a_job_on_the_current_mesh_keeps_running() { }, ); } + +#[test] +fn a_cancel_keeps_the_maps_the_worker_sent_before_any_frame_took_them() { + let (mut harness, _progress, (_result_sender, map_sender)) = running_job(|current| current); + let data = Arc::new(vec![0.5; 64 * 64]); + let normal_before = harness.state().session.baked(0).and_then(|baked| baked.maps.get(&BakedMap::Normal).cloned()); + assert!(normal_before.is_some(), "the sample's Normal map is baked before the job"); + for (index, map) in [BakedMap::Curvature, BakedMap::AmbientOcclusion].into_iter().enumerate() { + map_sender.send(StreamedMap { map, index, total: 2, resolution: 64, height: 64, data: data.clone() }).unwrap(); + } + + harness.state_mut().cancel_bake(); + let baked = harness.state().session.baked(0).unwrap(); + for map in [BakedMap::Curvature, BakedMap::AmbientOcclusion] { + assert!(baked.maps.get(&map).is_some_and(|kept| Arc::ptr_eq(kept, &data)), "{map:?} is kept"); + } + let normal = baked.maps.get(&BakedMap::Normal); + assert!(normal.zip(normal_before.as_ref()).is_some_and(|(now, before)| Arc::ptr_eq(now, before)), "a map the worker never sent keeps the one baked before"); +} diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index f52fe624..5e7e9681 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -100,16 +100,22 @@ fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() { let app = harness.state(); assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick"); - for (set, map) in [(0, BakedMap::Position), (1, BakedMap::Id), (1, BakedMap::Position)] { - assert_eq!(state(app, set, map), Some(BakeMapState::Canceled), "set {set}'s unfinished {map:?} warns"); + for map in [BakedMap::Id, BakedMap::Position] { + assert_eq!(state(app, 1, map), Some(BakeMapState::Canceled), "set 1 was still queued, so its {map:?} warns"); } + + // A map the worker sent before the cancel is kept too, so whether set 0's Position finished depends on timing + let row = state(app, 0, BakedMap::Position); + assert!(matches!(row, Some(BakeMapState::Baked | BakeMapState::Canceled)), "set 0's Position is ticked or, unfinished, warns: {row:?}"); let after = app.session.baked(0).cloned().unwrap_or_default(); let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) { (Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new), (old, new) => old.is_some() != new.is_some(), }; - assert!(changed(BakedMap::Id), "the ticked map is in the document"); - assert!(!changed(BakedMap::Position), "the unfinished map stays as it was"); + for map in [BakedMap::Id, BakedMap::Position] { + let ticked = state(app, 0, map) == Some(BakeMapState::Baked); + assert_eq!(changed(map), ticked, "set 0's {map:?} is in the document exactly when its row is ticked"); + } } #[test] diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index 6c879100..b4c2be8a 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -11,12 +11,17 @@ use texturecraft_ui_egui::docking::Panel; /// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask fn harness() -> Harness<'static, TextureCraftApp> { + harness_with("curvature") +} + +/// A plane whose bake makes only the position map, with a `generator` selected in a fill layer's mask +fn harness_with(generator: &str) -> Harness<'static, TextureCraftApp> { let mesh = primitives::builtin("plane").unwrap(); let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); 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(); - execute(&mut session, "effect.add.generator", &json!({ "generator": "curvature" })).unwrap(); + execute(&mut session, "effect.add.generator", &json!({ "generator": generator })).unwrap(); session.view = ViewMode::Mask(LayerId(layer)); session.update(); @@ -67,3 +72,9 @@ fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() { assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature))); assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); } + +#[test] +fn rust_runoff_notes_the_occlusion_it_reads_though_no_input_replaces_it() { + let harness = harness_with("Dripping Rust"); + harness.get_by_label("Ambient Occlusion map not baked"); +} From 57ffd56a039794a4a8bc220f0e47668a0e47a4b6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:42:53 +0000 Subject: [PATCH 77/80] Start an auto-rebake canceled in one project again in the next project opened, and wait while a press is held in a floating panel's window --- crates/ui-egui/src/auto_rebake.rs | 60 +++++++++++++++++++++++++- crates/ui-egui/src/docking.rs | 25 +++++++---- crates/ui-egui/tests/it/auto_rebake.rs | 23 ++++++++++ 3 files changed, 98 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 07bbcaab..473e80ce 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -13,6 +13,8 @@ pub type Due = (usize, BakedMap, BakeSource, Option); /// What the app has seen of the out-of-date auto-rebake maps #[derive(Default)] pub struct AutoRebake { + /// The project these records are of: another project starts with none + project: u64, /// The due maps and the frame time they were first seen as they are pending: Option<(Vec, f64)>, /// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes @@ -21,6 +23,10 @@ pub struct AutoRebake { /// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.auto_rebake.project != app.session.project_id { + app.auto_rebake = AutoRebake { project: app.session.project_id, ..AutoRebake::default() }; + } + if app.ui.mode != state::Mode::Baking { app.auto_rebake.pending = None; return; @@ -48,10 +54,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); // A held press (a slider dragged and paused) is still editing: the wait starts once it is let go - if ctx.input(|input| input.pointer.any_down()) { + if pointer_held(ctx, app.docks.floating_windows()) { app.auto_rebake.pending = Some((waiting, now)); return; } + match &app.auto_rebake.pending { Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} Some((seen, _)) if *seen == waiting => return, @@ -68,6 +75,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { } } +/// Whether a mouse button is down in the main window or in one of the floating panels' own `windows` +fn pointer_held(ctx: &egui::Context, windows: &[egui::ViewportId]) -> bool { + ctx.input(|input| input.pointer.any_down()) || windows.iter().any(|window| ctx.input_for(*window, |input| input.pointer.any_down())) +} + /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { let (set, map, ..) = rebake; @@ -83,3 +95,49 @@ fn start(app: &mut TextureCraftApp, rebake: Due) { app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) }); } + +#[cfg(test)] +mod tests { + use super::*; + + /// Whether a press is held, seen from the main window after a button went down in a floating panel's window (`window_listed`) + fn held_after_a_press_in_a_floating_window(window_listed: bool) -> bool { + use std::{cell::RefCell, rc::Rc}; + + let window = egui::ViewportId::from_hash_of("floating panel"); + let context = egui::Context::default(); + context.set_embed_viewports(false); + + // Runs the window's pass inside its parent's, as eframe does + let arriving = Rc::new(RefCell::new(Vec::new())); + let queued = Rc::clone(&arriving); + egui::Context::set_immediate_viewport_renderer(move |context, viewport| { + let mut input = egui::RawInput { viewport_id: viewport.ids.this, events: queued.take(), ..Default::default() }; + input.viewports.insert(viewport.ids.this, egui::ViewportInfo { parent: Some(viewport.ids.parent), ..Default::default() }); + let mut output = context.run_ui(input, viewport.viewport_ui_cb); + output.textures_delta.clear(); + }); + + let at = egui::pos2(20.0, 20.0); + let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + *arriving.borrow_mut() = vec![egui::Event::PointerMoved(at), press]; + let windows: &[egui::ViewportId] = if window_listed { &[window] } else { &[] }; + let mut held = false; + + // The first pass hands the press to the window after the hold was read; the second reads it + for _ in 0..2 { + let mut output = context.run_ui(egui::RawInput::default(), |ui| { + held = pointer_held(ui.ctx(), windows); + ui.ctx().show_viewport_immediate(window, egui::ViewportBuilder::default(), |_, _| {}); + }); + output.textures_delta.clear(); + } + held + } + + #[test] + fn a_press_held_in_a_floating_panels_window_counts_as_held() { + assert!(held_after_a_press_in_a_floating_window(true), "the slider dragged in a floating panel is still editing"); + assert!(!held_after_a_press_in_a_floating_window(false), "the main window's own pointer is up"); + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index f1acd9e7..5f75aaae 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -391,23 +391,29 @@ impl Dock { } } -/// What the dock area keeps between passes: the workspace it shows and the panels' specs. +/// What the dock area keeps between passes: the workspace it shows and the panels' specs #[derive(Default)] pub(crate) struct LiveDock { shown: Option>, specs: Tracked, - /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window. + /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window continue_move: Option<(Panel, egui::Vec2)>, + /// The OS windows of the floating panels, as the last pass's dock drew them + floating_windows: Vec, } impl LiveDock { - /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`. + /// The OS windows the last pass's dock drew floating panels in + pub(crate) fn floating_windows(&self) -> &[ViewportId] { + &self.floating_windows + } + + /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab` pub(crate) fn hand_over(&mut self, panel: Panel, grab: egui::Vec2) { self.continue_move = Some((panel, grab)); } - /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, - /// so an idle pass keeps the workspace's revision and the dock reads no spec. + /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, so an idle pass reads no spec fn shown(&mut self, workspace: &Workspace) -> Arc { if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) { return Arc::clone(shown); @@ -470,7 +476,7 @@ pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> b modal } -/// Draw the dock (viewport and panels) into `ui`. +/// Draw the dock (viewport and panels) into `ui` pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { // Rendering keeps disabled panels visible because it shares the painting dock let dock_mode = if app.ui.mode == crate::state::Mode::Rendering { crate::state::Mode::Painting } else { app.ui.mode }; @@ -484,12 +490,11 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let context = ui.ctx().clone(); refresh_specs(app); let shown = app.docks.shown(&app.ui.dock.workspace); - // The specs leave the app while its panels borrow it, and come back with their revision. + // The specs leave the app while its panels borrow it, and come back with their revision let specs = std::mem::take(&mut app.docks.specs); let hand_over = app.docks.continue_move.take(); let raise = app.ui.dock.raise.take(); - // Panels arrange in a split tree around the viewport; floating title bars only move windows. - // Each closable tab has its close button, as each group header had one for its shown panel. + // Panels split around the viewport, floating title bars only move windows, and each closable tab has its close button let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false).tab_close_buttons(true); let (output, focused_windows) = { let tokens = Tokens::get(&context); @@ -505,6 +510,8 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { (output, panels.focused_windows) }; app.docks.specs = specs; + app.docks.floating_windows.clear(); + app.docks.floating_windows.extend(output.windows.iter().map(|(_, viewport)| *viewport)); // The popup needs the viewport the dock recorded this frame crate::rail_popup::show(app, &context); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 398e93b8..15534f76 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -9,6 +9,9 @@ use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::Mode; +/// Frames far past the half-second settle wait, at the harness's quarter-second step +const PAST_THE_SETTLE_FRAMES: usize = 60; + /// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { let mesh = primitives::builtin("plane").unwrap(); @@ -174,3 +177,23 @@ fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_st harness.drop_at(corner); super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some()); } + +#[test] +fn a_rebake_canceled_in_one_project_still_runs_in_the_next_project_opened() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + harness.state_mut().cancel_bake(); + harness.run_steps(PAST_THE_SETTLE_FRAMES); + assert!(harness.state().bake.is_none(), "a canceled rebake is not tried again in its project"); + + // The same project opened again: its out-of-date map reads what the canceled one read + let mesh = primitives::builtin("plane").unwrap(); + let mut next = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut next, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut next, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut next, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + harness.state_mut().session.switch_to(next); + + super::step_until(&mut harness, "the rebake in the opened project", |app| app.bake.is_some()); +} From ba1d3aebc33c42621d70943f838d68165cc1cae7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:03:15 +0000 Subject: [PATCH 78/80] Keep the Baking Log tabs clear of the issues filter on a narrow dock, scrolling them when they don't fit, and cut Matching by Name's part names short to their column, in full on hover --- crates/ui-egui/src/baking_log.rs | 122 ++++++++++++------ .../ui-egui/src/baking_log/matching_list.rs | 86 ++++++++++-- crates/ui-egui/tests/it/baking_log.rs | 53 ++++++++ 3 files changed, 204 insertions(+), 57 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index db0db2a7..affb1803 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -3,7 +3,7 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeLogMatching, BakeMapState}; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; @@ -71,15 +71,15 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, &app.session.bake_log) { + + // The tabs keep clear of the issues filter at its widest, so picking a tab never moves the edge they scroll under + let filter_room = BakingLogTab::ALL.into_iter().map(|tab| filter_width(ui, issue_count(&app.session.bake_log, tab))).fold(0.0, f32::max); + let tabs_right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT - filter_room - TAB_GAP; + if let Some(tab) = tabs(ui, strip.with_max_x(tabs_right.max(strip.left())), app.ui.baking_log_tab, &app.session.bake_log) { app.ui.baking_log_tab = tab; } let tab = app.ui.baking_log_tab; - let issue_count = match tab { - BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::MatchingByName => app.session.bake_log.matching.as_ref().map_or(0, |matching| matching.issue_count()), - }; + let issue_count = issue_count(&app.session.bake_log, tab); if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; } @@ -136,55 +136,91 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa app.ui.dock.focus(Panel::MeshMapSettings); } -/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +/// How many rows of `tab` have an issue, for the issues filter's count +fn issue_count(log: &BakeLog, tab: BakingLogTab) -> usize { + match tab { + BakingLogTab::BakingProcess => log.maps.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::HighPolyParameters => log.highs.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::MatchingByName => log.matching.as_ref().map_or(0, BakeLogMatching::issue_count), + } +} + +/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; they scroll sideways when wider than it fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option { let tokens = Tokens::get(ui.ctx()); - let mut picked = None; - let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; - for tab in BakingLogTab::ALL { - let name = tr(tab.name()); - let on = tab == shown; - let width = ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING; - 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(("baking_log_tab", tab)), Sense::click()); - response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); - if response.clicked() { - picked = Some(tab); - } + let names = BakingLogTab::ALL.map(|tab| tr(tab.name())); + let widths = names.map(|name| ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING); + let first_left = SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; + let content_width = first_left + widths.iter().sum::() + TAB_GAP * (widths.len() - 1) as f32; - let painter = ui.painter(); - if on { - shown_tab_box(painter, &tokens, rect); - } - let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; - let in_progress = match tab { - BakingLogTab::BakingProcess => log.is_running(), - BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), - BakingLogTab::MatchingByName => false, - }; - let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; - let center_y = strip.center().y + TAB_TOP / 2.0; - painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); - let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; - painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); - if response.has_focus() { - crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); - } + let mut strip_ui = ui.new_child(egui::UiBuilder::new().max_rect(strip).id_salt("baking_log_tabs")); + egui::ScrollArea::horizontal() + .id_salt("baking_log_tabs") + .auto_shrink([false, false]) + .show(&mut strip_ui, |ui| { + let (content, _) = ui.allocate_exact_size(vec2(content_width, strip.height()), Sense::hover()); + let mut picked = None; + let mut left = content.left() + first_left; + for ((tab, name), width) in BakingLogTab::ALL.into_iter().zip(names).zip(widths) { + if tab_button(ui, content, left, width, (tab, name), tab == shown, log) { + picked = Some(tab); + } + left += width + TAB_GAP; + } + picked + }) + .inner +} - left += width + TAB_GAP; +/// One tab `width` wide from `left` on the `strip`, scrolled into view when the focus reaches it; dots for its icon while its work runs +fn tab_button(ui: &mut Ui, strip: Rect, left: f32, width: f32, (tab, name): (BakingLogTab, &str), on: bool, log: &BakeLog) -> bool { + let tokens = Tokens::get(ui.ctx()); + 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(("baking_log_tab", tab)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); + if response.gained_focus() { + response.scroll_to_me(None); } - picked + + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, rect); + } + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let in_progress = match tab { + BakingLogTab::BakingProcess => log.is_running(), + BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), + BakingLogTab::MatchingByName => false, + }; + let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); + } + response.clicked() +} + +/// The issues filter's width when it counts `issue_count` rows +fn filter_width(ui: &Ui, issue_count: usize) -> f32 { + let count_width = if issue_count == 0 { + 0.0 + } else { + let tokens = Tokens::get(ui.ctx()); + ui.painter().layout_no_wrap(issue_count.to_string(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP + }; + FILTER_BUTTON_WIDTH + count_width } /// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool { let tokens = Tokens::get(ui.ctx()); let count = (issue_count > 0).then(|| issue_count.to_string()); - let count_width = - count.as_ref().map_or(0.0, |count| ui.painter().layout_no_wrap(count.clone(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP); let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT; let center_y = strip.center().y + FILTER_DROP; - let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); + let rect = Rect::from_min_max(pos2(right - filter_width(ui, issue_count), center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); let name = match &count { Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]), diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs index b64565cb..8f4e278b 100644 --- a/crates/ui-egui/src/baking_log/matching_list.rs +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -1,6 +1,6 @@ //! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part -use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use texturecraft_engine::bake::{BakeLogMatching, NamePair}; @@ -8,17 +8,21 @@ use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT}; use crate::i18n::{tr, trf}; use crate::property_sheet::SIDE_PADDING_POINTS; use crate::theme::{Tokens, semibold}; +use crate::widgets::elided; /// Size of the column captions const CAPTION_SIZE: f32 = 11.0; +/// Air between the end of a low poly name and the high poly column +const COLUMN_GAP: f32 = 8.0; + /// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) { let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)]; - for (left, caption) in columns(rect).into_iter().zip(captions) { - ui.painter().text(pos2(left, rect.center().y), Align2::LEFT_CENTER, caption, FontId::proportional(CAPTION_SIZE), tokens.text_dim); + for (column, caption) in columns(rect).into_iter().zip(captions) { + column_text(ui, column, caption, CAPTION_SIZE, tokens.text_dim); } rule(ui, rect); @@ -32,9 +36,19 @@ fn caption(template: &str, suffix: &str) -> String { template.split("{suffix}").map(str::to_uppercase).collect::>().join(suffix) } -/// The left edges of the low and high poly columns of `row` -fn columns(row: Rect) -> [f32; 2] { - [row.left() + SIDE_PADDING_POINTS, row.center().x] +/// The low and high poly columns of `row`, each ending a gap short of the next column or the side padding +fn columns(row: Rect) -> [Rect; 2] { + let low = row.with_min_x(row.left() + SIDE_PADDING_POINTS).with_max_x(row.center().x - COLUMN_GAP); + let high = row.with_min_x(row.center().x).with_max_x(row.right() - SIDE_PADDING_POINTS); + [low, high] +} + +/// Paint `text` in `color` at the left end of `column`, centred on its height and cut short to its width; whether it was cut +fn column_text(ui: &Ui, column: Rect, text: String, size: f32, color: Color32) -> bool { + let galley = elided(ui.painter(), text, size, color, column.width()); + let cut_short = galley.elided; + ui.painter().galley(pos2(column.left(), column.center().y - galley.size().y / 2.0), galley, color); + cut_short } /// The hairline under `row`, inside the side padding @@ -62,19 +76,63 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { if response.hovered() { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); } - let center_y = rect.center().y; - for (left, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { + let mut cut_short = false; + for (column, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { match part { - Some(part) => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, part, FontId::proportional(NAME_SIZE), tokens.text), - None => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning), - }; + Some(part) => cut_short |= column_text(ui, column, part.clone(), NAME_SIZE, tokens.text), + None => { + painter.text(pos2(column.left(), column.center().y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning); + } + } } rule(ui, rect); - if let Some(reason) = reason { + // A name cut short shows in full on hover; the row's label carries it in full already + if reason.is_some() || cut_short { response.on_hover_ui(|ui| { - ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); - ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + if cut_short { + ui.label(egui::RichText::new(&name).size(NAME_SIZE).color(tokens.text)); + } + if let Some(reason) = reason { + ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + } }); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Names longer than their column, in a list as narrow as a small docked log + #[test] + fn long_names_stay_in_their_own_column() { + let long = |side: &str| format!("Left_shoulder_strap_buckle_with_its_rivets_and_stitching_{side}"); + let matching = BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![NamePair { low: Some(long("low")), high: Some(long("high")) }], + }; + let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(320.0, 200.0)); + let context = egui::Context::default(); + let mut output = context.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| matching_list(ui, &matching, false)); + output.textures_delta.clear(); + + let texts: Vec = output + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(text.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert_eq!(texts.len(), 4, "two captions and two names"); + for (index, text) in texts.iter().enumerate() { + assert!(screen.contains_rect(*text), "text {index} {text:?} stays inside the list"); + for other in &texts[index + 1..] { + assert!(!text.intersects(*other), "text {index} {text:?} runs into {other:?}"); + } + } + } +} diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 5e7e9681..5c616fa5 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -1,5 +1,6 @@ //! The Baking Log panel: the latest bake, map by map +use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; @@ -251,3 +252,55 @@ fn the_matching_tab_says_when_no_set_matched_by_name() { harness.get_by_label("Set Match to By Mesh Name to pair parts by name."); } + +#[test] +fn on_a_narrow_dock_the_tabs_scroll_clear_of_the_issues_filter() { + // A window this narrow leaves the docked log less room than its three tabs and the filter take together + const NARROW_WINDOW_WIDTH: f32 = 520.0; + + let mut harness = Harness::builder() + .with_size(egui::vec2(NARROW_WINDOW_WIDTH, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, texturecraft_engine::sample_session(256, 64).unwrap())); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let filter = harness.get_by_label("Show only rows with an issue").rect(); + let strip_start = harness.get_by_role_and_label(Role::Tab, "Baking Process").rect().left(); + let last_tab = harness.get_by_role_and_label(Role::Tab, "Matching by Name").rect(); + assert!(last_tab.right() > filter.left(), "unscrolled, the tabs {last_tab:?} run past the filter {filter:?}, so they must scroll"); + + // Frames for the strip's scroll to the focused tab to finish + const SCROLL_FRAMES: usize = 30; + + for tab in ["Baking Process", "High Poly Parameters", "Matching by Name"] { + harness.get_by_role_and_label(Role::Tab, tab).focus(); + harness.run_steps(SCROLL_FRAMES); + + let rect = harness.get_by_role_and_label(Role::Tab, tab).rect(); + assert!(rect.right() <= filter.left(), "the focused {tab} tab {rect:?} ends left of the filter {filter:?}"); + assert!(rect.left() >= strip_start, "the focused {tab} tab {rect:?} starts inside the log, where the first tab starts unscrolled"); + } +} + +#[test] +fn a_matching_name_cut_short_shows_in_full_on_hover() { + const LONG_NAME: &str = "Left_shoulder_strap_buckle_with_its_rivets_and_its_stitching_low"; + + // Frames past the tooltip delay + const TOOLTIP_FRAMES: usize = 60; + + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = NamePair { low: Some(LONG_NAME.into()), high: Some("Strap_high".into()) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { low_suffix: "_low".into(), high_suffix: "_high".into(), pairs: vec![pair] }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + let label = format!("{LONG_NAME}, Strap_high"); + let row = harness.get_by_label(&label).rect(); + assert_eq!(harness.query_all_by_label(&label).count(), 1, "no tooltip before hovering"); + + harness.hover_at(row.center()); + harness.run_steps(TOOLTIP_FRAMES); + + assert_eq!(harness.query_all_by_label(&label).count(), 2, "the tooltip carries both names in full"); +} From c8fbe38ed70f223f745ec5033f6e9954fea8fd01 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 09:19:38 -0500 Subject: [PATCH 79/80] ci: notify artcraft-services on release state changes (#881) * ci: notify artcraft-services on release state changes * ci: pass only the dispatch token to the notify-services workflow secrets: inherit hands the called workflow every repository secret, including the signing credentials. The reusable workflow only reads ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one. --------- Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .github/workflows/notify-services.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/workflows/notify-services.yml diff --git a/.github/workflows/notify-services.yml b/.github/workflows/notify-services.yml new file mode 100644 index 00000000..3dc8eaf4 --- /dev/null +++ b/.github/workflows/notify-services.yml @@ -0,0 +1,20 @@ +name: Notify Services on Release Change + +on: + release: + types: + - published + - unpublished + - created + - edited + - deleted + - prereleased + - released + +permissions: {} + +jobs: + notify: + uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main + secrets: + ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }} From edb8456d62134be8a16bf50a14cd78c900531166 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:55:20 +0100 Subject: [PATCH 80/80] ci(deps): bump the actions group across 1 directory with 6 updates (#831) * ci(deps): bump the actions group across 1 directory with 6 updates Bumps the actions group with 6 updates in the / directory: | Package | From | To | | --- | --- | --- | | [step-security/harden-runner](https://github.com/step-security/harden-runner) | `2.22.4` | `2.23.0` | | [storytold/craft-common-actions/actions/checkout-craft-fonts](https://github.com/storytold/craft-common-actions) | `605d58766e8f536564da8fc81d3676ac86816dea` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/actions/checkout-craft-i18n](https://github.com/storytold/craft-common-actions) | `605d58766e8f536564da8fc81d3676ac86816dea` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/actions/rust-channel](https://github.com/storytold/craft-common-actions) | `605d58766e8f536564da8fc81d3676ac86816dea` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/.github/workflows/nightly-release.yml](https://github.com/storytold/craft-common-actions) | `be00e5ccd18b68e950c8a08532f2230e7c3d0cba` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | | [storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml](https://github.com/storytold/craft-common-actions) | `be00e5ccd18b68e950c8a08532f2230e7c3d0cba` | `f94a43818dabb2e85f2f4d5cd768bb8e5662600a` | Updates `step-security/harden-runner` from 2.22.4 to 2.23.0 - [Release notes](https://github.com/step-security/harden-runner/releases) - [Commits](https://github.com/step-security/harden-runner/compare/1d88384fd173af6ecb012dfd0264a306b711241a...aebdcf6156ab6691adf63218240e476564a1ed4c) Updates `storytold/craft-common-actions/actions/checkout-craft-fonts` from 605d58766e8f536564da8fc81d3676ac86816dea to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/actions/checkout-craft-i18n` from 605d58766e8f536564da8fc81d3676ac86816dea to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/actions/rust-channel` from 605d58766e8f536564da8fc81d3676ac86816dea to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/605d58766e8f536564da8fc81d3676ac86816dea...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/.github/workflows/nightly-release.yml` from be00e5ccd18b68e950c8a08532f2230e7c3d0cba to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/be00e5ccd18b68e950c8a08532f2230e7c3d0cba...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) Updates `storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml` from be00e5ccd18b68e950c8a08532f2230e7c3d0cba to f94a43818dabb2e85f2f4d5cd768bb8e5662600a - [Commits](https://github.com/storytold/craft-common-actions/compare/be00e5ccd18b68e950c8a08532f2230e7c3d0cba...f94a43818dabb2e85f2f4d5cd768bb8e5662600a) --- updated-dependencies: - dependency-name: step-security/harden-runner dependency-version: 2.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: actions - dependency-name: storytold/craft-common-actions/.github/workflows/nightly-release.yml dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/actions/checkout-craft-fonts dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/actions/checkout-craft-i18n dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions - dependency-name: storytold/craft-common-actions/actions/rust-channel dependency-version: 1754016e67ca9b74dfa4cf4678b2ac3548e9840f dependency-type: direct:production dependency-group: actions ... Signed-off-by: dependabot[bot] * ci: keep nightly tooling-revision and signing policy in lockstep Dependabot bumped the nightly-unsigned and nightly-release uses pins to f94a438 but left tooling-revision and the installed signing policy on be00e5c. The packaging checks require those pins to match. --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- .github/nightly-signing-policy.json | 6 +++--- .github/workflows/nightly-macos.yml | 8 ++++---- .github/workflows/nightly-sign.yml | 4 ++-- .github/workflows/nightly.yml | 4 ++-- docs/nightly-release-preparation.md | 6 +++--- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 35cb9eeb..ab63e5a3 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1419654881, "producer_workflow_id": 429738073, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index 75134544..1c49c360 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -36,7 +36,7 @@ jobs: RUST_BACKTRACE: 1 steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 with: egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -44,12 +44,12 @@ jobs: 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 + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: ref: aced4137c022f1f587624d48e81ec77e1914a9cc - - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/actions/rust-channel@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: targets: aarch64-apple-darwin - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 998acbae..65767940 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,9 +34,9 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a app-name: texturecraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 1600b2e0..a0933e12 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a app-name: texturecraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 6ed80ba0..616c743c 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -15,8 +15,8 @@ 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 `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions -main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the +Shared tooling is pinned to `f94a43818dabb2e85f2f4d5cd768bb8e5662600a`, the craft-common-actions +main commit that merged [#382](https://github.com/storytold/craft-common-actions/pull/382) (first-signer-attempt creation time is reconciled on re-read) after [#371](https://github.com/storytold/craft-common-actions/pull/371) (the candidate is admitted on the built commit's own Sonar analysis, not main's latest) after [#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly registry rows for the 14 apps) and @@ -80,7 +80,7 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` |---|---|---| | `repository_id` | `1419654881` | `gh api repos/storytold/texturecraft --jq .id` | | `producer_workflow_id` | `429738073` | `gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id` | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions #371 after #370, #369 and #364) | The callers' pin | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `f94a4381…` (craft-common-actions #382 after #379, #376, #371, #370, #369 and #364) | 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`) |