diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index e4404588..577da682 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -730,7 +730,7 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c kind: &e.kind, blend: e.blend, opacity: e.opacity, - data: if matches!(e.kind, EffectKind::Paint) { tile_of(inp, img, tx, ty, channel) } else { None }, + data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, preview: previews(inp, target), } }) @@ -1109,7 +1109,7 @@ impl<'a, 'b> Texel<'a, 'b> { for e in m.effects.iter().skip(skip) { let o = e.opacity.clamp(0.0, 1.0); match e.kind { - EffectKind::Paint => { + EffectKind::Paint | EffectKind::Path(_) => { let (mut pv, mut cov) = match e.data.as_deref() { Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), @@ -1420,7 +1420,7 @@ impl<'a, 'b> Texel<'a, 'b> { fn content_effect(&mut self, e: &EffectPlan, c: &ChanPlan, v: [f32; 3], cov: f32) -> ([f32; 3], f32) { let o = e.opacity.clamp(0.0, 1.0); match e.kind { - EffectKind::Paint => { + EffectKind::Paint | EffectKind::Path(_) => { let (p, pc) = self.painted(e.data.as_deref(), c, e.preview); over(c, e.blend, v, cov, p, pc * o) } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ed263910..86c34356 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -860,6 +860,9 @@ impl Filter { pub enum EffectKind { /// Painted grayscale (mask) or material (content) pixels keyed by the effect id. Paint, + /// A path sublayer: pixels keyed by the effect id like [`EffectKind::Paint`], but painted + /// only from its stored paths and repainted whenever one is added, edited or removed. + Path(Vec), /// A uniform or procedural grayscale fill. Fill { source: Source, @@ -887,6 +890,21 @@ pub enum EffectKind { Anchor, } +/// One path of a path sublayer: its control points and how it was painted. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct PathShape { + /// Surface positions (3D view) or texture coordinates with z = 0 (2D view). + pub points: Vec<[f32; 3]>, + pub uv: bool, + pub closed: bool, + /// A closed path fills its interior instead of stroking the curve. + pub fill: bool, + /// Viewport size (pixels) the path was painted in. + pub viewport: [f32; 2], + /// Brush, material and camera the engine paints the path with (owned by the engine). + pub paint: serde_json::Value, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum CompareOp { LesserThan, @@ -898,6 +916,7 @@ impl EffectKind { pub fn name(&self) -> &'static str { match self { EffectKind::Paint => "Paint", + EffectKind::Path(_) => "Path", EffectKind::Fill { .. } => "Fill", EffectKind::Generator(_) => "Generator", EffectKind::Levels(_) => "Levels", @@ -915,10 +934,15 @@ impl EffectKind { match self { EffectKind::Material(_) | EffectKind::Anchor => Some(true), EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => Some(false), - EffectKind::Paint | EffectKind::Levels(_) | EffectKind::Filter(_) => None, + EffectKind::Paint | EffectKind::Path(_) | EffectKind::Levels(_) | EffectKind::Filter(_) => None, } } + /// Holds painted pixels keyed by the effect id (paint and path sublayers). + pub fn painted(&self) -> bool { + matches!(self, EffectKind::Paint | EffectKind::Path(_)) + } + /// Anchor points read by this effect's sources. fn reads_anchor(&self) -> bool { match self { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 89120e08..8c13a18d 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -16,7 +16,7 @@ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, - MaskBackground, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, + MaskBackground, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BakeMatch, BakeSettings, BakedMap, Camera, DepthOfField, DirectionMode, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 9baa23c8..e69e9f40 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -37,6 +37,14 @@ fn effect_json(s: &Session, e: &Effect, content: bool) -> Value { ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }) } EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]), + EffectKind::Path(paths) => { + ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::>()); + ej["tiles"] = json!(if content { + s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::() + } else { + s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0) + }); + } EffectKind::Paint if content => { ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::()) } diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 9d58ce3f..fc314941 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -57,6 +57,14 @@ impl Session { let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e); Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) }) } + // Path sublayers are painted only from their stored paths. + Some((owner, eff)) if matches!(eff.kind, EffectKind::Path(_)) && self.painting_paths => { + let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e); + Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) }) + } + Some((_, eff)) if matches!(eff.kind, EffectKind::Path(_)) => { + Err(EngineError::Other("a path sublayer holds paths only: edit them with the Path tool, or paint on a paint sublayer".into())) + } _ => Err(EngineError::Other("the selected effect is not a paint effect".into())), }, StackTarget::Mask => { diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 0826f6e1..ca0de3f2 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -1,14 +1,22 @@ //! The Path tool: control points placed on the surface (3D view) or in texture space (2D view) -//! and a smooth curve through them, committed as one brush stroke, or, when closed and filled, -//! as an antialiased lasso fill of the visible surface (3D) or of the UV region (2D). +//! and a smooth curve through them, painted with the brush, or, when closed and filled, as an +//! antialiased lasso fill of the visible surface (3D) or of the UV region (2D). +//! +//! Paths are non-destructive: a committed path is stored in a path sublayer +//! ([`EffectKind::Path`]) that is repainted from its paths whenever one is added, edited +//! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). + +use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; +use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_paint::{Lasso, fill_coverage, spline}; +use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; -use crate::commands::{CommandSpec, always, bad, boolp}; -use crate::session::Tool; +use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; +use crate::session::{StackTarget, Tool}; use crate::tool_cmds::{points_param, set_tool, viewport_of}; use crate::{EngineError, Result, Session, cmd}; @@ -29,6 +37,9 @@ pub struct PathState { pub closed: bool, /// 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. + #[serde(default)] + pub editing: Option<(LayerId, usize)>, } impl PathState { @@ -44,16 +55,46 @@ impl PathState { } } +/// What a stored path is painted with ([`PathShape::paint`]). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct PathPaint { + brush: BrushSettings, + values: BTreeMap, + enabled: BTreeSet, + mask_value: f32, + camera: OrbitCamera, +} + pub fn specs() -> Vec { - vec![cmd!( - "tool.path", - "Path", - ["Tools"], - Some("7"), - "{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit paints the curve with the current brush, or fills a closed, filled path", - always, - path - )] + vec![ + cmd!( + "tool.path", + "Path", + ["Tools"], + Some("7"), + "{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit adds the path to the selected path sublayer (or a new one), painted with the current brush or filled when closed and filled. While a stored path is edited (path.edit), changes repaint it at once", + always, + path + ), + cmd!( + "path.edit", + "Edit path", + ["Tools"], + None, + "{effect: path sublayer id, index: path index} — loads a stored path into the Path tool (with its brush and material); changes to it repaint the sublayer live until commit or clear", + has_layer, + edit_path + ), + cmd!( + "path.remove", + "Remove path", + ["Tools"], + None, + "{effect: path sublayer id, index: path index} — removes a stored path and repaints its sublayer", + has_layer, + remove_path + ), + ] } fn path(s: &mut Session, p: &Value) -> Result { @@ -64,6 +105,7 @@ fn path(s: &mut Session, p: &Value) -> Result { let vp = viewport_of(s, p); if boolp(p, "clear") == Some(true) { s.tool.path.points.clear(); + s.tool.path.editing = None; } let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) { (Some(pts), _) => Some(( @@ -95,10 +137,67 @@ fn path(s: &mut Session, p: &Value) -> Result { s.update(); r } else { + if s.path_live()? { + s.update(); + } Value::Null }; let st = &s.tool.path; - Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "committed": committed })) + 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 })) +} + +/// The `effect` and `index` params naming a stored path, with the path. +fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathShape)> { + let eid = LayerId(u64p(p, "effect").ok_or_else(|| bad(cmd, "`effect` (a path sublayer id) is required"))?); + let index = u64p(p, "index").ok_or_else(|| bad(cmd, "`index` is required"))?; + let shapes = s.paths(eid).ok_or_else(|| bad(cmd, format!("{} is not a path sublayer", eid.0)))?; + let i = + usize::try_from(index).ok().filter(|i| *i < shapes.len()).ok_or_else(|| bad(cmd, format!("no path {index} (the sublayer has {})", shapes.len())))?; + let shape = shapes.get(i).cloned().ok_or_else(|| bad(cmd, format!("no path {index}")))?; + Ok((eid, i, shape)) +} + +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)?; + 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.target = StackTarget::Effect(eid); + Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() })) +} + +fn remove_path(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.remove"; + let (eid, index, _) = path_ref(s, CMD, p)?; + s.edit("Remove path", |s| { + if let Some(Effect { kind: EffectKind::Path(shapes), .. }) = s.doc.project.effect_mut(eid) + && index < shapes.len() + { + shapes.remove(index); + } + s.render_paths(eid) + })?; + if s.tool.path.editing.is_some_and(|(e, _)| e == eid) { + s.stop_path_edit(); + } + s.update(); + Ok(json!({ "effect": eid.0, "paths": s.paths(eid).map_or(0, <[_]>::len) })) +} + +fn read_paint(shape: &PathShape) -> Result { + serde_json::from_value(shape.paint.clone()).map_err(|e| EngineError::Other(format!("unreadable path settings: {e}"))) +} + +/// 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 } } /// NDC (y up) to viewport pixels (origin top-left). @@ -118,8 +217,169 @@ impl Session { path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect() } - /// Paint the path with the current brush (or fill it when closed and filled), then clear it. + /// 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) { + Some((_, Effect { kind: EffectKind::Path(shapes), .. })) => Some(shapes), + _ => None, + } + } + + /// The Path tool's curve with the current brush and material, as painted from `camera`. + fn path_shape(&self, camera: OrbitCamera, viewport: Vec2) -> PathShape { + let (t, path) = (&self.tool, &self.tool.path); + let paint = PathPaint { brush: t.brush.clone(), values: t.values.clone(), enabled: t.enabled.clone(), mask_value: t.mask_value, camera }; + PathShape { + points: path.points.iter().map(|p| p.to_array()).collect(), + uv: path.uv, + closed: path.closed, + fill: path.fill, + viewport: viewport.to_array(), + paint: serde_json::to_value(paint).unwrap_or_default(), + } + } + + /// 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. pub fn commit_path(&mut self, viewport: Vec2) -> Result { + let shape = self.path_shape(self.camera, viewport); + let editing = self.tool.path.editing; + let label = editing.map_or("Path".to_string(), |(_, i)| format!("Edit path {}", i + 1)); + let out = self.edit_merging(&label, editing.is_some(), |s| { + let (eid, index) = match editing { + Some(at) => at, + None => (s.path_effect()?, usize::MAX), + }; + 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; + 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. + 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 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 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) + }); + if unchanged { + return Ok(false); + } + let shape = self.path_shape(self.camera, self.viewport); + self.edit_merging(&format!("Edit path {}", index + 1), true, |s| s.put_path(eid, index, shape))?; + 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(); + } + } + + /// 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 { + let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?; + let p = &self.doc.project; + let mask = match self.target { + StackTarget::Effect(e) => match p.effect(e) { + Some((_, x)) if matches!(x.kind, EffectKind::Path(_)) => return Ok(e), + Some((owner, _)) => !p.layer(owner)?.content_effects.iter().any(|x| x.id == e), + None => false, + }, + StackTarget::Mask => true, + StackTarget::Content => false, + }; + // An instance's content and (unless it has its own) mask belong to its source. + let owner = if mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) }; + let eid = self.doc.project.alloc_id(); + let l = self.doc.project.layer_mut(owner)?; + let e = Effect::new(eid, EffectKind::Path(Vec::new())); + if mask { + l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(e); + } else if l.is_group() { + return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", l.name))); + } else { + l.content_effects.push(e); + } + Ok(eid) + } + + /// 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 { + let index = match self.doc.project.effect_mut(eid) { + Some(Effect { kind: EffectKind::Path(shapes), .. }) => match shapes.get_mut(index) { + Some(slot) => { + *slot = shape; + index + } + None => { + shapes.push(shape); + shapes.len() - 1 + } + }, + _ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))), + }; + let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({})); + out["effect"] = json!(eid.0); + out["index"] = json!(index); + Ok(out) + } + + /// Repaint path sublayer `eid` from scratch with its stored paths, bottom to top. Runs + /// inside the caller's undo step. + fn render_paths(&mut self, eid: LayerId) -> Result> { + let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec(); + self.doc.pixels.masks.remove(&eid); + self.doc.pixels.layers.retain(|(id, _), _| *id != eid); + // Each path goes through the regular stroke and fill code with its own settings; their + // own history entries are dropped (the caller records one step). + let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); + let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo)); + self.target = StackTarget::Effect(eid); + self.quick_mask.editing = false; + self.tool.tool = Tool::Path; + self.painting_paths = true; + let out = shapes.iter().map(|sh| self.paint_shape(sh)).collect(); + self.painting_paths = false; + (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; + (self.undo, self.redo) = history; + out + } + + fn paint_shape(&mut self, shape: &PathShape) -> Result { + let paint = read_paint(shape)?; + 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.tool.path = state_of(shape); + self.paint_path(Vec2::from_array(shape.viewport).max(Vec2::splat(16.0)).min(Vec2::splat(16384.0))) + } + + /// Paint the Path tool's curve with the current brush (or fill it when closed and filled) + /// into the paint target. + fn paint_path(&mut self, viewport: Vec2) -> Result { let (uv, closed) = (self.tool.path.uv, self.tool.path.closed); let fill = closed && self.tool.path.fill; let pts: Vec = self.path_view_points(viewport).into_iter().flatten().collect(); @@ -130,15 +390,13 @@ impl Session { return Err(EngineError::Other("a filled path needs at least three points".into())); } let curve = spline(&pts, closed, if uv { STEP_UV } else { STEP_PX }); - let out = if fill { + Ok(if fill { json!({ "filledTiles": self.lasso_fill(curve, uv, viewport)? }) } else if uv { json!({ "tiles": self.stroke_uv_points(&curve)? }) } else { json!({ "stamps": self.stroke_points(&curve, viewport)? }) - }; - self.tool.path.points.clear(); - Ok(out) + }) } /// Fill the inside of `poly`: viewport pixels over the visible surface, or texture diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 14891a8f..65ab2dc9 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -339,6 +339,8 @@ pub struct Session { pub images: texturecraft_compose::ImageStore, /// Temporary texel mask limiting paint strokes (not saved, not in the history). pub quick_mask: crate::quick_mask::QuickMask, + /// A path sublayer is being repainted from its paths (the only way to paint into one). + pub(crate) painting_paths: bool, pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -389,6 +391,7 @@ impl Session { clipboard: None, images: Default::default(), quick_mask: Default::default(), + painting_paths: false, path: None, modified: false, revision: 1, @@ -607,6 +610,8 @@ impl Session { pub fn undo(&mut self) -> Result { self.cancel_stroke(); + // 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); self.after_history(&now); @@ -617,6 +622,8 @@ impl Session { pub fn redo(&mut self) -> Result { self.cancel_stroke(); + // 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); self.after_history(&now); diff --git a/crates/engine/tests/path_tool.rs b/crates/engine/tests/path_tool.rs index cb54142e..d2bb95b5 100644 --- a/crates/engine/tests/path_tool.rs +++ b/crates/engine/tests/path_tool.rs @@ -143,3 +143,78 @@ fn radial_symmetry_paints_copies_around_the_axis() { s.camera.yaw = std::f32::consts::PI; assert!(red_at(&s, 200.0, 200.0), "the radial copy on the back"); } + +/// The selected layer's content path sublayers: (effect id, stored paths). +fn path_sublayers(s: &Session) -> Vec<(u64, usize)> { + let l = s.doc.project.layer(s.selected_layer().unwrap()).unwrap(); + l.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id.0, p.len()))).collect() +} + +#[test] +fn committed_paths_stay_editable_in_a_path_sublayer() { + 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(); + assert_eq!(r["committed"]["index"], 0); + assert_eq!(path_sublayers(&s), vec![(eid, 1)]); + // The next path goes into the same (selected) sublayer. + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.9], [0.8, 0.9]], "commit": true})).unwrap(); + assert_eq!((r["committed"]["effect"].as_u64(), r["committed"]["index"].as_u64()), (Some(eid), Some(1))); + assert_eq!(path_sublayers(&s), vec![(eid, 2)]); + assert!(red_at(&s, 200.0, 180.0) && red_uv(&s, 0.5, 0.9)); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains("\"paths\""), "inspect lists the paths"); + // Paths are saved with the project; editing a loaded path repaints only once it changes. + let saved = serde_json::to_string(&s.doc.project).unwrap(); + s.doc.project = serde_json::from_str(&saved).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 2)]); + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert!(!s.path_live().unwrap(), "a loaded path matches its settings"); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + + // Manual strokes can't paint over a path sublayer. + let err = execute(&mut s, "tool.stroke", &json!({"points": [[200, 240]]})).unwrap_err().to_string(); + assert!(err.contains("path sublayer"), "{err}"); + + // Edit the first path: moving its points repaints it live, the other path stays. + let undo_before = s.history_labels().len(); + let r = execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(r["points"], 3); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 250], [200, 230], [260, 250]]})).unwrap(); + assert_eq!(r["editing"]["index"], 0, "{r}"); + assert!(red_at(&s, 200.0, 230.0), "the edited curve shows at once"); + assert!(!red_at(&s, 200.0, 180.0), "the old curve is gone"); + assert!(red_uv(&s, 0.5, 0.9), "the other path is kept"); + // Brush changes repaint too, merged into the same undo step. + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + execute(&mut s, "tool.path", &json!({})).unwrap(); + assert!(!red_at(&s, 200.0, 230.0), "repainted with the new color"); + assert_eq!(s.history_labels().len(), undo_before + 1); + execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + assert_eq!(s.history_labels().len(), undo_before + 1, "one step for the whole edit"); + assert!(s.tool.path.editing.is_none() && s.tool.path.points.is_empty()); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 230.0), "undo restores the original path"); + + // Remove a path: its paint goes, the sublayer keeps the rest. + execute(&mut s, "path.remove", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 1)]); + assert!(!red_at(&s, 200.0, 180.0) && red_uv(&s, 0.5, 0.9)); + assert!(execute(&mut s, "path.edit", &json!({"effect": eid, "index": 5})).is_err()); + assert!(execute(&mut s, "path.remove", &json!({"effect": 999999, "index": 0})).is_err()); +} + +#[test] +fn undo_while_editing_a_path_stops_the_edit() { + 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, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 250], [200, 230], [260, 250]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.tool.path.editing.is_none()); + assert!(!s.path_live().unwrap(), "nothing repaints over the undone state"); + s.update(); + assert!(red_at(&s, 200.0, 180.0)); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ba2ddcfd..4db25e9e 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1658,6 +1658,29 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(RichText::new(hint).color(tk.text_dim)); tool_properties(app, ui); } + EffectKind::Path(paths) => { + ui.label( + RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) + .color(tk.text_dim), + ); + let editing = app.session.tool.path.editing; + for i in 0..paths.len() { + ui.horizontal(|ui| { + let on = editing == Some((eid, i)); + if ui.selectable_label(on, format!("{} {}", tr("Path"), i + 1)).on_hover_text(tr("Edit")).clicked() { + if on { + app.run("tool.path", json!({"clear": true})); + } else { + app.run("path.edit", json!({"effect": id, "index": i})); + } + } + if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { + app.run("path.remove", json!({"effect": id, "index": i})); + } + }); + } + tool_properties(app, ui); + } EffectKind::Filter(f) => filter_properties(app, ui, id, f), other => { ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 04c7a3d9..f9106d57 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -176,6 +176,7 @@ mod tests { // Effect, view and camera names the engine gives. k.extend([ "Paint", + "Path", "Fill", "Generator", "Levels", diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 75c795b3..4c3409ba 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -955,4 +955,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"), ("Twill weave", "نسيج مائل"), ("Save the changes to {name} first?", "هل تريد حفظ التغييرات في {name} أولًا؟"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "تبقى المسارات قابلة للتعديل: اختر مسارًا لتحريك نقاطه أو تغيير فرشاته ومادته، فتُعاد رسم الطبقة الفرعية فورًا. أضف المسارات بأداة المسار.", + ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b0341184..002b0773 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1010,4 +1010,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"), ("Twill weave", "Köperbindung"), ("Save the changes to {name} first?", "Änderungen an {name} zuerst speichern?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Pfade bleiben bearbeitbar: Wähle einen, um seine Punkte zu verschieben oder Pinsel und Material zu ändern, und die Unterebene wird sofort neu gemalt. Füge Pfade mit dem Pfad-Werkzeug hinzu.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index df2151d9..aafaf2af 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -995,4 +995,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"), ("Twill weave", "Tejido de sarga"), ("Save the changes to {name} first?", "¿Guardar primero los cambios de {name}?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Los trazados siguen siendo editables: elige uno para mover sus puntos o cambiar su pincel y material, y la subcapa se vuelve a pintar al instante. Añade trazados con la herramienta Trazado.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 2b943710..dae13fa6 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1010,4 +1010,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"), ("Twill weave", "Armure sergé"), ("Save the changes to {name} first?", "Enregistrer d'abord les modifications de {name} ?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Les tracés restent modifiables : choisissez-en un pour déplacer ses points ou changer sa brosse et sa matière, et la sous-couche se repeint aussitôt. Ajoutez des tracés avec l'outil Tracé.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 5192aef7..7853a9de 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1004,4 +1004,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"), ("Twill weave", "Tessuto a saia"), ("Save the changes to {name} first?", "Salvare prima le modifiche a {name}?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "I tracciati restano modificabili: scegline uno per spostarne i punti o cambiarne pennello e materiale, e il sottolivello si ridipinge subito. Aggiungi tracciati con lo strumento Tracciato.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 9b1d9be9..bd3f938d 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -977,4 +977,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"), ("Twill weave", "綾織り"), ("Save the changes to {name} first?", "先に {name} の変更を保存しますか?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "パスは編集可能なままです。パスを選んで点を移動したりブラシやマテリアルを変えたりすると、サブレイヤーがすぐに描き直されます。パスはパスツールで追加します。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df30e1a5..4852b47d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -962,4 +962,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"), ("Twill weave", "능직"), ("Save the changes to {name} first?", "먼저 {name}의 변경 사항을 저장할까요?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "패스는 계속 편집할 수 있습니다. 패스를 골라 점을 옮기거나 브러시와 재질을 바꾸면 하위 레이어가 바로 다시 칠해집니다. 패스는 패스 도구로 추가합니다.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 097a6e00..9504e2c8 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -992,4 +992,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"), ("Twill weave", "Tecido sarja"), ("Save the changes to {name} first?", "Salvar primeiro as alterações em {name}?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "Os caminhos continuam editáveis: escolha um para mover seus pontos ou mudar seu pincel e material, e a subcamada é repintada na hora. Adicione caminhos com a ferramenta Caminho.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index b21bebf9..eaf5ad5a 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -908,4 +908,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"), ("Twill weave", "斜纹织物"), ("Save the changes to {name} first?", "是否先保存对 {name} 的更改?"), + ( + "Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.", + "路径始终可编辑:选择一条路径来移动其控制点或更改其笔刷和材质,子图层会立即重绘。使用路径工具添加路径。", + ), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e6e99567..632616c2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -387,6 +387,11 @@ 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. + if let Err(e) = self.session.path_live() { + self.session.stop_path_edit(); + self.toast(e.to_string(), true); + } profile::drive(self, ctx); self.toasts.retain(|t| t.until > now); self.profiler.logic_ms = (now_ms() - t0) as f32; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 3f83a1ad..73144d81 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -302,6 +302,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if i.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); + app.session.tool.path.editing = None; } }); for id in fire {