From b9e1e34ab05d3931ba229609960a56bab48ef138 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:40:53 -0600 Subject: [PATCH 01/28] Snapshots share the tile table of images they don't change --- crates/engine/tests/perf.rs | 29 +++++++++++++++++++ crates/texel/src/tile.rs | 58 ++++++++++++++++++++++++++++++++----- docs/architecture.md | 7 +++-- 3 files changed, 84 insertions(+), 10 deletions(-) diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs index eeee7662..600d9811 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/perf.rs @@ -319,6 +319,35 @@ fn bench_8k_stroke_end() { } } +/// What undo history costs: cloning a many-layer document, and a run of small strokes that each +/// make one undo step. +#[test] +#[ignore] +fn bench_history() { + let res = 4096; + let t = Instant::now(); + let mut s = stack(res); + for _ in 0..20 { + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[200, 300], [260, 320]]})).unwrap(); + } + println!("[{res}²] history setup {:.2?}", t.elapsed()); + let t = Instant::now(); + for _ in 0..100 { + drop(std::hint::black_box(s.doc.clone())); + } + println!("[{res}²] document clone {:.2?} average over 100", t.elapsed() / 100); + let t = Instant::now(); + for i in 0..100 { + let y = 400 + i * 5; + execute(&mut s, "tool.stroke", &json!({"points": [[200, y], [260, y + 20]]})).unwrap(); + } + let total = t.elapsed(); + println!("[{res}²] 100 strokes {total:.2?} ({:.2?} per stroke)", total / 100); + let m = s.memory(); + println!("[{res}²] memory: layer pixels {:.1} MB, composites {:.1} MB, hot-layer cache {:.1} MB", mb(m.pixels), mb(m.composites), mb(m.cache)); +} + #[test] #[ignore] fn bench_8k_resize() { diff --git a/crates/texel/src/tile.rs b/crates/texel/src/tile.rs index 0b94e6cc..05f0140a 100644 --- a/crates/texel/src/tile.rs +++ b/crates/texel/src/tile.rs @@ -10,8 +10,9 @@ pub const TILE_AREA: usize = (TILE * TILE) as usize; /// A tile's texel data: `TILE_AREA × comps` interleaved components. pub type TileData = Arc>; -/// An image split into 64×64 tiles; unallocated tiles read as zero. Cloning shares every tile, -/// so snapshots for undo cost one `Arc` clone per allocated tile. +/// An image split into 64×64 tiles; unallocated tiles read as zero. Cloning shares the tile table +/// and every tile, so a snapshot costs one reference-count bump; the first write after a clone +/// copies the table (one pointer per tile slot) once. #[derive(Clone, Debug, PartialEq)] pub struct TileImage { width: u32, @@ -19,7 +20,7 @@ pub struct TileImage { comps: usize, tiles_x: u32, tiles_y: u32, - tiles: Vec>, + tiles: Arc>>, } impl TileImage { @@ -28,7 +29,7 @@ impl TileImage { let (width, height) = (width.max(1), height.max(1)); let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); - TileImage { width, height, comps: comps.clamp(1, 4), tiles_x, tiles_y, tiles: vec![None; (tiles_x * tiles_y) as usize] } + TileImage { width, height, comps: comps.clamp(1, 4), tiles_x, tiles_y, tiles: Arc::new(vec![None; (tiles_x * tiles_y) as usize]) } } pub fn width(&self) -> u32 { @@ -65,7 +66,7 @@ impl TileImage { let len = TILE_AREA * self.comps; let data = data.filter(|d| d.len() == len); if let Some(i) = self.tile_index(tx, ty) - && let Some(slot) = self.tiles.get_mut(i) + && let Some(slot) = Arc::make_mut(&mut self.tiles).get_mut(i) { *slot = data; } @@ -76,7 +77,7 @@ impl TileImage { pub fn tile_mut(&mut self, tx: u32, ty: u32, fill: &[u16]) -> Option<&mut [u16]> { let comps = self.comps; let i = self.tile_index(tx, ty)?; - let slot = self.tiles.get_mut(i)?; + let slot = Arc::make_mut(&mut self.tiles).get_mut(i)?; let tile = slot.get_or_insert_with(|| { let mut v = vec![0u16; TILE_AREA * comps]; if fill.iter().any(|f| *f != 0) { @@ -140,9 +141,19 @@ impl TileImage { self.allocated_count() * TILE_AREA * self.comps * 2 } + /// Whether `self` and `other` share their tile table: no tile of either changed since one + /// was cloned from the other. + pub fn same_tiles(&self, other: &TileImage) -> bool { + Arc::ptr_eq(&self.tiles, &other.tiles) + } + /// Drop tiles whose every texel is zero. pub fn prune_empty(&mut self) { - for t in &mut self.tiles { + let is_empty = |t: &Option| t.as_ref().is_some_and(|d| d.iter().all(|v| *v == 0)); + if !self.tiles.iter().any(is_empty) { + return; + } + for t in Arc::make_mut(&mut self.tiles) { if t.as_ref().is_some_and(|d| d.iter().all(|v| *v == 0)) { *t = None; } @@ -205,6 +216,39 @@ mod tests { assert_eq!(a.get(1, 0)[0], 6); } + #[test] + fn clone_shares_the_table_until_written() { + let mut a = TileImage::new(512, 512, 2); + a.set(0, 0, &[1, 2]); + let mut b = a.clone(); + assert!(a.same_tiles(&b)); + b.set(70, 0, &[3, 4]); + assert!(!a.same_tiles(&b)); + assert_eq!(a.get(70, 0)[..2], [0, 0]); + assert_eq!(b.get(70, 0)[..2], [3, 4]); + assert_eq!(a.get(0, 0)[..2], [1, 2]); + assert_eq!(b.get(0, 0)[..2], [1, 2]); + } + + #[test] + fn out_of_range_writes_do_not_unshare() { + let mut a = TileImage::new(512, 512, 2); + a.set(0, 0, &[1, 2]); + let mut b = a.clone(); + b.set_tile(999, 999, None); + assert!(b.tile_mut(999, 999, &[0, 0]).is_none()); + assert!(a.same_tiles(&b)); + } + + #[test] + fn noop_prune_does_not_unshare() { + let mut a = TileImage::new(512, 512, 2); + a.set(0, 0, &[1, 2]); + let mut b = a.clone(); + b.prune_empty(); + assert!(a.same_tiles(&b)); + } + #[test] fn tile_mut_fills_new_tiles() { let mut img = TileImage::new(64, 64, 2); diff --git a/docs/architecture.md b/docs/architecture.md index 5eda226c..d53763a3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -72,9 +72,10 @@ normal channel and baked normals by reoriented normal mapping, and packs channel ## Undo `Session::edit` snapshots the `Document` (project + pixels + baked maps + resources) before a -change and restores it if the change fails. Pixel data is copy-on-write (`Arc` tiles), so a -snapshot costs one reference-count bump per allocated tile, and an undo step only keeps the tiles -that actually changed. +change and restores it if the change fails. Pixel images are copy-on-write at two levels: an +image's tile table and each 64×64 tile are `Arc`-shared, so a snapshot costs one +reference-count bump per image, and an undo step keeps only the tables and tiles the change +wrote. ## Rendering From e840fa65ec7a9da478ef78b8feafa2f595db2874 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 23:25:06 +0100 Subject: [PATCH 02/28] Add Edit > Change mesh... (file.changeMesh) to move a project onto another mesh Reimport mesh only re-read the project's own copy of the mesh, so there was no way to put the layers on a different mesh. The new command takes a mesh file, keeps layers, texture sets and settings, and carries painted strokes over by default. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/file_cmds.rs | 37 ++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/windows.rs | 7 ++++++ docs/features.md | 3 ++- docs/parity.md | 3 ++- 14 files changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 78916328..d8165f51 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -37,6 +37,15 @@ pub fn specs() -> Vec { always, reimport ), + cmd!( + "file.changeMesh", + "Change mesh...", + ["Edit"], + None, + "{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index", + always, + change_mesh + ), cmd!( "file.exportTextures", "Export textures", @@ -413,6 +422,13 @@ fn reimport(s: &mut Session, p: &Value) -> Result { s.reimport_mesh(file, crate::commands::boolp(p, "preserveStrokes").unwrap_or(false)) } +#[cfg(not(target_arch = "wasm32"))] +fn change_mesh(s: &mut Session, p: &Value) -> Result { + let path = native::path_param(p, "path", "file.changeMesh")?; + let file = native::read_mesh("file.changeMesh", path)?; + s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true)) +} + #[cfg(not(target_arch = "wasm32"))] impl Session { /// Replace the mesh with `file` (or re-read the project's own copy) and keep the project: @@ -679,6 +695,27 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A project built on one mesh moves to another mesh file with its layers intact, even when + /// it carries its own copy of the mesh (a plain reimport would only re-read that copy). + #[test] + fn change_mesh_swaps_the_mesh_and_keeps_the_layers() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let quad = dir.join("quad.obj"); + std::fs::write(&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 4/4\n").unwrap(); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layers = s.doc.project.layers.len(); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap(); + assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use"); + assert_eq!(s.doc.project.mesh_file, "tri.obj"); + assert_eq!(s.doc.project.layers.len(), layers, "the layers stay"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { // A GLB quad whose mesh and node have no name: its one part is named after the file. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 939b0b3c..89fadc94 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -663,6 +663,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "إعادة"), ("Reimport mesh", "إعادة استيراد المجسم"), + ("Change mesh...", "تغيير المجسم..."), ("Relative to the bounding box diagonal.", "نسبة إلى قطر المربع المحيط."), ("Remove", "إزالة"), ("Remove channel", "إزالة القناة"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ae02fbd2..de7ee6f2 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -702,6 +702,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Wiederholen"), ("Reimport mesh", "Mesh neu importieren"), + ("Change mesh...", "Mesh ändern..."), ("Relative to the bounding box diagonal.", "Relativ zur Diagonale des Begrenzungsrahmens."), ("Remove", "Entfernen"), ("Remove channel", "Kanal entfernen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 00964af6..5a9941a3 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -690,6 +690,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Rehacer"), ("Reimport mesh", "Reimportar malla"), + ("Change mesh...", "Cambiar malla..."), ("Relative to the bounding box diagonal.", "Relativo a la diagonal del cuadro delimitador."), ("Remove", "Quitar"), ("Remove channel", "Quitar canal"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f9fa0d3b..e0df73be 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -705,6 +705,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Rétablir"), ("Reimport mesh", "Réimporter le maillage"), + ("Change mesh...", "Changer le maillage..."), ("Relative to the bounding box diagonal.", "Relatif à la diagonale de la boîte englobante."), ("Remove", "Supprimer"), ("Remove channel", "Supprimer le canal"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 765f5e8c..409aa31f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -699,6 +699,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Ripeti"), ("Reimport mesh", "Reimporta mesh"), + ("Change mesh...", "Cambia mesh..."), ("Relative to the bounding box diagonal.", "Relativa alla diagonale del bounding box."), ("Remove", "Rimuovi"), ("Remove channel", "Rimuovi canale"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 41f6a048..69c32d77 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -678,6 +678,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "やり直し"), ("Reimport mesh", "メッシュを再インポート"), + ("Change mesh...", "メッシュを変更..."), ("Relative to the bounding box diagonal.", "バウンディングボックスの対角線に対する相対値。"), ("Remove", "削除"), ("Remove channel", "チャンネルを削除"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 9f6aabbe..0edab0f6 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -669,6 +669,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "다시 실행"), ("Reimport mesh", "메시 다시 가져오기"), + ("Change mesh...", "메시 변경..."), ("Relative to the bounding box diagonal.", "바운딩 박스 대각선 기준입니다."), ("Remove", "제거"), ("Remove channel", "채널 제거"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 67b4697b..253b263c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -687,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Refazer"), ("Reimport mesh", "Reimportar malha"), + ("Change mesh...", "Alterar malha..."), ("Relative to the bounding box diagonal.", "Relativo à diagonal da caixa delimitadora."), ("Remove", "Remover"), ("Remove channel", "Remover canal"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 73e05b93..50fe1c66 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -618,6 +618,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "重做"), ("Reimport mesh", "重新导入网格"), + ("Change mesh...", "更换网格..."), ("Relative to the bounding box diagonal.", "相对于包围盒对角线。"), ("Remove", "移除"), ("Remove channel", "移除通道"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 09f19c07..8c1ce538 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -56,6 +56,7 @@ pub const CATALOG: &[Item] = &[ sep("Edit"), it("Edit", "Project Configuration...", "ui.projectConfig", None), it("Edit", "Reimport mesh", "file.reimportMesh", Some("Ctrl+Shift+R")), + it("Edit", "Change mesh...", "file.changeMesh", None), it("Edit", "Settings...", "ui.settings", None), it("Mode", "Bake Mesh Maps", "ui.mode.bake", Some("F8")), it("Mode", "Painting", "ui.mode.paint", Some("F9")), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8ecab281..08e4a756 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1138,6 +1138,13 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> app.run("file.reimportMesh", json!({"path": path, "preserveStrokes": true})); true } + "file.changeMesh" => { + // Layers and texture sets stay; the strokes follow the surface onto the new mesh. + if let Some(p) = rfd::FileDialog::new().add_filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS).pick_file() { + app.run("file.changeMesh", json!({"path": p.display().to_string()})); + } + true + } _ => false, } } diff --git a/docs/features.md b/docs/features.md index fcbaca5f..2e6a9881 100644 --- a/docs/features.md +++ b/docs/features.md @@ -80,7 +80,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. - Reimport a changed mesh and your painted strokes stay on the surface. + Reimport a changed mesh and your painted strokes stay on the surface. **Edit ▸ Change mesh...** + (`file.changeMesh`) moves the project onto a different mesh file and keeps its layers. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). diff --git a/docs/parity.md b/docs/parity.md index d6543d54..7724e50f 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**55 of 55 menu items live (100%).** +**56 of 56 menu items live (100%).** ## File @@ -31,6 +31,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Redo | `edit.redo` | Ctrl+Y | live | | Project Configuration... | `ui.projectConfig` | | live | | Reimport mesh | `file.reimportMesh` | Ctrl+Shift+R | live | +| Change mesh... | `file.changeMesh` | | live | | Settings... | `ui.settings` | | live | ## Mode From f3217da0a91e9577f181c50362d40f494ce30a37 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 23:33:37 +0100 Subject: [PATCH 03/28] Add wasm stub for file.changeMesh Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/file_cmds.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d8165f51..9a1a7fc1 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -605,6 +605,8 @@ use unsupported as save_copy; #[cfg(target_arch = "wasm32")] use unsupported as reimport; #[cfg(target_arch = "wasm32")] +use unsupported as change_mesh; +#[cfg(target_arch = "wasm32")] use unsupported as export_textures; #[cfg(target_arch = "wasm32")] use unsupported as export_mesh; From 00f770ee1b16ab0f59c702b8ce6b1f25d69c7676 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:29:04 +0100 Subject: [PATCH 04/28] Change mesh: keep bake meshes and Auto-rebake, mark modified, decode images, stop old bake Review points on Edit > Change mesh (and Reimport mesh, which shares the path): - the high polys, cage (when it fits) and skew map of the project were dropped; - Auto-rebake was switched off, so the old baked map stayed in use; - the project was not marked modified; - image resources were not decoded in the new session; - a bake running during the swap applied its result to the new mesh; - painted pixels of a set with no old surface in reach were blanked, now kept. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/file_cmds.rs | 14 ++++++++++ crates/engine/src/preserve.rs | 29 +++++++++++++++++++-- crates/engine/tests/auto_rebake.rs | 41 ++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 14 ++++++++-- 4 files changed, 94 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 9a1a7fc1..4cb190dd 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -436,6 +436,7 @@ impl Session { /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies /// like `file.reimportMesh`: `{preserved?}`. pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { + let from_file = file.is_some(); 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; @@ -457,6 +458,19 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.sync_images(); + // The high polys and the skew map stay; the cage must have the new mesh's triangles. + next.bake_meshes = self.bake_meshes.clone(); + if next.bake_meshes.cage.as_ref().is_some_and(|c| c.mesh.triangle_count() != next.mesh.triangle_count()) { + next.bake_meshes.cage = None; + next.log.push("the cage mesh was dropped: it does not have the new mesh's triangles".into()); + } + if next.bake_meshes.skew.is_some() && self.source.uvs != next.source.uvs { + next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into()); + } + // Auto-rebake stays on; the new mesh makes the baked map out of date, so it bakes again. + next.auto_rebake = self.auto_rebake.clone(); + next.modified = self.modified || from_file; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); self.switch_to(next); Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n }))) diff --git a/crates/engine/src/preserve.rs b/crates/engine/src/preserve.rs index 38544edc..01e14398 100644 --- a/crates/engine/src/preserve.rs +++ b/crates/engine/src/preserve.rs @@ -16,7 +16,8 @@ use crate::Session; const REACH: f32 = 0.05; /// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s -/// document) from `old`'s UV layout. Returns how many texels found the old surface. +/// document) from `old`'s UV layout. Returns how many texels found the old surface; +/// a texture set where none does keeps its pixels as they are. pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius()); let mut found = 0; @@ -52,7 +53,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { ((tx, ty), src) }) .collect(); - found += table.values().flatten().filter(|p| p[0].is_finite()).count(); + let matched = table.values().flatten().filter(|p| p[0].is_finite()).count(); + found += matched; + // No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is. + if matched == 0 { + continue; + } let map = |x: f32, y: f32| { let (xi, yi) = (x as u32, y as u32); table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1])) @@ -104,4 +110,23 @@ mod tests { } assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong"); } + + #[test] + fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..64 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // The same plane far away: nothing of the old surface is within reach. + let mut mesh = (*s.mesh).clone(); + for p in &mut mesh.positions { + p.x += 100.0; + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there"); + } } diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs index e6a37275..79883634 100644 --- a/crates/engine/tests/auto_rebake.rs +++ b/crates/engine/tests/auto_rebake.rs @@ -154,3 +154,44 @@ fn painting_or_clearing_the_skew_map_is_a_change() { assert_eq!(due(&mut s), [0], "and so is taking it away"); let _ = std::fs::remove_dir_all(dir); } + +/// Edit > Change mesh swaps the mesh under a baked project: the high poly and Auto-rebake stay (the +/// new mesh makes the map out of date), the project counts as changed, and image resources are decoded. +#[test] +fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { + let (mut s, dir) = baked_session("change"); + let mut obj = String::new(); + let plane = primitives::builtin("plane").unwrap(); + for p in &plane.positions { + obj += &format!("v {} {} {}\n", p.x, p.y, p.z); + } + for uv in &plane.uvs { + obj += &format!("vt {} {}\n", uv.x, 1.0 - uv.y); + } + for t in plane.indices.chunks_exact(3) { + obj += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1); + } + let new_mesh = dir.join("low.obj"); + std::fs::write(&new_mesh, obj).unwrap(); + // A 1x1 PNG as an image resource. + let png = &[ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, + 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00, + 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + s.import_resource_bytes("dot.png", png.to_vec()).unwrap(); + execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap(); + execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); + assert!(due(&mut s).is_empty()); + s.modified = false; + + execute(&mut s, "file.changeMesh", &json!({ "path": new_mesh.display().to_string() })).unwrap(); + assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert!(s.bake_meshes.skew.is_some(), "the skew map stays"); + assert!(s.modified, "the project differs from the saved one"); + assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); + assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], "height", "Auto-rebake stays on"); + assert_eq!(due(&mut s), [0], "and the map baked for the old mesh is out of date"); + + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1d0841dc..5f9b9676 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -53,6 +53,8 @@ pub struct BakeJob { pub total: usize, /// Bake only this map (an Auto-rebake); None bakes every ticked map. pub only: Option, + /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. + pub mesh_id: u64, } /// A MaterialCraft material re-cooking on a worker thread (one per layer at a time). @@ -209,7 +211,7 @@ impl TextureCraftApp { return; } let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total, only: None }); + self.bake = Some(BakeJob { queue: sets, current: None, total, only: None, mesh_id: self.session.mesh_id }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -263,6 +265,14 @@ impl TextureCraftApp { fn poll_bake(&mut self, ctx: &egui::Context) { let Some(job) = self.bake.as_mut() else { return }; + if job.mesh_id != self.session.mesh_id { + // The mesh was swapped under the job: stop it and drop its result. + if let Some((_, p, _)) = &job.current { + p.cancel.store(true, Ordering::Relaxed); + } + self.bake = None; + return; + } ctx.request_repaint_after(std::time::Duration::from_millis(50)); if let Some((ts, _, rx)) = &job.current { match rx.try_recv() { @@ -328,7 +338,7 @@ impl TextureCraftApp { let due = self.session.auto_rebake_due(); if !due.is_empty() { let total = due.len(); - self.bake = Some(BakeJob { queue: due, current: None, total, only: self.session.auto_rebake.map }); + self.bake = Some(BakeJob { queue: due, current: None, total, only: self.session.auto_rebake.map, mesh_id: self.session.mesh_id }); } } From da900411f767c68f9370834d84ff1896b6b46759 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:23:06 -0600 Subject: [PATCH 05/28] Keep bench_history's strokes on the mesh The last strokes started below the 800-pixel viewport and missed the sphere: only 23 of the 100 made an undo step, so the per-stroke time averaged in no-ops. The strokes now cross the framed sphere, and the bench asserts that each one makes a history step. --- crates/engine/tests/perf.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs index 600d9811..f7591a70 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/perf.rs @@ -337,12 +337,15 @@ fn bench_history() { drop(std::hint::black_box(s.doc.clone())); } println!("[{res}²] document clone {:.2?} average over 100", t.elapsed() / 100); + let steps = s.history_labels().len(); let t = Instant::now(); for i in 0..100 { - let y = 400 + i * 5; - execute(&mut s, "tool.stroke", &json!({"points": [[200, y], [260, y + 20]]})).unwrap(); + // Rows 300..490 of the 800-pixel viewport, across the framed sphere. + let y = 300 + (i % 20) * 10; + execute(&mut s, "tool.stroke", &json!({"points": [[300, y], [360, y + 20]]})).unwrap(); } let total = t.elapsed(); + assert_eq!(s.history_labels().len(), steps + 100, "every stroke paints the mesh and makes an undo step"); println!("[{res}²] 100 strokes {total:.2?} ({:.2?} per stroke)", total / 100); let m = s.memory(); println!("[{res}²] memory: layer pixels {:.1} MB, composites {:.1} MB, hot-layer cache {:.1} MB", mb(m.pixels), mb(m.composites), mb(m.cache)); From 10ed11db4a7f9d7b77b72ff5e7af1dd1273b0c89 Mon Sep 17 00:00:00 2001 From: Simon Hull <5488089+simonhull@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:58:59 -0600 Subject: [PATCH 06/28] Undo, redo and one-shot fills recomposite only the tiles whose pixels changed --- crates/compose/src/below.rs | 84 +++++++++++++++++++++++++++++++ crates/compose/src/eval.rs | 28 +++++++++++ crates/compose/src/lib.rs | 2 +- crates/engine/src/session.rs | 27 ++++++++-- crates/engine/tests/perf.rs | 53 ++++++++++++++++++++ crates/engine/tests/session.rs | 92 ++++++++++++++++++++++++++++++++++ 6 files changed, 281 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cf675d4f..d5345c92 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -124,6 +124,46 @@ impl StackKey { } } +impl StackKey { + /// The tiles whose pixels differ between `self` and `other` when nothing but painted pixels + /// changed (same set, roots, layers, baked maps and images; the same images by id, channel + /// and size). None when anything else differs: the caller recomposites everything. + pub fn changed_tiles(&self, other: &StackKey) -> Option> { + if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images { + return None; + } + if self.pixels.len() != other.pixels.len() { + return None; + } + let size = self.set.size(); + let mut changed = BTreeSet::new(); + for ((id_a, ch_a, a), (id_b, ch_b, b)) in self.pixels.iter().zip(&other.pixels) { + let (a, b) = (&a.0, &b.0); + let same_shape = id_a == id_b && ch_a == ch_b && a.width() == b.width() && a.height() == b.height() && a.comps() == b.comps(); + // Image tiles are composite tiles only when the grids coincide. + if !same_shape || (a.width(), a.height()) != size { + return None; + } + if a.same_tiles(b) { + continue; + } + for ty in 0..a.tiles_y() { + for tx in 0..a.tiles_x() { + let equal = match (a.tile_handle(tx, ty), b.tile_handle(tx, ty)) { + (None, None) => true, + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + _ => false, + }; + if !equal { + changed.insert((tx, ty)); + } + } + } + } + Some(changed) + } +} + /// An image compared by tile identity: holding the clone keeps its tiles alive, and a tile /// rewritten since is a different allocation (copy-on-write), so pointer equality means the /// same pixels without reading them. @@ -345,4 +385,48 @@ mod tests { c.set_hot(Some(LayerId(3))); assert!(c.is_empty() && c.bytes() == 0); } + + /// A project with one paint layer in a 128 px set, its pixels and a key builder. + fn painted() -> (Project, PixelStore, LayerId) { + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 128)); + let id = project.alloc_id(); + let layer = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]); + project.insert_layer(0, layer, None, false).unwrap(); + (project, PixelStore::default(), id) + } + + fn key(project: &Project, pixels: &PixelStore) -> StackKey { + let stack = project.texture_sets[0].stack.clone(); + StackKey::new(project, pixels, &BakedMaps::default(), &ImageStore::default(), 0, &stack).unwrap() + } + + #[test] + fn changed_tiles_lists_only_rewritten_tiles() { + let (project, mut pixels, id) = painted(); + pixels.layer_mut(id, Channel::BaseColor, (128, 128)).set(70, 5, &[9, 9, 9, 9]); + let before = key(&project, &pixels); + pixels.layer_mut(id, Channel::BaseColor, (128, 128)).set(70, 6, &[1, 1, 1, 1]); + let after = key(&project, &pixels); + assert_eq!(before.changed_tiles(&after), Some(BTreeSet::from([(1, 0)]))); + } + + #[test] + fn changed_tiles_is_none_when_a_layer_changes() { + let (mut project, pixels, id) = painted(); + let before = key(&project, &pixels); + project + .layer_mut(id) + .unwrap() + .channels + .insert(Channel::BaseColor, texturecraft_core::ChannelBlend { mode: texturecraft_core::BlendMode::Multiply, opacity: 0.5 }); + assert_eq!(before.changed_tiles(&key(&project, &pixels)), None); + } + + #[test] + fn changed_tiles_is_empty_for_identical_documents() { + let (project, mut pixels, id) = painted(); + pixels.layer_mut(id, Channel::BaseColor, (128, 128)).set(3, 3, &[5, 5, 5, 5]); + assert_eq!(key(&project, &pixels).changed_tiles(&key(&project, &pixels)), Some(BTreeSet::new())); + } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index de26d5bd..d98b1fe6 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -297,6 +297,18 @@ fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { .last() } +/// Whether any effect (mask or content) of a layer drawn in texture set `ts` reads texels +/// around each texel (blur, sharpen, warp, edge, bevel, glow, mosaic, slope blur). Conservative: +/// hidden layers and disabled masks count too. +pub fn stack_reads_neighbours(project: &Project, ts: usize) -> bool { + let Some(set) = project.texture_sets.get(ts) else { return false }; + project + .render_tree(&set.stack) + .iter() + .filter_map(|id| project.layers.get(id)) + .any(|l| neighbourhood(&l.content_effects, 2048).is_some() || l.mask.as_ref().is_some_and(|m| neighbourhood(&m.effects, 2048).is_some())) +} + /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn /// counterclockwise on screen. fn direction(angle: f32) -> [f32; 2] { @@ -2175,6 +2187,22 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + #[test] + fn stack_reads_neighbours_sees_blurs_in_masks_and_content() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0; 3], 1.0); + assert!(!stack_reads_neighbours(&f.project, 0)); + let mut mask = Mask::new(MaskBackground::White); + let eid = f.project.alloc_id(); + mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); + f.project.layer_mut(id).unwrap().mask = Some(mask); + assert!(stack_reads_neighbours(&f.project, 0)); + f.project.layer_mut(id).unwrap().mask = None; + assert!(!stack_reads_neighbours(&f.project, 0)); + content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0 })); + assert!(stack_reads_neighbours(&f.project, 0)); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..b73231c8 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -17,6 +17,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_image, pad_tiles, + mask_image, pad_tiles, stack_reads_neighbours, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 10a90287..cda91902 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -4,7 +4,9 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; +use texturecraft_compose::{ + BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours, +}; use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; @@ -539,10 +541,27 @@ impl Session { StackKey::new(&d.project, &d.pixels, d.baked.get(&ts).unwrap_or(&empty), &images, ts, stack) }; for ts in 0..self.caches.len() { - if (all || key(other, ts) != key(&self.doc, ts)) - && let Some(c) = self.caches.get_mut(ts) - { + let Some(c) = self.caches.get_mut(ts) else { continue }; + if all { c.invalidate_all(); + continue; + } + let (before, after) = (key(other, ts), key(&self.doc, ts)); + if before == after { + continue; + } + // Only painted pixels changed and nothing reads across tiles: the tiles whose pixels + // differ are the tiles to recomposite. Anything else recomposites the whole set. + let tiles = match (&before, &after) { + (Some(a), Some(b)) if !stack_reads_neighbours(&self.doc.project, ts) && !stack_reads_neighbours(&other.project, ts) => a.changed_tiles(b), + _ => None, + }; + match tiles { + Some(tiles) => { + let covered: BTreeSet<(u32, u32)> = c.covered_tiles.iter().copied().collect(); + c.dirty.extend(tiles.into_iter().filter(|t| covered.contains(t))); + } + None => c.invalidate_all(), } } } diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs index f7591a70..46ff0780 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/perf.rs @@ -351,6 +351,59 @@ fn bench_history() { println!("[{res}²] memory: layer pixels {:.1} MB, composites {:.1} MB, hot-layer cache {:.1} MB", mb(m.pixels), mb(m.composites), mb(m.cache)); } +/// Drain the pending tiles with `Session::update`, returning how long that took. +fn settle(s: &mut Session) -> Duration { + let t = Instant::now(); + while s.pending_tiles() > 0 { + s.update(); + } + t.elapsed() +} + +/// Undo and redo of one small stroke: the tiles left pending and the time to recomposite them. +/// `blur` keeps the stack's blurred mask (a neighbourhood filter forces a full recomposite). +fn bench_undo_at(res: u32, blur: bool) { + use texturecraft_engine::core::{EffectKind, Filter}; + let t = Instant::now(); + let mut s = stack(res); + if !blur { + let blurs: Vec<_> = s + .doc + .project + .layers + .values() + .filter_map(|l| l.mask.as_ref()) + .flat_map(|m| m.effects.iter()) + .filter(|e| matches!(e.kind, EffectKind::Filter(Filter::Blur { .. }))) + .map(|e| e.id.0) + .collect(); + for id in blurs { + execute(&mut s, "effect.remove", &json!({"effect": id})).unwrap(); + } + } + s.update(); + let label = if blur { "blur mask kept" } else { "no neighbourhood filters" }; + println!("[{res}², {label}] setup {:.2?} ({} covered tiles)", t.elapsed(), s.caches[0].covered_tiles.len()); + // The first stroke on a layer creates its images (and recomposites everything when undone). + execute(&mut s, "tool.stroke", &json!({"points": [[500, 500], [520, 510]]})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[300, 300], [330, 310]]})).unwrap(); + s.update(); + for (name, cmd) in [("undo", "edit.undo"), ("redo", "edit.redo")] { + execute(&mut s, cmd, &Value::Null).unwrap(); + let pending = s.pending_tiles(); + println!("[{res}², {label}] {name}: {pending} tiles pending, settled in {:.2?}", settle(&mut s)); + } +} + +#[test] +#[ignore] +fn bench_undo() { + // 4096 only: the 8192 setup takes many minutes under load. + let res = 4096; + bench_undo_at(res, true); + bench_undo_at(res, false); +} + #[test] #[ignore] fn bench_8k_resize() { diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..a752e79b 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -380,3 +380,95 @@ fn background_resizes_match_the_command_and_keep_later_edits() { b.update(); assert_eq!(b.caches[0].size, (512, 512)); } + +/// A 2048 sphere set with a fill layer and an empty paint layer, a small brush, and the +/// oracle: the composite after recompositing every covered tile from scratch. +fn painted_set() -> Session { + use texturecraft_engine::geom::glam::Vec2; + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 12, "hardness": 70, "opacity": 0.8})).unwrap(); + // A stroke creates the layer's images; later edits only rewrite tiles of images that exist + // (the first stroke of a channel adds an image, which recomposites the whole set). + execute(&mut s, "tool.stroke", &json!({"points": [[150, 160], [170, 170]]})).unwrap(); + s.update(); + s +} + +fn full(s: &mut Session) -> texturecraft_engine::compose::Composite { + s.caches[0].invalidate_all(); + s.update(); + s.caches[0].composite.clone() +} + +/// Undo and redo of `change` queue the right tiles: `Some(max)` fewer than `max` of them, matching +/// a full recomposite once updated; `None` every covered tile. +fn check_undo_redo(s: &mut Session, change: impl FnOnce(&mut Session), limit: Option) { + change(s); + s.update(); + for cmd in ["edit.undo", "edit.redo"] { + execute(s, cmd, &Value::Null).unwrap(); + let (dirty, covered) = (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len()); + match limit { + Some(max) => assert!(0 < dirty && dirty < max, "{cmd}: {dirty} of {covered} tiles dirty"), + None => assert_eq!(dirty, covered, "{cmd}"), + } + s.update(); + let settled = s.caches[0].composite.clone(); + assert_eq!(settled, full(s), "{cmd}: matches a full recomposite"); + } +} + +#[test] +fn undo_recomposites_only_changed_tiles() { + let mut s = painted_set(); + let stroke = |s: &mut Session| drop(execute(s, "tool.stroke", &json!({"points": [[150, 200], [190, 210]]})).unwrap()); + // The stroke covers a handful of the set's 1024 tiles. + check_undo_redo(&mut s, stroke, Some(64)); +} + +#[test] +fn undo_with_a_blur_above_recomposites_everything() { + use texturecraft_engine::geom::glam::Vec2; + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap(); + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + execute(&mut s, "effect.add.filter", &json!({"filter": "blur", "radius": 8})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 12, "hardness": 70, "opacity": 0.8})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[150, 160], [170, 170]]})).unwrap(); + s.update(); + let stroke = |s: &mut Session| drop(execute(s, "tool.stroke", &json!({"points": [[150, 200], [190, 210]]})).unwrap()); + check_undo_redo(&mut s, stroke, None); +} + +#[test] +fn polygon_fill_recomposites_only_changed_tiles() { + let mut s = painted_set(); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.1})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[150, 240], [170, 250]]})).unwrap(); + execute(&mut s, "tool.polygonFill", &Value::Null).unwrap(); + s.update(); + let tris = s.polygon_fill(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap(); + assert!(tris > 0); + let (dirty, covered) = (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len()); + assert!(0 < dirty && dirty < covered / 4, "{dirty} of {covered} tiles dirty after one triangle"); + s.update(); + let settled = s.caches[0].composite.clone(); + assert_eq!(settled, full(&mut s)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.caches[0].dirty.len() < covered / 4); + s.update(); + let settled = s.caches[0].composite.clone(); + assert_eq!(settled, full(&mut s)); +} + +#[test] +fn undo_of_a_layer_change_recomposites_everything() { + let mut s = painted_set(); + let change = |s: &mut Session| drop(execute(s, "layer.blend", &json!({"channel": "all", "opacity": 0.5})).unwrap()); + check_undo_redo(&mut s, change, None); +} From 0791e9fe35999598c27b71c3f350eed772f40b72 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:53:57 +0100 Subject: [PATCH 07/28] changeMesh: reset the low-poly colour cache and drop the cage when the mesh changes Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/file_cmds.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d6af0410..6ca53a28 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -465,11 +465,14 @@ impl Session { next.log.extend(warnings); next.path = self.path.clone(); next.sync_images(); - // The high polys and the skew map stay; the cage must have the new mesh's triangles. + // The high polys and the skew map stay. The cage is sampled by triangle index and + // barycentrics, so it stays only for an identical mesh; the low poly's base colours are + // read again from the new mesh. next.bake_meshes = self.bake_meshes.clone(); - if next.bake_meshes.cage.as_ref().is_some_and(|c| c.mesh.triangle_count() != next.mesh.triangle_count()) { + next.bake_meshes.low_base_color = Default::default(); + if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { next.bake_meshes.cage = None; - next.log.push("the cage mesh was dropped: it does not have the new mesh's triangles".into()); + next.log.push("the cage mesh was dropped: the low-poly mesh changed".into()); } if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into()); @@ -746,6 +749,28 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + #[test] + fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.obj"); + std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + // Same triangle count, other vertices. + let b = dir.join("b.obj"); + std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); + let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.bake_meshes.cage = Some(cage); + let _ = s.bake_meshes.low_base_color.set(Err("old".into())); + // The same mesh again keeps the cage but not the cached colours. + crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_some()); + assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { // A GLB quad whose mesh and node have no name: its one part is named after the file. From d180ee3112b8a2984533c4e161e8961e892b85ab Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 00:56:13 +0100 Subject: [PATCH 08/28] changeMesh: keep the painted pixels when the UV layout and topology are unchanged preserve_strokes sampled the nearest world-space point, so a mesh moved a little along its surface with the same indices and UVs shifted existing marks, and texels outside reach were cleared. An unchanged layout now skips the reprojection. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/preserve.rs | 36 ++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/preserve.rs b/crates/engine/src/preserve.rs index 01e14398..b0d0526b 100644 --- a/crates/engine/src/preserve.rs +++ b/crates/engine/src/preserve.rs @@ -17,8 +17,13 @@ const REACH: f32 = 0.05; /// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s /// document) from `old`'s UV layout. Returns how many texels found the old surface; -/// a texture set where none does keeps its pixels as they are. +/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the +/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already +/// sit where they belong, however far the mesh moved. pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { + if same_layout(&old.mesh, &next.mesh) { + return 0; + } let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius()); let mut found = 0; for ts in 0..next.set_count() { @@ -69,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { found } +/// Same index buffer, same UVs per vertex and the same material ranges. +fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool { + let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::>(); + a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b) +} + #[cfg(test)] mod tests { use super::*; @@ -129,4 +140,27 @@ mod tests { let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there"); } + + #[test] + fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..128 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // Slid along its own surface by a fraction of the plane: half of it still overlaps the old one. + let mut mesh = (*s.mesh).clone(); + let shift = mesh.radius() * 0.5; + for p in &mut mesh.positions { + p.x += shift; + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + for x in 0..128 { + assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved"); + assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint"); + } + } } From d5bdeedf8c4ca4a5698e9b97cea1e2861249c2d3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 01:40:48 +0100 Subject: [PATCH 09/28] Test the zero-match fallback with a different UV layout The no-surface-in-reach test now also mirrors the UVs, so it no longer exits through the unchanged-layout shortcut. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/preserve.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/preserve.rs b/crates/engine/src/preserve.rs index b0d0526b..d68f20bc 100644 --- a/crates/engine/src/preserve.rs +++ b/crates/engine/src/preserve.rs @@ -130,11 +130,15 @@ mod tests { for x in 0..64 { img.set(x, 40, &[65535, 0, 0, 65535]); } - // The same plane far away: nothing of the old surface is within reach. + // The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout + // shortcut is not taken): nothing of the old surface is within reach. let mut mesh = (*s.mesh).clone(); for p in &mut mesh.positions { p.x += 100.0; } + for uv in &mut mesh.uvs { + *uv = Vec2::new(1.0 - uv.x, uv.y); + } let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); assert_eq!(preserve_strokes(&s, &mut next), 0); let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); From b52fca296d935abe93208f2fb61c2855853fd1f5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 22:15:57 +0100 Subject: [PATCH 10/28] Use as_chunks in the change-mesh test (clippy) Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/tests/it/bake.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index f834121d..6d135f4f 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -639,7 +639,7 @@ fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { for uv in &plane.uvs { low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y); } - for t in plane.indices.chunks_exact(3) { + for t in plane.indices.as_chunks::<3>().0 { low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1); } let low = temp_file("change_low.obj", &low); From 0cf1edb328460aaed1f63dc16322a4879d5d3e35 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 22:16:28 +0100 Subject: [PATCH 11/28] Use the shared file dialog for Change mesh Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/windows.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f7e81751..df254412 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -923,9 +923,12 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } "file.changeMesh" => { // Layers and texture sets stay; the strokes follow the surface onto the new mesh. - if let Some(p) = rfd::FileDialog::new().add_filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS).pick_file() { - app.run("file.changeMesh", json!({"path": p.display().to_string()})); - } + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + app.ask_file(dialog, Bound::Project, |app, paths| { + if let Some(p) = paths.first() { + app.run("file.changeMesh", json!({"path": p.display().to_string()})); + } + }); true } _ => false, From 2e021b851be6c5c8e48571eaf38037293c19e980 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 22:16:45 +0100 Subject: [PATCH 12/28] Adapt the bake job tests to RunningBake and mesh_id Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/tests/bake_preview.rs | 2 ++ crates/ui-egui/tests/it/bake_job_mesh.rs | 16 +++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6860bdc4..1703abde 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -125,9 +125,11 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { result_sender.send(Ok(output)).unwrap(); let app = harness.state_mut(); app.start_bake(vec![0]); + let mesh_id = app.session.mesh_id; app.bake = Some(BakeJob { queue: Vec::new(), total: 1, + mesh_id, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 6744bb6b..d3877479 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -6,7 +6,7 @@ use std::sync::atomic::Ordering; use egui_kittest::Harness; use texturecraft_engine::bake::Progress; -use texturecraft_ui_egui::{BakeJob, TextureCraftApp}; +use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; /// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { @@ -14,11 +14,21 @@ fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, Textu let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.run_steps(4); let progress = Arc::new(Progress::new()); - let (tx, rx) = std::sync::mpsc::channel(); + let (tx, receiver) = std::sync::mpsc::channel(); + let (maps_tx, maps) = std::sync::mpsc::channel(); let id = mesh_id(h.state().session.mesh_id); // Leak the sender so the channel stays empty instead of closed. std::mem::forget(tx); - h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some((0, progress.clone(), rx)), total: 1, mesh_id: id }); + std::mem::forget(maps_tx); + let running = RunningBake { + set_index: 0, + progress: progress.clone(), + receiver, + maps, + maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + maps_total: 1, + }; + h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); (h, progress) } From 55885011c83f3c6501d1575f70d226df8ecbb39a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 22:16:56 +0100 Subject: [PATCH 13/28] Format Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/tests/it/bake_job_mesh.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index d3877479..0311c054 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -20,14 +20,8 @@ fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, Textu // Leak the sender so the channel stays empty instead of closed. std::mem::forget(tx); std::mem::forget(maps_tx); - let running = RunningBake { - set_index: 0, - progress: progress.clone(), - receiver, - maps, - maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), - maps_total: 1, - }; + let running = + RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); (h, progress) } From f32e4ea7f059bc62b8b09c8ed224bbd1b2898f0d Mon Sep 17 00:00:00 2001 From: Subtilicus Date: Thu, 12 Nov 2026 09:42:02 +0100 Subject: [PATCH 14/28] Keep baked normals above 8 bits in the viewport The viewport's Normal display texture was RGBA8, so baked normals (stored as f32) were quantised to 8 bits per axis before shading. On smooth, mirror-like materials this showed as banding. The texture is now RGBA16F holding the signed normal (flat is exactly +z), as Height already does; the raster and GPU path-tracing shaders read it directly. --- crates/compose/src/display.rs | 70 +++++++++++++++++----------- crates/render/src/renderer.rs | 5 +- crates/render/src/shaders/mesh.wgsl | 9 ++-- crates/render/src/shaders/trace.wgsl | 5 +- 4 files changed, 52 insertions(+), 37 deletions(-) diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 5ebb667b..d0501c8f 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -6,13 +6,16 @@ //! |-----------|----------|-------------------|----------------|-------------------|-------------------| //! | BaseColor | sRGB8 | base color | | | opacity | //! | Orm | RGBA8 | AO (× baked) | roughness | metallic | specular level | -//! | Normal | RGBA8 | normal x | normal y | normal z | sheen roughness | +//! | Normal | RGBA16F | normal x | normal y | normal z | sheen roughness | //! | Height | RGBA16F | height | Specular (F0) r| g | b | //! | Emissive | sRGB8 | emissive | | | scattering weight | //! | Lobes | RGBA8 | coat weight | coat roughness | anisotropy level | anisotropy angle | //! | Sheen | sRGB8 | sheen color | | | sheen weight | //! | Extra | RGBA8 | coat normal x | coat normal y | transmission | tile scale | //! +//! Normal holds the tangent-space normal signed (flat is `(0, 0, 1)`) in half floats: baked +//! normals are high-precision data, and 8 bits per axis bands smooth surfaces in the shading. +//! //! Extra packs the coat normal's x and y as `128 + 127 × n` (the default normal is exactly 0; //! z is rebuilt in the shader). Its alpha is the [`Composite::block_scales`] of the texel's UV //! tile as `32 × log2(1 / scale)` (0 for a tile filling its block): the shader turns height @@ -36,7 +39,7 @@ pub enum DisplayKind { /// RGBA8 linear: ambient occlusion (channel × baked), roughness (1 − glossiness when the set /// has a Glossiness channel), metallic, specular level. Orm, - /// RGBA8: painted tangent-space normal. + /// RGBA16F: the shown tangent-space normal, signed (flat is `(0, 0, 1)`), alpha = sheen roughness. Normal, /// RGBA16F: height in r, the linear Specular (F0) color in gba. Height, @@ -64,7 +67,7 @@ impl DisplayKind { /// Bytes per texel of the upload format. pub fn bytes_per_texel(self) -> usize { - if self == DisplayKind::Height { 8 } else { 4 } + if matches!(self, DisplayKind::Height | DisplayKind::Normal) { 8 } else { 4 } } /// Display textures affected by a channel. @@ -176,29 +179,23 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t } } DisplayKind::Normal => { - let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); - for i in 0..TILE_AREA { - let pixel = &mut out[i * 4..i * 4 + 4]; - + let (n, sheen_roughness) = (get(Channel::Normal), get(Channel::SheenRoughness)); + let sheen_default = Channel::SheenRoughness.default_value()[0]; + for (i, pixel) in out.as_chunks_mut::<8>().0.iter_mut().enumerate() { // The baked normal is the base the painted normal details sit on (as in export) let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales); - match (n, base) { - (Some(t), None) => { - for (k, d) in pixel.iter_mut().take(3).enumerate() { - *d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0)); - } - } - (detail, Some(base)) => { - let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); - let v = texturecraft_core::blend::rnm(base, detail); - for (d, v) in pixel.iter_mut().zip(v) { - *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - } - } - (None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]), + let painted = n.map(|t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); + let packed = match (painted, base) { + (Some(painted), None) => painted, + (painted, Some(base)) => texturecraft_core::blend::rnm(base, painted.unwrap_or([0.5, 0.5, 1.0])), + (None, None) => [0.5, 0.5, 1.0], + }; + let sheen = sheen_roughness.and_then(|t| t.get(i)).map_or(sheen_default, |v| *v as f32 / 65535.0); + let [x, y, z] = packed.map(|v| (v * 2.0 - 1.0).clamp(-1.0, 1.0)); + for (k, c) in [x, y, z, sheen].into_iter().enumerate() { + pixel[k * 2..k * 2 + 2].copy_from_slice(&half::f16::from_f32(c).to_le_bytes()); } - pixel[3] = sheen_roughness(i); } } DisplayKind::Height => { @@ -250,8 +247,7 @@ mod tests { let comp = Composite::new(&[], 64); let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0); assert_eq!(&orm[..4], &[255, 128, 0, 128]); - let n = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Normal, 0, 0); - assert_eq!(&n[..4], &[128, 128, 255, 128], "sheen roughness 0.5 rides in alpha"); + assert_eq!(normal_texel(&comp, &BakedMaps::default(), 0), [0.0, 0.0, 1.0, 0.5], "flat, sheen roughness 0.5 rides in alpha"); assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]); assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1"); assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]); @@ -269,18 +265,36 @@ mod tests { // A baked normal tilted to +X (packed), 64² like the set. let tilted = [0.8f32, 0.5, 0.9]; let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(tilted.repeat(64 * 64)))].into_iter().collect() }; - let shown = |comp: &Composite| tile_bytes(comp, &baked, DisplayKind::Normal, 0, 0)[..3].to_vec(); - let pack = |v: [f32; 3]| v.map(|x| (x * 255.0 + 0.5) as u8).to_vec(); + let shown = |comp: &Composite| normal_texel(comp, &baked, 0)[..3].to_vec(); + let pack = |v: [f32; 3]| v.map(|x| half::f16::from_f32(x * 2.0 - 1.0).to_f32()).to_vec(); // No normal channel: the baked normal as it is. assert_eq!(shown(&Composite::new(&[], 64)), pack(tilted)); // A flat painted normal leaves it; a painted detail is re-oriented onto it. let mut comp = Composite::new(&[Channel::Normal], 64); comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.5), to_u16(1.0)]); - assert!(shown(&comp).iter().zip(pack(tilted)).all(|(a, b)| (*a as i32 - b as i32).abs() <= 1), "{:?}", shown(&comp)); + assert!(shown(&comp).iter().zip(pack(tilted)).all(|(a, b)| (a - b).abs() < 1e-3), "{:?}", shown(&comp)); comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.8), to_u16(0.9)]); assert_eq!(shown(&comp), pack(texturecraft_core::blend::rnm(tilted, [0.5, 0.8, 0.9]))); } + /// Texel `i` of the Normal display tile (0, 0) decoded: signed normal, sheen roughness. + fn normal_texel(comp: &Composite, baked: &BakedMaps, i: usize) -> [f32; 4] { + let t = tile_bytes(comp, baked, DisplayKind::Normal, 0, 0); + [0, 1, 2, 3].map(|k| half::f16::from_le_bytes([t[i * 8 + k * 2], t[i * 8 + k * 2 + 1]]).to_f32()) + } + + #[test] + fn baked_normals_keep_more_than_8_bits_in_the_viewport() { + // A smooth baked gradient steps 1/1024 per texel: 8 bits rounded four texels to one value, + // which shaded as visible bands on curved surfaces. + let ramp: Vec = (0..64 * 64).flat_map(|i| [0.5 + (i % 64) as f32 / 1024.0, 0.5, 0.9]).collect(); + let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(ramp))].into_iter().collect() }; + let comp = Composite::new(&[], 64); + let xs: Vec = (0..8).map(|i| normal_texel(&comp, &baked, i)[0]).collect(); + assert!(xs.windows(2).all(|w| w[1] > w[0]), "every texel of the gradient is distinct: {xs:?}"); + assert!(xs.windows(2).all(|w| w[1] - w[0] < 1.0 / 255.0), "steps finer than one 8-bit level: {xs:?}"); + } + #[test] fn glossiness_shows_as_roughness_and_specular_rides_in_height() { let mut comp = Composite::new(&[Channel::Glossiness, Channel::Specular], 64); @@ -314,7 +328,7 @@ mod tests { let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1); assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes)); assert!(near(&px(DisplayKind::Sheen), &[255, 0, 188, 204]), "{:?}", px(DisplayKind::Sheen)); - assert!(near(&px(DisplayKind::Normal)[3..], &[77]) && near(&px(DisplayKind::Emissive)[3..], &[102])); + assert!((normal_texel(&comp, &BakedMaps::default(), 1)[3] - 0.3).abs() < 1e-3 && near(&px(DisplayKind::Emissive)[3..], &[102])); assert!(near(&px(DisplayKind::Extra), &[255, 128, 153, 0]), "{:?}", px(DisplayKind::Extra)); for c in Channel::LOBES { assert_ne!(DisplayKind::of_channel(c), DisplayKind::Orm, "{c:?}"); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1636f1ad..a69561ba 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -626,8 +626,9 @@ fn uniform_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { pub(crate) fn display_format(k: DisplayKind) -> wgpu::TextureFormat { match k { DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => wgpu::TextureFormat::Rgba8UnormSrgb, - DisplayKind::Orm | DisplayKind::Normal | DisplayKind::Lobes | DisplayKind::Extra => wgpu::TextureFormat::Rgba8Unorm, - DisplayKind::Height => wgpu::TextureFormat::Rgba16Float, + DisplayKind::Orm | DisplayKind::Lobes | DisplayKind::Extra => wgpu::TextureFormat::Rgba8Unorm, + // Baked normals are smooth high-precision data: 8 bits band the shading + DisplayKind::Normal | DisplayKind::Height => wgpu::TextureFormat::Rgba16Float, } } diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 23c4bd64..5be8ddd5 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -249,8 +249,8 @@ fn rnm(base: vec3, detail: vec3) -> vec3 { return normalize(t * dot(t, u) - u * t.z); } -// Signed values packed in 8 bits: byte 128 decodes to exactly 0, so flat normals stay flat -// (the CPU packing and both path tracers use the same rule). +// Signed values packed in 8 bits (the coat normal in Extra): byte 128 decodes to exactly 0, so +// flat normals stay flat (the CPU packing uses the same rule). fn snorm8(v: vec3) -> vec3 { return clamp((v * 255.0 - 128.0) / 127.0, vec3(-1.0), vec3(1.0)); } @@ -407,7 +407,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { // Same slope rule as texture export: strength 1 tilts 45° for a height change of 1 over 1/16 of the width. let k = g.mode.z * dims.x / 16.0 * tile_scale(uv); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); - var n_detail = snorm8(nrm_s); + // The Normal texture holds the signed normal in half floats (flat is exactly +z) + var n_detail = clamp(nrm_s, vec3(-1.0), vec3(1.0)); n_detail.y *= g.mode.w; let n_ts = rnm(n_height, normalize(n_detail)); let n = normalize(t * n_ts.x + b * n_ts.y + n_geo * n_ts.z); @@ -601,7 +602,7 @@ fn fs_uv(i: VOut) -> @location(0) vec4 { switch ch { case 1: { return data_out(vec3(orm.b)); } case 2: { return data_out(vec3(orm.g)); } - case 3: { return raw_out(textureSample(t_nrm, samp, i.uv).rgb); } + case 3: { return raw_out(textureSample(t_nrm, samp, i.uv).rgb * 0.5 + 0.5); } case 4: { return raw_out(vec3(textureSample(t_height, samp, i.uv).r * 0.5 + 0.5)); } case 5: { return data_out(textureSample(t_emis, samp, i.uv).rgb); } case 6: { return raw_out(vec3(base_s.a)); } diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index 10fe6853..995c9f32 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -299,9 +299,8 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { let hy = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r; n_height = normalize_or(vec3(-hx * 0.5 * k, hy * 0.5 * k, 1.0), vec3(0.0, 0.0, 1.0)); } - // 8-bit normals centred on 128, so the flat normal (128, 128, 255) is exactly +z (with - // `× 2 − 1` it would lean 0.3°, shifting every reflection). - let detail = normalize_or((nrm_t.rgb * 255.0 - 128.0) / 127.0, vec3(0.0, 0.0, 1.0)); + // The signed normal in half floats, as in mesh.wgsl (flat is exactly +z) + let detail = normalize_or(clamp(nrm_t.rgb, vec3(-1.0), vec3(1.0)), vec3(0.0, 0.0, 1.0)); let n_ts = rnm(n_height, detail); let tt = normalize_or(tw - n_geo * dot(n_geo, tw), onb_t(n_geo)); let b = cross(n_geo, tt) * tsign; From 052bccedf49d79bcb7660d29bf5c92191c5504c6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 14 Nov 2026 11:12:04 +0100 Subject: [PATCH 15/28] Remember the new mesh path after Change mesh Change mesh replaced the mesh but left Project::mesh_path on the old file, so Reimport mesh (and a saved project) went back to the original mesh. The path is now stored after the swap succeeded; a failed change keeps the old one. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/file_cmds.rs | 38 +++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index bdb19e7e..fa19c905 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -451,7 +451,10 @@ fn reimport(s: &mut Session, p: &Value) -> Result { fn change_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "path", "file.changeMesh")?; let file = native::read_mesh("file.changeMesh", path)?; - s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true)) + let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?; + // Only after the swap succeeded: Reimport mesh and Save keep following the new file. + s.doc.project.mesh_path = native::absolute(path); + Ok(reply) } #[cfg(not(target_arch = "wasm32"))] @@ -816,6 +819,39 @@ f 1/1 2/2 3/3 std::fs::remove_dir_all(&dir).ok(); } + /// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B, + /// not A. A failed change leaves the remembered path alone. + #[test] + fn change_mesh_remembers_the_new_file_for_reimport() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"); + let (a, b) = (dir.join("a.obj"), dir.join("b.obj")); + std::fs::write(&a, obj(1.0)).unwrap(); + std::fs::write(&b, obj(2.0)).unwrap(); + let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap(); + let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap(); + // A failed change (unreadable file) keeps A. + let missing = dir.join("missing.obj"); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err()); + assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str())); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert_eq!(width(&s), 2.0); + let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered"); + assert_ne!(a_abs, b_abs); + // The remembered path survives save and reopen. + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str())); + // Edit B, then Reimport from the remembered path: B's edits arrive, not A. + std::fs::write(&b, obj(3.0)).unwrap(); + let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap(); + crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap(); + assert_eq!(width(&reopened), 3.0); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() { let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id())); From 5828177d8c067eb90e5586292263c53ce2f4a6e0 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 16:43:37 +0100 Subject: [PATCH 16/28] Remove the temporary Edit > Change mesh... menu item The file.changeMesh command stays (trusted local command API and the control channel); the Project Configuration window will offer it in a later PR. The command is no longer listed under the Edit menu. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/file_cmds.rs | 4 ++-- crates/engine/tests/it/bake.rs | 2 +- crates/ui-egui/src/menus.rs | 1 - crates/ui-egui/src/windows.rs | 10 ---------- crates/ui-egui/tests/it/bake_job_mesh.rs | 2 +- docs/features.md | 4 ++-- docs/parity.md | 1 - 7 files changed, 6 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index fa19c905..e4d17f53 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -39,8 +39,8 @@ pub fn specs() -> Vec { ), cmd!( "file.changeMesh", - "Change mesh...", - ["Edit"], + "Change mesh", + [], None, "{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index", always, diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 6d135f4f..62afeb63 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -613,7 +613,7 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { assert_eq!(session.history_labels(), history); } -/// Edit > Change mesh swaps the mesh under a baked project: the high poly and the skew map stay, +/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay, /// the project counts as changed, and image resources are decoded in the new session. #[test] fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 51081b18..72d78b34 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -57,7 +57,6 @@ pub const CATALOG: &[Item] = &[ sep("Edit"), it("Edit", "Project Configuration...", "ui.projectConfig", None), it("Edit", "Reimport mesh", "file.reimportMesh", Some("Ctrl+Shift+R")), - it("Edit", "Change mesh...", "file.changeMesh", None), it("Edit", "Settings...", "ui.settings", None), it("Mode", "Bake Mesh Maps", "ui.mode.bake", Some("F8")), it("Mode", "Painting", "ui.mode.paint", Some("F9")), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 145727a7..8d573899 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -977,16 +977,6 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> }); true } - "file.changeMesh" => { - // Layers and texture sets stay; the strokes follow the surface onto the new mesh. - let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); - app.ask_file(dialog, Bound::Project, |app, paths| { - if let Some(p) = paths.first() { - app.run("file.changeMesh", json!({"path": p.display().to_string()})); - } - }); - true - } _ => false, } } diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 0311c054..60f6f03e 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -1,4 +1,4 @@ -//! A bake job belongs to the mesh it started on: when Edit > Change mesh (or a reimport) swaps +//! 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. use std::sync::Arc; diff --git a/docs/features.md b/docs/features.md index 9cba8319..a456a371 100644 --- a/docs/features.md +++ b/docs/features.md @@ -80,8 +80,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. - Reimport a changed mesh and your painted strokes stay on the surface. **Edit ▸ Change mesh...** - (`file.changeMesh`) moves the project onto a different mesh file and keeps its layers. + Reimport a changed mesh and your painted strokes stay on the surface. The + `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). diff --git a/docs/parity.md b/docs/parity.md index 3fd7392b..75f6fd30 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -31,7 +31,6 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Redo | `edit.redo` | Ctrl+Y | live | | Project Configuration... | `ui.projectConfig` | | live | | Reimport mesh | `file.reimportMesh` | Ctrl+Shift+R | live | -| Change mesh... | `file.changeMesh` | | live | | Settings... | `ui.settings` | | live | ## Mode From a1847a2e244907b7e52600ab997ecbefee999c1c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 16:51:26 +0100 Subject: [PATCH 17/28] Edit > Project Configuration: a window with the 3D mesh section Select... picks another mesh file (ticks Reimport mesh), OK runs file.changeMesh, or file.reimportMesh when only Reimport mesh is ticked. The Display panel keeps its own rail icon and View entry. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus.rs | 4 + crates/ui-egui/src/project_config.rs | 139 +++++++++++++++++ crates/ui-egui/src/rail_popup.rs | 1 + crates/ui-egui/src/state.rs | 14 ++ crates/ui-egui/src/windows.rs | 4 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/project_config.rs | 172 ++++++++++++++++++++++ crates/ui-egui/tests/it/rail.rs | 5 +- docs/features.md | 2 + 10 files changed, 340 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/project_config.rs create mode 100644 crates/ui-egui/tests/it/project_config.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b80b1790..6daf3c5e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -40,6 +40,8 @@ mod preview_image; mod preview_request; mod preview_worker; pub mod profile; +#[cfg(not(target_arch = "wasm32"))] +mod project_config; pub mod properties_popup; mod rail_popup; pub mod render_mode; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 72d78b34..4f39b6fd 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -156,6 +156,10 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.newProject" => app.ui.windows.new_project = true, "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), + #[cfg(not(target_arch = "wasm32"))] + "ui.projectConfig" => crate::project_config::open(app), + // The browser can't change the mesh file, so only the Display panel is left to open. + #[cfg(target_arch = "wasm32")] "ui.projectConfig" => crate::rail_popup::open(app, crate::docking::Panel::Display), "ui.settings" => app.ui.windows.settings = true, "ui.mode.bake" => app.ui.mode = Mode::Baking, diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs new file mode 100644 index 00000000..f23552b2 --- /dev/null +++ b/crates/ui-egui/src/project_config.rs @@ -0,0 +1,139 @@ +//! Edit > Project Configuration...: the project's settings in sections. Today it has one, the +//! 3D mesh: pick another mesh file for the project, or read the current one again. + +use egui::{Key, Modifiers}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::tr; +use crate::state::ProjectConfig; +use crate::theme::caption; +use crate::widgets::primary_button; + +/// Room for the Select... button beside the path. +const SELECT_BUTTON_WIDTH: f32 = 90.0; + +/// Opens the window on the current project, with nothing chosen yet. +pub(crate) fn open(app: &mut TextureCraftApp) { + app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, project: app.session.project_id }); +} + +/// `text` with its beginning replaced by an ellipsis until `fits` accepts it (the end of a path +/// is the part that tells files apart). +fn elide_start(text: &str, fits: impl Fn(&str) -> bool) -> String { + if fits(text) { + return text.to_string(); + } + let chars: Vec = text.chars().collect(); + let shown = |from: usize| format!("…{}", chars[from..].iter().collect::()); + // Dropping more characters only ever makes it shorter, so the first start that fits is found by bisection. + let (mut low, mut high) = (1, chars.len()); + while low < high { + let mid = low + (high - low) / 2; + if fits(&shown(mid)) { + high = mid; + } else { + low = mid + 1; + } + } + shown(low) +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut config) = app.ui.windows.project_config.clone() else { return }; + // Another project was opened meanwhile: the choices were for the old one. + if config.project != app.session.project_id { + app.ui.windows.project_config = None; + return; + } + let current = app.session.doc.project.mesh_path.clone(); + // A file other than the project's own is the project's new mesh. + let changed = config.mesh.as_ref().filter(|chosen| **chosen != current).cloned(); + + let mut open = true; + let (mut ok, mut cancel, mut select) = (false, false, false); + let font = egui::TextStyle::Body.resolve(&ctx.style()); + crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(460.0).show(ctx, |ui| { + // One section per part of the project; more follow the same pattern. + ui.label(caption(tr("3D MESH"))); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.label(tr("3D mesh")); + let shown = changed.clone().unwrap_or_else(|| current.clone()); + let max = (ui.available_width() - SELECT_BUTTON_WIDTH).max(60.0); + let measure = |s: &str| ui.painter().layout_no_wrap(s.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= max; + if shown.is_empty() { + ui.weak(tr("Built-in mesh")); + } else { + ui.label(elide_start(&shown, measure)).on_hover_text(&shown); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + select = ui.button(tr("Select...")).clicked(); + }); + }); + ui.add_space(4.0); + // Another file always reads the mesh again, so its box is ticked and stays ticked. + let mut reimport = config.reimport || changed.is_some(); + ui.add_enabled(changed.is_none(), egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))) + .on_hover_text(tr("Read the mesh file again, keeping the layers and painted strokes")); + config.reimport = reimport; + ui.add_space(12.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ok = ui.add(primary_button(ui, tr("OK"))).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + }); + // Esc cancels; Enter confirms unless a button has the keyboard (it presses that one itself). + let nothing_focused = ctx.memory(|m| m.focused()).is_none(); + ctx.input_mut(|i| { + cancel |= i.consume_key(Modifiers::NONE, Key::Escape); + ok |= nothing_focused && i.consume_key(Modifiers::NONE, Key::Enter); + }); + + if select { + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + app.ask_file(dialog, Bound::Project, |app, paths| { + let Some(path) = paths.first().map(|p| p.display().to_string()) else { return }; + let current = app.session.doc.project.mesh_path.clone(); + if let Some(config) = app.ui.windows.project_config.as_mut() { + // Picking the project's own file again drops an earlier choice. + config.mesh = (path != current).then_some(path); + config.reimport |= config.mesh.is_some(); + } + }); + } + if ok || cancel || !open { + app.ui.windows.project_config = None; + } else { + // Keep a tick made now; the file answer arrives later through the stored value. + if let Some(stored) = app.ui.windows.project_config.as_mut() { + stored.reimport = config.reimport; + } + } + if ok { + if let Some(path) = changed { + app.run("file.changeMesh", json!({"path": path, "preserveStrokes": true})); + } else if config.reimport { + crate::menus::invoke(app, ctx, "file.reimportMesh"); + } + } +} + +#[cfg(test)] +mod tests { + use super::elide_start; + + #[test] + fn a_path_that_fits_is_unchanged() { + assert_eq!(elide_start("/a/b.obj", |s| s.chars().count() <= 20), "/a/b.obj"); + } + + #[test] + fn a_long_path_loses_its_beginning() { + let shown = elide_start("/home/me/projects/models/hero.obj", |s| s.chars().count() <= 12); + assert_eq!(shown, "…/hero.obj", "the longest tail that fits, not a shorter one"); + } +} diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index afe85f1a..6826c1a0 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -102,6 +102,7 @@ pub(crate) fn toggle(app: &mut TextureCraftApp, panel: Panel) { } /// Open `panel` from the rail: in its popup, or where it is in the dock (bake mode has no rail) +#[cfg(target_arch = "wasm32")] pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) { if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { app.ui.dock.focus(panel); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e52a2907..20d89882 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -76,11 +76,25 @@ pub struct Windows { /// The start window: new, open, recent projects (the app opens it at launch). #[serde(skip)] pub start: bool, + /// Edit > Project Configuration: what is chosen so far, applied by OK. + #[serde(skip)] + pub project_config: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, } +/// Edit > Project Configuration, the 3D mesh section. +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ProjectConfig { + /// A mesh file picked with Select..., not applied until OK. + pub mesh: Option, + /// The Reimport mesh box. + pub reimport: bool, + /// The project the window was opened on (`Session::project_id`). + pub project: u64, +} + /// An action that replaces or ends the project, held while the project has unsaved changes. #[derive(Clone, Debug, PartialEq)] pub enum Unsaved { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8d573899..0416b022 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -23,6 +23,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { new_project(app, ctx); about(app, ctx); settings(app, ctx); + #[cfg(not(target_arch = "wasm32"))] + crate::project_config::show(app, ctx); crate::keymap::window(app, ctx); crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] @@ -152,7 +154,7 @@ pub(crate) fn window<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Win } /// A centered dialog; `id` keeps its place across UI languages. -fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { +pub(crate) fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> { egui::Window::new(title.to_owned()) .id(egui::Id::unique(id)) .open(open) diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 00f1ba79..8f0483ce 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -26,6 +26,7 @@ mod path_in_view; mod path_list; mod pen_pressure; mod polygon_fill; +mod project_config; mod properties_popup; mod rail; mod shelf_drop; diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs new file mode 100644 index 00000000..984cae5c --- /dev/null +++ b/crates/ui-egui/tests/it/project_config.rs @@ -0,0 +1,172 @@ +//! Edit > Project Configuration...: the 3D mesh section. File pickers are answered by the +//! override, never shown. + +use std::path::PathBuf; + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; +const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"; +const TITLE: &str = "Project configuration"; + +/// A new folder for one test. +fn temp_dir(test: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-project-config-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// An app whose project is the quad in `dir/quad.obj` with a fill layer on it. +fn app_on_a_quad(dir: &std::path::Path) -> Harness<'static, TextureCraftApp> { + let file = dir.join("quad.obj"); + std::fs::write(&file, QUAD).unwrap(); + let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); + texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + session.doc.project.mesh_path = file.display().to_string(); + 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 +} + +fn open_window(h: &mut Harness<'_, TextureCraftApp>) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.projectConfig"); + h.run_steps(3); +} + +fn window_is_open(h: &Harness<'_, TextureCraftApp>) -> bool { + h.query_by_label(TITLE).is_some() +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + h.get_by_role_and_label(role, label).click(); + h.run_steps(3); +} + +/// Select... answered with `file`. +fn select(h: &mut Harness<'_, TextureCraftApp>, file: &std::path::Path) { + let file = file.to_path_buf(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![file.clone()])))); + click(h, Role::Button, "Select..."); +} + +fn reimport_ticked(h: &Harness<'_, TextureCraftApp>) -> bool { + h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.reimport) +} + +#[test] +fn the_menu_opens_the_window() { + let dir = temp_dir("menu"); + let mut h = app_on_a_quad(&dir); + assert!(!window_is_open(&h)); + open_window(&mut h); + assert!(window_is_open(&h)); + assert!(h.query_by_label("3D MESH").is_some(), "the 3D mesh section"); + assert!(!reimport_ticked(&h), "nothing is ticked at first"); + assert!(h.state().ui.rail_panel.is_none(), "the Display panel stays where it was"); +} + +#[test] +fn another_file_shows_its_path_and_ticks_reimport() { + let dir = temp_dir("select"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + open_window(&mut h); + select(&mut h, &tri); + assert!(h.query_by_label_contains("tri.obj").is_some(), "the chosen file is shown"); + assert!(reimport_ticked(&h)); + assert_eq!(h.state().session.mesh.triangle_count(), 2, "nothing changes before OK"); +} + +#[test] +fn ok_moves_the_project_to_the_chosen_mesh_and_keeps_the_layers() { + let dir = temp_dir("ok"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + let layers = h.state().session.doc.project.layers.len(); + open_window(&mut h); + select(&mut h, &tri); + click(&mut h, Role::Button, "OK"); + let session = &h.state().session; + assert_eq!(session.mesh.triangle_count(), 1, "the new mesh is in use"); + assert_eq!(session.doc.project.mesh_file, "tri.obj"); + assert!(session.doc.project.mesh_path.ends_with("tri.obj"), "Reimport mesh now follows the new file"); + assert_eq!(session.doc.project.layers.len(), layers, "the layers stay"); + assert!(!window_is_open(&h)); +} + +#[test] +fn ticking_reimport_alone_reads_the_same_file_again() { + let dir = temp_dir("reimport"); + let mut h = app_on_a_quad(&dir); + let project = h.state().session.project_id; + let layers = h.state().session.doc.project.layers.len(); + // The file changed on disk since it was imported + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + open_window(&mut h); + click(&mut h, Role::CheckBox, "Reimport mesh"); + assert!(reimport_ticked(&h)); + click(&mut h, Role::Button, "OK"); + let session = &h.state().session; + assert_eq!(session.mesh.triangle_count(), 1, "the edited file was read again"); + assert_eq!(session.project_id, project); + assert_eq!(session.doc.project.layers.len(), layers); + assert!(!window_is_open(&h)); +} + +#[test] +fn ok_with_nothing_chosen_changes_nothing() { + let dir = temp_dir("nothing"); + let mut h = app_on_a_quad(&dir); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + let mesh = h.state().session.mesh_id; + open_window(&mut h); + click(&mut h, Role::Button, "OK"); + assert_eq!(h.state().session.mesh_id, mesh); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + assert!(!window_is_open(&h)); +} + +#[test] +fn cancel_and_escape_change_nothing() { + let dir = temp_dir("cancel"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + let mesh = h.state().session.mesh_id; + open_window(&mut h); + select(&mut h, &tri); + click(&mut h, Role::Button, "Cancel"); + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.mesh_id, mesh); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + + // Opened again, the old choice is gone, and Esc closes it too + open_window(&mut h); + assert!(!reimport_ticked(&h)); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.mesh_id, mesh); +} + +#[test] +fn a_failing_change_is_reported_as_a_toast() { + let dir = temp_dir("error"); + let mut h = app_on_a_quad(&dir); + let missing = dir.join("missing.obj"); + open_window(&mut h); + select(&mut h, &missing); + click(&mut h, Role::Button, "OK"); + assert!(h.state().toasts.iter().any(|t| t.error), "the error shows as a toast"); + assert_eq!(h.state().session.mesh.triangle_count(), 2, "the project keeps its mesh"); +} diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index db4046f6..ae91c96b 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -226,9 +226,8 @@ fn window_views_open_the_rail_panels_popup() { assert!(popup_shows(&harness, "Shader Settings")); assert!(!harness.state().ui.dock.is_open(Panel::Shader)); - // Project configuration opens Display Settings, in its popup too - texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.projectConfig"); - harness.run_steps(SETTLE_FRAMES); + // Display Settings opens the same way, from its own rail icon (Project Configuration is a window of its own) + click_rail(&mut harness, "Display Settings"); assert!(popup_shows(&harness, "Display Settings")); } diff --git a/docs/features.md b/docs/features.md index a456a371..93b2f894 100644 --- a/docs/features.md +++ b/docs/features.md @@ -82,6 +82,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and images and a loose USD layer's textures are read from its folder and kept in the project. Reimport a changed mesh and your painted strokes stay on the surface. The `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. + **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the + file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). From a05109991b3f46b97e223ec17f09a6936735a1d6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 16:59:20 +0100 Subject: [PATCH 18/28] Project Configuration: review fixes Escape closes the window before a stroke is cancelled, Enter only when no field or button had the keyboard, the Reimport tick is the user's own, a failed change keeps the window open, a missing or built-in mesh has nothing to reimport, and the built-in label falls back to the imported file name. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/menus.rs | 8 +- crates/ui-egui/src/project_config.rs | 86 +++++++++------ crates/ui-egui/src/state.rs | 4 +- crates/ui-egui/tests/it/project_config.rs | 123 ++++++++++++++++++++-- 4 files changed, 180 insertions(+), 41 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4f39b6fd..4be1e51b 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -348,6 +348,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Escape closes a dropdown before Properties, the rail popup, color picking or the stroke let popup_open = egui::Popup::is_any_open(ctx); + #[cfg(not(target_arch = "wasm32"))] + let nothing_focused = ctx.memory(|memory| memory.focused().is_none()); let commands_to_invoke = ctx.input_mut(|input| { // egui's label selection copies on these events at the end of the frame let copies: Vec<_> = input.events.iter().filter(|event| matches!(event, egui::Event::Copy | egui::Event::Cut)).cloned().collect(); @@ -367,7 +369,11 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + if app.ui.windows.project_config.is_some() { + // Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched + #[cfg(not(target_arch = "wasm32"))] + crate::project_config::keys_in(app, input, nothing_focused); + } else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index f23552b2..1f7ac622 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -16,7 +16,7 @@ const SELECT_BUTTON_WIDTH: f32 = 90.0; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { - app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, project: app.session.project_id }); + app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, confirm: false, project: app.session.project_id }); } /// `text` with its beginning replaced by an ellipsis until `fits` accepts it (the end of a path @@ -40,6 +40,22 @@ fn elide_start(text: &str, fits: impl Fn(&str) -> bool) -> String { shown(low) } +/// The keys of the open window, read in `menus::shortcuts` before any panel draws: Escape closes +/// it (and goes no further, so it doesn't cancel a stroke), Enter confirms it unless a text field +/// or button had the keyboard (`nothing_focused`), whose Enter belongs to it. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool) { + let escape = input.consume_key(Modifiers::NONE, Key::Escape); + let enter = input.consume_key(Modifiers::NONE, Key::Enter); + if escape { + app.ui.windows.project_config = None; + } else if enter + && nothing_focused + && let Some(config) = app.ui.windows.project_config.as_mut() + { + config.confirm = true; + } +} + pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(mut config) = app.ui.windows.project_config.clone() else { return }; // Another project was opened meanwhile: the choices were for the old one. @@ -47,20 +63,24 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.project_config = None; return; } - let current = app.session.doc.project.mesh_path.clone(); + let project = &app.session.doc.project; + let current = project.mesh_path.clone(); + // What the project's mesh came from: its file, or at least the name it was imported under. + let named = if current.is_empty() { project.mesh_file.clone() } else { current.clone() }; + let readable = app.session.remembered_mesh_path().is_some(); // A file other than the project's own is the project's new mesh. let changed = config.mesh.as_ref().filter(|chosen| **chosen != current).cloned(); let mut open = true; - let (mut ok, mut cancel, mut select) = (false, false, false); - let font = egui::TextStyle::Body.resolve(&ctx.style()); + let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(460.0).show(ctx, |ui| { // One section per part of the project; more follow the same pattern. ui.label(caption(tr("3D MESH"))); ui.add_space(4.0); ui.horizontal(|ui| { ui.label(tr("3D mesh")); - let shown = changed.clone().unwrap_or_else(|| current.clone()); + let shown = changed.clone().unwrap_or_else(|| named.clone()); + let font = egui::TextStyle::Body.resolve(ui.style()); let max = (ui.available_width() - SELECT_BUTTON_WIDTH).max(60.0); let measure = |s: &str| ui.painter().layout_no_wrap(s.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= max; if shown.is_empty() { @@ -72,26 +92,29 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { select = ui.button(tr("Select...")).clicked(); }); }); + if changed.is_none() && !current.is_empty() && !readable { + ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); + } ui.add_space(4.0); - // Another file always reads the mesh again, so its box is ticked and stays ticked. + // Another file always reads the mesh again, so its box shows ticked and can't be cleared. + // Without a file on disk there is nothing to read again. let mut reimport = config.reimport || changed.is_some(); - ui.add_enabled(changed.is_none(), egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))) - .on_hover_text(tr("Read the mesh file again, keeping the layers and painted strokes")); - config.reimport = reimport; + let free = changed.is_none() && readable; + let tick = ui.add_enabled(free, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))); + if free { + config.reimport = reimport; + tick.on_hover_text(tr("Read the mesh file again, keeping the layers and painted strokes")); + } else if changed.is_none() { + tick.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); + } ui.add_space(12.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ok = ui.add(primary_button(ui, tr("OK"))).clicked(); + ok |= ui.add(primary_button(ui, tr("OK"))).clicked(); cancel = ui.button(tr("Cancel")).clicked(); }); }); }); - // Esc cancels; Enter confirms unless a button has the keyboard (it presses that one itself). - let nothing_focused = ctx.memory(|m| m.focused()).is_none(); - ctx.input_mut(|i| { - cancel |= i.consume_key(Modifiers::NONE, Key::Escape); - ok |= nothing_focused && i.consume_key(Modifiers::NONE, Key::Enter); - }); if select { let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); @@ -101,24 +124,25 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if let Some(config) = app.ui.windows.project_config.as_mut() { // Picking the project's own file again drops an earlier choice. config.mesh = (path != current).then_some(path); - config.reimport |= config.mesh.is_some(); } }); } - if ok || cancel || !open { + // OK closes the window once the change worked; a failure leaves it open, choice kept, with its toast. + let done = ok + && if let Some(path) = changed { + app.run("file.changeMesh", json!({"path": path, "preserveStrokes": true})).is_some() + } else if config.reimport + && let Some(path) = app.session.remembered_mesh_path().map(str::to_string) + { + app.run("file.reimportMesh", json!({"path": path, "preserveStrokes": true})).is_some() + } else { + true + }; + if done || cancel || !open { app.ui.windows.project_config = None; - } else { - // Keep a tick made now; the file answer arrives later through the stored value. - if let Some(stored) = app.ui.windows.project_config.as_mut() { - stored.reimport = config.reimport; - } - } - if ok { - if let Some(path) = changed { - app.run("file.changeMesh", json!({"path": path, "preserveStrokes": true})); - } else if config.reimport { - crate::menus::invoke(app, ctx, "file.reimportMesh"); - } + } else if let Some(stored) = app.ui.windows.project_config.as_mut() { + // Keep the tick made now; the file answer arrives later through the stored value. + stored.reimport = config.reimport; } } @@ -134,6 +158,6 @@ mod tests { #[test] fn a_long_path_loses_its_beginning() { let shown = elide_start("/home/me/projects/models/hero.obj", |s| s.chars().count() <= 12); - assert_eq!(shown, "…/hero.obj", "the longest tail that fits, not a shorter one"); + assert_eq!(shown, "…ls/hero.obj", "the longest tail that fits, not a shorter one"); } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 20d89882..3e949768 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -89,8 +89,10 @@ pub struct Windows { pub struct ProjectConfig { /// A mesh file picked with Select..., not applied until OK. pub mesh: Option, - /// The Reimport mesh box. + /// The Reimport mesh box as the user set it (a chosen file reads the mesh again whatever it says). pub reimport: bool, + /// Enter was pressed: OK in the next frame. + pub confirm: bool, /// The project the window was opened on (`Session::project_id`). pub project: u64, } diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 984cae5c..c8cefe8c 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -5,7 +5,7 @@ use std::path::PathBuf; use egui::Role; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; @@ -15,11 +15,26 @@ const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\n const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"; const TITLE: &str = "Project configuration"; -/// A new folder for one test. -fn temp_dir(test: &str) -> PathBuf { +/// A new folder for one test, removed when the test ends (also when it fails). +struct TempDir(PathBuf); + +impl std::ops::Deref for TempDir { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} + +fn temp_dir(test: &str) -> TempDir { let dir = std::env::temp_dir().join(format!("texturecraft-project-config-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - dir + TempDir(dir) } /// An app whose project is the quad in `dir/quad.obj` with a fill layer on it. @@ -57,7 +72,13 @@ fn select(h: &mut Harness<'_, TextureCraftApp>, file: &std::path::Path) { click(h, Role::Button, "Select..."); } +/// The Reimport mesh box as the window shows it. fn reimport_ticked(h: &Harness<'_, TextureCraftApp>) -> bool { + h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +/// The tick the user made themselves, as stored. +fn own_tick(h: &Harness<'_, TextureCraftApp>) -> bool { h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.reimport) } @@ -83,6 +104,7 @@ fn another_file_shows_its_path_and_ticks_reimport() { select(&mut h, &tri); assert!(h.query_by_label_contains("tri.obj").is_some(), "the chosen file is shown"); assert!(reimport_ticked(&h)); + assert!(!own_tick(&h), "shown ticked, not stored as the user's tick"); assert_eq!(h.state().session.mesh.triangle_count(), 2, "nothing changes before OK"); } @@ -114,7 +136,7 @@ fn ticking_reimport_alone_reads_the_same_file_again() { std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); open_window(&mut h); click(&mut h, Role::CheckBox, "Reimport mesh"); - assert!(reimport_ticked(&h)); + assert!(reimport_ticked(&h) && own_tick(&h)); click(&mut h, Role::Button, "OK"); let session = &h.state().session; assert_eq!(session.mesh.triangle_count(), 1, "the edited file was read again"); @@ -137,7 +159,7 @@ fn ok_with_nothing_chosen_changes_nothing() { } #[test] -fn cancel_and_escape_change_nothing() { +fn cancel_changes_nothing() { let dir = temp_dir("cancel"); let mut h = app_on_a_quad(&dir); let tri = dir.join("tri.obj"); @@ -150,13 +172,96 @@ fn cancel_and_escape_change_nothing() { assert_eq!(h.state().session.mesh_id, mesh); assert_eq!(h.state().session.mesh.triangle_count(), 2); - // Opened again, the old choice is gone, and Esc closes it too + // Opened again, the old choice is gone open_window(&mut h); assert!(!reimport_ticked(&h)); + assert!(h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.mesh.is_none())); +} + +#[test] +fn escape_closes_the_window_and_leaves_a_stroke_alone() { + let dir = temp_dir("escape"); + let mut h = app_on_a_quad(&dir); + assert_eq!(h.state().ui.mode, texturecraft_ui_egui::state::Mode::Painting, "Painting is where Escape cancels strokes"); + texturecraft_engine::execute(&mut h.state_mut().session, "layer.add.paint", &json!({})).unwrap(); + h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + open_window(&mut h); h.key_press(egui::Key::Escape); h.run_steps(3); assert!(!window_is_open(&h)); - assert_eq!(h.state().session.mesh_id, mesh); + assert!(h.state().session.stroke_active(), "Escape went to the window, not to the stroke"); +} + +#[test] +fn enter_confirms_but_not_a_text_fields_enter() { + let dir = temp_dir("enter"); + let mut h = app_on_a_quad(&dir); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + open_window(&mut h); + // Ticked without a click, which would leave the box focused + h.state_mut().ui.windows.project_config.as_mut().unwrap().reimport = true; + // Renaming a layer: Enter belongs to the text field + let layer = h.state().session.selected_layer().unwrap().0; + let name = h.state().session.doc.project.layers.values().find(|l| l.id.0 == layer).unwrap().name.clone(); + h.state_mut().ui.rename = Some((layer, name)); + h.run_steps(3); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.state().ui.rename.is_none(), "Enter ended the rename"); + assert!(window_is_open(&h), "and did not press OK"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + + // With nothing focused, Enter is OK + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.mesh.triangle_count(), 1, "the tick was applied"); +} + +#[test] +fn picking_the_projects_own_file_again_drops_the_choice_and_its_tick() { + let dir = temp_dir("own"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + let mesh = h.state().session.mesh_id; + open_window(&mut h); + select(&mut h, &tri); + let own = h.state().session.doc.project.mesh_path.clone(); + select(&mut h, std::path::Path::new(&own)); + assert!(!reimport_ticked(&h), "the tick was only ever the file's"); + click(&mut h, Role::Button, "OK"); + assert_eq!(h.state().session.mesh_id, mesh, "OK does nothing"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); +} + +#[test] +fn a_missing_file_cannot_be_reimported() { + let dir = temp_dir("missing"); + let mut h = app_on_a_quad(&dir); + std::fs::remove_file(dir.join("quad.obj")).unwrap(); + open_window(&mut h); + assert!(h.query_by_label("File not found").is_some()); + assert!(h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().is_disabled()); + click(&mut h, Role::Button, "OK"); + assert_eq!(h.state().file_dialogs.pending(), 0, "no second dialog"); + assert!(!window_is_open(&h)); + assert!(h.state().toasts.is_empty()); +} + +#[test] +fn a_built_in_mesh_shows_its_name_and_has_nothing_to_reimport() { + let dir = temp_dir("builtin"); + let mut h = app_on_a_quad(&dir); + h.state_mut().session.doc.project.mesh_path.clear(); + open_window(&mut h); + assert!(h.query_by_label("quad.obj").is_some(), "the name it was imported under"); + assert!(h.query_by_label("File not found").is_none()); + assert!(h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().is_disabled()); + h.state_mut().session.doc.project.mesh_file.clear(); + h.run_steps(2); + assert!(h.query_by_label("Built-in mesh").is_some()); } #[test] @@ -168,5 +273,7 @@ fn a_failing_change_is_reported_as_a_toast() { select(&mut h, &missing); click(&mut h, Role::Button, "OK"); assert!(h.state().toasts.iter().any(|t| t.error), "the error shows as a toast"); + assert!(window_is_open(&h), "the window stays open"); + assert_eq!(h.state().ui.windows.project_config.as_ref().and_then(|c| c.mesh.clone()), Some(missing.display().to_string()), "with the choice kept"); assert_eq!(h.state().session.mesh.triangle_count(), 2, "the project keeps its mesh"); } From 91884a9585a195e7620348a89401947bc3c9d4af Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 17:04:44 +0100 Subject: [PATCH 19/28] Project Configuration: normal map format, UV tiles, import settings PROJECT SETTINGS sets the project's normal map format on OK and shows the UV tiles read only. Import settings holds Preserve stroke positions on mesh, passed as preserveStrokes to file.changeMesh / file.reimportMesh. A failed OK no longer re-fires from a stored Enter. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/project_config.rs | 106 ++++++++++++++++++---- crates/ui-egui/src/state.rs | 6 +- crates/ui-egui/tests/it/project_config.rs | 70 ++++++++++++++ docs/features.md | 4 +- 4 files changed, 167 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 1f7ac622..f0f76d37 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -2,21 +2,22 @@ //! 3D mesh: pick another mesh file for the project, or read the current one again. use egui::{Key, Modifiers}; -use serde_json::json; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; -use crate::i18n::tr; +use crate::i18n::{tr, trf}; use crate::state::ProjectConfig; use crate::theme::caption; -use crate::widgets::primary_button; +use crate::widgets::{combo, primary_button}; /// Room for the Select... button beside the path. const SELECT_BUTTON_WIDTH: f32 = 90.0; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { - app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, confirm: false, project: app.session.project_id }); + app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, preserve: true, normal_format: None, confirm: false, project: app.session.project_id }); } /// `text` with its beginning replaced by an ellipsis until `fits` accepts it (the end of a path @@ -56,6 +57,23 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, n } } +/// The command OK runs for the mesh: the project moves to `chosen`, or `reimport` (the project's +/// own file, when Reimport mesh is ticked) is read again. `preserve` is the Import settings box. +fn mesh_command(chosen: Option<&str>, reimport: Option<&str>, preserve: bool) -> Option<(&'static str, Value)> { + match (chosen, reimport) { + (Some(path), _) => Some(("file.changeMesh", json!({"path": path, "preserveStrokes": preserve}))), + (None, Some(path)) => Some(("file.reimportMesh", json!({"path": path, "preserveStrokes": preserve}))), + (None, None) => None, + } +} + +fn format_name(format: NormalFormat) -> &'static str { + match format { + NormalFormat::OpenGl => "OpenGL", + NormalFormat::DirectX => "DirectX", + } +} + pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(mut config) = app.ui.windows.project_config.clone() else { return }; // Another project was opened meanwhile: the choices were for the old one. @@ -68,6 +86,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // What the project's mesh came from: its file, or at least the name it was imported under. let named = if current.is_empty() { project.mesh_file.clone() } else { current.clone() }; let readable = app.session.remembered_mesh_path().is_some(); + let normal_format = project.normal_format; + // Each texture set's UV tiles, as `1001, 1002` (None: the set has none). + let tiles: Vec<(String, Option)> = project + .texture_sets + .iter() + .map(|set| (set.name.clone(), (!set.uv_tiles.is_empty()).then(|| set.uv_tiles.iter().map(u32::to_string).collect::>().join(", ")))) + .collect(); // A file other than the project's own is the project's new mesh. let changed = config.mesh.as_ref().filter(|chosen| **chosen != current).cloned(); @@ -107,6 +132,39 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if changed.is_none() { tick.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); } + ui.add_space(8.0); + ui.label(caption(tr("Import settings"))); + // Only a mesh that is going to be read has settings to apply. + let importing = changed.is_some() || (config.reimport && readable); + ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))) + .on_hover_text(tr("Painted strokes follow the surface when the new mesh's UVs differ")); + + ui.add_space(12.0); + ui.label(caption(tr("PROJECT SETTINGS"))); + ui.add_space(4.0); + let shown_format = config.normal_format.unwrap_or(normal_format); + combo(ui, tr("Normal map format"), format_name(shown_format), |ui| { + for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { + if ui.selectable_label(format == shown_format, format_name(format)).clicked() { + config.normal_format = (format != normal_format).then_some(format); + } + } + }) + .on_hover_text(tr( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + )); + ui.add_space(4.0); + // Read only: the tiles are set when the project is created. + ui.label(tr("UV Tile settings (UDIMs)")); + if tiles.iter().all(|(_, t)| t.is_none()) { + ui.label(egui::RichText::new(tr("Off")).weak()); + } + for (name, t) in tiles.iter().filter(|(_, t)| t.is_some()) { + let list = t.as_deref().unwrap_or_default(); + ui.label(egui::RichText::new(if tiles.len() > 1 { trf("{set}: {tiles}", &[("set", name), ("tiles", list)]) } else { list.to_string() }).weak()); + } + ui.label(egui::RichText::new(tr("You can't change UV Tile settings once a project has been created.")).small().weak()); + ui.add_space(12.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -127,28 +185,31 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } }); } - // OK closes the window once the change worked; a failure leaves it open, choice kept, with its toast. - let done = ok - && if let Some(path) = changed { - app.run("file.changeMesh", json!({"path": path, "preserveStrokes": true})).is_some() - } else if config.reimport - && let Some(path) = app.session.remembered_mesh_path().map(str::to_string) - { - app.run("file.reimportMesh", json!({"path": path, "preserveStrokes": true})).is_some() - } else { - true + // OK closes the window once everything worked; a failure leaves it open, choices kept, with its toast. + // The mesh goes first: a project that couldn't change its mesh stays as it was. + let done = ok && { + let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); + let mesh_done = match mesh_command(changed.as_deref(), reimport.as_deref(), config.preserve) { + Some((command, params)) => app.run(command, params).is_some(), + None => true, }; + mesh_done + && match config.normal_format { + Some(format) => app.run("textureSet.settings", json!({"normalFormat": if format == NormalFormat::DirectX { "directX" } else { "openGl" }})).is_some(), + None => true, + } + }; if done || cancel || !open { app.ui.windows.project_config = None; } else if let Some(stored) = app.ui.windows.project_config.as_mut() { - // Keep the tick made now; the file answer arrives later through the stored value. - stored.reimport = config.reimport; + // Keep the choices made now; the file answer arrives later through the stored value. + (stored.reimport, stored.preserve, stored.normal_format, stored.confirm) = (config.reimport, config.preserve, config.normal_format, false); } } #[cfg(test)] mod tests { - use super::elide_start; + use super::{elide_start, mesh_command}; #[test] fn a_path_that_fits_is_unchanged() { @@ -160,4 +221,15 @@ mod tests { let shown = elide_start("/home/me/projects/models/hero.obj", |s| s.chars().count() <= 12); assert_eq!(shown, "…ls/hero.obj", "the longest tail that fits, not a shorter one"); } + + #[test] + fn the_import_setting_goes_to_the_command() { + for preserve in [true, false] { + let (command, params) = mesh_command(Some("/a/b.obj"), None, preserve).unwrap(); + assert_eq!((command, params["preserveStrokes"].as_bool()), ("file.changeMesh", Some(preserve))); + let (command, params) = mesh_command(None, Some("/a/c.obj"), preserve).unwrap(); + assert_eq!((command, params["preserveStrokes"].as_bool(), params["path"].as_str()), ("file.reimportMesh", Some(preserve), Some("/a/c.obj"))); + } + assert!(mesh_command(None, None, true).is_none(), "nothing to read"); + } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3e949768..2b5af1af 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -84,13 +84,17 @@ pub struct Windows { pub unsaved: Option, } -/// Edit > Project Configuration, the 3D mesh section. +/// Edit > Project Configuration: the choices made so far, applied by OK. #[derive(Clone, Debug, PartialEq, Default)] pub struct ProjectConfig { /// A mesh file picked with Select..., not applied until OK. pub mesh: Option, /// The Reimport mesh box as the user set it (a chosen file reads the mesh again whatever it says). pub reimport: bool, + /// Import settings: painted strokes follow the surface of the new mesh. + pub preserve: bool, + /// The normal map format picked, when it differs from the project's. + pub normal_format: Option, /// Enter was pressed: OK in the next frame. pub confirm: bool, /// The project the window was opened on (`Session::project_id`). diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index c8cefe8c..588c25e7 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -277,3 +277,73 @@ fn a_failing_change_is_reported_as_a_toast() { assert_eq!(h.state().ui.windows.project_config.as_ref().and_then(|c| c.mesh.clone()), Some(missing.display().to_string()), "with the choice kept"); assert_eq!(h.state().session.mesh.triangle_count(), 2, "the project keeps its mesh"); } + +fn project_normal_format(h: &Harness<'_, TextureCraftApp>) -> texturecraft_engine::core::NormalFormat { + h.state().session.doc.project.normal_format +} + +#[test] +fn the_normal_map_format_changes_on_ok_and_shows_in_the_texture_set_panel() { + use texturecraft_engine::core::NormalFormat; + let dir = temp_dir("normal-format"); + let mut h = app_on_a_quad(&dir); + open_window(&mut h); + click(&mut h, Role::ComboBox, "OpenGL"); + click(&mut h, Role::Button, "DirectX"); + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl, "nothing changes before OK"); + click(&mut h, Role::Button, "OK"); + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); + h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::TextureSetSettings); + h.run_steps(3); + assert!(h.query_by_label("DirectX").is_some(), "the Texture Set Settings panel shows the project's format"); + // One undo step puts it back + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + h.run_steps(3); + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); +} + +#[test] +fn cancel_discards_a_normal_map_format() { + use texturecraft_engine::core::NormalFormat; + let dir = temp_dir("normal-format-cancel"); + let mut h = app_on_a_quad(&dir); + open_window(&mut h); + click(&mut h, Role::ComboBox, "OpenGL"); + click(&mut h, Role::Button, "DirectX"); + click(&mut h, Role::Button, "Cancel"); + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); +} + +#[test] +fn uv_tiles_are_shown_read_only() { + let dir = temp_dir("udim"); + let mut h = app_on_a_quad(&dir); + open_window(&mut h); + assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some()); + assert!(h.query_by_label("Off").is_some(), "a project without UV tiles"); + assert!(h.query_by_label("You can't change UV Tile settings once a project has been created.").is_some()); + click(&mut h, Role::Button, "Cancel"); + + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.uvTiles", &json!({"ts": 0, "enabled": true})).unwrap(); + open_window(&mut h); + assert!(h.query_by_label("Off").is_none()); + assert!(h.query_by_label("1001").is_some(), "the tile list of a UDIM project"); +} + +#[test] +fn preserving_strokes_is_an_import_setting_of_a_mesh_that_is_read() { + let dir = temp_dir("preserve"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + let box_of = |h: &Harness<'_, TextureCraftApp>| h.get_by_role_and_label(Role::CheckBox, "Preserve stroke positions on mesh").accesskit_node().is_disabled(); + open_window(&mut h); + assert!(box_of(&h), "greyed while no mesh is going to be read"); + assert!(h.state().ui.windows.project_config.as_ref().unwrap().preserve, "on by default"); + select(&mut h, &tri); + assert!(!box_of(&h)); + click(&mut h, Role::CheckBox, "Preserve stroke positions on mesh"); + assert!(!h.state().ui.windows.project_config.as_ref().unwrap().preserve); + click(&mut h, Role::Button, "OK"); + assert_eq!(h.state().session.mesh.triangle_count(), 1, "the mesh changed without reprojecting strokes"); +} diff --git a/docs/features.md b/docs/features.md index 93b2f894..8bb3f2ec 100644 --- a/docs/features.md +++ b/docs/features.md @@ -83,7 +83,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA Reimport a changed mesh and your painted strokes stay on the surface. The `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the - file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. + file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted + strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and + shows its UV tiles (read only). - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). From e9b9d43fd9def9f8f4857b569497cd0976f80f3f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 17:09:03 +0100 Subject: [PATCH 20/28] Project Configuration: review fixes for the project settings The UV tile list is read only with a hint to Texture Set Settings (the old Painter note was wrong here). The normal map format is skipped when the project already has it, a mesh already changed is not read again by a retry, and the tests now show strokes moving or staying with the Preserve box. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/project_config.rs | 28 +++-- crates/ui-egui/tests/it/project_config.rs | 139 ++++++++++++++++++++-- docs/features.md | 2 +- 3 files changed, 151 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index f0f76d37..16be9590 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -17,7 +17,8 @@ const SELECT_BUTTON_WIDTH: f32 = 90.0; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { - app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, preserve: true, normal_format: None, confirm: false, project: app.session.project_id }); + app.ui.windows.project_config = + Some(ProjectConfig { mesh: None, reimport: false, preserve: true, normal_format: None, confirm: false, project: app.session.project_id }); } /// `text` with its beginning replaced by an ellipsis until `fits` accepts it (the end of a path @@ -154,16 +155,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", )); ui.add_space(4.0); - // Read only: the tiles are set when the project is created. + // Read only here; the Texture Set Settings panel changes them. ui.label(tr("UV Tile settings (UDIMs)")); if tiles.iter().all(|(_, t)| t.is_none()) { - ui.label(egui::RichText::new(tr("Off")).weak()); + ui.label(egui::RichText::new(tr("No UV tiles")).weak()); } for (name, t) in tiles.iter().filter(|(_, t)| t.is_some()) { let list = t.as_deref().unwrap_or_default(); - ui.label(egui::RichText::new(if tiles.len() > 1 { trf("{set}: {tiles}", &[("set", name), ("tiles", list)]) } else { list.to_string() }).weak()); + ui.label(egui::RichText::new(if tiles.len() > 1 { trf("{set}: {tiles}", &[("set", name), ("tiles", &list)]) } else { list.to_string() }).weak()); } - ui.label(egui::RichText::new(tr("You can't change UV Tile settings once a project has been created.")).small().weak()); + ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak()); ui.add_space(12.0); ui.horizontal(|ui| { @@ -187,15 +188,20 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } // OK closes the window once everything worked; a failure leaves it open, choices kept, with its toast. // The mesh goes first: a project that couldn't change its mesh stays as it was. + let mut mesh_applied = false; let done = ok && { let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); - let mesh_done = match mesh_command(changed.as_deref(), reimport.as_deref(), config.preserve) { + mesh_applied = match mesh_command(changed.as_deref(), reimport.as_deref(), config.preserve) { Some((command, params)) => app.run(command, params).is_some(), None => true, }; - mesh_done - && match config.normal_format { - Some(format) => app.run("textureSet.settings", json!({"normalFormat": if format == NormalFormat::DirectX { "directX" } else { "openGl" }})).is_some(), + // The format is compared with what the project has now: the Texture Set Settings panel may have set it too. + let format = config.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + mesh_applied + && match format { + Some(format) => { + app.run("textureSet.settings", json!({"normalFormat": if format == NormalFormat::DirectX { "directX" } else { "openGl" }})).is_some() + } None => true, } }; @@ -204,6 +210,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if let Some(stored) = app.ui.windows.project_config.as_mut() { // Keep the choices made now; the file answer arrives later through the stored value. (stored.reimport, stored.preserve, stored.normal_format, stored.confirm) = (config.reimport, config.preserve, config.normal_format, false); + // A mesh already changed is not read again by a retry of the rest. + if ok && mesh_applied { + (stored.mesh, stored.reimport) = (None, false); + } } } diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 588c25e7..f3b5a584 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -13,6 +13,8 @@ use texturecraft_ui_egui::file_dialogs::{Answer, Request}; const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"; +/// The format combo's tooltip, which is its accessible label. +const FORMAT_HINT: &str = "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export"; const TITLE: &str = "Project configuration"; /// A new folder for one test, removed when the test ends (also when it fails). @@ -50,6 +52,20 @@ fn app_on_a_quad(dir: &std::path::Path) -> Harness<'static, TextureCraftApp> { h } +/// The widget of `role` and `label` inside the window, which sits at the middle of the screen +/// (a panel of the dock may show the same text). +fn in_window<'h>(h: &'h Harness<'_, TextureCraftApp>, role: Role, label: &'h str) -> egui_kittest::Node<'h> { + let middle = egui::pos2(800.0, 480.0); + h.get_all_by_role_and_label(role, label) + .min_by(|a, b| a.rect().center().distance(middle).total_cmp(&b.rect().center().distance(middle))) + .expect("the widget in the window") +} + +fn click_in_window(h: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + in_window(h, role, label).click(); + h.run_steps(3); +} + fn open_window(h: &mut Harness<'_, TextureCraftApp>) { let ctx = h.ctx.clone(); texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.projectConfig"); @@ -288,14 +304,14 @@ fn the_normal_map_format_changes_on_ok_and_shows_in_the_texture_set_panel() { let dir = temp_dir("normal-format"); let mut h = app_on_a_quad(&dir); open_window(&mut h); - click(&mut h, Role::ComboBox, "OpenGL"); - click(&mut h, Role::Button, "DirectX"); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); assert_eq!(project_normal_format(&h), NormalFormat::OpenGl, "nothing changes before OK"); click(&mut h, Role::Button, "OK"); assert_eq!(project_normal_format(&h), NormalFormat::DirectX); h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::TextureSetSettings); h.run_steps(3); - assert!(h.query_by_label("DirectX").is_some(), "the Texture Set Settings panel shows the project's format"); + assert!(h.query_all_by_value("DirectX").next().is_some(), "the Texture Set Settings panel shows the project's format"); // One undo step puts it back h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); h.run_steps(3); @@ -308,8 +324,8 @@ fn cancel_discards_a_normal_map_format() { let dir = temp_dir("normal-format-cancel"); let mut h = app_on_a_quad(&dir); open_window(&mut h); - click(&mut h, Role::ComboBox, "OpenGL"); - click(&mut h, Role::Button, "DirectX"); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); click(&mut h, Role::Button, "Cancel"); assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); } @@ -320,13 +336,13 @@ fn uv_tiles_are_shown_read_only() { let mut h = app_on_a_quad(&dir); open_window(&mut h); assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some()); - assert!(h.query_by_label("Off").is_some(), "a project without UV tiles"); - assert!(h.query_by_label("You can't change UV Tile settings once a project has been created.").is_some()); + assert!(h.query_by_label("No UV tiles").is_some(), "a project without UV tiles"); + assert!(h.query_by_label("Change them in Texture Set Settings").is_some()); click(&mut h, Role::Button, "Cancel"); texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.uvTiles", &json!({"ts": 0, "enabled": true})).unwrap(); open_window(&mut h); - assert!(h.query_by_label("Off").is_none()); + assert!(h.query_by_label("No UV tiles").is_none()); assert!(h.query_by_label("1001").is_some(), "the tile list of a UDIM project"); } @@ -347,3 +363,110 @@ fn preserving_strokes_is_an_import_setting_of_a_mesh_that_is_read() { click(&mut h, Role::Button, "OK"); assert_eq!(h.state().session.mesh.triangle_count(), 1, "the mesh changed without reprojecting strokes"); } + +/// The same quad with its UVs mirrored in u. +const MIRRORED_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1 0\nvt 0 0\nvt 0 1\nvt 1 1\nf 1/1 2/2 3/3 4/4\n"; + +/// Paints the half of the quad with the larger x on its first layer. +fn paint_the_right_half(h: &mut Harness<'_, TextureCraftApp>) -> texturecraft_engine::core::LayerId { + use texturecraft_engine::core::Channel; + let session = &mut h.state_mut().session; + let id = session.doc.project.texture_sets[0].stack[0]; + let (size, cells) = { + let cache = &session.caches[0]; + let xs: Vec<(usize, f32)> = + (0..cache.size.0 as usize * cache.size.1 as usize).filter_map(|i| cache.gbuf.surface(&session.mesh, i).map(|p| (i, p.pos.x))).collect(); + let (low, high) = xs.iter().fold((f32::MAX, f32::MIN), |(l, h), (_, x)| (l.min(*x), h.max(*x))); + (cache.size, xs.into_iter().filter(|(_, x)| *x > (low + high) / 2.0).map(|(i, _)| i).collect::>()) + }; + let image = session.doc.pixels.layer_mut(id, Channel::BaseColor, size); + for i in cells { + image.set(i as u32 % size.0, i as u32 / size.0, &[65535, 0, 0, 65535]); + } + id +} + +/// Painted texels on the right and on the left half of the quad's surface, away from the middle. +fn painted_halves(h: &Harness<'_, TextureCraftApp>, id: texturecraft_engine::core::LayerId) -> (usize, usize) { + use texturecraft_engine::core::Channel; + let session = &h.state().session; + let cache = &session.caches[0]; + let image = session.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + let texels: Vec<(u32, u32, f32)> = (0..cache.size.0 * cache.size.1) + .filter_map(|i| cache.gbuf.surface(&session.mesh, i as usize).map(|p| (i % cache.size.0, i / cache.size.0, p.pos.x))) + .collect(); + let (low, high) = texels.iter().fold((f32::MAX, f32::MIN), |(l, h), t| (l.min(t.2), h.max(t.2))); + let (middle, margin) = ((low + high) / 2.0, (high - low) * 0.05); + let painted = |x: u32, y: u32| image.get(x, y)[3] > 32768; + let right = texels.iter().filter(|t| t.2 > middle + margin && painted(t.0, t.1)).count(); + let left = texels.iter().filter(|t| t.2 < middle - margin && painted(t.0, t.1)).count(); + (right, left) +} + +/// OK on a mirrored-UV mesh with the Preserve box as given; returns the painted (right, left) texels afterwards. +fn painted_after_changing_to_mirrored_uvs(test: &str, preserve: bool) -> ((usize, usize), (usize, usize)) { + let dir = temp_dir(test); + let mut h = app_on_a_quad(&dir); + let mirrored = dir.join("mirrored.obj"); + std::fs::write(&mirrored, MIRRORED_QUAD).unwrap(); + let id = paint_the_right_half(&mut h); + let before = painted_halves(&h, id); + open_window(&mut h); + select(&mut h, &mirrored); + if !preserve { + click(&mut h, Role::CheckBox, "Preserve stroke positions on mesh"); + } + click(&mut h, Role::Button, "OK"); + assert!(!window_is_open(&h)); + (before, painted_halves(&h, id)) +} + +#[test] +fn preserve_on_moves_the_strokes_with_the_surface() { + let (before, after) = painted_after_changing_to_mirrored_uvs("preserve-on", true); + assert!(before.0 > 2000 && before.1 == 0, "painted on the right half: {before:?}"); + assert!(after.0 > 2000 && after.1 < 200, "still on the right half of the surface: {after:?}"); +} + +#[test] +fn preserve_off_leaves_the_strokes_in_the_uv_layout() { + let (_, after) = painted_after_changing_to_mirrored_uvs("preserve-off", false); + assert!(after.1 > 2000 && after.0 < 200, "the paint stayed where it was in UV space, now on the left half: {after:?}"); +} + +#[test] +fn a_mesh_and_a_format_change_in_one_ok() { + use texturecraft_engine::core::NormalFormat; + let dir = temp_dir("both"); + let mut h = app_on_a_quad(&dir); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, TRIANGLE).unwrap(); + open_window(&mut h); + select(&mut h, &tri); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + click(&mut h, Role::Button, "OK"); + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.mesh.triangle_count(), 1); + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + h.run_steps(3); + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl, "the format is one undo step"); + assert_eq!(h.state().session.mesh.triangle_count(), 1, "and the mesh stays"); +} + +#[test] +fn a_format_the_project_already_has_is_not_set_again() { + use texturecraft_engine::core::NormalFormat; + let dir = temp_dir("same-format"); + let mut h = app_on_a_quad(&dir); + open_window(&mut h); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + // The Texture Set Settings panel sets it meanwhile + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap(); + let steps = h.state().session.history_labels().len(); + click(&mut h, Role::Button, "OK"); + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); + assert_eq!(h.state().session.history_labels().len(), steps, "no extra undo step"); +} diff --git a/docs/features.md b/docs/features.md index 8bb3f2ec..02f09251 100644 --- a/docs/features.md +++ b/docs/features.md @@ -85,7 +85,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and - shows its UV tiles (read only). + lists its UV tiles (read only; Texture Set Settings changes them). - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). From 979d57699874f857ad08dbb620efbb598b3dabeb Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:36:03 +0100 Subject: [PATCH 21/28] Project Configuration: an open dropdown takes Escape and Enter first; a reimport of a deleted file reports and keeps the window open --- crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/project_config.rs | 21 ++++++--- crates/ui-egui/tests/it/project_config.rs | 55 +++++++++++++++++++++++ 3 files changed, 72 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4be1e51b..3401b409 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -372,7 +372,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.ui.windows.project_config.is_some() { // Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched #[cfg(not(target_arch = "wasm32"))] - crate::project_config::keys_in(app, input, nothing_focused); + crate::project_config::keys_in(app, input, nothing_focused, popup_open); } else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 16be9590..3e19579f 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -44,8 +44,12 @@ fn elide_start(text: &str, fits: impl Fn(&str) -> bool) -> String { /// The keys of the open window, read in `menus::shortcuts` before any panel draws: Escape closes /// it (and goes no further, so it doesn't cancel a stroke), Enter confirms it unless a text field -/// or button had the keyboard (`nothing_focused`), whose Enter belongs to it. -pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool) { +/// or button had the keyboard (`nothing_focused`), whose Enter belongs to it. An open dropdown +/// (`popup_open`) takes both keys first: Escape closes only it, Enter doesn't press OK behind it. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool, popup_open: bool) { + if popup_open { + return; + } let escape = input.consume_key(Modifiers::NONE, Key::Escape); let enter = input.consume_key(Modifiers::NONE, Key::Enter); if escape { @@ -191,9 +195,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut mesh_applied = false; let done = ok && { let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); - mesh_applied = match mesh_command(changed.as_deref(), reimport.as_deref(), config.preserve) { - Some((command, params)) => app.run(command, params).is_some(), - None => true, + mesh_applied = if config.reimport && changed.is_none() && reimport.is_none() { + // The file went away after the box was ticked: say so and stay open (the tick is dropped, so a second OK applies the rest). + app.toast(tr("File not found"), true); + config.reimport = false; + false + } else { + match mesh_command(changed.as_deref(), reimport.as_deref(), config.preserve) { + Some((command, params)) => app.run(command, params).is_some(), + None => true, + } }; // The format is compared with what the project has now: the Texture Set Settings panel may have set it too. let format = config.normal_format.filter(|format| *format != app.session.doc.project.normal_format); diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index f3b5a584..c7012a81 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -208,6 +208,61 @@ fn escape_closes_the_window_and_leaves_a_stroke_alone() { assert!(h.state().session.stroke_active(), "Escape went to the window, not to the stroke"); } +#[test] +fn escape_with_the_dropdown_open_closes_only_the_dropdown() { + let dir = temp_dir("escape-dropdown"); + let mut h = app_on_a_quad(&dir); + open_window(&mut h); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + assert!(egui::Popup::is_any_open(&h.ctx), "the dropdown is open"); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(!egui::Popup::is_any_open(&h.ctx), "Escape closed the dropdown"); + assert!(window_is_open(&h), "and left the window"); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(!window_is_open(&h), "the next Escape closes the window"); +} + +#[test] +fn enter_with_the_dropdown_open_does_not_press_ok() { + let dir = temp_dir("enter-dropdown"); + let mut h = app_on_a_quad(&dir); + std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap(); + open_window(&mut h); + h.state_mut().ui.windows.project_config.as_mut().unwrap().reimport = true; + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + // Nothing focused, as the shortcut handler needs for Enter to mean OK + h.ctx.memory_mut(|m| { + if let Some(id) = m.focused() { + m.surrender_focus(id); + } + }); + h.run_steps(1); + assert!(egui::Popup::is_any_open(&h.ctx), "the dropdown is still open"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(window_is_open(&h), "Enter did not press OK behind the dropdown"); + assert_eq!(h.state().session.mesh.triangle_count(), 2, "nothing was applied"); +} + +#[test] +fn ok_after_the_ticked_file_went_missing_reports_it_and_stays_open() { + let dir = temp_dir("ticked-then-missing"); + let mut h = app_on_a_quad(&dir); + open_window(&mut h); + click_in_window(&mut h, Role::CheckBox, "Reimport mesh"); + assert!(own_tick(&h)); + std::fs::remove_file(dir.join("quad.obj")).unwrap(); + click(&mut h, Role::Button, "OK"); + assert!(window_is_open(&h), "the window stays open"); + assert!(h.state().toasts.iter().any(|t| t.error && t.text == "File not found"), "the error shows as a toast"); + assert!(!own_tick(&h), "the tick that can't be applied is dropped"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + click(&mut h, Role::Button, "OK"); + assert!(!window_is_open(&h), "a second OK has nothing left to read"); +} + #[test] fn enter_confirms_but_not_a_text_fields_enter() { let dir = temp_dir("enter"); From e7a3b613976b803f8955c2e8d9c329b8a5465537 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:38:00 +0100 Subject: [PATCH 22/28] Project Configuration tests: check that nothing has the keyboard before Enter, and let the layout settle before OK --- crates/ui-egui/tests/it/project_config.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index c7012a81..1a092cd6 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -239,6 +239,7 @@ fn enter_with_the_dropdown_open_does_not_press_ok() { } }); h.run_steps(1); + assert!(h.ctx.memory(|m| m.focused().is_none()), "nothing has the keyboard"); assert!(egui::Popup::is_any_open(&h.ctx), "the dropdown is still open"); h.key_press(egui::Key::Enter); h.run_steps(3); @@ -254,6 +255,7 @@ fn ok_after_the_ticked_file_went_missing_reports_it_and_stays_open() { click_in_window(&mut h, Role::CheckBox, "Reimport mesh"); assert!(own_tick(&h)); std::fs::remove_file(dir.join("quad.obj")).unwrap(); + h.run_steps(2); click(&mut h, Role::Button, "OK"); assert!(window_is_open(&h), "the window stays open"); assert!(h.state().toasts.iter().any(|t| t.error && t.text == "File not found"), "the error shows as a toast"); From 37943821ec49ea8e1dd792ed3a3dc03ed108d1d6 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Tue, 10 Nov 2026 23:06:56 +0100 Subject: [PATCH 23/28] fix(ui): retain pen pressure across frames without touch updates (#287) --- crates/ui-egui/src/viewport.rs | 10 +++++++++- crates/ui-egui/tests/it/pen_pressure.rs | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 6fd29db0..2bb9347c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1730,7 +1730,15 @@ fn pen_pressure(ui: &Ui) -> f32 { ui.data_mut(|d| d.remove_temp::(id)); 1.0 } - _ => 1.0, + _ => { + let active = ui.input(|i| i.pointer.primary_down() || i.pointer.any_down() || i.pointer.primary_released() || i.pointer.any_released()); + if active { + ui.data(|d| d.get_temp::(id)).unwrap_or(1.0) + } else { + ui.data_mut(|d| d.remove_temp::(id)); + 1.0 + } + } } } diff --git a/crates/ui-egui/tests/it/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs index f2c1fcee..3e0e74c7 100644 --- a/crates/ui-egui/tests/it/pen_pressure.rs +++ b/crates/ui-egui/tests/it/pen_pressure.rs @@ -80,3 +80,18 @@ fn a_light_pen_tap_paints_a_small_dab() { assert!(mouse > 1.0, "the mouse click painted: {mouse}"); assert!(light > 0.0 && light < mouse * 0.25, "the tap keeps its contact pressure: {light} vs {mouse}"); } + +#[test] +fn frames_omitting_touch_events_during_stroke_do_not_spike_pressure() { + let to = pos2(800.0, 500.0); + let intermittent = paint_2d(|h| { + frame(h, Some((TouchPhase::Start, Some(0.2))), FROM, Some(true)); + for k in 1..=8 { + let pen = if k % 2 == 0 { Some((TouchPhase::Move, Some(0.2))) } else { None }; + frame(h, pen, FROM + (to - FROM) * (k as f32 / 8.0), None); + } + frame(h, Some((TouchPhase::End, Some(0.2))), to, Some(false)); + }); + let mouse = stroke(None); + assert!(intermittent > 0.0 && intermittent < mouse * 0.5, "intermittent frames without touch keep light pressure: {intermittent} vs {mouse}"); +} From 49b17f2f8b5f94f85bdd9a819f2a9c54d3fea88e Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Wed, 11 Nov 2026 20:32:20 +0100 Subject: [PATCH 24/28] fix(ui): clear cached pen pressure on a new non-touch press (#287) --- crates/ui-egui/src/viewport.rs | 10 ++++++---- crates/ui-egui/tests/it/pen_pressure.rs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 2bb9347c..a5bac683 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1725,14 +1725,16 @@ fn pen_pressure(ui: &Ui) -> f32 { } // A pen lifts with no pressure, so keep its contact pressure for a tap Some((egui::TouchPhase::End, None)) => ui.data(|d| d.get_temp(id)).unwrap_or(1.0), - // A finger must not inherit an earlier pen's pressure - Some((egui::TouchPhase::Start, None)) => { + // A touch without pressure (a finger) must not inherit an earlier pen's. + Some((egui::TouchPhase::Start | egui::TouchPhase::Cancel, None)) => { ui.data_mut(|d| d.remove_temp::(id)); 1.0 } _ => { - let active = ui.input(|i| i.pointer.primary_down() || i.pointer.any_down() || i.pointer.primary_released() || i.pointer.any_released()); - if active { + let (pressed, active) = ui.input(|i| { + (i.pointer.any_pressed(), i.pointer.primary_down() || i.pointer.any_down() || i.pointer.primary_released() || i.pointer.any_released()) + }); + if active && !pressed { ui.data(|d| d.get_temp::(id)).unwrap_or(1.0) } else { ui.data_mut(|d| d.remove_temp::(id)); diff --git a/crates/ui-egui/tests/it/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs index 3e0e74c7..e9474fc9 100644 --- a/crates/ui-egui/tests/it/pen_pressure.rs +++ b/crates/ui-egui/tests/it/pen_pressure.rs @@ -95,3 +95,20 @@ fn frames_omitting_touch_events_during_stroke_do_not_spike_pressure() { let mouse = stroke(None); assert!(intermittent > 0.0 && intermittent < mouse * 0.5, "intermittent frames without touch keep light pressure: {intermittent} vs {mouse}"); } + +#[test] +fn mouse_stroke_immediately_after_pen_release_uses_full_pressure() { + let to = pos2(800.0, 500.0); + let baseline = stroke(None); + let immediate_mouse = paint_2d(|h| { + let tap_pos = pos2(600.0, 680.0); + frame(h, Some((TouchPhase::Start, Some(0.2))), tap_pos, Some(true)); + frame(h, Some((TouchPhase::End, None)), tap_pos, Some(false)); + frame(h, None, FROM, Some(true)); + for k in 1..=8 { + frame(h, None, FROM + (to - FROM) * (k as f32 / 8.0), None); + } + frame(h, None, to, Some(false)); + }); + assert!(immediate_mouse > baseline * 0.9, "mouse stroke after pen release keeps full pressure: {immediate_mouse} vs {baseline}"); +} From 54f101a8dffaac62e6ae3903269fcf8a10ba3e17 Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Mon, 16 Nov 2026 10:52:43 +0100 Subject: [PATCH 25/28] fix(ui): tie touch-free pressure cache to primary gesture and test secondary button press (#287) --- crates/ui-egui/src/viewport.rs | 8 +++----- crates/ui-egui/tests/it/pen_pressure.rs | 27 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a5bac683..2026dbee 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1709,7 +1709,7 @@ pub(crate) fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, position: /// windowing layer reports it for Windows Ink pens, and in the browser for pens that send touch /// events (tablets and phones); other pens come through as a mouse. /// shortcut: the windowing layer reports no pen tilt, so tilt can't drive the brush angle yet. -fn pen_pressure(ui: &Ui) -> f32 { +pub fn pen_pressure(ui: &Ui) -> f32 { let id = egui::Id::unique("pen_pressure"); let touch = ui.input(|i| { i.raw.events.iter().rev().find_map(|e| match e { @@ -1731,10 +1731,8 @@ fn pen_pressure(ui: &Ui) -> f32 { 1.0 } _ => { - let (pressed, active) = ui.input(|i| { - (i.pointer.any_pressed(), i.pointer.primary_down() || i.pointer.any_down() || i.pointer.primary_released() || i.pointer.any_released()) - }); - if active && !pressed { + let (primary_pressed, active) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_down() || i.pointer.primary_released())); + if active && !primary_pressed { ui.data(|d| d.get_temp::(id)).unwrap_or(1.0) } else { ui.data_mut(|d| d.remove_temp::(id)); diff --git a/crates/ui-egui/tests/it/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs index e9474fc9..6cc4493c 100644 --- a/crates/ui-egui/tests/it/pen_pressure.rs +++ b/crates/ui-egui/tests/it/pen_pressure.rs @@ -112,3 +112,30 @@ fn mouse_stroke_immediately_after_pen_release_uses_full_pressure() { }); assert!(immediate_mouse > baseline * 0.9, "mouse stroke after pen release keeps full pressure: {immediate_mouse} vs {baseline}"); } + +#[test] +fn secondary_pressed_during_active_primary_pen_stroke_retains_light_pressure() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(2); + + let ctx = h.ctx.clone(); + let mut raw = egui::RawInput::default(); + raw.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Start, pos: pos2(100.0, 100.0), force: Some(0.2) }); + raw.events.push(Event::PointerButton { pos: pos2(100.0, 100.0), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + let _ = ctx.run_ui(raw, |ctx| { + egui::CentralPanel::default().show(ctx, |ui| { + let p = texturecraft_ui_egui::viewport::pen_pressure(ui); + assert!((p - 0.2).abs() < 1e-4, "initial touch records 0.2: {p}"); + }); + }); + + let mut raw2 = egui::RawInput::default(); + raw2.events.push(Event::PointerButton { pos: pos2(110.0, 100.0), button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + let _ = ctx.run_ui(raw2, |ctx| { + egui::CentralPanel::default().show(ctx, |ui| { + let p = texturecraft_ui_egui::viewport::pen_pressure(ui); + assert!((p - 0.2).abs() < 1e-4, "secondary pressed must not clear the cached pressure to 1.0: {p}"); + }); + }); +} From 92a9c515220494ac771c8a3b813a9e556fe75442 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 22:13:30 +0100 Subject: [PATCH 26/28] Project Configuration: info icons on every setting and a note that a mesh change recomputes all channels --- crates/ui-egui/src/dock.rs | 2 +- crates/ui-egui/src/project_config.rs | 62 ++++++++++++++++------- crates/ui-egui/tests/it/project_config.rs | 19 +++++++ 3 files changed, 64 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 94b3b11e..88d6b728 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1635,7 +1635,7 @@ fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut } /// A dim info icon explaining a setting on hover -fn info_icon(ui: &mut Ui, text: &str) { +pub(crate) fn info_icon(ui: &mut Ui, text: &str) { ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text); } diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 3e19579f..dd579f6f 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -6,14 +6,17 @@ use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; use crate::TextureCraftApp; +use crate::dock::info_icon; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{tr, trf}; use crate::state::ProjectConfig; use crate::theme::caption; -use crate::widgets::{combo, primary_button}; +use crate::widgets::primary_button; -/// Room for the Select... button beside the path. -const SELECT_BUTTON_WIDTH: f32 = 90.0; +/// Room for the Select... button and its info icon beside the path. +const SELECT_BUTTON_WIDTH: f32 = 150.0; +/// Room for an info icon at the end of a row. +const INFO_WIDTH: f32 = 28.0; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { @@ -109,6 +112,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add_space(4.0); ui.horizontal(|ui| { ui.label(tr("3D mesh")); + info_icon(ui, tr("The mesh file the project is built on. Hover the path to see it in full.")); let shown = changed.clone().unwrap_or_else(|| named.clone()); let font = egui::TextStyle::Body.resolve(ui.style()); let max = (ui.available_width() - SELECT_BUTTON_WIDTH).max(60.0); @@ -119,6 +123,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(elide_start(&shown, measure)).on_hover_text(&shown); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("Choose another mesh file for the project. It is read when you press OK.")); select = ui.button(tr("Select...")).clicked(); }); }); @@ -130,10 +135,15 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // Without a file on disk there is nothing to read again. let mut reimport = config.reimport || changed.is_some(); let free = changed.is_none() && readable; - let tick = ui.add_enabled(free, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))); + let tick = ui + .horizontal(|ui| { + let tick = ui.add_enabled(free, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))); + info_icon(ui, tr("Read the mesh file again, keeping the layers and painted strokes")); + tick + }) + .inner; if free { config.reimport = reimport; - tick.on_hover_text(tr("Read the mesh file again, keeping the layers and painted strokes")); } else if changed.is_none() { tick.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); } @@ -141,26 +151,40 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(caption(tr("Import settings"))); // Only a mesh that is going to be read has settings to apply. let importing = changed.is_some() || (config.reimport && readable); - ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))) - .on_hover_text(tr("Painted strokes follow the surface when the new mesh's UVs differ")); + ui.horizontal(|ui| { + ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))); + info_icon(ui, tr("Painted strokes follow the surface when the new mesh's UVs differ")); + }); ui.add_space(12.0); ui.label(caption(tr("PROJECT SETTINGS"))); ui.add_space(4.0); let shown_format = config.normal_format.unwrap_or(normal_format); - combo(ui, tr("Normal map format"), format_name(shown_format), |ui| { - for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { - if ui.selectable_label(format == shown_format, format_name(format)).clicked() { - config.normal_format = (format != normal_format).then_some(format); - } - } - }) - .on_hover_text(tr( - "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", - )); + ui.horizontal(|ui| { + ui.label(tr("Normal map format")); + egui::ComboBox::from_id_salt(tr("Normal map format")) + .width((ui.available_width() - INFO_WIDTH).max(60.0)) + .wrap_mode(egui::TextWrapMode::Truncate) + .selected_text(format_name(shown_format)) + .show_ui(ui, |ui| { + for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { + if ui.selectable_label(format == shown_format, format_name(format)).clicked() { + config.normal_format = (format != normal_format).then_some(format); + } + } + }) + .response + .on_hover_text(tr( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + )); + info_icon(ui, tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")); + }); ui.add_space(4.0); // Read only here; the Texture Set Settings panel changes them. - ui.label(tr("UV Tile settings (UDIMs)")); + ui.horizontal(|ui| { + ui.label(tr("UV Tile settings (UDIMs)")); + info_icon(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings.")); + }); if tiles.iter().all(|(_, t)| t.is_none()) { ui.label(egui::RichText::new(tr("No UV tiles")).weak()); } @@ -171,6 +195,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak()); ui.add_space(12.0); + ui.label(egui::RichText::new(tr("Choosing or reimporting a mesh recomputes all channels.")).small().weak()); + ui.add_space(4.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ok |= ui.add(primary_button(ui, tr("OK"))).clicked(); diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 1a092cd6..1f039859 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -110,6 +110,25 @@ fn the_menu_opens_the_window() { assert!(h.state().ui.rail_panel.is_none(), "the Display panel stays where it was"); } +#[test] +fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() { + let dir = temp_dir("info"); + let mut h = app_on_a_quad(&dir); + open_window(&mut h); + assert!(h.query_by_label("Choosing or reimporting a mesh recomputes all channels.").is_some(), "the note above the buttons"); + let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect(); + assert_eq!(icons.len(), 6, "mesh path, Select, Reimport mesh, Preserve strokes, Normal map format, UV tiles"); + let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."; + assert!(h.query_by_label(tip).is_none(), "no tooltip before hovering"); + // The icons sit in the order of the window's rows: the format one is the fifth from the top. + let mut centers: Vec<_> = icons.iter().map(|n| n.rect().center()).collect(); + centers.sort_by(|a, b| a.y.total_cmp(&b.y)); + let format_center = centers[4]; + h.hover_at(format_center); + h.run_steps(30); + assert!(h.query_by_label(tip).is_some(), "hovering the normal map format icon explains it"); +} + #[test] fn another_file_shows_its_path_and_ticks_reimport() { let dir = temp_dir("select"); From c34022c53fb3dfe942d2d66e534f4452658afa12 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 17 Nov 2026 06:58:50 +0000 Subject: [PATCH 27/28] Auto: Recover pen pressure through unforced touch moves Recover an earlier forced sample from the same contact when the latest touch event is an unforced Move. Stop recovery at a completed contact and add press-frame and contact-boundary regressions. --- crates/ui-egui/src/viewport.rs | 12 ++++++-- crates/ui-egui/tests/it/pen_pressure.rs | 41 +++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index d8a2be64..d7030d9c 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1717,21 +1717,27 @@ pub fn pen_pressure(ui: &Ui) -> f32 { egui::Event::Touch { device_id, id: touch_id, phase, force, .. } => { let mut contact_force = force.filter(|pressure| pressure.is_finite()); let mut effective_phase = *phase; - if contact_force.is_none() && *phase == egui::TouchPhase::End { - // Recover a same-frame pen sample or pressure-free touch start + if contact_force.is_none() && matches!(*phase, egui::TouchPhase::Move | egui::TouchPhase::End) { + // Recover pressure only from this contact, including an unforced press-frame move for previous_event in events[..index].iter().rev() { if let egui::Event::Touch { device_id: previous_device_id, id: previous_touch_id, phase: previous_phase, force: previous_force, .. } = previous_event && previous_device_id == device_id && previous_touch_id == touch_id { + // A completed contact cannot supply pressure to a reused touch ID + if matches!(previous_phase, egui::TouchPhase::End | egui::TouchPhase::Cancel) { + effective_phase = egui::TouchPhase::Cancel; + break; + } + contact_force = previous_force.filter(|pressure| pressure.is_finite()); if contact_force.is_none() && *previous_phase == egui::TouchPhase::Start { effective_phase = egui::TouchPhase::Start; break; } - if contact_force.is_some() || matches!(previous_phase, egui::TouchPhase::End | egui::TouchPhase::Cancel) { + if contact_force.is_some() { break; } } diff --git a/crates/ui-egui/tests/it/pen_pressure.rs b/crates/ui-egui/tests/it/pen_pressure.rs index 778f0b5b..36b67d2b 100644 --- a/crates/ui-egui/tests/it/pen_pressure.rs +++ b/crates/ui-egui/tests/it/pen_pressure.rs @@ -164,6 +164,47 @@ fn touch_start_and_unforced_end_in_one_frame_keep_contact_pressure() { .drop_without_applying_deltas(); } +#[test] +fn unforced_move_on_press_frame_keeps_same_contact_pressure() { + let context = egui::Context::default(); + let position = pos2(100.0, 100.0); + let mut press_input = egui::RawInput::default(); + press_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Start, pos: position, force: Some(0.2) }); + press_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: position, force: None }); + press_input.events.push(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + + context + .run_ui(press_input, |ui| { + let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui); + assert!((pressure - 0.2).abs() < 1e-4, "press frame keeps the same contact's pressure: {pressure}"); + }) + .drop_without_applying_deltas(); + + context + .run_ui(egui::RawInput::default(), |ui| { + let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui); + assert!((pressure - 0.2).abs() < 1e-4, "touch-free frame keeps the recovered pressure: {pressure}"); + }) + .drop_without_applying_deltas(); +} + +#[test] +fn unforced_move_does_not_recover_a_completed_contact() { + let context = egui::Context::default(); + let position = pos2(100.0, 100.0); + let mut input = egui::RawInput::default(); + input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::End, pos: position, force: Some(0.2) }); + input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: position, force: None }); + input.events.push(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + + context + .run_ui(input, |ui| { + let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui); + assert!((pressure - 1.0).abs() < 1e-4, "a completed contact cannot supply pressure to the later move: {pressure}"); + }) + .drop_without_applying_deltas(); +} + #[test] fn unforced_touch_start_and_end_in_one_frame_clear_old_pen_pressure() { let context = egui::Context::default(); From 037bd206a8c4281bb00980d0e41c4c6887ddcdf1 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 17 Nov 2026 07:06:07 +0000 Subject: [PATCH 28/28] Auto: Keep Project Configuration actions reachable on short screens Bound the dialog to the viewport and enable vertical scrolling. Add a 30-set regression that verifies OK and Cancel remain reachable. --- crates/ui-egui/src/project_config.rs | 9 +++++++- crates/ui-egui/tests/it/project_config.rs | 28 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 9f0ff589..80942b1b 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -23,6 +23,8 @@ const INFO_WIDTH_POINTS: f32 = 28.0; const MIN_FIELD_WIDTH_POINTS: f32 = 60.0; /// Initial width of the configuration dialog. const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 460.0; +/// Leave space around the centered dialog on short viewports. +const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { @@ -133,7 +135,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(DEFAULT_DIALOG_WIDTH_POINTS).show(ctx, |ui| { + let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open) + .default_width(DEFAULT_DIALOG_WIDTH_POINTS) + .max_height((ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS).max(0.0)) + .vscroll(true); + + dialog.show(ctx, |ui| { // Keep the project sections in the order users expect ui.label(caption(tr("3D MESH"))); ui.add_space(4.0); diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 321e2b0c..969c5e5c 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -98,6 +98,34 @@ fn the_menu_opens_the_window() { assert!(h.state().ui.rail_panel.is_none(), "the Display panel stays where it was"); } +#[test] +fn many_texture_sets_keep_dialog_actions_reachable_in_a_short_viewport() { + let dir = temp_dir("many-tiles"); + let mut h = app_on_a_quad(&dir); + let template = h.state().session.doc.project.texture_sets[0].clone(); + h.state_mut().session.doc.project.texture_sets = (0..30) + .map(|index| { + let mut set = template.clone(); + set.name = format!("Set {index}"); + set.uv_tiles = vec![1001]; + set + }) + .collect(); + h.set_size(egui::vec2(800.0, 480.0)); + + open_window(&mut h); + h.get_by_role_and_label(Role::Button, "Cancel").scroll_to_me(); + h.run_steps(3); + + let ok = h.get_by_role_and_label(Role::Button, "OK"); + assert!(ok.rect().top() >= 0.0 && ok.rect().bottom() <= 480.0, "OK must be inside the viewport after scrolling: {:?}", ok.rect()); + let cancel = h.get_by_role_and_label(Role::Button, "Cancel"); + assert!(cancel.rect().top() >= 0.0 && cancel.rect().bottom() <= 480.0, "Cancel must be inside the viewport after scrolling: {:?}", cancel.rect()); + cancel.click(); + h.run_steps(3); + assert!(!window_is_open(&h)); +} + #[test] fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() { let dir = temp_dir("info");