From 4003e3172d3e05f5f3ea7817db936b8b9f1542e4 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 04:51:39 +0000 Subject: [PATCH 1/6] Path tool: live preview while placing points, edit points in the views - The brush stroke paints while points are placed and dragged (3D and 2D); applying is one undo step, Esc removes the unfinished path - Click the curve to insert a point, select a point and remove it with Backspace or the Remove point button; undo steps through point changes - The selected layer's other paths are drawn (lit under the pointer) and a click opens one for editing; 3D lines follow where their paint lands - A path repaint recomposites only the tiles it changed, not the whole set - Pen pointer for the tool; new paths start open; Apply/Cancel removed - Switching texture sets applies a path being placed first Closes #333 --- crates/engine/src/layer_cmds.rs | 7 + crates/engine/src/lib.rs | 1 + crates/engine/src/path_draft.rs | 13 + crates/engine/src/path_tool.rs | 357 ++++++++++++++++++++++---- crates/engine/src/session.rs | 75 +++++- crates/engine/src/set_cmds.rs | 6 + crates/engine/tests/path_tool.rs | 168 ++++++++++++- crates/paint/src/lib.rs | 2 +- crates/paint/src/path.rs | 36 +-- crates/ui-egui/src/i18n/ar.rs | 9 +- crates/ui-egui/src/i18n/de.rs | 8 +- crates/ui-egui/src/i18n/es.rs | 9 +- crates/ui-egui/src/i18n/fr.rs | 9 +- crates/ui-egui/src/i18n/it.rs | 8 +- crates/ui-egui/src/i18n/ja.rs | 9 +- crates/ui-egui/src/i18n/ko.rs | 9 +- crates/ui-egui/src/i18n/pt_br.rs | 9 +- crates/ui-egui/src/i18n/zh_hans.rs | 9 +- crates/ui-egui/src/lib.rs | 9 +- crates/ui-egui/src/menus.rs | 3 +- crates/ui-egui/src/path_hit.rs | 17 ++ crates/ui-egui/src/toolbar.rs | 30 +-- crates/ui-egui/src/viewport.rs | 364 ++++++++++++++++++++++----- crates/ui-egui/tests/path_in_view.rs | 144 +++++++++++ 24 files changed, 1117 insertions(+), 194 deletions(-) create mode 100644 crates/engine/src/path_draft.rs create mode 100644 crates/ui-egui/src/path_hit.rs create mode 100644 crates/ui-egui/tests/path_in_view.rs diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 747d7da1..36cd090c 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -168,6 +168,12 @@ fn group(s: &mut Session, p: &Value) -> Result { fn select(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.select", p)?; let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?; + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + } + s.active_set = ts; s.selected.insert(ts, id); s.target = match p.get("target") { @@ -184,6 +190,7 @@ fn select(s: &mut Session, p: &Value) -> Result { }, None => StackTarget::Content, }; + s.revision = s.revision.wrapping_add(1); Ok(json!({ "layer": id.0, "textureSet": ts })) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..bfc3bf9e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; pub mod painting; +mod path_draft; pub mod path_tool; // Mesh reimport reads files: native only. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/path_draft.rs b/crates/engine/src/path_draft.rs new file mode 100644 index 00000000..6322a7dc --- /dev/null +++ b/crates/engine/src/path_draft.rs @@ -0,0 +1,13 @@ +//! A new Path tool path previewed in the document before it is applied + +use serde_json::Value; + +use crate::Document; + +/// A new path previewed in the document before it is applied +pub(crate) struct PathDraft { + /// The document before the preview + pub(crate) base: Document, + /// What painting the preview last reported (the commit's report when nothing changed since) + pub(crate) painted: Value, +} diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 150a103e..d5b232b1 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -7,45 +7,59 @@ //! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use texturecraft_compose::{PaintTarget, PixelStore}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; -use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; +use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; +use crate::path_draft::PathDraft; use crate::session::{StackTarget, Tool}; use crate::tool_cmds::{points_param, set_tool, viewport_of}; -use crate::{EngineError, Result, Session, cmd}; +use crate::{Document, EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// The undo step that adds a new path +pub(crate) const NEW_PATH_LABEL: &str = "Path"; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; +/// A stored path's viewport is clamped to this range (pixels per side) before painting from it +const MIN_PAINT_VIEWPORT_PX: f32 = 16.0; +const MAX_PAINT_VIEWPORT_PX: f32 = 16384.0; +/// Sampling step of a 3D path's curve on the mesh for the views, in its paint viewport pixels +const SURFACE_STEP_PX: f32 = 4.0; const MIN_PROJECTIVE_W: f32 = 1e-6; // Allow ray hits to differ slightly from transformed texel positions const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001; -/// The curve being edited with the Path tool. +/// The curve being edited with the Path tool #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PathState { - /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view). + /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view) pub points: Vec, - /// The points are texture coordinates (placed in the 2D view). + /// The points are texture coordinates (placed in the 2D view) pub uv: bool, - /// The curve loops back to its first point. + /// The curve loops back to its first point pub closed: bool, - /// A closed path fills its interior instead of stroking the curve. + /// A closed path fills its interior instead of stroking the curve pub fill: bool, - /// The stored path being edited: (path sublayer, index). Changes repaint it live. + /// The stored path being edited: (path sublayer, index). Changes repaint it live #[serde(default)] pub editing: Option<(LayerId, usize)>, - /// This edit has already repainted: later changes join its undo step, not an earlier edit's. + /// This edit has already repainted: later changes join its undo step, not an earlier edit's #[serde(default)] pub edited: bool, + /// The selected control point (drawn in the accent color; Backspace or Remove point removes it) + #[serde(default)] + pub selected: Option, } impl PathState { @@ -59,6 +73,42 @@ impl PathState { self.points.push(p); } } + + /// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't + pub fn insert(&mut self, at: usize, p: Vec3) -> Option { + if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS { + return None; + } + + self.points.insert(at, p); + self.selected = Some(at); + self.selected + } + + /// The same curve (points, open or closed, filled, view) as `other` + fn same_curve(&self, other: &PathState) -> bool { + (&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv) + } + + /// Empty the tool for the next path: no points, open, nothing selected or edited + pub fn clear(&mut self) { + self.points.clear(); + self.closed = false; + self.selected = None; + self.editing = None; + self.edited = false; + } + + /// Remove the selected control point, or the last one when none is selected + pub fn remove_selected(&mut self) { + let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1)); + if let Some(i) = at { + self.points.remove(i); + } + if self.closed && self.points.len() < 3 { + self.closed = false; + } + } } /// A path sublayer's pixels after painting its first paths (`below`), with the mesh and @@ -121,20 +171,21 @@ fn path(s: &mut Session, p: &Value) -> Result { if s.tool.tool != Tool::Path { set_tool(s, Tool::Path)?; } - let vp = viewport_of(s, p); + let viewport = viewport_of(s, p); if boolp(p, "clear") == Some(true) { - s.tool.path.points.clear(); - s.tool.path.editing = None; + s.cancel_path(); } + let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) { - (Some(pts), _) => Some(( - pts.iter() + (Some(pixels), _) => Some(( + pixels + .iter() .enumerate() - .map(|(i, q)| s.pick(*q, vp).map(|h| h.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) + .map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) .collect::>>()?, false, )), - (None, Some(pts)) => Some((pts.iter().map(|q| q.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), + (None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), (None, None) => None, }; if let Some((points, uv)) = placed { @@ -151,19 +202,21 @@ fn path(s: &mut Session, p: &Value) -> Result { s.tool.path.fill = v; } s.revision = s.revision.wrapping_add(1); + let committed = if boolp(p, "commit") == Some(true) { - let r = s.commit_path(vp)?; + let report = s.commit_path(viewport)?; s.update(); - r + report } else { if s.path_live()? { s.update(); } Value::Null }; - let st = &s.tool.path; - let editing = st.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); - Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "editing": editing, "committed": committed })) + + let path = &s.tool.path; + let editing = path.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); + Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed })) } /// The `effect` and `index` params naming a stored path, with the path. @@ -181,12 +234,15 @@ fn edit_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.edit"; let (eid, index, shape) = path_ref(s, CMD, p)?; let paint = read_paint(&shape)?; + + s.finish_path()?; set_tool(s, Tool::Path)?; s.tool.brush = paint.brush; s.tool.values = paint.values; s.tool.enabled = paint.enabled; s.tool.mask_value = paint.mask_value; s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) }; + s.path_steps = Default::default(); s.target = StackTarget::Effect(eid); Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() })) } @@ -216,10 +272,46 @@ fn read_paint(shape: &PathShape) -> Result { Ok(paint) } -/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]). +/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); - PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, editing: None, edited: false } + PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() } +} + +/// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation) +fn changed_tiles(before: &PixelStore, after: &PixelStore, eid: LayerId) -> BTreeSet<(u32, u32)> { + let (before_images, after_images) = (sublayer_images(before, eid), sublayer_images(after, eid)); + let channels: BTreeSet> = before_images.keys().chain(after_images.keys()).copied().collect(); + + let mut tiles = BTreeSet::new(); + for channel in channels { + let (before_image, after_image) = (before_images.get(&channel), after_images.get(&channel)); + let Some(image) = before_image.or(after_image) else { continue }; + for ty in 0..image.tiles_y() { + for tx in 0..image.tiles_x() { + let same = match (before_image.and_then(|i| i.tile_handle(tx, ty)), after_image.and_then(|i| i.tile_handle(tx, ty))) { + (None, None) => true, + (Some(before_tile), Some(after_tile)) => Arc::ptr_eq(before_tile, after_tile), + _ => false, + }; + if !same { + tiles.insert((tx, ty)); + } + } + } + } + tiles +} + +/// Sublayer `eid`'s images by channel (None: its mask image) +fn sublayer_images(pixels: &PixelStore, eid: LayerId) -> BTreeMap, &TileImage> { + let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, channel), image)| (Some(*channel), image)); + layers.chain(pixels.masks.get(&eid).map(|mask| (None, mask))).collect() +} + +/// The camera and viewport a stored path paints through (the views draw its curve the same way) +fn paint_view(shape: &PathShape, paint: &PathPaint) -> (OrbitCamera, Vec2) { + (paint.camera, Vec2::from_array(shape.viewport).max(Vec2::splat(MIN_PAINT_VIEWPORT_PX)).min(Vec2::splat(MAX_PAINT_VIEWPORT_PX))) } /// NDC (y up) to viewport pixels (origin top-left). @@ -239,6 +331,11 @@ impl Session { path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect() } + /// The stored paths of path sublayer `eid` as Path tool states, for the views to draw + pub fn stored_path_states(&self, eid: LayerId) -> Vec { + self.paths(eid).unwrap_or_default().iter().map(state_of).collect() + } + /// The stored paths of path sublayer `eid` (None if it isn't one). pub fn paths(&self, eid: LayerId) -> Option<&[PathShape]> { match self.doc.project.effect(eid) { @@ -261,12 +358,32 @@ impl Session { } } - /// Store the Path tool's curve (a new path in the selected path sublayer, or in a new one; - /// or the path being edited) and repaint the sublayer, as one undo step. Clears the tool. + /// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool pub fn commit_path(&mut self, viewport: Vec2) -> Result { let shape = self.path_shape(self.camera, viewport); + if let Some(draft) = self.path_draft.take() { + match self.tool.path.editing { + // The preview is what applying paints: keep its pixels + Some((eid, index)) if self.paths(eid).and_then(|v| v.get(index)) == Some(&shape) => { + self.push_step(NEW_PATH_LABEL, draft.base, false); + self.target = StackTarget::Effect(eid); + self.tool.path.clear(); + let mut out = draft.painted; + out["effect"] = json!(eid.0); + out["index"] = json!(index); + return Ok(out); + } + // Otherwise it paints again from the document before the preview + _ => { + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + self.tool.path.editing = None; + } + } + } + let editing = self.tool.path.editing; - let label = editing.map_or("Path".to_string(), |(_, i)| format!("Edit path {}", i + 1)); + let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1)); let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| { let (eid, index) = match editing { Some(at) => at, @@ -274,29 +391,34 @@ impl Session { }; s.put_path(eid, index, shape) })?; + if let Some(eid) = out.get("effect").and_then(Value::as_u64) { self.target = StackTarget::Effect(LayerId(eid)); } - self.tool.path.points.clear(); - self.tool.path.editing = None; + self.tool.path.clear(); Ok(out) } - /// While a stored path is edited, repaint its sublayer when the tool's points, brush or - /// material changed (orbiting or resizing the view alone doesn't), merged into one undo - /// step. Cheap when nothing changed; the UI calls it every frame. Returns whether it - /// repainted. + /// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame pub fn path_live(&mut self) -> Result { - let Some((eid, index)) = self.tool.path.editing else { return Ok(false) }; - let Some(stored) = self.paths(eid).and_then(|v| v.get(index)).cloned() else { - self.stop_path_edit(); - return Ok(false); + let stored = match self.tool.path.editing { + Some((eid, index)) => match self.paths(eid).and_then(|v| v.get(index)).cloned() { + Some(shape) => Some((eid, index, shape)), + None => { + self.stop_path_edit(); + return Ok(false); + } + }, + None => None, }; + let path = &self.tool.path; if self.tool.tool != Tool::Path || self.stroke.is_some() || path.points.is_empty() || (path.closed && path.fill && path.points.len() < 3) { return Ok(false); } - // Typed comparison: the stored settings went through JSON (f64), maybe a save and load. + let Some((eid, index, stored)) = stored else { return self.start_path_draft() }; + + // Typed comparison: the stored settings went through JSON (f64), maybe a save and load let unchanged = read_paint(&stored).is_ok_and(|p| { let now = self.path_shape(p.camera, Vec2::from_array(stored.viewport)); (&now.points, now.uv, now.closed, now.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) && read_paint(&now).is_ok_and(|n| n == p) @@ -304,19 +426,111 @@ impl Session { if unchanged { return Ok(false); } + let shape = self.path_shape(self.camera, self.viewport); - self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |s| s.put_path(eid, index, shape))?; - self.tool.path.edited = true; + let (painted, before) = self.repaint_path(eid, index, shape)?; + match &mut self.path_draft { + Some(draft) => draft.painted = painted, + None => { + // The path's own repaint keeps its point changes undoable, unlike other steps + let steps = std::mem::take(&mut self.path_steps); + self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited); + self.path_steps = steps; + self.tool.path.edited = true; + } + } Ok(true) } - /// Stop editing a stored path (its changes are already applied) and clear the tool. - pub fn stop_path_edit(&mut self) { - if self.tool.path.editing.take().is_some() { - self.tool.path.points.clear(); + /// Paint a new path's first preview where [`Session::commit_path`] would add it, keeping the document before it for apply and cancel + fn start_path_draft(&mut self) -> Result { + let base = self.doc.clone(); + let shape = self.path_shape(self.camera, self.viewport); + let placed = self.path_effect().and_then(|eid| { + let index = self.paths(eid).map_or(0, <[_]>::len); + self.put_path(eid, index, shape).map(|painted| ((eid, index), painted)) + }); + match placed { + Ok((at, painted)) => { + // Placing a path is a new action: what was undone before can't be redone over it + self.redo.clear(); + self.tool.path.editing = Some(at); + self.changed_without_history(&base); + self.path_draft = Some(PathDraft { base, painted }); + Ok(true) + } + Err(e) => { + self.doc = base; + Err(e) + } } } + /// Remember the curve before a point change from a view, so undo steps back through those changes while the path is edited + pub fn path_checkpoint(&mut self) { + if !self.path_steps.0.last().is_some_and(|s| s.same_curve(&self.tool.path)) { + self.path_steps.0.push(self.tool.path.clone()); + self.path_steps.1.clear(); + } + } + + /// Whether [`Session::step_path`] would undo (`back`) or redo a point change + pub(crate) fn path_step_pending(&self, back: bool) -> bool { + let steps = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) + } + + /// Undo (`back`) or redo the edited path's last point change, false when there is none; with no points left the path is gone + pub(crate) fn step_path(&mut self, back: bool) -> bool { + if self.tool.tool != Tool::Path { + return false; + } + + let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; + // A checkpoint taken by a press that changed nothing isn't a step + while from.last().is_some_and(|s| s.same_curve(&self.tool.path)) { + from.pop(); + } + let Some(state) = from.pop() else { return false }; + + let path = &mut self.tool.path; + let now = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state }); + to.push(now); + + if self.tool.path.points.is_empty() { + self.stop_path_edit(); + } + true + } + + /// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes + pub fn finish_path(&mut self) -> Result<()> { + if self.path_draft.is_some() { + let viewport = self.viewport; + self.commit_path(viewport)?; + } + self.stop_path_edit(); + Ok(()) + } + + /// Cancel the Path tool's path: a new one's preview is removed, a stored one keeps its applied changes + pub fn cancel_path(&mut self) { + self.stop_path_edit(); + self.tool.path.clear(); + } + + /// Stop editing a stored path (its changes are already applied) and clear the tool; a new path's preview is removed + pub fn stop_path_edit(&mut self) { + if let Some(draft) = self.path_draft.take() { + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + } + if self.tool.path.editing.is_some() { + self.tool.path.clear(); + } + self.path_steps = Default::default(); + } + /// The selected path sublayer, or a new one on the selected layer's content or mask /// (whichever is selected). fn path_effect(&mut self) -> Result { @@ -346,6 +560,32 @@ impl Session { Ok(eid) } + /// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before + fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> { + let before = self.doc.clone(); + let painted = match self.put_path(eid, index, shape) { + Ok(v) => v, + Err(e) => { + self.doc = before; + return Err(e); + } + }; + + // Paths paint into the active set; a sublayer in another set recomposites in full + let project = &self.doc.project; + let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts); + if set == Some(self.ts()) { + // Content or mask, the sublayer's owner decides which sets redraw + let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid); + self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles); + } else { + self.invalidate_changed(&before); + } + self.revision = self.revision.wrapping_add(1); + self.modified = true; + Ok((painted, before)) + } + /// Replace path `index` of sublayer `eid` (append when out of range) and repaint the /// sublayer. Returns what painting that path reported, with the sublayer and index. fn put_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result { @@ -421,13 +661,40 @@ impl Session { fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; + let (camera, viewport) = paint_view(shape, &paint); self.tool.brush = paint.brush; self.tool.values = paint.values; self.tool.enabled = paint.enabled; self.tool.mask_value = paint.mask_value; - self.camera = paint.camera; + self.camera = camera; self.tool.path = state_of(shape); - self.paint_path(Vec2::from_array(shape.viewport).max(Vec2::splat(16.0)).min(Vec2::splat(16384.0))) + self.paint_path(viewport) + } + + /// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh) + pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec>> { + let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); + let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::>>() else { + return Vec::new(); + }; + + let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport }; + spline_segments(&screen, closed, SURFACE_STEP_PX) + .into_iter() + .zip(&screen) + .map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect()) + .collect() + } + + /// [`Session::path_surface`] of a stored 3D path through the camera and viewport it paints with + pub fn stored_path_surface(&self, eid: LayerId, index: usize) -> Option>>> { + let shape = self.paths(eid)?.get(index)?; + if shape.uv { + return None; + } + let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?); + let path = state_of(shape); + Some(self.path_surface(&path.points, path.closed, camera, viewport)) } /// Paint the Path tool's curve with the current brush (or fill it when closed and filled) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..d4b61a9d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -347,6 +347,10 @@ pub struct Session { 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, + /// A new path's live preview: the path becomes an undo step only when it is applied + pub(crate) path_draft: Option, + /// Point changes of the path being edited: (earlier states for undo, undone states for redo) + pub(crate) path_steps: (Vec, Vec), pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -363,8 +367,7 @@ pub struct Session { } impl Session { - /// A session for `project` on `mesh` (texture sets must reference mesh materials). The - /// UVs of UV-tiled sets are mapped into their tile atlas (see [`Session::source_mesh`]). + /// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`]) pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec)>) -> Result { mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?; let source = Arc::new(mesh); @@ -400,6 +403,8 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_draft: None, + path_steps: Default::default(), path: None, modified: false, revision: 1, @@ -513,24 +518,45 @@ impl Session { self.record(label, before, false); } - /// A change from `before` to the current document: a new undo step `label`, or with - /// `merge` part of the previous one when it has the same label. + /// A change from `before`: a new undo step `label`, or with `merge` part of the previous one when it has the same label fn record(&mut self, label: &str, before: Document, merge: bool) { + self.invalidate_changed(&before); + self.push_step(label, before, merge); + } + + /// [`Session::record`] for a change whose tiles the caller already marked for recompositing + pub(crate) fn push_step(&mut self, label: &str, before: Document, merge: bool) { + // Another change during a new path's preview makes the path its own step first + if !self.painting_paths + && let Some(draft) = self.path_draft.take() + { + self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base)); + } + + // Point changes of an edited path undo only until another step lands + if !self.painting_paths { + self.path_steps = Default::default(); + } self.modified = true; self.revision = self.revision.wrapping_add(1); - self.invalidate_changed(&before); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { self.undo.push((label.to_string(), before)); - if self.undo.len() > MAX_HISTORY { - self.undo.remove(0); - } } + let over = self.undo.len().saturating_sub(MAX_HISTORY); + self.undo.drain(..over); self.redo.clear(); } + /// A change from `other` to the current document that is not an undo step (a path preview) + pub(crate) fn changed_without_history(&mut self, other: &Document) { + self.modified = true; + self.revision = self.revision.wrapping_add(1); + self.invalidate_changed(other); + } + /// Mark dirty every texture set whose composite differs between `other` and the current /// document (after an edit, undo or redo). - fn invalidate_changed(&mut self, other: &Document) { + pub(crate) fn invalidate_changed(&mut self, other: &Document) { self.follow_uv_layouts(&other.project); self.sync_caches(); let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); @@ -605,15 +631,21 @@ impl Session { } pub fn can_undo(&self) -> bool { - !self.undo.is_empty() + !self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true) } pub fn can_redo(&self) -> bool { - !self.redo.is_empty() + !self.redo.is_empty() || self.path_step_pending(false) } pub fn undo_label(&self) -> Option<&str> { + if self.path_draft.is_some() || self.path_step_pending(true) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.undo.last().map(|(l, _)| l.as_str()) } pub fn redo_label(&self) -> Option<&str> { + if self.path_step_pending(false) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.redo.last().map(|(l, _)| l.as_str()) } /// The undone steps, the next one to redo first. @@ -626,7 +658,19 @@ impl Session { pub fn undo(&mut self) -> Result { self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + + // While a path is edited, undo steps back through its point changes first + if self.step_path(true) { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // A path being placed isn't a step yet: undo removes it + if self.path_draft.is_some() { + self.stop_path_edit(); + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // An edited path would otherwise repaint over the restored document self.stop_path_edit(); let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; let now = std::mem::replace(&mut self.doc, doc); @@ -638,7 +682,12 @@ impl Session { pub fn redo(&mut self) -> Result { self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + + if self.step_path(false) { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // An edited path would otherwise repaint over the restored document self.stop_path_edit(); let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; let now = std::mem::replace(&mut self.doc, doc); diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 1d9cc7f0..e9a77b96 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -77,6 +77,12 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { fn select(s: &mut Session, p: &Value) -> Result { let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; s.cancel_stroke(); + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + } + s.active_set = ts; s.target = StackTarget::Content; s.revision = s.revision.wrapping_add(1); diff --git a/crates/engine/tests/path_tool.rs b/crates/engine/tests/path_tool.rs index b053e979..429f506b 100644 --- a/crates/engine/tests/path_tool.rs +++ b/crates/engine/tests/path_tool.rs @@ -37,7 +37,7 @@ fn path_stroke_paints_along_the_curve() { let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); assert_eq!(r["points"], 3); assert_eq!(s.tool.tool, texturecraft_engine::Tool::Path); - assert!(!red_at(&s, 200.0, 180.0), "nothing painted before commit"); + assert!(red_at(&s, 200.0, 180.0), "the path is previewed before it is applied"); let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); assert!(r["committed"]["stamps"].as_u64().unwrap() > 10, "{r}"); assert_eq!(r["points"], 0, "commit clears the path"); @@ -46,11 +46,11 @@ fn path_stroke_paints_along_the_curve() { } assert!(!red_at(&s, 200.0, 240.0), "below the curve"); assert!(!red_at(&s, 200.0, 130.0), "above the curve"); - // One undo step. + // One undo step execute(&mut s, "edit.undo", &Value::Null).unwrap(); s.update(); assert!(!red_at(&s, 200.0, 180.0)); - // Errors: no points, points off the mesh. + // Errors: no points, points off the mesh assert!(execute(&mut s, "tool.path", &json!({"commit": true})).is_err()); assert!(execute(&mut s, "tool.path", &json!({"points": [[2, 2]]})).is_err()); } @@ -278,3 +278,165 @@ fn each_path_and_each_edit_of_one_is_its_own_undo_step() { s.update(); assert!(red_at(&s, 200.0, 230.0), "undo brings back the first edit"); } + +/// The pixels of every path sublayer of the selected layer, comparable +fn path_pixels(s: &Session) -> Vec { + let ids: Vec = path_sublayers(s).into_iter().map(|(id, _)| id).collect(); + let mut v: Vec = s.doc.pixels.layers.iter().filter(|((id, _), _)| ids.contains(&id.0)).map(|(k, img)| format!("{k:?}{img:?}")).collect(); + v.sort(); + v +} + +#[test] +fn placing_points_previews_the_path_with_no_undo_step_until_it_is_applied() { + let points = json!([[140, 210], [200, 180], [260, 210]]); + let mut direct = session(primitives::sphere(1.0, 48, 24)); + execute(&mut direct, "tool.path", &json!({"points": points, "commit": true})).unwrap(); + + let mut s = session(primitives::sphere(1.0, 48, 24)); + let start = s.history_labels(); + execute(&mut s, "tool.path", &json!({"points": [[140, 280], [260, 280]]})).unwrap(); + assert!(red_at(&s, 200.0, 280.0)); + execute(&mut s, "tool.path", &json!({"points": points})).unwrap(); + assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 280.0), "the preview follows the points"); + assert_eq!(s.history_labels(), start, "no undo step while placing"); + execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + assert_eq!(s.history_labels().len(), start.len() + 1, "applying is one undo step"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(path_pixels(&s), path_pixels(&direct), "the same pixels as applying without a preview"); + + // Cancelling removes the preview + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(red_at(&s, 200.0, 250.0)); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0) && red_at(&s, 200.0, 180.0)); + assert_eq!(s.history_labels().len(), start.len() + 1); +} + +#[test] +fn undo_while_placing_removes_the_preview_only() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0), "the preview is gone"); + assert!(red_at(&s, 200.0, 180.0), "the applied path stays"); + assert_eq!(s.history_labels().len(), steps); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none()); +} + +#[test] +fn another_change_while_placing_makes_the_path_its_own_step_first() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let labels = s.history_labels(); + assert_eq!(labels.len(), steps + 2); + assert_eq!(labels.get(steps).map(String::as_str), Some("Path")); + // Undoing the other change keeps the path; undoing again removes it + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 180.0)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 180.0)); +} + +#[test] +fn editing_another_path_while_placing_applies_the_new_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = r["committed"]["effect"].as_u64().unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 2)], "the new path was applied"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(s.tool.path.editing, Some((texturecraft_engine::core::LayerId(eid), 0))); +} + +#[test] +fn the_next_path_starts_open_after_a_closed_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "closed": true, "commit": true})).unwrap(); + assert!(!s.tool.path.closed, "applying a closed path leaves the tool open for the next one"); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]], "closed": true})).unwrap(); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + assert!(!s.tool.path.closed, "cancelling does too"); +} + +/// A short path's repaint marks under 1/N of a 1024-texel set's 256 tiles +const SHORT_PATH_TILE_SHARE_DIVISOR: usize = 4; + +/// Move the middle point of the Path tool's curve down to viewport row `y` and repaint, returning the (dirty, all) tile counts +fn move_middle_point(s: &mut Session, y: f32) -> (usize, usize) { + s.tool.path.points[1] = s.pick(Vec2::new(200.0, y), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len()) +} + +#[test] +fn moving_a_point_recomposites_only_the_paths_tiles() { + // 1024 texels: 256 tiles, so a short path covers few of them + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:test", None, 1024).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + (s.camera.yaw, s.camera.pitch) = (0.0, 0.0); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + s.update(); + + let (dirty, all) = move_middle_point(&mut s, 190.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "a new path: {dirty} of {all} tiles to recomposite"); + s.update(); + + let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": r["committed"]["effect"], "index": 0})).unwrap(); + s.update(); + // Another row than the applied one, so the edit changes the path + let (dirty, all) = move_middle_point(&mut s, 200.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "an applied path being edited: {dirty} of {all} tiles to recomposite"); +} + +#[test] +fn another_change_ends_the_point_undo_of_an_edited_path() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = texturecraft_engine::core::LayerId(r["committed"]["effect"].as_u64().unwrap()); + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 0})).unwrap(); + s.path_checkpoint(); + s.tool.path.points[1] = s.pick(Vec2::new(200.0, 230.0), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + let moved: Vec<[f32; 3]> = s.tool.path.points.iter().map(|p| p.to_array()).collect(); + let layers = s.doc.project.layers.len(); + + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layers.len(), layers, "undo removes the new layer"); + assert_eq!(s.paths(eid).unwrap()[0].points, moved, "the path keeps its moved point"); +} + +#[test] +fn placing_a_path_ends_redo() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.can_redo()); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(!s.can_redo(), "redo would throw the path being placed away"); +} + +#[test] +fn switching_texture_sets_applies_the_path_being_placed() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]]})).unwrap(); + + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1); + assert_eq!(s.undo_label(), Some("Path")); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none(), "the path no longer paints into the other set"); +} diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..aad8fbda 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -25,7 +25,7 @@ pub mod visibility; pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha}; pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask}; -pub use path::{Lasso, spline}; +pub use path::{Lasso, spline, spline_segments}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; diff --git a/crates/paint/src/path.rs b/crates/paint/src/path.rs index fe483ee0..0075e411 100644 --- a/crates/paint/src/path.rs +++ b/crates/paint/src/path.rs @@ -6,12 +6,18 @@ use texturecraft_geom::glam::Vec2; /// Most samples per curve segment. const MAX_SEGMENT_SAMPLES: f32 = 1024.0; -/// A Catmull-Rom spline through `points`, sampled about every `step` units. Closed curves wrap -/// back to the first point; the result starts at the first point. +/// A Catmull-Rom spline through `points`, sampled about every `step` units, starting on the first point (closed curves end there too) pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec { + let mut out: Vec = points.first().copied().into_iter().collect(); + out.extend(spline_segments(points, closed, step).into_iter().flatten()); + out +} + +/// [`spline`]'s samples per segment: segment `s` holds those after point `s`, up to and including the next point +pub fn spline_segments(points: &[Vec2], closed: bool, step: f32) -> Vec> { let n = points.len(); if n < 2 { - return points.to_vec(); + return Vec::new(); } let at = |i: isize| { let i = if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) }; @@ -19,17 +25,19 @@ pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec { }; let step = if step.is_finite() && step > 1e-6 { step } else { 1.0 }; let segments = if closed { n } else { n - 1 } as isize; - let mut out = vec![at(0)]; - for s in 0..segments { - let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2)); - let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize; - for j in 1..=k { - let t = j as f32 / k as f32; - let (t2, t3) = (t * t, t * t * t); - out.push(0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3)); - } - } - out + (0..segments) + .map(|s| { + let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2)); + let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize; + (1..=k) + .map(|j| { + let t = j as f32 / k as f32; + let (t2, t3) = (t * t, t * t * t); + 0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3) + }) + .collect() + }) + .collect() } /// A closed polygon's coverage: 1 inside, 0 outside, a one-unit ramp across the edge. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..d3fd9f4b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -74,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "مستوى تباين الخواص"), ("Antialiasing", "تنعيم الحواف"), ("Aperture", "فتحة العدسة"), - ("Apply", "تطبيق"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), ("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"), @@ -561,7 +560,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "ارسم على المجسم لتعديل هذا القناع. استخدم قيمة القناع في لسان تبويب المادة للتدرج الرمادي.", ), - ("Paint the path with the brush (Enter)", "رسم المسار بالفرشاة (Enter)"), ("Paint with the current tool", "الرسم بالأداة الحالية"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -580,7 +578,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "لصق الطبقة (الطبقات)"), ("Path", "مسار"), ("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "المسار: النقر يضيف نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "المسار: النقر يضيف نقطة، والنقر على المنحنى يُدرج نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي", + ), ("Pattern scale", "مقياس النمط"), ("Perlin noise", "ضوضاء بيرلن (Perlin)"), ("Pick focus in the viewport", "اختر نقطة التركيز في منفذ العرض"), @@ -627,8 +628,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "إزالة الطبقة"), ("Remove layer(s)", "إزالة الطبقة (الطبقات)"), ("Remove mask", "إزالة القناع"), + ("Remove point", "إزالة النقطة"), ("Remove resource", "إزالة المورد"), - ("Remove the path (Esc)", "إزالة المسار (Esc)"), ("Remove the shortcut", "إزالة الاختصار"), ("Remove this output", "إزالة هذا المخرج"), ("Remove unused resources...", "إزالة الموارد غير المستخدمة..."), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..ff19c0c0 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Anisotropiestärke"), ("Antialiasing", "Kantenglättung"), ("Aperture", "Blende"), - ("Apply", "Anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), ("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"), @@ -594,7 +593,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Auf das Mesh malen, um diese Maske zu bearbeiten. Für Grau den Maskenwert im Tab Material verwenden.", ), - ("Paint the path with the brush (Enter)", "Pfad mit dem Pinsel malen (Eingabe)"), ("Paint with the current tool", "Mit dem aktuellen Werkzeug malen"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -617,8 +615,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Pfad"), ("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Pfad: Klicken fügt einen Punkt hinzu, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Pfad: Klicken fügt einen Punkt hinzu, Klicken auf die Kurve fügt einen ein, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", ), ("Pattern scale", "Musterskalierung"), ("Perlin noise", "Perlin-Rauschen"), @@ -666,8 +664,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Ebene entfernen"), ("Remove layer(s)", "Ebene(n) entfernen"), ("Remove mask", "Maske entfernen"), + ("Remove point", "Punkt entfernen"), ("Remove resource", "Ressource entfernen"), - ("Remove the path (Esc)", "Pfad entfernen (Esc)"), ("Remove the shortcut", "Tastenkürzel entfernen"), ("Remove this output", "Diese Ausgabe entfernen"), ("Remove unused resources...", "Unbenutzte Ressourcen entfernen..."), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..d38471eb 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -74,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nivel de anisotropía"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), - ("Apply", "Aplicar"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), ("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"), @@ -585,7 +584,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinta sobre la malla para editar esta máscara. Usa el valor de máscara de la pestaña Material para el gris.", ), - ("Paint the path with the brush (Enter)", "Pintar el trazado con el pincel (Intro)"), ("Paint with the current tool", "Pintar con la herramienta actual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -607,7 +605,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Pegar capa(s)"), ("Path", "Trazado"), ("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Trazado: clic añade un punto, arrastrar lo mueve, Intro aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Trazado: clic añade un punto, clic en la curva inserta uno, arrastrar lo mueve, Intro aplica, Esc cancela", + ), ("Pattern scale", "Escala del patrón"), ("Perlin noise", "Ruido Perlin"), ("Pick focus in the viewport", "Elegir el enfoque en la ventana gráfica"), @@ -654,8 +655,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Eliminar capa"), ("Remove layer(s)", "Eliminar capa(s)"), ("Remove mask", "Quitar máscara"), + ("Remove point", "Quitar punto"), ("Remove resource", "Quitar recurso"), - ("Remove the path (Esc)", "Quitar el trazado (Esc)"), ("Remove the shortcut", "Quitar el atajo"), ("Remove this output", "Quitar esta salida"), ("Remove unused resources...", "Quitar recursos no usados..."), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..fcebf4b9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -80,7 +80,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Niveau d'anisotropie"), ("Antialiasing", "Anticrénelage"), ("Aperture", "Ouverture"), - ("Apply", "Appliquer"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), ("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"), @@ -600,7 +599,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Peignez sur le maillage pour modifier ce masque. Utilisez la valeur de masque de l'onglet Matériau pour le gris.", ), - ("Paint the path with the brush (Enter)", "Peindre le tracé avec le pinceau (Enter)"), ("Paint with the current tool", "Peindre avec l'outil actuel"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -622,7 +620,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Coller le(s) calque(s)"), ("Path", "Tracé"), ("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Tracé : cliquer ajoute un point, glisser le déplace, Enter applique, Esc annule"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracé : cliquer ajoute un point, cliquer sur la courbe en insère un, glisser le déplace, Enter applique, Esc annule", + ), ("Pattern scale", "Échelle du motif"), ("Perlin noise", "Bruit de Perlin"), ("Pick focus in the viewport", "Choisir la mise au point dans la fenêtre d'affichage"), @@ -669,8 +670,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Supprimer le calque"), ("Remove layer(s)", "Supprimer le(s) calque(s)"), ("Remove mask", "Supprimer le masque"), + ("Remove point", "Retirer le point"), ("Remove resource", "Supprimer la ressource"), - ("Remove the path (Esc)", "Supprimer le tracé (Esc)"), ("Remove the shortcut", "Supprimer le raccourci"), ("Remove this output", "Supprimer cette sortie"), ("Remove unused resources...", "Supprimer les ressources inutilisées..."), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..a22e34ae 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Livello anisotropia"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), - ("Apply", "Applica"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), ("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"), @@ -591,7 +590,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Dipingi sulla mesh per modificare questa maschera. Usa il valore maschera della scheda Materiale per il grigio.", ), - ("Paint the path with the brush (Enter)", "Dipingi il tracciato con il pennello (Invio)"), ("Paint with the current tool", "Dipingi con lo strumento corrente"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -614,8 +612,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Tracciato"), ("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Tracciato: clic aggiunge un punto, trascina lo sposta, Invio applica, Esc annulla", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracciato: clic aggiunge un punto, clic sulla curva ne inserisce uno, trascina lo sposta, Invio applica, Esc annulla", ), ("Pattern scale", "Scala motivo"), ("Perlin noise", "Rumore Perlin"), @@ -663,8 +661,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Rimuovi livello"), ("Remove layer(s)", "Rimuovi livello/i"), ("Remove mask", "Rimuovi maschera"), + ("Remove point", "Rimuovi punto"), ("Remove resource", "Rimuovi risorsa"), - ("Remove the path (Esc)", "Rimuovi il tracciato (Esc)"), ("Remove the shortcut", "Rimuovi la scorciatoia"), ("Remove this output", "Rimuovi questo output"), ("Remove unused resources...", "Rimuovi risorse inutilizzate..."), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..b44388e3 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -80,7 +80,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "異方性レベル"), ("Antialiasing", "アンチエイリアス"), ("Aperture", "絞り"), - ("Apply", "適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), ("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"), @@ -579,7 +578,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "メッシュにペイントしてこのマスクを編集します。グレーには「マテリアル」タブのマスク値を使用します。", ), - ("Paint the path with the brush (Enter)", "ブラシでパスをペイント (Enter)"), ("Paint with the current tool", "現在のツールでペイント"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -598,7 +596,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "レイヤーを貼り付け"), ("Path", "パス"), ("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "パス: クリックでポイントを追加、ドラッグで移動、Enterで適用、Escでキャンセル"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "パス: クリックでポイントを追加、カーブをクリックで挿入、ドラッグで移動、Enterで適用、Escでキャンセル", + ), ("Pattern scale", "パターンのスケール"), ("Perlin noise", "パーリンノイズ"), ("Pick focus in the viewport", "ビューポートでフォーカスを指定"), @@ -645,8 +646,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "レイヤーを削除"), ("Remove layer(s)", "レイヤーを削除"), ("Remove mask", "マスクを削除"), + ("Remove point", "ポイントを削除"), ("Remove resource", "リソースを削除"), - ("Remove the path (Esc)", "パスを削除 (Esc)"), ("Remove the shortcut", "ショートカットを削除"), ("Remove this output", "この出力を削除"), ("Remove unused resources...", "未使用のリソースを削除..."), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..34293f2b 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "이방성 레벨"), ("Antialiasing", "안티앨리어싱"), ("Aperture", "조리개"), - ("Apply", "적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), ("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"), @@ -570,7 +569,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "메시에 칠하여 이 마스크를 편집합니다. 회색은 머티리얼 탭의 마스크 값을 사용하세요.", ), - ("Paint the path with the brush (Enter)", "브러시로 패스를 칠합니다 (Enter)"), ("Paint with the current tool", "현재 도구로 페인팅"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -589,7 +587,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "레이어 붙여넣기"), ("Path", "패스"), ("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "패스: 클릭으로 점 추가, 드래그로 이동, Enter로 적용, Esc로 취소"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "패스: 클릭으로 점 추가, 곡선 클릭으로 점 삽입, 드래그로 이동, Enter로 적용, Esc로 취소", + ), ("Pattern scale", "패턴 스케일"), ("Perlin noise", "펄린 노이즈"), ("Pick focus in the viewport", "뷰포트에서 초점 선택"), @@ -636,8 +637,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "레이어 제거"), ("Remove layer(s)", "레이어 제거"), ("Remove mask", "마스크 제거"), + ("Remove point", "점 제거"), ("Remove resource", "리소스 제거"), - ("Remove the path (Esc)", "패스를 제거합니다 (Esc)"), ("Remove the shortcut", "단축키를 제거합니다"), ("Remove this output", "이 출력을 제거합니다"), ("Remove unused resources...", "사용하지 않는 리소스 제거..."), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..317410ce 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nível de anisotropia"), ("Antialiasing", "Antisserrilhamento"), ("Aperture", "Abertura"), - ("Apply", "Aplicar"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), ("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"), @@ -582,7 +581,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinte na malha para editar esta máscara. Use o valor de máscara da aba Material para cinza.", ), - ("Paint the path with the brush (Enter)", "Pintar o caminho com o pincel (Enter)"), ("Paint with the current tool", "Pintar com a ferramenta atual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -604,7 +602,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Colar camada(s)"), ("Path", "Caminho"), ("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Caminho: clicar adiciona um ponto, arrastar o move, Enter aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Caminho: clicar adiciona um ponto, clicar na curva insere um, arrastar o move, Enter aplica, Esc cancela", + ), ("Pattern scale", "Escala do padrão"), ("Perlin noise", "Ruído Perlin"), ("Pick focus in the viewport", "Escolher o foco na viewport"), @@ -651,8 +652,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Remover camada"), ("Remove layer(s)", "Remover camada(s)"), ("Remove mask", "Remover máscara"), + ("Remove point", "Remover ponto"), ("Remove resource", "Remover recurso"), - ("Remove the path (Esc)", "Remover o caminho (Esc)"), ("Remove the shortcut", "Remover o atalho"), ("Remove this output", "Remover esta saída"), ("Remove unused resources...", "Remover recursos não usados..."), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..0fea6a3a 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -68,7 +68,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "各向异性强度"), ("Antialiasing", "抗锯齿"), ("Aperture", "光圈"), - ("Apply", "应用"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), ("Automatic (from the mesh UVs)", "自动(基于网格 UV)"), @@ -531,7 +530,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paint chips", "掉漆"), ("Paint on the mesh to edit the layer content.", "在网格上绘画以编辑图层内容。"), ("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "在网格上绘画以编辑此遮罩。灰度请使用“材质”选项卡中的遮罩值。"), - ("Paint the path with the brush (Enter)", "用笔刷绘制路径(Enter)"), ("Paint with the current tool", "使用当前工具绘画"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -550,7 +548,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "粘贴图层"), ("Path", "路径"), ("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "路径:单击添加点,拖动移动点,Enter 应用,Esc 取消"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "路径:单击添加点,单击曲线插入点,拖动移动点,Enter 应用,Esc 取消", + ), ("Pattern scale", "图案缩放"), ("Perlin noise", "柏林噪波"), ("Pick focus in the viewport", "在视口中拾取焦点"), @@ -597,8 +598,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "移除图层"), ("Remove layer(s)", "移除图层"), ("Remove mask", "移除遮罩"), + ("Remove point", "移除点"), ("Remove resource", "移除资源"), - ("Remove the path (Esc)", "移除路径(Esc)"), ("Remove the shortcut", "移除快捷键"), ("Remove this output", "移除此输出"), ("Remove unused resources...", "移除未使用的资源..."), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..91194620 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -20,6 +20,7 @@ mod mask_preview_image; mod mask_shape; pub mod menus; pub mod parity; +mod path_hit; mod preview_image; mod preview_request; mod preview_worker; @@ -508,7 +509,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.poll_resize(ctx); self.poll_link_cooks(ctx); - // The library shelf rescans when the window comes back (MaterialCraft may have sent a material). + // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; @@ -528,9 +529,9 @@ impl eframe::App for TextureCraftApp { } self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); menus::shortcuts(self, ctx); - // A stored path being edited repaints its sublayer as its points, brush or material change. + // The Path tool's curve repaints (a preview while placed) as its points, brush or material change if let Err(e) = self.session.path_live() { - self.session.stop_path_edit(); + self.session.cancel_path(); self.toast(e.to_string(), true); } profile::drive(self, ctx); @@ -553,7 +554,7 @@ impl eframe::App for TextureCraftApp { } let hide = self.ui.hide_ui; let tk = theme::Tokens::get(&ctx); - // The dock keeps the cards' gutter from the bars and rails around it. + // The dock keeps the cards' gutter from the bars and rails around it let frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; egui::CentralPanel::default().frame(frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b74aa300..dff70ca7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -341,8 +341,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.properties_popup = None; } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); - app.session.tool.path.points.clear(); - app.session.tool.path.editing = None; + app.session.cancel_path(); } }); diff --git a/crates/ui-egui/src/path_hit.rs b/crates/ui-egui/src/path_hit.rs new file mode 100644 index 00000000..6b62f0f0 --- /dev/null +++ b/crates/ui-egui/src/path_hit.rs @@ -0,0 +1,17 @@ +//! What a pointer position in a view is over, for the Path tool + +use egui::Pos2; +use texturecraft_engine::core::LayerId; + +/// What a pointer position in a view is over, for the Path tool +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum PathHit { + /// A control point of the path being edited + Point(usize), + /// The edited path's curve: the segment starting at this point, and the nearest screen position on it + Curve(usize, Pos2), + /// Another stored path of the selected layer: (path sublayer, index) + Stored(LayerId, usize), + /// Nothing of a path + Miss, +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index eee357f7..9cc550ae 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -320,25 +320,21 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { /// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let button_size = ui.spacing().interact_size.y; - let path = &mut app.session.tool.path; - if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, button_size).clicked() { - path.closed = !path.closed; + let path = &app.session.tool.path; + let (closed, fill) = (path.closed, path.fill); + let selected = path.selected.is_some_and(|i| i < path.points.len()); + if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() { + app.session.path_checkpoint(); + app.session.tool.path.closed = !closed; } - let fill_tip = if path.closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; - if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, button_size).clicked() { - path.fill = !path.fill; + let fill_tip = if closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; + if icon_button(ui, ic::PAINT_BUCKET, fill_tip, fill, button_size).clicked() { + app.session.path_checkpoint(); + app.session.tool.path.fill = !fill; } - - let has_points = !path.points.is_empty(); - if ui - .add_enabled(has_points, egui::Button::new(format!("{} {}", ic::CHECK, tr("Apply")))) - .on_hover_text(tr("Paint the path with the brush (Enter)")) - .clicked() - { - app.run("tool.path", json!({"commit": true})); - } - if ui.add_enabled(has_points, egui::Button::new(format!("{} {}", ic::X, tr("Cancel")))).on_hover_text(tr("Remove the path (Esc)")).clicked() { - app.run("tool.path", json!({"clear": true})); + if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() { + app.session.path_checkpoint(); + app.session.tool.path.remove_selected(); } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..ff8c2ae8 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1,7 +1,7 @@ //! The 3D viewport and the 2D UV view: navigation, painting input, brush cursor and the GPU //! callbacks that render them. -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use egui::emath::GuiRounding as _; use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; @@ -15,6 +15,7 @@ use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; +use crate::path_hit::PathHit; use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; @@ -576,7 +577,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); if painting && path_tool { - path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); + path_input(app, ui, &response, (rect, false), |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -630,6 +631,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !navigating && response.hovered() && brush_tool(app.session.tool.tool) + && (app.session.tool.tool != Tool::Path || adjusting) && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { @@ -646,7 +648,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !path_tool && let Some(from) = app.last_paint_point { - rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hover_pos); + rubber_band(ui, rect, &[pos2(rect.left() + from.x, rect.top() + from.y), hover_pos]); } } @@ -897,11 +899,42 @@ fn project(app: &TextureCraftApp, rect: Rect, p: Vec3) -> Option { Some(pos2(rect.left() + (n.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - n.y * 0.5) * rect.height())) } -/// Control point grab radius (points). +/// Control point and curve grab radius (points) const HANDLE_GRAB: f32 = 8.0; +/// Opacity of the selected layer's other stored paths +const PATH_STORED_OPACITY: f32 = 0.55; +/// Opacity of a curve where the mesh hides it +const PATH_HIDDEN_OPACITY: f32 = 0.5; +/// A control point counts as hidden when the surface under it is this much closer (relative) +const PATH_HIDDEN_DEPTH: f32 = 0.01; +/// The Path tool's pointer glyph size (points) +const PATH_CURSOR_SIZE: f32 = 18.0; +/// A path's line and the dark outline under it (points) +const PATH_LINE_WIDTH: f32 = 1.4; +const PATH_OUTLINE_WIDTH: f32 = 3.0; +/// Where the view hint sits from the view's bottom left corner, and its text size (points) +const PATH_HINT_OFFSET: egui::Vec2 = vec2(56.0, -12.0); +const PATH_HINT_FONT_SIZE: f32 = 12.0; +/// The pen pointer's drop shadow, and the space before its insert plus (points) +const PATH_CURSOR_SHADOW_OFFSET: egui::Vec2 = vec2(1.0, 1.0); +const PATH_CURSOR_PLUS_GAP: f32 = 1.0; +/// Dash and gap lengths of a line still to be painted (points) +const RUBBER_BAND_DASH: f32 = 6.0; +const RUBBER_BAND_GAP: f32 = 4.0; +/// The insert plus beside the pen pointer, relative to the pen's size +const PATH_CURSOR_PLUS_SCALE: f32 = 0.6; +/// Space kept right of the view hint, and its narrowest wrap width (points) +const PATH_HINT_MARGIN: f32 = 8.0; +const PATH_HINT_MIN_WIDTH: f32 = 80.0; +/// How much a control point marker grows under the pointer, and when selected (points) +const PATH_POINT_HOVER_GROWTH: f32 = 1.5; +const PATH_POINT_SELECTED_GROWTH: f32 = 0.5; +/// Control point marker radius (points) +const PATH_POINT_RADIUS: f32 = 3.0; +/// Curve sampling step on screen (points) +const PATH_SCREEN_STEP: f32 = 3.0; -/// Path tool keys: Enter applies the path, Backspace removes its last point (Esc, handled with -/// the global shortcuts, cancels it). +/// Path tool keys: Enter applies the path, Backspace removes the selected (or last) point; Esc is a global shortcut fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Path @@ -915,19 +948,123 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { app.run("tool.path", json!({"commit": true})); } if back { - app.session.tool.path.points.pop(); + app.session.path_checkpoint(); + app.session.tool.path.remove_selected(); } } -/// Path tool input in a view (`uv`: the 2D view). Pressing on a control point drags it, -/// elsewhere adds a point (and drags it); clicking the first point of an open path closes it. -/// `place` maps a pointer position to a path point (None off the surface), `show` a path point -/// to the screen. +/// The selected layer's stored paths except the edited one: (path sublayer, index, path) +fn other_paths(app: &TextureCraftApp) -> Vec<(texturecraft_engine::core::LayerId, usize, texturecraft_engine::PathState)> { + let s = &app.session; + let Some(layer) = s.selected_layer().and_then(|id| s.doc.project.layer(id).ok()) else { return Vec::new() }; + let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|m| m.effects.iter())); + effects + .flat_map(|e| s.stored_path_states(e.id).into_iter().enumerate().map(move |(i, path)| (e.id, i, path))) + .filter(|(e, i, _)| s.tool.path.editing != Some((*e, *i))) + .collect() +} + +/// The screen curve through `points` per segment, each starting on its first point +fn screen_segments(points: &[Pos2], closed: bool) -> Vec> { + let pts: Vec = points.iter().map(|p| Vec2::new(p.x, p.y)).collect(); + texturecraft_engine::paint::spline_segments(&pts, closed, PATH_SCREEN_STEP) + .into_iter() + .zip(points) + .map(|(samples, first)| std::iter::once(*first).chain(samples.into_iter().map(|v| pos2(v.x, v.y))).collect()) + .collect() +} + +/// A path's curve in a view per segment: screen position and whether the mesh leaves it visible (None off the mesh or screen) +type ScreenCurve = Vec>>; + +/// A 3D path's curve on the mesh, per segment ([`texturecraft_engine::Session::path_surface`]) +type SurfaceCurve = Arc>>>; + +/// The nearest segment of `curve` within grab distance of `at`, with the nearest position on it +fn segment_near(curve: &ScreenCurve, at: Pos2) -> Option<(usize, Pos2)> { + let nearest = |segment: &Vec>| { + segment.windows(2).filter_map(|w| Some(closest_on_line(w[0]?.0, w[1]?.0, at))).min_by(|a, b| a.distance(at).total_cmp(&b.distance(at))) + }; + curve + .iter() + .enumerate() + .filter_map(|(i, segment)| nearest(segment).map(|p| (i, p))) + .filter(|(_, p)| p.distance(at) < HANDLE_GRAB) + .min_by(|a, b| a.1.distance(at).total_cmp(&b.1.distance(at))) +} + +/// `path`'s curve in a view; a 3D curve lies where its paint lands, and without `depth_test` (hit tests) every sample counts as visible +fn curve_on_screen( + app: &TextureCraftApp, + ui: &Ui, + (rect, uv, depth_test): (Rect, bool, bool), + path: &texturecraft_engine::PathState, + stored: Option<(texturecraft_engine::core::LayerId, usize)>, + show: &impl Fn(&TextureCraftApp, Vec3) -> Option, +) -> ScreenCurve { + if uv { + let Some(points) = path.points.iter().map(|p| show(app, *p)).collect::>>() else { return Vec::new() }; + return screen_segments(&points, path.closed).into_iter().map(|segment| segment.into_iter().map(|at| Some((at, true))).collect()).collect(); + } + let s = &app.session; + let surface = stored + .and_then(|(eid, index)| stored_surface(app, ui, eid, index)) + .unwrap_or_else(|| Arc::new(s.path_surface(&path.points, path.closed, s.camera, s.viewport))); + surface + .iter() + .map(|segment| segment.iter().map(|p| p.and_then(|p| show(app, p).map(|at| (at, !depth_test || path_point_visible(app, rect, p, at))))).collect()) + .collect() +} + +/// [`texturecraft_engine::Session::stored_path_surface`], kept until the path or the mesh changes +fn stored_surface(app: &TextureCraftApp, ui: &Ui, eid: texturecraft_engine::core::LayerId, index: usize) -> Option { + let key = (app.session.mesh_id, app.session.paths(eid)?.get(index)?.clone()); + let id = egui::Id::unique(("path_surface", eid.0, index)); + if let Some((cached, surface)) = ui.data(|d| d.get_temp::<((u64, texturecraft_engine::core::PathShape), SurfaceCurve)>(id)) + && cached == key + { + return Some(surface); + } + let surface = Arc::new(app.session.stored_path_surface(eid, index)?); + ui.data_mut(|d| d.insert_temp(id, (key, surface.clone()))); + Some(surface) +} + +/// The point of the segment `a`–`b` nearest to `p` +fn closest_on_line(a: Pos2, b: Pos2, p: Pos2) -> Pos2 { + let ab = b - a; + let t = if ab.length_sq() > 0.0 { ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + a + ab * t +} + +/// What `at` is over in a view (`uv`: the 2D view); `show` maps a path point to the screen +fn path_hit(app: &TextureCraftApp, ui: &Ui, (rect, uv): (Rect, bool), at: Pos2, show: &impl Fn(&TextureCraftApp, Vec3) -> Option) -> PathHit { + let path = &app.session.tool.path; + if path.uv == uv { + if let Some(i) = path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) { + return PathHit::Point(i); + } + if let Some((i, on)) = segment_near(&curve_on_screen(app, ui, (rect, uv, false), path, path.editing, show), at) { + return PathHit::Curve(i, on); + } + } + for (eid, i, other) in other_paths(app) { + if other.uv == uv + && (other.points.iter().any(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) + || segment_near(&curve_on_screen(app, ui, (rect, uv, false), &other, Some((eid, i)), show), at).is_some()) + { + return PathHit::Stored(eid, i); + } + } + PathHit::Miss +} + +/// Path tool presses in a view: select and drag a point, insert on the curve, open another path, close on the first point, or add a point fn path_input( app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, - uv: bool, + (rect, uv): (Rect, bool), place: impl Fn(&TextureCraftApp, Pos2) -> Option, show: impl Fn(&TextureCraftApp, Vec3) -> Option, ) { @@ -937,24 +1074,48 @@ fn path_input( && let Some(at) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()) { let path = &app.session.tool.path; - let near = if path.uv == uv { path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) } else { None }; - match near { - Some(0) if clicked && !path.closed && path.points.len() >= 3 => app.session.tool.path.closed = true, - Some(i) => ui.data_mut(|d| { - d.insert_temp(drag_id, i); - }), - None => match place(app, at) { + let (closed, len) = (path.closed, path.points.len()); + let hit = path_hit(app, ui, (rect, uv), at, &show); + if !matches!(hit, PathHit::Stored(..)) { + app.session.path_checkpoint(); + } + + let grab = match hit { + PathHit::Point(0) if clicked && !closed && len >= 3 => { + app.session.tool.path.closed = true; + None + } + PathHit::Point(i) => { + app.session.tool.path.selected = Some(i); + Some(i) + } + PathHit::Stored(eid, index) => { + app.run("path.edit", json!({"effect": eid.0, "index": index})); + None + } + hit => match place(app, if let PathHit::Curve(_, on) = hit { on } else { at }) { Some(p) => { - app.session.tool.path.push(p, uv); - let last = app.session.tool.path.points.len().saturating_sub(1); - ui.data_mut(|d| { - d.insert_temp(drag_id, last); - }); + let path = &mut app.session.tool.path; + match hit { + PathHit::Curve(i, _) => path.insert(i + 1, p), + _ => { + path.push(p, uv); + path.selected = path.points.len().checked_sub(1); + path.selected + } + } + } + None => { + app.toast(tr("Place path points on the mesh"), false); + None } - None => app.toast(tr("Place path points on the mesh"), false), }, + }; + if let Some(i) = grab { + ui.data_mut(|d| d.insert_temp(drag_id, i)); } } + if resp.dragged_by(PointerButton::Primary) && let Some(i) = ui.data(|d| d.get_temp::(drag_id)) && let Some(p) = resp.interact_pointer_pos().and_then(|pos| place(app, pos)) @@ -962,45 +1123,134 @@ fn path_input( { *q = p; } + if !resp.is_pointer_button_down_on() { ui.data_mut(|d| d.remove::(drag_id)); } } -/// The path being edited: its curve, control points (the first one in the accent color) and, -/// while open, a dashed preview of the next segment. -fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Response, uv: bool, show: impl Fn(&TextureCraftApp, Vec3) -> Option) { - let tk = Tokens::get(ui.ctx()); - let p = ui.painter_at(rect); - let path = &app.session.tool.path; - let hint = tr("Path: click adds a point, drag moves it, Enter applies, Esc cancels"); - p.text(rect.left_bottom() + vec2(56.0, -12.0), egui::Align2::LEFT_BOTTOM, hint, egui::FontId::proportional(12.0), tk.viewport_text); - if path.uv != uv { - return; - } - let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); - let pts: Vec = handles.iter().map(|h| Vec2::new(h.x, h.y)).collect(); - let curve: Vec = texturecraft_engine::paint::spline(&pts, path.closed, 3.0).into_iter().map(|v| pos2(v.x, v.y)).collect(); - let color = if path.closed && path.fill { tk.viewport_accent } else { Color32::from_white_alpha(230) }; - p.add(egui::Shape::line(curve.clone(), Stroke::new(3.0, Color32::from_black_alpha(140)))); - p.add(egui::Shape::line(curve, Stroke::new(1.4, color))); - let hover = resp.hover_pos(); - if !path.closed - && let (Some(last), Some(to)) = (handles.last(), hover) - { - rubber_band(ui, rect, *last, to); - } - for (i, h) in handles.iter().enumerate() { - let r = if hover.is_some_and(|m| m.distance(*h) < HANDLE_GRAB) { 5.5 } else { 4.0 }; - p.circle(*h, r, if i == 0 { tk.viewport_accent } else { Color32::WHITE }, Stroke::new(1.5, Color32::from_black_alpha(180))); +/// Is path point `p` (on screen at `at`) in front of the mesh in the 3D view `rect`? +fn path_point_visible(app: &TextureCraftApp, rect: Rect, p: Vec3, at: Pos2) -> bool { + let eye = app.session.camera.eye(); + let local = Vec2::new(at.x - rect.left(), at.y - rect.top()); + app.session.pick(local, app.session.viewport).is_none_or(|hit| hit.pos.distance(eye) >= p.distance(eye) * (1.0 - PATH_HIDDEN_DEPTH)) +} + +/// Draw `curve` in `color` over a dark outline, as a faint line where the mesh hides it +fn draw_path_curve(painter: &egui::Painter, curve: &ScreenCurve, color: Color32) { + let draw = |run: &mut Vec, shown: bool| { + if run.len() > 1 { + // Hidden parts are a ghost line: no outline, half strength + if shown { + painter.add(egui::Shape::line(run.clone(), Stroke::new(PATH_OUTLINE_WIDTH, Color32::from_black_alpha(140)))); + } + painter.add(egui::Shape::line( + std::mem::take(run), + Stroke::new(PATH_LINE_WIDTH, if shown { color } else { color.gamma_multiply(PATH_HIDDEN_OPACITY) }), + )); + } + run.clear(); + }; + for segment in curve { + // Runs of samples the view shows (or hides) alike, joined at the sample where that changes + let (mut run, mut shown) = (Vec::new(), true); + for sample in segment { + match *sample { + Some((at, visible)) => { + if visible != shown && !run.is_empty() { + run.push(at); + draw(&mut run, shown); + } + shown = visible; + run.push(at); + } + None => draw(&mut run, shown), + } + } + draw(&mut run, shown); } } -/// Dashed preview of a straight segment. -fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { - let p = ui.painter_at(rect); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(2.5, Color32::from_black_alpha(120)), 6.0, 4.0)); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); +/// The layer's other paths (lit under the pointer), then the edited path with its points, the next segment's preview and the pen cursor +fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Response, uv: bool, show: impl Fn(&TextureCraftApp, Vec3) -> Option) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let hint = tr("Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels"); + // Wrapped to the view: the hint is longer than a narrow split view + let at = rect.left_bottom() + PATH_HINT_OFFSET; + let wrap = (rect.right() - at.x - PATH_HINT_MARGIN).max(PATH_HINT_MIN_WIDTH); + let hint = painter.layout(hint.to_string(), egui::FontId::proportional(PATH_HINT_FONT_SIZE), tk.viewport_text, wrap); + painter.galley(at - vec2(0.0, hint.size().y), hint, tk.viewport_text); + + let hover = resp.hover_pos(); + let hit = hover.map(|at| (at, path_hit(app, ui, (rect, uv), at, &show))); + for (eid, i, other) in other_paths(app).iter().filter(|(_, _, other)| other.uv == uv) { + let curve = curve_on_screen(app, ui, (rect, uv, true), other, Some((*eid, *i)), &show); + // The path a click opens lights up + let opened = matches!(hit, Some((_, PathHit::Stored(e, n))) if (e, n) == (*eid, *i)); + draw_path_curve(&painter, &curve, if opened { Color32::WHITE } else { Color32::WHITE.gamma_multiply(PATH_STORED_OPACITY) }); + } + + let path = &app.session.tool.path; + if path.uv == uv { + draw_path_curve(&painter, &curve_on_screen(app, ui, (rect, uv, true), path, path.editing, &show), tk.viewport_accent); + let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); + if !path.closed + && !handles.is_empty() + && let Some((to, PathHit::Miss)) = hit + { + let mut next = handles.clone(); + next.push(to); + if let Some(segment) = screen_segments(&next, false).last() { + rubber_band(ui, rect, segment); + } + } + + for (i, handle) in handles.iter().enumerate() { + // Small markers: the curve is what the user is shaping + let hovered = hover.is_some_and(|m| m.distance(*handle) < HANDLE_GRAB); + let radius = if hovered { PATH_POINT_RADIUS + PATH_POINT_HOVER_GROWTH } else { PATH_POINT_RADIUS }; + if path.selected == Some(i) { + painter.circle(*handle, radius + PATH_POINT_SELECTED_GROWTH, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(160))); + } else { + painter.circle(*handle, radius, Color32::from_black_alpha(110), Stroke::new(1.0, Color32::from_white_alpha(if hovered { 230 } else { 150 }))); + } + } + } + + if let Some((at, hit)) = hit + && !ui.input(|i| i.modifiers.command) + { + if let PathHit::Curve(_, on) = hit { + // Where the click inserts its point + painter.circle(on, PATH_POINT_RADIUS, Color32::from_black_alpha(60), Stroke::new(1.0, Color32::from_white_alpha(110))); + } + path_cursor(ui, &painter, at, matches!(hit, PathHit::Curve(..))); + } +} + +/// The Path tool's pointer: a pen with its nib at `at`, and a plus when a click inserts a point +fn path_cursor(ui: &Ui, painter: &egui::Painter, at: Pos2, insert: bool) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + let glyph = |icon: &str, size: f32, color: Color32| painter.layout_no_wrap(icon.to_string(), egui::FontId::proportional(size), color); + for (offset, color) in [(PATH_CURSOR_SHADOW_OFFSET, Color32::from_black_alpha(200)), (egui::Vec2::ZERO, Color32::WHITE)] { + // The pen's nib is the bottom left corner of the drawn glyph + let pen = glyph(egui_phosphor::regular::PEN_NIB, PATH_CURSOR_SIZE, color); + let origin = at + offset - pen.mesh_bounds.left_bottom().to_vec2(); + let right = origin + pen.mesh_bounds.right_bottom().to_vec2(); + painter.galley(origin, pen, color); + if insert { + let plus = glyph(egui_phosphor::regular::PLUS, PATH_CURSOR_SIZE * PATH_CURSOR_PLUS_SCALE, color); + painter.galley(right + vec2(PATH_CURSOR_PLUS_GAP, 0.0) - plus.mesh_bounds.left_top().to_vec2(), plus, color); + } + } +} + +/// Dashed preview of a line still to be painted +fn rubber_band(ui: &Ui, rect: Rect, line: &[Pos2]) { + let painter = ui.painter_at(rect); + painter.add(egui::Shape::dashed_line(line, Stroke::new(2.5, Color32::from_black_alpha(120)), RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + painter.add(egui::Shape::dashed_line(line, Stroke::new(1.0, Color32::from_white_alpha(200)), RUBBER_BAND_DASH, RUBBER_BAND_GAP)); } /// V held with the Clone tool in painting mode: clicks set the clone source. @@ -1214,7 +1464,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Painting in UV space let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; if painting && path_tool { - path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); + path_input(app, ui, &response, (rect, true), |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { diff --git a/crates/ui-egui/tests/path_in_view.rs b/crates/ui-egui/tests/path_in_view.rs new file mode 100644 index 00000000..d044ff4d --- /dev/null +++ b/crates/ui-egui/tests/path_in_view.rs @@ -0,0 +1,144 @@ +//! The Path tool in the 2D view: placing previews the path, and points are edited where they are drawn + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +type AppHarness<'a> = Harness<'a, TextureCraftApp>; + +// Three points left to right across the middle of the 2D view's texture +const A: Pos2 = pos2(600.0, 500.0); +const B: Pos2 = pos2(700.0, 500.0); +const C: Pos2 = pos2(800.0, 500.0); + +fn harness() -> AppHarness<'static> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + // Tall enough that the 2D view's texture square takes A, B and C + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.layout = ViewLayout::Only2D; + h.run_steps(4); + h +} + +fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { + let events = &mut h.input_mut().events; + events.push(Event::PointerMoved(pos)); + if let Some(pressed) = pressed { + events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.step(); +} + +fn click(h: &mut AppHarness<'_>, at: Pos2) { + pointer(h, at, Some(true)); + pointer(h, at, Some(false)); + h.run_steps(2); +} + +fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { + pointer(h, from, Some(true)); + for k in 1..=6 { + pointer(h, from + (to - from) * (k as f32 / 6.0), None); + } + pointer(h, to, Some(false)); + h.run_steps(2); +} + +fn key(h: &mut AppHarness<'_>, key: Key) { + h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// The path sublayers of the selected layer: (id, stored paths) +fn path_sublayers(h: &AppHarness<'_>) -> Vec<(LayerId, usize)> { + let s = &h.state().session; + let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap(); + layer.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id, p.len()))).collect() +} + +/// Channel images painted in path sublayer `eid` +fn painted_channels(h: &AppHarness<'_>, eid: LayerId) -> usize { + h.state().session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == eid).count() +} + +#[test] +fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() { + let mut h = harness(); + let steps = h.state().session.history_labels().len(); + for at in [A, B, C] { + click(&mut h, at); + } + assert_eq!(h.state().session.tool.path.points.len(), 3); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("the preview is a path in a path sublayer: {:?}", path_sublayers(&h)) }; + assert!(painted_channels(&h, eid) > 0, "the preview painted"); + assert_eq!(h.state().session.history_labels().len(), steps, "no undo step while placing"); + key(&mut h, Key::Enter); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert_eq!(h.state().session.undo_label(), Some("Path")); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), vec![(eid, 1)]); +} + +#[test] +fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + key(&mut h, Key::Enter); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("one path") }; + let stored = |h: &AppHarness<'_>| h.state().session.paths(eid).unwrap()[0].points.clone(); + let before = stored(&h); + let steps = h.state().session.history_labels().len(); + + // A click on the path's curve opens it for editing without repainting it + click(&mut h, A.lerp(B, 0.5)); + assert_eq!(h.state().session.tool.path.editing, Some((eid, 0))); + assert_eq!(h.state().session.history_labels().len(), steps, "opening a path repaints nothing"); + + drag(&mut h, B, B + egui::vec2(0.0, 60.0)); + let after = stored(&h); + assert_eq!(after.len(), 3); + assert_eq!((after[0], after[2]), (before[0], before[2])); + assert!(after[1][1] > before[1][1], "the dragged point moved down: {:?} -> {:?}", before[1], after[1]); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "the edit is one step"); +} + +#[test] +fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + let path = |h: &AppHarness<'_>| h.state().session.tool.path.clone(); + let before = path(&h).points; + click(&mut h, B.lerp(C, 0.5)); + let after = path(&h); + assert_eq!(after.points.len(), 4, "inserted, not appended"); + assert_eq!(after.selected, Some(2)); + assert_eq!((after.points[1], after.points[3]), (before[1], before[2])); + assert!(after.points[2].x > before[1].x && after.points[2].x < before[2].x); + + // B, not A: clicking the first point closes the path + click(&mut h, B); + assert_eq!(path(&h).selected, Some(1)); + key(&mut h, Key::Backspace); + assert_eq!(path(&h).points, vec![after.points[0], after.points[2], after.points[3]]); + + // Undo brings the point back and keeps the path; again, the inserted point goes + let undo = |h: &mut AppHarness<'_>| { + h.input_mut().events.push(Event::Key { key: Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }); + h.run_steps(2); + }; + undo(&mut h); + assert_eq!(path(&h).points, after.points); + undo(&mut h); + assert_eq!(path(&h).points, before); + assert!(!path_sublayers(&h).is_empty(), "the path is still there"); +} From 2f2ba103be59b27d10b7ff8b5849a05e5cd0d95d Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 20:39:32 -0500 Subject: [PATCH 2/6] Fix non-Linux path benchmark imports --- crates/engine/tests/it/path_perf.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/it/path_perf.rs b/crates/engine/tests/it/path_perf.rs index 7c103b18..8c81a9ea 100644 --- a/crates/engine/tests/it/path_perf.rs +++ b/crates/engine/tests/it/path_perf.rs @@ -3,8 +3,8 @@ use std::time::{Duration, Instant}; use serde_json::json; -use texturecraft_engine::geom::{glam::Vec2, primitives}; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::execute; +use texturecraft_engine::geom::glam::Vec2; fn median_ms(samples: &mut [Duration]) -> f64 { samples.sort_unstable(); @@ -72,6 +72,9 @@ fn resident_kib() -> usize { #[test] #[ignore = "release memory soak: 1,000 edits across 100 canceled previews"] fn path_preview_memory_soak() { + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives; + let mut session = Session::new_project("Path soak", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); session.viewport = Vec2::splat(400.0); session.update(); From f17e524776a39e92ddd3ee4d8baf0d41332d2764 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:07:57 -0500 Subject: [PATCH 3/6] Fix path undo repaint and restore Apply --- crates/engine/src/path_tool.rs | 35 +++++---- crates/engine/src/session.rs | 14 +++- crates/engine/tests/it/path_perf.rs | 4 ++ crates/engine/tests/it/path_tool.rs | 90 ++++++++++++++++++++++-- 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/path_surface_cache.rs | 1 + crates/ui-egui/src/toolbar.rs | 5 ++ crates/ui-egui/tests/it/path_in_view.rs | 34 +++++++++ 16 files changed, 170 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index e0c23a40..84c7ca5e 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -166,6 +166,7 @@ pub fn specs() -> Vec { ] } +/// Set the curve from command parameters, then preview or commit it in the supplied viewport fn path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "tool.path"; if s.tool.tool != Tool::Path { @@ -232,6 +233,7 @@ fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathSh Ok((eid, i, shape)) } +/// Finish any draft and load a stored path's geometry and paint settings for live editing fn edit_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.edit"; let (eid, index, shape) = path_ref(s, CMD, p)?; @@ -249,6 +251,7 @@ fn edit_path(s: &mut Session, p: &Value) -> Result { Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() })) } +/// Remove one stored curve and repaint its sublayer as an atomic document edit fn remove_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.remove"; let (eid, index, _) = path_ref(s, CMD, p)?; @@ -592,27 +595,31 @@ impl Session { self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) } - /// Undo (`back`) or redo the edited path's last point change, false when there is none; with no points left the path is gone - pub(crate) fn step_path(&mut self, back: bool) -> bool { + /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history + pub(crate) fn step_path(&mut self, back: bool) -> Result { if self.tool.tool != Tool::Path { - return false; + return Ok(false); } - let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; - // A checkpoint taken by a press that changed nothing isn't a step - while from.last().is_some_and(|s| s.same_curve(&self.tool.path)) { - from.pop(); - } - let Some(state) = from.pop() else { return false }; + // Skip no-change checkpoints without consuming history until the repaint succeeds + let from = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) }; let path = &mut self.tool.path; - let now = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state }); - to.push(now); + let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() }); + if let Err(error) = self.path_live() { + self.tool.path = previous; + return Err(error); + } if self.tool.path.points.is_empty() { self.stop_path_edit(); + } else { + let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; + from.truncate(index); + to.push(previous); } - true + Ok(true) } /// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes @@ -989,7 +996,7 @@ mod tests { session.tool.path.points = vec![Vec3::ZERO; MAX_PATH_POINTS]; session.path_checkpoint(); assert!(!session.path_step_pending(true)); - assert!(!session.step_path(true)); + assert!(!session.step_path(true).unwrap()); for index in 0..crate::session::MAX_HISTORY + 10 { session.path_checkpoint(); @@ -999,7 +1006,7 @@ mod tests { assert_eq!(session.path_steps.0.len(), crate::session::MAX_HISTORY); assert_eq!(session.path_steps.0.iter().map(|state| state.points.len()).sum::(), crate::session::MAX_HISTORY * MAX_PATH_POINTS); session.path_checkpoint(); - assert!(session.step_path(true), "a no-change checkpoint does not consume an undo"); + assert!(session.step_path(true).unwrap(), "a no-change checkpoint does not consume an undo"); assert_eq!(session.tool.path.points[0].x, (crate::session::MAX_HISTORY + 9) as f32); } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 61b1f238..41bfacbb 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -647,24 +647,32 @@ impl Session { } } + /// Whether a point edit, an uncommitted path preview, or a document edit can be undone pub fn can_undo(&self) -> bool { !self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true) } + + /// Whether a point edit or document edit can be restored pub fn can_redo(&self) -> bool { !self.redo.is_empty() || self.path_step_pending(false) } + + /// Label of the next undo action, giving an active path's point edits and preview priority pub fn undo_label(&self) -> Option<&str> { if self.path_draft.is_some() || self.path_step_pending(true) { return Some(crate::path_tool::NEW_PATH_LABEL); } self.undo.last().map(|(l, _)| l.as_str()) } + + /// Label of the next redo action, giving an active path's point history priority pub fn redo_label(&self) -> Option<&str> { if self.path_step_pending(false) { return Some(crate::path_tool::NEW_PATH_LABEL); } self.redo.last().map(|(l, _)| l.as_str()) } + /// The undone steps, the next one to redo first. pub fn redo_labels(&self) -> Vec { self.redo.iter().rev().map(|(l, _)| l.clone()).collect() @@ -673,13 +681,14 @@ impl Session { self.undo.iter().map(|(l, _)| l.clone()).collect() } + /// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order pub fn undo(&mut self) -> Result { // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); self.end_polygon_fill_box(); // While a path is edited, undo steps back through its point changes first - if self.step_path(true) { + if self.step_path(true)? { return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); } @@ -699,12 +708,13 @@ impl Session { Ok(label) } + /// Restore a point edit and its pixels before considering document redo pub fn redo(&mut self) -> Result { // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); self.end_polygon_fill_box(); - if self.step_path(false) { + if self.step_path(false)? { return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); } diff --git a/crates/engine/tests/it/path_perf.rs b/crates/engine/tests/it/path_perf.rs index 8c81a9ea..ac09c302 100644 --- a/crates/engine/tests/it/path_perf.rs +++ b/crates/engine/tests/it/path_perf.rs @@ -6,11 +6,13 @@ use serde_json::json; use texturecraft_engine::execute; use texturecraft_engine::geom::glam::Vec2; +/// Sort a nonempty timing sample in place and report its middle value in milliseconds fn median_ms(samples: &mut [Duration]) -> f64 { samples.sort_unstable(); samples[samples.len() / 2].as_secs_f64() * 1_000.0 } +/// Separate repaint cost from dirty-tile and full-set compositing across representative brush sizes #[test] #[ignore = "release benchmark: two texture resolutions and brush sizes"] fn path_preview_timings() { @@ -62,12 +64,14 @@ fn path_preview_timings() { } } +/// Observe resident memory without treating allocator-retained pages as a leak #[cfg(target_os = "linux")] fn resident_kib() -> usize { let status = std::fs::read_to_string("/proc/self/status").unwrap(); status.lines().find_map(|line| line.strip_prefix("VmRSS:").and_then(|rest| rest.split_whitespace().next()).and_then(|n| n.parse().ok())).unwrap() } +/// Check that repeated canceled previews release tile buffers and leave no document history #[cfg(target_os = "linux")] #[test] #[ignore = "release memory soak: 1,000 edits across 100 canceled previews"] diff --git a/crates/engine/tests/it/path_tool.rs b/crates/engine/tests/it/path_tool.rs index 93c1ff93..77b2edbd 100644 --- a/crates/engine/tests/it/path_tool.rs +++ b/crates/engine/tests/it/path_tool.rs @@ -517,6 +517,7 @@ fn preview_uses_the_commands_explicit_viewport() { assert_eq!(preview, path_pixels(&direct)); } +/// Headless history commands must restore geometry and pixels before any frame or subsequent edit #[test] fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { let mut session = session(wall()); @@ -524,33 +525,110 @@ fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); let original = session.tool.path.points.clone(); + let original_pixels = session.doc.pixels.clone(); let history = session.history_labels().len(); session.insert_path_point(1, Vec3::new(0.5, 0.5, 0.0)); session.path_live().unwrap(); let inserted = session.tool.path.points.clone(); + let inserted_pixels = session.doc.pixels.clone(); session.move_path_point(1, Vec3::new(0.5, 0.6, 0.0), true); session.move_path_point(1, Vec3::new(0.5, 0.7, 0.0), false); session.path_live().unwrap(); let moved = session.tool.path.points.clone(); + let moved_pixels = session.doc.pixels.clone(); session.remove_selected_path_point(); session.path_live().unwrap(); let removed = session.tool.path.points.clone(); + let removed_pixels = session.doc.pixels.clone(); - for expected in [&moved, &inserted, &original] { - session.undo().unwrap(); - session.path_live().unwrap(); + for (expected, pixels) in [(&moved, &moved_pixels), (&inserted, &inserted_pixels), (&original, &original_pixels)] { + execute(&mut session, "edit.undo", &Value::Null).unwrap(); assert_eq!(&session.tool.path.points, expected); assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); } session.select_path_point(0); assert!(session.can_redo(), "selection must preserve point redo"); - for expected in [&inserted, &moved, &removed] { - session.redo().unwrap(); - session.path_live().unwrap(); + for (expected, pixels) in [(&inserted, &inserted_pixels), (&moved, &moved_pixels), (&removed, &removed_pixels)] { + execute(&mut session, "edit.redo", &Value::Null).unwrap(); assert_eq!(&session.tool.path.points, expected); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); } assert_eq!(session.history_labels().len(), history + 1, "all point edits share one document step"); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(session.paths(effect).unwrap()[0].points, moved.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, moved_pixels.layers, "a subsequent command keeps the undone path pixels"); +} + +/// A bad path above the edited one must not consume undo or redo when repainting fails +#[test] +fn point_history_repaint_errors_preserve_the_edit_and_can_be_retried() { + use texturecraft_engine::core::{EffectKind, LayerId}; + + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let effect = LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap(); + let paint = session.paths(effect).unwrap()[1].paint.clone(); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + + for (command, expected) in [("edit.undo", &original), ("edit.redo", &moved)] { + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = Value::Null; + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = (session.history_labels(), session.redo_labels()); + + let error = execute(&mut session, command, &Value::Null).unwrap_err(); + + assert!(error.to_string().contains("unreadable path settings"), "{error}"); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!((session.history_labels(), session.redo_labels()), history); + + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = paint.clone(); + execute(&mut session, command, &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected, "the failed step remains available"); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + } +} + +/// Point history repaints an uncommitted preview without creating document undo steps +#[test] +fn draft_point_history_repaints_immediately_and_undoing_all_points_cancels() { + let mut session = session(wall()); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + let before = session.doc.clone(); + let history = session.history_labels(); + session.append_path_point(Vec3::new(0.2, 0.5, 0.0), true); + session.path_live().unwrap(); + let one_point = session.doc.clone(); + session.append_path_point(Vec3::new(0.8, 0.5, 0.0), true); + session.path_live().unwrap(); + let two_points = session.doc.clone(); + + for (command, expected) in [("edit.undo", &one_point), ("edit.redo", &two_points), ("edit.undo", &one_point), ("edit.undo", &before)] { + execute(&mut session, command, &Value::Null).unwrap(); + + assert_eq!(session.doc.project, expected.project); + assert_eq!(session.doc.pixels.layers, expected.pixels.layers); + assert_eq!(session.history_labels(), history); + } + assert!(session.tool.path.points.is_empty()); + assert!(session.tool.path.editing.is_none()); } #[test] diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 902ab3e7..d6441751 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -84,6 +84,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "مستوى تباين الخواص"), ("Antialiasing", "تنعيم الحواف"), ("Aperture", "فتحة العدسة"), + ("Apply", "تطبيق"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), ("Auto", "تلقائي"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 10d0224f..5fe3f757 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Anisotropiestärke"), ("Antialiasing", "Kantenglättung"), ("Aperture", "Blende"), + ("Apply", "Anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 9d933b5a..99bd5ded 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -84,6 +84,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nivel de anisotropía"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), + ("Apply", "Aplicar"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5e31ba0c..3b1628a7 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -90,6 +90,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Niveau d'anisotropie"), ("Antialiasing", "Anticrénelage"), ("Aperture", "Ouverture"), + ("Apply", "Appliquer"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index cbcafb67..b3407b5d 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Livello anisotropia"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), + ("Apply", "Applica"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 492dd84b..51cba39d 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -90,6 +90,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "異方性レベル"), ("Antialiasing", "アンチエイリアス"), ("Aperture", "絞り"), + ("Apply", "適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), ("Auto", "自動"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 9961d9eb..114f576d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "이방성 레벨"), ("Antialiasing", "안티앨리어싱"), ("Aperture", "조리개"), + ("Apply", "적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), ("Auto", "자동"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index d99c3e55..ee92fbc1 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nível de anisotropia"), ("Antialiasing", "Antisserrilhamento"), ("Aperture", "Abertura"), + ("Apply", "Aplicar"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c1194cf5..54719ab9 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -75,6 +75,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "各向异性强度"), ("Antialiasing", "抗锯齿"), ("Aperture", "光圈"), + ("Apply", "应用"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), ("Auto", "自动"), diff --git a/crates/ui-egui/src/path_surface_cache.rs b/crates/ui-egui/src/path_surface_cache.rs index e16e3a36..9b216083 100644 --- a/crates/ui-egui/src/path_surface_cache.rs +++ b/crates/ui-egui/src/path_surface_cache.rs @@ -17,6 +17,7 @@ pub(crate) struct PathSurfaceCache { } impl PathSurfaceCache { + /// Reuse an unchanged curve and retain it for this pass; UV or missing paths have no surface curve pub(crate) fn get(&mut self, session: &Session, effect: LayerId, index: usize) -> Option { let shape = session.paths(effect)?.get(index)?; let key = (session.mesh_id, effect, index); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e9e6fc60..133240d6 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -328,6 +328,7 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let path = &app.session.tool.path; let (closed, fill) = (path.closed, path.fill); let selected = path.selected.is_some_and(|i| i < path.points.len()); + let has_points = !path.points.is_empty(); if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() { app.session.set_path_closed(!closed); } @@ -340,6 +341,10 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() { app.session.remove_selected_path_point(); } + + if ui.add_enabled_ui(has_points, |ui| icon_button(ui, ic::CHECK, tr("Apply"), false, button_size)).inner.clicked() { + app.run("tool.path", json!({"commit": true})); + } } pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index d044ff4d..8604ced8 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -2,6 +2,7 @@ use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; @@ -15,6 +16,7 @@ const A: Pos2 = pos2(600.0, 500.0); const B: Pos2 = pos2(700.0, 500.0); const C: Pos2 = pos2(800.0, 500.0); +/// A Path tool session whose texture fills the test pointer coordinates in the 2D view fn harness() -> AppHarness<'static> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); @@ -26,6 +28,7 @@ fn harness() -> AppHarness<'static> { h } +/// Advance one input frame, optionally changing the primary button's state fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { let events = &mut h.input_mut().events; events.push(Event::PointerMoved(pos)); @@ -35,12 +38,14 @@ fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { h.step(); } +/// Send a complete pointer click and allow the resulting preview to update fn click(h: &mut AppHarness<'_>, at: Pos2) { pointer(h, at, Some(true)); pointer(h, at, Some(false)); h.run_steps(2); } +/// Move through several frames so the test exercises drag grouping as well as its final position fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { pointer(h, from, Some(true)); for k in 1..=6 { @@ -50,6 +55,7 @@ fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { h.run_steps(2); } +/// Dispatch an unmodified tool key and settle the resulting UI state fn key(h: &mut AppHarness<'_>, key: Key) { h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); h.run_steps(2); @@ -85,6 +91,34 @@ fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() { assert_eq!(path_sublayers(&h), vec![(eid, 1)]); } +/// Applying with the pointer commits the preview without leaving the current texture set +#[test] +fn apply_button_commits_the_path_in_the_current_texture_set() { + let mut h = harness(); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + let steps = h.state().session.history_labels().len(); + let texture_set = h.state().session.ts(); + for at in [A, B, C] { + click(&mut h, at); + } + let paths = path_sublayers(&h); + let preview = h.state().session.doc.pixels.layers.clone(); + + // Path controls share the horizontally scrolling brush toolbar + h.get_all_by_label("Apply").next().unwrap().scroll_to_me(); + h.run_steps(30); + assert!(!h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + h.get_all_by_label("Apply").next().unwrap().click(); + h.run_steps(2); + + assert_eq!(h.state().session.ts(), texture_set); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), paths); + assert_eq!(h.state().session.doc.pixels.layers, preview); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); +} + #[test] fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { let mut h = harness(); From 4612e1aa8705d33a9d3489d891723103814656ab Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:32:02 -0500 Subject: [PATCH 4/6] Handle texture deltas in path cache test --- crates/ui-egui/src/viewport.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index da04c4d4..0974eba7 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1885,7 +1885,7 @@ mod tests { // Every path in the selection stays warm, and leaving it releases every sampled buffer for _ in 0..4 { - let _ = context.run_ui(Default::default(), |ui| { + let output = context.run_ui(Default::default(), |ui| { for index in 0..8 { let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); assert!(surface.iter().map(Vec::len).sum::() > 10); @@ -1896,22 +1896,26 @@ mod tests { } } }); + + // This cache lifecycle test has no renderer to consume texture updates + output.drop_without_applying_deltas(); } let EffectKind::Path(paths) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") }; for path in paths { path.viewport = [800.0, 800.0]; } - let _ = context.run_ui(Default::default(), |ui| { + let output = context.run_ui(Default::default(), |ui| { for (index, previous) in previous.iter_mut().enumerate() { let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); assert!(previous.upgrade().is_none(), "editing a path releases its obsolete samples"); *previous = Arc::downgrade(&surface); } }); + output.drop_without_applying_deltas(); for _ in 0..2 { - let _ = context.run_pass(Default::default(), |_| {}); + context.run_pass(Default::default(), |_| {}).drop_without_applying_deltas(); } assert!(previous.iter().all(|surface| surface.upgrade().is_none()), "unused path surfaces must be freed while the window stays open"); From 906b22630f686db66184e766d864c86ffe70a466 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:59:49 -0500 Subject: [PATCH 5/6] Fix History jumps through pending path edits --- crates/engine/src/path_tool.rs | 29 ++++++ crates/ui-egui/src/windows.rs | 3 +- crates/ui-egui/tests/it/history_panel.rs | 109 +++++++++++++++++++++++ 3 files changed, 140 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 84c7ca5e..d252d430 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -595,6 +595,35 @@ impl Session { self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) } + /// Undo calls needed to move back through document history, including pending path operations. + /// With zero document steps, only an uncommitted draft is canceled; stored edits stay applied. + pub fn history_undo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 && self.path_draft.is_none() { + return 0; + } + + let mut steps = document_steps; + let mut current = &self.tool.path; + if self.tool.tool == Tool::Path { + for state in self.path_steps.0.iter().rev() { + if state.same_curve(current) { + continue; + } + + steps = steps.saturating_add(1); + + // Restoring an empty curve cancels the draft and clears point history in the same undo + if state.points.is_empty() { + return steps; + } + + current = state; + } + } + + steps.saturating_add(usize::from(self.path_draft.is_some())) + } + /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history pub(crate) fn step_path(&mut self, back: bool) -> Result { if self.tool.tool != Tool::Path { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 068cd0bf..8359b80b 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -367,7 +367,8 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { // Each row is the state after that many steps let steps = done_count - row as i64; if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - jump = steps; + // Undo consumes point edits and drafts before the document rows shown here + jump = if steps >= 0 { app.session.history_undo_steps(steps as usize) as i64 } else { steps }; } } }); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index b3f134f0..6a1988b3 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -3,9 +3,118 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; +/// Show document history so row clicks exercise the same command dispatch as the application +fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.focus(Panel::History); + harness.run_steps(4); + harness +} + +/// Three document rows provide an intermediate target that detects both short and excessive jumps +fn renamed_session() -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + session +} + +/// Canceling a preview can be its own undo or part of undoing the first placed point +#[test] +fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { + for placed in [false, true] { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + if placed { + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + for point in [Vec3::new(0.2, 0.5, 0.0), Vec3::new(0.5, 0.3, 0.0), Vec3::new(0.8, 0.5, 0.0)] { + session.append_path_point(point, true); + session.path_live().unwrap(); + } + } else { + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + } + session.path_checkpoint(); + let mut harness = history_harness(session); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), 2); + assert!(harness.state().session.tool.path.points.is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); + } +} + +/// A row jump traverses point history, while the Undo and Redo buttons still take one point step +#[test] +fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + session.move_path_point(0, original[0], true); + session.path_live().unwrap(); + session.path_checkpoint(); + let done = session.history_labels().len(); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, moved); + assert_eq!(harness.state().session.history_labels().len(), done); + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_by_label("Edit path 1").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), done - 1); + assert!(harness.state().session.tool.path.points.is_empty()); +} + +/// Returning to the current document row cancels a draft without undoing a document step +#[test] +fn clicking_the_current_history_row_cancels_a_draft() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + let mut harness = history_harness(session); + + harness.get_by_label("Project opened").click(); + harness.run_steps(3); + + assert!(harness.state().session.tool.path.points.is_empty()); + assert!(harness.state().session.history_labels().is_empty()); + assert!(harness.state().session.redo_labels().is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); +} + #[test] fn clicking_a_history_step_returns_to_it() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); From 76b9a30f630258604fd655fa3c24ccd4e9b7bb96 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 22:23:51 -0500 Subject: [PATCH 6/6] Guard stored paths and fix History redo jumps --- crates/engine/src/path_tool.rs | 59 ++++++++++++++++------- crates/engine/tests/it/path_tool.rs | 60 ++++++++++++++++++++++++ crates/ui-egui/src/windows.rs | 8 +++- crates/ui-egui/tests/it/history_panel.rs | 44 +++++++++++++++++ crates/ui-egui/tests/it/path_in_view.rs | 26 ++++++++++ 5 files changed, 178 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index d252d430..60eee97f 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -532,6 +532,11 @@ impl Session { return None; } + // A click in the other view must not replace a committed path's coordinate space + if self.tool.path.editing.is_some() && self.path_draft.is_none() && self.tool.path.uv != uv { + return None; + } + self.path_checkpoint(); self.tool.path.push(point, uv); self.tool.path.selected = self.tool.path.points.len().checked_sub(1); @@ -602,26 +607,46 @@ impl Session { return 0; } - let mut steps = document_steps; - let mut current = &self.tool.path; - if self.tool.tool == Tool::Path { - for state in self.path_steps.0.iter().rev() { - if state.same_curve(current) { - continue; - } + let (point_steps, clears_path) = self.path_steps_before_document(true); + let cancel_draft = self.path_draft.is_some() && !clears_path; + document_steps.saturating_add(point_steps).saturating_add(usize::from(cancel_draft)) + } - steps = steps.saturating_add(1); - - // Restoring an empty curve cancels the draft and clears point history in the same undo - if state.points.is_empty() { - return steps; - } - - current = state; - } + /// Redo calls needed to move forward through document history, including pending point edits. + /// Unlike undo, document redo cancels any remaining draft in the same call. + pub fn history_redo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 { + return 0; } - steps.saturating_add(usize::from(self.path_draft.is_some())) + document_steps.saturating_add(self.path_steps_before_document(false).0) + } + + /// Count pending point steps and whether their last step clears the path + fn path_steps_before_document(&self, back: bool) -> (usize, bool) { + if self.tool.tool != Tool::Path { + return (0, false); + } + + let states = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let mut steps = 0usize; + let mut current = &self.tool.path; + for state in states.iter().rev() { + if state.same_curve(current) { + continue; + } + + steps = steps.saturating_add(1); + + // Restoring an empty curve cancels the draft and clears point history in the same step + if state.points.is_empty() { + return (steps, true); + } + + current = state; + } + + (steps, false) } /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history diff --git a/crates/engine/tests/it/path_tool.rs b/crates/engine/tests/it/path_tool.rs index 77b2edbd..bb4ea764 100644 --- a/crates/engine/tests/it/path_tool.rs +++ b/crates/engine/tests/it/path_tool.rs @@ -517,6 +517,66 @@ fn preview_uses_the_commands_explicit_viewport() { assert_eq!(preview, path_pixels(&direct)); } +/// An opposite-view placement must preserve the stored curve, painted pixels and point redo +#[test] +fn stored_paths_ignore_point_placement_from_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let params = + if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true}) } else { json!({"points": [[140, 210], [260, 210]], "commit": true}) }; + let report = execute(&mut session, "tool.path", ¶ms).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let (effect, index) = session.tool.path.editing.unwrap(); + let uv_point = Vec3::new(0.5, 0.6, 0.0); + let world_point = session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos; + assert_eq!(session.append_path_point(if uv { uv_point } else { world_point }, uv), Some(2)); + session.path_live().unwrap(); + let extended = session.tool.path.points.clone(); + session.undo().unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + + let placed = session.append_path_point(if uv { world_point } else { uv_point }, !uv); + session.path_live().unwrap(); + + assert_eq!(session.paths(effect).unwrap()[index].uv, uv, "the stored path must keep its coordinate space"); + assert_eq!(placed, None); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.doc.pixels.masks, before.pixels.masks); + assert_eq!(session.history_labels(), history); + assert!(session.can_redo(), "ignored placement must preserve point redo"); + + session.redo().unwrap(); + assert_eq!(session.tool.path.points, extended); + } +} + +/// A new, uncommitted curve can still switch views and cancel without changing the document +#[test] +fn draft_paths_can_switch_to_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let before = session.doc.clone(); + let history = session.history_labels(); + let params = if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]}) } else { json!({"points": [[140, 210], [260, 210]]}) }; + execute(&mut session, "tool.path", ¶ms).unwrap(); + let point = if uv { session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos } else { Vec3::new(0.5, 0.6, 0.0) }; + + assert_eq!(session.append_path_point(point, !uv), Some(0)); + session.path_live().unwrap(); + + assert_eq!(session.tool.path.points, vec![point]); + assert_eq!(session.tool.path.uv, !uv); + assert_eq!(session.history_labels(), history); + session.cancel_path(); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + } +} + /// Headless history commands must restore geometry and pixels before any frame or subsequent edit #[test] fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8359b80b..9cc8a5f9 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -367,8 +367,12 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { // Each row is the state after that many steps let steps = done_count - row as i64; if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - // Undo consumes point edits and drafts before the document rows shown here - jump = if steps >= 0 { app.session.history_undo_steps(steps as usize) as i64 } else { steps }; + // Point history is consumed before the document rows shown here + jump = if steps >= 0 { + app.session.history_undo_steps(steps as usize) as i64 + } else { + -(app.session.history_redo_steps((-steps) as usize) as i64) + }; } } }); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 6a1988b3..7103161b 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -97,6 +97,50 @@ fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() assert!(harness.state().session.tool.path.points.is_empty()); } +/// Incomplete filled curves keep point redo separate from the document redo rows +#[test] +fn history_redo_jump_accounts_for_point_steps_without_changing_single_steps() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let report = + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.3], [0.8, 0.5]], "closed": true, "fill": true, "commit": true})).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + let done = session.history_labels().len(); + execute(&mut session, "edit.undo", &json!({"steps": 3})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + + // Partial filled shapes do not repaint; their undo/redo leaves document redo available + for points in [json!([[0.2, 0.5], [0.8, 0.5]]), json!([[0.2, 0.5]]), json!([[0.2, 0.5], [0.8, 0.5]])] { + session.path_checkpoint(); + execute(&mut session, "tool.path", &json!({"uvPoints": points})).unwrap(); + } + for _ in 0..3 { + session.undo().unwrap(); + } + assert_eq!(session.redo_labels().len(), 3); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points.len(), 2); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + + harness.get_all_by_label("Rename layer (undone)").last().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step C"); + assert_eq!(harness.state().session.history_labels().len(), done); + assert!(harness.state().session.redo_labels().is_empty()); + assert!(harness.state().session.tool.path.points.is_empty()); +} + /// Returning to the current document row cancels a draft without undoing a document step #[test] fn clicking_the_current_history_row_cancels_a_draft() { diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index 8604ced8..819a5468 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -144,6 +144,32 @@ fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { assert_eq!(h.state().session.history_labels().len(), steps + 1, "the edit is one step"); } +#[test] +fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { + let mut session = + texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [260, 210]], "viewport": [400, 400], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(4); + let view_3d = harness.state().viewport_rect; + let view_2d_center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + + click(&mut harness, view_2d_center); + + assert_eq!(harness.state().session.tool.path, path); + assert_eq!(harness.state().session.doc.project, before.project); + assert_eq!(harness.state().session.doc.pixels.layers, before.pixels.layers); + assert_eq!(harness.state().session.history_labels(), history); +} + #[test] fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() { let mut h = harness();