diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 0e5e8f8b..39e26672 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 { diff --git a/crates/engine/src/motion_path_tests.rs b/crates/engine/src/motion_path_tests.rs index dd6cf8b5..3abb1762 100644 --- a/crates/engine/src/motion_path_tests.rs +++ b/crates/engine/src/motion_path_tests.rs @@ -203,3 +203,186 @@ 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 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 6fcb6557..8f0c0a93 100644 --- a/crates/geom/src/edit.rs +++ b/crates/geom/src/edit.rs @@ -395,7 +395,8 @@ fn merge_cubics(a: [Vec2; 4], b: [Vec2; 4]) -> Option<[Vec2; 4]> { 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]); - if !(poly(&a) + poly(&b) > 1e-6) { + // (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]); }