diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4ee21784..128c5ea7 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -93,7 +93,7 @@ OR Apache-2.0) is noted in the table. | Exact clipping of filled paths by a convex polygon | `crates/geom/src/clip.rs` | I. E. Sutherland and G. W. Hodgman, "Reentrant Polygon Clipping", CACM 17(1), 1974, extended to Bézier segments (de Casteljau subdivision, roots bracketed by critical points) | Published algorithm; no code taken. | | Shape morphing (cubic normalization, subdivision to equal segment counts, winding and start-point alignment) | `crates/geom/src/morph.rs` | Standard curve-blending techniques from the public computer-graphics literature (de Casteljau subdivision, exact degree elevation) | | | Affine QR decomposition for tweening | `crates/geom/src/affine.rs` | Standard linear algebra | | -| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines) | `crates/geom/src/fit.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. | +| Least-squares cubic Bézier curve fitting (Pencil "Smooth", Brush centre lines and outlines; deleting a motion path point refits its neighbours, `Path::merge_at`) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs` | P. J. Schneider, *An Algorithm for Automatically Fitting Digitized Curves*, Graphics Gems (1990) | Ported from PhotoCraft's mask tracer and adapted for open strokes. Published algorithm. | | Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). | | Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. | | Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a819c63..a0f94d58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +* **Motion path points and moving the whole path** (ADR 0038, the second slice of motion + paths). With the Subselection tool, double-click a motion path to add a point (the curve and + the motion don't change), and Shift-click to select several anchors. Delete removes them: the + path refits through the rest, and the ends stay, because they are where the motion starts and + ends. Right-click makes points smooth or corners, or straightens the path. The Pen's + Alt-click adds a point to a motion path or to a selected shape. Ctrl-drag (⌘-drag) the path + or its object to move the whole path, and Properties › Path start moves it by number; the + timing stays exactly. Headless: `motion.add_point`, `motion.delete_points`, + `motion.convert_point`, `motion.move_path`, and `anchors` in `motion.info`. Not yet: + anchors tied to frames (spatial keys; ADR 0038 explains why), a marquee over path anchors, + nudging and transforming a whole path. + * **AniCraft in a web browser** (ADR 0036, first slice; `docs/web.md`). The editor builds for WebAssembly and runs in a page: `scripts/build-web.sh` (or `.ps1`) makes `web/`, which any static server can serve. The module is about 9 MB, 3.3 MB gzipped. diff --git a/crates/doc/src/motion.rs b/crates/doc/src/motion.rs index a215f1e4..60123b4b 100644 --- a/crates/doc/src/motion.rs +++ b/crates/doc/src/motion.rs @@ -505,6 +505,39 @@ impl MotionTween { true } + /// Moves the whole motion by `d`: the path and every X/Y key, so the object travels the same + /// way, `d` over, on the same frames (the timing compares positions only with each other). + /// An axis without keys follows the object's own position, which the caller moves. False, + /// with nothing changed, when a key or the path would leave the X/Y range. + pub fn translate(&mut self, d: Vec2) -> bool { + if !d.is_finite() { + return false; + } + let path = match &self.path { + Some(p) => match motion_path(&p.transformed(&Affine::translate(d.x, d.y))) { + Some(moved) => Some(moved), + None => return false, + }, + None => None, + }; + let shift = |p: Property| if p == Property::X { d.x } else { d.y }; + let fits = [Property::X, Property::Y].into_iter().all(|p| self.track(p).is_none_or(|t| t.keys.iter().all(|k| p.range().contains(&(k.value + shift(p)))))); + if !fits { + return false; + } + for p in [Property::X, Property::Y] { + if let Some(t) = self.track_mut(p) { + for k in &mut t.keys { + k.value += shift(p); + } + } + } + if path.is_some() { + self.path = path; + } + true + } + pub fn track(&self, p: Property) -> Option<&Track> { self.tracks.iter().find(|t| t.property == p) } @@ -928,6 +961,30 @@ mod tests { } } + #[test] + fn moving_the_whole_path_keeps_the_motion_and_its_timing() { + let base = el(1, 0.0, 0.0); + let mut m = diagonal(Easing::CubicBezier(0.2, 0.9, 0.4, 1.3)); + assert!(m.set_path(&quarter(100.0), &Props::of(&base), 20)); + m.orient = true; + m.set_key(Property::Y, 8, 30.0, 0.0); + let d = Vec2::new(-37.5, 212.25); + let mut moved = m.clone(); + assert!(moved.translate(d)); + let moved_base = el(1, d.x, d.y); + for i in 0..=100 { + let f = i as f32 / 4.0; + let (a, b) = (m.apply(&base, f), moved.apply(&moved_base, f)); + assert!((a.transform.translation() + d).distance(b.transform.translation()) < 1e-3, "frame {f}"); + assert!((a.transform.decompose().rotation - b.transform.decompose().rotation).abs() < 1e-4, "frame {f}: the turn is the same"); + } + assert_eq!(moved.key_frames(), m.key_frames(), "no key moves in time"); + // Out of range: refused, nothing changed. + let before = moved.clone(); + assert!(!moved.translate(Vec2::new(2e6, 0.0)) && !moved.translate(Vec2::new(f32::NAN, 0.0))); + assert_eq!(moved, before); + } + #[test] fn a_path_from_the_tracks_moves_the_same_way() { // Right 100 over 10 frames, then down 100 over the next 10. diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 0e5e8f8b..3b864a9f 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -25,6 +25,10 @@ pub fn specs() -> Vec { c("motion.set_path", "Edit Motion Path", "", None, "{d: SVG path data in stage space (its first subpath; ends are the start and end positions), layer?, frame?}", true, set_path), c("motion.clear_path", "Remove Motion Path", "", None, "{layer?, frame?}: back to the straight path the X/Y curves trace", true, clear_path), c("motion.orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}: turn the object as its motion path turns", true, orient), + c("motion.add_point", "Add Motion Path Point", "", None, "{x, y, slop? (stage units, default 4) | segment, t (0..1), layer?, frame?}: an anchor on the motion path, its shape unchanged → {anchor}", true, add_point), + c("motion.delete_points", "Delete Motion Path Points", "", None, "{anchors: [index, ..] (as motion.info lists them; the ends stay), layer?, frame?}: the path refits through the rest", true, delete_points), + c("motion.convert_point", "Convert Motion Path Point", "", None, "{anchor, smooth: bool, layer?, frame?}: smooth (handles in line) or corner (handles on the anchor)", true, convert_point), + c("motion.move_path", "Move Motion Path", "", None, "{dx, dy, layer?, frame?}: the whole path with its object, keeping the timing", true, move_path), ] } @@ -193,7 +197,149 @@ fn path_summary(m: &MotionTween) -> Value { let Some(path) = &m.path else { return json!({"path": null, "orient": m.orient}) }; let len = anicraft_geom::walk::CurveWalk::new(path).map_or(0.0, |w| w.length()); let (a, b) = anicraft_doc::motion::path_ends(path).unwrap_or_default(); - json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "orient": m.orient}) + // Anchor `i` is path command `i` (a motion path is a move and cubics). + let anchors: Vec<[f32; 2]> = path.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect(); + json!({"path": path.to_svg(), "segments": path.cmds.len().saturating_sub(1), "length": len, "start": [a.x, a.y], "end": [b.x, b.y], "anchors": anchors, "orient": m.orient}) +} + +/// Edits the motion path at the target frame with `edit`: the tween's own path, or the straight +/// one its X/Y curves trace (which the edit makes its own, as on the stage). The ends' keys stay +/// unless the edit moved an end, so the timing is kept. Returns what `edit` returned and the +/// path's summary. +fn edit_path(s: &mut Session, p: &Value, edit: impl FnOnce(&mut anicraft_geom::Path) -> Result) -> Result<(T, Value)> { + let (kf, _) = motion_span(s, p)?; + let base = base_of(kf)?; + let last = kf.duration.saturating_sub(1); + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + let mut path = m.path.clone().or_else(|| m.path_from_tracks(&base)).ok_or_else(|| EngineError::State("the object doesn't move yet, so it has no path: move it at a later frame of the tween first".into()))?; + let out = edit(&mut path)?; + if !m.set_path(&path, &base, last) { + return Err(EngineError::State("that would leave the motion path with no length".into())); + } + Ok((out, path_summary(m))) +} + +/// An anchor index param, checked against the path. +fn anchor_index(p: &Value, key: &str, path: &anicraft_geom::Path) -> Result { + let i = opt_u64(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required")))?; + let n = path.cmds.len(); + usize::try_from(i).ok().filter(|i| *i < n).ok_or_else(|| EngineError::Param(format!("no anchor {i} on this motion path (it has {n}, from 0 at the start)"))) +} + +/// Where `motion.add_point` adds: near a stage point, or at a curve parameter of a segment. +enum PointAt { + Near(Vec2), + On(usize, f32), +} + +fn add_point(s: &mut Session, p: &Value) -> Result { + let at = match (opt_f32(p, "x")?, opt_f32(p, "y")?, opt_u64(p, "segment")?) { + (Some(x), Some(y), None) => PointAt::Near(Vec2::new(x, y)), + (None, None, Some(seg)) => PointAt::On(usize::try_from(seg).unwrap_or(usize::MAX), opt_f32(p, "t")?.ok_or_else(|| EngineError::Param("param 't' is required with 'segment' (0..1 along it)".into()))?), + _ => return Err(EngineError::Param("give either x and y (a point on the path) or segment and t".into())), + }; + let slop = opt_f32(p, "slop")?.unwrap_or(4.0); + if !(0.0..=1000.0).contains(&slop) { + return Err(EngineError::Param("param 'slop' must be between 0 and 1000".into())); + } + let (anchor, mut v) = edit_path(s, p, |path| { + if path.cmds.len() > anicraft_doc::motion::MAX_PATH_SEGMENTS { + return Err(EngineError::State(format!("a motion path holds at most {} segments", anicraft_doc::motion::MAX_PATH_SEGMENTS))); + } + let (cmd, t) = match at { + PointAt::Near(q) => { + let (cmd, t, dist) = path.nearest_segment(q, &Affine::IDENTITY).ok_or_else(|| EngineError::State("the motion path has no segments".into()))?; + if dist > slop { + return Err(EngineError::State(format!("({}, {}) is not on the motion path ({dist:.1} px away)", q.x, q.y))); + } + (cmd, t) + } + PointAt::On(seg, t) => { + if !(0.0..=1.0).contains(&t) { + return Err(EngineError::Param("param 't' must be between 0 and 1".into())); + } + if seg == 0 || seg >= path.cmds.len() { + return Err(EngineError::Param(format!("no segment {seg} on this motion path (1 to {})", path.cmds.len().saturating_sub(1)))); + } + (seg, t) + } + }; + // At an existing anchor there is nothing to add. + if !(1e-3..=1.0 - 1e-3).contains(&t) { + return Err(EngineError::State("there is already an anchor there".into())); + } + if !path.split_segment(cmd, t) { + return Err(EngineError::State("cannot add a point there".into())); + } + // The new anchor ends the first half. + Ok(cmd) + })?; + v["anchor"] = json!(anchor); + Ok(v) +} + +fn delete_points(s: &mut Session, p: &Value) -> Result { + let wanted = opt_u64_list(p, "anchors")?.ok_or_else(|| EngineError::Param("param 'anchors' is required (a list of anchor indices)".into()))?; + if wanted.is_empty() { + return Err(EngineError::Param("param 'anchors' lists no anchor".into())); + } + let ((deleted, kept_ends), mut v) = edit_path(s, p, |path| { + let n = path.cmds.len(); + let mut set = std::collections::BTreeSet::new(); + for &i in wanted.iter().take(100_000) { + match usize::try_from(i).ok().filter(|i| *i < n) { + Some(i) => set.insert(i), + None => return Err(EngineError::Param(format!("no anchor {i} on this motion path (it has {n}, from 0 at the start)"))), + }; + } + let ends = set.remove(&0) | set.remove(&n.saturating_sub(1)); + if set.is_empty() { + return Err(EngineError::State("the ends of a motion path can't be deleted: they are where the motion starts and ends. Drag them to move them, or Straighten the path".into())); + } + // Last first, so the indices still to go stay where they were. + let mut deleted = 0; + for i in set.into_iter().rev() { + if path.merge_at(i) { + deleted += 1; + } + } + Ok((deleted, ends)) + })?; + v["deleted"] = json!(deleted); + v["kept_ends"] = json!(kept_ends); + Ok(v) +} + +fn convert_point(s: &mut Session, p: &Value) -> Result { + let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required (true: smooth, false: corner)".into()))?; + let (changed, mut v) = edit_path(s, p, |path| { + let a = anchor_index(p, "anchor", path)?; + Ok(if smooth { path.make_smooth(a) } else { path.make_corner(a) }) + })?; + v["changed"] = json!(changed); + Ok(v) +} + +fn move_path(s: &mut Session, p: &Value) -> Result { + let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?); + if !d.is_finite() { + return Err(EngineError::Param("params 'dx' and 'dy' must be finite".into())); + } + let (kf, _) = motion_span(s, p)?; + let i = kf.motion.as_ref().and_then(|m| m.target_index(&kf.elements)).ok_or_else(|| EngineError::State("the motion tween's object is no longer on its keyframe".into()))?; + let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?; + if !m.translate(d) { + return Err(EngineError::Param("that would move the motion path beyond ±1000000 px".into())); + } + // The object's own place moves too (an axis without keys is where it is). + if let Some(slot) = kf.elements.get_mut(i) { + let mut el = (**slot).clone(); + el.transform = Affine::translate(d.x, d.y).mul(&el.transform); + *slot = Arc::new(el); + } + let mut v = kf.motion.as_ref().map_or(Value::Null, path_summary); + v["moved"] = json!([d.x, d.y]); + Ok(v) } fn clear_path(s: &mut Session, p: &Value) -> Result { @@ -413,5 +559,7 @@ fn info(s: &mut Session, p: &Value) -> Result { // Where the object is (on a motion path the X/Y values are its timing, not its place). let position = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| m.apply(e, (frame - kf.start) as f32).transform.translation()).map(|q| json!([q.x, q.y])); let path = path_summary(m); - Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path["path"], "orient": m.orient})) + // The anchors point edits address: the path's own, or the straight path's (ADR 0038). + let anchors: Vec<[f32; 2]> = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).map(|p| p.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect()).unwrap_or_default(); + Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path["path"], "anchors": anchors, "orient": m.orient})) } diff --git a/crates/engine/src/motion_path_tests.rs b/crates/engine/src/motion_path_tests.rs index dd6cf8b5..f01e57b2 100644 --- a/crates/engine/src/motion_path_tests.rs +++ b/crates/engine/src/motion_path_tests.rs @@ -203,3 +203,188 @@ fn motion_paths_round_trip_through_the_file_format() { assert_eq!(back, plain.doc); assert!(pos(&mut plain, 12).distance(Vec2::new(5.0 + 100.0 * 12.0 / 23.0, 5.0)) < 1e-3); } + +// ----- point editing and moving the whole path (ADR 0038) --------------------------------- + +/// The object's place on every frame of the span. +fn track_of(s: &mut Session) -> Vec { + (0..24).map(|f| pos(s, f)).collect() +} + +fn path_d(s: &Session) -> String { + motion(s).path.as_ref().map(|p| p.to_svg()).unwrap_or_default() +} + +/// An S through (55, -40): up from the start, over, and down to the end, with a smooth middle. +const S_CURVE: &str = "M5 5 C5 -40 30 -40 55 -40 C80 -40 105 -40 105 5"; + +#[test] +fn adding_a_point_leaves_the_curve_and_the_motion_unchanged() { + let mut s = moving(); + run(&mut s, "motion.set_path", json!({"d": HUMP})); + let before = track_of(&mut s); + let keys = motion(&s).tracks.clone(); + let steps = s.history_len(); + // On the path where the object is at frame 9, as a click there would be. + let at = pos(&mut s, 9); + let v = run(&mut s, "motion.add_point", json!({"x": at.x, "y": at.y})); + assert_eq!((v["anchor"].as_u64(), v["segments"].as_u64()), (Some(1), Some(2))); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + let new = Vec2::new(v["anchors"][1][0].as_f64().unwrap_or(0.0) as f32, v["anchors"][1][1].as_f64().unwrap_or(0.0) as f32); + assert!(new.distance(at) < 0.05, "the new anchor is where the object passes: {new:?} vs {at:?}"); + assert_eq!(motion(&s).tracks, keys, "the timing keeps its keys"); + for (f, (a, b)) in before.iter().zip(track_of(&mut s)).enumerate() { + assert!(a.distance(b) < 0.01, "frame {f}: {a:?} vs {b:?}"); + } + // By segment and curve parameter too. + let v = run(&mut s, "motion.add_point", json!({"segment": 2, "t": 0.5})); + assert_eq!((v["anchor"].as_u64(), v["segments"].as_u64()), (Some(2), Some(3))); + for (f, (a, b)) in before.iter().zip(track_of(&mut s)).enumerate() { + assert!(a.distance(b) < 0.01, "frame {f}: {a:?} vs {b:?}"); + } + // Refused: off the path, on an anchor, no such segment, mixed or missing params. + let d = path_d(&s); + for p in [ + json!({"x": 55, "y": 300}), + json!({"segment": 1, "t": 0.0}), + json!({"segment": 0, "t": 0.5}), + json!({"segment": 9, "t": 0.5}), + json!({"segment": 1, "t": 1.5}), + json!({"segment": 1}), + json!({"x": 5, "y": 5, "segment": 1, "t": 0.5}), + json!({}), + json!({"x": 5, "y": 5, "slop": -1}), + ] { + assert!(s.execute("motion.add_point", &p).is_err(), "{p}"); + } + assert_eq!(path_d(&s), d, "refusals change nothing"); +} + +#[test] +fn deleting_a_point_keeps_the_ends_and_the_timing() { + let mut s = moving(); + run(&mut s, "motion.set_path", json!({"d": S_CURVE})); + let keys = motion(&s).tracks.clone(); + let steps = s.history_len(); + let v = run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + assert_eq!((v["deleted"].as_u64(), v["segments"].as_u64(), v["kept_ends"].as_bool()), (Some(1), Some(1), Some(false))); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + assert_eq!(motion(&s).tracks, keys, "the ends didn't move, so neither did a key"); + assert!(pos(&mut s, 0).distance(Vec2::new(5.0, 5.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 5.0)) < 1e-3, "the ends stay"); + // The one cubic left still leaves straight up and comes straight down, over the top. + let Some(anicraft_geom::PathCmd::CubicTo(c1, c2, _)) = motion(&s).path.as_ref().and_then(|p| p.cmds.get(1)).copied() else { panic!("a cubic") }; + assert!((c1.x - 5.0).abs() < 1e-3 && c1.y < 5.0 && (c2.x - 105.0).abs() < 1e-3 && c2.y < 5.0, "{c1:?} {c2:?}"); + assert!(pos(&mut s, 12).y < -25.0, "still over the top: {:?}", pos(&mut s, 12)); + // The ends can't go; asking for an end and a middle point deletes the middle one. + let d = path_d(&s); + let e = s.execute("motion.delete_points", &json!({"anchors": [0, 1]})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("ends"), "{e}"); + assert_eq!(path_d(&s), d); + run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.4})); + let v = run(&mut s, "motion.delete_points", json!({"anchors": [0, 1, 2]})); + assert_eq!((v["deleted"].as_u64(), v["kept_ends"].as_bool()), (Some(1), Some(true))); + for p in [json!({"anchors": [7]}), json!({"anchors": []}), json!({"anchors": "1"}), json!({})] { + assert!(s.execute("motion.delete_points", &p).is_err(), "{p}"); + } +} + +#[test] +fn a_point_added_then_deleted_gives_the_path_back() { + let mut s = moving(); + run(&mut s, "motion.set_path", json!({"d": HUMP})); + let before = track_of(&mut s); + run(&mut s, "motion.add_point", json!({"segment": 1, "t": 0.3})); + run(&mut s, "motion.delete_points", json!({"anchors": [1]})); + for (f, (a, b)) in before.iter().zip(track_of(&mut s)).enumerate() { + assert!(a.distance(b) < 0.02, "frame {f}: {a:?} vs {b:?}"); + } +} + +#[test] +fn converting_a_point_makes_it_a_corner_or_smooth() { + let mut s = moving(); + run(&mut s, "motion.set_path", json!({"d": S_CURVE})); + let point = |s: &Session, cmd: usize, slot: u8| motion(s).path.as_ref().and_then(|p| p.point(cmd, slot)).unwrap_or_default(); + let v = run(&mut s, "motion.convert_point", json!({"anchor": 1, "smooth": false})); + assert_eq!(v["changed"], true); + let a = point(&s, 1, 0); + assert!(point(&s, 1, 2).distance(a) < 1e-4 && point(&s, 2, 1).distance(a) < 1e-4, "both handles on the anchor"); + run(&mut s, "motion.convert_point", json!({"anchor": 1, "smooth": true})); + let (i, o) = (point(&s, 1, 2) - a, point(&s, 2, 1) - a); + assert!(i.length() > 1.0 && o.length() > 1.0 && i.normalized().dot(o.normalized()) < -0.9999, "in line again: {i:?} {o:?}"); + assert!(pos(&mut s, 0).distance(Vec2::new(5.0, 5.0)) < 1e-3 && pos(&mut s, 23).distance(Vec2::new(105.0, 5.0)) < 1e-3); + for p in [json!({"anchor": 9, "smooth": true}), json!({"anchor": 1}), json!({"smooth": true})] { + assert!(s.execute("motion.convert_point", &p).is_err(), "{p}"); + } +} + +#[test] +fn editing_points_of_a_straight_motion_makes_its_path() { + let mut s = moving(); + assert!(motion(&s).path.is_none()); + let info = run(&mut s, "motion.info", json!({})); + assert_eq!(info["anchors"], json!([[5.0, 5.0], [105.0, 5.0]]), "the straight path's anchors"); + let before = track_of(&mut s); + run(&mut s, "motion.add_point", json!({"x": 55, "y": 5})); + assert!(motion(&s).path.is_some(), "the straight path became the tween's own"); + for (f, (a, b)) in before.iter().zip(track_of(&mut s)).enumerate() { + assert!(a.distance(b) < 0.01, "frame {f}: {a:?} vs {b:?}"); + } + // A tween that doesn't move has no path to edit. + let mut still = Session::default(); + run(&mut still, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + run(&mut still, "timeline.create_motion_tween", json!({})); + for (id, p) in [("motion.add_point", json!({"x": 5, "y": 5})), ("motion.delete_points", json!({"anchors": [1]})), ("motion.convert_point", json!({"anchor": 0, "smooth": true}))] { + assert!(still.execute(id, &p).is_err(), "{id}"); + } +} + +#[test] +fn moving_the_whole_path_keeps_its_shape_and_timing() { + let mut s = moving(); + run(&mut s, "motion.set_path", json!({"d": S_CURVE})); + run(&mut s, "motion.orient", json!({"orient": true})); + s.set_frame(12); + run(&mut s, "modify.rotate_cw", json!({})); + let before = track_of(&mut s); + let turns: Vec = (0..24).map(|f| rotation(&mut s, f)).collect(); + let keys = motion(&s).key_frames(); + let steps = s.history_len(); + let d = Vec2::new(-40.5, 120.25); + let v = run(&mut s, "motion.move_path", json!({"dx": d.x, "dy": d.y})); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + assert!(v["path"].as_str().is_some_and(|p| p.starts_with("M-35.5 125.25")), "{}", v["path"]); + for (f, a) in before.iter().enumerate() { + let b = pos(&mut s, f as u32); + assert!((*a + d).distance(b) < 1e-3, "frame {f}: {a:?} + d vs {b:?}"); + assert!((rotation(&mut s, f as u32) - turns[f]).abs() < 1e-3, "frame {f}: the same turn"); + } + assert_eq!(motion(&s).key_frames(), keys, "no key moved in time"); + // A drag is a gesture: one undo step for many moves; undo puts it back. + let steps = s.history_len(); + s.begin_gesture("Move Motion Path"); + for _ in 0..6 { + run(&mut s, "motion.move_path", json!({"dx": 2.5, "dy": -1})); + } + s.end_gesture(); + assert_eq!(s.history_len(), steps + 1); + assert!(pos(&mut s, 23).distance(before[23] + d + Vec2::new(15.0, -6.0)) < 1e-3); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(pos(&mut s, 23).distance(before[23]) < 1e-3); + for p in [json!({"dx": 2e6, "dy": 0}), json!({"dx": 1}), json!({"dx": "1", "dy": 0})] { + assert!(s.execute("motion.move_path", &p).is_err(), "{p}"); + } +} + +#[test] +fn moving_a_straight_motion_moves_it_all() { + // No path: the X/Y keys move; an axis without keys moves with the object itself. + let mut s = moving(); + let before = track_of(&mut s); + run(&mut s, "motion.move_path", json!({"dx": 10, "dy": 30})); + assert!(motion(&s).path.is_none(), "no path was made"); + for (f, a) in before.iter().enumerate() { + assert!((*a + Vec2::new(10.0, 30.0)).distance(pos(&mut s, f as u32)) < 1e-3, "frame {f}"); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2a5e6c37..8990dc0c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -561,6 +561,10 @@ fn panic_hunt_every_command() { json!({"orient": true, "d": "M0 0 C 1e5 -1e5 -1e5 1e5 10 10 Q 5 5 0 0 Z M 9 9 L 1 1"}), json!({"orient": "x", "d": 5, "property": "x", "value": 1e6}), json!({"orient": false, "d": "M 1e6 1e6 L -1e6 -1e6", "dx": 1e6, "dy": -1e6}), + // Motion path points (ADR 0038): ends, repeats and out-of-range anchors, segments. + json!({"anchors": [0, 1, 2, 3, u64::MAX], "anchor": 1, "smooth": true, "segment": 1, "t": 0.5}), + json!({"anchors": [1, 1, 1], "anchor": u64::MAX, "smooth": false, "segment": u64::MAX, "t": f64::NAN}), + json!({"x": 75, "y": 0, "slop": 1000, "anchors": [1], "anchor": 0, "smooth": true, "dx": -0.5, "dy": 3}), // Brush strokes: huge tips over long drags, specks, pressure at the limits. json!({"points": [[0, 0, 0.0], [99_999, 99_999, 1.0], [-99_999, 5, 0.5]], "size": 2000, "shape": "square", "angle": 1e6, "roundness": 5, "smoothing": 0, "mode": "behind", "unit": 0.001}), json!({"points": (0..3000).map(|i| json!([i % 7, (i * 13) % 11, f64::from(i % 3) * 0.5])).collect::>(), "size": 0.1, "mode": "fills", "smoothing": 100, "unit": 1000}), diff --git a/crates/geom/src/edit.rs b/crates/geom/src/edit.rs index 49db78bf..8f0c0a93 100644 --- a/crates/geom/src/edit.rs +++ b/crates/geom/src/edit.rs @@ -234,6 +234,28 @@ impl Path { } } + /// Removes the anchor between segments `cmd` and `cmd + 1`, replacing both with the one + /// cubic that comes closest to them: it keeps the outer anchors and the directions their + /// handles leave in, and takes the handle lengths that fit the old curve best (least + /// squares over samples of both segments, with Newton steps refining where each sample + /// falls on the new curve; Schneider, "An Algorithm for Automatically Fitting Digitized + /// Curves", Graphics Gems, 1990). Deleting a point that splitting added gives the old curve + /// back. False (nothing changed) unless both commands are segments. + pub fn merge_at(&mut self, cmd: usize) -> bool { + if !(self.is_segment(cmd) && self.is_segment(cmd + 1)) { + return false; + } + self.to_cubic(cmd); + self.to_cubic(cmd + 1); + let (Some(p0), Some(&PathCmd::CubicTo(a1, a2, m)), Some(&PathCmd::CubicTo(b1, b2, p3))) = (self.segment_start(cmd), self.cmds.get(cmd), self.cmds.get(cmd + 1)) else { return false }; + let Some(c) = merge_cubics([p0, a1, a2, m], [m, b1, b2, p3]) else { return false }; + if let Some(slot) = self.cmds.get_mut(cmd + 1) { + *slot = PathCmd::CubicTo(c[1], c[2], c[3]); + } + self.cmds.remove(cmd); + true + } + /// Makes anchor `cmd` a corner: its handles collapse onto it (segments stay curves). pub fn make_corner(&mut self, cmd: usize) -> bool { let Some(a) = self.point(cmd, ANCHOR) else { return false }; @@ -355,6 +377,82 @@ impl Path { } } +/// The first direction of `cands` (vectors from an end anchor) of some length, unit length. +fn leaving(cands: [Vec2; 3]) -> Option { + cands.into_iter().find(|v| v.length() > 1e-4).map(Vec2::normalized) +} + +/// One cubic in place of `a` then `b` (see [`Path::merge_at`]). `None` for non-finite input. +fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> { + use crate::walk::cubic_point; + const N: usize = 24; + let (p0, p3) = (a[0], b[3]); + if !a.iter().chain(&b).all(|p| p.is_finite()) { + return None; + } + // Direction of travel out of each end (a handle on its anchor: the next point along). + let span = p0.distance(p3); + let t1 = leaving([a[1] - p0, a[2] - p0, a[3] - p0]).unwrap_or_else(|| (p3 - p0).normalized()); + let t2 = leaving([b[2] - p3, b[1] - p3, b[0] - p3]).unwrap_or_else(|| (p0 - p3).normalized()); + let poly = |c: &[Vec2; 4]| c[0].distance(c[1]) + c[1].distance(c[2]) + c[2].distance(c[3]); + // (The points are finite, so the lengths are too.) + if poly(&a) + poly(&b) <= 1e-6 { + // Nothing of any length: the straight cubic between the ends. + return Some([p0, p0.lerp(p3, 1.0 / 3.0), p0.lerp(p3, 2.0 / 3.0), p3]); + } + // Where the middle anchor falls on the new curve, `tau`: had the two been cut from one + // cubic at `tau`, the middle anchor's handles would be in the ratio tau : 1 − tau (de + // Casteljau), so that ratio places it exactly; a corner falls back on the lengths. + let (inn, out) = (a[3].distance(a[2]), b[1].distance(b[0])); + let tau = if inn + out > 1e-6 { inn / (inn + out) } else { poly(&a) / (poly(&a) + poly(&b)) }; + let tau = if tau.is_finite() { tau.clamp(0.02, 0.98) } else { 0.5 }; + // Samples of the old curve, and where each starts on the new one. + let pts: Vec = (0..=N).map(|i| cubic_point(&a, i as f32 / N as f32)).chain((1..=N).map(|i| cubic_point(&b, i as f32 / N as f32))).collect(); + let mut u: Vec = (0..=N).map(|i| tau * i as f32 / N as f32).chain((1..=N).map(|i| tau + (1.0 - tau) * i as f32 / N as f32)).collect(); + let mut best = [p0, p0 + t1 * (span / 3.0), p3 + t2 * (span / 3.0), p3]; + for _ in 0..16 { + // Least squares for the handle lengths with the parameters fixed (Schneider's + // generateBezier). + let (mut c00, mut c01, mut c11, mut x0, mut x1) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 0.0f64); + for (q, &t) in pts.iter().zip(&u) { + let s = 1.0 - t; + let (b0, b1, b2, b3) = (s * s * s, 3.0 * s * s * t, 3.0 * s * t * t, t * t * t); + let (v1, v2) = (t1 * b1, t2 * b2); + let rest = *q - (p0 * (b0 + b1) + p3 * (b2 + b3)); + c00 += f64::from(v1.dot(v1)); + c01 += f64::from(v1.dot(v2)); + c11 += f64::from(v2.dot(v2)); + x0 += f64::from(v1.dot(rest)); + x1 += f64::from(v2.dot(rest)); + } + let det = c00 * c11 - c01 * c01; + let (mut l1, mut l2) = if det.abs() > 1e-12 { (((x0 * c11 - x1 * c01) / det) as f32, ((c00 * x1 - c01 * x0) / det) as f32) } else { (span / 3.0, span / 3.0) }; + // A handle pointing backwards (or too short to mean anything) is no fit: a third of + // the way, as a straight segment would have. + if !(l1.is_finite() && l2.is_finite()) || l1 < span * 1e-3 || l2 < span * 1e-3 { + (l1, l2) = (span / 3.0, span / 3.0); + } + best = [p0, p0 + t1 * l1, p3 + t2 * l2, p3]; + // Newton steps: where on the new curve each sample is nearest. + for (q, t) in pts.iter().zip(u.iter_mut()) { + let s = 1.0 - *t; + let c = &best; + let p = cubic_point(c, *t); + let d1 = (c[1] - c[0]) * (3.0 * s * s) + (c[2] - c[1]) * (6.0 * s * *t) + (c[3] - c[2]) * (3.0 * *t * *t); + let d2 = (c[2] - c[1] * 2.0 + c[0]) * (6.0 * s) + (c[3] - c[2] * 2.0 + c[1]) * (6.0 * *t); + let num = (p - *q).dot(d1); + let den = d1.dot(d1) + (p - *q).dot(d2); + if den.abs() > 1e-9 { + let next = *t - num / den; + if next.is_finite() { + *t = next.clamp(0.0, 1.0); + } + } + } + } + best.iter().all(|p| p.is_finite()).then_some(best) +} + /// Ramer–Douglas–Peucker simplification (iterative; bounded memory). pub fn simplify(points: &[Vec2], tolerance: f32) -> Vec { let n = points.len(); @@ -487,6 +585,60 @@ mod tests { assert_eq!(r.point(0, ANCHOR), Some(Vec2::new(10.0, 0.0))); } + /// Largest distance from points of `p`'s segment `cmd` to the curve `q` (sampled densely). + fn deviation(p: &Path, q: &Path) -> f32 { + let dense = q.flatten(&Affine::IDENTITY, 0.001); + let qs = &dense[0].points; + let near = |pt: Vec2| qs.windows(2).map(|w| crate::path::segment_distance(pt, w[0], w[1])).fold(f32::INFINITY, f32::min); + p.flatten(&Affine::IDENTITY, 0.01)[0].points.iter().map(|pt| near(*pt)).fold(0.0, f32::max) + } + + #[test] + fn merging_undoes_a_split() { + for t in [0.2f32, 0.5, 0.83] { + let p = cubic_path(); + let mut q = p.clone(); + assert!(q.split_segment(1, t)); + assert!(q.merge_at(1)); + assert_eq!(q.cmds.len(), p.cmds.len()); + assert_eq!(q.point(1, ANCHOR), p.point(1, ANCHOR), "the outer anchors stay"); + assert_eq!(q.point(0, ANCHOR), p.point(0, ANCHOR)); + let (Some(a), Some(b)) = (q.point(1, C1), p.point(1, C1)) else { panic!("cubic") }; + assert!(a.distance(b) < 0.01 && q.point(1, C2).unwrap().distance(p.point(1, C2).unwrap()) < 0.01, "t {t}: {:?} vs {:?}", q.cmds[1], p.cmds[1]); + assert!(deviation(&q, &p) < 0.01 && deviation(&p, &q) < 0.01, "t {t}"); + } + } + + #[test] + fn merging_two_unrelated_curves_keeps_the_ends_and_their_directions() { + // An S: up and over, then down and under; the merged curve keeps the S's ends and the + // directions it leaves and arrives in, and stays near it. + let mut p = Path::new(); + p.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(0.0, -40.0), Vec2::new(50.0, -40.0), Vec2::new(50.0, 0.0)).cubic_to(Vec2::new(50.0, 40.0), Vec2::new(100.0, 40.0), Vec2::new(100.0, 0.0)); + let before = p.clone(); + assert!(p.merge_at(1)); + assert_eq!(p.anchors().iter().map(|a| a.1).collect::>(), vec![Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)]); + let (c1, c2) = (p.point(1, C1).unwrap(), p.point(1, C2).unwrap()); + assert!(c1.x.abs() < 1e-4 && c1.y < 0.0, "leaves straight up: {c1:?}"); + assert!((c2.x - 100.0).abs() < 1e-4 && c2.y > 0.0, "arrives straight up: {c2:?}"); + assert!(deviation(&p, &before) < 12.0, "{}", deviation(&p, &before)); + // Lines merge into a line; corners (handles on their anchors) still find a direction. + let mut l = Path::new(); + l.move_to(Vec2::new(0.0, 0.0)).line_to(Vec2::new(10.0, 0.0)).line_to(Vec2::new(20.0, 0.0)); + assert!(l.merge_at(1)); + assert_eq!(l.cmds.len(), 2); + assert!((0..=10).all(|i| l.segment_point(1, i as f32 / 10.0).is_some_and(|q| q.y.abs() < 1e-5 && (0.0..=20.0).contains(&q.x))), "{:?}", l.cmds); + let mut c = Path::new(); + c.move_to(Vec2::new(0.0, 0.0)).cubic_to(Vec2::new(0.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(10.0, 10.0)).cubic_to(Vec2::new(10.0, 10.0), Vec2::new(20.0, 0.0), Vec2::new(20.0, 0.0)); + assert!(c.merge_at(1) && c.cmds.iter().all(|x| match x { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => p.is_finite(), + PathCmd::CubicTo(a, b, p) => a.is_finite() && b.is_finite() && p.is_finite(), + _ => true, + })); + // Only between two segments. + assert!(!cubic_path().merge_at(0) && !cubic_path().merge_at(2) && !cubic_path().merge_at(9)); + } + #[test] fn closed_subpaths_have_one_start_anchor() { let mut r = Path::rect(0.0, 0.0, 10.0, 10.0); diff --git a/docs/adr/0030-motion-paths.md b/docs/adr/0030-motion-paths.md index 0ba6c04a..d6b73af4 100644 --- a/docs/adr/0030-motion-paths.md +++ b/docs/adr/0030-motion-paths.md @@ -94,8 +94,9 @@ and loses nothing irreversible, so it doesn't ask (ADR 0004). * Performance: evaluating a tween on an 8-segment path with orient takes 10–15 µs per object per frame, and the stage's 240 frame dots 20–30 µs together (one `CurveWalk` per call; measured on the development machine, release and dev profiles). -* Not yet (later PRs): position keys as anchors (spatial keys), adding or deleting path points - and converting them smooth/corner on the stage, moving the whole path, copying and pasting +* Adding, deleting and converting path points and moving the whole path came next, in + ADR 0038, which also explains why anchors tied to frames wait for a model change. +* Not yet (later PRs): position keys as anchors (spatial keys), copying and pasting a path from a stroke or onto a guide, ease along the path for loop paths, the path shown for tweens inside symbols edited in place, snapping the ends, and importing motion paths from XFL (motion tween import still waits on samples, ADR 0016). diff --git a/docs/adr/0038-motion-path-points.md b/docs/adr/0038-motion-path-points.md new file mode 100644 index 00000000..145e9a32 --- /dev/null +++ b/docs/adr/0038-motion-path-points.md @@ -0,0 +1,121 @@ +# ADR 0038: Editing motion path points and moving the whole path + +* Status: accepted (2026-11-09) +* Relates to: ADR 0030 (motion paths), ADR 0016 (motion tweens), ADR 0004 (destructive + actions), roadmap M2 + +## Context + +ADR 0030 gave motion tweens a cubic Bézier path that the object travels by arc length, timed +by the X/Y curves. Artists could bend it (Selection), drag its anchors and handles +(Subselection) and straighten it, but not add or delete points, make a point smooth or a +corner, or move the whole path. In Animate those edits work on a motion path as they do on +any path: the Subselection and Pen tools add and delete anchor points, a point is converted +between smooth and corner, and the whole path is moved by selecting and dragging it. We +learned this behaviour from Adobe's public help pages and from watching the program; nothing +was copied. The shape point editing in `geom::edit` and `cmds_path` (`path.add_point`, +`path.delete_points`, `path.convert_point`) already does most of it on shapes. + +## Decision + +1. **Point edits are commands on the path, reusing `geom::edit`.** `motion.add_point` + splits the nearest segment by de Casteljau subdivision (`Path::split_segment`). + `motion.delete_points` removes anchors, and `motion.convert_point` uses `make_smooth` and + `make_corner`. All three edit the tween's path, or the straight path its X/Y curves trace, + which the edit makes the tween's own (as a drag does in ADR 0030). Each one then goes + through `MotionTween::set_path`. That keeps the normal form, and it keeps the ends' X/Y keys + exactly when the ends didn't move, so **no point edit changes the timing**. Anchor `i` is + path command `i`, because a motion path is a move followed by cubics. `motion.info` and the + path commands list `anchors` in that order, so agents can address them. +2. **Adding a point changes nothing you can see.** The split curve is the same curve, so the + object takes the same path on the same frames. Tests check this to 0.01 px on every frame. + A path that already has `MAX_PATH_SEGMENTS` segments refuses another point instead of + silently cutting off its end. +3. **Deleting a point refits instead of dropping.** Dropping an anchor (`remove_anchor`, as + shapes do) keeps the next segment's control points, and that warps the curve. A motion path + is the object's route, so it should stay close to where it was. `Path::merge_at` replaces the + two segments around the anchor with the one cubic that fits them best: + * It keeps the outer anchors and the directions their handles leave in. + * It finds the handle lengths by least squares over samples of both segments, with Newton + steps refining each sample's parameter (Schneider, *Graphics Gems*, 1990). + * The samples start at the de Casteljau ratio of the middle anchor's handles. That ratio is + exact when the two segments were once one, so **deleting a point that was added gives the + original curve back** (tested to 0.01 px on the handles). +4. **The ends can't be deleted.** They are where the motion starts and ends: the first and + last position keys hold them (ADR 0030 §3). Deleting an end would have to drop keys, or + move the start somewhere the artist didn't put it. Asking to delete only ends is refused + with a message that says why and what to do instead (drag them, or Straighten). Asking for + ends and middle points deletes the middle points and reports `kept_ends`, which the status + bar repeats. Deleting points is undoable and routine, so it doesn't ask first (ADR 0004). +5. **Moving the whole path keeps the timing exactly.** `motion.move_path {dx, dy}` + (`MotionTween::translate`) moves: + * the path; + * every X and Y key; + * the object's own position, which is the value of an axis that has no keys. + + The timing only compares positions with each other (chords and how far along them the X/Y + curves are), so every frame lands exactly `d` over, with the same turn. Tests check this to + 0.001 px and 0.001° on every frame. A move that would leave the ±1,000,000 px range is + refused and changes nothing. With no path, the straight motion moves the same way. +6. **On the stage** (`src/motion_path.rs`): + * Subselection keeps a set of selected anchors. A click selects one; Shift adds or removes. + A selected anchor shows its handles. + * A double-click on the path adds a point there and selects it. + * Delete or Backspace removes the selected anchors. These keys are taken before the + global shortcuts, so the object isn't deleted. + * A right-click on an anchor offers Make Smooth, Make Corner, Delete Point(s) and + Straighten Path. Delete is disabled, with a tooltip, when only ends are selected. + * The Pen shows the anchors. **Alt-click** on the path adds a point, and the Pen now does + the same on a selected shape's outline. While Alt is held, the stretch the click would + split widens and the cursor shows a plus. + * **Ctrl-drag** (⌘ on macOS) the path, an anchor or the object, with Selection or + Subselection, to move the whole path. We chose Ctrl because a plain drag already bends + the path or moves the object. Alt-drag is how Animate users copy, and Shift constrains. + Ctrl (⌘) is free on the stage, and as a modifier it reads as "the whole thing". + * Properties › Frame shows **Path start** X/Y, which is where the motion starts. Editing + it moves the whole path. It is also the keyboard and screen-reader route to the move. + * Each gesture is one undo step: drags and the Properties fields through session gestures, + and converting several anchors as one gesture. Edits show in the same frame. +7. **The file format doesn't change.** No new field: the path, keys and object were already + saved. + +## Anchors tied to frames: not in this slice + +Pinning an anchor to a frame (spatial keys), so the object passes it exactly then, doesn't fit +the timing model of ADR 0030 cleanly: + +* The X/Y curves are the timing, and the share of the path covered between two position keys + is set by the chords between the keys' positions. +* A pinned anchor would be a second, competing source of timing. Which wins when they + disagree? What happens to the X/Y keys when the pin moves, and to a pin when points are + added or deleted, since anchor indices shift? +* Doing it properly means position keys *become* anchors: the timing comes from per-anchor + frames plus an ease along the path, and the X/Y curves turn into a view of that, not its + source. That is a model change with its own ADR, file format fields and Motion Editor + behaviour. + +Until then, moving the object at a frame bends the path through that point (ADR 0030 §4), +which covers the common "be here on this frame" case without a new model. + +## Consequences + +* The X/Y keys never change from a point edit, so retiming and path editing stay independent. +* A deleted point's neighbours keep their directions, so a smooth path stays smooth. A sharp + S folded into one segment can only be approximated: one cubic has one inflection's worth of + freedom. +* Performance, measured with the optimised dev profile on the development machine: + * One add-and-delete pair through the command registry, undo snapshot included: 40 µs on + an 8-segment path, 0.32 ms at 100 segments, 4.2 ms at 999 segments. + * The refit itself: 7 µs. + * One drag frame of `motion.move_path`: 15 µs, 0.1 ms and 1.8 ms on the same paths. + + Most of the cost is measuring the path again (`CurveWalk`) and snapshotting the keyframe. +* Not yet (later PRs): + * anchors tied to frames (above); + * a marquee over motion path anchors; + * arrow-key nudging and Free Transform (scale, rotate) of a whole path; + * deleting an end by giving the start to the next anchor (with its keys); + * the Convert Anchor Point tool's drag-out of handles; + * moving the path of a tween inside a symbol edited in place; + * and the rest of ADR 0030's list: copying and pasting paths, eases on loop paths, snapping + the ends, XFL motion path import. diff --git a/docs/roadmap.md b/docs/roadmap.md index b8369b1f..c151c3e9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -10,7 +10,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---| | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | | Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | -| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient`). Not yet: adding/deleting path points on the stage, anchors tied to frames (spatial keys), moving the whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | +| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path`). Not yet: anchors tied to frames (spatial keys, a model change: ADR 0038), a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. Not yet: bending segments by dragging, snapping, moving shared points together, partial marquee selection, merging bucket fills and pastes, XFL raw shapes, gradients and width profiles in the merge. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing gradient or width-profiled shapes, eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. Not yet: ActionScript (ADR 0013 tiers), filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | @@ -31,7 +31,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (basic); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | -| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030; spatial keys, point add/delete, 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | +| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038; spatial keys, 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); GPU binning deferred (not the bottleneck as tiles); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: eleven packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); not yet: `.fla` variants of the corpus, sound and video items; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output; effects, volume and sounds in symbols later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | diff --git a/src/a11y.rs b/src/a11y.rs index 38161b62..f7d44702 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -351,7 +351,7 @@ mod tests { for tool in [Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "camera", "cameraview", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "camera", "cameraview", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 2ea9f7bd..82b6d80b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -117,8 +117,8 @@ impl Tool { pub fn hint(self) -> &'static str { match self { Tool::Select => "Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection.", - Tool::Subselect => "Click a shape to show its points. Drag points or handles to reshape (Shift adds to the point selection, drag on empty space to marquee points). Double-click an edge to add a point; Delete removes points. Right-click to make a point smooth or a corner.", - Tool::Pen => "Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point.", + Tool::Subselect => "Click a shape to show its points. Drag points or handles to reshape (Shift adds to the point selection, drag on empty space to marquee points). Double-click an edge to add a point; Delete removes points. Right-click to make a point smooth or a corner. A motion path's points edit the same way (its ends stay).", + Tool::Pen => "Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point. Alt-click a selected shape or a motion path to add a point to it.", Tool::Text => "Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too.", Tool::Pencil => "Drag to draw freehand. The options bar sets Smooth, Straighten or Ink.", Tool::Brush => "Drag to paint filled shapes in the fill colour (a click paints a dab). [ and ] change the size; the options set the shape, smoothing and paint mode.", @@ -197,6 +197,8 @@ pub enum Drag { /// Editing the motion path (ADR 0030) from stage point `start`; the path as it was when the /// drag began is `App::motion_drag`. MotionPath { grab: crate::motion_path::Grab, start: egui::Pos2 }, + /// Moving the whole motion path (ADR 0038), from stage point `last` last frame. + MotionMove { last: egui::Pos2 }, /// Camera tool (ADR 0027): panning from screen point `last`, turning from pointer angle /// `last` (radians about the camera centre), or zooming with the wheel until `until` /// (seconds; the turns of one burst are one undo step). @@ -310,8 +312,8 @@ pub struct App { pub points: Vec, /// Width tool: the selected width point (shape, index). pub width_sel: Option<(anicraft_engine::doc::ElementId, usize)>, - /// Subselection: the motion path anchor whose handles show (ADR 0030). - pub motion_anchor: Option, + /// Subselection: the selected motion path anchors, whose handles show (ADR 0030, 0038). + pub motion_anchors: Vec, /// The motion path as it was when the drag on it began. pub motion_drag: Option, /// Selected frames on the timeline, and the drag on the frame grid. @@ -464,7 +466,7 @@ impl App { align_to_stage: false, points: Vec::new(), width_sel: None, - motion_anchor: None, + motion_anchors: Vec::new(), motion_drag: None, frame_sel: None, tl_drag: timeline::TlDrag::None, @@ -977,7 +979,7 @@ impl App { self.me_key = Some(0); self.run("timeline.goto", json!({"frame": 6})); } - Some(which @ ("motionpath" | "motionpoints")) => { + Some(which @ ("motionpath" | "motionpoints" | "motionedit")) => { // The Star layer's span as a motion tween along a curved, oriented motion path, // the star selected half way along it (ADR 0030); with Subselection, the // middle anchor's handles show. @@ -993,12 +995,20 @@ impl App { } self.run("timeline.goto", json!({"frame": 9})); self.run("edit.select_all", json!({})); - if which == "motionpoints" { + if which != "motionpath" { // The span selected instead of the star: Properties shows the tween's rows. self.run("element.select", json!({"ids": []})); self.frame_sel = Some(timeline::FrameSel::cell(self.s.layer, 9)); self.tool = Tool::Subselect; - self.motion_anchor = Some(1); + self.motion_anchors = vec![1]; + } + if which == "motionedit" { + // Points edited (ADR 0038): one added on the second segment, the middle + // anchor made a corner, both selected with their handles showing. + self.run("motion.add_point", json!({"segment": 2, "t": 0.45})); + self.run("motion.convert_point", json!({"anchor": 1, "smooth": false})); + self.motion_anchors = vec![1, 2]; + self.status_ok(format!("Added a point to the motion path. {} to undo.", platform::shortcut_label("Ctrl+Z"))); } } Some("pen") => { @@ -1463,6 +1473,7 @@ impl App { } let control = keys == crate::a11y::Keyboard::Control; if !control { + crate::motion_path::consume_keys(self, ctx); pathtools::consume_keys(self, ctx); crate::widthtool::consume_keys(self, ctx); } diff --git a/src/main.rs b/src/main.rs index c62f8afd..494c5700 100644 --- a/src/main.rs +++ b/src/main.rs @@ -158,7 +158,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|testmovie|exporthtml]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|testmovie|exporthtml]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/motion_path.rs b/src/motion_path.rs index 1f057750..9f917368 100644 --- a/src/motion_path.rs +++ b/src/motion_path.rs @@ -1,28 +1,36 @@ -//! Motion paths on the stage (ADR 0030). When a motion tween's object is selected, or a frame -//! of its span is, the stage shows the path its registration point travels, in the motion +//! Motion paths on the stage (ADR 0030, 0038). When a motion tween's object is selected, or a +//! frame of its span is, the stage shows the path its registration point travels, in the motion //! colour, with a dot on every frame (larger on position keys). //! //! * **Selection (V)**: drag the path to bend it, or drag either end to move where the motion //! starts or ends. Dragging the object itself still moves it (auto-key). //! * **Subselection (A)**: drag any anchor, or a selected anchor's handles (Alt breaks a smooth -//! pair). A click on an anchor selects it and shows its handles. +//! pair). A click on an anchor selects it and shows its handles (Shift adds to the selection); +//! a double-click on the path adds an anchor there; Delete removes the selected anchors (the +//! ends stay); right-click makes them smooth or corners. +//! * **Pen (P)**: Alt-click the path to add an anchor, as on shapes. +//! * **Ctrl-drag** (⌘ on macOS) the path or its object, with Selection or Subselection, to move +//! the whole path; the timing stays. //! //! A tween without a path of its own shows the straight path its X/Y curves trace; the first -//! edit makes it a path. Every change is `motion.set_path`, and a drag is one undo step (a +//! edit makes it a path. Every change is a `motion.*` command, and a drag is one undo step (a //! session gesture). Only the anchor selection and the drag in progress live here. use crate::app::{App, Drag, Tool}; use crate::pathtools::Xf; use crate::theme::T; -use anicraft_engine::doc::Props; +use anicraft_engine::doc::{ElementId, Props}; use anicraft_engine::geom::edit::{ANCHOR, C1, C2}; use anicraft_engine::geom::{Affine, Path, PathCmd, Vec2}; -use egui::{Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; +use egui::{Key, Modifiers, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2}; use serde_json::json; /// Grab radius for anchors, handles and the path, in screen points. const PICK: f32 = 6.0; +/// Most selected anchors whose handles show (a marquee of hundreds would bury the path). +const MAX_SHOWN_HANDLES: usize = 64; + /// What a press on the path took hold of. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Grab { @@ -44,6 +52,8 @@ pub struct Shown { pub keys: Vec, /// The playhead's frame in the span. pub offset: u32, + /// The object travelling it. + pub target: ElementId, } /// The motion path of the active layer's motion tween at the playhead, when its object or a @@ -67,14 +77,15 @@ pub fn shown(app: &App) -> Option { let mut keys: Vec = [anicraft_engine::doc::Property::X, anicraft_engine::doc::Property::Y].into_iter().filter_map(|p| m.track(p)).flat_map(|t| t.keys.iter().map(|k| k.frame)).filter(|f| *f < k.duration).collect(); keys.sort_unstable(); keys.dedup(); - Some(Shown { path, dots, keys, offset: app.s.frame - k.start }) + Some(Shown { path, dots, keys, offset: app.s.frame - k.start, target: target.id }) } -/// The anchors the tool can take: both ends with Selection, every anchor with Subselection. +/// The anchors the tool can take: both ends with Selection, every anchor with Subselection +/// (and shown to the Pen, which adds between them). fn grabbable_anchors(path: &Path, tool: Tool) -> Vec<(usize, Vec2)> { let all = path.anchors(); match tool { - Tool::Subselect => all, + Tool::Subselect | Tool::Pen => all, _ => { let n = all.len(); all.into_iter().enumerate().filter(|(i, _)| *i == 0 || *i + 1 == n).map(|(_, a)| a).collect() @@ -82,26 +93,33 @@ fn grabbable_anchors(path: &Path, tool: Tool) -> Vec<(usize, Vec2)> { } } -/// The handles shown for the selected anchor: `(cmd, slot)`. -fn handles(path: &Path, anchor: Option) -> Vec<(usize, u8)> { - let Some(a) = anchor else { return Vec::new() }; - let (i, o) = path.anchor_segments(a); +/// The handles shown for the selected anchors: `(cmd, slot, anchor)`. +fn handles(path: &Path, anchors: &[usize]) -> Vec<(usize, u8, usize)> { let mut v = Vec::new(); - if let Some(i) = i.filter(|&i| matches!(path.cmds.get(i), Some(PathCmd::CubicTo(..)))) { - v.push((i, C2)); - } - if let Some(o) = o.filter(|&o| matches!(path.cmds.get(o), Some(PathCmd::CubicTo(..)))) { - v.push((o, C1)); + for &a in anchors.iter().take(MAX_SHOWN_HANDLES) { + let (i, o) = path.anchor_segments(a); + if let Some(i) = i.filter(|&i| matches!(path.cmds.get(i), Some(PathCmd::CubicTo(..)))) { + v.push((i, C2, a)); + } + if let Some(o) = o.filter(|&o| matches!(path.cmds.get(o), Some(PathCmd::CubicTo(..)))) { + v.push((o, C1, a)); + } } v } +/// The stretch of path under screen point `p`: `(cmd, t)`. +fn on_segment(shown: &Shown, p: Pos2, xf: Xf) -> Option<(usize, f32)> { + let (cmd, t, d) = shown.path.nearest_segment(xf.to_stage(p), &Affine::IDENTITY)?; + (d * xf.zoom <= PICK).then_some((cmd, t)) +} + /// The handle, anchor or (with Selection) the stretch of path under screen point `p`. /// `segments` is false while the press should first go to the object under it. pub fn hit(app: &App, shown: &Shown, p: Pos2, xf: Xf, segments: bool) -> Option { let near = |q: Vec2| xf.to_screen(q).distance(p) <= PICK; if app.tool == Tool::Subselect { - for (cmd, slot) in handles(&shown.path, app.motion_anchor) { + for (cmd, slot, _) in handles(&shown.path, &app.motion_anchors) { if shown.path.point(cmd, slot).is_some_and(near) { return Some(Grab::Handle(cmd, slot)); } @@ -111,18 +129,18 @@ pub fn hit(app: &App, shown: &Shown, p: Pos2, xf: Xf, segments: bool) -> Option< return Some(Grab::Anchor(cmd)); } if segments && app.tool == Tool::Select { - let (cmd, t, d) = shown.path.nearest_segment(xf.to_stage(p), &Affine::IDENTITY)?; - if d * xf.zoom <= PICK { - return Some(Grab::Segment(cmd, t)); - } + return on_segment(shown, p, xf).map(|(cmd, t)| Grab::Segment(cmd, t)); } None } -/// Starts dragging `grab`: one undo step until the drag ends. +/// Starts dragging `grab`: one undo step until the drag ends. An anchor not yet selected becomes +/// the selection. pub fn drag_start(app: &mut App, shown: Shown, grab: Grab, at: Vec2) -> Drag { - if let Grab::Anchor(a) = grab { - app.motion_anchor = Some(a); + if let Grab::Anchor(a) = grab + && !app.motion_anchors.contains(&a) + { + app.motion_anchors = vec![a]; } app.motion_drag = Some(shown.path); app.s.begin_gesture("Edit Motion Path"); @@ -175,27 +193,219 @@ pub fn drag_end(app: &mut App) { app.s.end_gesture(); } -/// A click with Subselection on an anchor selects it (showing its handles); false when the -/// click wasn't on one. -pub fn click(app: &mut App, p: Pos2, xf: Xf) -> bool { +// ----- moving the whole path --------------------------------------------------------------- + +/// Whether a Ctrl-press at screen point `p` takes the whole path: on the path, an anchor, or +/// the object travelling it. +pub fn move_hit(app: &App, p: Pos2, xf: Xf) -> bool { let Some(shown) = shown(app) else { return false }; - match hit(app, &shown, p, xf, false) { - Some(Grab::Anchor(a)) => { - app.motion_anchor = Some(a); - true - } - Some(_) => true, - None => false, + let near_anchor = shown.path.anchors().iter().any(|(_, q)| xf.to_screen(*q).distance(p) <= PICK); + near_anchor || on_segment(&shown, p, xf).is_some() || app.s.hit_test(xf.to_stage(p), 3.0 * xf.unit()).is_some_and(|(_, e)| e == shown.target) +} + +/// Starts moving the whole path from stage point `at`: one undo step until the drag ends. +pub fn move_start(app: &mut App, at: Vec2) -> Drag { + app.s.begin_gesture("Move Motion Path"); + Drag::MotionMove { last: pos2(at.x, at.y) } +} + +/// Moves the whole path by the pointer's move since the last frame. +pub fn move_to(app: &mut App, d: Vec2) { + if d.x != 0.0 || d.y != 0.0 { + app.run("motion.move_path", json!({"dx": d.x, "dy": d.y})); } } -/// Forgets an anchor selection the path no longer has. -pub fn upkeep(app: &mut App) { - if let Some(a) = app.motion_anchor - && shown(app).is_none_or(|s| s.path.point(a, ANCHOR).is_none()) - { - app.motion_anchor = None; +// ----- adding, deleting and converting points -------------------------------------------- + +/// Adds an anchor where screen point `p` is on the path and selects it; false when `p` isn't on +/// the path (or is on an anchor already). +fn add_at(app: &mut App, p: Pos2, xf: Xf) -> bool { + let Some(shown) = shown(app) else { return false }; + if shown.path.anchors().iter().any(|(_, q)| xf.to_screen(*q).distance(p) <= PICK) || on_segment(&shown, p, xf).is_none() { + return false; } + let sp = xf.to_stage(p); + if let Some(v) = app.run("motion.add_point", json!({"x": sp.x, "y": sp.y, "slop": PICK * xf.unit()})) { + app.motion_anchors = v["anchor"].as_u64().map(|a| vec![a as usize]).unwrap_or_default(); + app.points.clear(); + app.status_ok(format!("Added a point to the motion path. {} to undo.", crate::platform::shortcut_label("Ctrl+Z"))); + } + true +} + +/// Double-click with Subselection: on the path it adds an anchor there. False when the +/// double-click wasn't on the path. +pub fn double_click(app: &mut App, p: Pos2, xf: Xf) -> bool { + app.tool == Tool::Subselect && add_at(app, p, xf) +} + +/// Alt-click with the Pen (no path being drawn): on the path it adds an anchor there, as on a +/// shape. False when the click wasn't on the path. +pub fn pen_alt_click(app: &mut App, p: Pos2, xf: Xf) -> bool { + app.tool == Tool::Pen && app.pen.is_none() && add_at(app, p, xf) +} + +/// With the Pen and Alt held: the stretch of path an Alt-click would add a point to. +pub fn pen_hot(app: &App, p: Pos2, xf: Xf) -> Option { + if app.pen.is_some() { + return None; + } + let shown = shown(app)?; + if shown.path.anchors().iter().any(|(_, q)| xf.to_screen(*q).distance(p) <= PICK) { + return None; + } + on_segment(&shown, p, xf).map(|(cmd, t)| Grab::Segment(cmd, t)) +} + +/// The selected anchors that are on the path now (an older selection may name others). +fn selected(app: &App) -> Vec { + let Some(shown) = shown(app) else { return Vec::new() }; + let n = shown.path.cmds.len(); + app.motion_anchors.iter().copied().filter(|a| *a < n).collect() +} + +/// Whether anchor `a` of an `n`-command path is an end. +fn is_end(a: usize, n: usize) -> bool { + a == 0 || a + 1 == n +} + +/// Deletes the selected anchors; the ends stay (the status says why). +pub fn delete_selected(app: &mut App) { + let anchors = selected(app); + if anchors.is_empty() { + return; + } + if let Some(v) = app.run("motion.delete_points", json!({"anchors": anchors})) { + let n = v["deleted"].as_u64().unwrap_or(0); + let what = if n == 1 { "1 point".to_string() } else { format!("{n} points") }; + let undo = crate::platform::shortcut_label("Ctrl+Z"); + app.status_ok(if v["kept_ends"].as_bool() == Some(true) { format!("Deleted {what} from the motion path; its ends stay, as they are where the motion starts and ends. {undo} to undo.") } else { format!("Deleted {what} from the motion path. {undo} to undo.") }); + app.motion_anchors.clear(); + } +} + +/// Makes the selected anchors smooth or corners (one undo step). +pub fn convert_selected(app: &mut App, smooth: bool) { + let anchors = selected(app); + if anchors.is_empty() { + return; + } + app.s.begin_gesture(if smooth { "Make Smooth" } else { "Make Corner" }); + for a in anchors { + app.run("motion.convert_point", json!({"anchor": a, "smooth": smooth})); + } + app.s.end_gesture(); +} + +/// A click with Subselection: on an anchor it selects it (Shift adds or removes), on a handle +/// or the path it keeps the selection. False when the click wasn't on the path, which then +/// drops the anchor selection. +pub fn click(app: &mut App, p: Pos2, xf: Xf, shift: bool) -> bool { + let Some(shown) = shown(app) else { return false }; + match hit(app, &shown, p, xf, false) { + Some(Grab::Anchor(a)) => { + if !shift { + app.motion_anchors = vec![a]; + } else if let Some(i) = app.motion_anchors.iter().position(|x| *x == a) { + app.motion_anchors.remove(i); + } else { + app.motion_anchors.push(a); + } + app.points.clear(); + true + } + Some(_) => true, + None if on_segment(&shown, p, xf).is_some() => { + if !shift { + app.motion_anchors.clear(); + } + true + } + None => { + app.motion_anchors.clear(); + false + } + } +} + +/// A right-click with Subselection on an anchor selects it (keeping a selection it is part of), +/// so the menu acts on it; on the path it keeps the selection. False when it wasn't on the path. +pub fn secondary_click(app: &mut App, p: Pos2, xf: Xf) -> bool { + if app.tool != Tool::Subselect { + return false; + } + let Some(shown) = shown(app) else { return false }; + match hit(app, &shown, p, xf, false) { + Some(Grab::Anchor(a)) => { + if !app.motion_anchors.contains(&a) { + app.motion_anchors = vec![a]; + } + app.points.clear(); + true + } + Some(_) => true, + None => on_segment(&shown, p, xf).is_some(), + } +} + +/// The right-click menu for selected motion path anchors; false when none is selected. +pub fn menu(app: &mut App, ui: &mut egui::Ui) -> bool { + if app.tool != Tool::Subselect { + return false; + } + let anchors = selected(app); + let Some(n) = shown(app).map(|s| s.path.cmds.len()) else { return false }; + if anchors.is_empty() { + return false; + } + if ui.button("Make Smooth").clicked() { + convert_selected(app, true); + ui.close(); + } + if ui.button("Make Corner").clicked() { + convert_selected(app, false); + ui.close(); + } + ui.separator(); + let deletable = anchors.iter().any(|a| !is_end(*a, n)); + let label = if anchors.len() > 1 { "Delete Points" } else { "Delete Point" }; + let resp = ui.add_enabled(deletable, egui::Button::new(label)); + let resp = if deletable { resp } else { resp.on_disabled_hover_text("The ends of a motion path are where the motion starts and ends: drag them to move them") }; + if resp.clicked() { + delete_selected(app); + ui.close(); + } + if ui.button("Straighten Path").on_hover_text("Back to the straight path the X and Y curves trace").clicked() { + app.run("motion.clear_path", json!({})); + app.motion_anchors.clear(); + ui.close(); + } + true +} + +/// Keys for the selected anchors with Subselection, taken before the global shortcuts (so +/// Delete removes points, not the object). +pub fn consume_keys(app: &mut App, ctx: &egui::Context) { + if app.tool != Tool::Subselect || app.motion_anchors.is_empty() || shown(app).is_none() { + return; + } + let take = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); + if take(Key::Delete) || take(Key::Backspace) { + delete_selected(app); + } + if take(Key::Escape) { + app.motion_anchors.clear(); + } +} + +/// Forgets selected anchors the path no longer has. +pub fn upkeep(app: &mut App) { + if app.motion_anchors.is_empty() { + return; + } + let n = shown(app).map_or(0, |s| s.path.cmds.len()); + app.motion_anchors.retain(|a| *a < n); } fn anchor_box(painter: &Painter, c: Pos2, filled: bool) { @@ -206,10 +416,11 @@ fn anchor_box(painter: &Painter, c: Pos2, filled: bool) { /// Draws the path: a line in the motion colour on a dark halo (it reads on any artwork), a dot /// per frame, larger on position keys and ringed at the playhead, and the anchors the tool can -/// take (with the selected anchor's handles under Subselection). +/// take (with the selected anchors' handles under Subselection). `hot` is what the pointer is +/// over; a segment there (or the whole path, being moved) draws wider. pub fn draw(app: &App, painter: &Painter, shown: &Shown, xf: Xf, hot: Option) { let to_px = Affine::translate(xf.origin.x, xf.origin.y).mul(&Affine::scale(xf.zoom, xf.zoom)); - let wide = matches!(hot, Some(Grab::Segment(..))) || matches!(app.drag, Drag::MotionPath { grab: Grab::Segment(..), .. }); + let wide = matches!(hot, Some(Grab::Segment(..))) || matches!(app.drag, Drag::MotionPath { grab: Grab::Segment(..), .. } | Drag::MotionMove { .. }); for pl in shown.path.flatten(&to_px, 0.35) { let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); painter.add(egui::Shape::line(pts.clone(), Stroke::new(if wide { 4.5 } else { 3.0 }, T.ink))); @@ -230,8 +441,7 @@ pub fn draw(app: &App, painter: &Painter, shown: &Shown, xf: Xf, hot: Option>(), vec![0, 2]); assert_eq!(grabbable_anchors(&p, Tool::Subselect).len(), 3); - assert_eq!(handles(&p, Some(1)), vec![(1, C2), (2, C1)]); - assert_eq!(handles(&p, Some(0)), vec![(1, C1)]); + assert_eq!(grabbable_anchors(&p, Tool::Pen).len(), 3); + assert_eq!(handles(&p, &[1]), vec![(1, C2, 1), (2, C1, 1)]); + assert_eq!(handles(&p, &[0]), vec![(1, C1, 0)]); + assert_eq!(handles(&p, &[0, 2]), vec![(1, C1, 0), (2, C2, 2)], "every selected anchor shows its handles"); + assert!(is_end(0, 3) && is_end(2, 3) && !is_end(1, 3)); } } diff --git a/src/panels.rs b/src/panels.rs index 3d66b91b..cebab823 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -1096,11 +1096,29 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L Some(n) => format!("Curved · {n} segments"), None => "Straight".to_string(), }; - ui.label(text(Type::Body, what)).on_hover_text("Select the object to see its path on the stage. Drag the path to bend it, its ends to move them; the Subselection tool (A) edits its points and handles."); + let how = format!( + "Select the object to see its path on the stage. Drag the path to bend it and its ends to move them; {} the path or the object to move the whole path. With the Subselection tool (A), drag points and handles, double-click the path to add a point (or Alt-click it with the Pen), Delete removes points, and right-click makes them smooth or corners.", + crate::platform::shortcut_label("Ctrl+Drag") + ); + ui.label(text(Type::Body, what)).on_hover_text(how); if segments.is_some() && ui.small_button("Straighten").on_hover_text("Back to the straight path the X and Y curves trace").named("Straighten motion path").clicked() { app.run("motion.clear_path", json!({})); } }); + // Where the path starts; changing it moves the whole path (ADR 0038). + let base = m.target_index(&k.elements).and_then(|i| k.elements.get(i)).map(|e| anicraft_engine::doc::Props::of(e)); + let start = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).and_then(|p| anicraft_engine::doc::motion::path_ends(&p)).map(|(a, _)| a); + if let Some(a) = start { + let (mut x, mut y) = (a.x, a.y); + row(ui, "Path start", |ui| { + let hint = "Where the motion starts. Changing it moves the whole path, and the object with it; the timing stays."; + let rx = ui.add(egui::DragValue::new(&mut x).prefix("X ").speed(1.0).max_decimals(1)).named("Motion path start X").on_hover_text(hint); + let ry = ui.add(egui::DragValue::new(&mut y).prefix("Y ").speed(1.0).max_decimals(1)).named("Motion path start Y").on_hover_text(hint); + if rx.changed() || ry.changed() { + live(app, "Move Motion Path", "motion.move_path", json!({"dx": x - a.x, "dy": y - a.y})); + } + }); + } let mut orient = m.orient; if crate::theme::checkbox(ui, &mut orient, "Orient to path").on_hover_text("Turn the object as its motion path turns").named("Orient to path").changed() { app.run("motion.orient", json!({"orient": orient})); diff --git a/src/pathtools.rs b/src/pathtools.rs index 67a2fac9..d8c098c5 100644 --- a/src/pathtools.rs +++ b/src/pathtools.rs @@ -85,6 +85,14 @@ pub fn pen_input(app: &mut App, ui: &egui::Ui, resp: &egui::Response, xf: Xf) { let (pressed, down, alt) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_down(), i.modifiers.alt)); let Some(pos) = resp.interact_pointer_pos().or_else(|| resp.hover_pos()) else { return }; let p = xf.to_stage(pos); + // Alt-click on a path, with no path being drawn, adds a point to it: the motion path first + // (ADR 0038), then a selected shape's outline. + if pressed && resp.hovered() && alt && app.pen.as_ref().is_none_or(|pen| pen.knots.is_empty()) { + app.pen = None; + if crate::motion_path::pen_alt_click(app, pos, xf) || add_point_on_selected(app, pos, xf) { + return; + } + } if pressed && resp.hovered() { let tol = PICK * xf.unit(); let pen = app.pen.get_or_insert_with(PenPath::default); @@ -319,15 +327,23 @@ pub fn subselect_click(app: &mut App, at: Pos2, shift: bool, xf: Xf) { /// Double-click on a selected shape's outline adds a point there and selects it. pub fn subselect_double_click(app: &mut App, at: Pos2, xf: Xf) { + add_point_on_selected(app, at, xf); +} + +/// Adds a point where screen point `at` is on a selected shape's outline and selects it (the +/// Subselection double-click, the Pen's Alt-click). False when it wasn't on one. +fn add_point_on_selected(app: &mut App, at: Pos2, xf: Xf) -> bool { let sp = xf.to_stage(at); for (id, _, _) in selected_shapes(app) { let r = app.s.execute("path.add_point", &json!({"id": id.0, "x": sp.x, "y": sp.y, "slop": PICK * xf.unit()})); if let Ok(v) = r { app.points = v["cmd"].as_u64().map(|c| vec![(id, c as usize, ANCHOR)]).unwrap_or_default(); - app.status_ok("Added a point. Ctrl+Z to undo."); - return; + app.motion_anchors.clear(); + app.status_ok(format!("Added a point. {} to undo.", crate::platform::shortcut_label("Ctrl+Z"))); + return true; } } + false } /// Anchors in the point selection, grouped per element. diff --git a/src/stage.rs b/src/stage.rs index be24db66..c325d8eb 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -255,7 +255,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // ---- tools ---------------------------------------------------------------------------- - let (shift, alt, space) = ui.input(|i| (i.modifiers.shift, i.modifiers.alt, i.key_down(Key::Space))); + let (shift, alt, space, command) = ui.input(|i| (i.modifiers.shift, i.modifiers.alt, i.key_down(Key::Space), i.modifiers.command)); let pointer = resp.hover_pos().or_else(|| resp.interact_pointer_pos()); app.cursor_stage = pointer.filter(|p| canvas.contains(*p)).map(to_stage); let panning = app.tool == Tool::Hand || space || resp.dragged_by(egui::PointerButton::Middle); @@ -284,6 +284,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { crate::motion_path::hit(app, &shown, p, xf, open).map(|g| (shown, g)) }; let mp_hot = if mp_tools && app.drag == Drag::None { pointer.and_then(|p| mp_grab(app, p)).map(|(_, g)| g) } else { None }; + // Ctrl (⌘) with the path or its object under the pointer: a drag moves the whole path + // (ADR 0038). The Pen with Alt over the path adds a point there. + let mp_move = mp_tools && command && app.drag == Drag::None && pointer.is_some_and(|p| crate::motion_path::move_hit(app, p, xf)); + let pen_hot = if app.tool == Tool::Pen && alt && !panning && !preview && app.drag == Drag::None { pointer.and_then(|p| crate::motion_path::pen_hot(app, p, xf)) } else { None }; if resp.hovered() { let icon = match app.tool { _ if panning => CursorIcon::Grab, @@ -293,7 +297,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Tool::Camera => CursorIcon::Grab, _ if hint_hot.is_some() && app.drag == Drag::None => CursorIcon::Grab, _ if matches!(app.drag, Drag::MotionPath { .. }) => CursorIcon::Grabbing, + _ if mp_move || matches!(app.drag, Drag::MotionMove { .. }) => CursorIcon::Move, _ if mp_hot.is_some() => CursorIcon::Grab, + _ if pen_hot.is_some() => CursorIcon::Copy, Tool::Width => crate::widthtool::cursor(app, pointer, xf), Tool::Transform => { let zone = match app.drag { @@ -342,6 +348,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } else if let Some(m) = hint_at(press) { app.s.begin_gesture("Move Shape Hint"); Drag::Hint { index: m.index, side: m.side } + } else if mp_tools && command && crate::motion_path::move_hit(app, press, xf) { + crate::motion_path::move_start(app, to_v(sp)) } else if let Some((shown, grab)) = mp_tools.then(|| mp_grab(app, press)).flatten() { crate::motion_path::drag_start(app, shown, grab, to_v(sp)) } else { @@ -434,6 +442,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let (grab, start) = (*grab, *start); crate::motion_path::drag_to(app, grab, start, c, alt); } + (Drag::MotionMove { last }, Some(c)) => { + let d = c - *last; + *last = c; + crate::motion_path::move_to(app, Vec2::new(d.x, d.y)); + } (Drag::Hint { index, side }, Some(c)) => { // Live: the hint snaps to the nearest edge as the pointer moves. let (index, side) = (*index, *side); @@ -466,7 +479,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.drop_raw(); app.s.end_gesture(); } - Drag::Transform { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } => app.s.end_gesture(), + Drag::Transform { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } => app.s.end_gesture(), Drag::Width { .. } => crate::widthtool::drag_end(app), Drag::MotionPath { .. } => crate::motion_path::drag_end(app), Drag::PointMarquee { start, cur } => crate::pathtools::marquee_points(app, start, cur, shift), @@ -502,7 +515,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let sp = to_stage(p); match app.tool { Tool::Subselect if !panning => { - if !crate::motion_path::click(app, p, xf) { + if !crate::motion_path::click(app, p, xf, shift) { crate::pathtools::subselect_click(app, p, shift, xf); } } @@ -562,7 +575,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { let sp = to_stage(p); let under = app.s.hit_test(to_v(sp), 3.0 / zoom).map(|(_, e)| e); - if under.is_none_or(|e| !app.s.selection.contains(&e)) { + // On the motion path, the menu is for its points: the selection stays. + let on_path = !panning && crate::motion_path::secondary_click(app, p, xf); + if !on_path && under.is_none_or(|e| !app.s.selection.contains(&e)) { app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": false})); } } @@ -583,13 +598,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { && !preview && resp.double_clicked() && let Some(p) = resp.interact_pointer_pos() + // On the motion path first, else on a selected shape's outline. + && !crate::motion_path::double_click(app, p, xf) { crate::pathtools::subselect_double_click(app, p, xf); } resp.context_menu(|ui| { ui.set_min_width(220.0); - if crate::shape_hints::menu(app, ui) || crate::pathtools::point_menu(app, ui) { + if crate::shape_hints::menu(app, ui) || crate::motion_path::menu(app, ui) || crate::pathtools::point_menu(app, ui) { return; } if app.s.selection.is_empty() { @@ -872,7 +889,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { let hot = match app.drag { Drag::MotionPath { grab, .. } => Some(grab), - _ => mp_hot, + _ => mp_hot.or(pen_hot), }; crate::motion_path::draw(app, &painter, &shown, xf, hot); }