From 66d8d6deec385dcb2a0b7add7be70f60680131eb Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 18:37:09 -0700 Subject: [PATCH 1/9] docs: reserve ADR 0045 for raw points (M1) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..8ec5d830 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0045 | m1/raw-points | Raw points: add, delete, smooth pairs, snapping while drawing, raw shapes inside symbols | From 2571a71cdac483fc1fa34c80c774dcce98f01817 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 18:45:48 -0700 Subject: [PATCH 2/9] feat(engine): add and delete raw anchors, smooth handle pairs, Make Smooth/Corner on raw points, snapping while drawing (M1) --- crates/engine/src/cmds_path.rs | 32 ++- crates/engine/src/cmds_raw.rs | 59 +++- crates/engine/src/cmds_rawpoints.rs | 246 +++++++++++++++++ crates/engine/src/cmds_rawsub.rs | 45 ++- crates/engine/src/lib.rs | 4 + crates/engine/src/rawpoints_tests.rs | 263 ++++++++++++++++++ crates/geom/src/edit.rs | 2 +- crates/geom/src/raw.rs | 396 +++++++++++++++++++++++++++ 8 files changed, 1039 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/cmds_rawpoints.rs create mode 100644 crates/engine/src/rawpoints_tests.rs diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs index fa223743..62e4ba18 100644 --- a/crates/engine/src/cmds_path.rs +++ b/crates/engine/src/cmds_path.rs @@ -9,7 +9,7 @@ use crate::cmds_draw::{MAX_EXTENT, add_shape, object_param, style}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{Element, ElementId, ElementKind, Shape}; -use anicraft_geom::edit::{ANCHOR, polyline_path, simplify}; +use anicraft_geom::edit::{ANCHOR, C1, C2, polyline_path, simplify}; use anicraft_geom::{Affine, Path, PathCmd, Vec2, fit_curve}; use serde_json::{Value, json}; use std::collections::BTreeSet; @@ -28,7 +28,7 @@ pub fn specs() -> Vec { true, draw_freehand, ), - c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy}", true, move_points), + c("path.move_points", "Move Points", "", None, "{id, points: [[cmd, slot], ..], dx, dy, smooth?: bool} (a handle moved alone at a smooth anchor turns the other one with it, keeping its length, unless smooth is false: Alt breaks the pair)", true, move_points), c("path.add_point", "Add Anchor Point", "", None, "{id, x, y, slop?}", true, add_point), c("path.delete_points", "Delete Anchor Points", "", None, "{id, cmds: [..]}", true, delete_points), c("path.convert_point", "Convert Anchor Point", "", None, "{id, cmd, smooth: bool}", true, convert_point), @@ -149,6 +149,7 @@ fn move_points(s: &mut Session, p: &Value) -> Result { let slot = pair.get(1).and_then(Value::as_u64).filter(|s| *s <= 2).ok_or_else(bad)?; wanted.push((usize::try_from(cmd).unwrap_or(usize::MAX), slot as u8)); } + let smooth = opt_bool(p, "smooth")?.unwrap_or(true); let (sh, m) = shape_mut(s, p)?; let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?; let local = inv.apply_vector(d); @@ -168,15 +169,42 @@ fn move_points(s: &mut Session, p: &Value) -> Result { set.insert((cmd, slot)); } } + // The other handle of a smooth anchor whose handle moves alone (ADR 0045), as it was. + let partners: Vec<(usize, u8, Vec2, Vec2)> = if smooth { set.iter().filter_map(|&(cmd, slot)| partner(path, &set, cmd, slot)).collect() } else { Vec::new() }; for &(cmd, slot) in &set { if let Some(q) = path.point(cmd, slot) { path.set_point(cmd, slot, q + local); } } + for (cmd, slot, anchor, handle) in partners { + if let Some(k) = path.point(cmd, slot) { + path.set_point(cmd, slot, anicraft_geom::raw::turned_opposite(anchor, handle + local, k)); + } + } check_path(path)?; Ok(json!({"moved": set.len()})) } +/// For handle `(cmd, slot)` moving alone: the other handle of its anchor when the anchor is smooth +/// and that handle stays (`(cmd, slot)`), with the anchor and this handle where they are now. +fn partner(path: &Path, moving: &BTreeSet<(usize, u8)>, cmd: usize, slot: u8) -> Option<(usize, u8, Vec2, Vec2)> { + // Slot 2 is the in-handle of anchor `cmd`; slot 1 the out-handle of the anchor before. + let anchor = match slot { + C2 => path.canonical_anchor(cmd), + C1 => path.canonical_anchor(cmd.checked_sub(1)?), + _ => return None, + }; + let (i, o) = path.anchor_segments(anchor); + let other = if slot == C2 { (o?, C1) } else { (i?, C2) }; + if moving.contains(&other) || path.anchor_group(anchor).iter().any(|g| g.1 == ANCHOR && moving.contains(g)) { + return None; + } + let (a, h, k) = (path.point(anchor, ANCHOR)?, path.point(cmd, slot)?, path.point(other.0, other.1)?); + // A quadratic's control is both its ends' handle: turning it would bend the other end. + let cubic = |c: usize| matches!(path.cmds.get(c), Some(PathCmd::CubicTo(..))); + (cubic(other.0) && anicraft_geom::raw::smooth_at(a, h, k)).then_some((other.0, other.1, a, h)) +} + fn add_point(s: &mut Session, p: &Value) -> Result { let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 1000.0); diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index 7b122f1b..e5e16f90 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -158,7 +158,7 @@ fn hit(s: &mut Session, p: &Value) -> Result { } /// Makes the layer of what is at `at` (within `slop`) the active one, as a click does. -fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) { +pub(crate) fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) { if let Some((layer, _)) = s.hit_test(at, slop) && layer != s.layer { @@ -263,6 +263,38 @@ pub(crate) fn edit_edge(s: &mut Session, id: ElementId, cmd: usize, old: &Cubic, Ok(changed) } +/// Changes every copy of the edge `old` (stage space) into `new` (same ends): in every raw shape on +/// the editable keyframe, or only in `only` (a drawing object edits itself alone). Returns the +/// shapes that changed. +pub(crate) fn follow_edge(s: &mut Session, only: Option, old: &Cubic, new: &Cubic) -> Result> { + let area = new.iter().chain(old).fold(Rect::EMPTY, |mut r, q| { + r.include(*q); + r + }); + let kf = s.editable_keyframe()?; + let mut changed = Vec::new(); + for e in kf.elements.iter_mut() { + let take = match only { + Some(id) => e.id == id, + None => mergeable(e).is_some_and(|x| !reach(x, &e.transform).intersect(&area).is_empty()), + }; + if !take { + continue; + } + let (Some(inv), ElementKind::Shape(x)) = (e.transform.inverse(), &e.kind) else { continue }; + let mut edited = (*x.path).clone(); + if rawgeom::follow(&mut edited, &rawgeom::transform(old, &inv), &rawgeom::transform(new, &inv), SNAP / e.transform.mean_scale().max(1e-6)) == 0 { + continue; + } + check_extent(&edited)?; + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(edited); + } + changed.push(e.id); + } + Ok(changed) +} + // ----- moving shared points --------------------------------------------------------------------- fn points_param(p: &Value) -> Result>> { @@ -497,6 +529,31 @@ fn snap_point(els: &[Arc], to: Vec2, radius: f32, moving: &[(ElementId, snap_to(&t, to, radius).map(|(q, k, _)| (q, k)) } +/// Where a point drawn at `p` snaps (the Line, Rectangle, Oval, PolyStar and Pen tools, ADR +/// 0045): the nearest anchor within `radius`, else the nearest point on a line or fill edge, of +/// what the stage shows near it. +pub(crate) fn snap_drawn(s: &Session, p: Vec2, radius: f32) -> Option<(Vec2, SnapTo)> { + if !(radius > 0.0 && p.is_finite()) { + return None; + } + let dl = s.display_list(); + let mut t = Targets::default(); + for item in dl.items.iter() { + if t.points.len() + t.segs.len() > MAX_TARGETS { + break; + } + let pad = item.stroke.as_ref().map_or(0.0, |st| st.reach() * item.transform.mean_scale()); + if !item.path.bounds().transformed(&item.transform).inflate(pad + radius).contains(p) { + continue; + } + let mut path = (*item.path).clone(); + path.close_explicitly(); + t.points.extend(path.editable_anchors().into_iter().map(|(_, q)| item.transform.apply(q))); + t.segs.extend((0..path.cmds.len().min(MAX_TARGETS)).filter_map(|k| rawgeom::segment_cubic(&path, k)).map(|c| rawgeom::transform(&c, &item.transform))); + } + snap_to(&t, p, radius).map(|(q, k, _)| (q, k)) +} + /// After the selection moved: the extra move that snaps one of its anchors (the nearest to /// `from` when given, else whichever comes closest) onto an anchor or line of the shapes that /// did not move, within `radius`. diff --git a/crates/engine/src/cmds_rawpoints.rs b/crates/engine/src/cmds_rawpoints.rs new file mode 100644 index 00000000..b4b9bbbe --- /dev/null +++ b/crates/engine/src/cmds_rawpoints.rs @@ -0,0 +1,246 @@ +//! Adding and deleting the anchors of raw drawings, making them smooth or corners, and where a +//! point being drawn snaps (ADR 0045; issue #42 §1 and §3). +//! +//! A layer's merged drawing stores a shared point once in each shape that has it (ADR 0031), so +//! these work on positions, as the Subselection tool shows them (`raw.points`), and change every +//! copy alike: an added point is added to every shape with that edge; a deleted one is joined +//! across in every shape that has it, so the drawing stays connected. + +use crate::cmds_raw::{activate_layer_at, check_extent, follow_edge, positions_param, remerge_in_place, snap_drawn}; +use crate::merge::{mergeable, reach}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ElementId, ElementKind, Keyframe}; +use anicraft_geom::planar::SNAP; +use anicraft_geom::raw::{self as rawgeom, Seg, Sub}; +use anicraft_geom::{Path, Vec2}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "raw.add_point", + "Add Anchor Point", + "", + None, + "{x, y, slop?} adds an anchor on the raw line or fill edge at (x, y): every raw shape with that edge gets it, and the curve keeps its shape; returns where it is", + true, + add_point as crate::RunFn, + ), + c( + "raw.delete_points", + "Delete Anchor Points", + "", + None, + "{points: [[x, y], ..]} deletes the raw anchors at those positions (as raw.points lists them): every shape that has one is joined across it, so the drawing stays connected; a free end shortens its line; a shape left with nothing is removed; a point where three or more edges meet is kept", + true, + delete_points, + ), + c( + "raw.convert_points", + "Convert Anchor Points", + "", + None, + "{points: [[x, y], ..], smooth: bool} makes the raw anchors at those positions smooth (their handles in one line) or corners (handles drawn in), in every shape that has them", + true, + convert_points, + ), + c( + "draw.snap", + "Snap Point", + "", + None, + "{x, y, snap} where a point drawn at (x, y) snaps while Snap to Objects is on: the nearest anchor within `snap` stage units, else the nearest point on a line or fill edge; returns {x, y, snapped: {x, y, to} | null}", + false, + snap_cmd, + ), + ] +} + +/// Ends of segments this near a position are at it (the copies of a shared point lie within +/// `SNAP` of each other, ADR 0042). +const ENDS: f32 = 1.5 * SNAP; + +/// The raw shapes on `kf` near `at`: index, whether filled, and stage-space subpaths. +fn near(kf: &Keyframe, at: Vec2) -> Vec<(usize, bool, Vec)> { + kf.elements + .iter() + .enumerate() + .filter_map(|(i, e)| { + let sh = mergeable(e)?; + reach(sh, &e.transform).contains(at).then(|| (i, sh.fill.is_some(), rawgeom::subpaths(&sh.path.transformed(&e.transform)))) + }) + .collect() +} + +/// The distinct edges leaving `at` among `shapes`. +fn edges(shapes: &[(usize, bool, Vec)], at: Vec2) -> Vec { + rawgeom::distinct_edges(shapes.iter().flat_map(|(_, _, subs)| rawgeom::edges_at(subs, at, ENDS)), ENDS) +} + +fn points(p: &Value) -> Result> { + let pts = positions_param(p, "points")?; + if pts.is_empty() { + return Err(EngineError::Param("param 'points' is required: the positions of the anchors, as raw.points lists them".into())); + } + Ok(pts) +} + +// ----- adding ------------------------------------------------------------------------------------ + +fn add_point(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let slop = opt_f32(p, "slop")?.unwrap_or(4.0).clamp(0.0, 100.0); + activate_layer_at(s, at, slop); + // The nearest raw line or fill edge. + let mut best: Option<(f32, Vec2)> = None; + for e in s.visible_elements() { + let Some(sh) = mergeable(&e) else { continue }; + if !reach(sh, &e.transform).inflate(slop).contains(at) { + continue; + } + let mut path = (*sh.path).clone(); + path.close_explicitly(); + let half = sh.stroke.as_ref().map_or(0.0, |st| st.width * 0.5 * e.transform.mean_scale()); + if let Some((cmd, t, d)) = path.nearest_segment(at, &e.transform) + && d <= slop + half + && best.is_none_or(|b| d < b.0) + && let Some(q) = path.segment_point(cmd, t) + { + best = Some((d, e.transform.apply(q))); + } + } + let (_, q) = best.ok_or_else(|| EngineError::State("no line or fill edge of a merged drawing there".into()))?; + let kf = s.editable_keyframe()?; + if near(kf, q).iter().any(|(_, _, subs)| subs.iter().flat_map(|sb| &sb.segs).any(|g| g.c[0].distance(q) <= 2.0 * SNAP || g.c[3].distance(q) <= 2.0 * SNAP)) { + return Err(EngineError::State("there is a point there already".into())); + } + let mut changed = Vec::new(); + for e in kf.elements.iter_mut() { + let Some(sh) = mergeable(e) else { continue }; + if !reach(sh, &e.transform).contains(q) { + continue; + } + let Some(inv) = e.transform.inverse() else { continue }; + let mut path = (*sh.path).clone(); + path.close_explicitly(); + let len = path.cmds.len(); + // Splits the segment through the point (de Casteljau: the curve is unchanged). + rawgeom::anchors_at(&mut path, inv.apply(q), SNAP / e.transform.mean_scale().max(1e-6)); + if path.cmds.len() == len { + continue; + } + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(path); + } + changed.push(e.id); + } + if changed.is_empty() { + return Err(EngineError::State("cannot add a point there".into())); + } + // Nothing moved, so nothing merges: the point stays until a merge finds it on a straight + // line that it no longer bends (issue #42 §1). + Ok(json!({"x": q.x, "y": q.y, "changed": changed.iter().map(|e| e.0).collect::>()})) +} + +// ----- deleting ---------------------------------------------------------------------------------- + +fn delete_points(s: &mut Session, p: &Value) -> Result { + let pts = points(p)?; + let (mut deleted, mut kept) = (0usize, 0usize); + let mut changed: Vec = Vec::new(); + let mut removed: Vec = Vec::new(); + for at in pts { + let kf = s.editable_keyframe()?; + let shapes = near(kf, at); + let edges = edges(&shapes, at); + let joined = match edges.as_slice() { + [] => continue, + [_] => None, + [a, b] => Some(rawgeom::join(a, b).ok_or_else(|| EngineError::Param("cannot join the lines across that point".into()))?), + _ => { + kept += 1; + continue; + } + }; + let mut gone: Vec = Vec::new(); + let mut any = false; + for (i, filled, mut subs) in shapes { + if !rawgeom::delete_anchor(&mut subs, at, &edges, joined.as_ref(), ENDS) { + continue; + } + rawgeom::tidy(&mut subs, filled); + let Some(e) = kf.elements.get_mut(i) else { continue }; + any = true; + if subs.is_empty() { + gone.push(e.id); + continue; + } + let Some(inv) = e.transform.inverse() else { continue }; + let path: Path = rawgeom::from_subpaths(&subs).transformed(&inv); + check_extent(&path)?; + if let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind { + x.path = Arc::new(path); + } + if !changed.contains(&e.id) { + changed.push(e.id); + } + } + kf.elements.retain(|e| !gone.contains(&e.id)); + changed.retain(|id| !gone.contains(id)); + removed.extend(gone); + deleted += usize::from(any); + } + if deleted == 0 { + return Err(EngineError::State(if kept > 0 { "a point where three or more lines meet can't be deleted; delete a line there instead".into() } else { "no point of a merged drawing there".into() })); + } + let here = s.layer; + s.selection.retain(|l, id| l != here || !removed.contains(&id)); + // Joined runs and fills merge again with what they touch, as after any edit. + remerge_in_place(s, &changed)?; + Ok(json!({"deleted": deleted, "kept": kept, "removed": removed.iter().map(|e| e.0).collect::>(), "selected": s.selection.id_list()})) +} + +// ----- smooth and corner ------------------------------------------------------------------------- + +fn convert_points(s: &mut Session, p: &Value) -> Result { + let pts = points(p)?; + let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required".into()))?; + let mut changed: Vec = Vec::new(); + let mut converted = 0usize; + for at in pts { + let kf = s.editable_keyframe()?; + let edges = edges(&near(kf, at), at); + let edits: Vec<(Seg, Seg)> = if smooth { + match edges.as_slice() { + [a, b] => rawgeom::smooth_pair(a, b).map(|(na, nb)| vec![(*a, na), (*b, nb)]).unwrap_or_default(), + _ => Vec::new(), + } + } else { + edges.iter().filter_map(|e| rawgeom::corner(e).map(|n| (*e, n))).collect() + }; + converted += usize::from(!edits.is_empty()); + for (old, new) in edits { + for id in follow_edge(s, None, &old.c, &new.c)? { + if !changed.contains(&id) { + changed.push(id); + } + } + } + } + remerge_in_place(s, &changed)?; + Ok(json!({"converted": converted, "changed": changed.len()})) +} + +// ----- snapping while drawing -------------------------------------------------------------------- + +fn snap_cmd(s: &mut Session, p: &Value) -> Result { + let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?); + let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0)); + Ok(match snap_drawn(s, at, radius) { + Some((q, kind)) => json!({"x": q.x, "y": q.y, "snapped": {"x": q.x, "y": q.y, "to": kind.key()}}), + None => json!({"x": at.x, "y": at.y, "snapped": null}), + }) +} diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs index 7187da73..b6ba1e86 100644 --- a/crates/engine/src/cmds_rawsub.rs +++ b/crates/engine/src/cmds_rawsub.rs @@ -10,8 +10,8 @@ //! Which anchors are selected is view state, kept by the editor (as for drawing objects): the //! commands here report anchors and handles by stage position, and take positions back. -use crate::cmds_raw::{check_extent, edit_edge, remerge_in_place}; -use crate::merge::mergeable; +use crate::cmds_raw::{check_extent, edit_edge, follow_edge, remerge_in_place}; +use crate::merge::{mergeable, reach}; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{Element, ElementId, ElementKind}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Move Handle", "", None, - "{id, cmd, slot: 1|2, dx, dy, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false)", + "{id, cmd, slot: 1|2, dx, dy, smooth?: bool, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false); at a smooth anchor the other handle turns to stay opposite, keeping its length (unless smooth is false: Alt breaks the pair)", true, move_handle, ), @@ -400,6 +400,32 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { // ----- handles ----------------------------------------------------------------------------------- +/// The other curve at the anchor of handle `slot` of `old` (stage space) when the anchor is smooth +/// there: the one edge leaving it whose handle lies opposite this one ([`rawgeom::smooth_at`]), in +/// any raw shape on the layer (or in `el` alone, a drawing object). Oriented from the anchor. +fn opposite_handle(els: &[Arc], el: &Element, raw: bool, old: &Cubic, slot: usize) -> Option { + let (a, h) = if slot == 1 { (old[0], old[1]) } else { (old[3], old[2]) }; + let dragged = rawgeom::Seg { c: if slot == 1 { *old } else { [old[3], old[2], old[1], old[0]] }, line: false }; + let tol = 1.5 * SNAP; + let mut subs = Vec::new(); + let from = |e: &Element| match &e.kind { + ElementKind::Shape(sh) => rawgeom::subpaths(&sh.path.transformed(&e.transform)), + _ => Vec::new(), + }; + if raw { + for e in els.iter().filter(|e| mergeable(e).is_some_and(|sh| reach(sh, &e.transform).contains(a))) { + subs.extend(from(e)); + } + } else { + subs = from(el); + } + let edges = rawgeom::distinct_edges(rawgeom::edges_at(&subs, a, tol), tol); + let mut found = edges.into_iter().filter(|f| !rawgeom::same_edge(f, &dragged, tol) && !f.line && rawgeom::smooth_at(a, h, f.c[1])); + let f = found.next()?; + // Two candidates: a junction, not a smooth pair. + found.next().is_none().then_some(f) +} + fn move_handle(s: &mut Session, p: &Value) -> Result { let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?; @@ -426,7 +452,18 @@ fn move_handle(s: &mut Session, p: &Value) -> Result { bounds.move_to(new[0]).cubic_to(new[1], new[2], new[3]); check_extent(&bounds)?; let raw = mergeable(el).is_some(); - let changed = edit_edge(s, id, cmd, &old, &new, raw)?; + // A smooth anchor's other handle turns with this one (ADR 0045). + let partner = if opt_bool(p, "smooth")?.unwrap_or(true) { opposite_handle(&els, el, raw, &old, slot).map(|f| (f, new[slot])) } else { None }; + let mut changed = edit_edge(s, id, cmd, &old, &new, raw)?; + if let Some((f, h)) = partner { + let a = f.c[0]; + let turned = rawgeom::Seg { c: [a, rawgeom::turned_opposite(a, h, f.c[1]), f.c[2], f.c[3]], line: false }; + for e in follow_edge(s, (!raw).then_some(id), &f.c, &turned.c)? { + if !changed.contains(&e) { + changed.push(e); + } + } + } if raw && merge_after { remerge_in_place(s, &changed)?; } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 753276fc..073dd9ab 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,6 +20,7 @@ mod cmds_paint; mod cmds_path; pub mod cmds_raw; pub mod cmds_rawsub; +mod cmds_rawpoints; mod cmds_recovery; mod cmds_script; pub mod cmds_plugin; @@ -116,6 +117,7 @@ pub fn commands() -> Vec { v.extend(cmds_path::specs()); v.extend(cmds_raw::specs()); v.extend(cmds_rawsub::specs()); + v.extend(cmds_rawpoints::specs()); v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); @@ -902,6 +904,8 @@ mod raw_tests; #[cfg(test)] mod rawsub_tests; #[cfg(test)] +mod rawpoints_tests; +#[cfg(test)] mod brush_tests; #[cfg(test)] mod web_tests; diff --git a/crates/engine/src/rawpoints_tests.rs b/crates/engine/src/rawpoints_tests.rs new file mode 100644 index 00000000..17c94bdf --- /dev/null +++ b/crates/engine/src/rawpoints_tests.rs @@ -0,0 +1,263 @@ +//! Adding and deleting raw anchors, smooth handle pairs, Make Smooth / Corner and snapping while +//! drawing (ADR 0045), through the commands. + +use crate::Session; +use anicraft_doc::{Element, ElementKind}; +use anicraft_geom::raw::{self as rawgeom}; +use anicraft_geom::walk::cubic_point; +use anicraft_geom::Vec2; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn raw_session() -> Session { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + s +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn is_fill(e: &Element) -> bool { + matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some()) +} + +fn all_ids(s: &Session) -> Vec { + raw(s).iter().map(|e| e.id).collect() +} + +fn anchors(s: &Session) -> Vec { + s.raw_points(&all_ids(s)).anchors +} + +fn has(points: &[Vec2], p: (f32, f32)) -> bool { + points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3) +} + +fn area(e: &Element) -> f32 { + let ElementKind::Shape(sh) = &e.kind else { return 0.0 }; + sh.path.flatten(&e.transform, 0.01).iter().map(|pl| pl.points.iter().zip(pl.points.iter().cycle().skip(1)).map(|(a, b)| a.cross(*b)).sum::() * 0.5).sum::().abs() +} + +/// Every shape's anchors in stage space. +fn shape_anchors(e: &Element) -> Vec { + match &e.kind { + ElementKind::Shape(sh) => sh.path.editable_anchors().into_iter().map(|(_, q)| e.transform.apply(q)).collect(), + _ => Vec::new(), + } +} + +/// Largest distance from points of the curve `c` (stage space) to the shape's outline. +fn off_outline(e: &Element, c: &rawgeom::Cubic) -> f32 { + let ElementKind::Shape(sh) = &e.kind else { return f32::INFINITY }; + (0..=20).map(|i| sh.path.distance_to_edge(cubic_point(c, i as f32 / 20.0), &e.transform)).fold(0.0, f32::max) +} + +/// A raw arc (a fill under it and its outline): `M0 100 C0 0 200 0 200 100 Z`. +fn arc(s: &mut Session) -> rawgeom::Cubic { + run(s, "draw.path", json!({"d": "M0 100 C0 0 200 0 200 100 Z", "fill": "#ff0000", "stroke": "#000000"})); + run(s, "edit.deselect", json!({})); + [Vec2::new(0.0, 100.0), Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), Vec2::new(200.0, 100.0)] +} + +#[test] +fn an_added_point_is_shared_by_every_shape_on_the_edge_and_the_curve_keeps_its_shape() { + let mut s = raw_session(); + let c = arc(&mut s); + let before = anchors(&s).len(); + // How far the outlines are from the drawn curve (flattening): adding may not change it. + let was: Vec<(anicraft_doc::ElementId, f32)> = raw(&s).iter().map(|e| (e.id, off_outline(e, &c))).collect(); + let top = cubic_point(&c, 0.5); + let v = run(&mut s, "raw.add_point", json!({"x": top.x, "y": top.y + 1.0, "slop": 4})); + let at = Vec2::new(v["x"].as_f64().unwrap_or(0.0) as f32, v["y"].as_f64().unwrap_or(0.0) as f32); + assert!(at.distance(top) < 0.05, "on the curve: {at:?} vs {top:?}"); + assert_eq!(v["changed"].as_array().map(Vec::len), Some(2), "the fill and its outline: {v}"); + assert_eq!(anchors(&s).len(), before + 1, "listed once"); + let changed: Vec = v["changed"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + for e in raw(&s).into_iter().filter(|e| changed.contains(&e.id.0)) { + assert!(has(&shape_anchors(&e), (at.x, at.y)), "{} lacks the point", e.id.0); + // Analytic: the old curve still lies on every shape's outline, as closely as before. + let w = was.iter().find(|x| x.0 == e.id).map_or(0.0, |x| x.1); + assert!(off_outline(&e, &c) <= w + 1e-3 && w < 0.25, "the curve moved: {} (was {w})", off_outline(&e, &c)); + } + // One undo step; a second point at the same place is refused. + assert!(s.can_undo()); + assert!(s.execute("raw.add_point", &json!({"x": at.x, "y": at.y})).is_err()); + assert!(s.execute("raw.add_point", &json!({"x": 900, "y": 900})).is_err(), "nothing there"); + // Deleting it gives the curve back, in both shapes. + run(&mut s, "raw.delete_points", json!({"points": [[at.x, at.y]]})); + assert_eq!(anchors(&s).len(), before); + let on_curve: Vec> = raw(&s).into_iter().filter(|e| off_outline(e, &c) < 0.3).collect(); + assert_eq!(on_curve.len(), 2, "the fill and the arc's line still follow the curve"); +} + +#[test] +fn deleting_a_corner_rejoins_the_fill_and_its_outline() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + run(&mut s, "edit.deselect", json!({})); + let steps = s.history_len(); + let v = run(&mut s, "raw.delete_points", json!({"points": [[0, 0]]})); + assert_eq!(v["deleted"], json!(1), "{v}"); + assert_eq!(s.history_len(), steps + 1, "one undo step"); + // A triangle of half the area, outlined all round. + let fill: Vec> = raw(&s).into_iter().filter(|e| is_fill(e)).collect(); + assert_eq!(fill.len(), 1); + assert!((area(&fill[0]) - 4000.0).abs() < 1.0, "{}", area(&fill[0])); + let pts = anchors(&s); + assert_eq!(pts.len(), 3, "{pts:?}"); + assert!(!has(&pts, (0.0, 0.0))); + // Connectivity: every shape's anchors are shared with another shape. + let all = raw(&s); + for e in &all { + for p in shape_anchors(e) { + let n = all.iter().filter(|o| o.id != e.id && has(&shape_anchors(o), (p.x, p.y))).count(); + assert!(n >= 1, "{p:?} of {} is on no other shape", e.id.0); + } + } + // The diagonal is stroked: some outline runs from (0, 80) to (100, 0). + let diag = rawgeom::Seg::line(Vec2::new(0.0, 80.0), Vec2::new(100.0, 0.0)).c; + assert!(all.iter().filter(|e| !is_fill(e)).any(|e| off_outline(e, &diag) < 0.05), "no line on the new edge"); + s.undo().unwrap_or_default(); + assert_eq!(anchors(&s).len(), 4); +} + +#[test] +fn deleting_the_last_points_of_a_line_removes_it_and_junctions_stay() { + let mut s = raw_session(); + run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"})); + let v = run(&mut s, "raw.delete_points", json!({"points": [[100, 0]]})); + assert_eq!(v["removed"].as_array().map(Vec::len), Some(1), "a one-segment line goes: {v}"); + assert!(raw(&s).is_empty()); + assert!(s.selection.is_empty(), "nothing selected that is gone"); + // A T: the point where the stem stands on the bar joins three edges. + run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0, "stroke": "#000000"})); + run(&mut s, "draw.line", json!({"x0": 50, "y0": 0, "x1": 50, "y1": 60, "stroke": "#000000"})); + let n = raw(&s).len(); + let e = s.execute("raw.delete_points", &json!({"points": [[50, 0]]})); + assert!(e.is_err_and(|e| e.to_string().contains("three or more"))); + assert_eq!(raw(&s).len(), n); + // The stem's free end shortens nothing else. + run(&mut s, "raw.delete_points", json!({"points": [[50, 60]]})); + assert!(!has(&anchors(&s), (50.0, 60.0))); + assert!(has(&anchors(&s), (0.0, 0.0)) && has(&anchors(&s), (100.0, 0.0))); + assert!(s.execute("raw.delete_points", &json!({"points": []})).is_err()); + assert!(s.execute("raw.delete_points", &json!({"points": [[500, 500]]})).is_err()); +} + +/// A raw S-curve stroke through (100, 0) with a smooth anchor there. +fn s_curve(s: &mut Session) { + run(s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null})); + run(s, "edit.deselect", json!({})); +} + +/// The handles at `a` listed by `raw.points`. +fn handles_at(s: &Session, a: Vec2) -> Vec { + s.raw_points(&all_ids(s)).handles.into_iter().filter(|h| h.anchor.distance(a) < 0.3).collect() +} + +#[test] +fn dragging_a_smooth_anchors_handle_keeps_the_other_opposite_and_alt_breaks_it() { + let mut s = raw_session(); + s_curve(&mut s); + let a = Vec2::new(100.0, 0.0); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2, "{hs:?}"); + let (h, k) = (hs[0], hs[1]); + let len_k = k.at.distance(a); + run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 0, "dy": 30})); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2); + let (moved, other) = if hs[0].at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5 { (hs[0], hs[1]) } else { (hs[1], hs[0]) }; + assert!(moved.at.distance(h.at + Vec2::new(0.0, 30.0)) < 0.5, "{hs:?}"); + // Colinear: on one line through the anchor, opposite, the other's length kept. + assert!(rawgeom::smooth_at(a, moved.at, other.at), "{moved:?} {other:?}"); + assert!((moved.at - a).normalized().cross((other.at - a).normalized()).abs() < 1e-3); + assert!((other.at.distance(a) - len_k).abs() < 0.3); + // Alt (smooth: false) moves the handle alone: a corner. + let before = other.at; + run(&mut s, "raw.move_handle", json!({"id": moved.id.0, "cmd": moved.cmd, "slot": moved.slot, "dx": 30, "dy": 0, "smooth": false})); + let hs = handles_at(&s, a); + assert!(hs.iter().any(|x| x.at.distance(before) < 0.3), "the other stays: {hs:?}"); + assert!(!rawgeom::smooth_at(a, hs[0].at, hs[1].at)); +} + +#[test] +fn make_corner_and_make_smooth_on_raw_anchors() { + let mut s = raw_session(); + s_curve(&mut s); + let a = Vec2::new(100.0, 0.0); + let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": false})); + assert_eq!(v["converted"], json!(1), "{v}"); + assert!(handles_at(&s, a).is_empty(), "the handles are drawn in"); + let v = run(&mut s, "raw.convert_points", json!({"points": [[a.x, a.y]], "smooth": true})); + assert_eq!(v["converted"], json!(1), "{v}"); + let hs = handles_at(&s, a); + assert_eq!(hs.len(), 2, "{hs:?}"); + assert!(rawgeom::smooth_at(a, hs[0].at, hs[1].at)); + // Smooth on a fill's corner: the fill and both sides it has there follow. + run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "raw.convert_points", json!({"points": [[300, 0]], "smooth": true})); + assert_eq!(v["converted"], json!(1)); + let fill = raw(&s).into_iter().find(|e| is_fill(e)).unwrap_or_else(|| panic!("a fill")); + assert!(area(&fill) > 8000.0, "the corner rounds out: {}", area(&fill)); + for e in raw(&s).iter().filter(|e| !is_fill(e) && e.transform.apply(Vec2::ZERO).x > 250.0) { + let ElementKind::Shape(sh) = &e.kind else { continue }; + let ElementKind::Shape(fs) = &fill.kind else { continue }; + for pl in sh.path.flatten(&e.transform, 0.05) { + for p in pl.points { + assert!(fs.path.distance_to_edge(p, &fill.transform) < 0.3, "{p:?} off the fill's edge"); + } + } + } +} + +#[test] +fn drawing_snaps_to_anchors_then_lines_while_snap_to_objects_is_on() { + let mut s = raw_session(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10})); + assert_eq!(v["snapped"]["to"], json!("point"), "{v}"); + assert_eq!((v["x"].as_f64(), v["y"].as_f64()), (Some(100.0), Some(0.0))); + let v = run(&mut s, "draw.snap", json!({"x": 50, "y": 84, "snap": 10})); + assert_eq!(v["snapped"]["to"], json!("line"), "{v}"); + assert!((v["y"].as_f64().unwrap_or(0.0) - 80.0).abs() < 1e-3 && (v["x"].as_f64().unwrap_or(0.0) - 50.0).abs() < 1e-3); + let v = run(&mut s, "draw.snap", json!({"x": 300, "y": 300, "snap": 10})); + assert!(v["snapped"].is_null()); + // Off, nothing snaps. + run(&mut s, "draw.snap_to_objects", json!({"on": false})); + let v = run(&mut s, "draw.snap", json!({"x": 104, "y": 3, "snap": 10})); + assert!(v["snapped"].is_null() && v["x"] == json!(104.0)); + // A line drawn from a snapped point shares the rectangle's corner. + run(&mut s, "draw.snap_to_objects", json!({"on": true})); + let a = run(&mut s, "draw.snap", json!({"x": 98, "y": 78, "snap": 10})); + run(&mut s, "draw.line", json!({"x0": a["x"], "y0": a["y"], "x1": 200, "y1": 200, "stroke": "#000000"})); + assert!(has(&anchors(&s), (100.0, 80.0)) && anchors(&s).len() == 5, "{:?}", anchors(&s)); +} + +#[test] +fn an_object_paths_smooth_anchor_keeps_its_handles_opposite() { + let mut s = Session::new(anicraft_doc::Document::default()); + let v = run(&mut s, "draw.path", json!({"d": "M0 0 C0 -50 60 -50 100 0 C140 50 200 50 200 0", "stroke": "#000000", "fill": null})); + let id = v["element"].as_u64().unwrap_or(0); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + let p = sh.path.clone(); + // The in-handle of anchor 1 (C2 of command 1) moves; command 2's C1 turns with it. + run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 0, "dy": 25})); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + let (a, h, k) = (sh.path.point(1, 0), sh.path.point(1, 2), sh.path.point(2, 1)); + let (Some(a), Some(h), Some(k)) = (a, h, k) else { panic!("points") }; + assert!(rawgeom::smooth_at(a, h, k), "{a:?} {h:?} {k:?}"); + assert!((k.distance(a) - p.point(2, 1).map_or(0.0, |q| q.distance(a))).abs() < 1e-3, "length kept"); + run(&mut s, "path.move_points", json!({"id": id, "points": [[1, 2]], "dx": 30, "dy": 0, "smooth": false})); + let el = s.visible_elements().into_iter().find(|e| e.id.0 == id).unwrap_or_else(|| panic!("the path")); + let ElementKind::Shape(sh) = &el.kind else { panic!() }; + assert_eq!(sh.path.point(2, 1), Some(k), "Alt moves the handle alone"); +} diff --git a/crates/geom/src/edit.rs b/crates/geom/src/edit.rs index 8f0c0a93..ea9ed0ec 100644 --- a/crates/geom/src/edit.rs +++ b/crates/geom/src/edit.rs @@ -383,7 +383,7 @@ fn leaving(cands: [Vec2; 3]) -> Option { } /// 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]> { +pub(crate) 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]); diff --git a/crates/geom/src/raw.rs b/crates/geom/src/raw.rs index e5f66f93..a16acba5 100644 --- a/crates/geom/src/raw.rs +++ b/crates/geom/src/raw.rs @@ -180,6 +180,298 @@ pub fn anchors_at(path: &mut Path, p: Vec2, tol: f32) -> Vec { } } +// ----- points shared by several shapes (ADR 0045) ------------------------------------------------ + +/// One segment of a subpath: a cubic, and whether it is a straight line (kept a line when the path +/// is written back). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Seg { + pub c: Cubic, + pub line: bool, +} + +impl Seg { + pub fn line(a: Vec2, b: Vec2) -> Seg { + Seg { c: [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b], line: true } + } + /// The same segment run the other way. + pub fn reversed(&self) -> Seg { + Seg { c: [self.c[3], self.c[2], self.c[1], self.c[0]], line: self.line } + } +} + +/// A subpath as its segments, each starting where the one before ends. A closed one ends where +/// it starts. +#[derive(Clone, Debug, PartialEq)] +pub struct Sub { + pub segs: Vec, + pub closed: bool, +} + +/// `path` as subpaths (a `Close` that draws an edge back to the start gets that edge as a line; +/// a lone move is dropped). +pub fn subpaths(path: &Path) -> Vec { + let mut p = path.clone(); + p.close_explicitly(); + let mut out: Vec = Vec::new(); + let mut cur: Option = None; + for k in 0..p.cmds.len().min(MAX_CMDS) { + match p.cmds.get(k) { + Some(PathCmd::MoveTo(_)) => { + out.extend(cur.take().filter(|s| !s.segs.is_empty())); + cur = Some(Sub { segs: Vec::new(), closed: false }); + } + Some(PathCmd::Close) => { + if let Some(mut s) = cur.take().filter(|s| !s.segs.is_empty()) { + s.closed = true; + out.push(s); + } + } + Some(cmd) => { + if let Some(c) = segment_cubic(&p, k) { + let seg = Seg { c, line: matches!(cmd, PathCmd::LineTo(_)) }; + cur.get_or_insert_with(|| Sub { segs: Vec::new(), closed: false }).segs.push(seg); + } + } + None => break, + } + } + out.extend(cur.filter(|s| !s.segs.is_empty())); + out +} + +/// The path of `subs` (lines as lines, everything else as cubics). +pub fn from_subpaths(subs: &[Sub]) -> Path { + let mut p = Path::new(); + for s in subs { + let Some(first) = s.segs.first() else { continue }; + p.move_to(first.c[0]); + for g in &s.segs { + if g.line { + p.line_to(g.c[3]); + } else { + p.cubic_to(g.c[1], g.c[2], g.c[3]); + } + } + if s.closed { + p.close(); + } + } + p +} + +/// The segments of `subs` that start or end at `at` (within `tol`), each as the edge leaving +/// `at` (reversed when it ends there). +pub fn edges_at(subs: &[Sub], at: Vec2, tol: f32) -> Vec { + let mut out = Vec::new(); + for s in subs { + for g in &s.segs { + if g.c[0].distance(at) <= tol { + out.push(*g); + } + if g.c[3].distance(at) <= tol { + out.push(g.reversed()); + } + } + } + out +} + +/// Whether two edges leaving one anchor are the same edge: their far ends and points along them +/// within `tol`. +pub fn same_edge(a: &Seg, b: &Seg, tol: f32) -> bool { + a.c[3].distance(b.c[3]) <= tol && [0.25f32, 0.5, 0.75].iter().all(|&t| cubic_point(&a.c, t).distance(cubic_point(&b.c, t)) <= tol * 2.0) +} + +/// The edges among `edges` that are distinct ([`same_edge`]), in order. +pub fn distinct_edges(edges: impl IntoIterator, tol: f32) -> Vec { + let mut out: Vec = Vec::new(); + for e in edges { + if !out.iter().any(|x| same_edge(x, &e, tol)) { + out.push(e); + } + } + out +} + +/// The one edge in place of the edges `a` and `b` that leave an anchor: from `a`'s far end to +/// `b`'s. Two lines make a line; anything else the cubic that fits both best, keeping the +/// directions they leave their far ends in ([`Path::merge_at`]'s fit). +pub fn join(a: &Seg, b: &Seg) -> Option { + if a.line && b.line { + return Some(Seg::line(a.c[3], b.c[3])); + } + let c = crate::edit::merge_cubics(a.reversed().c, b.c)?; + Some(Seg { c, line: false }) +} + +/// The edges `a` and `b` that leave one anchor, made smooth there: their handles at the anchor on +/// one line, along the direction from `a`'s far end to `b`'s, each a third of its edge's chord +/// long ([`Path::make_smooth`]). `None` when the far ends coincide. +pub fn smooth_pair(a: &Seg, b: &Seg) -> Option<(Seg, Seg)> { + let at = a.c[0]; + let dir = (b.c[3] - a.c[3]).normalized(); + if dir == Vec2::ZERO { + return None; + } + let ha = at - dir * (at.distance(a.c[3]) / 3.0); + let hb = at + dir * (at.distance(b.c[3]) / 3.0); + let (na, nb) = (Seg { c: [at, ha, a.c[2], a.c[3]], line: false }, Seg { c: [at, hb, b.c[2], b.c[3]], line: false }); + (na.c.iter().chain(&nb.c).all(|p| p.is_finite())).then_some((na, nb)) +} + +/// `e` (leaving an anchor) with its handle at the anchor drawn in onto it: a corner there. `None` +/// when it has none to draw in (a line, or a handle already on the anchor). +pub fn corner(e: &Seg) -> Option { + (!e.line && e.c[1].distance(e.c[0]) > 1e-4).then_some(Seg { c: [e.c[0], e.c[0], e.c[2], e.c[3]], line: false }) +} + +/// Handles at one anchor lying on one line, on opposite sides, within this angle's sine (3°): a +/// smooth anchor. +const SMOOTH_SIN: f32 = 0.052; + +/// Whether the handles `h` and `k` of the anchor `a` make it smooth: both off the anchor, on one +/// line through it, on opposite sides. +pub fn smooth_at(a: Vec2, h: Vec2, k: Vec2) -> bool { + let (u, v) = (h - a, k - a); + let (lu, lv) = (u.length(), v.length()); + lu > 1e-4 && lv > 1e-4 && u.dot(v) < 0.0 && (u.cross(v) / (lu * lv)).abs() <= SMOOTH_SIN +} + +/// `k` turned about the anchor `a` so it lies opposite `h`, keeping its length (the other handle +/// of a smooth anchor while `h` is dragged). `k` itself when `h` is on the anchor. +pub fn turned_opposite(a: Vec2, h: Vec2, k: Vec2) -> Vec2 { + let dir = (h - a).normalized(); + if dir == Vec2::ZERO { + return k; + } + a - dir * a.distance(k) +} + +/// Deletes the anchor at `at` (within `tol`) from `subs`, where the drawing has the distinct +/// edges `edges` leaving it. +/// +/// * Two edges: every copy of either becomes `joined` (the edge from the first's far end to the +/// second's, see [`join`]). A run through the anchor takes it once in place of both; a line +/// ending there now runs along the whole new edge, so the drawing stays connected. +/// * One edge (the free end of lines): the segment there goes. +/// +/// Returns whether anything changed. Subpaths may be left empty or flat: see [`tidy`]. +pub fn delete_anchor(subs: &mut [Sub], at: Vec2, edges: &[Seg], joined: Option<&Seg>, tol: f32) -> bool { + let which = |e: &Seg| edges.iter().position(|x| same_edge(x, e, tol)); + let toward = |from: usize| -> Option { + // The new edge leaving the far end of edge `from` (towards the other edge's far end). + let j = joined?; + Some(if from == 0 { *j } else { j.reversed() }) + }; + let mut changed = false; + for s in subs.iter_mut() { + // Each pass takes one vertex at `at`; bounded by the segments there are. + for _ in 0..=s.segs.len() { + let Some(step) = vertex_at(s, at, tol) else { break }; + let done = match step { + Vertex::Through(v) => { + // in: segs[v - 1] arrives, out: segs[v] leaves (v ≥ 1 after rotation). + let (Some(inn), Some(out)) = (s.segs.get(v - 1).copied(), s.segs.get(v).copied()) else { break }; + match (which(&inn.reversed()), which(&out), edges.len()) { + (Some(a), Some(b), 2) if a != b => match toward(a) { + Some(n) => { + s.segs.splice(v - 1..=v, [n]); + true + } + None => false, + }, + _ => false, + } + } + Vertex::Start => match (s.segs.first().and_then(&which), edges.len()) { + // The new first segment ends where the old one did. + (Some(a), 2) => match (toward(1 - a), s.segs.first_mut()) { + (Some(n), Some(first)) => { + *first = n; + true + } + _ => false, + }, + (Some(_), 1) => { + s.segs.remove(0); + true + } + _ => false, + }, + Vertex::End => { + match (s.segs.last().and_then(|g| which(&g.reversed())), edges.len()) { + (Some(a), 2) => match (toward(a), s.segs.last_mut()) { + (Some(n), Some(last)) => { + *last = n; + true + } + _ => false, + }, + (Some(_), 1) => { + s.segs.pop(); + true + } + _ => false, + } + } + }; + if !done { + break; + } + changed = true; + } + } + changed +} + +/// Where a subpath has a vertex at a point. +enum Vertex { + /// Between segments `v - 1` and `v` (a closed subpath is turned so `v ≥ 1`). + Through(usize), + /// An open subpath's start or end. + Start, + End, +} + +fn vertex_at(s: &mut Sub, at: Vec2, tol: f32) -> Option { + let n = s.segs.len(); + if n == 0 { + return None; + } + if s.closed { + let v = s.segs.iter().position(|g| g.c[0].distance(at) <= tol)?; + // Turn the loop so the vertex is not at the seam. + let turn = if v == 0 { n - 1 } else { 0 }; + s.segs.rotate_left(turn); + return Some(Vertex::Through(if v == 0 { 1 } else { v })); + } + if s.segs.first().is_some_and(|g| g.c[0].distance(at) <= tol) { + return Some(Vertex::Start); + } + if s.segs.last().is_some_and(|g| g.c[3].distance(at) <= tol) { + return Some(Vertex::End); + } + (1..n).find(|&v| s.segs.get(v).is_some_and(|g| g.c[0].distance(at) <= tol)).map(Vertex::Through) +} + +/// Drops the subpaths an edit left with nothing to show: no segments, no length, or (when +/// `filled`) a closed outline with no area. +pub fn tidy(subs: &mut Vec, filled: bool) { + subs.retain(|s| { + let pts: Vec = s.segs.iter().flat_map(|g| (0..8).map(move |i| cubic_point(&g.c, i as f32 / 8.0))).chain(s.segs.last().map(|g| g.c[3])).collect(); + let length: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.distance(*b))).sum(); + if s.segs.is_empty() || length <= 1e-3 { + return false; + } + if filled && s.closed { + let area: f32 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map_or(0.0, |(a, b)| a.cross(*b))).sum::() * 0.5; + return area.abs() > 1e-3; + } + true + }); +} + #[cfg(test)] mod tests { use super::*; @@ -235,6 +527,110 @@ mod tests { assert!(anchors_at(&mut p, Vec2::new(40.0, 5.0), 0.2).is_empty()); } + fn v(x: f32, y: f32) -> Vec2 { + Vec2::new(x, y) + } + + #[test] + fn subpaths_round_trip() { + let mut p = Path::rect(0.0, 0.0, 10.0, 10.0); + p.move_to(v(20.0, 0.0)).cubic_to(v(20.0, 5.0), v(25.0, 10.0), v(30.0, 10.0)); + let subs = subpaths(&p); + assert_eq!(subs.len(), 2); + assert!(subs[0].closed && subs[0].segs.len() == 4 && subs[0].segs.iter().all(|g| g.line), "the closing edge is written out: {:?}", subs[0]); + assert!(!subs[1].closed && !subs[1].segs[0].line); + let back = subpaths(&from_subpaths(&subs)); + assert_eq!(back, subs); + } + + /// A raw rectangle as merge drawing stores it: the fill and four sides, each its own path. + fn outlined_rect() -> Vec> { + let (a, b, c, d) = (v(0.0, 0.0), v(100.0, 0.0), v(100.0, 80.0), v(0.0, 80.0)); + // The fill starts at the corner deleted below, to cover the seam. + let fill = vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, d), Seg::line(d, a)], closed: true }]; + let side = |p, q| vec![Sub { segs: vec![Seg::line(p, q)], closed: false }]; + vec![fill, side(a, b), side(b, c), side(c, d), side(d, a)] + } + + fn delete(shapes: &mut [Vec], at: Vec2) -> usize { + let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, at, 0.2)), 0.2); + let joined = if edges.len() == 2 { join(&edges[0], &edges[1]) } else { None }; + shapes.iter_mut().map(|s| delete_anchor(s, at, &edges, joined.as_ref(), 0.2)).filter(|c| *c).count() + } + + #[test] + fn deleting_a_corner_keeps_the_drawing_connected() { + let mut shapes = outlined_rect(); + let edges = distinct_edges(shapes.iter().flat_map(|s| edges_at(s, v(0.0, 0.0), 0.2)), 0.2); + assert_eq!(edges.len(), 2, "two edges meet at a corner, each in the fill and a side"); + assert_eq!(delete(&mut shapes, v(0.0, 0.0)), 3, "the fill and both sides there"); + // The fill is a triangle now, cut along the diagonal from (0, 80) to (100, 0). + let fill = &shapes[0][0]; + assert!(fill.closed && fill.segs.len() == 3 && fill.segs.iter().all(|g| g.line), "{fill:?}"); + assert!(fill.segs.iter().all(|g| g.c[0].distance(v(0.0, 0.0)) > 1.0)); + // Both sides that ended there now run along the diagonal: every anchor is shared. + let diag = Seg::line(v(0.0, 80.0), v(100.0, 0.0)); + for s in [&shapes[1], &shapes[4]] { + let g = s[0].segs[0]; + assert!(same_edge(&g, &diag, 0.01) || same_edge(&g.reversed(), &diag, 0.01), "{g:?}"); + } + let anchors: Vec = shapes.iter().flatten().flat_map(|s| s.segs.iter().flat_map(|g| [g.c[0], g.c[3]])).collect(); + for p in &anchors { + assert!(anchors.iter().filter(|q| q.distance(*p) < 1e-3).count() >= 2, "{p:?} is on one shape only"); + } + } + + #[test] + fn deleting_a_point_that_splitting_added_gives_the_curve_back() { + let arc = Seg { c: [v(0.0, 0.0), v(0.0, -60.0), v(100.0, -60.0), v(100.0, 0.0)], line: false }; + let (a, b) = (sub(&arc.c, 0.0, 0.35), sub(&arc.c, 0.35, 1.0)); + let at = a[3]; + // A fill under the arc and the arc's own stroke, both with the point. + let fill = vec![Sub { segs: vec![Seg { c: a, line: false }, Seg { c: b, line: false }, Seg::line(v(100.0, 0.0), v(0.0, 0.0))], closed: true }]; + let stroke = vec![Sub { segs: vec![Seg { c: b, line: false }.reversed(), Seg { c: a, line: false }.reversed()], closed: false }]; + let mut shapes = vec![fill, stroke]; + assert_eq!(delete(&mut shapes, at), 2); + let (f, s) = (shapes[0][0].segs[0], shapes[1][0].segs[0]); + assert_eq!((shapes[0][0].segs.len(), shapes[1][0].segs.len()), (2, 1)); + for t in [0.1f32, 0.3, 0.5, 0.7, 0.9] { + assert!(nearest(&f.c, cubic_point(&arc.c, t)).1 < 0.05, "fill off the old curve at {t}"); + } + assert!(same_edge(&f, &s.reversed(), 1e-3), "the fill and the stroke keep one edge"); + } + + #[test] + fn deleting_a_free_end_shortens_the_line_and_its_last_point_removes_it() { + let mut shapes = vec![vec![Sub { segs: vec![Seg::line(v(0.0, 0.0), v(50.0, 0.0)), Seg::line(v(50.0, 0.0), v(50.0, 50.0))], closed: false }]]; + assert_eq!(delete(&mut shapes, v(50.0, 50.0)), 1); + assert_eq!(shapes[0][0].segs.len(), 1); + assert_eq!(delete(&mut shapes, v(50.0, 0.0)), 1); + tidy(&mut shapes[0], false); + assert!(shapes[0].is_empty()); + // A triangle's fill losing a corner has no area left. + let tri = |a, b, c| vec![Sub { segs: vec![Seg::line(a, b), Seg::line(b, c), Seg::line(c, a)], closed: true }]; + let mut t = vec![tri(v(0.0, 0.0), v(10.0, 0.0), v(5.0, 9.0))]; + assert_eq!(delete(&mut t, v(5.0, 9.0)), 1); + tidy(&mut t[0], true); + assert!(t[0].is_empty(), "{:?}", t[0]); + } + + #[test] + fn smooth_and_corner_handles() { + let (a, b) = (Seg::line(v(0.0, 0.0), v(-30.0, 10.0)), Seg::line(v(0.0, 0.0), v(40.0, 10.0))); + let Some((sa, sb)) = smooth_pair(&a, &b) else { panic!("no pair") }; + assert!(smooth_at(v(0.0, 0.0), sa.c[1], sb.c[1]), "{sa:?} {sb:?}"); + assert!((sa.c[1].distance(v(0.0, 0.0)) - a.c[3].length() / 3.0).abs() < 1e-3); + assert_eq!((sa.c[3], sb.c[3]), (a.c[3], b.c[3]), "far ends stay"); + let Some(c) = corner(&sa) else { panic!("a curve has a handle") }; + assert_eq!(c.c[1], c.c[0]); + assert!(corner(&a).is_none() && corner(&c).is_none(), "nothing to draw in"); + // Dragging one handle of a smooth anchor turns the other with it, keeping its length. + let k = turned_opposite(v(0.0, 0.0), v(0.0, 10.0), v(20.0, 0.0)); + assert!(k.distance(v(0.0, -20.0)) < 1e-4, "{k:?}"); + assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0)), "a corner"); + assert!(!smooth_at(v(0.0, 0.0), v(10.0, 0.0), v(20.0, 0.1)), "same side"); + } + #[test] fn nearest_finds_the_closest_point_on_a_curve() { let c = [Vec2::new(0.0, 0.0), Vec2::new(0.0, 50.0), Vec2::new(100.0, 50.0), Vec2::new(100.0, 0.0)]; From 96229c97bab3e30ec8dd1bacf730da2dfc7708f5 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 18:50:08 -0700 Subject: [PATCH 3/9] feat(stage): raw points in the editor: Delete, Make Smooth/Corner, adding with the Pen and Subselection, Alt breaks handle pairs, shape tools snap, Ctrl+Shift+/ (M1) --- crates/engine/src/cmds_draw.rs | 2 +- crates/engine/src/lib.rs | 3 ++ src/app.rs | 4 +- src/pathtools.rs | 95 +++++++++++++++++++++++++++++----- src/stage.rs | 45 +++++++++++++--- 5 files changed, 128 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 79a902f1..7186276a 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -15,7 +15,7 @@ pub fn specs() -> Vec { c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, object?}", true, draw_star), c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line), c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing), - c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", None, "{on?: bool} (default: toggle) dragged points and selections snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point and raw.move_handle do nothing while it is off)", false, snap_to_objects), + c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", Some("Ctrl+Shift+/"), "{on?: bool} (default: toggle) dragged points and selections, and the points the Line, Rectangle, Oval, PolyStar and Pen tools draw, snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point, raw.move_handle and draw.snap do nothing while it is off)", false, snap_to_objects), c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all), c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| { s.selection.clear(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 073dd9ab..daec66e3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -136,6 +136,9 @@ pub const SHORTCUT_ALIASES: &[(&str, &str)] = &[ ("Backspace", "edit.delete"), ("Shift+,", "timeline.first_frame"), ("Shift+.", "timeline.last_frame"), + // Snap to Objects is Animate's Ctrl+Shift+/ (ADR 0045). Where / and ? share a key (US, UK), + // the key arrives as ?, so that spelling is bound too. + ("Ctrl+Shift+?", "draw.snap_to_objects"), ]; pub fn find_command(id: &str) -> Option { diff --git a/src/app.rs b/src/app.rs index 77f89c9d..b4674d72 100644 --- a/src/app.rs +++ b/src/app.rs @@ -121,8 +121,8 @@ impl Tool { pub fn hint(self) -> &'static str { match self { Tool::Select => tr_noop!("Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection."), - Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. On drawing objects, double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."), - Tool::Pen => tr_noop!("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::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it; a smooth point's handles stay in line, Alt moves one alone); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. Double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."), + Tool::Pen => tr_noop!("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, a merged drawing's line or a motion path to add a point to it. Points snap to points and lines while Snap to Objects is on."), Tool::Text => tr_noop!("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 => tr_noop!("Drag to draw freehand. The options bar sets Smooth, Straighten or Ink."), Tool::Brush => tr_noop!("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."), diff --git a/src/pathtools.rs b/src/pathtools.rs index 7cfd838e..35f4d934 100644 --- a/src/pathtools.rs +++ b/src/pathtools.rs @@ -106,6 +106,10 @@ pub fn pen_input(app: &mut App, ui: &egui::Ui, resp: &egui::Response, xf: Xf) { commit_pen(app, false); return; } + // A new knot snaps to points, lines and fill edges (ADR 0045); handles never do. + let p = crate::stage::snap_draw(app, pos2(p.x, p.y), xf.zoom); + let p = Vec2::new(p.x, p.y); + let Some(pen) = app.pen.as_mut() else { return }; pen.knots.push([p; 3]); pen.dragging = true; return; @@ -293,13 +297,14 @@ pub fn subselect_drag_start(app: &mut App, press: Pos2, shift: bool, xf: Xf) -> Drag::PointMarquee { start: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) } } -/// Moves the selected points by a stage-space delta (inside the open gesture). -pub fn move_points(app: &mut App, d: Vec2) { +/// Moves the selected points by a stage-space delta (inside the open gesture). A handle moved +/// alone at a smooth anchor turns the other one with it unless `smooth` is false (Alt). +pub fn move_points(app: &mut App, d: Vec2, smooth: bool) { let mut ids: Vec = app.points.iter().map(|p| p.0).collect(); ids.dedup(); for id in ids { let pts: Vec<[u64; 2]> = app.points.iter().filter(|p| p.0 == id).map(|p| [p.1 as u64, u64::from(p.2)]).collect(); - app.run("path.move_points", json!({"id": id.0, "points": pts, "dx": d.x, "dy": d.y})); + app.run("path.move_points", json!({"id": id.0, "points": pts, "dx": d.x, "dy": d.y, "smooth": smooth})); } } @@ -372,7 +377,25 @@ fn add_point_on_selected(app: &mut App, at: Pos2, xf: Xf) -> bool { return true; } } - false + raw_add_point(app, at, xf) +} + +/// Adds a point on the raw line or fill edge at screen point `at` (ADR 0045): every raw shape with +/// that edge gets it, and it shows selected with everything connected to it. False when there +/// is no raw edge there. +fn raw_add_point(app: &mut App, at: Pos2, xf: Xf) -> bool { + let sp = xf.to_stage(at); + let Ok(v) = app.s.execute("raw.add_point", &json!({"x": sp.x, "y": sp.y, "slop": PICK * xf.unit()})) else { return false }; + let q = Vec2::new(v["x"].as_f64().unwrap_or(0.0) as f32, v["y"].as_f64().unwrap_or(0.0) as f32); + // Show the shapes on it, as a Subselection click there would. + if let Some(r) = app.run("raw.subselect", json!({"x": q.x, "y": q.y, "slop": 2.0 * xf.unit()})) { + app.raw_ends = positions(&r["ends"]); + } + app.points.clear(); + app.motion_anchors.clear(); + app.raw_anchors = vec![q]; + app.status_ok(tr!("Added a point. {undo} to undo.", undo = app.undo_key())); + true } /// Anchors in the point selection, grouped per element. @@ -397,6 +420,27 @@ pub fn delete_points(app: &mut App) { app.points.clear(); } +/// Deletes the selected raw anchors (ADR 0045): the shapes that share each are joined across it. +fn raw_delete(app: &mut App) { + let pts: Vec<[f32; 2]> = app.raw_anchors.iter().map(|q| [q.x, q.y]).collect(); + let Some(v) = app.run("raw.delete_points", json!({"points": pts})) else { return }; + app.raw_anchors.clear(); + app.raw_ends.clear(); + let (n, kept) = (v["deleted"].as_u64().unwrap_or(0) as usize, v["kept"].as_u64().unwrap_or(0) as usize); + let undo = app.undo_key(); + app.status_ok(if kept > 0 { + trn!("Deleted {n} point; kept {kept} where three or more lines meet. {undo} to undo.", "Deleted {n} points; kept {kept} where three or more lines meet. {undo} to undo.", n, kept = kept, undo = undo) + } else { + trn!("Deleted {n} point. {undo} to undo.", "Deleted {n} points. {undo} to undo.", n, undo = undo) + }); +} + +/// Makes the selected raw anchors smooth or corners, in every shape that has them. +fn raw_convert(app: &mut App, smooth: bool) { + let pts: Vec<[f32; 2]> = app.raw_anchors.iter().map(|q| [q.x, q.y]).collect(); + app.run("raw.convert_points", json!({"points": pts, "smooth": smooth})); +} + pub fn convert_points(app: &mut App, smooth: bool) { for (id, cmds) in selected_anchors(app) { for cmd in cmds { @@ -405,22 +449,25 @@ pub fn convert_points(app: &mut App, smooth: bool) { } } -/// Right-click menu for selected points; false when no anchor is selected. +/// Right-click menu for selected points (of drawing objects, or raw anchors, ADR 0045); false +/// when no anchor is selected. pub fn point_menu(app: &mut App, ui: &mut egui::Ui) -> bool { - if app.tool != Tool::Subselect || selected_anchors(app).is_empty() { + let raw = !app.raw_anchors.is_empty(); + if app.tool != Tool::Subselect || (!raw && selected_anchors(app).is_empty()) { return false; } if ui.button(tr!("Make Smooth")).clicked() { - convert_points(app, true); + if raw { raw_convert(app, true) } else { convert_points(app, true) } ui.close(); } if ui.button(tr!("Make Corner")).clicked() { - convert_points(app, false); + if raw { raw_convert(app, false) } else { convert_points(app, false) } ui.close(); } ui.separator(); - if ui.button(tr!("Delete Point")).clicked() { - delete_points(app); + let label = if raw { trn!("Delete Point", "Delete Points", app.raw_anchors.len()) } else { tr!("Delete Point").to_string() }; + if ui.button(label).clicked() { + if raw { raw_delete(app) } else { delete_points(app) } ui.close(); } true @@ -668,7 +715,7 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) { } if app.tool == Tool::Subselect && !app.raw_anchors.is_empty() { if take(Key::Delete) || take(Key::Backspace) { - app.status_err(tr!("Points of merged drawings can't be deleted yet. Select the parts with the Selection tool (V) and delete them.")); + raw_delete(app); } if take(Key::Escape) { app.raw_anchors.clear(); @@ -701,7 +748,7 @@ fn move_points_step(app: &mut App, d: Vec2) { if own { app.s.begin_gesture(tr_noop!("Move Points")); } - move_points(app, d); + move_points(app, d, true); if own { app.s.end_gesture(); } @@ -866,6 +913,30 @@ mod tests { assert!(app.s.can_undo()); } + #[test] + fn delete_removes_selected_raw_anchors_and_a_double_click_adds_one() { + let (mut app, ctx) = app_and_ctx(); + subselect_click(&mut app, pos2(50.0, 0.0), false, XF); + subselect_click(&mut app, pos2(0.0, 0.0), false, XF); + assert_eq!(app.raw_anchors.len(), 1); + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::Key { key: Key::Delete, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + let mut out = ctx.run_ui(input, |ui| consume_keys(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.raw_anchors.is_empty()); + let pts = raw_shown(&app); + assert_eq!(pts.anchors.len(), 3, "a triangle: {:?}", pts.anchors); + assert!(!has(&pts.anchors, 0.0, 0.0)); + // A double-click on the right side adds a point there, shared and selected. + subselect_double_click(&mut app, pos2(101.0, 40.0), XF); + assert!(has(&app.raw_anchors, 100.0, 40.0), "{:?}", app.raw_anchors); + assert_eq!(raw_shown(&app).anchors.len(), 4); + // Make Smooth reaches the engine for raw anchors: the corner at (100, 80) rounds. + app.raw_anchors = vec![Vec2::new(100.0, 80.0)]; + raw_convert(&mut app, true); + assert!(!raw_shown(&app).handles.is_empty(), "smooth: handles appear"); + } + #[test] fn a_press_takes_an_anchor_or_moves_everything_connected() { let (mut app, _) = app_and_ctx(); diff --git a/src/stage.rs b/src/stage.rs index c0d81ba7..162725ca 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -424,7 +424,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // With the Faucet on, the eraser deletes on a click instead. Tool::Eraser if !app.eraser.faucet => crate::erasertool::start(app, to_v(sp)), Tool::Pen | Tool::Text | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper | Tool::Eraser => Drag::None, - Tool::Rect | Tool::Oval | Tool::Star | Tool::Line => Drag::Shape { start: sp, cur: sp }, + // The press snaps to points, lines and fill edges (ADR 0045). + Tool::Rect | Tool::Oval | Tool::Star | Tool::Line => { + let start = snap_draw(app, sp, zoom); + Drag::Shape { start, cur: start } + } Tool::Camera => crate::camera_tool::drag_start(app, &cam_geo, press), Tool::Hand => Drag::Pan, Tool::Zoom => Drag::None, @@ -449,7 +453,16 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.drag = d; } if resp.dragged() { - let cur = resp.interact_pointer_pos().map(to_stage); + let mut cur = resp.interact_pointer_pos().map(to_stage); + // A shape's other end snaps too, unless Shift constrains it (ADR 0045). + if let (Drag::Shape { .. }, Some(c)) = (app.drag, cur) { + cur = Some(if shift { + app.snap_ring = None; + c + } else { + snap_draw(app, c, zoom) + }); + } match (&mut app.drag, cur) { (Drag::Pan, _) => app.view.pan += resp.drag_delta(), (Drag::Move { last }, Some(c)) => { @@ -475,7 +488,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Subselection (ADR 0042): the curve changes in every raw shape that has it. let d = c - *last; if d.length_sq() > 0.0 { - let p = json!({"id": id.0, "cmd": *cmd, "slot": *slot, "dx": d.x, "dy": d.y, "merge": false}); + // A smooth anchor's other handle turns with it; Alt breaks the pair (ADR 0045). + let p = json!({"id": id.0, "cmd": *cmd, "slot": *slot, "dx": d.x, "dy": d.y, "smooth": !alt, "merge": false}); *last = c; if let Some(v) = app.run("raw.move_handle", p) { touched(app, &v["changed"]); @@ -514,7 +528,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let d = c - *last; if d.length_sq() > 0.0 { *last = c; - crate::pathtools::move_points(app, Vec2::new(d.x, d.y)); + crate::pathtools::move_points(app, Vec2::new(d.x, d.y), !alt); } } (Drag::PointMarquee { cur: m, .. }, Some(c)) => *m = c, @@ -970,8 +984,18 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Drag::Shape { start, cur } => draw_preview(app, &painter, to_screen(Vec2::new(start.x, start.y)), to_screen(Vec2::new(cur.x, cur.y)), zoom), _ => {} } - // The snap ring where a dragged point or selection snapped (ADR 0041). - if let Some(at) = app.snap_ring.filter(|_| matches!(app.drag, Drag::SnapMove { .. } | Drag::RawPoint { .. })) { + // The drawing tools show where a press would start, snapped (ADR 0045). + let draws = matches!(app.tool, Tool::Line | Tool::Rect | Tool::Oval | Tool::Star | Tool::Pen) && !panning && !paused && app.pen.as_ref().is_none_or(|p| !p.dragging); + if draws && app.drag == Drag::None { + match pointer.filter(|p| canvas.contains(*p) && resp.hovered()) { + Some(p) => { + snap_draw(app, to_stage(p), zoom); + } + None => app.snap_ring = None, + } + } + // The snap ring where a dragged point, selection or drawn point snapped (ADR 0041, 0045). + if let Some(at) = app.snap_ring.filter(|_| matches!(app.drag, Drag::SnapMove { .. } | Drag::RawPoint { .. } | Drag::Shape { .. }) || (draws && app.drag == Drag::None)) { let c = to_screen(at); painter.circle_stroke(c, SNAP_RING + 1.0, Stroke::new(3.0, Color32::WHITE)); painter.circle_stroke(c, SNAP_RING, Stroke::new(2.0, T.selection)); @@ -1033,6 +1057,15 @@ const SNAP_PX: f32 = 10.0; /// The snap ring's radius (screen pixels). const SNAP_RING: f32 = 6.0; +/// Where a point drawn at stage point `p` goes (the Line, Rectangle, Oval, PolyStar and Pen tools, +/// ADR 0045): snapped within 10 screen pixels to an anchor, else a line or fill edge, while Snap +/// to Objects is on. The snap ring shows where it snapped. +pub fn snap_draw(app: &mut App, p: Pos2, zoom: f32) -> Pos2 { + let v = app.s.execute("draw.snap", &json!({"x": p.x, "y": p.y, "snap": SNAP_PX / zoom.max(1e-3)})); + app.snap_ring = v.as_ref().ok().and_then(snapped_at); + app.snap_ring.map_or(p, |q| pos2(q.x, q.y)) +} + /// A Selection-tool move, this frame: one of the selection's corners (the one nearest the /// pointer) snaps within 10 screen pixels. fn snap_move(app: &mut App, c: Pos2, zoom: f32) { From 43f7bff81effd7a74dbba0877b91041ed7e9b374 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:00:39 -0700 Subject: [PATCH 4/9] feat(engine): edit a symbol's timeline in place: every command, merge drawing and the raw tools work inside it (M1) --- crates/doc/src/eval.rs | 9 + crates/doc/src/lib.rs | 2 +- crates/engine/src/cmds_actions.rs | 2 +- crates/engine/src/cmds_bone.rs | 26 +-- crates/engine/src/cmds_camera.rs | 14 +- crates/engine/src/cmds_draw.rs | 13 +- crates/engine/src/cmds_erase.rs | 4 +- crates/engine/src/cmds_file.rs | 4 +- crates/engine/src/cmds_frames.rs | 14 +- crates/engine/src/cmds_hints.rs | 6 +- crates/engine/src/cmds_modify.rs | 15 +- crates/engine/src/cmds_motion.rs | 6 +- crates/engine/src/cmds_plugin.rs | 3 +- crates/engine/src/cmds_raw.rs | 2 +- crates/engine/src/cmds_rawsub.rs | 2 +- crates/engine/src/cmds_scene.rs | 4 +- crates/engine/src/cmds_sound.rs | 2 +- crates/engine/src/cmds_timeline.rs | 36 ++-- crates/engine/src/confirm.rs | 10 +- crates/engine/src/editing.rs | 327 +++++++++++++++++++++++++++++ crates/engine/src/editing_tests.rs | 131 ++++++++++++ crates/engine/src/history.rs | 2 + crates/engine/src/lib.rs | 52 +++-- crates/engine/src/selection.rs | 18 +- crates/engine/src/tests.rs | 20 +- 25 files changed, 620 insertions(+), 104 deletions(-) create mode 100644 crates/engine/src/editing.rs create mode 100644 crates/engine/src/editing_tests.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 501f104a..9fbf3a82 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -127,6 +127,15 @@ pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList { out } +/// A symbol's timeline at its own `frame`, in the symbol's space, as the stage edits it while the +/// symbol is open for editing (ADR 0045): what picking and bounds use then. Its layers are the +/// top-level ones, as a scene's are in [`evaluate_scene`]. +pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList { + let mut out = DisplayList::default(); + eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY), &mut out, None); + out +} + /// Scene `scene` at its own `frame` as the movie shows it: through the scene's camera, each /// layer shifted by its depth, the camera's tint over everything (ADR 0027). Without a camera /// this is [`evaluate_scene`]. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 444d6aa5..be69ff6a 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -30,7 +30,7 @@ pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, Soun pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use camera::Camera; pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose}; -pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start}; +pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, guide_walk, instance_start}; pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript}; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; diff --git a/crates/engine/src/cmds_actions.rs b/crates/engine/src/cmds_actions.rs index ce9540f1..f9dc5dff 100644 --- a/crates/engine/src/cmds_actions.rs +++ b/crates/engine/src/cmds_actions.rs @@ -37,7 +37,7 @@ pub(crate) enum Scope { /// A timeline commands address: a scene's (the one being edited) or a library symbol's. fn timeline_mut(s: &mut Session, symbol: Option, scope: Scope) -> Result<&mut Timeline> { match symbol { - None => Ok(s.doc.timeline_mut(s.scene)), + None => Ok(crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)), Some(id) => { let sym = s.doc.library.iter_mut().find(|x| x.id == id).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; if scope == Scope::Runs && sym.kind != SymbolKind::MovieClip { diff --git a/crates/engine/src/cmds_bone.rs b/crates/engine/src/cmds_bone.rs index a2d67fd8..d18defb7 100644 --- a/crates/engine/src/cmds_bone.rs +++ b/crates/engine/src/cmds_bone.rs @@ -46,7 +46,7 @@ struct Found { /// Instance `id` on the scene at the playhead (as it shows: tweened, posed). fn find_instance(s: &Session, id: ElementId) -> Option { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); tl.layers.iter().enumerate().find_map(|(index, l)| { let (_, els) = evaluate_layer_elements(l, s.frame)?; let el = els.iter().find(|e| e.id == id)?.clone(); @@ -56,8 +56,8 @@ fn find_instance(s: &Session, id: ElementId) -> Option { /// The armature layer holding bone `id`, and its armature. fn find_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc)> { - s.doc - .timeline(s.scene) + s + .timeline() .layers .iter() .filter(|l| l.kind == LayerKind::Armature) @@ -85,7 +85,7 @@ fn opt_point(p: &Value, key: &str) -> Result> { } fn unlocked(s: &Session, id: LayerId) -> Result<()> { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let l = tl.layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; if l.locked || tl.locked_by_folder(id) { return Err(EngineError::State(format!("layer '{}' is locked", l.name))); @@ -105,7 +105,7 @@ fn take_off(s: &mut Session, layer: LayerId, id: ElementId) -> Result<()> { /// A layer name `base_N` no layer of the scene has yet. fn fresh_name(s: &Session, base: &str) -> String { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); (1..).map(|n| format!("{base}{n}")).find(|n| tl.layers.iter().all(|l| &l.name != n)).unwrap_or_else(|| base.to_string()) } @@ -142,7 +142,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } unlocked(s, x.layer)?; } - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default()); let (fa, ta) = (arm_of(&f), arm_of(&t)); match (&fa, &ta) { @@ -186,10 +186,10 @@ fn add(s: &mut Session, p: &Value) -> Result { None => { // The first bone: both instances move to a new armature layer above them, whose one // pose spans from their keyframe to the end of the timeline. - let (start, end) = s.doc.timeline(s.scene).layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); + let (start, end) = s.timeline().layer(f.layer).and_then(|l| l.keyframe_at(s.frame)).map_or((s.frame, s.frame + 1), |k| (k.start, k.end())); let end = end.max(s.frame_count()); take_off(s, f.layer, from)?; - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let lid = LayerId(s.doc.alloc_id()); @@ -203,7 +203,7 @@ fn add(s: &mut Session, p: &Value) -> Result { k.tween = Some(Tween::default()); layer.keyframes = vec![Arc::new(k)]; let index = f.index.min(t.index); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); layer.parent = tl.container_at(index, LayerKind::Armature); tl.layers.insert(index.min(tl.layers.len()), Arc::new(layer)); tl.repair_masks(); @@ -230,7 +230,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { left.bones.retain(|b| !gone.contains(&b.id)); let dissolve = left.is_empty(); let freed: Vec = if dissolve { arm.members() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() }; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?; let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame()); @@ -244,7 +244,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { let mut k = Keyframe::new(start, end.saturating_sub(start).max(1)); k.elements = shown; freed_layer.keyframes = vec![Arc::new(k)]; - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); if dissolve { tl.layers.retain(|l| l.id != lid); tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer)); @@ -328,7 +328,7 @@ fn edit_pose(s: &mut Session, lid: LayerId, frame: u32, edit: impl FnOnce(&Ar if frame > MAX_FRAME { return Err(EngineError::Param(format!("param 'frame' must be at most {MAX_FRAME}"))); } - let arm = s.doc.timeline(s.scene).layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?; + let arm = s.timeline().layer(lid).and_then(|l| l.armature.clone()).ok_or_else(|| EngineError::State("that is not an armature layer".into()))?; // Past the end a pose carries on from the last one (not a blank keyframe). { let l = s.layer_mut(Some(lid))?; @@ -411,7 +411,7 @@ fn solve(s: &mut Session, p: &Value) -> Result { fn info(s: &mut Session, p: &Value) -> Result { let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); let only = opt_u64(p, "layer")?.map(LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let deg = |v: f32| v.to_degrees(); let pt = |v: Vec2| json!([v.x, v.y]); let list: Vec = tl diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index e8fd10a3..91af9403 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { /// The scene's camera layer id. pub(crate) fn camera_layer(s: &Session) -> Option { - s.doc.timeline(s.scene).camera_layer().map(|l| l.id) + s.timeline().camera_layer().map(|l| l.id) } fn no_camera() -> EngineError { @@ -47,7 +47,7 @@ fn add(s: &mut Session, _: &Value) -> Result { s.selection.clear(); return Ok(json!({"layer": id.0, "added": false})); } - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let id = LayerId(s.doc.alloc_id()); @@ -61,7 +61,7 @@ fn add(s: &mut Session, _: &Value) -> Result { let mut k = Keyframe::new(0, frames); k.elements.push(Arc::new(Camera::rest(&s.doc.stage).to_element(el))); layer.keyframes = vec![Arc::new(k)]; - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.insert(0, Arc::new(layer)); tl.repair_masks(); s.layer = id; @@ -71,11 +71,11 @@ fn add(s: &mut Session, _: &Value) -> Result { fn remove(s: &mut Session, _: &Value) -> Result { let id = camera_layer(s).ok_or_else(no_camera)?; - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.retain(|l| l.id != id); tl.repair_masks(); if s.layer == id { - s.layer = s.doc.timeline(s.scene).layers.first().map_or(LayerId(0), |l| l.id); + s.layer = s.timeline().layers.first().map_or(LayerId(0), |l| l.id); s.selection.clear(); } Ok(json!({"removed": id.0})) @@ -187,9 +187,9 @@ fn camera_json(c: &Camera, stage: &anicraft_doc::Stage) -> Value { fn info(s: &mut Session, p: &Value) -> Result { let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME); let Some(id) = camera_layer(s) else { return Ok(json!({"camera": false})) }; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let on = tl.camera_layer().is_some_and(|l| l.visible); - let mut v = s.doc.timeline(s.scene).camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage)); + let mut v = s.timeline().camera_state_at(frame, &s.doc.stage).map_or_else(|| json!({}), |c| camera_json(&c, &s.doc.stage)); v["camera"] = json!(true); v["layer"] = json!(id.0); v["on"] = json!(on); diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 7186276a..03944cb7 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -181,7 +181,7 @@ fn object_drawing(s: &mut Session, p: &Value) -> Result { /// Everything on every visible, unlocked layer at the playhead, as Animate's Select All. fn select_all(s: &mut Session, _: &Value) -> Result { - let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let layers: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); let mut sel = Selection::default(); for l in layers.into_iter().filter(|l| s.gathers(*l)) { sel.extend_on(l, s.elements_on(l).iter().map(|e| e.id)); @@ -202,9 +202,9 @@ fn select(s: &mut Session, p: &Value) -> Result { // Where each element is at the playhead: on `layer`, else the active layer first, then the // others top to bottom. let order: Vec = match opt_u64(p, "layer")?.map(LayerId) { - Some(l) if s.doc.timeline(s.scene).layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), + Some(l) if s.timeline().layer(l).is_none() => return Err(EngineError::State(format!("no layer with id {}", l.0))), Some(l) => vec![l], - None => std::iter::once(s.layer).chain(s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), + None => std::iter::once(s.layer).chain(s.timeline().layers.iter().map(|l| l.id).filter(|l| *l != s.layer)).collect(), }; let mut at: std::collections::HashMap = std::collections::HashMap::new(); for l in order { @@ -218,7 +218,7 @@ fn select(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State(format!("element {} is not on the active layer, or any layer, at this frame", id.0))); }; if !s.selectable(l) { - let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); return Err(EngineError::State(format!("element {} is on layer '{name}', which is locked or hidden", id.0))); } picked.push((l, id)); @@ -662,7 +662,7 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { let mut inner: Vec> = Vec::with_capacity(layers.len()); for l in layers { let sel = s.selection.on(l); - let source = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let source = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); let picked = s.with_layer(l, |s| -> Result>> { let kf = s.editable_keyframe()?; let first_pos = kf.elements.iter().position(|e| sel.contains(&e.id)).unwrap_or(kf.elements.len()); @@ -756,6 +756,9 @@ fn place(s: &mut Session, p: &Value) -> Result { if s.doc.symbol(sym).is_none() { return Err(EngineError::State(format!("no symbol with id {}", sym.0))); } + if crate::editing::would_nest(s, sym) { + return Err(EngineError::State("a symbol can't be placed inside itself".into())); + } let x = opt_f32(p, "x")?.unwrap_or(s.doc.stage.width as f32 / 2.0); let y = opt_f32(p, "y")?.unwrap_or(s.doc.stage.height as f32 / 2.0); let id = ElementId(s.doc.alloc_id()); diff --git a/crates/engine/src/cmds_erase.rs b/crates/engine/src/cmds_erase.rs index 3f3d22f9..1d18a625 100644 --- a/crates/engine/src/cmds_erase.rs +++ b/crates/engine/src/cmds_erase.rs @@ -267,7 +267,7 @@ fn faucet(s: &mut Session, p: &Value) -> Result { /// The layers `draw.erase_all` clears: visible, unlocked layers that hold artwork (not folders, /// not the camera), with the number of elements at the playhead on each. pub(crate) fn erasable_layers(s: &Session) -> Vec<(anicraft_doc::LayerId, usize)> { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); tl.layers .iter() .filter(|l| l.visible && !l.locked && !tl.locked_by_folder(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera)) @@ -283,7 +283,7 @@ fn erase_all(s: &mut Session, _: &Value) -> Result { let (scene, frame) = (s.scene, s.frame); let mut erased = 0; for (id, _) in &layers { - let Some(layer) = s.doc.timeline_mut(scene).layer_mut(*id) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(*id) else { continue }; let Some(i) = layer.keyframe_index_at(frame) else { continue }; let Some(kf) = layer.keyframe_mut(i) else { continue }; erased += kf.elements.len(); diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 2d59059b..5a046c8c 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -298,7 +298,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { // Clips and masks (ADR 0021): a folder named after the file holding, top first, each // run of artwork, with a mask layer over the runs that are masked. let made = layers.len() + masks + 1; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); if tl.layers.len() + made > 1000 { return Err(EngineError::State(format!("importing {} would make {made} layers; a timeline holds at most 1000", path.display()))); } @@ -343,7 +343,7 @@ fn import_to_stage(s: &mut Session, p: &Value) -> Result { cl.keyframes = keys(els); stack.push(cl); } - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); for (k, l) in stack.into_iter().enumerate() { tl.layers.insert((at + k).min(tl.layers.len()), Arc::new(l)); } diff --git a/crates/engine/src/cmds_frames.rs b/crates/engine/src/cmds_frames.rs index ac52fa73..b3d0b131 100644 --- a/crates/engine/src/cmds_frames.rs +++ b/crates/engine/src/cmds_frames.rs @@ -83,11 +83,11 @@ fn copy_frames(s: &mut Session, p: &Value) -> Result { let count = count_param(p)?; let mut ids = target_layers(s, p)?; // Top to bottom, whatever order the params gave. - let order: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let order: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); ids.sort_by_key(|id| order.iter().position(|o| o == id)); let mut layers = Vec::with_capacity(ids.len()); for id in ids { - let l = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; layers.push(FrameSlice { name: l.name.clone(), keys: slice(l, frame, count)? }); } let clip = FrameClipboard { layers, count, symbols: Vec::new(), sounds: Vec::new() }; @@ -123,7 +123,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { if frame.saturating_add(clip.count) > MAX_FRAME || s.frame_count().saturating_add(clip.count) > MAX_FRAME { return Err(EngineError::State("the timeline would grow past its maximum length".into())); } - let mut row = s.doc.timeline(s.scene).layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?; + let mut row = s.timeline().layers.iter().position(|l| l.id == top).ok_or_else(|| EngineError::State(format!("no layer with id {}", top.0)))?; import_symbols(s, &clip.symbols); for x in &clip.sounds { if s.doc.sound(x.id).is_none() { @@ -135,8 +135,8 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { let mut pasted = Vec::new(); for sl in &clip.layers { // Missing layers below are created, named after the copied ones. - if s.doc.timeline(s.scene).layers.get(row).is_none() { - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.get(row).is_none() { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let id = LayerId(s.doc.alloc_id()); @@ -145,7 +145,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { // The pasted keys are its frames (no stray blank frame at 1). l.keyframes.clear(); } - s.doc.timeline_mut(s.scene).layers.push(Arc::new(l)); + crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.push(Arc::new(l)); } let mut keys = Vec::with_capacity(sl.keys.len()); for k in &sl.keys { @@ -161,7 +161,7 @@ fn paste_frames(s: &mut Session, p: &Value) -> Result { } keys.push(Arc::new(k)); } - let Some(layer) = s.doc.timeline_mut(s.scene).layers.get_mut(row).map(Arc::make_mut) else { continue }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing).layers.get_mut(row).map(Arc::make_mut) else { continue }; crate::cmds_camera::keys_fit(layer.kind, keys.iter().map(|k| &**k))?; if layer.keyframe_index_at(frame).is_some() { insert_keyframe_at(layer, frame, true)?; diff --git a/crates/engine/src/cmds_hints.rs b/crates/engine/src/cmds_hints.rs index f9fce628..63f942a4 100644 --- a/crates/engine/src/cmds_hints.rs +++ b/crates/engine/src/cmds_hints.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; let (i, side) = layer.hint_tween_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is not in a shape tween; select the span and use Insert › Create Shape Tween", frame + 1)))?; Ok((lid, i, side)) @@ -36,7 +36,7 @@ fn find(s: &Session, p: &Value) -> Result<(LayerId, usize, HintSide)> { /// The same, for an edit: refuses locked layers. fn find_mut<'a>(s: &'a mut Session, p: &Value) -> Result<(&'a mut Layer, usize, HintSide)> { let (lid, i, side) = find(s, p)?; - if s.doc.timeline(s.scene).locked_by_folder(lid) { + if s.timeline().locked_by_folder(lid) { return Err(EngineError::State("the layer is in a locked folder".into())); } let layer = s.layer_mut(Some(lid))?; @@ -125,7 +125,7 @@ fn clear_hints(s: &mut Session, p: &Value) -> Result { fn list_hints(s: &mut Session, p: &Value) -> Result { let (lid, i, side) = find(s, p)?; - let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?; + let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State("no such layer".into()))?; let (Some(a), Some(b)) = (layer.hint_keyframe(i, HintSide::Start), layer.hint_keyframe(i, HintSide::End)) else { return Err(EngineError::State("the keyframe went away".into())) }; let hints: Vec = a .hints diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index 209bf9f7..5455b5a8 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -101,7 +101,7 @@ fn copy(s: &mut Session, _: &Value) -> Result { let mut copied = Vec::with_capacity(layers.len()); for l in layers { let elements: Vec = s.elements_on(l).iter().filter(|e| s.selection.contains(l, e.id)).map(|e| (**e).clone()).collect(); - let name = s.doc.timeline(s.scene).layer(l).map(|x| x.name.clone()).unwrap_or_default(); + let name = s.timeline().layer(l).map(|x| x.name.clone()).unwrap_or_default(); if !elements.is_empty() { copied.push(ClipLayer { layer: l, name, elements }); } @@ -145,7 +145,7 @@ fn paste_targets(s: &mut Session) -> Result> { if n <= 1 { return Ok(vec![s.layer]); } - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let drawable = |s: &Session, l: &Layer| s.selectable(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature); let home: Vec = s.clipboard.layers.iter().filter_map(|c| tl.layer(c.layer).filter(|l| l.name == c.name && drawable(s, l)).map(|l| l.id)).collect(); if home.len() == n { @@ -156,17 +156,17 @@ fn paste_targets(s: &mut Session) -> Result> { out.extend(tl.layers.iter().skip(at + 1).filter(|l| drawable(s, l)).map(|l| l.id).take(n - 1)); let names: Vec = s.clipboard.layers.iter().skip(out.len()).map(|c| c.name.clone()).collect(); for name in names { - if s.doc.timeline(s.scene).layers.len() >= 1000 { + if s.timeline().layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } let id = LayerId(s.doc.alloc_id()); - let count = s.doc.timeline(s.scene).layers.len(); + let count = s.timeline().layers.len(); let mut layer = Layer::new(id, name); if let Some(k) = layer.keyframe_mut(0) { k.duration = s.frame_count().max(1); } layer.color = crate::cmds_timeline::layer_color(count + 1); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.push(Arc::new(layer)); tl.repair_masks(); out.push(id); @@ -178,6 +178,11 @@ fn paste_with(s: &mut Session, offset: Vec2) -> Result { if s.clipboard.is_empty() { return Err(EngineError::State("the clipboard is empty".into())); } + // Inside an open symbol, an instance of it (or of one using it) would nest it in itself. + let nests = s.clipboard.layers.iter().flat_map(|c| &c.elements).any(|e| matches!(e.kind, anicraft_doc::ElementKind::Symbol { symbol, .. } if crate::editing::would_nest(s, symbol))); + if nests { + return Err(EngineError::State("a symbol can't be pasted inside itself".into())); + } import_symbols(s, &s.clipboard.symbols.clone()); let targets = paste_targets(s)?; let copied = s.clipboard.layers.clone(); diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index 2f7f6cc2..b0d9e750 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -68,7 +68,7 @@ pub(crate) fn begin_edit(layer: LayerId, kf: &mut Keyframe, frame: u32) -> Optio /// the base back. On the span's first frame a property without keys changes the base itself. pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) { let scene = s.scene; - let Some(layer) = s.doc.timeline_mut(scene).layer_mut(e.layer) else { return }; + let Some(layer) = crate::editing::edited_mut(&mut s.doc, scene, &s.editing).layer_mut(e.layer) else { return }; let Some(kf) = layer.keyframe_starting_at(e.start).and_then(|i| layer.keyframe_mut(i)) else { return }; let Some(idx) = kf.elements.iter().position(|x| x.id == e.target) else { return }; let Some(after) = kf.elements.get(idx).map(|x| (**x).clone()) else { return }; @@ -411,7 +411,7 @@ pub(crate) fn create(s: &mut Session, p: &Value) -> Result { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); let (start, ids) = { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let layer = tl.layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; if layer.kind == LayerKind::Folder { return Err(EngineError::State("a folder holds layers, not frames; pick a layer inside it".into())); @@ -545,7 +545,7 @@ fn set_ease(s: &mut Session, p: &Value) -> Result { fn info(s: &mut Session, p: &Value) -> Result { let (lid, frame) = target(s, p)?; let lid = lid.unwrap_or(s.layer); - let layer = s.doc.timeline(s.scene).layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; + let layer = s.timeline().layer(lid).ok_or_else(|| EngineError::State(format!("no layer with id {}", lid.0)))?; let kf = layer.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?; let m = kf.motion.as_ref().ok_or_else(|| EngineError::State(format!("frame {} is not in a motion tween", frame + 1)))?; let base = m.target_index(&kf.elements).and_then(|i| kf.elements.get(i)).map(|e| Props::of(e)); diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 9dd37206..f0d41024 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -75,8 +75,7 @@ impl Host for SessionHost<'_> { fn document_view(s: &Session) -> Value { let st = &s.doc.stage; let layers: Vec = s - .doc - .timeline(s.scene) + .timeline() .layers .iter() .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "parent": l.parent.map(|p| p.0)})) diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index e5e16f90..699c027c 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -612,7 +612,7 @@ fn select_rect(s: &mut Session, p: &Value) -> Result { // What each layer has under the marquee, from one display list: wholly inside, or (raw // shapes) partly. let mut found: Vec<(LayerId, Vec, Vec)> = Vec::new(); - let layers: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); + let layers: Vec = s.timeline().layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); for l in layers { let (mut picked, mut partial) = (Vec::new(), Vec::new()); for e in s.elements_on(l) { diff --git a/crates/engine/src/cmds_rawsub.rs b/crates/engine/src/cmds_rawsub.rs index b6ba1e86..93114ea8 100644 --- a/crates/engine/src/cmds_rawsub.rs +++ b/crates/engine/src/cmds_rawsub.rs @@ -378,7 +378,7 @@ fn subselect_rect(s: &mut Session, p: &Value) -> Result { if !add { s.selection.clear(); } - let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer); + let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.timeline().locked_by_folder(s.layer); let empty = json!({"selected": s.selection.id_list(), "anchors": []}); if !usable || !(r.width() > 0.0 || r.height() > 0.0) { return Ok(empty); diff --git a/crates/engine/src/cmds_scene.rs b/crates/engine/src/cmds_scene.rs index 4ff21586..e5ff51fb 100644 --- a/crates/engine/src/cmds_scene.rs +++ b/crates/engine/src/cmds_scene.rs @@ -32,9 +32,11 @@ pub(crate) fn target_scene(s: &Session, p: &Value) -> Result { /// Opens scene `i` at its first frame, on its top layer. fn open_scene(s: &mut Session, i: usize) { + // A scene is edited from its own timeline: open symbols close first (ADR 0045). + s.exit_all(); s.scene = i.min(s.doc.scenes.len().saturating_sub(1)); s.frame = 0; - s.layer = s.doc.timeline(s.scene).layers.first().map_or(LayerId(0), |l| l.id); + s.layer = s.timeline().layers.first().map_or(LayerId(0), |l| l.id); s.selection.clear(); } diff --git a/crates/engine/src/cmds_sound.rs b/crates/engine/src/cmds_sound.rs index 7a8d9a31..c87a6522 100644 --- a/crates/engine/src/cmds_sound.rs +++ b/crates/engine/src/cmds_sound.rs @@ -239,7 +239,7 @@ fn set(s: &mut Session, p: &Value) -> Result { // shaped over, which Custom starts from. let (lid, frame) = target(s, p)?; let fps = s.doc.stage.fps; - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let place = tl.layer(lid.unwrap_or(s.layer)).and_then(|l| l.keyframe_at(frame)).map(|k| (k.duration, s.doc.frame_count().saturating_sub(s.doc.scene_start(s.scene).saturating_add(k.start)))); let sounds = s.doc.sounds.clone(); let heard = move |fs: &FrameSound| match (sounds.iter().find(|x| x.id == fs.sound), place) { diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index c452ac97..456ddd78 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -54,11 +54,11 @@ pub fn specs() -> Vec { /// mask back into a normal layer (its masked layers become normal too). fn toggle_mask(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let is_mask = s.doc.timeline(s.scene).layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask; + let is_mask = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?.kind == LayerKind::Mask; let ty = if is_mask { "normal" } else { "mask" }; set_type(s, id, ty)?; if !is_mask { - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); // The normal layer directly below, in the same folder, becomes masked. let mask_parent = tl.layer(id).and_then(|m| m.parent); if let Some(i) = tl.layers.iter().position(|l| l.id == id) @@ -76,7 +76,7 @@ fn toggle_mask(s: &mut Session, p: &Value) -> Result { /// Draw a line on the guide; the layer's classic tweens travel along it. fn add_motion_guide(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let Some(l) = tl.layers.get(i) else { return Err(EngineError::State("no such layer".into())) }; if l.kind != LayerKind::Normal { @@ -100,7 +100,7 @@ fn add_motion_guide(s: &mut Session, p: &Value) -> Result { if let Some(k) = guide.keyframe_mut(0) { k.duration = s.frame_count().max(1); } - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.insert(i, Arc::new(guide)); if let Some(l) = tl.layers.get_mut(i + 1) { Arc::make_mut(l).parent = Some(gid); @@ -127,7 +127,7 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result { } fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder) { return Err(EngineError::State("a folder holds layers; it can't become another kind of layer".into())); @@ -162,8 +162,8 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { } fn layer_type_json(s: &Session, id: LayerId) -> Value { - let Some(l) = s.doc.timeline(s.scene).layer(id) else { return json!({}) }; - let tl = s.doc.timeline(s.scene); + let Some(l) = s.timeline().layer(id) else { return json!({}) }; + let tl = s.timeline(); let parent_kind = l.parent.and_then(|p| tl.layer(p)).map(|x| x.kind); let masked_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Mask)); let guided_by = l.parent.filter(|_| parent_kind == Some(LayerKind::Guide)); @@ -200,7 +200,7 @@ pub(crate) fn target_layers(s: &Session, p: &Value) -> Result> { let mut out: Vec = Vec::with_capacity(ids.len()); let mut folders = 0; for id in ids { - let Some(l) = s.doc.timeline(s.scene).layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) }; + let Some(l) = s.timeline().layer(id) else { return Err(EngineError::State(format!("no layer with id {}", id.0))) }; // Folders have no frames: a range across a folder row acts on the layers only. if l.kind == LayerKind::Folder { folders += 1; @@ -463,7 +463,7 @@ fn move_keyframes(s: &mut Session, p: &Value) -> Result { /// keep their content. Lifting everything before placing anything makes overlapping row /// ranges (dragging two rows down by one) come out right. fn move_across_layers(s: &mut Session, p: &Value, from: u32, to: u32, by: i64, layer_by: i64) -> Result { - let order: Vec = s.doc.timeline(s.scene).layers.iter().map(|l| l.id).collect(); + let order: Vec = s.timeline().layers.iter().map(|l| l.id).collect(); let mut rows: Vec = target_layers(s, p)?.iter().filter_map(|id| order.iter().position(|o| o == id)).collect(); rows.sort_unstable(); let mut plan = Vec::with_capacity(rows.len()); @@ -661,7 +661,7 @@ pub(crate) fn layer_color(n: usize) -> anicraft_doc::Rgba { } fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); if tl.layers.len() >= 1000 { return Err(EngineError::State("too many layers (limit 1000)".into())); } @@ -688,7 +688,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { k.duration = s.frame_count().max(1); } layer.color = layer_color(n); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); tl.layers.insert(at, Arc::new(layer)); tl.repair_masks(); s.layer = id; @@ -700,7 +700,7 @@ fn add_layer(s: &mut Session, p: &Value, kind: LayerKind) -> Result { /// stays where it is, in the mask's folder. fn delete_layer(s: &mut Session, p: &Value) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let is_folder = tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder); let range = if is_folder { tl.group_range(i) } else { i..i + 1 }; @@ -709,7 +709,7 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result { return Err(EngineError::State("a document needs at least one layer to draw on".into())); } let up = tl.layers.get(i).and_then(|l| l.parent); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); if !is_folder { for l in tl.layers.iter_mut().filter(|l| l.parent == Some(id)) { Arc::make_mut(l).parent = up; @@ -718,8 +718,8 @@ fn delete_layer(s: &mut Session, p: &Value) -> Result { let removed: Vec = tl.layers.drain(range.clone()).map(|l| l.id).collect(); tl.repair_masks(); if removed.contains(&s.layer) { - let j = range.start.min(s.doc.timeline(s.scene).layers.len().saturating_sub(1)); - s.layer = s.doc.timeline(s.scene).layers.get(j).map_or(LayerId(0), |l| l.id); + let j = range.start.min(s.timeline().layers.len().saturating_sub(1)); + s.layer = s.timeline().layers.get(j).map_or(LayerId(0), |l| l.id); s.selection.clear(); } Ok(json!({"deleted": id.0, "layers": removed.len()})) @@ -747,11 +747,11 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { let id = if let Some(id) = opt_u64(p, "layer")? { LayerId(id) } else if let Some(i) = opt_u64(p, "index")? { - usize::try_from(i).ok().and_then(|i| s.doc.timeline(s.scene).layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))? + usize::try_from(i).ok().and_then(|i| s.timeline().layers.get(i)).map(|l| l.id).ok_or_else(|| EngineError::Param("layer index out of range".into()))? } else { return Err(EngineError::Param("pass {\"layer\": id} or {\"index\": n}".into())); }; - if s.doc.timeline(s.scene).layer(id).is_none() { + if s.timeline().layer(id).is_none() { return Err(EngineError::State(format!("no layer with id {}", id.0))); } // A click on a layer's name in Animate: the layer becomes active with all of its artwork at @@ -774,7 +774,7 @@ fn select_layer(s: &mut Session, p: &Value) -> Result { /// where it landed: moving it in under a folder or mask puts it inside, moving it out frees it. fn move_layer(s: &mut Session, p: &Value, d: i64) -> Result { let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); - let tl = s.doc.timeline_mut(s.scene); + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; let n = tl.layers.len(); if tl.layers.get(i).is_some_and(|l| matches!(l.kind, LayerKind::Mask | LayerKind::Folder)) { diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 138d0fa0..66410e71 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -40,7 +40,7 @@ fn plural(n: usize, word: &str) -> String { fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> { let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId); - s.doc.timeline(s.scene).layer(id) + s.timeline().layer(id) } fn target_frame(s: &Session, p: &Value) -> u32 { @@ -59,7 +59,7 @@ fn lost_keys(s: &Session, p: &Value, hit: impl Fn(&Keyframe) -> bool) -> Vec<(St None => vec![p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId)], }; ids.iter() - .filter_map(|id| s.doc.timeline(s.scene).layer(*id)) + .filter_map(|id| s.timeline().layer(*id)) .flat_map(|l| l.keyframes.iter().filter(|k| !k.elements.is_empty() && hit(k)).map(|k| (l.name.clone(), k.elements.len()))) .collect() } @@ -155,11 +155,11 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: false, }) } - "camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?), + "camera.remove" => camera_removal(s, s.timeline().camera_layer()?), "bone.remove" => { // The bone's moves in every pose go with it (ADR 0043); one pose loses nothing. let id = anicraft_doc::BoneId(p.get("bone").and_then(Value::as_u64)?); - let l = s.doc.timeline(s.scene).layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; + let l = s.timeline().layers.iter().find(|l| l.armature.as_ref().is_some_and(|a| a.bone(id).is_some()))?; let arm = l.armature.as_deref()?; let n = crate::cmds_bone::poses(l); let below = arm.subtree(id).len().saturating_sub(1); @@ -184,7 +184,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { } if l.kind == anicraft_doc::LayerKind::Folder { // A folder goes with everything in it. - let tl = s.doc.timeline(s.scene); + let tl = s.timeline(); let i = tl.layers.iter().position(|x| x.id == l.id)?; let inner = tl.layers.get(tl.group_range(i))?; let n = inner.len().saturating_sub(1); diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs new file mode 100644 index 00000000..b068e542 --- /dev/null +++ b/crates/engine/src/editing.rs @@ -0,0 +1,327 @@ +//! Editing a symbol's timeline in place (ADR 0045), as Animate's double-click on an instance does. +//! +//! The session keeps a stack of open symbols. While one is open, every command works on its +//! timeline instead of the scene's ([`Session::timeline`]): its layers are the active layers, the +//! playhead is its playhead, and positions are in its own space. So drawing, merge drawing (ADR +//! 0031), the Selection tool (ADR 0041) and Subselection (ADR 0042) behave inside a symbol exactly +//! as on the stage: they are the same commands on another timeline. Which symbol is open is view +//! state, but undo snapshots keep it, so an undo goes back to where its change was made. +//! +//! The stage draws [`Session::stage_picture`]: the open symbol where its instance stands, over the +//! timelines it sits in, dimmed. + +use crate::history::StateId; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Selection, Session}; +use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LoopMode, Symbol, SymbolId, SymbolKind, Timeline}; +use anicraft_geom::{Affine, Vec2}; +use serde_json::{Value, json}; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "symbol.edit", + "Edit Symbols", + "Edit", + Some("Ctrl+E"), + "{id?: instance element id, symbol?: library symbol id} opens a symbol's timeline for editing: the instance `id` (default: the selected instance) in place, or a Library symbol at the stage's centre. Every command then works inside it. With nothing to open while a symbol is open, goes back to the document (Animate's Ctrl+E)", + false, + edit as crate::RunFn, + ), + c("symbol.exit", "Edit Document", "Edit", None, "{all?: bool} closes the open symbol (default: one level; all: back to the scene), selecting the instance it was opened from", false, exit), + ] +} + +/// Most symbols open inside each other at once. +const MAX_LEVELS: usize = 32; +/// How much the artwork around an open symbol shows (Animate dims it). +const DIM: f32 = 0.35; + +/// A symbol open for editing, and what to go back to. +#[derive(Clone, Debug, PartialEq)] +pub struct EditLevel { + pub symbol: SymbolId, + /// The instance it was opened from, on the timeline below (none: from the Library). + pub instance: Option<(LayerId, ElementId)>, + /// Stage space from the symbol's space: where the instance stands (through every level). + pub transform: Affine, + /// The timeline below as it was: its active layer, playhead and selection. + pub layer: LayerId, + pub frame: u32, + pub selection: Selection, +} + +/// The timeline being edited: the open symbol's, else the scene's. +pub(crate) fn edited<'a>(doc: &'a Document, scene: usize, editing: &[EditLevel]) -> &'a Timeline { + match editing.last().and_then(|l| doc.symbol(l.symbol)) { + Some(sym) => &sym.timeline, + None => doc.timeline(scene), + } +} + +/// [`edited`] ([`Session::timeline`]), copy-on-write. Takes the fields, so a caller can keep using the session's others. +pub(crate) fn edited_mut<'a>(doc: &'a mut Document, scene: usize, editing: &[EditLevel]) -> &'a mut Timeline { + let open = editing.last().and_then(|l| doc.library.iter().position(|s| s.id == l.symbol)); + // (Borrowed only on the branch that returns it.) + match open { + Some(i) if i < doc.library.len() => &mut Arc::make_mut(&mut doc.library[i]).timeline, + _ => doc.timeline_mut(scene), + } +} + +/// How the stage shows the open symbol: its space on the stage is `translate(origin) · +/// scale(scale)`. `in_place` when that is exactly where its instance stands, so the artwork +/// around it shows too. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EditView { + pub origin: Vec2, + pub scale: f32, + pub in_place: bool, +} + +/// What the stage draws: a document, the movie frame of it to render, and a state id for caching +/// the picture (equal ids, equal pictures). +#[derive(Clone)] +pub struct StagePicture { + pub doc: Document, + pub frame: u32, + pub state: StateId, +} + +impl Session { + /// The timeline being edited: the open symbol's (ADR 0045), else the scene's. + pub fn timeline(&self) -> &Timeline { + edited(&self.doc, self.scene, &self.editing) + } + + /// The symbol open for editing, if any. + pub fn editing_symbol(&self) -> Option { + self.editing.last().map(|l| l.symbol) + } + + /// Closes levels whose symbol is gone (an undo, a Library deletion), from the first such. + pub(crate) fn fix_editing(&mut self) { + if let Some(i) = self.editing.iter().position(|l| self.doc.symbol(l.symbol).is_none()) { + while self.editing.len() > i { + self.exit_level(); + } + } + } + + fn enter_level(&mut self, symbol: SymbolId, instance: Option<(LayerId, ElementId)>, transform: Affine, frame: u32) { + self.editing.push(EditLevel { symbol, instance, transform, layer: self.layer, frame: self.frame, selection: std::mem::take(&mut self.selection) }); + // The top layer inside, at the frame the instance shows. + self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); + self.frame = frame.min(self.timeline().frame_count().saturating_sub(1)); + self.revision += 1; + self.dl_cache.replace(None); + } + + /// Closes the open symbol; the instance it was opened from is selected again. False when + /// none is open. + pub(crate) fn exit_level(&mut self) -> bool { + let Some(l) = self.editing.pop() else { return false }; + self.layer = l.layer; + self.frame = l.frame; + self.selection = match l.instance { + Some((layer, id)) => Selection::only(layer, [id]), + None => l.selection, + }; + self.revision += 1; + self.dl_cache.replace(None); + true + } + + /// Closes every open symbol (scene changes, opening a document). + pub(crate) fn exit_all(&mut self) { + while self.exit_level() {} + } + + /// How the stage shows the open symbol, `None` on the stage itself. In place when its + /// instance is only moved and scaled evenly (the editor's view can follow that exactly); + /// otherwise upright and at full size, with its registration point where the instance's is. + pub fn edit_view(&self) -> Option { + let l = self.editing.last()?; + let [a, b, c, d, e, f] = l.transform.m; + let origin = Vec2::new(e, f); + let even = b.abs() < 1e-5 && c.abs() < 1e-5 && a > 1e-4 && (a - d).abs() <= 1e-4 * a.max(1.0); + let in_place = even && self.editing.iter().all(|l| l.instance.is_some()); + Some(if in_place { EditView { origin, scale: a, in_place } } else { EditView { origin, scale: 1.0, in_place: false } }) + } + + /// What the stage draws (ADR 0045): the document at the playhead; while a symbol is open, its + /// timeline at its playhead where its instance stands, over the timelines it sits in dimmed. + pub fn stage_picture(&self) -> Arc { + let Some(view) = self.edit_view() else { + return Arc::new(StagePicture { doc: self.doc.clone(), frame: self.doc.scene_start(self.scene).saturating_add(self.frame), state: self.state }); + }; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (self.state, self.scene, self.frame).hash(&mut h); + for l in &self.editing { + (l.symbol, l.instance, l.frame, l.transform.m.map(f32::to_bits)).hash(&mut h); + } + let key = h.finish(); + if let Some((k, pic)) = &*self.picture_cache.borrow() + && *k == key + { + return pic.clone(); + } + let mut doc = self.doc.clone(); + let mut tl = Timeline::default(); + // The open symbol, in front. + let at = Affine::translate(view.origin.x, view.origin.y).mul(&Affine::scale(view.scale, view.scale)); + tl.layers.push(placed(&mut doc, self.timeline().clone(), at, self.frame, 1.0)); + // Around it, dimmed: each timeline below, without the instance opened from it. + if view.in_place { + for (i, l) in self.editing.iter().enumerate().rev() { + let parent = i.checked_sub(1).and_then(|j| self.editing.get(j)); + let below = match parent { + None => self.doc.timeline(self.scene).clone(), + Some(p) => self.doc.symbol(p.symbol).map(|s| s.timeline.clone()).unwrap_or_default(), + }; + let xf = parent.map_or(Affine::IDENTITY, |p| p.transform); + tl.layers.push(placed(&mut doc, without(below, l.instance), xf, l.frame, DIM)); + } + } + *doc.timeline_mut(self.scene) = tl; + // Apart from document states (counted up from 1), and the same for the same picture. + let pic = Arc::new(StagePicture { frame: doc.scene_start(self.scene), doc, state: key | 1 << 63 }); + self.picture_cache.replace(Some((key, pic.clone()))); + pic + } +} + +/// A layer holding `timeline` as a graphic symbol's instance at `transform`, showing its `frame` +/// at opacity `alpha` (a symbol added to `doc`, which is only drawn). +fn placed(doc: &mut Document, timeline: Timeline, transform: Affine, frame: u32, alpha: f32) -> Arc { + let symbol = SymbolId(doc.alloc_id()); + doc.library.push(Arc::new(Symbol { id: symbol, name: String::new(), kind: SymbolKind::Graphic, linkage: None, timeline })); + let mut k = Keyframe::new(0, 1); + k.elements.push(Arc::new(Element { + id: ElementId(doc.alloc_id()), + name: String::new(), + transform, + color: ColorEffect { alpha, ..ColorEffect::default() }, + kind: ElementKind::Symbol { symbol, loop_mode: LoopMode::SingleFrame, first_frame: frame, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + })); + let mut layer = Layer::new(LayerId(doc.alloc_id()), ""); + layer.keyframes.push(Arc::new(k)); + Arc::new(layer) +} + +/// Whether an instance of `sym` placed in the open symbol would put a symbol inside itself: `sym` +/// is open, or uses an open one, however deep. +pub(crate) fn would_nest(s: &Session, sym: SymbolId) -> bool { + if s.editing.is_empty() { + return false; + } + let mut seen: Vec = Vec::new(); + let mut todo = vec![sym]; + while let Some(id) = todo.pop() { + if s.editing.iter().any(|l| l.symbol == id) { + return true; + } + if seen.contains(&id) || seen.len() > 100_000 { + continue; + } + seen.push(id); + let Some(sym) = s.doc.symbol(id) else { continue }; + for k in sym.timeline.layers.iter().flat_map(|l| l.keyframes.iter()) { + todo.extend(k.elements.iter().filter_map(|e| match e.kind { + ElementKind::Symbol { symbol, .. } => Some(symbol), + _ => None, + })); + } + } + false +} + +/// `tl` without the instance `which` (on every keyframe of its layer). +fn without(mut tl: Timeline, which: Option<(LayerId, ElementId)>) -> Timeline { + let Some((layer, id)) = which else { return tl }; + if let Some(l) = tl.layer_mut(layer) { + for k in &mut l.keyframes { + if k.elements.iter().any(|e| e.id == id) { + Arc::make_mut(k).elements.retain(|e| e.id != id); + } + } + } + tl +} + +/// The instance `id` on a layer at the playhead of the timeline being edited, and its layer. +fn instance(s: &Session, id: ElementId) -> Option<(LayerId, Arc)> { + s.timeline().layers.iter().map(|l| l.id).find_map(|l| s.elements_on(l).into_iter().find(|e| e.id == id).map(|e| (l, e))) +} + +fn edit(s: &mut Session, p: &Value) -> Result { + if s.editing.len() >= MAX_LEVELS { + return Err(EngineError::State(format!("at most {MAX_LEVELS} symbols can be open inside each other"))); + } + // From the Library: alone, its registration point at the stage's centre. + if let Some(sym) = opt_u64(p, "symbol")? { + let symbol = SymbolId(sym); + if s.doc.symbol(symbol).is_none() { + return Err(EngineError::State(format!("no symbol {sym} in the Library"))); + } + if s.editing.iter().any(|l| l.symbol == symbol) { + return Err(EngineError::State("that symbol is open already".into())); + } + let c = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5); + s.enter_level(symbol, None, Affine::translate(c.x, c.y), 0); + return Ok(editing_json(s)); + } + let id = match opt_u64(p, "id")? { + Some(i) => ElementId(i), + None => { + let picked: Vec = s.selection.on(s.layer).into_iter().filter(|id| instance(s, *id).is_some_and(|(_, e)| matches!(e.kind, ElementKind::Symbol { .. }))).collect(); + match picked.as_slice() { + [one] => *one, + // Nothing to open: Ctrl+E goes back to the document, as in Animate. + [] if !s.editing.is_empty() => { + s.exit_all(); + return Ok(editing_json(s)); + } + [] => return Err(EngineError::State("select a symbol instance to edit it (or double-click it)".into())), + _ => return Err(EngineError::State("select one symbol instance to edit".into())), + } + } + }; + let (layer, el) = instance(s, id).ok_or_else(|| EngineError::State(format!("element {} is not on a layer here at this frame", id.0)))?; + if !s.selectable(layer) { + return Err(EngineError::State("that instance's layer is locked or hidden".into())); + } + let ElementKind::Symbol { symbol, loop_mode, first_frame, .. } = el.kind else { return Err(EngineError::State("that is not a symbol instance".into())) }; + let sym = s.doc.symbol(symbol).ok_or_else(|| EngineError::State("that instance's symbol is missing from the Library".into()))?; + if s.editing.iter().any(|l| l.symbol == symbol) { + return Err(EngineError::State("that symbol is open already".into())); + } + // A graphic opens at the frame the instance shows; movie clips and buttons at their first. + let len = sym.timeline.frame_count(); + let start = s.timeline().layer(layer).and_then(|l| l.keyframe_at(s.frame)).map_or(s.frame, |k| k.start); + let frame = if sym.kind == SymbolKind::Graphic { loop_mode.local_frame(s.frame.saturating_sub(start), first_frame, len) } else { 0 }; + let below = s.editing.last().map_or(Affine::IDENTITY, |l| l.transform); + s.enter_level(symbol, Some((layer, id)), below.mul(&el.transform), frame); + Ok(editing_json(s)) +} + +fn exit(s: &mut Session, p: &Value) -> Result { + if s.editing.is_empty() { + return Err(EngineError::State("no symbol is open for editing".into())); + } + if opt_bool(p, "all")?.unwrap_or(false) { + s.exit_all(); + } else { + s.exit_level(); + } + Ok(editing_json(s)) +} + +/// The open symbols, outermost first. +pub(crate) fn editing_json(s: &Session) -> Value { + let list: Vec = s.editing.iter().map(|l| json!({"symbol": l.symbol.0, "name": s.doc.symbol(l.symbol).map(|x| x.name.clone()), "instance": l.instance.map(|(_, e)| e.0)})).collect(); + json!({"editing": list, "layer": s.layer.0, "frame": s.frame, "selected": s.selection.id_list()}) +} diff --git a/crates/engine/src/editing_tests.rs b/crates/engine/src/editing_tests.rs new file mode 100644 index 00000000..18b6a459 --- /dev/null +++ b/crates/engine/src/editing_tests.rs @@ -0,0 +1,131 @@ +//! Editing a symbol's timeline in place, with raw drawings inside it (ADR 0045). + +use crate::Session; +use anicraft_doc::{Element, ElementId, ElementKind, SymbolId}; +use anicraft_geom::Vec2; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn raw(s: &Session) -> Vec> { + s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect() +} + +fn has(points: &[Vec2], p: (f32, f32)) -> bool { + points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 0.3) +} + +/// A raw outlined rectangle (100 × 80) turned into a symbol, its instance moved to stand at +/// (250, 140): the symbol's space runs from (−50, −40) to (50, 40). +fn boxed() -> (Session, ElementId, SymbolId) { + let mut s = Session::new(anicraft_doc::Document::default()); + run(&mut s, "draw.object_drawing", json!({"on": false})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"})); + let v = run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let (inst, sym) = (ElementId(v["instance"].as_u64().unwrap_or(0)), SymbolId(v["symbol"].as_u64().unwrap_or(0))); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 100})); + (s, inst, sym) +} + +#[test] +fn raw_shapes_inside_a_symbol_merge_and_take_the_selection_and_subselection_tools() { + let (mut s, inst, sym) = boxed(); + let steps = s.history_len(); + let v = run(&mut s, "symbol.edit", json!({})); + assert_eq!(v["editing"][0]["symbol"], json!(sym.0), "{v}"); + assert_eq!(s.history_len(), steps, "opening is not an edit"); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(view.in_place && view.origin.distance(Vec2::new(250.0, 140.0)) < 1e-3 && (view.scale - 1.0).abs() < 1e-6, "{view:?}"); + // Inside: the symbol's own layer, its raw drawing of five shapes, in its space. + assert_eq!(s.timeline().layers.len(), 1); + assert_eq!(raw(&s).len(), 5); + assert!(s.hit_test(Vec2::new(0.0, 0.0), 1.0).is_some(), "picking is in the symbol's space"); + // Subselection: everything connected shows its four corners. + let v = run(&mut s, "raw.subselect", json!({"x": 0, "y": -40})); + assert_eq!(v["anchors"].as_array().map(Vec::len), Some(4), "{v}"); + // The Selection tool: a corner moves with every shape on it. + run(&mut s, "raw.move_point", json!({"x": 50, "y": -40, "to_x": 60, "to_y": -50})); + assert!(has(&s.raw_points(&raw(&s).iter().map(|e| e.id).collect::>()).anchors, (60.0, -50.0))); + // Merge drawing: a line right across cuts the fill in two. + run(&mut s, "draw.line", json!({"x0": -70, "y0": 0, "x1": 70, "y1": 0, "stroke": "#000000"})); + let fills = raw(&s).into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(); + assert_eq!(fills, 2); + // Points: added and deleted inside, shared as on the stage. + run(&mut s, "raw.add_point", json!({"x": -50, "y": 20})); + run(&mut s, "raw.delete_points", json!({"points": [[-50, 20]]})); + // Back on the stage: the instance is selected and shows the edits where it stands. + run(&mut s, "symbol.exit", json!({})); + assert!(s.editing.is_empty()); + assert_eq!(s.selection.ids().collect::>(), vec![inst]); + let b = s.element_bounds(inst); + assert!(b.max.x > 309.0 && b.min.y < 91.0, "the moved corner at (310, 90): {b:?}"); +} + +#[test] +fn undo_goes_back_into_the_symbol_where_the_change_was_made() { + let (mut s, _, sym) = boxed(); + run(&mut s, "symbol.edit", json!({})); + run(&mut s, "raw.delete_points", json!({"points": [[-50, -40]]})); + assert_eq!(raw(&s).iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).count(), 1); + run(&mut s, "symbol.exit", json!({})); + assert!(s.undo().is_ok()); + assert_eq!(s.editing_symbol(), Some(sym), "undo opens the symbol again"); + assert_eq!(s.raw_points(&raw(&s).iter().map(|e| e.id).collect::>()).anchors.len(), 4, "with the corner back"); + // Undoing the conversion takes the symbol away: editing closes. + while s.undo().is_ok() {} + assert!(s.editing.is_empty() && s.doc.library.is_empty()); +} + +#[test] +fn opening_from_the_library_and_guards() { + let (mut s, inst, sym) = boxed(); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("symbol.edit", &json!({})).is_err(), "nothing selected to open"); + assert!(s.execute("symbol.exit", &json!({})).is_err(), "nothing open"); + run(&mut s, "symbol.edit", json!({"symbol": sym.0})); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + let centre = Vec2::new(s.doc.stage.width as f32 * 0.5, s.doc.stage.height as f32 * 0.5); + assert!(!view.in_place && view.origin == centre, "alone, at the stage's centre: {view:?}"); + assert!(s.execute("library.place", &json!({"symbol": sym.0})).is_err(), "not inside itself"); + assert!(s.execute("symbol.edit", &json!({"symbol": sym.0})).is_err(), "open already"); + // Ctrl+E with nothing to open goes back to the document. + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "symbol.edit", json!({})); + assert!(s.editing.is_empty()); + // A rotated instance opens upright where it stands, the artwork around it hidden. + run(&mut s, "element.select", json!({"ids": [inst.0]})); + run(&mut s, "modify.transform", json!({"a": 0.0, "b": 1.0, "c": -1.0, "d": 0.0, "e": 0.0, "f": 0.0})); + run(&mut s, "symbol.edit", json!({"id": inst.0})); + let view = s.edit_view().unwrap_or_else(|| panic!("open")); + assert!(!view.in_place && (view.scale - 1.0).abs() < 1e-6, "{view:?}"); + // A scene change closes it. + run(&mut s, "scene.new", json!({})); + assert!(s.editing.is_empty()); +} + +#[test] +fn the_stage_shows_the_open_symbol_in_place_over_the_dimmed_stage() { + let (mut s, _, _) = boxed(); + // Something else on the stage, beside the instance. + run(&mut s, "draw.rect", json!({"x": 400, "y": 300, "w": 50, "h": 50, "fill": "#0000ff", "stroke": null, "object": true})); + run(&mut s, "element.pick", json!({"x": 250, "y": 140})); + run(&mut s, "symbol.edit", json!({})); + let pic = s.stage_picture(); + assert_eq!(pic.state, s.stage_picture().state, "the same picture twice"); + let px = anicraft_render::render_frame(&pic.doc, pic.frame, 1.0).unwrap_or_else(|e| panic!("{e}")); + let at = |x: u32, y: u32| px.pixel(x, y).unwrap_or_else(|| panic!("in the picture")); + // The symbol's fill in full red where its instance stands... + let red = at(250, 140); + assert!(red[0] > 0.95 && red[1] < 0.05 && red[2] < 0.05, "{red:?}"); + // ...and the stage around it dimmed (blue at about a third over white). + let blue = at(425, 325); + assert!(blue[2] > 0.95 && blue[0] > 0.5 && blue[0] < 0.8, "{blue:?}"); + // The document itself is untouched by the picture. + assert_eq!(s.doc.library.len(), 1); + // Back on the stage, the picture is the document. + run(&mut s, "symbol.exit", json!({})); + assert_eq!(s.stage_picture().state, s.state); +} diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 25294358..bc77a119 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -28,6 +28,8 @@ pub struct Snapshot { pub doc: Document, pub state: StateId, pub scene: usize, + /// The symbols open for editing (ADR 0045). + pub editing: Vec, pub frame: u32, pub layer: LayerId, pub selection: crate::Selection, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index daec66e3..122e0d96 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod cmds_text; mod cmds_timeline; mod cmds_width; pub mod confirm; +pub mod editing; pub mod format; pub mod history; mod merge; @@ -118,6 +119,7 @@ pub fn commands() -> Vec { v.extend(cmds_raw::specs()); v.extend(cmds_rawsub::specs()); v.extend(cmds_rawpoints::specs()); + v.extend(editing::specs()); v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); @@ -207,14 +209,17 @@ impl ToolStyle { } /// An open document plus everything the editor tracks about it. -/// A display list and the `(state, scene, frame)` it was evaluated for. -type CachedList = (StateId, usize, u32, Arc); +/// A display list and the `(state, scene, frame, open symbol)` it was evaluated for. +type CachedList = (StateId, usize, u32, Option, Arc); pub struct Session { /// The document: a persistent tree, so cloning it (undo, render thread) is cheap. pub doc: Document, /// The scene being edited (index into `doc.scenes`). pub scene: usize, + /// Symbols open for editing, outermost first (ADR 0045). While one is open, commands work on + /// its timeline: `frame`, `layer` and `selection` are its. + pub editing: Vec, /// Playhead within the scene (0-based). pub frame: u32, /// Active layer. @@ -254,6 +259,8 @@ pub struct Session { pub(crate) pending_cut: Option<(CutOrigin, Vec)>, /// The open gesture began on a provisional cut: the document with the cut. gesture_cut: Option, + /// The last picture of an open symbol in place, by its key (ADR 0045). + picture_cache: RefCell)>>, } /// Each piece of a marquee's cut, with the shape it was cut from. @@ -297,6 +304,7 @@ impl Session { Session { doc, scene: 0, + editing: Vec::new(), frame: 0, layer, selection: Selection::default(), @@ -317,6 +325,7 @@ impl Session { provisional: None, pending_cut: None, gesture_cut: None, + picture_cache: RefCell::new(None), } } @@ -591,20 +600,22 @@ impl Session { if g.doc == self.doc && g.selection == self.selection { return; } - let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; + let back = Snapshot { label: String::new(), doc: g.doc.clone(), state: g.state, scene: g.scene, editing: g.editing.clone(), frame: g.frame, layer: g.layer, selection: g.selection.clone(), bytes: 0 }; self.restore(back); self.revision += 1; self.fix_selection(); } fn snapshot(&self, label: &str) -> Snapshot { - Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } + Snapshot { label: label.to_string(), doc: self.doc.clone(), state: self.state, scene: self.scene, editing: self.editing.clone(), frame: self.frame, layer: self.layer, selection: self.selection.clone(), bytes: 0 } } fn restore(&mut self, s: Snapshot) { self.doc = s.doc; self.state = s.state; self.scene = s.scene; + // Where the change was made: an undo inside a symbol opens it again (ADR 0045). + self.editing = s.editing; self.frame = s.frame; self.layer = s.layer; self.selection = s.selection; @@ -665,28 +676,34 @@ impl Session { // ----- queries --------------------------------------------------------------------------- pub fn frame_count(&self) -> u32 { - self.doc.timeline(self.scene).frame_count() + self.timeline().frame_count() } pub fn active_layer(&self) -> Option<&Layer> { - self.doc.timeline(self.scene).layer(self.layer) + self.timeline().layer(self.layer) } pub fn active_layer_index(&self) -> Option { - self.doc.timeline(self.scene).layers.iter().position(|l| l.id == self.layer) + self.timeline().layers.iter().position(|l| l.id == self.layer) } /// The current scene evaluated at the playhead, cached per `(state, scene, frame)`. pub fn display_list(&self) -> Arc { - if let Some((s, sc, f, dl)) = &*self.dl_cache.borrow() + let open = self.editing_symbol(); + if let Some((s, sc, f, o, dl)) = &*self.dl_cache.borrow() && *s == self.state && *sc == self.scene && *f == self.frame + && *o == open { return dl.clone(); } - let dl = Arc::new(evaluate_scene(&self.doc, self.scene, self.frame)); - self.dl_cache.replace(Some((self.state, self.scene, self.frame, dl.clone()))); + // An open symbol is edited in its own space (ADR 0045). + let dl = Arc::new(match open.and_then(|id| self.doc.symbol(id)) { + Some(sym) => anicraft_doc::evaluate_timeline(&self.doc, &sym.timeline, self.frame), + None => evaluate_scene(&self.doc, self.scene, self.frame), + }); + self.dl_cache.replace(Some((self.state, self.scene, self.frame, open, dl.clone()))); dl } @@ -706,7 +723,7 @@ impl Session { if !bounds.contains(p) { continue; } - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); let Some(layer) = tl.layer(item.layer) else { continue }; if layer.locked || tl.locked_by_folder(layer.id) { continue; @@ -742,7 +759,7 @@ impl Session { pub(crate) fn layer_mut(&mut self, id: Option) -> Result<&mut Layer> { let id = id.unwrap_or(self.layer); - self.doc.timeline_mut(self.scene).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) + crate::editing::edited_mut(&mut self.doc, self.scene, &self.editing).layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) } /// The keyframe on the active layer that edits at the playhead should change. Creates a @@ -756,7 +773,7 @@ impl Session { /// refused there. pub(crate) fn editable_keyframe_in(&mut self, what: KeyEdit) -> Result<&mut Keyframe> { let frame = self.frame; - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); if let Some(l) = tl.layer(self.layer) { if l.kind == LayerKind::Folder { return Err(EngineError::State(format!("'{}' is a folder; pick a layer inside it to draw on", l.name))); @@ -773,7 +790,7 @@ impl Session { } // Through the fields, not `layer_mut`, so `motion_edit` can be set below. let (scene, active) = (self.scene, self.layer); - let layer = self.doc.timeline_mut(scene).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; + let layer = crate::editing::edited_mut(&mut self.doc, scene, &self.editing).layer_mut(active).ok_or_else(|| EngineError::State(format!("no layer with id {}", active.0)))?; if layer.locked { return Err(EngineError::State(format!("layer '{}' is locked", layer.name))); } @@ -813,8 +830,7 @@ impl Session { /// JSON summary used by `doc.info` and the CLI. pub fn info(&self) -> Value { let layers: Vec = self - .doc - .timeline(self.scene) + .timeline() .layers .iter() .map(|l| { @@ -836,6 +852,8 @@ impl Session { "layer": self.layer.0, "selection": self.selection.id_list(), "selection_layers": self.selected_layers().iter().map(|l| l.0).collect::>(), + // The symbols open for editing, outermost first (ADR 0045); `layers` are the open one's. + "editing": editing::editing_json(self)["editing"], "layers": layers, "library": symbols, "sounds": sounds, @@ -909,6 +927,8 @@ mod rawsub_tests; #[cfg(test)] mod rawpoints_tests; #[cfg(test)] +mod editing_tests; +#[cfg(test)] mod brush_tests; #[cfg(test)] mod web_tests; diff --git a/crates/engine/src/selection.rs b/crates/engine/src/selection.rs index 964cfa78..8d727b37 100644 --- a/crates/engine/src/selection.rs +++ b/crates/engine/src/selection.rs @@ -184,13 +184,13 @@ fn merge_results(results: Vec<(LayerId, Value)>) -> Value { impl Session { /// The elements on `layer` at the playhead (tweens applied). pub fn elements_on(&self, layer: LayerId) -> Vec> { - self.doc.timeline(self.scene).layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() + self.timeline().layer(layer).and_then(|l| evaluate_layer_elements(l, self.frame)).map(|(_, e)| e.into_owned()).unwrap_or_default() } /// Whether artwork on `layer` can be selected: it is in this scene, shown and unlocked /// (folders included), and not a folder. pub fn selectable(&self, layer: LayerId) -> bool { - let tl = self.doc.timeline(self.scene); + let tl = self.timeline(); let Some(i) = tl.layers.iter().position(|l| l.id == layer) else { return false }; tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder) && !tl.locked_by_folder(layer) && !tl.hidden_by_folder(i) } @@ -199,14 +199,14 @@ impl Session { /// artwork on it. The camera layer holds only the camera, and an armature layer's /// instances are posed by their bones, so they are gathered only while active. pub fn gathers(&self, layer: LayerId) -> bool { - let kind = self.doc.timeline(self.scene).layer(layer).map(|l| l.kind); + let kind = self.timeline().layer(layer).map(|l| l.kind); self.selectable(layer) && (layer == self.layer || !matches!(kind, Some(LayerKind::Camera | LayerKind::Armature))) } /// The layers with selected items, top to bottom. pub fn selected_layers(&self) -> Vec { let mine = self.selection.layers(); - self.doc.timeline(self.scene).layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() + self.timeline().layers.iter().map(|l| l.id).filter(|l| mine.contains(l)).collect() } /// Every selected element as it looks at the playhead, with its layer: layers top to @@ -249,8 +249,10 @@ impl Session { /// locked (a locked or hidden layer is never selected), and keeps the active layer valid. pub fn fix_selection(&mut self) { self.scene = self.scene.min(self.doc.scenes.len().saturating_sub(1)); - if self.doc.timeline(self.scene).layer(self.layer).is_none() { - self.layer = self.doc.timeline(self.scene).layers.first().map_or(LayerId(0), |l| l.id); + // A symbol that is gone closes (ADR 0045). + self.fix_editing(); + if self.timeline().layer(self.layer).is_none() { + self.layer = self.timeline().layers.first().map_or(LayerId(0), |l| l.id); } if self.selection.is_empty() { return; @@ -321,7 +323,7 @@ impl Session { } } } - if self.doc.timeline(self.scene).layer(active).is_some() { + if self.timeline().layer(active).is_some() { self.layer = active; } self.selection = after; @@ -341,7 +343,7 @@ impl Session { crate::cmds_motion::finish_edit(self, edit); } self.dl_cache.replace(None); - if self.doc.timeline(self.scene).layer(active).is_some() { + if self.timeline().layer(active).is_some() { self.layer = active; } r diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 49287701..fae1f477 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -665,7 +665,21 @@ fn panic_hunt_every_command() { layered.execute(id, &p).unwrap(); } assert_eq!(layered.selected_layers().len(), 2, "the fuzz starts with a selection on two layers"); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered] { + // Raw drawings inside a symbol open for editing in place (ADR 0045), with a point added. + let mut in_symbol = Session::default(); + in_symbol.style.object_drawing = false; + for (id, p) in [ + ("draw.rect", json!({"x": 0, "y": 0, "w": 60, "h": 60})), + ("modify.convert_to_symbol", json!({"name": "Inner"})), + ("element.translate", json!({"dx": 30, "dy": 15})), + ("symbol.edit", json!({})), + ("draw.rect", json!({"x": 30, "y": 30, "w": 60, "h": 60, "fill": "#ff0000"})), + ("raw.add_point", json!({"x": 45, "y": 90})), + ] { + in_symbol.execute(id, &p).unwrap(); + } + assert_eq!(in_symbol.editing.len(), 1, "the fuzz starts inside a symbol"); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -677,10 +691,12 @@ fn panic_hunt_every_command() { let _ = s.execute(spec.id, p); } } - // The document must still evaluate and render. + // The document must still evaluate and render, and so must what the stage shows. for f in [0, 1, 5, 47, 1000] { let _ = anicraft_render::render_frame(&s.doc, f, 0.1); } + let pic = s.stage_picture(); + let _ = anicraft_render::render_frame(&pic.doc, pic.frame, 0.1); // ...and its sounds lay out and mix. let voices = anicraft_doc::sound::voices(&s.doc, 8000); let mut out = vec![0.0; 2 * 4096]; From 02908914680d9d8f4cadc11d30dcda0780c94991 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:07:18 -0700 Subject: [PATCH 5/9] feat(stage): edit symbols in place: double-click an instance, Ctrl+E, the edit bar's path back; Library Edit Symbol (M1) --- crates/engine/src/cmds_camera.rs | 4 ++ src/actions_panel.rs | 4 +- src/app.rs | 51 ++++++++++++++++++-- src/bone_tool.rs | 12 ++--- src/camera_tool.rs | 8 ++-- src/main.rs | 2 +- src/menus.rs | 7 ++- src/motion_path.rs | 2 +- src/panels.rs | 44 ++++++++++++++--- src/stage.rs | 81 +++++++++++++++++++++++--------- src/timeline.rs | 18 +++---- 11 files changed, 174 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmds_camera.rs b/crates/engine/src/cmds_camera.rs index 91af9403..a5b64bbe 100644 --- a/crates/engine/src/cmds_camera.rs +++ b/crates/engine/src/cmds_camera.rs @@ -42,6 +42,10 @@ fn no_camera() -> EngineError { } fn add(s: &mut Session, _: &Value) -> Result { + // A scene has the camera, not a symbol (ADR 0027, 0045). + if !s.editing.is_empty() { + return Err(EngineError::State("the camera belongs to a scene: close the symbol you are editing first (Edit › Edit Document)".into())); + } if let Some(id) = camera_layer(s) { s.layer = id; s.selection.clear(); diff --git a/src/actions_panel.rs b/src/actions_panel.rs index 106087c5..28c7a5b7 100644 --- a/src/actions_panel.rs +++ b/src/actions_panel.rs @@ -444,7 +444,7 @@ fn script_view(app: &mut App, ui: &mut egui::Ui, t: &FrameTarget, src: Option<&S fn frame_target(app: &mut App, ui: &mut egui::Ui, doc: &Document) -> Option { match app.actions.symbol { None => { - let tl = doc.timeline(app.s.scene); + let tl = app.s.timeline().clone(); let layer = tl.layer(app.s.layer)?; let frame = app.s.frame; form_row(ui, FORM_LABEL_DOCK, tr!("Keyframe"), |ui| { @@ -581,7 +581,7 @@ fn instance_tab(app: &mut App, ui: &mut egui::Ui, e: &Element) { ui.label(text(Type::Caption, tr!("Name it to address it from actions (letters, digits and _). Its events work without a name."))); } let ElementKind::Symbol { events, .. } = &e.kind else { return }; - let tl = doc.timeline(app.s.scene).clone(); + let tl = app.s.timeline().clone(); let cx = Choices::new(&doc, &tl, true); ui.add_space(4.0); ui.label(text(Type::Caption, tr!("Its actions run on the timeline it is on: “this” is the main timeline."))); diff --git a/src/app.rs b/src/app.rs index b4674d72..9545c415 100644 --- a/src/app.rs +++ b/src/app.rs @@ -568,7 +568,7 @@ impl App { /// through, so it says how to add one. pub fn toggle_camera_preview(&mut self) { self.camera_preview = !self.camera_preview; - if self.camera_preview && self.s.doc.timeline(self.s.scene).camera_layer().is_none() { + if self.camera_preview && self.s.timeline().camera_layer().is_none() { self.status_ok(tr!("Preview through camera is on; add a camera (the camera button on the timeline, or the Camera tool) to look through it.")); } } @@ -949,6 +949,49 @@ impl App { self.drag = Drag::RawHandle { id: h.id, cmd: h.cmd, slot: h.slot, last: egui::pos2(h.at.x + 40.0, h.at.y + 10.0) }; } } + Some("rawpoints") => { + // Raw points (ADR 0045) on a new layer: an outlined square whose top-left corner + // was deleted (the fill and its outline joined across the diagonal), and a point + // added on its right side, pulled out and made smooth, selected with its handle + // pair showing. + self.run("layer.new", json!({})); + self.run("draw.rect", json!({"x": 240, "y": 140, "w": 320, "h": 260, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("draw.ellipse", json!({"x": 640, "y": 170, "w": 240, "h": 200, "fill": "#3d8bfd", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("edit.deselect", json!({})); + self.run("raw.delete_points", json!({"points": [[240, 140]]})); + self.run("raw.add_point", json!({"x": 560, "y": 270})); + self.run("raw.move_point", json!({"x": 560, "y": 270, "to_x": 620, "to_y": 270})); + self.run("raw.convert_points", json!({"points": [[620, 270]], "smooth": true})); + self.tool = Tool::Subselect; + self.run("raw.subselect", json!({"x": 400, "y": 400, "slop": 4})); + self.raw_ends = Vec::new(); + self.raw_anchors = vec![anicraft_engine::geom::Vec2::new(620.0, 270.0)]; + } + Some("rawsnap") => { + // Snapping while drawing (ADR 0045): a line being drawn from a corner of a raw + // square, its end snapping onto the square's other corner (the ring). + self.run("layer.new", json!({})); + self.run("draw.rect", json!({"x": 240, "y": 140, "w": 320, "h": 260, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("edit.deselect", json!({})); + self.tool = Tool::Line; + self.drag = Drag::Shape { start: egui::pos2(240.0, 400.0), cur: egui::pos2(560.0, 140.0) }; + self.snap_ring = Some(anicraft_engine::geom::Vec2::new(560.0, 140.0)); + } + Some("symboledit") => { + // A symbol open for editing in place (ADR 0045): a raw drawing inside it, merged + // with a line drawn across it there, its connected points showing under the + // Subselection tool; the stage around it dimmed, the way back above. + self.run("layer.new", json!({})); + self.run("draw.rect", json!({"x": 260, "y": 160, "w": 300, "h": 220, "fill": "#e8553b", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("modify.convert_to_symbol", json!({"name": "Badge"})); + self.run("symbol.edit", json!({})); + self.run("draw.line", json!({"x0": -190, "y0": 40, "x1": 190, "y1": -40, "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("draw.ellipse", json!({"x": 60, "y": -150, "w": 140, "h": 140, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 3, "object": false})); + self.run("edit.deselect", json!({})); + self.tool = Tool::Subselect; + self.run("raw.subselect", json!({"x": 0, "y": 60, "slop": 4})); + self.raw_ends = Vec::new(); + } Some(which @ ("brush" | "brushing")) => { // Brushed artwork on a new layer (ADR 0033): a pressure-tapered wave, a flat // calligraphic tip at 45°, square dabs, and a pink stroke painted behind a raw @@ -1016,7 +1059,7 @@ impl App { Some("frames") => { // Frames 8–20 selected on the top three layers, with a keyframe drag in progress: // 6 frames later and one layer down. - let layers = &self.s.doc.timeline(self.s.scene).layers; + let layers = &self.s.timeline().layers; if let (Some(a), Some(b)) = (layers.first(), layers.get(2)) { self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 7), head: (b.id, 19) }); self.tl_drag = timeline::TlDrag::Move { grab: 10, by: 6, grab_row: 0, rows_by: 1 }; @@ -1129,7 +1172,7 @@ impl App { } Some("span") => { // Stretching the Star layer's span by its end, with the length readout. - if let Some(l) = self.s.doc.timeline(self.s.scene).layers.get(1) + if let Some(l) = self.s.timeline().layers.get(1) && let Some(k) = l.keyframes.first() { self.tl_drag = timeline::TlDrag::Span { layer: l.id, start: k.start, end: k.end(), to: k.end() + 6 }; @@ -1728,7 +1771,7 @@ impl App { self.status_ok(if self.align_to_stage { tr!("Align: to stage") } else { tr!("Align: to the selection") }); } "view.select_all_frames" => { - let layers = &self.s.doc.timeline(self.s.scene).layers; + let layers = &self.s.timeline().layers; if let (Some(a), Some(b)) = (layers.first(), layers.last()) { let last = self.s.frame_count().saturating_sub(1); self.frame_sel = Some(timeline::FrameSel { anchor: (a.id, 0), head: (b.id, last) }); diff --git a/src/bone_tool.rs b/src/bone_tool.rs index fff28374..d9a59e03 100644 --- a/src/bone_tool.rs +++ b/src/bone_tool.rs @@ -35,7 +35,7 @@ pub struct Shown { /// Every visible armature on the scene at the playhead, bottom layer first. pub fn shown(app: &App) -> Vec { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); tl.layers .iter() .enumerate() @@ -85,7 +85,7 @@ fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 { /// its layer and id. fn instance_at(app: &App, sp: Vec2, slop: f32, skip: Option) -> Option<(LayerId, ElementId)> { let dl = app.s.display_list(); - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); for item in dl.items.iter().rev() { if Some(item.element) == skip || item.guide || item.masks.is_some() { continue; @@ -120,7 +120,7 @@ pub fn select(app: &mut App, layer: LayerId, bone: Option) { pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag { let sp = xf.to_stage(press); if let Some((layer, id, Part::End)) = hit(app, xf, press) - && let Some(child) = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(id)).map(|b| b.child) + && let Some(child) = app.s.timeline().layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(id)).map(|b| b.child) && let Some(b) = shown(app).into_iter().find(|s| s.layer == layer).and_then(|s| s.bones.into_iter().find(|b| b.id == id)) { // A chain joins end to start. @@ -163,7 +163,7 @@ pub fn click(app: &mut App, xf: Xf, p: Pos2) { /// isn't on an armature. pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option { let sp = xf.to_stage(press); - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let (layer, bone, local) = match hit(app, xf, press) { Some((layer, id, _)) => (layer, Some(id), None), None => { @@ -178,7 +178,7 @@ pub fn select_drag_start(app: &mut App, xf: Xf, press: Pos2) -> Option { match bone { Some(id) => { select(app, layer, Some(id)); - let arm = app.s.doc.timeline(app.s.scene).layer(layer).and_then(|l| l.armature.clone())?; + let arm = app.s.timeline().layer(layer).and_then(|l| l.armature.clone())?; if armature::movable_chain(&arm, id).is_empty() { app.status_ok(tr!("That bone is pinned (or hangs from a pinned bone): unpin it in Properties to drag it.")); return Some(Drag::None); @@ -231,7 +231,7 @@ pub fn consume_keys(app: &mut App, ctx: &egui::Context) { /// Drops a selected bone that no longer exists. pub fn upkeep(app: &mut App) { if let Some(id) = app.bone_sel { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); if !tl.layers.iter().any(|l| l.kind == LayerKind::Armature && l.armature.as_ref().is_some_and(|a| a.bone(id).is_some())) { app.bone_sel = None; } diff --git a/src/camera_tool.rs b/src/camera_tool.rs index fb322a87..f83d79b0 100644 --- a/src/camera_tool.rs +++ b/src/camera_tool.rs @@ -37,18 +37,18 @@ impl Geo { /// The scene's camera at the playhead (the rest camera on a blank camera keyframe). pub fn camera(app: &App) -> Option { - app.s.doc.timeline(app.s.scene).camera_state_at(app.s.frame, &app.s.doc.stage) + app.s.timeline().camera_state_at(app.s.frame, &app.s.doc.stage) } /// Whether the stage shows the movie through the camera this frame. pub fn previewing(app: &App) -> bool { - app.camera_preview && app.s.doc.timeline(app.s.scene).camera_layer().is_some() + app.camera_preview && app.s.timeline().camera_layer().is_some() } /// Picking the Camera tool adds a camera when the scene has none (as Animate does), once per /// pick: undoing the add leaves the tool in hand without adding it again. pub fn on_tool_change(app: &mut App) { - if app.tool == Tool::Camera && app.last_tool != Tool::Camera && app.s.doc.timeline(app.s.scene).camera_layer().is_none() && app.run("camera.add", json!({})).is_some() { + if app.tool == Tool::Camera && app.last_tool != Tool::Camera && app.s.timeline().camera_layer().is_none() && app.run("camera.add", json!({})).is_some() { app.status_ok(tr!("Added a camera. Drag on the stage to pan it, turn it with the round handle, zoom with the wheel. {undo} to undo.", undo = app.undo_key())); } app.last_tool = app.tool; @@ -150,7 +150,7 @@ pub fn tick(app: &mut App, ctx: &egui::Context, now: f64) { /// The camera frame (editing) or the camera-view marks (previewing), and the Camera tool's /// handles. pub fn draw(app: &App, painter: &egui::Painter, g: &Geo, hot: Option) { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let Some(layer) = tl.camera_layer() else { return }; let Some(cam) = camera(app) else { return }; let color = to_color32(layer.color); diff --git a/src/main.rs b/src/main.rs index 7afe4600..6406039e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -175,7 +175,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|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|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|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|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope]\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/menus.rs b/src/menus.rs index 997d2c6a..720d6ee9 100644 --- a/src/menus.rs +++ b/src/menus.rs @@ -46,12 +46,15 @@ fn enabled(app: &App, id: &str) -> bool { "edit.undo" => app.s.can_undo(), "edit.redo" => app.s.can_redo(), "edit.delete" | "edit.duplicate" | "modify.convert_to_symbol" | "modify.break_apart" | "arrange.bring_to_front" | "arrange.send_to_back" => !app.s.selection.is_empty(), - "layer.delete" => app.s.doc.timeline(app.s.scene).layers.len() > 1, + "layer.delete" => app.s.timeline().layers.len() > 1, "scene.delete" => app.s.doc.scenes.len() > 1, + // Ctrl+E opens the selected instance, or goes back to the document (ADR 0045). + "symbol.exit" => !app.s.editing.is_empty(), + "symbol.edit" => !app.s.editing.is_empty() || app.s.selected_elements().iter().any(|(_, e)| matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { .. })), "scene.prev" | "scene.move_up" => app.s.scene > 0, "scene.next" | "scene.move_down" => app.s.scene + 1 < app.s.doc.scenes.len(), "timeline.clear_keyframe" => match app.frame_sel { - Some(sel) => sel.has_keys(&app.s.doc.timeline(app.s.scene).layers), + Some(sel) => sel.has_keys(&app.s.timeline().layers), None => app.s.active_layer().is_some_and(|l| l.keyframe_starting_at(app.s.frame).is_some()), }, "timeline.paste_frames" => !app.s.frame_clipboard.is_empty(), diff --git a/src/motion_path.rs b/src/motion_path.rs index a9d40f66..60acc37d 100644 --- a/src/motion_path.rs +++ b/src/motion_path.rs @@ -59,7 +59,7 @@ pub struct Shown { /// The motion path of the active layer's motion tween at the playhead, when its object or a /// frame of its span is selected and it moves at all. pub fn shown(app: &App) -> Option { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let layer = app.s.active_layer().filter(|l| l.visible && l.kind == anicraft_engine::doc::LayerKind::Normal)?; let k = layer.keyframe_at(app.s.frame)?; let m = k.motion.as_ref()?; diff --git a/src/panels.rs b/src/panels.rs index 7d713209..a572d2eb 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -139,6 +139,11 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { app.playing = false; app.frame_sel = None; app.run("scene.select", serde_json::json!({"scene": i})); + } else if r.inner.clicked() && !app.s.editing.is_empty() { + // The scene itself, from inside a symbol: back to it (ADR 0045). + app.playing = false; + app.frame_sel = None; + app.run("symbol.exit", serde_json::json!({"all": true})); } } ui.separator(); @@ -148,6 +153,22 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) { }) .response .set_name(tr!("Scene")); + // The symbols open for editing (ADR 0045), as in Animate's edit bar: a click on one + // goes back to it; the last is the one being edited. + let open: Vec = app.s.editing.iter().map(|l| app.s.doc.symbol(l.symbol).map_or_else(String::new, |s| s.name.clone())).collect(); + let mut back: Option = None; + for (i, name) in open.iter().enumerate() { + ui.label(text(Type::Caption, "›")); + if i + 1 == open.len() { + ui.label(text(Type::Body, name.clone()).strong()); + } else if ui.link(text(Type::Body, name.clone())).on_hover_text(tr!("Back to this symbol")).clicked() { + back = Some(i + 1); + } + } + if let Some(keep) = back { + app.playing = false; + while app.s.editing.len() > keep && app.run("symbol.exit", serde_json::json!({})).is_some() {} + } ui.label(text(Type::Caption, "›")); let layer = app.s.active_layer().map_or("—".to_string(), |l| l.name.clone()); ui.label(text(Type::Body, layer).color(T.text_dim)); @@ -384,13 +405,13 @@ fn properties(app: &mut App, ui: &mut egui::Ui) { }); } // ---- the camera, with the Camera tool or its layer active (ADR 0027) ---- - let camera_layer = app.s.doc.timeline(app.s.scene).camera_layer().map(|l| l.id); + let camera_layer = app.s.timeline().camera_layer().map(|l| l.id); if camera_layer.is_some() && (app.tool == Tool::Camera || camera_layer == Some(app.s.layer)) { section(ui, "prop_camera", Section::Rule, tr!("Camera"), None, |ui| camera_props(app, ui)); } // ---- the bone picked on the stage (ADR 0043) ---- if let Some(id) = app.bone_sel { - let name = app.s.doc.timeline(app.s.scene).layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| b.name.clone())); + let name = app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| b.name.clone())); if let Some(name) = name { let title = if name.is_empty() { tr!("Bone").to_string() } else { tr!("Bone: {name}", name = name) }; section(ui, "prop_bone", Section::Rule, &title, None, |ui| bone_props(app, ui, id)); @@ -1142,14 +1163,14 @@ fn camera_props(app: &mut App, ui: &mut egui::Ui) { app.run("camera.set", json!({"reset": true})); } }); - let hidden = app.s.doc.timeline(app.s.scene).camera_layer().is_some_and(|l| !l.visible); + let hidden = app.s.timeline().camera_layer().is_some_and(|l| !l.visible); ui.label(text(Type::Caption, if hidden { tr!("The camera layer is hidden: the movie shows the stage as it is.") } else { tr!("The movie shows what the frame on the stage shows. Layer depth (in Frame, per layer) moves far layers less.") })); } /// The selected bone: its joint angle at the playhead (editing it keys the pose), the joint's /// limits, the pin, and removal. fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId) { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let Some((layer, bone)) = tl.layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.bone(id)).map(|b| (l.clone(), b.clone()))) else { return }; let pose = anicraft_engine::doc::armature::pose_at(&layer, app.s.frame).unwrap_or_default(); let mut angle = bone.allow(pose.angle(id)).to_degrees(); @@ -1223,14 +1244,14 @@ fn document_props(app: &mut App, ui: &mut egui::Ui) { fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::Layer, frame: u32) { if layer.kind == anicraft_engine::doc::LayerKind::Folder { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); let n = tl.layers.iter().position(|l| l.id == layer.id).map_or(0, |i| tl.group_range(i).len().saturating_sub(1)); ui.label(text(Type::Label, trn!("Folder · {n} layer", "Folder · {n} layers", n))); ui.label(text(Type::Caption, tr!("Folders hold layers, not frames. Hiding or locking the folder hides or locks everything in it; move layers in under it with Up and Down."))); return; } // Layer depth matters once the scene has a camera: deeper layers move less as it pans. - if layer.kind != anicraft_engine::doc::LayerKind::Camera && app.s.doc.timeline(app.s.scene).camera_layer().is_some() { + if layer.kind != anicraft_engine::doc::LayerKind::Camera && app.s.timeline().camera_layer().is_some() { let mut depth = layer.depth; let (lo, hi) = (anicraft_engine::doc::camera::MIN_DEPTH, anicraft_engine::doc::camera::MAX_DEPTH); row(ui, tr!("Depth"), |ui| { @@ -1351,7 +1372,7 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L .set_name(tr!("Tween kind")); }); // On a layer a motion guide steers: turn with the path. - let guided = layer.parent.is_some_and(|p| app.s.doc.timeline(app.s.scene).layer(p).is_some_and(|g| g.kind == anicraft_engine::doc::LayerKind::Guide)); + let guided = layer.parent.is_some_and(|p| app.s.timeline().layer(p).is_some_and(|g| g.kind == anicraft_engine::doc::LayerKind::Guide)); if guided { let mut orient = t.orient; if crate::theme::checkbox(ui, &mut orient, tr!("Orient to path")).on_hover_text(tr!("Turn with the motion guide as it bends")).changed() { @@ -1792,6 +1813,15 @@ fn library(app: &mut App, ui: &mut egui::Ui) { if resp.double_clicked() { place(app, row.item); } + // Opens it alone, its registration point at the stage's centre (ADR 0045). + if let LibraryItem::Symbol(id) = row.item { + resp.context_menu(|ui| { + if ui.button(tr!("Edit Symbol")).clicked() { + ui.close(); + app.run("symbol.edit", json!({"symbol": id.0})); + } + }); + } if let LibraryItem::Sound(id) = row.item { resp.context_menu(|ui| { if ui.button(tr!("Delete Sound")).clicked() { diff --git a/src/stage.rs b/src/stage.rs index 162725ca..9333b993 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -241,19 +241,27 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } - let zoom = app.view.zoom; + let st_zoom = app.view.zoom; // Snap the stage origin to whole device pixels: tile edges then land exactly on screen // pixels, so texture filtering can't show seams between tiles. - let raw = canvas.center() + app.view.pan - size * zoom * 0.5; - let origin = pos2((raw.x * ppp).round() / ppp, (raw.y * ppp).round() / ppp); + let raw = canvas.center() + app.view.pan - size * st_zoom * 0.5; + let st_origin = pos2((raw.x * ppp).round() / ppp, (raw.y * ppp).round() / ppp); + let st_screen = |p: Vec2| pos2(st_origin.x + p.x * st_zoom, st_origin.y + p.y * st_zoom); + let stage_rect = Rect::from_min_size(st_origin, size * st_zoom); + // While a symbol is open (ADR 0045), tools and overlays work in its space, which the stage + // shows moved and scaled where its instance stands. + let edit_view = app.s.edit_view(); + let (origin, zoom) = match edit_view { + Some(v) => (st_origin + vec2(v.origin.x, v.origin.y) * st_zoom, st_zoom * v.scale), + None => (st_origin, st_zoom), + }; let to_screen = |p: Vec2| pos2(origin.x + p.x * zoom, origin.y + p.y * zoom); let to_stage = |p: Pos2| pos2((p.x - origin.x) / zoom, (p.y - origin.y) / zoom); - let stage_rect = Rect::from_min_size(origin, size * zoom); let painter = ui.painter_at(canvas); // View > Preview Through Camera: the stage shows the movie's picture (ADR 0027). Artwork // tools pause meanwhile (what they'd edit is in stage space, not where it shows). let preview = crate::camera_tool::previewing(app); - let cam_geo = crate::camera_tool::Geo { origin, zoom, stage_rect, preview }; + let cam_geo = crate::camera_tool::Geo { origin: st_origin, zoom: st_zoom, stage_rect, preview }; // ---- tools ---------------------------------------------------------------------------- @@ -664,9 +672,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { { commit_text(app); let sp = to_stage(p); - // Raw artwork (ADR 0031): a stroke and the strokes joined to it, or a fill and its outline. - if !open_text_at(app, sp, 3.0 / zoom.max(1e-3)) { - app.run("element.select_connected", json!({"x": sp.x, "y": sp.y, "add": shift, "slop": 3.0 / zoom.max(1e-3)})); + let slop = 3.0 / zoom.max(1e-3); + if !open_text_at(app, sp, slop) { + match app.s.hit_test(to_v(sp), slop) { + // A symbol instance opens for editing in place (ADR 0045). + Some((layer, id)) if app.s.elements_on(layer).iter().any(|e| e.id == id && matches!(e.kind, anicraft_engine::doc::ElementKind::Symbol { .. })) => { + app.run("symbol.edit", json!({"id": id.0})); + } + // Raw artwork (ADR 0031): a stroke and the strokes joined to it, or a fill and + // its outline. + Some(_) => { + app.run("element.select_connected", json!({"x": sp.x, "y": sp.y, "add": shift, "slop": slop})); + } + // Empty space inside a symbol goes back up a level, as in Animate. + None if !app.s.editing.is_empty() => { + app.run("symbol.exit", json!({})); + } + None => {} + } } } if app.tool == Tool::Subselect @@ -738,18 +761,21 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } // Jobs are keyed by who draws them, so a renderer switch re-renders (old tiles stand in). let raster = app.stage_cache.service.as_ref().map_or(0, RenderService::raster_id); - // Tiles on a device-pixel grid at this zoom (ADR 0007). - let z = zoom * ppp; + // Tiles on a device-pixel grid at this zoom (ADR 0007), of what the stage shows: the + // document, or an open symbol in place (ADR 0045). + let z = st_zoom * ppp; let bg = app.s.doc.stage.background; let stage_px = ((size.x * z).ceil().max(1.0) as u32, (size.y * z).ceil().max(1.0) as u32); - let px = [(vis.min.x - origin.x) * ppp, (vis.min.y - origin.y) * ppp, (vis.max.x - origin.x) * ppp, (vis.max.y - origin.y) * ppp]; + let px = [(vis.min.x - st_origin.x) * ppp, (vis.min.y - st_origin.y) * ppp, (vis.max.x - st_origin.x) * ppp, (vis.max.y - st_origin.y) * ppp]; let visible = tiles_for(z, stage_px, px, 0, bg); - let onion = app.onion && !app.playing; - let state = app.s.state; + let pic = app.s.stage_picture(); + let editing = edit_view.is_some(); + let onion = app.onion && !app.playing && !editing; + let state = pic.state; // Render jobs take movie frames: the current scene starts at `start`. let start = app.s.doc.scene_start(app.s.scene); let frame = app.s.frame; - let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &app.s.doc, start + frame, t.view, onion).through_camera(preview); (t, j) }).collect(); + let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview); (t, j) }).collect(); let keys: Vec = jobs.iter().map(|(_, j)| j.key).collect(); let missing: Vec = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect(); @@ -810,33 +836,33 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // during playback, the next frames' visible tiles. if let Some(svc) = &app.stage_cache.service { let mut ahead: Vec = Vec::new(); - if app.playing { + if app.playing && !editing { let n = app.s.frame_count().max(1); for d in 1..=LOOKAHEAD.min(n - 1) { let f = (frame + d) % n; ahead.extend(jobs.iter().map(|(t, _)| make_job_for(raster, state, &app.s.doc, start + f, t.view, false).through_camera(preview))); } } else { - ahead.extend(tiles_for(z, stage_px, px, 1, bg).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job_for(raster, state, &app.s.doc, start + frame, t.view, onion).through_camera(preview))); + ahead.extend(tiles_for(z, stage_px, px, 1, bg).into_iter().filter(|t| !jobs.iter().any(|(v, _)| v.rect == t.rect)).map(|t| make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview))); } svc.prefetch(ahead); } // Draw: tiles from earlier zooms/states that cover the view go first (scaled, as a // placeholder), then the current tiles on top. - let view_rect = [(vis.min.x - origin.x) / zoom, (vis.min.y - origin.y) / zoom, (vis.max.x - origin.x) / zoom, (vis.max.y - origin.y) / zoom]; + let view_rect = [(vis.min.x - st_origin.x) / st_zoom, (vis.min.y - st_origin.y) / st_zoom, (vis.max.x - st_origin.x) / st_zoom, (vis.max.y - st_origin.y) / st_zoom]; let overlaps = |r: &[f32; 4]| r[0] < view_rect[2] && r[2] > view_rect[0] && r[1] < view_rect[3] && r[3] > view_rect[1]; let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); let mut stale: Vec<&TileTex> = app.stage_cache.tiles.iter().filter(|t| !keys.contains(&t.key) && overlaps(&t.rect)).collect(); if ready < keys.len() { stale.sort_by_key(|t| t.used); for t in stale.iter().rev().take(96).rev() { - let r = Rect::from_min_max(to_screen(Vec2::new(t.rect[0], t.rect[1])), to_screen(Vec2::new(t.rect[2], t.rect[3]))); + let r = Rect::from_min_max(st_screen(Vec2::new(t.rect[0], t.rect[1])), st_screen(Vec2::new(t.rect[2], t.rect[3]))); painter.image(t.tex.id(), r, uv, Color32::WHITE); } } for t in app.stage_cache.tiles.iter().filter(|t| keys.contains(&t.key)) { - let r = Rect::from_min_max(to_screen(Vec2::new(t.rect[0], t.rect[1])), to_screen(Vec2::new(t.rect[2], t.rect[3]))); + let r = Rect::from_min_max(st_screen(Vec2::new(t.rect[0], t.rect[1])), st_screen(Vec2::new(t.rect[2], t.rect[3]))); painter.image(t.tex.id(), r, uv, Color32::WHITE); } @@ -863,7 +889,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if preview { // The movie's picture: stage-space overlays don't belong on it. painter.text(stage_rect.left_top() + vec2(0.0, -6.0), egui::Align2::LEFT_BOTTOM, tr!("Camera view"), crate::theme::font(crate::theme::Type::Caption), T.text_dim); - let badge = format!("{:.0}%", zoom * 100.0); + let badge = format!("{:.0}%", st_zoom * 100.0); painter.text(canvas.right_bottom() + vec2(-10.0, -8.0), egui::Align2::RIGHT_BOTTOM, badge, crate::theme::font(crate::theme::Type::Data), T.text_dim); crate::a11y::surface(ui, &resp, &tr!("Stage · previewing through the camera · {tool} tool · frame {frame}", tool = crate::i18n::t(app.tool.label()), frame = app.s.frame + 1)); return; @@ -876,7 +902,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let to_px = Affine::translate(origin.x, origin.y).mul(&Affine::scale(zoom, zoom)); let dl = app.s.display_list(); for item in dl.items.iter().filter(|i| i.masks.is_some() || i.guide).take(2_000) { - let Some(layer) = app.s.doc.timeline(app.s.scene).layer(item.layer).filter(|l| item.guide || !l.locked) else { continue }; + let Some(layer) = app.s.timeline().layer(item.layer).filter(|l| item.guide || !l.locked) else { continue }; let stroke = Stroke::new(if item.guide { 2.0 } else { 1.5 }, to_color32(layer.color)); for pl in item.path.flatten(&to_px.mul(&item.transform), 0.5) { let pts: Vec = pl.points.iter().map(|p| pos2(p.x, p.y)).collect(); @@ -1023,8 +1049,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { text_editor(app, ui, to_screen(Vec2::new(0.0, 0.0)), zoom); + // Inside a symbol: its registration point (ADR 0045; the way back is in the edit bar). + if edit_view.is_some() { + let c = to_screen(Vec2::ZERO); + for (a, b) in [(vec2(-8.0, 0.0), vec2(8.0, 0.0)), (vec2(0.0, -8.0), vec2(0.0, 8.0))] { + painter.line_segment([c + a, c + b], Stroke::new(3.0, Color32::WHITE)); + painter.line_segment([c + a, c + b], Stroke::new(1.0, T.ink)); + } + } + // zoom badge - let badge = format!("{:.0}%", zoom * 100.0); + let badge = format!("{:.0}%", st_zoom * 100.0); painter.text(canvas.right_bottom() + vec2(-10.0, -8.0), egui::Align2::RIGHT_BOTTOM, badge, crate::theme::font(crate::theme::Type::Data), T.text_dim); // Last, so the focus ring is drawn over the artwork. let selected = app.s.selection.len(); @@ -1143,7 +1178,7 @@ fn grab_mark(painter: &egui::Painter, p: Pos2, grab: Grab) { /// The raw shapes (parts of the layer's merged drawing) on the active layer. /// The raw shapes at the playhead, on every layer, with their layers. fn raw_ids(app: &App) -> std::collections::HashSet<(anicraft_engine::doc::LayerId, anicraft_engine::doc::ElementId)> { - let layers: Vec<_> = app.s.doc.timeline(app.s.scene).layers.iter().map(|l| l.id).collect(); + let layers: Vec<_> = app.s.timeline().layers.iter().map(|l| l.id).collect(); layers.into_iter().flat_map(|l| app.s.elements_on(l).into_iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).map(move |e| (l, e.id))).collect() } diff --git a/src/timeline.rs b/src/timeline.rs index 98376422..7ee59944 100644 --- a/src/timeline.rs +++ b/src/timeline.rs @@ -94,7 +94,7 @@ pub enum TlDrag { /// Range params for the frame commands when frames are selected: `{layers, frame, count}`. pub fn range_params(app: &App) -> Option { let sel = app.frame_sel?; - let layers = sel.layers(&app.s.doc.timeline(app.s.scene).layers); + let layers = sel.layers(&app.s.timeline().layers); if layers.is_empty() { return None; } @@ -109,7 +109,7 @@ pub const RANGE_COMMANDS: [&str; 7] = ["timeline.insert_frame", "timeline.remove /// Params for Paste Frames: the selection's top layer and first frame. pub fn paste_params(app: &App) -> Option { let sel = app.frame_sel?; - let top = *sel.layers(&app.s.doc.timeline(app.s.scene).layers).first()?; + let top = *sel.layers(&app.s.timeline().layers).first()?; Some(json!({"layer": top.0, "frame": sel.frames().0})) } @@ -157,7 +157,7 @@ fn transport(app: &mut App, ui: &mut egui::Ui) { } // Add Camera, as Animate has it on the timeline: on while the scene has a camera; a click // then takes it away (asking first when the camera moves; undoable). - let has = app.s.doc.timeline(app.s.scene).camera_layer().is_some(); + let has = app.s.timeline().camera_layer().is_some(); if icon_button(ui, if has { tr!("Remove camera") } else { tr!("Add camera") }, Some(has), Icon::Camera).clicked() { if has { app.request("camera.remove", json!({})); @@ -195,7 +195,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // A frame selection lives while the playhead is inside it and its layers exist. if let Some(sel) = app.frame_sel { let (f0, f1) = sel.frames(); - let gone = sel.layers(&app.s.doc.timeline(app.s.scene).layers).is_empty(); + let gone = sel.layers(&app.s.timeline().layers).is_empty(); if gone || app.playing || (app.tl_drag == TlDrag::None && !(f0..=f1).contains(&app.s.frame)) { app.frame_sel = None; } @@ -242,7 +242,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // rows and columns are painted, so cost is independent of document size. // Rows are the layers not inside a closed folder (`rows[r]` is row r's layer index). let rows: Vec = { - let tl = app.s.doc.timeline(app.s.scene); + let tl = app.s.timeline(); (0..tl.layers.len()).filter(|&i| !app.tl_collapsed.iter().any(|f| tl.is_inside(i, *f))).collect() }; let n_layers = rows.len(); @@ -315,14 +315,14 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } // rows - let layers = app.s.doc.timeline(app.s.scene).layers.clone(); + let layers = app.s.timeline().layers.clone(); let active = app.s.layer; // Layers with selected artwork show a square in their colour after the name, as in // Animate: a selection can span layers (ADR 0044). let holding = app.s.selection.layers(); let rows_top = ruler.bottom(); let rows_bottom = body.bottom() - FOOTER_H; - let tl_now = app.s.doc.timeline(app.s.scene).clone(); + let tl_now = app.s.timeline().clone(); for (r, &i) in rows.iter().enumerate().skip(first_row) { let Some(layer) = layers.get(i) else { continue }; let y = rows_top + (r - first_row) as f32 * ROW_H; @@ -501,7 +501,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { if menus::check_item(ui, tr!("Mask"), layer.kind == LayerKind::Mask, !is_folder) { app.run("layer.toggle_mask", json!({"layer": layer.id.0})); } - let can_mask = layer.kind == LayerKind::Normal && app.s.doc.timeline(app.s.scene).mask_above(i).is_some(); + let can_mask = layer.kind == LayerKind::Normal && app.s.timeline().mask_above(i).is_some(); if menus::check_item(ui, tr!("Masked"), masked, can_mask || masked) { let ty = if masked { "normal" } else { "masked" }; app.run("layer.set_type", json!({"layer": layer.id.0, "type": ty})); @@ -511,7 +511,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let ty = if layer.kind == LayerKind::Guide { "normal" } else { "guide" }; app.run("layer.set_type", json!({"layer": layer.id.0, "type": ty})); } - let can_guide = layer.kind == LayerKind::Normal && app.s.doc.timeline(app.s.scene).guide_above(i).is_some(); + let can_guide = layer.kind == LayerKind::Normal && app.s.timeline().guide_above(i).is_some(); if menus::check_item(ui, tr!("Guided"), guided, can_guide || guided) { let ty = if guided { "normal" } else { "guided" }; app.run("layer.set_type", json!({"layer": layer.id.0, "type": ty})); From b30b7a445302a2c36462c61a645e6ed1d9ce266c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:08:32 -0700 Subject: [PATCH 6/9] test(engine): raw points and symbol editing timings (M1) --- crates/engine/src/rawpoints_tests.rs | 50 ++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/engine/src/rawpoints_tests.rs b/crates/engine/src/rawpoints_tests.rs index 17c94bdf..8c5d34ef 100644 --- a/crates/engine/src/rawpoints_tests.rs +++ b/crates/engine/src/rawpoints_tests.rs @@ -261,3 +261,53 @@ fn an_object_paths_smooth_anchor_keeps_its_handles_opposite() { let ElementKind::Shape(sh) = &el.kind else { panic!() }; assert_eq!(sh.path.point(2, 1), Some(k), "Alt moves the handle alone"); } + +#[test] +fn raw_points_timings() { + // ADR 0042's drawing: 12 × 12 outlined, rounded squares and a line across every row. + let mut s = raw_session(); + for i in 0..12 { + for j in 0..12 { + run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000", "radius": 6})); + } + run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"})); + } + run(&mut s, "edit.deselect", json!({})); + let n = s.visible_elements().len(); + let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let v = run(&mut s, "raw.add_point", json!({"x": 320, "y": 300})); + let add = ms(t); + let at = [v["x"].as_f64().unwrap_or(0.0), v["y"].as_f64().unwrap_or(0.0)]; + let t = std::time::Instant::now(); + run(&mut s, "raw.delete_points", json!({"points": [at]})); + let delete = ms(t); + let t = std::time::Instant::now(); + run(&mut s, "raw.convert_points", json!({"points": [[306, 300]], "smooth": true})); + let smooth = ms(t); + let h = handles_at(&s, Vec2::new(306.0, 300.0)).first().copied().unwrap_or_else(|| panic!("handles after Make Smooth")); + s.begin_gesture("Move Handle"); + let t = std::time::Instant::now(); + run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 1, "dy": 1, "merge": false})); + let pair = ms(t); + s.end_gesture(); + let t = std::time::Instant::now(); + for k in 0..100 { + let _ = s.execute("draw.snap", &json!({"x": 3 + k * 6, "y": 303, "snap": 10})); + } + let snap = ms(t) / 100.0; + // Inside a symbol: the whole drawing converted, opened in place, and its stage picture. + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Grid"})); + let t = std::time::Instant::now(); + run(&mut s, "symbol.edit", json!({})); + let open = ms(t); + let t = std::time::Instant::now(); + let pic = s.stage_picture(); + let picture = ms(t); + let a = anchors(&s).first().copied().unwrap_or_else(|| panic!("anchors inside")); + let t = std::time::Instant::now(); + run(&mut s, "raw.move_point", json!({"x": a.x, "y": a.y, "to_x": a.x - 5.0, "to_y": a.y})); + let inside = ms(t); + eprintln!("{n} raw shapes; add point {add:.2} ms, delete point {delete:.2} ms, make smooth {smooth:.2} ms, smooth handle frame {pair:.2} ms, draw snap {snap:.3} ms; inside a symbol: open {open:.2} ms, stage picture {picture:.2} ms (frame {}), point move {inside:.2} ms", pic.frame); +} From 37583e588170465a43219749bdff9ee2c0fd71d3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:09:46 -0700 Subject: [PATCH 7/9] docs: ADR 0045 raw points and symbols in place; ADR 0041/0042 lists, roadmap, changelog; issue #42 (M1) --- CHANGELOG.md | 20 +++ .../0041-selection-tool-on-raw-drawings.md | 4 +- ...042-subselection-and-merging-everywhere.md | 14 +- ...aw-points-and-raw-shapes-inside-symbols.md | 157 ++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 15 +- 6 files changed, 198 insertions(+), 13 deletions(-) create mode 100644 docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 78f03c88..6d783472 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ ## Unreleased +* **Raw points, snapping while drawing, and symbols edited in place** (ADR 0045, issue #42, M1). + * **Add a point** on a merged drawing's line or fill edge with the Pen's Alt-click or a + Subselection double-click: every shape on that edge gets it, and the curve keeps its shape. + * **Delete points** with Delete (or the right-click menu): the shapes that share each point are + joined across it, so a fill and its outline stay together; deleting a line's last points + removes it. A point where three or more lines meet is kept, and the status bar says so. + * **Make Smooth / Make Corner** on raw points. Dragging a handle of a smooth point keeps the + other handle in line (on drawing objects too); **Alt** moves it alone. + * The **Line, Rectangle, Oval, PolyStar and Pen** tools snap their points to points, lines and + fill edges within 10 screen pixels, with a ring where they will snap. **Snap to Objects** is + now Ctrl+Shift+/, as in Animate. + * **Double-click a symbol instance** (or press Ctrl+E, or right-click it in the Library › Edit + Symbol) to edit it in place: the rest of the stage dims, the timeline shows the symbol's + layers, and merge drawing, the Selection and Subselection tools and every other tool work + inside it as on the stage. The edit bar shows `Scene 1 › Symbol`; click the scene, press + Ctrl+E or double-click empty stage to go back. Undo returns to the symbol where a change was + made. Rotated instances open upright. + * Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` + on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`; `doc.info` lists + the open symbols. * **ActionScript that controls the timeline now runs** (ADR 0013 tier 2). Frame scripts in Animate documents, and ones you type in the Actions panel, play in Test Movie and in the HTML canvas export when they use the ActionScript 3.0 most animation and e-learning files diff --git a/docs/adr/0041-selection-tool-on-raw-drawings.md b/docs/adr/0041-selection-tool-on-raw-drawings.md index 8093ca7d..2eeb622e 100644 --- a/docs/adr/0041-selection-tool-on-raw-drawings.md +++ b/docs/adr/0041-selection-tool-on-raw-drawings.md @@ -125,8 +125,8 @@ was copied. won). The move is at most 0.2, and merging again changes nothing (tested). * Not in this slice: * ~~selecting across layers~~ (ADR 0044); - * snapping while drawing with the shape tools; + * ~~snapping while drawing with the shape tools~~ (ADR 0045); * ~~a Snap to Objects switch~~ (ADR 0042); * ~~Subselection anchors and handles of connected raw shapes~~ (ADR 0042); - * bending or moving points of raw shapes inside symbols; + * ~~bending or moving points of raw shapes inside symbols~~ (ADR 0045); * the Free Transform tool's handles on raw parts. diff --git a/docs/adr/0042-subselection-and-merging-everywhere.md b/docs/adr/0042-subselection-and-merging-everywhere.md index 747ceb49..dd93c451 100644 --- a/docs/adr/0042-subselection-and-merging-everywhere.md +++ b/docs/adr/0042-subselection-and-merging-everywhere.md @@ -150,11 +150,11 @@ nothing was copied. * A Paint Bucket fill in merge drawing lies exactly along its lines. Deleting a line later joins fills of one colour, as in Animate. * Not in this slice: - * deleting raw anchors (Delete says so), and adding them; - * Make Smooth and Make Corner on raw anchors; - * smooth handle pairs (a handle moves alone, as on drawing objects); + * ~~deleting raw anchors (Delete says so), and adding them~~ (ADR 0045); + * ~~Make Smooth and Make Corner on raw anchors~~ (ADR 0045); + * ~~smooth handle pairs (a handle moves alone, as on drawing objects)~~ (ADR 0045); * width profiles in the merge; - * Subselection inside symbols; - * a default shortcut for Snap to Objects; - * snapping while drawing with the shape tools; - * a marquee across layers (ADR 0041). + * ~~Subselection inside symbols~~ (ADR 0045: symbols open for editing in place); + * ~~a default shortcut for Snap to Objects~~ (ADR 0045: Ctrl+Shift+/); + * ~~snapping while drawing with the shape tools~~ (ADR 0045); + * ~~a marquee across layers~~ (ADR 0044, for the Selection tool). diff --git a/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md b/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md new file mode 100644 index 00000000..e3d7d6b1 --- /dev/null +++ b/docs/adr/0045-raw-points-and-raw-shapes-inside-symbols.md @@ -0,0 +1,157 @@ +# ADR 0045: Raw points, snapping while drawing, and raw shapes inside symbols + +* Status: accepted (2026-11-10) +* Relates to: ADR 0031 (merge drawing), ADR 0041 (Selection tool on raw drawings), ADR 0042 + (Subselection and merging everywhere), ADR 0044 (selection across layers), ADR 0004 + (destructive actions), ADR 0001 (undo snapshots), issue #42 (sections 1 and 3) + +## Context + +ADR 0042 left these out of its slice: + +* adding and deleting raw anchors (Delete only said it could not); +* Make Smooth and Make Corner on raw anchors, and smooth handle pairs (a handle moved alone); +* snapping while drawing with the shape tools; +* a default shortcut for Snap to Objects; +* Subselection (and, from ADR 0041, the Selection tool) inside symbols. + +The last one needed more than the raw tools: AniCraft had no way to edit a symbol's timeline at +all. In Animate a double-click on an instance opens the symbol **in place**: the rest of the +stage dims, the timeline shows the symbol's layers, every tool works inside it, and the edit bar +says where you are (`Scene 1 › Badge`). + +Behaviour was learned from the issue, Adobe's public help pages and watching the program; +nothing was copied. + +## Decision + +1. **Points are positions, as in ADR 0042.** A shared point is stored once in each raw shape + that has it, so each command finds every copy near the position (within 1.5 × `SNAP`) and + changes them alike. The pure parts are in `anicraft_geom::raw`: a path as subpaths of + segments (`subpaths`, `from_subpaths`), the edges leaving a point (`edges_at`, + `distinct_edges`), and the edits below. + +2. **Adding a point** (`raw.add_point {x, y, slop?}`, the Pen's Alt-click and the Subselection + double-click on a raw line or fill edge) splits the segment there in every raw shape that has + that edge (de Casteljau, so the curve is unchanged; tested analytically). Nothing moved, so + nothing merges. A point added on a **straight** line lasts while it is used: once a merge + finds it still on a straight run (it was never moved), it is simplified away, as issue #42's + continuous simplification asks. On a curve it stays. + +3. **Deleting points** (`raw.delete_points {points}`, Delete or Backspace with Subselection, + the point menu) works on the drawing's edges at each point, not on one shape: + * **Two edges** (a corner, or a point along a line): they become one edge from the far end of + one to the far end of the other: two lines a line, anything else the cubic that fits both + best, keeping the directions they leave their far ends in (`join`, the fit `Path::merge_at` + uses; deleting a point that adding made gives the curve back). **Every copy** of either + edge becomes the new one: a fill's outline loses the corner, and a stroke that ended there + now runs along the whole new edge. The drawing stays connected; the merge that follows + joins the strokes that now overlap. + * **One edge** (the free end of lines): the segment there goes. + * **Three or more** (where lines cross or a line stands on another): the point is kept and + the editor says why. Joining three edges into one has no single right answer. + * What is left with nothing to show is removed: a subpath with no segments or no length, a + filled outline with no area; a shape with no subpaths. So deleting a line's last points + removes it. + * One command, so one undo step (ADR 0004: undoable, no confirmation), merged again + (`remerge_in_place`) like every raw edit. + + *Rejected:* deleting the point from each shape on its own (`Path::remove_anchor` per copy). + Each shape would fit its own curve, and a fill and its outline would part. + +4. **Make Smooth and Make Corner** (`raw.convert_points {points, smooth}`, the point menu): + smooth turns a point with two edges into one whose handles lie on one line, along the + direction between the far ends, a third of each chord long (`Path::make_smooth`'s rule); + corner draws every curve's handle there in onto the point. Each changed edge changes in + every shape (`follow_edge`, built on ADR 0041's `follow`). A smooth point on a straight line + is simplified away by the merge, as in point 2. + +5. **Smooth handle pairs.** Dragging one handle of a smooth point (its two handles on one line, + opposite, within 3°) turns the other to stay opposite, keeping its length: `raw.move_handle` + and `path.move_points` take `smooth?: bool` (default true); **Alt** breaks the pair. The + other handle is found among the edges at the point: exactly one other curve whose handle is + opposite (a junction has no pair). Drawing objects behave the same, so both kinds of shape + edit alike. + +6. **Snapping while drawing.** `draw.snap {x, y, snap}` (no undo step) says where a point drawn + at (x, y) goes: the nearest anchor within `snap`, else the nearest point on a line or fill + edge, of what the stage shows near it (display-list items whose bounds reach the point, so it + costs nothing far away). The Line, Rectangle, Oval, PolyStar and Pen tools snap their start + and end (the Pen its knots, never its handles) within 10 screen pixels, and show the snap + ring as you hover, where a press would start. Shift's constraint wins over snapping. Off when + Snap to Objects is off (`ToolStyle::snap_radius`). Scripts pass exact coordinates; the query + is there for them too. + +7. **Snap to Objects is Ctrl+Shift+/**, Animate's chord. Where `/` and `?` share a key (US, UK + layouts), the key arrives as `?`, so `Ctrl+Shift+?` is bound too (an engine alias). Neither + clashed with a default (the keymap's clash test). ADR 0042's worry was the layout: on layouts + where `/` needs Shift (German: Shift+7), Ctrl+Shift+that key arrives as `/`, which the first + binding catches. + +8. **Editing a symbol in place** (`crates/engine/src/editing.rs`): + * The session keeps a stack of open symbols (`Session::editing`). While one is open, + **every command works on its timeline** (`Session::timeline`; the 86 places that read + the scene's timeline now read this): the active layer, the playhead and the selection are + its, positions are in its space, the display list (picking, bounds, snapping) is its + timeline evaluated alone (`anicraft_doc::evaluate_timeline`). So merge drawing, the + Selection tool, Subselection, raw points, the Paint Bucket and the rest behave inside a + symbol exactly as on the stage: they are the same commands. + * `symbol.edit {id?, symbol?}` (Edit › Edit Symbols, **Ctrl+E**, a **double-click** on an + instance with the Selection tool) opens the selected or given instance where it stands, at + the frame a graphic shows (a movie clip or button at its first); `{symbol}` (the Library's + Edit Symbol) opens one alone at the stage's centre. Ctrl+E with no instance selected goes + back to the document, as in Animate. `symbol.exit {all?}` (Edit › Edit Document, a + double-click on empty stage, the edit bar's path) closes one level or all, selecting the + instance again. + * Which symbol is open is view state, but **undo snapshots keep it**, so undoing a change + made inside a symbol opens it again: the layer, frame and selection in the step belong to + that timeline. A symbol that goes away (an undo, a deletion) closes. Changing scene closes + every symbol. Placing or pasting a symbol inside itself (or inside a symbol it uses) is + refused; a camera can't be added inside a symbol. + * **What the stage draws** (`Session::stage_picture`): a picture document whose scene holds + the open timeline at its playhead where the instance stands, over each timeline below it + (without the instance it was opened from) at 35 % opacity. They are graphic instances of + copies of those timelines, so the oracle and the GPU stage draw them unchanged, and the + render cache keys them by a hash of the state and the open levels. + * **The editor's view follows the instance** when it is only moved and scaled evenly: the + stage's screen mapping becomes `origin + zoom · (t + k · p)`, which the shell's existing + origin-and-zoom mapping holds exactly, so every tool, overlay and snap radius works + unchanged. A rotated, skewed or flipped instance opens upright and unscaled at its + registration point, with the artwork around it hidden (a picture that did not line up with + the tools would mislead). + * The edit bar shows `Scene 1 › Badge › Layer 1`; a click on a symbol goes back to it, the + scene's menu goes back to the scene. A crosshair marks the registration point. + + *Rejected:* a full affine view mapping in the shell (rotated in-place editing). Every tool's + screen-space overlay assumes an axis-aligned mapping (selection boxes, Free Transform + handles, marquees); bending them all is a slice of its own. *Rejected:* addressing a symbol's + timeline through a `symbol` param on each command (as the Actions panel's commands do): + every command and tool would need it, and the tools would still need a view of the symbol. + +## Consequences + +* Issue #42's Subselection (§3) is complete on raw drawings, inside symbols too. The drawing + tools snap as the issue's §1 describes. +* Measured on 744 raw shapes (12 × 12 outlined, rounded squares and 12 lines; optimised debug + build, `raw_points_timings`): + + | Operation | Time | + |---|---| + | Add a point | 0.29 ms | + | Delete a point (joined, merged again) | 0.30 ms | + | Make Smooth | 0.34 ms | + | Smooth handle pair drag frame | 0.14 ms | + | Drawing snap (every frame while hovering) | 0.02 ms | + | Open a symbol of all 744 shapes | 0.04 ms | + | Its stage picture | 0.01 ms | + | A point move inside it | 0.52 ms | + +* `panic_hunt_every_command` also starts inside an open symbol with raw drawings, and renders + the stage picture. +* Not in this slice: + * in-place editing of rotated, skewed or flipped instances (they open upright, alone); + * the parent symbol's frame moving with the open one (a nested graphic shows the frame it + was opened at), and onion skin while a symbol is open; + * deleting a point where three or more edges meet; + * width profiles in the merge (ADR 0042); + * a marquee across layers with the Subselection tool (Animate keeps it on one layer too). diff --git a/docs/adr/README.md b/docs/adr/README.md index 8ec5d830..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0045 | m1/raw-points | Raw points: add, delete, smooth pairs, snapping while drawing, raw shapes inside symbols | diff --git a/docs/roadmap.md b/docs/roadmap.md index 8dcbfdfe..8a12ac6b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -11,7 +11,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. **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. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **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; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **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`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: a marquee across several layers, snapping while drawing, width profiles in the merge, deleting or adding raw anchors, smooth handle pairs. **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 width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | +| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **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`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or the Library's Edit Symbol) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright), onion skin inside a symbol. **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 width-profiled shapes (gradient fills erase since ADR 0042), 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. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). Not yet: ActionScript variables, conditions, reading properties, `removeEventListener`, enter-frame and keyboard events, functions from other frames, event bubbling, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. | | Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | @@ -100,8 +100,17 @@ Next, in order: segment or fill moves what is connected, arrow keys; Snap to Objects (View › Snapping, the magnet); the Paint Bucket's fills (exact, up to the lines) and pasted raw shapes merge; raw shapes from Animate files come in raw; gradients take part in the merge. Not yet: - width profiles in the merge, deleting or adding raw anchors, smooth handle pairs, a - default Snap to Objects shortcut. + width profiles in the merge. + * ~~**Raw points and raw shapes inside symbols** (ADR 0045)~~ ✅: add a point on a raw line + or fill edge (Pen Alt-click, Subselection double-click), shared by every shape on the edge; + delete raw points (the shapes on them joined across, the drawing kept connected; a line's + last points remove it); Make Smooth / Corner on raw points; smooth handle pairs (Alt breaks + them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap while + drawing; Snap to Objects is Ctrl+Shift+/; **symbols open for editing in place** + (double-click, Ctrl+E, the Library's Edit Symbol; the edit bar's path back), where merge + drawing, Selection and Subselection work as on the stage. Not yet: in-place editing of + rotated instances (they open upright), deleting a point where three edges meet, onion skin + inside a symbol. 1. M4 **XFL import, next slices**: ~~masks (with M2 mask layers)~~ ✅, ~~shape tweens~~ ✅, ~~every scene~~ ✅, ~~bitmaps~~ ✅ (PNG/JPEG data), ~~text~~ ✅ (one style per line; per-character styles with the text model), motion tweens, and ~~a larger self-authored From c67a6c80d44655fbab8ab925719d17b0cb5a33ec Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:09:51 -0700 Subject: [PATCH 8/9] docs: credit the curve fit raw point deletion uses (M1) --- ATTRIBUTION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 654ef16d..3481b5bd 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -103,7 +103,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; 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. | +| 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`; deleting a raw drawing's point joins its edges, `raw::join`, ADR 0045) | `crates/geom/src/fit.rs`, `crates/geom/src/edit.rs`, `crates/geom/src/raw.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. | From 6586de30bd6afd34534beab0c8dc6ae25dc664c9 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:23:52 -0700 Subject: [PATCH 9/9] fix(geom): pass the edge matcher by value, for newer clippy (M1) --- crates/geom/src/raw.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/geom/src/raw.rs b/crates/geom/src/raw.rs index a16acba5..b1f7a057 100644 --- a/crates/geom/src/raw.rs +++ b/crates/geom/src/raw.rs @@ -384,7 +384,7 @@ pub fn delete_anchor(subs: &mut [Sub], at: Vec2, edges: &[Seg], joined: Option<& _ => false, } } - Vertex::Start => match (s.segs.first().and_then(&which), edges.len()) { + Vertex::Start => match (s.segs.first().and_then(which), edges.len()) { // The new first segment ends where the old one did. (Some(a), 2) => match (toward(1 - a), s.segs.first_mut()) { (Some(n), Some(first)) => {