From e5a8f2ed78e31a5e1abfa14ba6676e4edf9d2e02 Mon Sep 17 00:00:00 2001 From: Justin John Date: Mon, 2 Nov 2026 12:43:10 +0530 Subject: [PATCH] Cache the paths below an edited path; test the path list UI Editing a path repaints only it and the paths above it: the sublayer's pixels after the paths below are cached (keyed by those paths, the mesh and the texture size) and reused while the edit goes on. A unit test checks the cached repaint matches painting every path. Adds a UI test for the path rows (pick to edit, pick again to finish, remove) and a properties-paths frame to the offscreen window snapshots. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/path_tool.rs | 97 ++++++++++++++++++++++++++-- crates/engine/src/session.rs | 3 + crates/ui-egui/tests/path_list.rs | 38 +++++++++++ crates/ui-egui/tests/ui_snapshots.rs | 15 +++++ 4 files changed, 146 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/tests/path_list.rs diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index ca0de3f2..4ed8fdba 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -55,6 +55,19 @@ impl PathState { } } +/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and +/// texture size they were painted for. +#[derive(Clone)] +// shortcut: the key doesn't cover image resources a path's brush alpha reads; replacing one +// leaves cached paths with the old alpha until a path below the edited one changes. +pub(crate) struct PathCache { + eid: LayerId, + key: (u64, Option<(u32, u32)>), + below: Vec, + mask: Option, + layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, +} + /// What a stored path is painted with ([`PathShape::paint`]). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct PathPaint { @@ -181,7 +194,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result { { shapes.remove(index); } - s.render_paths(eid) + s.render_paths(eid, index) })?; if s.tool.path.editing.is_some_and(|(e, _)| e == eid) { s.stop_path_edit(); @@ -339,18 +352,32 @@ impl Session { }, _ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))), }; - let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({})); + let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({})); out["effect"] = json!(eid.0); out["index"] = json!(index); Ok(out) } - /// Repaint path sublayer `eid` from scratch with its stored paths, bottom to top. Runs - /// inside the caller's undo step. - fn render_paths(&mut self, eid: LayerId) -> Result> { + /// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before + /// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are + /// cached for the next repaint otherwise, so editing a path repaints it and the paths above + /// only. Runs inside the caller's undo step. Returns each painted path's report (null for + /// the cached ones). + fn render_paths(&mut self, eid: LayerId, from: usize) -> Result> { let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec(); + let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size)); self.doc.pixels.masks.remove(&eid); self.doc.pixels.layers.retain(|(id, _), _| *id != eid); + let start = match &self.path_cache { + Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => { + if let Some(m) = &c.mask { + self.doc.pixels.masks.insert(eid, m.clone()); + } + self.doc.pixels.layers.extend(c.layers.iter().cloned()); + c.below.len() + } + _ => 0, + }; // Each path goes through the regular stroke and fill code with its own settings; their // own history entries are dropped (the caller records one step). let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); @@ -359,11 +386,27 @@ impl Session { self.quick_mask.editing = false; self.tool.tool = Tool::Path; self.painting_paths = true; - let out = shapes.iter().map(|sh| self.paint_shape(sh)).collect(); + let mut out = vec![Value::Null; start]; + let mut result = Ok(()); + for i in start..=shapes.len() { + if i == from.min(shapes.len()) && i > start { + let pixels = &self.doc.pixels; + let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); + self.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); + } + let Some(sh) = shapes.get(i) else { break }; + match self.paint_shape(sh) { + Ok(v) => out.push(v), + Err(e) => { + result = Err(e); + break; + } + } + } self.painting_paths = false; (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; (self.undo, self.redo) = history; - out + result.map(|_| out) } fn paint_shape(&mut self, shape: &PathShape) -> Result { @@ -440,3 +483,43 @@ impl Session { Ok(tiles) } } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::{Session, execute}; + + /// The path sublayer's pixels, comparable. + fn pixels(s: &Session, eid: texturecraft_core::LayerId) -> Vec { + let mut v: Vec = s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, img)| format!("{k:?}{img:?}")).collect(); + v.sort(); + v + } + + #[test] + fn cached_repaint_matches_a_full_repaint() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + s.update(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + let mut eid = 0; + for v in [0.2, 0.5, 0.8] { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + eid = r["committed"]["effect"].as_u64().unwrap(); + } + let eid = texturecraft_core::LayerId(eid); + // Live edits of the middle path reuse the bottom path's pixels. + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); + for v in [0.4, 0.45] { + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); + } + assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1)); + let r = s.render_paths(eid, 1).unwrap(); + assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}"); + let cached = pixels(&s, eid); + s.path_cache = None; + s.render_paths(eid, 0).unwrap(); + assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + assert!(!cached.is_empty()); + } +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index fb1b4bc9..43402d07 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -343,6 +343,8 @@ pub struct Session { pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). pub(crate) painting_paths: bool, + /// Pixels of the paths below the one being edited, so live edits skip repainting them. + pub(crate) path_cache: Option, pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -395,6 +397,7 @@ impl Session { images: Default::default(), quick_mask: Default::default(), painting_paths: false, + path_cache: None, path: None, modified: false, revision: 1, diff --git a/crates/ui-egui/tests/path_list.rs b/crates/ui-egui/tests/path_list.rs new file mode 100644 index 00000000..799ba000 --- /dev/null +++ b/crates/ui-egui/tests/path_list.rs @@ -0,0 +1,38 @@ +//! The path list in a path sublayer's properties: pick a path to edit it, remove one. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +#[test] +fn path_rows_edit_and_remove_paths() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + let r = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.4], [0.8, 0.5]], "commit": true})).unwrap(); + let eid = LayerId(r["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let editing = |h: &Harness<'_, TextureCraftApp>| h.state().session.tool.path.editing; + let count = |h: &Harness<'_, TextureCraftApp>| h.state().session.paths(eid).map_or(0, <[_]>::len); + + // Picking a row edits that path; picking it again finishes the edit. + h.get_by_label("Path 2").click(); + h.run_steps(3); + assert_eq!(editing(&h), Some((eid, 1))); + assert_eq!(h.state().session.tool.path.points.len(), 2); + h.get_by_label("Path 2").click(); + h.run_steps(3); + assert_eq!(editing(&h), None); + + // The remove button on the first row removes the first path. + let row = h.get_by_label("Path 1").rect(); + let remove = h.query_all_by_label("Remove").find(|n| (n.rect().center().y - row.center().y).abs() < row.height()).expect("a remove button on the row"); + remove.click(); + h.run_steps(3); + assert_eq!(count(&h), 1); + assert!(h.query_by_label("Path 2").is_none()); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index f3f752d1..2f716340 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -78,6 +78,21 @@ fn window_snapshots() { texturecraft_engine::execute(s, id, &p).unwrap(); } save(&mut h, &dir, "properties-levels"); + // A path sublayer: its paths listed in Properties, the second one being edited. + let s = &mut h.state_mut().session; + for (id, p) in [ + ("layer.add.paint", serde_json::Value::Null), + ("tool.path", serde_json::json!({"uvPoints": [[0.2, 0.5], [0.5, 0.4], [0.8, 0.5]], "commit": true})), + ("tool.path", serde_json::json!({"uvPoints": [[0.3, 0.7], [0.7, 0.7], [0.7, 0.9]], "closed": true, "fill": true, "commit": true})), + ] { + texturecraft_engine::execute(s, id, &p).unwrap(); + } + let effect = match s.target { + texturecraft_engine::StackTarget::Effect(e) => e.0, + _ => 0, + }; + texturecraft_engine::execute(s, "path.edit", &serde_json::json!({"effect": effect, "index": 1})).unwrap(); + save(&mut h, &dir, "properties-paths"); // Ctrl+right drag in the 3D view: the brush cursor where it began and the readout. let c = h.state().viewport_rect.center(); let (m, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary);