chore: merge main (onion skin) into stroke styles (M7)

This commit is contained in:
Tanish Manku committed 2026-11-10 19:22:53 -07:00
commit 0aa25bf1fa
28 files changed
+1915 -99

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ shaders or SDK code).
| Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | <https://github.com/source-foundry/Hack> | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) |
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
| `assets/icons/anicraft-*.svg` (18 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
| `assets/icons/anicraft-*.svg` (19 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper, muted sound, magnet, bone, edit multiple frames) | Align panel, layer-type, Width tool, Camera, Brush, Eraser, Eyedropper and Bone tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
| `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
+19
View File
@@ -19,6 +19,25 @@
miter limits and dash lengths. Older files open unchanged.
* Headless: new `stroke.set_style`; `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`
and `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`.
* **Onion skin controls and Edit Multiple Frames** (ADR 0047, M1). Onion skin works as Animate
users expect:
* **Markers** on the frame ruler: drag the start and end brackets to choose how many frames
show before and after the playhead. The onion menu (the arrow next to the timeline's onion
buttons, a right-click on the ruler, or View › Onion Skin Options) has Always Show Markers,
Anchor Markers (they stay put when the playhead moves), and the Onion 2, Onion 5 and Onion
All presets.
* Frames before the playhead are tinted blue and frames after it green, each fainter the
farther it is. Pick your own colours or turn tinting or fading off in the menu; **Outlines**
draws onion frames as outlines only, and **Keyframes Only** shows only keyframes. Your
choices are remembered.
* Onion frames now show over a background layer (they used to be hidden under it), and locked
layers are left out, as in Animate.
* **Edit Multiple Frames** (the timeline button next to Onion Skin) shows every keyframe
between the markers at full strength. Click, Shift-click, marquee or Select All to select
artwork on all of them, then drag it or use the arrow keys to move it everywhere at once:
one undo step. A motion tween's path moves with its object.
* Headless: `frames.artwork` lists the artwork on those keyframes and
`frames.edit_multiple` moves it.
* **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
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M9 3 L19 3 A2 2 0 0 1 21 5 L21 15" />
<path d="M6 6 L16 6 A2 2 0 0 1 18 8 L18 18" />
<rect x="3" y="9" width="12" height="12" rx="2" />
</svg>

After

Width:  |  Height:  |  Size: 340 B

+1 -1
View File
@@ -31,7 +31,7 @@ const MAX_ELEMENTS: usize = 10_000;
/// a namespace this list doesn't know is refused until someone decides (a test checks that
/// every registered namespace is known).
pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> {
const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw"];
const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "script", "raw", "frames"];
match id {
"edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"),
"edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" => {
+26 -21
View File
@@ -33,6 +33,7 @@ pub mod confirm;
pub mod format;
pub mod history;
mod merge;
pub mod onion;
pub mod recovery;
pub mod render_service;
pub mod selection;
@@ -111,6 +112,7 @@ pub fn commands() -> Vec<CommandSpec> {
v.extend(cmds_hints::specs());
v.extend(cmds_scene::specs());
v.extend(cmds_frames::specs());
v.extend(onion::specs());
v.extend(cmds_draw::specs());
v.extend(merge::specs());
v.extend(cmds_modify::specs());
@@ -148,6 +150,27 @@ pub use selection::Selection;
/// Last addressable frame (0-based); about 70 minutes at 24 fps.
pub const MAX_FRAME: u32 = 100_000;
/// The index of the topmost item of `dl` under `p` (stage space) that `ok` accepts (given its
/// index). A bounding-box test rejects almost every item before any curve is flattened;
/// masked-away parts cannot be picked.
pub(crate) fn pick_index(dl: &DisplayList, p: Vec2, slop: f32, ok: impl Fn(usize, &anicraft_doc::DisplayItem) -> bool) -> Option<usize> {
for (i, item) in dl.items.iter().enumerate().rev() {
let hw = item.stroke.as_ref().map_or(0.0, |s| s.reach() * item.transform.mean_scale());
let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop);
if !bounds.contains(p) || !ok(i, item) {
continue;
}
if item.clip.is_some_and(|c| !dl.clip_contains(c, p)) {
continue;
}
let inside = item.fill.is_some() && item.path.contains(p, &item.transform, item.fill_rule);
if inside || item.path.distance_to_edge(p, &item.transform) <= hw + slop {
return Some(i);
}
}
None
}
/// Drawing defaults used by the drawing commands when params omit colours.
#[derive(Clone, Debug)]
pub struct ToolStyle {
@@ -702,28 +725,10 @@ impl Session {
/// Topmost element under `p` (stage space) on a visible, unlocked layer. A bounding-box
/// test rejects almost every item before any curve is flattened.
pub fn hit_test(&self, p: Vec2, slop: f32) -> Option<(LayerId, ElementId)> {
let tl = self.doc.timeline(self.scene);
let dl = self.display_list();
for item in dl.items.iter().rev() {
let hw = item.stroke.as_ref().map_or(0.0, |s| s.reach() * item.transform.mean_scale());
let bounds = item.path.bounds().transformed(&item.transform).inflate(hw + slop);
if !bounds.contains(p) {
continue;
}
let tl = self.doc.timeline(self.scene);
let Some(layer) = tl.layer(item.layer) else { continue };
if layer.locked || tl.locked_by_folder(layer.id) {
continue;
}
// Masked-away parts cannot be picked.
if item.clip.is_some_and(|c| !dl.clip_contains(c, p)) {
continue;
}
let inside = item.fill.is_some() && item.path.contains(p, &item.transform, item.fill_rule);
if inside || item.path.distance_to_edge(p, &item.transform) <= hw + slop {
return Some((item.layer, item.element));
}
}
None
let i = pick_index(&dl, p, slop, |_, it| tl.layer(it.layer).is_some_and(|layer| !layer.locked && !tl.locked_by_folder(layer.id)))?;
dl.items.get(i).map(|it| (it.layer, it.element))
}
/// Stage-space bounds of a top-level element at the playhead.
+544
View File
@@ -0,0 +1,544 @@
//! Onion skin and Edit Multiple Frames (ADR 0047).
//!
//! **Onion skin** draws the frames around the playhead under it, faded: frames before it in the
//! *past* colour, frames after it in the *future* colour, each fainter the farther it is (when
//! fading is on). Which frames are shown is set by two markers: they follow the playhead
//! (`before` and `after` frames of it) or stay where they were put (anchored). Options: tint or
//! the artwork's own colours, outlines only, keyframes only.
//!
//! **Edit Multiple Frames** shows the artwork on every keyframe within the markers at full
//! strength, as if on one frame, and `frames.edit_multiple` moves it: the elements chosen (or all
//! of them) on each of those keyframes, as one undo step.
//!
//! Both are *view* settings: the shell keeps an [`OnionSkin`] and passes it with each render job
//! (keyed by [`OnionSkin::key`], so the frame cache keeps working), and the composition here is a
//! pure function of the document, the frame and the settings. Only the moves change the
//! document, through the command.
//!
//! Behaviour learned from Adobe's public help pages on onion skinning and from watching the
//! program; nothing was copied.
use crate::params::*;
use crate::{CommandSpec, EngineError, MAX_FRAME, Result, Session};
use anicraft_doc::{ColorEffect, DisplayList, Document, ElementId, LayerId, LayerKind, Rgba, Timeline};
use anicraft_geom::{Affine, Rect, Vec2};
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashSet};
use std::hash::{Hash, Hasher};
/// Most frames onion skin or Edit Multiple Frames draws besides the playhead's (the nearest
/// ones are kept): each is one more evaluation of the scene.
pub const MAX_EXTRA_FRAMES: usize = 120;
/// Opacity of the nearest onion frame, and of the farthest when fading by distance.
pub const NEAR_ALPHA: f32 = 0.5;
pub const FAR_ALPHA: f32 = 0.12;
/// How much of the past or future colour tints an onion frame (the rest is its own colour, so
/// fills and lines inside it stay apart).
pub const TINT_AMOUNT: f32 = 0.8;
/// The marker presets (Onion 2, Onion 5): frames on each side of the playhead.
pub const PRESETS: [u32; 2] = [2, 5];
/// Where the onion markers are.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Markers {
/// `before` frames before the playhead to `after` frames after it, following it.
Relative { before: u32, after: u32 },
/// Fixed frames (0-based, inclusive), whatever the playhead does. `last` beyond the end
/// reaches the end however long the timeline gets (Onion All).
Anchored { first: u32, last: u32 },
}
/// Onion skin and Edit Multiple Frames settings (view state the shell owns).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OnionSkin {
/// Onion skin is on: frames around the playhead show under it.
pub ghosts: bool,
/// Edit Multiple Frames is on: keyframes within the markers show at full strength (and
/// onion frames are not drawn).
pub edit_multiple: bool,
pub markers: Markers,
/// Tint onion frames with `past` and `future`; off, they keep their own colours.
pub tint: bool,
pub past: Rgba,
pub future: Rgba,
/// Fainter with distance from the playhead; off, every onion frame has [`NEAR_ALPHA`].
pub fade: bool,
/// Onion frames as hairline outlines in their colour.
pub outlines: bool,
/// Only frames where a keyframe starts (on each layer, its own keyframes).
pub keyframes_only: bool,
}
impl Default for OnionSkin {
fn default() -> Self {
OnionSkin {
ghosts: true,
edit_multiple: false,
markers: Markers::Relative { before: 2, after: 2 },
tint: true,
past: Rgba::hex(0x4f8dff),
future: Rgba::hex(0x4cd07d),
fade: true,
outlines: false,
keyframes_only: false,
}
}
}
/// Most frames a marker reaches from the playhead.
pub const MAX_REACH: u32 = MAX_FRAME;
impl OnionSkin {
/// Whether it changes what the stage shows.
pub fn shows(&self) -> bool {
self.ghosts || self.edit_multiple
}
/// The frames within the markers (0-based, inclusive) for a timeline of `frames` frames
/// with the playhead on `playhead`: always inside the timeline, `first <= last`.
pub fn range(&self, playhead: u32, frames: u32) -> (u32, u32) {
let end = frames.max(1) - 1;
match self.markers {
Markers::Relative { before, after } => {
let p = playhead.min(end);
(p.saturating_sub(before.min(MAX_REACH)), p.saturating_add(after.min(MAX_REACH)).min(end))
}
Markers::Anchored { first, last } => {
let (a, b) = (first.min(last), first.max(last));
(a.min(end), b.min(end))
}
}
}
/// Anchors the markers where they are now (`on`), or makes them follow the playhead again,
/// the same distance from it (a marker the playhead has passed is moved onto it).
pub fn set_anchored(&mut self, on: bool, playhead: u32, frames: u32) {
let (first, last) = self.range(playhead, frames);
self.markers = match (on, self.markers) {
(true, Markers::Relative { .. }) => Markers::Anchored { first, last },
(false, Markers::Anchored { .. }) => {
let p = playhead.min(frames.max(1) - 1);
Markers::Relative { before: p.saturating_sub(first), after: last.saturating_sub(p) }
}
(_, m) => m,
};
}
pub fn anchored(&self) -> bool {
matches!(self.markers, Markers::Anchored { .. })
}
/// Onion 2 / Onion 5: `n` frames on each side, following the playhead.
pub fn preset(&mut self, n: u32) {
self.markers = Markers::Relative { before: n.min(MAX_REACH), after: n.min(MAX_REACH) };
}
/// Onion All: the whole timeline, however long it gets.
pub fn all(&mut self) {
self.markers = Markers::Anchored { first: 0, last: MAX_FRAME };
}
/// Whether the markers are Onion All's.
pub fn is_all(&self) -> bool {
self.markers == Markers::Anchored { first: 0, last: MAX_FRAME }
}
/// Moves the start marker (`start`) or the end marker to frame `to`, keeping the range on
/// the right side of the playhead when relative, and never past the other marker.
pub fn drag_marker(&mut self, start: bool, to: u32, playhead: u32, frames: u32) {
let end = frames.max(1) - 1;
let to = to.min(end);
let (first, last) = self.range(playhead, frames);
let p = playhead.min(end);
self.markers = match self.markers {
Markers::Relative { after, .. } if start => Markers::Relative { before: p.saturating_sub(to.min(p)), after },
Markers::Relative { before, .. } => Markers::Relative { before, after: to.max(p) - p },
Markers::Anchored { .. } if start => Markers::Anchored { first: to.min(last), last },
Markers::Anchored { .. } => Markers::Anchored { first, last: to.max(first) },
};
}
/// Opacity of an onion frame `distance` frames from the playhead, on a side whose marker
/// is `reach` frames away.
pub fn alpha(&self, distance: u32, reach: u32) -> f32 {
if !self.fade || reach <= 1 {
return NEAR_ALPHA;
}
let t = (distance.saturating_sub(1) as f32 / (reach - 1) as f32).clamp(0.0, 1.0);
NEAR_ALPHA * (1.0 - t) + FAR_ALPHA * t
}
/// The colour effect an onion frame gets, and the outline colour (when outlines are on).
pub fn look(&self, past: bool, distance: u32, reach: u32) -> (ColorEffect, Option<Rgba>) {
let alpha = self.alpha(distance, reach);
let color = if past { self.past } else { self.future };
let (tint, tint_amount) = if self.tint { (color, TINT_AMOUNT) } else { (Rgba::WHITE, 0.0) };
let outline = self.outlines.then(|| color.with_alpha(alpha * color.a.clamp(0.0, 1.0)));
(ColorEffect { alpha, tint, tint_amount }, outline)
}
/// A hash of everything that changes the picture, for render-cache keys.
pub fn key(&self) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
(self.ghosts, self.edit_multiple, self.markers, self.tint, self.fade, self.outlines, self.keyframes_only).hash(&mut h);
for c in [self.past, self.future] {
[c.r, c.g, c.b, c.a].map(f32::to_bits).hash(&mut h);
}
h.finish()
}
}
/// One extra frame to draw under the playhead's: frame `frame`, only `layers`' artwork.
#[derive(Clone, Debug, PartialEq)]
pub struct Extra {
pub frame: u32,
pub layers: Vec<LayerId>,
/// An onion frame before the playhead (`Some(true)`), after it (`Some(false)`), or an Edit
/// Multiple Frames keyframe at full strength (`None`).
pub past: Option<bool>,
/// Frames from the playhead.
pub distance: u32,
}
/// Whether onion skin draws `layer` (Animate doesn't onion-skin locked layers).
fn ghosted(tl: &Timeline, i: usize) -> bool {
tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder && !tl.locked_by_folder(l.id) && !tl.hidden_by_folder(i))
}
/// Whether Edit Multiple Frames shows and edits `layer`'s other keyframes: it is shown and
/// unlocked, and holds artwork (not a folder, the camera or an armature posed by its bones).
pub fn multi_editable(tl: &Timeline, i: usize) -> bool {
ghosted(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature))
}
/// The onion frames to draw for the playhead on `playhead`, farthest first (nearest on top),
/// past and future taking turns at each distance.
pub fn onion_frames(tl: &Timeline, playhead: u32, skin: &OnionSkin) -> Vec<Extra> {
let (first, last) = skin.range(playhead, tl.frame_count());
let layers: Vec<usize> = (0..tl.layers.len()).filter(|&i| ghosted(tl, i)).collect();
if layers.is_empty() {
return Vec::new();
}
let mut out: Vec<Extra> = Vec::new();
// Nearest first, so the cap keeps the nearest; reversed at the end.
let reach = playhead.saturating_sub(first).max(last.saturating_sub(playhead));
for d in 1..=reach {
if out.len() >= MAX_EXTRA_FRAMES {
break;
}
// Future first: the list is reversed below, so at each distance the past frame is drawn
// first.
for (past, f) in [(false, playhead.checked_add(d)), (true, playhead.checked_sub(d))] {
let Some(f) = f.filter(|f| (first..=last).contains(f)) else { continue };
let ids: Vec<LayerId> = if skin.keyframes_only {
// A layer's keyframe starting there; the one the playhead is on only when it
// tweens (otherwise it looks the same as the playhead's frame).
layers.iter().filter_map(|&i| tl.layers.get(i)).filter(|l| l.keyframe_starting_at(f).and_then(|k| l.keyframes.get(k)).is_some_and(|k| !k.covers(playhead) || k.tween.is_some() || k.motion.is_some())).map(|l| l.id).collect()
} else {
layers.iter().filter_map(|&i| tl.layers.get(i)).map(|l| l.id).collect()
};
if !ids.is_empty() && out.len() < MAX_EXTRA_FRAMES {
out.push(Extra { frame: f, layers: ids, past: Some(past), distance: d });
}
}
}
out.reverse();
out
}
/// The keyframes Edit Multiple Frames draws besides the playhead's: on each editable layer,
/// every keyframe whose span reaches into `first..=last` except the one under the playhead,
/// drawn as it looks on its first frame. Grouped by that frame, in frame order.
pub fn multi_frames(tl: &Timeline, playhead: u32, first: u32, last: u32) -> Vec<Extra> {
let mut at: BTreeMap<u32, Vec<LayerId>> = BTreeMap::new();
for (i, l) in tl.layers.iter().enumerate() {
if !multi_editable(tl, i) {
continue;
}
for k in l.keyframes.iter().filter(|k| k.start <= last && k.end() > first && !k.covers(playhead)) {
at.entry(k.start).or_default().push(l.id);
}
}
let mut out: Vec<Extra> = at.into_iter().map(|(frame, layers)| Extra { frame, layers, past: None, distance: frame.abs_diff(playhead) }).collect();
if out.len() > MAX_EXTRA_FRAMES {
// Keep the nearest, still in frame order.
let mut by: Vec<u32> = out.iter().map(|e| e.distance).collect();
by.sort_unstable();
let cut = by.get(MAX_EXTRA_FRAMES - 1).copied().unwrap_or(0);
let mut kept = 0usize;
out.retain(|e| {
let keep = e.distance <= cut && kept < MAX_EXTRA_FRAMES;
kept += usize::from(keep);
keep
});
}
out
}
/// Keeps only `layers`' items (and the mask artwork their clips need, which draws nothing).
fn keep_layers(dl: &mut DisplayList, layers: &[LayerId]) {
let set: HashSet<LayerId> = layers.iter().copied().collect();
dl.items.retain(|i| set.contains(&i.layer) || (i.masks.is_some() && i.group.is_none()));
}
/// The parts as one list, layer by layer: each layer's items from every part, in part order,
/// then the next layer up. So a frame before or after the playhead shows under the playhead's
/// artwork *on its own layer* and over the layers below, as in Animate, and an opaque
/// background never hides it. Also says which part each item came from.
///
/// Reordering items is safe: a group's run lies within one layer (it stays unbroken), and the
/// renderers take mask artwork apart from what they draw, whatever its place in the list.
fn interleave(tl: &Timeline, parts: Vec<DisplayList>) -> (DisplayList, Vec<usize>) {
let n = tl.layers.len();
let rank: std::collections::HashMap<LayerId, usize> = tl.layers.iter().enumerate().map(|(i, l)| (l.id, i)).collect();
// Back to front: the bottom layer (the highest index) first; an unknown layer before all.
let bucket = |l: LayerId| rank.get(&l).map_or(0, |r| n - r);
let total = parts.iter().map(|p| p.items.len()).sum();
let mut dl = DisplayList::default();
let mut iters = Vec::with_capacity(parts.len());
for part in parts {
// Clips and groups renumbered as `DisplayList::append` does.
let (base, gbase) = (dl.clip_parents.len() as u32, dl.groups.len() as u32);
let shift = move |c: Option<u32>| c.map(|c| c + base);
let gshift = move |g: Option<u32>| g.map(|g| g + gbase);
dl.clip_parents.extend(part.clip_parents.into_iter().map(shift));
dl.groups.extend(part.groups.into_iter().map(|g| anicraft_doc::Group { parent: gshift(g.parent), clip: shift(g.clip), ..g }));
iters.push(
part.items
.into_iter()
.map(move |mut i| {
i.clip = shift(i.clip);
i.masks = shift(i.masks);
i.group = gshift(i.group);
i
})
.peekable(),
);
}
// Each part is already back to front, layer by layer: one merge, each item moved once.
let mut items = Vec::with_capacity(total);
let mut from = Vec::with_capacity(total);
for b in 0..=n {
for (k, it) in iters.iter_mut().enumerate() {
while let Some(x) = it.next_if(|x| bucket(x.layer) <= b) {
items.push(x);
from.push(k);
}
}
}
// (Nothing is left unless a part was out of layer order; keep it rather than drop it.)
for (k, it) in iters.into_iter().enumerate() {
for x in it {
items.push(x);
from.push(k);
}
}
dl.items = items;
(dl, from)
}
/// Scene `scene` at its frame `local` with what `skin` adds (nothing for `None`): onion frames,
/// or Edit Multiple Frames' keyframes, each under the playhead's artwork on its own layer.
/// `eval` evaluates one frame of the scene (with or without its camera).
pub fn compose(doc: &Document, scene: usize, local: u32, skin: Option<&OnionSkin>, eval: impl Fn(usize, u32) -> DisplayList + Sync) -> DisplayList {
let now = eval(scene, local);
let Some(skin) = skin.filter(|s| s.shows()) else { return now };
let tl = doc.timeline(scene);
let (first, last) = skin.range(local, tl.frame_count());
let extras = if skin.edit_multiple { multi_frames(tl, local, first, last) } else { onion_frames(tl, local, skin) };
if extras.is_empty() {
return now;
}
// The frames are independent: evaluated in parallel, kept in order.
use rayon::prelude::*;
let mut parts: Vec<DisplayList> = extras.par_iter().map(|e| eval(scene, e.frame)).collect();
for (part, e) in parts.iter_mut().zip(&extras) {
keep_layers(part, &e.layers);
if let Some(past) = e.past {
let reach = if past { local.saturating_sub(first) } else { last.saturating_sub(local) };
let (fx, outline) = skin.look(past, e.distance, reach);
for item in &mut part.items {
item.color = item.color.concat(&fx);
if outline.is_some() && item.masks.is_none() {
item.outline = outline;
}
}
}
}
parts.push(now);
interleave(tl, parts).0
}
// ----- Edit Multiple Frames: artwork, picking and moves ------------------------------------
/// An element on one keyframe: its layer, the keyframe's first frame and its id (an element
/// keeps its id from keyframe to keyframe, so the frame says which copy).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FrameItem {
pub layer: LayerId,
pub frame: u32,
pub element: ElementId,
}
impl FrameItem {
pub fn to_json(&self) -> Value {
json!([self.layer.0, self.frame, self.element.0])
}
}
impl Session {
/// What Edit Multiple Frames shows in `first..=last`, layer by layer as the stage draws it
/// (each keyframe as it looks on its first frame, the playhead's as it looks there), with
/// the keyframe start of each item's layer (`None`: a layer it doesn't edit).
fn multi_list(&self, first: u32, last: u32) -> (DisplayList, Vec<Option<u32>>) {
let tl = self.doc.timeline(self.scene);
let mut parts = Vec::new();
let mut starts: Vec<Vec<(LayerId, u32)>> = Vec::new();
for e in multi_frames(tl, self.frame, first, last) {
let mut dl = anicraft_doc::evaluate_scene(&self.doc, self.scene, e.frame);
keep_layers(&mut dl, &e.layers);
parts.push(dl);
starts.push(e.layers.iter().map(|l| (*l, e.frame)).collect());
}
// The playhead's frame: every editable layer, at the start of its keyframe there.
let now: Vec<(LayerId, u32)> = tl.layers.iter().enumerate().filter(|(i, _)| multi_editable(tl, *i)).filter_map(|(_, l)| l.keyframe_at(self.frame).map(|k| (l.id, k.start))).collect();
let mut dl = (*self.display_list()).clone();
keep_layers(&mut dl, &now.iter().map(|(l, _)| *l).collect::<Vec<_>>());
parts.push(dl);
starts.push(now);
let (dl, from) = interleave(tl, parts);
let frames = dl.items.iter().zip(&from).map(|(it, &k)| starts.get(k).and_then(|s| s.iter().find(|(l, _)| *l == it.layer)).map(|(_, f)| *f)).collect();
(dl, frames)
}
/// Every element Edit Multiple Frames shows in `first..=last`, with its stage bounds (the
/// playhead's elements as they look there), back to front.
pub fn multi_frame_items(&self, first: u32, last: u32) -> Vec<(FrameItem, Rect)> {
let (first, last) = (first.min(last), first.max(last));
let mut out: Vec<(FrameItem, Rect)> = Vec::new();
let mut index: std::collections::HashMap<FrameItem, usize> = std::collections::HashMap::new();
let (dl, frames) = self.multi_list(first, last);
{
for (item, frame) in dl.items.iter().zip(frames) {
let Some(frame) = frame else { continue };
let key = FrameItem { layer: item.layer, frame, element: item.element };
let pad = item.stroke.as_ref().map_or(0.0, anicraft_doc::Stroke::reach);
let b = item.path.bounds().inflate(pad).transformed(&item.transform);
match index.get(&key).and_then(|&i| out.get_mut(i)) {
Some((_, r)) => *r = r.union(&b),
None => {
index.insert(key, out.len());
out.push((key, b));
}
}
}
}
out
}
/// The topmost element Edit Multiple Frames shows under `p` in `first..=last`.
pub fn multi_frame_pick(&self, first: u32, last: u32, p: Vec2, slop: f32) -> Option<FrameItem> {
let (first, last) = (first.min(last), first.max(last));
let (dl, frames) = self.multi_list(first, last);
let i = crate::pick_index(&dl, p, slop, |i, _| frames.get(i).copied().flatten().is_some())?;
let item = dl.items.get(i)?;
Some(FrameItem { layer: item.layer, frame: frames.get(i).copied().flatten()?, element: item.element })
}
}
pub fn specs() -> Vec<CommandSpec> {
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
vec![
c("frames.artwork", "Artwork on Multiple Frames", "", None, "{first, last} lists every element Edit Multiple Frames shows in frames first..=last (0-based): [layer, frame (its keyframe's first frame), id] with stage bounds; the playhead's elements as they look there", false, artwork as crate::RunFn),
c("frames.edit_multiple", "Move on Multiple Frames", "", None, "{first, last, dx, dy, items?: [[layer, frame, id], ..]} moves artwork on every keyframe within frames first..=last (0-based) on visible, unlocked layers, as Edit Multiple Frames does: the items given (a keyframe's first frame and an element id), or all of them; a motion tween's path and X/Y keys move with its object; one undo step", true, edit_multiple),
]
}
/// The `first` and `last` params, in order.
fn range_param(p: &Value) -> Result<(u32, u32)> {
let req = |k: &str| opt_u32(p, k)?.ok_or_else(|| EngineError::Param(format!("param '{k}' is required (a frame, 0-based)")));
let (a, b) = (req("first")?, req("last")?);
if a.max(b) > MAX_FRAME {
return Err(EngineError::Param(format!("frames go up to {MAX_FRAME}")));
}
Ok((a.min(b), a.max(b)))
}
fn artwork(s: &mut Session, p: &Value) -> Result<Value> {
let (first, last) = range_param(p)?;
let items: Vec<Value> = s.multi_frame_items(first, last).into_iter().map(|(it, b)| json!({"layer": it.layer.0, "frame": it.frame, "id": it.element.0, "bounds": [b.min.x, b.min.y, b.max.x, b.max.y]})).collect();
Ok(json!({"first": first, "last": last, "items": items}))
}
/// Most items `frames.edit_multiple` takes.
const MAX_ITEMS: usize = 100_000;
fn items_param(p: &Value) -> Result<Option<Vec<FrameItem>>> {
let Some(v) = p.get("items").filter(|v| !v.is_null()) else { return Ok(None) };
let bad = || EngineError::Param("param 'items' must be a list of [layer, frame, id]".into());
let list = v.as_array().ok_or_else(bad)?;
if list.len() > MAX_ITEMS {
return Err(EngineError::Param(format!("param 'items' has more than {MAX_ITEMS} items")));
}
list.iter()
.map(|t| {
let t = t.as_array().filter(|t| t.len() == 3).ok_or_else(bad)?;
let n = |i: usize| t.get(i).and_then(Value::as_u64).ok_or_else(bad);
let frame = u32::try_from(n(1)?).map_err(|_| bad())?;
Ok(FrameItem { layer: LayerId(n(0)?), frame, element: ElementId(n(2)?) })
})
.collect::<Result<Vec<_>>>()
.map(Some)
}
fn edit_multiple(s: &mut Session, p: &Value) -> Result<Value> {
let (first, last) = range_param(p)?;
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
if d.x.abs() > crate::cmds_draw::MAX_EXTENT || d.y.abs() > crate::cmds_draw::MAX_EXTENT {
return Err(EngineError::Param("the move is too large".into()));
}
let shown: Vec<FrameItem> = s.multi_frame_items(first, last).into_iter().map(|(it, _)| it).collect();
let items = match items_param(p)? {
Some(list) => {
let have: HashSet<FrameItem> = shown.iter().copied().collect();
if let Some(bad) = list.iter().find(|it| !have.contains(it)) {
return Err(EngineError::State(format!(
"element {} on layer {} at frame {} is not on a keyframe Edit Multiple Frames shows in frames {first}..={last} (on a visible, unlocked layer)",
bad.element.0, bad.layer.0, bad.frame
)));
}
list
}
None => shown,
};
// One pass per keyframe: (layer, keyframe start) → its ids.
let mut by_key: BTreeMap<(LayerId, u32), HashSet<ElementId>> = BTreeMap::new();
for it in &items {
by_key.entry((it.layer, it.frame)).or_default().insert(it.element);
}
let mv = Affine::translate(d.x, d.y);
let mut moved = 0usize;
for ((layer, start), ids) in &by_key {
let l = s.layer_mut(Some(*layer))?;
let Some(ki) = l.keyframe_starting_at(*start) else { continue };
let Some(kf) = l.keyframe_mut(ki) else { continue };
// A motion tween's object carries its path and X/Y keys along (refused, with nothing
// changed, if they would leave the stage's range).
if let Some(m) = kf.motion.as_mut()
&& ids.contains(&m.target)
&& d != Vec2::ZERO
&& !m.translate(d)
{
return Err(EngineError::State("the motion path would move out of range".into()));
}
for e in kf.elements_mut_where(|id| ids.contains(&id)) {
e.transform = mv.mul(&e.transform);
moved += 1;
}
}
Ok(json!({"moved": moved, "keyframes": by_key.len(), "dx": d.x, "dy": d.y}))
}
#[cfg(test)]
#[path = "onion_tests.rs"]
mod tests;
+431
View File
@@ -0,0 +1,431 @@
//! Onion skin and Edit Multiple Frames (ADR 0047): markers, tint and fade, outlines, keyframes
//! only, the composed display list and its render, and moves on several keyframes.
use super::*;
use crate::Session;
use anicraft_doc::{DisplayItem, ElementId, LayerId, Rgba, evaluate_scene, sample};
use anicraft_render::{View, render};
use serde_json::{Value, json};
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
/// One layer, a 20 × 20 drawing object walking right: keyframes on frames 0, 4 and 8 (the last
/// one frame long) with it at x = 10, 50 and 90 (y = 10). The playhead is on frame 4.
fn walk() -> (Session, LayerId, ElementId) {
let mut s = Session::default();
let layer = s.layer;
let id = ElementId(run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap());
for f in [4, 8] {
run(&mut s, "timeline.goto", json!({"frame": f}));
run(&mut s, "timeline.insert_keyframe", json!({}));
run(&mut s, "element.select", json!({"ids": [id.0]}));
run(&mut s, "element.translate", json!({"dx": 40, "dy": 0}));
}
run(&mut s, "timeline.goto", json!({"frame": 4}));
assert_eq!(s.frame_count(), 9);
(s, layer, id)
}
/// The left edge of `id` on the keyframe of `layer` starting at `start`.
fn x_at(s: &Session, layer: LayerId, start: u32, id: ElementId) -> f32 {
let l = s.doc.timeline(s.scene).layer(layer).unwrap();
let k = l.keyframes.iter().find(|k| k.start == start).unwrap();
let e = k.elements.iter().find(|e| e.id == id).unwrap();
e.bounds(&s.doc).min.x
}
fn left(i: &DisplayItem) -> f32 {
i.path.bounds().transformed(&i.transform).min.x
}
#[test]
fn markers_stay_inside_the_timeline() {
let mut o = OnionSkin::default();
assert_eq!(o.range(0, 10), (0, 2), "nothing before frame 1");
assert_eq!(o.range(9, 10), (7, 9), "nothing after the last frame");
assert_eq!(o.range(50, 10), (7, 9), "a playhead past the end counts as the last frame");
assert_eq!(o.range(0, 0), (0, 0));
o.markers = Markers::Relative { before: u32::MAX, after: u32::MAX };
assert_eq!(o.range(5, 10), (0, 9));
o.markers = Markers::Anchored { first: 8, last: 3 };
assert_eq!(o.range(0, 10), (3, 8), "anchored markers in order, whatever the playhead");
o.markers = Markers::Anchored { first: 400, last: 900 };
assert_eq!(o.range(0, 10), (9, 9));
o.all();
assert!(o.is_all() && o.anchored());
assert_eq!(o.range(4, 10), (0, 9));
assert_eq!(o.range(4, 500), (0, 499), "Onion All grows with the timeline");
o.preset(5);
assert!(!o.anchored() && !o.is_all());
assert_eq!(o.range(10, 100), (5, 15));
}
#[test]
fn markers_drag_and_anchor() {
let mut o = OnionSkin::default();
o.drag_marker(true, 1, 6, 20);
assert_eq!(o.range(6, 20), (1, 8));
o.drag_marker(true, 9, 6, 20);
assert_eq!(o.range(6, 20), (6, 8), "the start marker stops at the playhead");
o.drag_marker(false, 50, 6, 20);
assert_eq!(o.range(6, 20), (6, 19), "the end marker stops at the last frame");
o.drag_marker(false, 2, 6, 20);
assert_eq!(o.range(6, 20), (6, 6));
// Anchoring keeps the frames; the playhead then moves without them.
o.preset(2);
o.set_anchored(true, 6, 20);
assert_eq!((o.range(6, 20), o.range(15, 20)), ((4, 8), (4, 8)));
o.drag_marker(true, 12, 15, 20);
assert_eq!(o.range(15, 20), (8, 8), "never past the other marker");
o.drag_marker(false, 3, 15, 20);
assert_eq!(o.range(15, 20), (8, 8));
o.drag_marker(false, 12, 15, 20);
assert_eq!(o.range(15, 20), (8, 12));
// Following the playhead again: the same distances from it...
o.set_anchored(false, 10, 20);
assert_eq!(o.markers, Markers::Relative { before: 2, after: 2 });
// ...and a marker the playhead has passed lands on it.
o.set_anchored(true, 10, 20);
o.set_anchored(false, 15, 20);
assert_eq!(o.range(15, 20), (8, 15));
}
#[test]
fn onion_frames_fade_by_distance_in_their_colours() {
let o = OnionSkin::default();
assert_eq!(o.alpha(1, 5), NEAR_ALPHA);
assert_eq!(o.alpha(5, 5), FAR_ALPHA);
assert!((o.alpha(3, 5) - (NEAR_ALPHA + FAR_ALPHA) / 2.0).abs() < 1e-6);
assert!((1..5).all(|d| o.alpha(d, 5) > o.alpha(d + 1, 5)), "fainter with each frame");
assert_eq!(o.alpha(1, 1), NEAR_ALPHA);
assert_eq!(o.alpha(9, 5), FAR_ALPHA, "never fainter than the farthest");
let flat = OnionSkin { fade: false, ..o };
assert!((1..=5).all(|d| flat.alpha(d, 5) == NEAR_ALPHA));
let (past, line) = o.look(true, 1, 2);
assert_eq!((past.tint, past.tint_amount, past.alpha, line), (o.past, TINT_AMOUNT, NEAR_ALPHA, None));
let (future, _) = o.look(false, 2, 2);
assert_eq!((future.tint, future.alpha), (o.future, FAR_ALPHA));
let (own, _) = OnionSkin { tint: false, ..o }.look(true, 1, 2);
assert_eq!(own.tint_amount, 0.0, "untinted frames keep their own colours");
let (_, line) = OnionSkin { outlines: true, ..o }.look(false, 2, 2);
assert_eq!(line, Some(o.future.with_alpha(FAR_ALPHA)));
}
#[test]
fn every_setting_is_in_the_key() {
let o = OnionSkin::default();
let variants = [
OnionSkin { ghosts: false, ..o },
OnionSkin { edit_multiple: true, ..o },
OnionSkin { markers: Markers::Relative { before: 2, after: 3 }, ..o },
OnionSkin { markers: Markers::Anchored { first: 0, last: 2 }, ..o },
OnionSkin { tint: false, ..o },
OnionSkin { past: Rgba::hex(0x123456), ..o },
OnionSkin { future: Rgba::hex(0x123456), ..o },
OnionSkin { fade: false, ..o },
OnionSkin { outlines: true, ..o },
OnionSkin { keyframes_only: true, ..o },
];
let mut keys: Vec<u64> = variants.iter().map(OnionSkin::key).collect();
keys.push(o.key());
let n = keys.len();
keys.sort_unstable();
keys.dedup();
assert_eq!(keys.len(), n);
assert_eq!(o.key(), OnionSkin::default().key());
}
#[test]
fn onion_frames_come_farthest_first_and_skip_locked_layers() {
let (mut s, a, _) = walk();
let b = LayerId(run(&mut s, "layer.new", json!({"name": "Locked"}))["layer"].as_u64().unwrap());
run(&mut s, "draw.rect", json!({"x": 0, "y": 100, "w": 9, "h": 9, "object": true}));
run(&mut s, "timeline.insert_frame", json!({"count": 8}));
run(&mut s, "layer.toggle_lock", json!({"layer": b.0}));
let tl = s.doc.timeline(s.scene);
let got: Vec<(u32, Option<bool>, u32)> = onion_frames(tl, 4, &OnionSkin::default()).iter().map(|e| (e.frame, e.past, e.distance)).collect();
assert_eq!(got, vec![(2, Some(true), 2), (6, Some(false), 2), (3, Some(true), 1), (5, Some(false), 1)]);
assert!(onion_frames(tl, 4, &OnionSkin::default()).iter().all(|e| e.layers == vec![a]), "locked layers are not onion-skinned");
// At the first frame there is no past.
assert!(onion_frames(tl, 0, &OnionSkin::default()).iter().all(|e| e.past == Some(false)));
}
#[test]
fn keyframes_only_shows_each_layers_own_keyframes() {
let (mut s, a, _) = walk();
let b = LayerId(run(&mut s, "layer.new", json!({"name": "B"}))["layer"].as_u64().unwrap());
run(&mut s, "timeline.goto", json!({"frame": 0}));
run(&mut s, "draw.rect", json!({"x": 0, "y": 100, "w": 9, "h": 9, "object": true}));
run(&mut s, "timeline.goto", json!({"frame": 2}));
run(&mut s, "timeline.insert_keyframe", json!({}));
run(&mut s, "timeline.insert_frame", json!({"count": 6}));
let tl = s.doc.timeline(s.scene);
let skin = OnionSkin { keyframes_only: true, markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() };
let mut got: Vec<(u32, Vec<LayerId>)> = onion_frames(tl, 4, &skin).into_iter().map(|e| (e.frame, e.layers)).collect();
got.sort_by_key(|(f, _)| *f);
// Frame 0 is a keyframe on both layers, frame 8 on A. B's keyframe on 2 is the one under the
// playhead and doesn't tween: it would only repeat what the playhead shows, so it is left out.
assert_eq!(got, vec![(0, vec![b, a]), (8, vec![a])]);
// With all frames, every frame in range is there.
let all = onion_frames(tl, 4, &OnionSkin { keyframes_only: false, ..skin }).len();
let (f0, f1) = skin.range(4, tl.frame_count());
assert_eq!(all as u32, f1 - f0);
}
#[test]
fn composed_onion_frames_are_tinted_faded_and_under_the_playhead() {
let (s, _, _) = walk();
let skin = OnionSkin::default();
let dl = compose(&s.doc, 0, 4, Some(&skin), |sc, f| evaluate_scene(&s.doc, sc, f));
// Frames 2, 6, 3, 5 under frame 4: the keyframes there hold the rectangle at 10, 50, 10, 50.
let got: Vec<(f32, f32, f32)> = dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect();
assert_eq!(got, vec![(10.0, FAR_ALPHA, TINT_AMOUNT), (50.0, FAR_ALPHA, TINT_AMOUNT), (10.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, NEAR_ALPHA, TINT_AMOUNT), (50.0, 1.0, 0.0)]);
assert_eq!(dl.items.first().map(|i| i.color.tint), Some(skin.past));
assert_eq!(dl.items.get(1).map(|i| i.color.tint), Some(skin.future));
// Off, or None: the frame alone.
let off = OnionSkin { ghosts: false, ..skin };
assert_eq!(compose(&s.doc, 0, 4, Some(&off), |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1);
assert_eq!(compose(&s.doc, 0, 4, None, |sc, f| evaluate_scene(&s.doc, sc, f)).items.len(), 1);
}
/// The pixel at (x, y), premultiplied RGBA8.
fn px(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
let i = ((y * w + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
}
#[test]
fn outline_mode_draws_onion_frames_as_edges_only() {
let (s, _, _) = walk();
let view = View { transform: Affine::IDENTITY, width: 120, height: 40, background: Some(Rgba::WHITE) };
let draw = |skin: &OnionSkin| {
let dl = compose(&s.doc, 0, 4, Some(skin), |sc, f| evaluate_scene(&s.doc, sc, f));
render(&dl, &view).unwrap().0.to_premul_rgba8()
};
let filled = draw(&OnionSkin { markers: Markers::Relative { before: 4, after: 0 }, ..OnionSkin::default() });
let lines = draw(&OnionSkin { markers: Markers::Relative { before: 4, after: 0 }, outlines: true, ..OnionSkin::default() });
const WHITE: [u8; 4] = [255; 4];
// Inside the onion rectangle (frames 0–3 hold it at 10..30): tinted when filled, the stage
// when outlined; on its left edge (x = 10), the outline shows.
assert_ne!(px(&filled, 120, 20, 20), WHITE);
assert_eq!(px(&lines, 120, 20, 20), WHITE);
assert_ne!(px(&lines, 120, 10, 20), WHITE);
let edge = px(&lines, 120, 10, 20);
assert!(edge[2] > edge[0], "in the past colour (blue): {edge:?}");
// The playhead's frame (x = 50..70) is drawn as it is, either way.
assert_eq!(px(&lines, 120, 60, 20), [0, 0, 0, 255]);
assert_eq!(px(&filled, 120, 60, 20), [0, 0, 0, 255]);
}
#[test]
fn edit_multiple_frames_shows_keyframes_within_the_markers_at_full_strength() {
let (mut s, a, id) = walk();
let tl = s.doc.timeline(s.scene);
let near = OnionSkin { edit_multiple: true, ..OnionSkin::default() };
// ±2 around 4 is frames 2..6: the keyframe on 0 reaches into it (to frame 3), the one on 8
// doesn't; the one on 4 is the playhead's.
assert_eq!(multi_frames(tl, 4, 2, 6).iter().map(|e| e.frame).collect::<Vec<_>>(), vec![0]);
let dl = compose(&s.doc, 0, 4, Some(&near), |sc, f| evaluate_scene(&s.doc, sc, f));
assert_eq!(dl.items.iter().map(|i| (left(i), i.color.alpha, i.color.tint_amount)).collect::<Vec<_>>(), vec![(10.0, 1.0, 0.0), (50.0, 1.0, 0.0)]);
let wide = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..near };
let dl = compose(&s.doc, 0, 4, Some(&wide), |sc, f| evaluate_scene(&s.doc, sc, f));
assert_eq!(dl.items.iter().map(left).collect::<Vec<_>>(), vec![10.0, 90.0, 50.0], "other keyframes in frame order, the playhead's on top");
// What it shows is what it lists, each with its keyframe's first frame.
let items: Vec<(FrameItem, f32)> = s.multi_frame_items(0, 8).into_iter().map(|(it, b)| (it, b.min.x)).collect();
let item = |frame| FrameItem { layer: a, frame, element: id };
assert_eq!(items, vec![(item(0), 10.0), (item(8), 90.0), (item(4), 50.0)]);
let v = run(&mut s, "frames.artwork", json!({"first": 8, "last": 0}));
assert_eq!(v["items"].as_array().map(Vec::len), Some(3));
assert_eq!(v["items"][1], json!({"layer": a.0, "frame": 8, "id": id.0, "bounds": [90.0, 10.0, 110.0, 30.0]}));
}
#[test]
fn a_move_on_multiple_frames_moves_each_keyframe_and_undoes_in_one_step() {
let (mut s, a, id) = walk();
let steps = s.history_len();
let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 5, "dy": 7}));
assert_eq!((v["moved"].as_u64(), v["keyframes"].as_u64()), (Some(3), Some(3)));
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [15.0, 55.0, 95.0]);
assert_eq!(s.history_len(), steps + 1);
s.undo().unwrap();
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [10.0, 50.0, 90.0], "one undo takes back every keyframe");
// Only the items given.
run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": -10, "dy": 0, "items": [[a.0, 8, id.0]]}));
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [10.0, 50.0, 80.0]);
// A drag: many small moves in one gesture are one step.
let steps = s.history_len();
s.begin_gesture("Move");
for _ in 0..10 {
run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 4, "dx": 1, "dy": 0}));
}
s.end_gesture();
assert_eq!(s.history_len(), steps + 1);
assert_eq!([0, 4, 8].map(|f| x_at(&s, a, f, id)), [20.0, 60.0, 80.0], "the keyframe on 8 is outside frames 0..4");
}
#[test]
fn moves_refuse_what_edit_multiple_frames_does_not_show() {
let (mut s, a, id) = walk();
let before = s.doc.clone();
let e = s.execute("frames.edit_multiple", &json!({"first": 0, "last": 3, "dx": 5, "dy": 0, "items": [[a.0, 8, id.0]]}));
assert!(e.is_err(), "the keyframe on 8 is outside the markers");
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 8, 999]]})).is_err());
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 8]]})).is_err());
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "dx": 5, "dy": 0})).is_err());
assert!(s.doc == before);
run(&mut s, "layer.toggle_lock", json!({"layer": a.0}));
assert!(s.multi_frame_items(0, 8).is_empty(), "nothing on a locked layer");
assert_eq!(run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 8, "dx": 5, "dy": 0}))["moved"], json!(0));
assert!(s.execute("frames.edit_multiple", &json!({"first": 0, "last": 8, "dx": 5, "dy": 0, "items": [[a.0, 0, id.0]]})).is_err());
}
#[test]
fn picking_finds_artwork_on_every_keyframe_shown() {
let (s, a, id) = walk();
let at = |x: f32| s.multi_frame_pick(0, 8, Vec2::new(x, 20.0), 1.0);
assert_eq!(at(100.0), Some(FrameItem { layer: a, frame: 8, element: id }));
assert_eq!(at(60.0), Some(FrameItem { layer: a, frame: 4, element: id }));
assert_eq!(at(20.0), Some(FrameItem { layer: a, frame: 0, element: id }));
assert_eq!(at(150.0), None);
assert_eq!(s.multi_frame_pick(2, 6, Vec2::new(100.0, 20.0), 1.0), None, "outside the markers");
}
#[test]
fn a_motion_tweens_path_and_keys_move_with_its_object() {
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 20, "h": 20, "object": true}));
run(&mut s, "timeline.insert_frame", json!({"count": 9}));
run(&mut s, "timeline.create_motion_tween", json!({}));
run(&mut s, "timeline.goto", json!({"frame": 9}));
run(&mut s, "edit.select_all", json!({}));
run(&mut s, "element.translate", json!({"dx": 100, "dy": 0}));
let x_on = |s: &Session, f: u32| evaluate_scene(&s.doc, 0, f).items.first().map(left).unwrap_or(f32::NAN);
let before: Vec<f32> = (0..10).map(|f| x_on(&s, f)).collect();
run(&mut s, "timeline.goto", json!({"frame": 0}));
let v = run(&mut s, "frames.edit_multiple", json!({"first": 0, "last": 9, "dx": 10, "dy": 0}));
assert_eq!(v["moved"], json!(1));
let after: Vec<f32> = (0..10).map(|f| x_on(&s, f)).collect();
for (b, a) in before.iter().zip(&after) {
assert!((a - b - 10.0).abs() < 1e-3, "{before:?} → {after:?}");
}
}
#[test]
fn every_setting_composes_and_renders_on_the_sample() {
let doc = sample::demo();
let n = doc.timeline(0).frame_count();
let view = View { transform: Affine::scale(0.1, 0.1), width: 128, height: 72, background: Some(doc.stage.background) };
let mut count = 0;
for bits in 0u32..64 {
let mut o = OnionSkin { ghosts: bits & 1 != 0, edit_multiple: bits & 2 != 0, tint: bits & 4 != 0, fade: bits & 8 != 0, outlines: bits & 16 != 0, keyframes_only: bits & 32 != 0, ..OnionSkin::default() };
for (i, f) in [0, n / 2, n - 1, n + 40].into_iter().enumerate() {
match i {
1 => o.all(),
2 => o.markers = Markers::Anchored { first: n + 5, last: 1 },
3 => o.preset(5),
_ => {}
}
let dl = compose(&doc, 0, f.min(n - 1), Some(&o), |sc, fr| evaluate_scene(&doc, sc, fr));
count += dl.items.len();
if bits % 7 == 0 {
assert!(render(&dl, &view).is_ok());
}
}
}
assert!(count > 0);
}
/// Measures the stage's cost with onion skin ±5 at 1080p, through the tiled path the stage uses
/// (one scene evaluation per frame, tiles in parallel), and that a second look is a cache hit:
/// `cargo test --release -p anicraft-engine onion_timings -- --ignored --nocapture`.
#[test]
#[ignore]
fn onion_timings() {
use crate::render_service::{RenderService, make_job};
for doc in [sample::demo(), sample::stress(20, 100, 48)] {
println!("-- {} items on a frame", evaluate_scene(&doc, 0, 30).items.len());
timings_of(&doc);
}
// The cache: the same frame and settings again are hits, other settings keyed apart.
let doc = sample::demo();
let five = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() };
let view = View { transform: Affine::scale(1.5, 1.5), width: 256, height: 256, background: Some(doc.stage.background) };
let jobs = |o: &OnionSkin| (0..40).map(|i| make_job(1, &doc, 30, View { transform: Affine::translate(-(i as f32) * 10.0, 0.0).mul(&view.transform), ..view }, Some(o))).collect::<Vec<_>>();
let svc = RenderService::new(1 << 30, None);
let first = svc.render_now_batch(jobs(&five));
let t = std::time::Instant::now();
let again = svc.request_batch(jobs(&five));
let hit = t.elapsed().as_secs_f32() * 1000.0;
assert!(again.iter().all(Option::is_some) && first.len() == again.len());
let outlined = svc.request_batch(jobs(&OnionSkin { outlines: true, ..five }));
assert!(outlined.iter().all(Option::is_none), "other settings are other pictures");
println!("cache: {} tiles, second look {hit:.3} ms, all hits", again.len());
}
fn timings_of(doc: &anicraft_doc::Document) {
use crate::render_service::{make_job, render_batch};
let (w, h) = (1920u32, 1080u32);
let z = w as f32 / doc.stage.width as f32;
let tile = 256u32;
let jobs = |onion: Option<&OnionSkin>, frame: u32| -> Vec<crate::render_service::FrameJob> {
let mut v = Vec::new();
for ty in 0..h.div_ceil(tile) {
for tx in 0..w.div_ceil(tile) {
let view = View { transform: Affine::translate(-((tx * tile) as f32), -((ty * tile) as f32)).mul(&Affine::scale(z, z)), width: tile.min(w - tx * tile), height: tile.min(h - ty * tile), background: Some(doc.stage.background) };
v.push(make_job(1, doc, frame, view, onion));
}
}
v
};
let five = OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() };
let cases: [(&str, Option<OnionSkin>); 5] = [
("off", None),
("±5, tinted, fading", Some(five)),
("±5, outlines", Some(OnionSkin { outlines: true, ..five })),
("±5, keyframes only", Some(OnionSkin { keyframes_only: true, ..five })),
("Edit Multiple Frames ±5", Some(OnionSkin { edit_multiple: true, ..five })),
];
for (name, o) in cases {
let mut best = f32::MAX;
for frame in [12u32, 30, 48] {
let t = std::time::Instant::now();
let _ = render_batch(&jobs(o.as_ref(), frame));
best = best.min(t.elapsed().as_secs_f32() * 1000.0);
}
let t = std::time::Instant::now();
let items = crate::render_service::display_list_with_onion(doc, 30, o.as_ref()).items.len();
let eval = t.elapsed().as_secs_f32() * 1000.0;
println!("{name}: 1080p {best:.1} ms (best of frames 12, 30, 48), scene {eval:.2} ms, {items} items on frame 30");
}
}
#[test]
fn extra_frames_sit_on_their_own_layer_over_an_opaque_background() {
// The sample's sky (locked) and hills cover the stage: frames before or after the playhead
// must show over them, under the playhead's artwork on their own layer only.
let doc = sample::demo();
let tl = doc.timeline(0);
let rank = |l: LayerId| tl.layers.iter().position(|x| x.id == l).unwrap();
for o in [OnionSkin { markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }, OnionSkin { edit_multiple: true, markers: Markers::Relative { before: 5, after: 5 }, ..OnionSkin::default() }] {
let dl = compose(&doc, 0, 12, Some(&o), |sc, f| evaluate_scene(&doc, sc, f));
let plain = evaluate_scene(&doc, 0, 12);
assert!(dl.items.len() > plain.items.len());
// Back to front: layer by layer, bottom first.
assert!(dl.items.windows(2).all(|w| rank(w[0].layer) >= rank(w[1].layer)), "items are grouped by layer, bottom up");
// On each layer, its own extra frames come before (under) the playhead's artwork.
let ball = plain.items.last().unwrap().layer;
let on_ball: Vec<&DisplayItem> = dl.items.iter().filter(|i| i.layer == ball).collect();
assert!(on_ball.len() > 1);
assert_eq!(on_ball.last().map(|i| (i.color.alpha, i.color.tint_amount)), Some((1.0, 0.0)), "the playhead's ball is on top");
}
// Rendered: the ball on frame 1 (top left of its path) shows over the sky, in Edit Multiple
// Frames at full strength.
let view = View { transform: Affine::IDENTITY, width: 1280, height: 720, background: Some(Rgba::WHITE) };
let multi = OnionSkin { edit_multiple: true, markers: Markers::Relative { before: 12, after: 0 }, ..OnionSkin::default() };
let with = render(&compose(&doc, 0, 12, Some(&multi), |sc, f| evaluate_scene(&doc, sc, f)), &view).unwrap().0.to_premul_rgba8();
let without = render(&evaluate_scene(&doc, 0, 12), &view).unwrap().0.to_premul_rgba8();
assert_ne!(px(&with, 1280, 200, 260), px(&without, 1280, 200, 260), "the ball on frame 1 is visible");
}
+46 -51
View File
@@ -15,7 +15,8 @@
//! a budget of their own, and only the shell knows what they are.
use crate::history::StateId;
use anicraft_doc::{ColorEffect, DisplayList, Document, Rgba, evaluate_scene, evaluate_scene_camera};
use crate::onion::OnionSkin;
use anicraft_doc::{DisplayList, Document, evaluate_scene, evaluate_scene_camera};
use anicraft_render::{RenderStats, View, render};
use rayon::prelude::*;
use std::collections::{HashMap, HashSet, VecDeque};
@@ -35,7 +36,8 @@ pub struct FrameJob {
pub doc: Document,
pub frame: u32,
pub view: View,
pub onion: bool,
/// Onion skin or Edit Multiple Frames (ADR 0047); `None`: the frame alone.
pub onion: Option<OnionSkin>,
/// Seen through the scene's camera (View › Preview Through Camera, ADR 0027): what the
/// movie shows, rather than the stage as edited.
pub camera: bool,
@@ -94,15 +96,20 @@ pub enum Raster {
/// draws it).
pub type Rasterizer = Arc<dyn Fn(&DisplayList, &View) -> Result<(Raster, RenderStats), String> + Send + Sync>;
/// What onion settings add to a key: nothing when they show nothing.
fn onion_key(onion: Option<&OnionSkin>) -> u64 {
onion.filter(|o| o.shows()).map_or(0, OnionSkin::key)
}
/// Identity of an evaluated scene: the display list depends on these and nothing else.
pub fn scene_key(state: StateId, frame: u32, onion: bool) -> u64 {
pub fn scene_key(state: StateId, frame: u32, onion: Option<&OnionSkin>) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
(state, frame, onion).hash(&mut h);
(state, frame, onion_key(onion)).hash(&mut h);
h.finish()
}
/// Cache key for a scene seen through a view (a frame or a tile).
pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 {
pub fn frame_key(state: StateId, frame: u32, view: &View, onion: Option<&OnionSkin>) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
state.hash(&mut h);
frame.hash(&mut h);
@@ -114,18 +121,19 @@ pub fn frame_key(state: StateId, frame: u32, view: &View, onion: bool) -> u64 {
if let Some(bg) = view.background {
[bg.r, bg.g, bg.b, bg.a].map(f32::to_bits).hash(&mut h);
}
onion.hash(&mut h);
onion_key(onion).hash(&mut h);
h.finish()
}
/// A job whose `scene` is derived from the same inputs as its key.
pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
FrameJob { key: frame_key(state, frame, &view, onion), raster: 0, scene: scene_key(state, frame, onion), doc: doc.clone(), frame, view, onion, camera: false }
pub fn make_job(state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob {
let onion = onion.filter(|o| o.shows()).copied();
FrameJob { key: frame_key(state, frame, &view, onion.as_ref()), raster: 0, scene: scene_key(state, frame, onion.as_ref()), doc: doc.clone(), frame, view, onion, camera: false }
}
/// A job for rasterizer `raster` (from [`RenderService::raster_id`]; 0 is the CPU oracle, and
/// gives [`make_job`]'s key), keyed apart from other rasterizers' pictures.
pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob {
let mut j = make_job(state, doc, frame, view, onion);
if raster != 0 {
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -136,33 +144,16 @@ pub fn make_job_for(raster: u64, state: StateId, doc: &Document, frame: u32, vie
j
}
/// Movie frame `frame`'s display list, with ±2 onion-skin frames (tinted red before, green after)
/// underneath, taken from the same scene only.
pub fn display_list_with_onion(doc: &Document, frame: u32, onion: bool) -> DisplayList {
/// Movie frame `frame`'s display list, with what `onion` adds underneath (onion frames or Edit
/// Multiple Frames' keyframes, ADR 0047), taken from the same scene only.
pub fn display_list_with_onion(doc: &Document, frame: u32, onion: Option<&OnionSkin>) -> DisplayList {
display_list_for(doc, frame, onion, false)
}
/// [`display_list_with_onion`], seen through the scene's camera when `camera` (ADR 0027).
pub fn display_list_for(doc: &Document, frame: u32, onion: bool, camera: bool) -> DisplayList {
let eval = |scene: usize, f: u32| if camera { evaluate_scene_camera(doc, scene, f) } else { evaluate_scene(doc, scene, f) };
let mut dl = DisplayList::default();
pub fn display_list_for(doc: &Document, frame: u32, onion: Option<&OnionSkin>, camera: bool) -> DisplayList {
let (scene, local) = doc.locate(frame);
if onion {
let n = i64::from(doc.timeline(scene).frame_count());
for (off, tint, alpha) in [(-2i64, 0xff5a5a, 0.12f32), (2, 0x4cd07d, 0.12), (-1, 0xff5a5a, 0.25), (1, 0x4cd07d, 0.25)] {
let f = i64::from(local) + off;
if f < 0 || f >= n {
continue;
}
let mut ghost = eval(scene, f as u32);
for item in &mut ghost.items {
item.color = item.color.concat(&ColorEffect { alpha, tint: Rgba::hex(tint), tint_amount: 1.0 });
}
dl.append(ghost);
}
}
dl.append(eval(scene, local));
dl
crate::onion::compose(doc, scene, local, onion, |scene, f| if camera { evaluate_scene_camera(doc, scene, f) } else { evaluate_scene(doc, scene, f) })
}
/// Renders a job against an already evaluated scene, on the CPU oracle.
@@ -201,7 +192,7 @@ fn render_job_by(job: &FrameJob, dl: &DisplayList, raster: Option<&Rasterizer>)
/// Renders a job synchronously, evaluating its scene.
pub fn render_job(job: &FrameJob) -> FrameImage {
render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion, job.camera))
render_job_with(job, &display_list_for(&job.doc, job.frame, job.onion.as_ref(), job.camera))
}
/// Renders a batch: one scene evaluation per distinct `scene`, then all images in parallel.
@@ -213,7 +204,7 @@ pub fn render_batch(jobs: &[FrameJob]) -> Vec<FrameImage> {
fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec<FrameImage> {
let mut scenes: HashMap<u64, Arc<DisplayList>> = HashMap::new();
for j in jobs {
scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion, j.camera)));
scenes.entry(j.scene).or_insert_with(|| Arc::new(display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera)));
}
jobs.par_iter()
.map(|j| {
@@ -221,7 +212,7 @@ fn render_batch_by(jobs: &[FrameJob], slot: &RasterSlot) -> Vec<FrameImage> {
let raster = slot.raster.as_ref().filter(|_| j.raster != 0 && j.raster == slot.id);
match scenes.get(&j.scene) {
Some(dl) => render_job_by(j, dl, raster),
None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion, j.camera), raster),
None => render_job_by(j, &display_list_for(&j.doc, j.frame, j.onion.as_ref(), j.camera), raster),
}
})
.collect()
@@ -391,7 +382,7 @@ impl RenderService {
}
/// A job for the rasterizer in use ([`make_job_for`] with [`RenderService::raster_id`]).
pub fn job(&self, state: StateId, doc: &Document, frame: u32, view: View, onion: bool) -> FrameJob {
pub fn job(&self, state: StateId, doc: &Document, frame: u32, view: View, onion: Option<&OnionSkin>) -> FrameJob {
make_job_for(self.raster_id(), state, doc, frame, view, onion)
}
@@ -594,7 +585,7 @@ mod tests {
fn job(doc: &Document, state: u64, frame: u32) -> FrameJob {
let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) };
make_job(state, doc, frame, view, false)
make_job(state, doc, frame, view, None)
}
#[test]
@@ -629,7 +620,7 @@ mod tests {
let z = 0.37f32; // deliberately odd zoom
let (w, h) = ((1280.0 * z).ceil() as u32, (720.0 * z).ceil() as u32);
let bg = Some(doc.stage.background);
let full = render_job(&make_job(1, &doc, 13, View { transform: Affine::scale(z, z), width: w, height: h, background: bg }, false));
let full = render_job(&make_job(1, &doc, 13, View { transform: Affine::scale(z, z), width: w, height: h, background: bg }, None));
let t = 128u32;
let mut jobs = Vec::new();
for ty in 0..h.div_ceil(t) {
@@ -640,7 +631,7 @@ mod tests {
height: t.min(h - ty * t),
background: bg,
};
jobs.push((tx, ty, make_job(1, &doc, 13, view, false)));
jobs.push((tx, ty, make_job(1, &doc, 13, view, None)));
}
}
let batch: Vec<FrameJob> = jobs.iter().map(|(_, _, j)| j.clone()).collect();
@@ -698,10 +689,10 @@ mod tests {
let doc = sample::demo();
let svc = RenderService::new(64 << 20, None);
let view = View { transform: Affine::scale(0.25, 0.25), width: 320, height: 180, background: Some(doc.stage.background) };
let cpu = svc.job(1, &doc, 9, view, false);
assert_eq!(cpu.key, make_job(1, &doc, 9, view, false).key, "no rasterizer: the oracle's keys");
let cpu = svc.job(1, &doc, 9, view, None);
assert_eq!(cpu.key, make_job(1, &doc, 9, view, None).key, "no rasterizer: the oracle's keys");
// A stand-in GPU that paints everything one colour, and refuses onion-skinned frames.
let plain = display_list_with_onion(&doc, 9, false).items.len();
let plain = display_list_with_onion(&doc, 9, None).items.len();
let flat: Rasterizer = Arc::new(move |dl: &DisplayList, v: &View| {
if dl.items.len() > plain {
return Err("too much".into());
@@ -710,23 +701,23 @@ mod tests {
});
svc.set_rasterizer(Some(flat));
assert!(svc.has_rasterizer());
let gpu = svc.job(1, &doc, 9, view, false);
let gpu = svc.job(1, &doc, 9, view, None);
assert_ne!(gpu.key, cpu.key, "pictures are keyed by who drew them");
let img = svc.render_now(gpu.clone());
assert!(img.gpu && img.fallback.is_none() && img.rgba_premul[..4] == [10, 20, 30, 255]);
// What it refuses, the oracle draws, saying why.
let onion = svc.job(1, &doc, 9, view, true);
let onion = svc.job(1, &doc, 9, view, Some(&OnionSkin::default()));
let img = svc.render_now(onion.clone());
assert!(!img.gpu && img.fallback.as_deref() == Some("too much"));
assert_eq!(img.rgba_premul, render_job(&make_job(1, &doc, 9, view, true)).rgba_premul);
assert_eq!(img.rgba_premul, render_job(&make_job(1, &doc, 9, view, Some(&OnionSkin::default()))).rgba_premul);
// Through the worker too; and a job made for an older rasterizer is drawn by the oracle.
let ahead = svc.job(1, &doc, 10, view, false);
let ahead = svc.job(1, &doc, 10, view, None);
svc.prefetch(vec![ahead.clone()]);
assert!(svc.wait_for(ahead.key, 10_000).is_some_and(|i| i.gpu));
svc.set_rasterizer(None);
let stale = FrameJob { key: 77, ..ahead };
assert!(!render_batch_by(&[stale], &svc.slot())[0].gpu);
assert_eq!(svc.job(1, &doc, 9, view, false).key, cpu.key, "back to the oracle's keys");
assert_eq!(svc.job(1, &doc, 9, view, None).key, cpu.key, "back to the oracle's keys");
}
#[test]
@@ -773,11 +764,11 @@ mod tests {
Ok((Raster::Native { image: Arc::new(7u32), width: v.width + u32::from(bad), height: v.height }, RenderStats::default()))
});
svc.set_rasterizer(Some(native));
let img = svc.render_now(svc.job(1, &doc, 3, view, false));
let img = svc.render_now(svc.job(1, &doc, 3, view, None));
assert!(img.gpu && img.rgba_premul.is_empty());
assert_eq!(img.native.as_ref().and_then(|n| n.downcast_ref::<u32>()), Some(&7));
wrong.store(true, std::sync::atomic::Ordering::Relaxed);
let img = svc.render_now(svc.job(1, &doc, 4, view, false));
let img = svc.render_now(svc.job(1, &doc, 4, view, None));
assert!(!img.gpu && img.native.is_none() && img.fallback.as_deref() == Some("the GPU returned a wrong-sized image"));
assert_eq!(img.rgba_premul.len(), 320 * 180 * 4, "the oracle drew it instead");
}
@@ -794,8 +785,12 @@ mod tests {
#[test]
fn onion_adds_neighbour_frames() {
let doc = sample::demo();
let plain = display_list_with_onion(&doc, 10, false).items.len();
let onion = display_list_with_onion(&doc, 10, true).items.len();
assert_eq!(onion, plain * 5);
let plain = display_list_with_onion(&doc, 10, None).items.len();
let onion = display_list_with_onion(&doc, 10, Some(&OnionSkin::default())).items.len();
// ±2 frames of every unlocked layer (Animate doesn't onion-skin locked ones).
let tl = doc.timeline(0);
let unlocked = display_list_with_onion(&doc, 10, None).items.iter().filter(|i| tl.layer(i.layer).is_some_and(|l| !l.locked)).count();
assert!(unlocked < plain, "the sample has a locked layer");
assert_eq!(onion, plain + 4 * unlocked);
}
}
+6
View File
@@ -617,6 +617,12 @@ fn panic_hunt_every_command() {
json!({"from": 10, "to": 12, "head": [0, 0], "tail": [1e30, 0], "name": "x".repeat(300)}),
json!({"from": 12, "to": 10, "head": [5], "tail": "x", "bone": u64::MAX}),
json!({"from": 11, "to": 13, "head": [-1e6, 1e6], "layer": 101}),
// Edit Multiple Frames (ADR 0047): ranges past the end or reversed, items that aren't
// there or aren't triples, moves at the limits.
json!({"first": 0, "last": 99_999, "dx": 1e7, "dy": -1e7, "items": [[0, 0, 1], "x", [u64::MAX, u64::MAX, u64::MAX]]}),
json!({"first": u64::MAX, "last": 0, "dx": 5, "dy": 5, "items": []}),
json!({"first": 40, "last": 0, "dx": 3, "dy": -2}),
json!({"first": 0, "last": 100_001, "dx": f64::NAN, "dy": 0, "items": [[1, 2]]}),
];
// File commands are exercised separately (they touch the disk).
let skip = |id: &str| id.starts_with("file.");
+1 -1
View File
@@ -47,7 +47,7 @@ fn the_stage_renders_without_a_thread() {
let svc = RenderService::new(64 << 20, None);
let view = anicraft_engine::render::View::stage(&s.doc, 0.5);
// No worker thread can start, so a request renders right away.
let img = svc.request(svc.job(s.state, &s.doc, 3, view, false)).expect("rendered on this thread");
let img = svc.request(svc.job(s.state, &s.doc, 3, view, None)).expect("rendered on this thread");
assert!(img.error.is_none() && img.width > 0 && img.rgba_premul.iter().any(|&b| b != 0));
}
+1 -1
View File
@@ -15,7 +15,7 @@ would freeze for that long on every edit.
placed by the stage area it covers so pan and zoom stay smooth, until the new one arrives.
Policy: one *urgent* slot (latest wins, so a drag never builds a backlog) plus a *prefetch*
queue, replaced wholesale. During playback the stage prefetches the next 12 frames.
2. **Frame cache keyed by content.** `frame_key(state id, frame, view, onion)`, LRU-bounded by
2. **Frame cache keyed by content.** `frame_key(state id, frame, view, onion)` (the onion settings' key since ADR 0047), LRU-bounded by
bytes (default 768 MB). Undo/redo and looping playback are cache hits.
3. **Two-phase, band-parallel rasterization** (`render::render`):
* Phase 1, parallel over items: cull by control-point bounds, flatten, stroke and build the
+1 -1
View File
@@ -22,7 +22,7 @@ renderer that draws only the viewport shows this.
* The stage is cut into **512 × 512 device-pixel tiles** on a grid anchored at stage (0, 0) for
the current zoom. Each tile is a `FrameJob` keyed by (state, frame, tile transform, size,
onion).
onion settings; ADR 0047).
* **Batching.** Each UI frame asks for all missing visible tiles in one `request_batch`.
The worker takes up to 32 jobs, **evaluates the scene once per (state, frame, onion)** and
renders the tiles in parallel. Newer batches replace pending ones (latest wins). Edits made
@@ -0,0 +1,117 @@
# ADR 0047: Onion skin controls and Edit Multiple Frames
* Status: accepted (2026-11-10)
* Relates to: ADR 0002 (render pipeline, frame cache), ADR 0007 (tiled stage), ADR 0019/0032
(GPU stage), ADR 0044 (selection across layers), ADR 0001 (undo), ADR 0040 (interface
languages)
## Context
Onion skin was a toggle that drew the two frames before the playhead in red and the two after
in green, under the whole picture, with no ADR. `docs/requirements.md` asks for a before/after
range, tint and outlines (P1). Artists coming from Animate expect its controls: onion markers
on the frame ruler that they drag, Always Show Markers, Anchor Markers, the Onion 2 / Onion 5 /
Onion All presets, outlines, and Edit Multiple Frames to move a whole animation at once.
Behaviour was learned from Adobe's public help pages on onion skinning and Edit Multiple Frames
and from watching the program; nothing was copied.
## Decision
1. **Settings are view state, composition is a pure function.** `anicraft_engine::onion::
OnionSkin` holds: on/off, Edit Multiple Frames on/off, the markers, tint, past and future
colours, fade by distance, outlines, keyframes only. The shell owns one (`App::onion`), and
passes it with each render job (`FrameJob::onion`, was a `bool`). `onion::compose(doc, scene,
frame, skin, eval)` builds the display list; the document never changes for it (golden rule
3). Render keys hash the settings (`OnionSkin::key`; nothing when it shows nothing), so the
frame cache keeps every look apart and a second look is a hit: going back to a frame or
undoing to a state already seen draws nothing new.
2. **Markers.** `Markers::Relative { before, after }` follow the playhead;
`Markers::Anchored { first, last }` stay on their frames. `range(playhead, frames)` always
lies inside the timeline with `first <= last` (a playhead past the end counts as the last
frame). Dragging a marker never crosses the playhead (relative) or the other marker
(anchored). Anchoring keeps the frames shown; un-anchoring keeps their distances from the
playhead, and a marker the playhead has passed lands on it. Onion 2 and Onion 5 are relative
±2 and ±5; **Onion All** is anchored from frame 1 to `MAX_FRAME`, so it grows with the
timeline.
3. **Which frames.** Onion skin draws every frame within the markers except the playhead's,
nearest on top, the past one first at each distance. **Locked layers are not onion-skinned**,
as in Animate (it is how artists keep a background out of the way), nor hidden ones.
**Keyframes only** keeps, per layer, the frames where that layer has a keyframe; the keyframe
under the playhead is left out unless it tweens (it would only repeat the playhead's frame).
At most `MAX_EXTRA_FRAMES` (120) extra frames are evaluated, the nearest ones.
4. **Look.** An onion frame's colour effect is `alpha` × the past or future colour at
`TINT_AMOUNT` (0.8: fills and lines inside it stay apart). With **fade**, alpha falls
linearly from `NEAR_ALPHA` (0.5) next to the playhead to `FAR_ALPHA` (0.12) at the marker;
without, every frame has 0.5. **Tint off** keeps the artwork's own colours (only faded).
**Outlines** draw onion frames as hairlines in their colour and alpha, through the existing
outline-mode path of the renderers (`DisplayItem::outline`), so the CPU oracle and the GPU
stage draw them alike. The default colours are theme tokens (`onion_past` blue and
`onion_future` green, as Animate users know them, brighter in high contrast); the onion menu
changes them, and Reset goes back to the theme's.
5. **Layering.** Extra frames are **interleaved layer by layer**: each layer's onion frames sit
under that layer's artwork at the playhead and over the layers below. (Before, they went
under the whole picture, so an opaque background layer hid them.) Each evaluated frame is
already back to front; one k-way merge by layer moves every item once. This is safe because
a group's run lies within one layer and both renderers take mask artwork apart from what
they draw. Extra frames are evaluated in parallel.
6. **Edit Multiple Frames** shows, on every visible, unlocked layer that holds artwork (not
folders, the camera or armatures), every keyframe whose span reaches into the markers, at
full strength, as it looks on its first frame, with the playhead's frame on top on each
layer; onion frames are not drawn meanwhile. Its selection is a list of `FrameItem
{ layer, frame (the keyframe's first frame), element }` (element ids are shared between
keyframes, so the frame says which copy), kept in the shell like the frame selection, since
commands get explicit items (`Session::selection` stays the playhead's, ADR 0044).
* `frames.artwork {first, last}` lists what it shows, with stage bounds;
`frames.edit_multiple {first, last, dx, dy, items?}` moves the items given, or all of
them, on each keyframe: one undo step (a drag is one gesture). A motion tween's path and
X/Y keys move with its object (`MotionTween::translate`). Items outside the markers or on
a locked or hidden layer are refused with nothing changed.
* On the stage the Selection and Free Transform tools click, Shift-click, marquee (what lies
wholly inside) and drag across those keyframes; Select All and Deselect All, and the arrow
keys, act on them. The playhead's keyframe is boxed in the selection colour, the others a
step lighter, and a badge on the stage names the frames.
* A new command namespace, `frames`; plug-ins may call it (document edits).
*Rejected:* a `range` param on `element.translate`. The selection it moves is the
playhead's (pairs of layer and element), and the same id is on several keyframes; it would
need a second kind of selection inside the engine for one command.
7. **In the editor.** The timeline has Onion Skin (Alt+Shift+O), Edit Multiple Frames and an
onion menu (also on a right-click on the ruler and in View › Onion Skin Options): Onion
Skin, Edit Multiple Frames, Outlines, Keyframes Only; Always Show Markers, Anchor Markers,
Onion 2 / 5 / All; Tint, Fade by Distance, Before and After colours, Reset. The menu stays
open while options change. The markers are brackets on the frame ruler in the past and future
colours, with the frames between them tinted, pinned when anchored; dragging one shows the
change live. Options, preset ranges and colours are saved in the preferences; on/off and
anchored markers last for the session. Screen readers hear the markers as sliders ("Onion
start marker", frame) and the menu by name; all text goes through `tr!`.
## Consequences
* Onion skin meets the P1 requirement (range, tint, outlines) and adds Animate's markers,
keyframes only and Edit Multiple Frames.
* Onion frames now show over opaque lower layers (a visible change: the sample's sky no longer
hides them).
* Measured at 1080p through the tiled path (release, 32 threads; `onion_timings`):
| Scene | Off | ±5 tinted, fading | ±5 outlines | Edit Multiple Frames ±5 |
|---|---|---|---|---|
| Sample (7 items a frame) | 5.9–6.1 ms | 6.0–6.5 ms | 6.5–7.0 ms | 6.0–6.1 ms |
| Stress, 2,000 items a frame (22,000 with ±5) | 7.2–7.9 ms | 16.2–17.2 ms | 34–39 ms | 6.6–7.3 ms |
Composing the ±5 stress scene takes 3.0–3.3 ms (was 8.3 ms before the merge and parallel
evaluation); a second look at the same 40 tiles is 0.02 ms, all cache hits. Hairline outlines
cost more to rasterize than fills, so outline mode on very heavy scenes is the slow case.
* Not in this slice:
* per-layer onion skin toggles, and onion skin inside a symbol being edited in place;
* Edit Multiple Frames deleting, transforming (scale, rotate), copying or recolouring across
keyframes; it moves only. Raw (merge) shapes moved there are not merged again with what
they land on;
* a marker drag that also scrolls the timeline;
* onion skin in Test Movie and exports (never: it is an editing aid).
+19
View File
@@ -52,6 +52,25 @@ Timing each step of a frame showed the time was outside the drawing itself:
Output is unchanged: the sample's frames and a bitmap document render byte-identical before
and after.
**Onion skin ±5 at 1080p (2026-11-10, ADR 0047).** Through the stage's tiled path (40 tiles
of 256 px, one scene evaluation per frame, tiles in parallel), release build, 32 threads, best
of frames 12, 30 and 48:
`cargo test --release -p anicraft-engine onion_timings -- --ignored --nocapture`.
| Scene | Off | ±5 tinted, fading | ±5 outlines | Keyframes only ±5 | Edit Multiple Frames ±5 |
|---|---|---|---|---|---|
| Sample (7 items a frame; 67 with ±5) | 5.9–6.1 ms | 6.0–6.5 ms | 6.5–7.0 ms | 5.8–6.2 ms | 6.0–6.1 ms |
| Stress 20 × 100 (2,000 items a frame; 22,000 with ±5) | 7.2–7.9 ms | 16.2–17.2 ms | 34–39 ms | 7.5–7.6 ms | 6.6–7.3 ms |
Composing the stress scene with ±5 (ten extra evaluations, then each layer's onion frames
merged under its own artwork) took 8.3 ms at first: 3.9 ms of it was putting the items in layer
order (an append, then a reorder). One k-way merge by layer, each item moved once, brought that
to 0.85 ms, and evaluating the extra frames in parallel brought the whole to 3.0–3.3 ms. Output
is unchanged (the onion tests compare items and pixels). The settings are part of every tile's
key, so the frame cache keeps working: looking at the same frame again is 40 hits in 0.02 ms,
and other settings are other pictures. Hairline outlines cost more to rasterize than fills, so
outline mode on very heavy scenes is the slow case.
**Crash-recovery autosave (2026-11-09, ADR 0015).** `bench` now runs one autosave the way the
app does: an `Autosaver` in a scratch recovery folder. The editing thread only hands over an
`Arc` snapshot of the document; the worker serializes and writes atomically (temp file,
+2 -2
View File
@@ -10,7 +10,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|---|---|
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **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-clicLine truncated
| 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, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **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, ovLine truncated
| 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. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **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 Line truncated
| 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 `<settings>/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. |
@@ -31,7 +31,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
| M | Theme | Exit criteria |
|---|---|---|
| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. |
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (basic); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. |
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. |
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038; spatial keys, 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); GPU binning deferred (not the bottleneck as tiles); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: shared filtered layers across tiles, an image atlas, GPU exports. |
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); not yet: `.fla` variants of the corpus, sound and video items; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. |
+1 -1
View File
@@ -352,7 +352,7 @@ mod tests {
for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
}
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript"] {
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple"] {
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
}
// The layer depth row shows on artwork layers once the scene has a camera.
+48 -4
View File
@@ -190,6 +190,10 @@ pub enum Drag {
/// pointer to the point. The points that move are `App::raw_points`.
RawPoint { at: egui::Pos2, off: egui::Vec2 },
Marquee { start: egui::Pos2, cur: egui::Pos2 },
/// Edit Multiple Frames (ADR 0047): moving the selection on every keyframe it is on, the
/// pointer at `last` last frame; or a marquee over them.
MultiMove { last: egui::Pos2 },
MultiMarquee { start: egui::Pos2, cur: egui::Pos2 },
Shape { start: egui::Pos2, cur: egui::Pos2 },
/// Subselection: dragging the selected points (stage position of the last frame).
Points { last: egui::Pos2 },
@@ -290,7 +294,9 @@ pub struct App {
pub playing: bool,
pub looping: bool,
play_acc: f64,
pub onion: bool,
/// Onion skin and Edit Multiple Frames (ADR 0047): view state, passed with each render.
pub onion: anicraft_engine::onion::OnionSkin,
pub onion_ui: crate::onion::OnionUi,
/// View › Preview Through Camera: the stage shows what the movie shows (ADR 0027).
pub camera_preview: bool,
/// The tool in hand last frame (picking the Camera tool adds a camera).
@@ -477,7 +483,8 @@ impl App {
playing: false,
looping: true,
play_acc: 0.0,
onion: false,
onion: crate::onion::from_prefs(&prefs.onion),
onion_ui: crate::onion::OnionUi::default(),
camera_preview: false,
last_tool: Tool::Select,
status: None,
@@ -635,6 +642,7 @@ impl App {
ctx.request_repaint();
ctx.set_zoom_factor(self.prefs.ui_scale);
theme::apply_palette(ctx, self.prefs.theme);
crate::onion::refresh_colors(self);
self.keymap = keymap::Keymap::new(&self.prefs.shortcuts);
self.shortcuts = self.keymap.table();
let wants_system = [&self.prefs.ui_font, &self.prefs.data_font].iter().any(|f| matches!(f, prefs::FontChoice::System(_)));
@@ -776,6 +784,24 @@ impl App {
self.scan_system_fonts();
}
Some("confirm") => self.request("layer.delete", json!({})),
Some(which @ ("onion" | "onionmenu")) => {
// Onion skin ±5 on a frame with frames before and after it, the markers on the
// ruler; with its menu open, in outlines (ADR 0047).
self.onion.ghosts = true;
self.onion.preset(5);
self.run("timeline.goto", json!({"frame": 12}));
if which == "onionmenu" {
self.onion.outlines = true;
self.onion_ui.open_menu = true;
}
}
Some("editmultiple") => {
// Edit Multiple Frames over the sample's walk, everything selected (ADR 0047).
self.onion.preset(5);
crate::onion::toggle_edit_multiple(self);
self.run("timeline.goto", json!({"frame": 12}));
crate::onion::select_all(self);
}
Some("selection") => {
// A selection across layers (ADR 0044): Select All takes every unlocked layer's
// artwork; the timeline marks the layers, Properties says how many.
@@ -1415,6 +1441,22 @@ impl App {
self.status_err(crate::i18n::t(why));
return;
}
// Edit Multiple Frames (ADR 0047) selects on every keyframe between the markers.
if crate::onion::editing(self) {
match id {
"edit.select_all" => return crate::onion::select_all(self),
"edit.deselect" => {
self.onion_ui.sel.clear();
return;
}
// This slice moves artwork across keyframes; other edits stay on one frame.
"edit.delete" | "edit.cut" | "edit.copy" | "edit.duplicate" if !self.onion_ui.sel.is_empty() => {
self.status_err(tr!("Edit Multiple Frames moves artwork on several keyframes; to delete, copy or duplicate it, turn Edit Multiple Frames off and work frame by frame."));
return;
}
_ => {}
}
}
if id == "timeline.paste_frames"
&& let Some(p) = timeline::paste_params(self)
{
@@ -1731,7 +1773,7 @@ impl App {
match id {
// View-state keys (Animate's), handled here rather than in the engine.
"view.fit" => self.view.fit = true,
"view.onion" => self.onion = !self.onion,
"view.onion" => crate::onion::toggle_ghosts(self),
"view.align_to_stage" => {
self.align_to_stage = !self.align_to_stage;
self.status_ok(if self.align_to_stage { tr!("Align: to stage") } else { tr!("Align: to the selection") });
@@ -1758,7 +1800,9 @@ impl App {
if play {
self.toggle_play();
}
if nudge != egui::Vec2::ZERO && !self.s.selection.is_empty() {
if nudge != egui::Vec2::ZERO && crate::onion::editing(self) {
crate::onion::nudge(self, anicraft_engine::geom::Vec2::new(nudge.x, nudge.y));
} else if nudge != egui::Vec2::ZERO && !self.s.selection.is_empty() {
// One undo step: the move, and raw shapes merging where they land (ADR 0031).
let own = !self.s.in_gesture();
if own {
+1 -1
View File
@@ -213,7 +213,7 @@ fn entries() -> Vec<Entry> {
v.extend(Tool::ALL.iter().map(|t| Entry::Tool(*t)));
// English keys, translated where they are drawn (`Entry::title`).
v.push(Entry::View(tr_noop!("Play / Stop"), "Enter", App::toggle_play));
v.push(Entry::View(tr_noop!("Onion Skin"), "", |a| a.onion = !a.onion));
v.push(Entry::View(tr_noop!("Onion Skin"), "", crate::onion::toggle_ghosts));
v.push(Entry::View(tr_noop!("Preview Through Camera"), "", App::toggle_camera_preview));
v.push(Entry::View(tr_noop!("Fit Stage in Window"), "Ctrl+0", |a| a.view.fit = true));
v.push(Entry::View(tr_noop!("Keyboard Shortcuts"), "F1", |a| a.show_shortcuts = true));
+1 -1
View File
@@ -578,7 +578,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() {
a.run("symbol.set_kind", serde_json::json!({"symbol": symbol, "kind": "movie_clip"}));
a.run("element.set_filters", serde_json::json!({"filters": [{"type": "drop_shadow"}, {"type": "gradient_glow"}]}));
}));
for panel in ["sound", "camera", "motion", "actions", "script", "prefs", "envelope"] {
for panel in ["sound", "camera", "motion", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple"] {
found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel))));
}
for tool in [crate::app::Tool::Brush, crate::app::Tool::Eraser, crate::app::Tool::PaintBucket, crate::app::Tool::Pencil, crate::app::Tool::Width] {
+7 -1
View File
@@ -67,11 +67,13 @@ pub enum Icon {
Camera,
Magnet,
Bone,
EditMultiple,
}
impl Icon {
#[cfg(test)]
pub const ALL: [Icon; 53] = [
pub const ALL: [Icon; 54] = [
Icon::EditMultiple,
Icon::Bone,
Icon::Magnet,
Icon::SoundOff,
@@ -200,6 +202,9 @@ impl Icon {
Icon::Magnet => ("anicraft-magnet", false),
// A bone: a wedge from its joint to its end (AniCraft original, on Lucide's grid).
Icon::Bone => ("anicraft-bone", false),
// Frames stacked one behind the other, all edited at once (AniCraft original, on
// Lucide's grid): Edit Multiple Frames.
Icon::EditMultiple => ("anicraft-edit-multiple", false),
Icon::FolderOpen => ("folder-open", false),
}
}
@@ -255,6 +260,7 @@ static FILES: &[(&str, &str)] = &[
("anicraft-masked", include_str!("../assets/icons/anicraft-masked.svg")),
("anicraft-camera", include_str!("../assets/icons/anicraft-camera.svg")),
("anicraft-bone", include_str!("../assets/icons/anicraft-bone.svg")),
("anicraft-edit-multiple", include_str!("../assets/icons/anicraft-edit-multiple.svg")),
("folder", include_str!("../assets/icons/folder.svg")),
("folder-open", include_str!("../assets/icons/folder-open.svg")),
];
+1
View File
@@ -38,6 +38,7 @@ mod menus;
mod motion_editor;
mod panels;
mod motion_path;
mod onion;
mod pathtools;
mod platform;
mod plugins_ui;
+8 -4
View File
@@ -198,9 +198,13 @@ pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &
app.zoom_about(canvas, center, 1.0);
}
ui.separator();
if ui_item(ui, tr!("Onion Skin"), "", Some(app.onion)) {
app.onion = !app.onion;
if ui_item(ui, tr!("Onion Skin"), app.keymap.primary("view.onion").unwrap_or(""), Some(app.onion.ghosts)) {
crate::onion::toggle_ghosts(app);
}
if ui_item(ui, tr!("Edit Multiple Frames"), "", Some(app.onion.edit_multiple)) {
crate::onion::toggle_edit_multiple(app);
}
ui.menu_button(tr!("Onion Skin Options"), |ui| crate::onion::menu(app, ui));
if ui_item(ui, tr!("Preview Through Camera"), "", Some(app.camera_preview)) {
app.toggle_camera_preview();
}
@@ -251,8 +255,8 @@ pub(crate) fn menu_contents(app: &mut App, ui: &mut egui::Ui, top: &str, cmds: &
app.show_actions = !app.show_actions;
}
ui.separator();
if ui_item(ui, tr!("Onion Skin"), "", Some(app.onion)) {
app.onion = !app.onion;
if ui_item(ui, tr!("Onion Skin"), "", Some(app.onion.ghosts)) {
crate::onion::toggle_ghosts(app);
}
ui.label(text(Type::Caption, tr!("Panels are docked: Tools, Stage, Timeline, Properties, Library")));
}
+547
View File
@@ -0,0 +1,547 @@
//! Onion skin and Edit Multiple Frames in the editor (ADR 0047): the timeline's buttons and
//! onion menu, the markers on the frame ruler, and Edit Multiple Frames on the stage.
//!
//! The settings are view state ([`OnionSkin`], in `App::onion`); the options that carry over
//! between sessions are also in the preferences. Only Edit Multiple Frames' moves change the
//! document, through `frames.edit_multiple`.
use crate::a11y::Named;
use crate::app::{App, Drag};
use crate::prefs::{ONION_REACH_MAX, OnionPrefs};
use crate::theme::{T, Type, color, font, text, to_color32, to_rgba};
use anicraft_engine::doc::Rgba;
use anicraft_engine::geom::{Rect as GRect, Vec2};
use anicraft_engine::onion::{FrameItem, Markers, OnionSkin, PRESETS};
use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::json;
use std::sync::Arc;
/// The onion menu's popup (opened by its button, a right-click on the ruler, or `--open onion`).
pub const MENU_ID: &str = "onion_menu";
/// What the shown items depend on: document state, scene, playhead and the markers' frames.
type ItemsKey = (u64, usize, u32, u32, u32);
/// Every element Edit Multiple Frames shows, with its stage bounds.
pub type Shown = Arc<Vec<(FrameItem, GRect)>>;
/// The editor's onion state beyond [`OnionSkin`].
#[derive(Default)]
pub struct OnionUi {
/// The marker being dragged on the ruler: the start (`true`) or the end.
pub drag: Option<bool>,
/// Edit Multiple Frames' selection: elements on keyframes within the markers.
pub sel: Vec<FrameItem>,
/// Open the onion menu on the next frame.
pub open_menu: bool,
/// What Edit Multiple Frames shows, for (state, scene, playhead, first, last).
cache: Option<(ItemsKey, Shown)>,
}
fn rgb(c: [u8; 3]) -> Rgba {
Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0)
}
/// The settings a session starts with: off, with the saved options and colours.
pub fn from_prefs(p: &OnionPrefs) -> OnionSkin {
let mut o = OnionSkin { ghosts: false, edit_multiple: false, markers: Markers::Relative { before: p.before, after: p.after }, tint: p.tint, fade: p.fade, outlines: p.outlines, keyframes_only: p.keyframes_only, ..OnionSkin::default() };
if p.all {
o.all();
}
o.past = p.past.map_or_else(|| to_rgba(T.onion_past), rgb);
o.future = p.future.map_or_else(|| to_rgba(T.onion_future), rgb);
o
}
/// The theme's colours where the user didn't pick their own (after a palette change).
pub fn refresh_colors(app: &mut App) {
app.onion.past = app.prefs.onion.past.map_or_else(|| to_rgba(T.onion_past), rgb);
app.onion.future = app.prefs.onion.future.map_or_else(|| to_rgba(T.onion_future), rgb);
}
/// Changes the settings and saves the options that carry over.
fn change(app: &mut App, ctx: &egui::Context, f: impl FnOnce(&mut OnionSkin, &mut OnionPrefs)) {
let mut p = app.prefs.clone();
f(&mut app.onion, &mut p.onion);
let o = app.onion;
match o.markers {
Markers::Relative { before, after } => {
p.onion.before = before.min(ONION_REACH_MAX);
p.onion.after = after.min(ONION_REACH_MAX);
p.onion.all = false;
}
Markers::Anchored { .. } => p.onion.all = o.is_all(),
}
(p.onion.tint, p.onion.fade, p.onion.outlines, p.onion.keyframes_only) = (o.tint, o.fade, o.outlines, o.keyframes_only);
app.set_prefs(ctx, p);
}
/// The frames within the markers (0-based, inclusive).
pub fn range(app: &App) -> (u32, u32) {
app.onion.range(app.s.frame, app.s.frame_count())
}
/// What the stage composes now: `None` while playing or when nothing is on.
pub fn stage_skin(app: &App) -> Option<&OnionSkin> {
(!app.playing && app.onion.shows()).then_some(&app.onion)
}
/// Onion skin on or off (the timeline button, View › Onion Skin, Alt+Shift+O).
pub fn toggle_ghosts(app: &mut App) {
app.onion.ghosts = !app.onion.ghosts;
}
/// Edit Multiple Frames on or off. The selection starts empty either way: what was selected on
/// one frame is not what is selected on several.
pub fn toggle_edit_multiple(app: &mut App) {
app.onion.edit_multiple = !app.onion.edit_multiple;
app.onion_ui.sel.clear();
if app.onion.edit_multiple {
app.s.selection.clear();
app.status_ok(tr!("Edit Multiple Frames: the keyframes between the onion markers show at full strength. Select and drag artwork to move it on all of them; drag the markers on the frame ruler to choose the frames."));
}
}
/// Edit Multiple Frames is taking the Selection tool's input.
pub fn editing(app: &App) -> bool {
app.onion.edit_multiple && !app.playing && !crate::camera_tool::previewing(app)
}
// ----- the menu ------------------------------------------------------------------------------
/// The onion menu: on/off, options, markers, colours. Stays open while options change.
pub fn menu(app: &mut App, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
let o = app.onion;
let key = app.keymap.primary("view.onion").unwrap_or("").to_string();
let mut ghosts = o.ghosts;
if ui.checkbox(&mut ghosts, a11y_key(tr!("Onion Skin"), &key)).changed() {
toggle_ghosts(app);
}
let mut multi = o.edit_multiple;
if ui.checkbox(&mut multi, tr!("Edit Multiple Frames")).on_hover_text(tr!("Show the keyframes between the markers at full strength, and select and move their artwork together")).changed() {
toggle_edit_multiple(app);
}
let mut outlines = o.outlines;
if ui.checkbox(&mut outlines, tr!("Outlines")).on_hover_text(tr!("Draw onion frames as outlines only")).changed() {
change(app, &ctx, |o, _| o.outlines = outlines);
}
let mut keys = o.keyframes_only;
if ui.checkbox(&mut keys, tr!("Keyframes Only")).on_hover_text(tr!("Onion-skin only the frames where a keyframe starts")).changed() {
change(app, &ctx, |o, _| o.keyframes_only = keys);
}
ui.separator();
ui.label(text(Type::Caption, tr!("Markers")));
let mut always = app.prefs.onion.always_markers;
if ui.checkbox(&mut always, tr!("Always Show Markers")).on_hover_text(tr!("Show the markers on the frame ruler even when onion skin is off")).changed() {
change(app, &ctx, |_, p| p.always_markers = always);
}
let mut anchored = o.anchored();
if ui.checkbox(&mut anchored, tr!("Anchor Markers")).on_hover_text(tr!("Keep the markers on their frames instead of moving them with the playhead")).changed() {
let (f, n) = (app.s.frame, app.s.frame_count());
change(app, &ctx, |o, _| o.set_anchored(anchored, f, n));
}
ui.horizontal(|ui| {
for n in PRESETS {
let on = o.markers == Markers::Relative { before: n, after: n };
if ui.selectable_label(on, tr!("Onion {n}", n = n)).on_hover_text(trn!("{n} frame before and after the playhead", "{n} frames before and after the playhead", n as usize)).clicked() {
change(app, &ctx, |o, _| o.preset(n));
}
}
if ui.selectable_label(o.is_all(), tr!("Onion All")).on_hover_text(tr!("Every frame of the timeline")).clicked() {
change(app, &ctx, |o, _| o.all());
}
});
ui.separator();
ui.label(text(Type::Caption, tr!("Colour")));
let mut tint = o.tint;
if ui.checkbox(&mut tint, tr!("Tint")).on_hover_text(tr!("Tint frames before the playhead and after it in their colours; off, they keep their own colours")).changed() {
change(app, &ctx, |o, _| o.tint = tint);
}
let mut fade = o.fade;
if ui.checkbox(&mut fade, tr!("Fade by Distance")).on_hover_text(tr!("Frames farther from the playhead are fainter")).changed() {
change(app, &ctx, |o, _| o.fade = fade);
}
ui.horizontal(|ui| {
for past in [true, false] {
let name = if past { tr!("Before colour") } else { tr!("After colour") };
ui.label(text(Type::Body, if past { tr!("Before") } else { tr!("After") }));
let mut c = to_color32(if past { o.past } else { o.future });
let r = ui.color_edit_button_srgba(&mut c).named(name).on_hover_text(if past { tr!("Colour of the frames before the playhead") } else { tr!("Colour of the frames after the playhead") });
if r.changed() {
let [cr, cg, cb, _] = c.to_srgba_unmultiplied();
change(app, &ctx, |o, p| {
let pick = [cr, cg, cb];
if past {
o.past = rgb(pick);
p.past = Some(pick);
} else {
o.future = rgb(pick);
p.future = Some(pick);
}
});
}
}
let custom = app.prefs.onion.past.is_some() || app.prefs.onion.future.is_some();
if ui.add_enabled(custom, egui::Button::new(tr!("Reset"))).on_hover_text(tr!("Back to the theme's colours")).clicked() {
change(app, &ctx, |o, p| {
p.past = None;
p.future = None;
o.past = to_rgba(T.onion_past);
o.future = to_rgba(T.onion_future);
});
}
});
}
/// A checkbox label with its shortcut, as menus show it.
fn a11y_key(name: &str, key: &str) -> String {
crate::a11y::with_key(name, Some(key))
}
/// The timeline's onion buttons: Onion Skin, Edit Multiple Frames and the onion menu.
pub fn buttons(app: &mut App, ui: &mut egui::Ui) {
let key = app.keymap.primary("view.onion").map(str::to_string);
if crate::timeline::icon_button(ui, &crate::a11y::with_key(tr!("Onion skin"), key.as_deref()), Some(app.onion.ghosts), crate::icons::Icon::Onion).clicked() {
toggle_ghosts(app);
}
if crate::timeline::icon_button(ui, tr!("Edit Multiple Frames"), Some(app.onion.edit_multiple), crate::icons::Icon::EditMultiple).clicked() {
toggle_edit_multiple(app);
}
let (rect, resp) = ui.allocate_exact_size(vec2(16.0, crate::theme::TARGET), Sense::click());
let hot = resp.hovered() || egui::Popup::is_id_open(ui.ctx(), egui::Id::new(MENU_ID));
ui.painter().rect_filled(rect, T.rc(), if hot { T.header } else { Color32::TRANSPARENT });
crate::icons::paint(ui.painter(), Rect::from_center_size(rect.center(), vec2(12.0, 12.0)), crate::icons::Icon::ChevronDown, if hot { T.icon_hot } else { T.icon });
crate::a11y::control(ui, &resp, egui::WidgetType::Button, tr!("Onion skin options"), None);
let resp = resp.on_hover_text(tr!("Onion skin options: markers, outlines, colours"));
if std::mem::take(&mut app.onion_ui.open_menu) {
egui::Popup::open_id(ui.ctx(), egui::Id::new(MENU_ID));
}
let shown = egui::Popup::menu(&resp).id(egui::Id::new(MENU_ID)).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
ui.set_min_width(230.0);
menu(app, ui);
});
// egui leaves the popup's own surface without a role or name.
if let Some(r) = shown {
ui.ctx().accesskit_node_builder(r.response.id, |node| {
node.set_role(egui::accesskit::Role::Menu);
node.set_label(tr!("Onion skin options"));
});
}
}
// ----- the markers on the frame ruler --------------------------------------------------------
/// Draws the onion markers on the frame ruler and lets them be dragged. `x_of` is a frame
/// cell's left edge, `frame_at` the frame under a pointer x.
pub fn ruler(app: &mut App, ui: &mut egui::Ui, ruler: Rect, cell_w: f32, x_of: impl Fn(u32) -> f32, frame_at: impl Fn(f32) -> u32) {
let shown = app.onion.shows() || app.prefs.onion.always_markers;
if !shown || app.playing {
app.onion_ui.drag = None;
return;
}
let (first, last) = range(app);
let p = app.s.frame;
let painter = ui.painter_at(ruler);
let (past, future) = (to_color32(app.onion.past), to_color32(app.onion.future));
let dim = if app.onion.shows() { 1.0 } else { 0.5 };
// The frames within the markers, before and after the playhead in their colours.
if first < p {
painter.rect_filled(Rect::from_min_max(pos2(x_of(first), ruler.top()), pos2(x_of(p), ruler.bottom())), 0.0, past.gamma_multiply(0.22 * dim));
}
if last > p {
painter.rect_filled(Rect::from_min_max(pos2(x_of(p + 1), ruler.top()), pos2(x_of(last + 1), ruler.bottom())), 0.0, future.gamma_multiply(0.22 * dim));
}
let frames = app.s.frame_count();
let anchored = app.onion.anchored();
for start in [true, false] {
let x = if start { x_of(first) } else { x_of(last + 1) };
let c = if start { past } else { future }.gamma_multiply(dim);
// A bracket: [ at the start, ] at the end.
let serif = (cell_w * 0.5).clamp(3.0, 6.0) * if start { 1.0 } else { -1.0 };
let (top, bottom) = (ruler.top() + 2.0, ruler.bottom() - 1.0);
let stroke = Stroke::new(2.0, c);
painter.line_segment([pos2(x, top), pos2(x, bottom)], stroke);
painter.line_segment([pos2(x, top), pos2(x + serif, top)], stroke);
painter.line_segment([pos2(x, bottom), pos2(x + serif, bottom)], stroke);
if anchored {
// Anchored markers carry a pin.
painter.circle_filled(pos2(x + serif * 0.6, ruler.center().y), 2.0, c);
}
let hit = Rect::from_center_size(pos2(x, ruler.center().y), vec2(10.0, ruler.height()));
let id = ui.id().with(("onion_marker", start));
let resp = ui.interact(hit, id, crate::a11y::pointer_only());
let at = if start { first } else { last };
let name = if start { tr!("Onion start marker") } else { tr!("Onion end marker") };
resp.widget_info(|| egui::WidgetInfo::slider(true, f64::from(at + 1), name));
if resp.hovered() || resp.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
}
if resp.drag_started() {
app.onion_ui.drag = Some(start);
}
if resp.dragged()
&& app.onion_ui.drag == Some(start)
&& let Some(ptr) = resp.interact_pointer_pos()
{
// The end marker sits after its frame's cell: aim at the cell the pointer is in.
let f = frame_at(if start { ptr.x + cell_w * 0.5 } else { ptr.x - cell_w * 0.5 });
app.onion.drag_marker(start, f, p, frames);
}
if resp.drag_stopped() {
app.onion_ui.drag = None;
// Saved when let go, not on every step of the drag.
let ctx = ui.ctx().clone();
change(app, &ctx, |_, _| {});
}
let tip = if anchored { tr!("Drag to choose the frames onion skin shows (anchored: they stay when the playhead moves)") } else { tr!("Drag to choose how many frames onion skin shows before and after the playhead") };
resp.on_hover_text(tip);
}
}
// ----- Edit Multiple Frames on the stage ------------------------------------------------------
/// Every element Edit Multiple Frames shows, with its stage bounds (cached per document state,
/// playhead and markers).
pub fn items(app: &mut App) -> Shown {
let (first, last) = range(app);
let key = (app.s.state, app.s.scene, app.s.frame, first, last);
if let Some((k, v)) = &app.onion_ui.cache
&& *k == key
{
return v.clone();
}
let v = Arc::new(app.s.multi_frame_items(first, last));
app.onion_ui.cache = Some((key, v.clone()));
v
}
/// The selection, less what isn't shown any more (after an undo, a marker drag, a new frame).
fn live_selection(app: &mut App) -> Vec<FrameItem> {
let shown = items(app);
let sel: Vec<FrameItem> = app.onion_ui.sel.iter().copied().filter(|it| shown.iter().any(|(s, _)| s == it)).collect();
app.onion_ui.sel.clone_from(&sel);
sel
}
/// Moves the selection by `d` on every keyframe it is on (no-op when nothing is selected).
fn move_by(app: &mut App, d: Vec2) -> bool {
let sel = live_selection(app);
if sel.is_empty() || d == Vec2::ZERO {
return false;
}
let (first, last) = range(app);
let items: Vec<serde_json::Value> = sel.iter().map(FrameItem::to_json).collect();
app.run("frames.edit_multiple", json!({"first": first, "last": last, "dx": d.x, "dy": d.y, "items": items})).is_some()
}
/// A press on the stage with Edit Multiple Frames on: on artwork, select it (unless it is) and
/// move; elsewhere, a marquee.
pub fn drag_start(app: &mut App, sp: Pos2, shift: bool, zoom: f32) -> Drag {
let (first, last) = range(app);
match app.s.multi_frame_pick(first, last, Vec2::new(sp.x, sp.y), 3.0 / zoom.max(1e-3)) {
Some(it) => {
if !app.onion_ui.sel.contains(&it) {
if !shift {
app.onion_ui.sel.clear();
}
app.onion_ui.sel.push(it);
}
// Undo labels stay English in the history and are translated where they show.
app.s.begin_gesture(tr_noop!("Move"));
Drag::MultiMove { last: sp }
}
None => Drag::MultiMarquee { start: sp, cur: sp },
}
}
/// The pointer moved to `c` during a move.
pub fn drag_to(app: &mut App, last: &mut Pos2, c: Pos2) {
let d = c - *last;
if d.length_sq() > 0.0 && move_by(app, Vec2::new(d.x, d.y)) {
*last = c;
}
}
/// A click: select what is under the pointer (Shift adds or takes away), or nothing.
pub fn click(app: &mut App, sp: Pos2, shift: bool, zoom: f32) {
let (first, last) = range(app);
match app.s.multi_frame_pick(first, last, Vec2::new(sp.x, sp.y), 3.0 / zoom.max(1e-3)) {
Some(it) if shift => match app.onion_ui.sel.iter().position(|s| *s == it) {
Some(i) => {
app.onion_ui.sel.remove(i);
}
None => app.onion_ui.sel.push(it),
},
Some(it) => app.onion_ui.sel = vec![it],
None if !shift => app.onion_ui.sel.clear(),
None => {}
}
}
/// A marquee let go: what lies wholly inside it, on every keyframe shown.
pub fn marquee(app: &mut App, a: Pos2, b: Pos2, shift: bool) {
let r = GRect::from_points(Vec2::new(a.x, a.y), Vec2::new(b.x, b.y));
let inside: Vec<FrameItem> = items(app).iter().filter(|(_, bb)| !bb.is_empty() && r.contains(bb.min) && r.contains(bb.max)).map(|(it, _)| *it).collect();
if !shift {
app.onion_ui.sel.clear();
}
for it in inside {
if !app.onion_ui.sel.contains(&it) {
app.onion_ui.sel.push(it);
}
}
}
/// Select All with Edit Multiple Frames on: every element on every keyframe shown.
pub fn select_all(app: &mut App) {
app.onion_ui.sel = items(app).iter().map(|(it, _)| *it).collect();
let n = app.onion_ui.sel.len();
app.status_ok(trn!("Selected {n} element on the frames between the markers", "Selected {n} elements on the frames between the markers", n));
}
/// The arrow keys with Edit Multiple Frames on: one undo step per press.
pub fn nudge(app: &mut App, d: Vec2) {
let own = !app.s.in_gesture();
if own {
app.s.begin_gesture(tr_noop!("Move")); // i18n-exempt: an undo label (the engine's English, translated where shown)
}
move_by(app, d);
if own {
app.s.end_gesture();
}
}
/// Boxes around the selection on every keyframe (and the artwork under the pointer), and the
/// marquee being dragged.
pub fn draw(app: &mut App, painter: &egui::Painter, to_screen: impl Fn(Vec2) -> Pos2, hover: Option<Pos2>, zoom: f32) {
let sel = live_selection(app);
let shown = items(app);
let box_of = |b: &GRect| Rect::from_min_max(to_screen(b.min), to_screen(b.max)).expand(1.0);
if let Some(h) = hover
&& app.drag == Drag::None
{
let (first, last) = range(app);
if let Some(it) = app.s.multi_frame_pick(first, last, Vec2::new(h.x, h.y), 3.0 / zoom.max(1e-3))
&& !sel.contains(&it)
&& let Some((_, b)) = shown.iter().find(|(s, _)| *s == it)
{
painter.rect_stroke(box_of(b), 0.0, Stroke::new(1.0, T.selection.gamma_multiply(0.55)), StrokeKind::Middle);
}
}
for (it, b) in shown.iter().filter(|(it, _)| sel.contains(it)) {
if b.is_empty() {
continue;
}
let r = box_of(b);
// The playhead's keyframe in the selection colour; the others a step lighter, so it is
// clear which artwork is on this frame.
let here = app.s.doc.timeline(app.s.scene).layer(it.layer).and_then(|l| l.keyframe_at(app.s.frame)).is_some_and(|k| k.start == it.frame);
let c = if here { T.selection } else { T.selection.gamma_multiply(0.7) };
painter.rect_stroke(r, 0.0, Stroke::new(if here { 1.5 } else { 1.0 }, c), StrokeKind::Middle);
}
if let Drag::MultiMarquee { start, cur } = app.drag {
let r = Rect::from_two_pos(to_screen(Vec2::new(start.x, start.y)), to_screen(Vec2::new(cur.x, cur.y)));
painter.rect_filled(r, 0.0, T.selection.gamma_multiply(0.12));
painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle);
}
}
/// A caption on the stage while Edit Multiple Frames is on: which frames it shows.
pub fn stage_badge(app: &App, painter: &egui::Painter, canvas: Rect) {
if !editing(app) {
return;
}
let (first, last) = range(app);
let s = tr!("Edit Multiple Frames: {first}–{last}", first = first + 1, last = last + 1);
let at = canvas.left_top() + vec2(10.0, 8.0);
let galley = painter.layout_no_wrap(s, font(Type::Caption), color(Type::Caption));
let r = Rect::from_min_size(at, galley.size()).expand2(vec2(6.0, 3.0));
painter.rect_filled(r, T.rc(), T.panel_alt);
painter.galley(at, galley, color(Type::Caption));
}
#[cfg(test)]
mod tests {
use super::*;
fn app() -> App {
let ctx = egui::Context::default();
let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo());
// Screenshot mode: default preferences, nothing saved.
App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png")))
}
#[test]
fn edit_multiple_frames_selects_and_moves_across_keyframes_in_one_step() {
let mut a = app();
a.open_panel(Some("editmultiple"));
assert!(editing(&a) && a.s.selection.is_empty(), "the playhead's selection is let go");
let sel = a.onion_ui.sel.clone();
assert!(sel.iter().any(|it| it.frame != sel[0].frame), "artwork on more than one keyframe: {sel:?}");
// Where each selected element is on its own keyframe.
let at = |a: &App| -> Vec<f32> {
sel.iter()
.map(|it| {
let l = a.s.doc.timeline(a.s.scene).layer(it.layer).expect("layer");
let k = l.keyframes.iter().find(|k| k.start == it.frame).expect("keyframe");
k.elements.iter().find(|e| e.id == it.element).expect("element").transform.translation().x
})
.collect()
};
let before = at(&a);
let steps = a.s.history_len();
nudge(&mut a, Vec2::new(10.0, 0.0));
assert_eq!(a.s.history_len(), steps + 1, "one undo step");
for (b, c) in before.iter().zip(at(&a)) {
assert!((c - b - 10.0).abs() < 1e-3, "{b} → {c}");
}
a.s.undo().expect("undo");
assert_eq!(at(&a), before, "one undo takes it all back");
assert_eq!(a.onion_ui.sel, sel, "the selection stays");
// Off: the selection goes with it, and arrow keys act on the playhead's selection again.
toggle_edit_multiple(&mut a);
assert!(!editing(&a) && a.onion_ui.sel.is_empty());
}
#[test]
fn a_marquee_takes_what_lies_wholly_inside_on_every_keyframe() {
let mut a = app();
a.open_panel(Some("editmultiple"));
let shown = items(&mut a);
let (first, _) = shown.iter().find(|(_, b)| b.max.x < 640.0 && b.max.y < 400.0 && !b.is_empty()).copied().expect("something in the top left");
marquee(&mut a, pos2(-5.0, -5.0), pos2(640.0, 400.0), false);
assert!(a.onion_ui.sel.contains(&first));
assert!(a.onion_ui.sel.iter().all(|it| shown.iter().any(|(s, b)| s == it && b.max.x <= 640.0 && b.max.y <= 400.0)));
marquee(&mut a, pos2(5000.0, 5000.0), pos2(5001.0, 5001.0), false);
assert!(a.onion_ui.sel.is_empty());
}
#[test]
fn options_are_saved_and_come_back() {
let mut a = app();
let ctx = egui::Context::default();
change(&mut a, &ctx, |o, p| {
o.preset(5);
o.outlines = true;
o.keyframes_only = true;
o.fade = false;
p.past = Some([1, 2, 3]);
});
let p = a.prefs.onion.clone();
assert_eq!((p.before, p.after, p.all, p.outlines, p.keyframes_only, p.fade, p.past), (5, 5, false, true, true, false, Some([1, 2, 3])));
let back = from_prefs(&p);
assert_eq!((back.markers, back.outlines, back.keyframes_only, back.fade, back.ghosts), (Markers::Relative { before: 5, after: 5 }, true, true, false, false));
assert_eq!(srgb_of(back.past), [1, 2, 3]);
change(&mut a, &ctx, |o, _| o.all());
assert!(a.prefs.onion.all && from_prefs(&a.prefs.onion).is_all());
// A broken file can't ask for more than the limit.
let mut big = a.prefs.clone();
big.onion.before = u32::MAX;
assert_eq!(big.sanitized().onion.before, ONION_REACH_MAX);
}
fn srgb_of(c: Rgba) -> [u8; 3] {
let [r, g, b, _] = to_color32(c).to_srgba_unmultiplied();
[r, g, b]
}
}
+2 -2
View File
@@ -166,8 +166,8 @@ pub fn edit_bar(app: &mut App, ui: &mut egui::Ui) {
})
.response
.set_name(tr!("Zoom"));
if ui.selectable_label(app.onion, tr!("Onion skin")).clicked() {
app.onion = !app.onion;
if ui.selectable_label(app.onion.ghosts, tr!("Onion skin")).clicked() {
crate::onion::toggle_ghosts(app);
}
let st = app.s.doc.stage;
ui.label(text(Type::Data, format!("{} × {} px", st.width, st.height)).color(T.text_faint)); // i18n-exempt: stage size, numbers and a unit
+36
View File
@@ -88,6 +88,39 @@ pub struct Prefs {
pub autosave_secs: u32,
/// Also make a copy after this many changes (0: by time only).
pub autosave_edits: u32,
/// Onion skin options (ADR 0047), kept from session to session.
pub onion: OnionPrefs,
}
/// Onion skin options that carry over between sessions (ADR 0047). Whether onion skin and Edit
/// Multiple Frames are on, and anchored markers, last for the session only, as in Animate.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct OnionPrefs {
/// Frames before and after the playhead the markers reach (unless Onion All).
pub before: u32,
pub after: u32,
/// Onion All: the markers span the whole timeline.
pub all: bool,
pub tint: bool,
pub fade: bool,
pub outlines: bool,
pub keyframes_only: bool,
/// The markers show on the frame ruler even while onion skin is off.
pub always_markers: bool,
/// The past and future colours the user picked (sRGB); `None`: the theme's.
pub past: Option<[u8; 3]>,
pub future: Option<[u8; 3]>,
}
/// Most frames a marker reaches from the playhead in the preferences (the timeline's own
/// limit is far beyond what anyone onion-skins).
pub const ONION_REACH_MAX: u32 = 999;
impl Default for OnionPrefs {
fn default() -> Self {
OnionPrefs { before: 2, after: 2, all: false, tint: true, fade: true, outlines: false, keyframes_only: false, always_markers: false, past: None, future: None }
}
}
impl Default for Prefs {
@@ -106,6 +139,7 @@ impl Default for Prefs {
autosave: true,
autosave_secs: 60,
autosave_edits: 25,
onion: OnionPrefs::default(),
}
}
}
@@ -135,6 +169,8 @@ impl Prefs {
self.shortcuts = crate::keymap::sanitize(std::mem::take(&mut self.shortcuts));
self.autosave_secs = self.autosave_secs.clamp(*AUTOSAVE_SECS_RANGE.start(), *AUTOSAVE_SECS_RANGE.end());
self.autosave_edits = self.autosave_edits.min(*AUTOSAVE_EDITS_RANGE.end());
self.onion.before = self.onion.before.min(ONION_REACH_MAX);
self.onion.after = self.onion.after.min(ONION_REACH_MAX);
self
}
+23 -2
View File
@@ -268,6 +268,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
// Selection box in screen space (free transform handles live on it).
let sel_bounds = bounds_arr(app.s.selection_bounds());
let sel_rect = sel_bounds.map(|b| Rect::from_min_max(to_screen(Vec2::new(b[0], b[1])), to_screen(Vec2::new(b[2], b[3]))));
// Edit Multiple Frames takes the Selection and Free Transform tools' input (ADR 0047).
let multi = crate::onion::editing(app) && !preview;
// Shape hint markers take the pointer first with the selection tools (ADR 0023).
let hint_tools = matches!(app.tool, Tool::Select | Tool::Transform | Tool::Subselect) && !panning && !preview;
let hint_marks = if hint_tools { crate::shape_hints::markers(app) } else { Vec::new() };
@@ -360,6 +362,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
} else {
let tool = app.tool;
match tool {
// Edit Multiple Frames (ADR 0047): artwork on every keyframe between the markers.
Tool::Select | Tool::Transform if multi => crate::onion::drag_start(app, sp, shift, zoom),
// On an armature, a drag poses it (ADR 0043).
Tool::Select if let Some(d) = crate::bone_tool::select_drag_start(app, xf, press) => d,
// Raw shapes (ADR 0041): an unselected corner or end moves, an unselected segment
@@ -460,6 +464,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
}
}
(Drag::SnapMove { .. }, Some(c)) => snap_move(app, c, zoom),
(Drag::MultiMove { last }, Some(c)) => {
let mut l = *last;
crate::onion::drag_to(app, &mut l, c);
app.drag = Drag::MultiMove { last: l };
}
(Drag::MultiMarquee { cur: m, .. }, Some(c)) => *m = c,
(Drag::Bend { id, cmd, t, last }, Some(c)) => {
let d = c - *last;
if d.length_sq() > 0.0 {
@@ -554,6 +564,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
Drag::Pencil => crate::pathtools::commit_pencil(app, xf),
Drag::Brush => crate::brushtool::commit(app, xf),
Drag::Eraser => crate::erasertool::commit(app, xf),
Drag::MultiMove { .. } => app.s.end_gesture(),
Drag::MultiMarquee { start, cur } => crate::onion::marquee(app, start, cur, shift),
Drag::Marquee { start, cur } => {
// The parts of raw fills and strokes under it, cut at its edges, and the objects
// wholly inside it (ADR 0041).
@@ -609,6 +621,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
}
}
Tool::Bone if !panning => crate::bone_tool::click(app, xf, p),
Tool::Select | Tool::Transform if !panning && multi => crate::onion::click(app, sp, shift, zoom),
// A click on a bone picks it (ADR 0043).
Tool::Select if !panning && let Some((layer, bone, _)) = crate::bone_tool::hit(app, xf, p) => crate::bone_tool::select(app, layer, Some(bone)),
// A click on a hint marker leaves the selection alone.
@@ -730,7 +743,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
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 visible = tiles_for(z, stage_px, px, 0, bg);
let onion = app.onion && !app.playing;
let onion = crate::onion::stage_skin(app).copied();
let onion = onion.as_ref();
let state = app.s.state;
// Render jobs take movie frames: the current scene starts at `start`.
let start = app.s.doc.scene_start(app.s.scene);
@@ -800,7 +814,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
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)));
ahead.extend(jobs.iter().map(|(t, _)| make_job_for(raster, state, &app.s.doc, start + f, t.view, None).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)));
@@ -875,6 +889,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let sel_stroke = Stroke::new(1.0, T.selection);
let raw = raw_ids(app);
if app.tool == Tool::Select && app.drag == Drag::None
&& !multi
&& app.palette.is_none()
&& !app.modal_open()
&& let Some(sp) = app.cursor_stage
@@ -897,6 +912,11 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
}
painter.add(egui::Shape::mesh(mesh));
}
if multi {
let hover = pointer.filter(|p| canvas.contains(*p) && !panning && !app.modal_open() && app.palette.is_none() && matches!(app.tool, Tool::Select | Tool::Transform)).map(to_stage);
crate::onion::draw(app, &painter, to_screen, hover, zoom);
crate::onion::stage_badge(app, &painter, canvas);
}
// Every selected element, on whichever layer it is (ADR 0044).
for (layer, e) in app.s.selected_elements() {
let id = e.id;
@@ -980,6 +1000,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
if app.tool == Tool::Select
&& app.drag == Drag::None
&& !panning
&& !multi
&& !app.modal_open()
&& let Some(p) = pointer.filter(|p| canvas.contains(*p))
&& let Some((_, grab)) = app.s.raw_grab(to_v(to_stage(p)), GRAB_EDGE / zoom, GRAB_POINT / zoom)
+14
View File
@@ -76,6 +76,10 @@ pub struct Tokens {
pub hint_unplaced: Color32,
pub hint_start: Color32,
pub hint_end: Color32,
/// Onion skin (ADR 0047): frames before the playhead (blue, as Animate users know it) and
/// after it (green); the defaults the onion menu can change. Also the ruler's markers.
pub onion_past: Color32,
pub onion_future: Color32,
/// Library symbol kinds.
pub kind_graphic: Color32,
pub kind_movie_clip: Color32,
@@ -142,6 +146,8 @@ pub const GRAPHITE: Tokens = Tokens {
hint_unplaced: Color32::from_rgb(0xff, 0x5c, 0x8a),
hint_start: Color32::from_rgb(0xff, 0xc2, 0x3d),
hint_end: Color32::from_rgb(0x4f, 0xe3, 0xa8),
onion_past: Color32::from_rgb(0x4f, 0x8d, 0xff),
onion_future: Color32::from_rgb(0x4c, 0xd0, 0x7d),
kind_graphic: Color32::from_rgb(0x22, 0xc7, 0xa9),
kind_movie_clip: Color32::from_rgb(0x5a, 0x8f, 0xff),
kind_button: Color32::from_rgb(0xff, 0xb5, 0x3d),
@@ -196,6 +202,8 @@ pub const HIGH_CONTRAST: Tokens = Tokens {
hint_unplaced: Color32::from_rgb(0xff, 0x7a, 0xa3),
hint_start: Color32::from_rgb(0xff, 0xd8, 0x1a),
hint_end: Color32::from_rgb(0x74, 0xff, 0xb0),
onion_past: Color32::from_rgb(0x6f, 0xa8, 0xff),
onion_future: Color32::from_rgb(0x5c, 0xf0, 0x9a),
kind_graphic: Color32::from_rgb(0x3d, 0xf0, 0xcf),
kind_movie_clip: Color32::from_rgb(0x85, 0xad, 0xff),
kind_button: Color32::from_rgb(0xff, 0xc8, 0x5c),
@@ -607,6 +615,12 @@ pub fn with_type<R>(ui: &mut egui::Ui, role: Type, add: impl FnOnce(&mut egui::U
.inner
}
/// The document colour of an interface colour (the onion skin's theme colours, ADR 0047).
pub fn to_rgba(c: Color32) -> anicraft_engine::doc::Rgba {
let [r, g, b, a] = c.to_srgba_unmultiplied();
anicraft_engine::doc::Rgba::new(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, f32::from(a) / 255.0)
}
pub fn to_color32(c: anicraft_engine::doc::Rgba) -> Color32 {
let c = c.sanitized();
Color32::from_rgba_unmultiplied((c.r * 255.0).round() as u8, (c.g * 255.0).round() as u8, (c.b * 255.0).round() as u8, (c.a * 255.0).round() as u8)
+6 -4
View File
@@ -151,10 +151,7 @@ fn transport(app: &mut App, ui: &mut egui::Ui) {
if icon_button(ui, tr!("Loop playback"), Some(looping), Icon::Loop).clicked() {
app.looping = !app.looping;
}
let onion = app.onion;
if icon_button(ui, tr!("Onion skin"), Some(onion), Icon::Onion).clicked() {
app.onion = !app.onion;
}
crate::onion::buttons(app, 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();
@@ -309,10 +306,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let playhead = f64::from(app.s.frame + 1);
ruler_resp.widget_info(|| egui::WidgetInfo::slider(true, playhead, tr!("Playhead (frame ruler)")));
if (ruler_resp.clicked() || ruler_resp.dragged())
&& app.onion_ui.drag.is_none()
&& let Some(p) = ruler_resp.interact_pointer_pos() {
app.playing = false;
app.run("timeline.goto", json!({"frame": frame_at(p.x)}));
}
// The onion menu on a right-click, as the markers live here (ADR 0047).
ruler_resp.context_menu(|ui| crate::onion::menu(app, ui));
// Onion markers over the ruler (they take the pointer before it).
crate::onion::ruler(app, ui, ruler, cell_w, x_of, frame_at);
// rows
let layers = app.s.doc.timeline(app.s.scene).layers.clone();