diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 39e26672..3b864a9f 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -559,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 3abb1762..f01e57b2 100644 --- a/crates/engine/src/motion_path_tests.rs +++ b/crates/engine/src/motion_path_tests.rs @@ -322,6 +322,8 @@ fn converting_a_point_makes_it_a_corner_or_smooth() { 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"); 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); }