From 1bc0c1c32cd93f4a33f4ea9bd94399e2c9a68612 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 19:02:19 -0700 Subject: [PATCH 1/5] docs: reserve ADR 0091 for filter presets, order, on/off and tweens (M5) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..3af10660 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0091 | m5/filters-2 (M5) | Filter presets, order, on/off and tweened filter values | From f7d90f361c9f6aadee3d0e3f4ff9e4ae011c7d63 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 19:18:58 -0700 Subject: [PATCH 2/5] feat(engine): filters switch on and off, reorder, copy and paste, and filter presets (M5) A filter list entry carries an enabled switch (FilterEntry, flattened into the filter's own object, so older files open unchanged); evaluate and the HTML export leave switched-off filters out, so every renderer and export draws them as absent. New filter.* commands: move, enable, remove, copy, paste, and presets (list, save, apply, rename, delete, export, import) kept in the session like brushes. XFL import keeps disabled filters, switched off. Classic tweens pair lists that include switched-off filters. --- crates/doc/src/eval.rs | 4 +- crates/doc/src/eval_tests.rs | 13 +- crates/doc/src/filter.rs | 64 +++++- crates/doc/src/lib.rs | 7 +- crates/engine/src/cmds_draw.rs | 57 +----- crates/engine/src/cmds_filter.rs | 296 ++++++++++++++++++++++++++++ crates/engine/src/cmds_plugin.rs | 5 + crates/engine/src/confirm.rs | 23 +++ crates/engine/src/filter_library.rs | 236 ++++++++++++++++++++++ crates/engine/src/lib.rs | 17 ++ crates/engine/src/plugin_tests.rs | 3 + crates/engine/src/tests.rs | 2 +- crates/engine/src/tests_filter.rs | 247 +++++++++++++++++++++++ crates/gpu/examples/gpu_bench.rs | 4 +- crates/gpu/src/tests.rs | 4 +- crates/render/src/html.rs | 8 +- crates/render/src/html_tests.rs | 4 +- crates/xfl/src/import.rs | 15 +- crates/xfl/src/tests.rs | 6 +- 19 files changed, 924 insertions(+), 91 deletions(-) create mode 100644 crates/engine/src/cmds_filter.rs create mode 100644 crates/engine/src/filter_library.rs create mode 100644 crates/engine/src/tests_filter.rs diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 9ff9b3c3..489372f4 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -715,9 +715,9 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out: // An alpha offset (Advanced) changes each item's alpha on its own: it stays // in the items' transform, and the group (for a blend or filters) is opaque. let fade = fx.alpha_factor().unwrap_or(1.0); - let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || !filters.is_empty()) { + let (color, group) = if masks.is_none() && (fade < 1.0 - 1e-4 || !blend.is_normal() || crate::filter::any_active(filters)) { let gid = out.groups.len() as u32; - out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: filters.iter().map(crate::Filter::sanitized).collect(), clip }); + out.groups.push(Group { parent: cx.group, alpha: fade, blend: *blend, filters: crate::filter::active(filters).into(), clip }); let inner = if fx.alpha_factor().is_some() { fx.without_alpha() } else { fx }; (cx.color.concat(&inner), Some(gid)) } else { diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index 080ba5cc..d79aca05 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -561,7 +561,7 @@ fn instance_filters_tween_when_they_pair_up() { let mut d = Document::default(); let sid = SymbolId(90); d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(Layer::new(LayerId(91), "x"))] } })); - let inst = |filters: Vec| Element { id: ElementId(92), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters, events: Vec::new() } }; + let inst = |filters: Vec| Element { id: ElementId(92), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: filters.into_iter().map(Into::into).collect(), events: Vec::new() } }; let blur = |b: f32| Filter::Blur { blur_x: b, blur_y: b, quality: 1 }; let mut tw = Tween::new(Easing::Linear, TweenKind::Classic); tw.set_ease(crate::EaseGroup::Filters, Some(Easing::QuadIn)); @@ -575,8 +575,13 @@ fn instance_filters_tween_when_they_pair_up() { ElementKind::Symbol { filters, .. } => filters.clone(), _ => Vec::new(), }; - assert_eq!(filters(5)[0], blur(40.0 * 0.25), "eased by the filters group's ease"); + assert_eq!(filters(5)[0], blur(40.0 * 0.25).into(), "eased by the filters group's ease"); // Lists that don't pair up hold the first keyframe's. - assert_eq!(crate::filter::lerp_filters(&[blur(1.0)], &[Filter::new("glow").unwrap()], 0.5), None); - assert_eq!(crate::filter::lerp_filters(&[blur(1.0)], &[blur(1.0), blur(2.0)], 0.5), None); + let e = |f: Filter| crate::FilterEntry::from(f); + assert_eq!(crate::filter::lerp_filters(&[e(blur(1.0))], &[e(Filter::new("glow").unwrap())], 0.5), None); + assert_eq!(crate::filter::lerp_filters(&[e(blur(1.0))], &[e(blur(1.0)), e(blur(2.0))], 0.5), None); + // A switched-off filter still pairs up (and stays off, as the first keyframe has it). + let off = crate::FilterEntry { filter: blur(0.0), enabled: false }; + let got = crate::filter::lerp_filters(std::slice::from_ref(&off), &[e(blur(10.0))], 0.5).unwrap(); + assert_eq!(got, vec![crate::FilterEntry { filter: blur(5.0), enabled: false }]); } diff --git a/crates/doc/src/filter.rs b/crates/doc/src/filter.rs index ce787e3b..ed5a4d9e 100644 --- a/crates/doc/src/filter.rs +++ b/crates/doc/src/filter.rs @@ -401,15 +401,65 @@ impl Filter { } } -/// The classic tween between two filter lists (ADR 0081): when both have the same kinds in the -/// same order, each filter's numbers and colours travel (switches such as Inner and Knockout, -/// and the quality, stay the first keyframe's; ramps travel stop by stop when they have as -/// many stops). `None` when the lists are equal or don't pair up: the first list holds. -pub fn lerp_filters(a: &[Filter], b: &[Filter], t: f32) -> Option> { - if a == b || a.len() != b.len() { +fn yes() -> bool { + true +} +fn is_on(b: &bool) -> bool { + *b +} + +/// One filter in an instance's list (ADR 0091): the filter and whether it is on. A filter +/// switched off keeps its settings and its place but draws nothing: [`active`] leaves it out, +/// so every renderer and export sees exactly the list without it. In files it is the filter's +/// own object with `"enabled": false` added (left out when on), so files from before open as +/// they were. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct FilterEntry { + #[serde(flatten)] + pub filter: Filter, + #[serde(default = "yes", skip_serializing_if = "is_on")] + pub enabled: bool, +} + +impl From for FilterEntry { + fn from(filter: Filter) -> FilterEntry { + FilterEntry { filter, enabled: true } + } +} + +impl FilterEntry { + /// The same entry with its filter in range. + pub fn sanitized(&self) -> FilterEntry { + FilterEntry { filter: self.filter.sanitized(), enabled: self.enabled } + } +} + +/// The filters that draw, in order and in range: the ones switched on. +pub fn active(list: &[FilterEntry]) -> Vec { + list.iter().filter(|e| e.enabled).map(|e| e.filter.sanitized()).collect() +} + +/// Whether any filter in the list draws. +pub fn any_active(list: &[FilterEntry]) -> bool { + list.iter().any(|e| e.enabled) +} + +/// Whether two lists pair up for a tween: the same kinds in the same order (Animate's rule; +/// switched-off filters count, so switching one off never breaks a tween). +pub fn pairs_up(a: &[FilterEntry], b: &[FilterEntry]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| std::mem::discriminant(&x.filter) == std::mem::discriminant(&y.filter)) +} + +/// The classic tween between two filter lists (ADR 0081, 0091): when both have the same kinds +/// in the same order, each filter's numbers and colours travel (switches such as Inner and +/// Knockout, the quality, and whether the filter is on stay the first keyframe's; ramps travel +/// stop by stop when they have as many stops). `None` when the lists are equal or don't pair +/// up: the first list holds. +pub fn lerp_filters(a: &[FilterEntry], b: &[FilterEntry], t: f32) -> Option> { + if a == b || !pairs_up(a, b) { return None; } - a.iter().zip(b).map(|(x, y)| x.lerp(y, t)).collect() + a.iter().zip(b).map(|(x, y)| Some(FilterEntry { filter: x.filter.lerp(&y.filter, t)?, enabled: x.enabled })).collect() } fn ramp_lerp(a: &[GradientStop], b: &[GradientStop], t: f32) -> Vec { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 74664e43..0e59c30b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -33,7 +33,7 @@ pub mod templates; pub mod sound; pub mod swatch; -pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; +pub use filter::{Filter, FilterEntry, FilterSide, active as active_filters, any_active as any_active_filter, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png}; pub use easing::{CustomEase, EaseDir, EaseFamily, EasePoint, Easing, Handle, MAX_EASE_NAME, MAX_EASE_POINTS, MAX_EASE_SAMPLES, MAX_EASE_Y, MAX_SAVED_EASES, SampledEase, SavedEase, ease_name}; pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform}; @@ -563,9 +563,10 @@ pub enum ElementKind { /// How the instance blends with what is below it (movie clips and buttons). #[serde(default, skip_serializing_if = "BlendMode::is_normal")] blend: BlendMode, - /// Filters, applied in order (movie clips and buttons). + /// Filters, applied in order (movie clips and buttons); each may be switched off + /// (ADR 0091). #[serde(default, skip_serializing_if = "Vec::is_empty")] - filters: Vec, + filters: Vec, /// What the instance does on pointer events in the player (buttons and movie clips; /// ADR 0024), one handler per event. #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 67d66930..f7164d0e 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1} sets the alpha multiplier and keeps the rest of the colour effect (None becomes Alpha; Brightness and Tint become Advanced below 1)", true, |s, p| s.each_layer(true, |s| set_alpha(s, p))), c("element.set_color_effect", "Colour Effect", "", None, "{style?: none|brightness|tint|advanced|alpha (default: the style the values belong to, else each element's own), alpha? (%, 0..100), brightness? (%, -100..100), tint? (#rrggbb), tint_amount? (%, 0..100), red_multiplier?, green_multiplier?, blue_multiplier?, alpha_multiplier? (%, -100..100), red_offset?, green_offset?, blue_offset?, alpha_offset? (-255..255)} on every selected element (ADR 0056); values not given keep each element's own. A new style starts from the look it can keep: Advanced is exactly the effect before, Alpha keeps the opacity, Brightness and Tint start at 0 %. The camera has no opacity (no Alpha style, alpha multiplier or offset)", true, |s, p| s.each_layer(true, |s| set_color_effect(s, p))), c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| set_blend(s, p))), - c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| set_filters(s, p))), + c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values, enabled?: bool (default true; false switches it off, keeping its settings)}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, |s, p| s.each_layer(false, |s| crate::cmds_filter::set_filters(s, p))), c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, |s, p| s.each_layer(false, |s| set_loop(s, p))), c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the symbols of every selected instance)}", true, set_symbol_kind), c( @@ -556,61 +556,6 @@ fn set_color_effect(s: &mut Session, p: &Value) -> Result { Ok(first.map_or(Value::Null, |fx| crate::color_effect_json(&fx))) } -/// Most filters on one instance. -const MAX_FILTERS: usize = 16; - -/// Filters for the selected movie clip and button instances (Animate offers them on those only). -fn set_filters(s: &mut Session, p: &Value) -> Result { - let mut list = p.get("filters").cloned().ok_or_else(|| EngineError::Param("param 'filters' is required (a list; [] removes them)".into()))?; - // Colours may be written "#rrggbb" (or "#rrggbbaa"), as everywhere in commands: the filter's - // own and its ramp stops'. - fn hex_colors(v: &mut Value, keys: &[&str]) -> Result<()> { - for k in keys { - if v.get(*k).is_some_and(Value::is_string) { - let c = opt_color(v, k)?.unwrap_or(anicraft_doc::Rgba::BLACK); - v[*k] = json!({"r": c.r, "g": c.g, "b": c.b, "a": c.a}); - } - } - Ok(()) - } - for f in list.as_array_mut().into_iter().flatten() { - hex_colors(f, &["color", "shadow_color", "highlight_color"])?; - if let Some(stops) = f.get_mut("stops").and_then(Value::as_array_mut) { - if stops.len() > anicraft_doc::MAX_RAMP_STOPS { - return Err(EngineError::Param(format!("a ramp has at most {} stops", anicraft_doc::MAX_RAMP_STOPS))); - } - for st in stops.iter_mut() { - hex_colors(st, &["color"])?; - } - } - } - let filters: Vec = serde_json::from_value(list).map_err(|e| EngineError::Param(format!("'filters' must be a list of {{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …}}: {e}")))?; - if filters.len() > MAX_FILTERS { - return Err(EngineError::Param(format!("at most {MAX_FILTERS} filters per instance"))); - } - let filters: Vec = filters.iter().map(anicraft_doc::Filter::sanitized).collect(); - let kinds: std::collections::HashMap = s.doc.library.iter().map(|x| (x.id, x.kind)).collect(); - let (mut set, mut graphics) = (0, 0); - for e in s.selected_props_mut()? { - if let ElementKind::Symbol { symbol, filters: f, .. } = &mut e.kind { - if kinds.get(symbol) == Some(&SymbolKind::Graphic) { - graphics += 1; - continue; - } - f.clone_from(&filters); - set += 1; - } - } - if set == 0 { - return Err(EngineError::State(if graphics > 0 { - "filters apply to movie clip and button instances, as in Animate; set the symbol's Type to Movie Clip first".into() - } else { - "select a movie clip or button instance".into() - })); - } - Ok(json!({"filters": filters.len(), "set": set})) -} - /// Blending for the selected movie clip and button instances (Animate offers it on those only). fn set_blend(s: &mut Session, p: &Value) -> Result { let key = str_req(p, "mode")?; diff --git a/crates/engine/src/cmds_filter.rs b/crates/engine/src/cmds_filter.rs new file mode 100644 index 00000000..5f0090bb --- /dev/null +++ b/crates/engine/src/cmds_filter.rs @@ -0,0 +1,296 @@ +//! The filter list of movie clip and button instances (ADR 0025, 0091): replacing it +//! (`element.set_filters`), reordering, switching filters on and off, removing them, copying +//! and pasting them between instances, and the user's filter presets. +//! +//! Every edit acts on each selected movie clip and button instance (graphics take no filters, +//! as in Animate) and is one undo step. A filter at an index acts where an instance has one; +//! the command fails only when it acts nowhere. Copied filters and presets live in the session, +//! outside the document and its undo history. + +use crate::filter_library::{FilterLibrary, MAX_FILE_BYTES, MAX_FILTERS, MAX_PRESETS}; +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{ElementKind, FilterEntry, SymbolId, SymbolKind}; +use serde_json::{Value, json}; + +pub fn specs() -> Vec { + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c("filter.move", "Move Filter", "{from, to} moves the filter at index `from` (0 is the first, applied first) to index `to` in the selected movie clip and button instances' lists; the order changes how they draw", true, (|s, p| s.each_layer(false, |s| move_filter(s, p))) as crate::RunFn), + c("filter.enable", "Enable Filter", "{enabled: bool, index? (default: every filter)} switches a filter on or off; a filter switched off keeps its settings and draws nothing", true, |s, p| s.each_layer(false, |s| enable(s, p))), + c("filter.remove", "Remove Filter", "{index? (default: every filter)} removes a filter from the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| remove(s, p))), + c("filter.copy", "Copy Filters", "{index? (default: every filter)} copies the selected instance's filters (one, or all), for Paste Filters", false, copy), + c("filter.paste", "Paste Filters", "{replace? (default false: added after the instances' own)} pastes the copied filters onto the selected movie clip and button instances", true, |s, p| s.each_layer(false, |s| paste(s, p))), + c("filter.preset_list", "Filter Presets", "{} your filter presets, each a name and its filters", false, preset_list), + c("filter.preset_save", "Save Filter Preset", "{name, filters? (a list as element.set_filters takes; default: the selected instance's)} saves a filter preset of your own (kept in your preferences; a name you have already is replaced, after asking)", false, preset_save), + c("filter.preset_apply", "Apply Filter Preset", "{name} gives the selected movie clip and button instances the preset's filters, replacing theirs (as Animate does)", true, |s, p| s.each_layer(false, |s| preset_apply(s, p))), + c("filter.preset_rename", "Rename Filter Preset", "{name, to}", false, preset_rename), + c("filter.preset_delete", "Delete Filter Preset", "{name} deletes a filter preset (asks first: it can't be undone; artwork that used it keeps its filters)", false, preset_delete), + c("filter.preset_export", "Export Filter Presets", "{path, names? (default: all)} writes your filter presets to a small JSON file", false, preset_export), + c("filter.preset_import", "Import Filter Presets", "{path} adds the presets in a filter preset file to yours (a name you have already gets a number)", false, preset_import), + ] +} + +/// A filter list from command params (`element.set_filters`, `filter.preset_save`): colours may +/// be "#rrggbb" or "#rrggbbaa", values are brought into range, at most [`MAX_FILTERS`]. +pub(crate) fn parse_list(list: Option<&Value>) -> Result> { + let mut list = list.cloned().ok_or_else(|| EngineError::Param("param 'filters' is required (a list; [] removes them)".into()))?; + fn hex_colors(v: &mut Value, keys: &[&str]) -> Result<()> { + for k in keys { + if v.get(*k).is_some_and(Value::is_string) { + let c = opt_color(v, k)?.unwrap_or(anicraft_doc::Rgba::BLACK); + v[*k] = json!({"r": c.r, "g": c.g, "b": c.b, "a": c.a}); + } + } + Ok(()) + } + if list.as_array().is_some_and(|a| a.len() > MAX_FILTERS) { + return Err(EngineError::Param(format!("at most {MAX_FILTERS} filters per instance"))); + } + for f in list.as_array_mut().into_iter().flatten() { + hex_colors(f, &["color", "shadow_color", "highlight_color"])?; + if let Some(stops) = f.get_mut("stops").and_then(Value::as_array_mut) { + if stops.len() > anicraft_doc::MAX_RAMP_STOPS { + return Err(EngineError::Param(format!("a ramp has at most {} stops", anicraft_doc::MAX_RAMP_STOPS))); + } + for st in stops.iter_mut() { + hex_colors(st, &["color"])?; + } + } + } + let filters: Vec = serde_json::from_value(list).map_err(|e| EngineError::Param(format!("'filters' must be a list of {{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values, enabled?: bool}}: {e}")))?; + Ok(filters.iter().map(FilterEntry::sanitized).collect()) +} + +/// Runs `edit` on the filter list of each selected movie clip and button instance; `edit` +/// says whether it changed that list. Fails when no instance takes filters, or none changed +/// (`nothing` says why). +fn edit_lists(s: &mut Session, nothing: &str, mut edit: impl FnMut(&mut Vec) -> bool) -> Result { + let kinds: std::collections::HashMap = s.doc.library.iter().map(|x| (x.id, x.kind)).collect(); + let (mut set, mut clips, mut graphics) = (0, 0, 0); + for e in s.selected_props_mut()? { + if let ElementKind::Symbol { symbol, filters, .. } = &mut e.kind { + if kinds.get(symbol) == Some(&SymbolKind::Graphic) { + graphics += 1; + continue; + } + clips += 1; + if edit(filters) { + set += 1; + } + } + } + if clips == 0 { + return Err(EngineError::State(if graphics > 0 { + "filters apply to movie clip and button instances, as in Animate; set the symbol's Type to Movie Clip first".into() + } else { + "select a movie clip or button instance".into() + })); + } + if set == 0 { + return Err(EngineError::State(nothing.into())); + } + Ok(set) +} + +/// Filters for the selected movie clip and button instances (Animate offers them on those only). +pub(crate) fn set_filters(s: &mut Session, p: &Value) -> Result { + let filters = parse_list(p.get("filters"))?; + let set = edit_lists(s, "", |f| { + f.clone_from(&filters); + true + })?; + Ok(json!({"filters": filters.len(), "set": set})) +} + +fn index(p: &Value, key: &str) -> Result> { + Ok(opt_u32(p, key)?.map(|i| i as usize)) +} + +fn index_req(p: &Value, key: &str) -> Result { + index(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required (a filter's index, 0 is the first)"))) +} + +fn no_filter(i: usize) -> String { + format!("the selection has no filter {} (0 is the first)", i) +} + +fn move_filter(s: &mut Session, p: &Value) -> Result { + let (from, to) = (index_req(p, "from")?, index_req(p, "to")?); + let set = edit_lists(s, &no_filter(from), |f| { + if from >= f.len() { + return false; + } + let to = to.min(f.len() - 1); + if from == to { + return true; + } + let x = f.remove(from); + f.insert(to, x); + true + })?; + Ok(json!({"moved": set})) +} + +fn enable(s: &mut Session, p: &Value) -> Result { + let on = opt_bool(p, "enabled")?.ok_or_else(|| EngineError::Param("param 'enabled' is required (true or false)".into()))?; + let at = index(p, "index")?; + let nothing = at.map_or_else(|| "the selection has no filters".to_string(), no_filter); + let set = edit_lists(s, ¬hing, |f| match at { + Some(i) => f.get_mut(i).map(|e| e.enabled = on).is_some(), + None => { + f.iter_mut().for_each(|e| e.enabled = on); + !f.is_empty() + } + })?; + Ok(json!({"enabled": on, "set": set})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let at = index(p, "index")?; + let nothing = at.map_or_else(|| "the selection has no filters".to_string(), no_filter); + let set = edit_lists(s, ¬hing, |f| match at { + Some(i) if i < f.len() => { + f.remove(i); + true + } + Some(_) => false, + None => { + let any = !f.is_empty(); + f.clear(); + any + } + })?; + Ok(json!({"removed": set})) +} + +/// The filters of the first selected movie clip or button instance, as it shows now. +fn selected_list(s: &Session) -> Result> { + let kinds: std::collections::HashMap = s.doc.library.iter().map(|x| (x.id, x.kind)).collect(); + s.selected_elements() + .into_iter() + .find_map(|(_, e)| match &e.kind { + ElementKind::Symbol { symbol, filters, .. } if kinds.get(symbol).is_some_and(|k| *k != SymbolKind::Graphic) => Some(filters.clone()), + _ => None, + }) + .ok_or_else(|| EngineError::State("select a movie clip or button instance".into())) +} + +fn copy(s: &mut Session, p: &Value) -> Result { + let list = selected_list(s)?; + let chosen = match index(p, "index")? { + Some(i) => vec![list.get(i).cloned().ok_or_else(|| EngineError::Param(no_filter(i)))?], + None if list.is_empty() => return Err(EngineError::State("the instance has no filters to copy".into())), + None => list, + }; + let n = chosen.len(); + s.filter_clipboard = Some(chosen); + Ok(json!({"copied": n})) +} + +/// `add` after each list (or in place of it with `replace`), refused past [`MAX_FILTERS`]. +fn put(s: &mut Session, add: &[FilterEntry], replace: bool) -> Result { + let mut full = false; + let set = edit_lists(s, "", |f| { + if replace { + *f = add.to_vec(); + return true; + } + if f.len() + add.len() > MAX_FILTERS { + full = true; + return false; + } + f.extend(add.iter().cloned()); + true + }); + match set { + Err(_) if full => Err(EngineError::State(format!("an instance has at most {MAX_FILTERS} filters; remove some first"))), + other => other, + } +} + +fn paste(s: &mut Session, p: &Value) -> Result { + let add = s.filter_clipboard.clone().ok_or_else(|| EngineError::State("no filters are copied yet (Copy Filters first)".into()))?; + let replace = opt_bool(p, "replace")?.unwrap_or(false); + let set = put(s, &add, replace)?; + Ok(json!({"pasted": add.len(), "set": set})) +} + +fn preset_json(p: &crate::filter_library::FilterPreset) -> Value { + json!({"name": p.name, "filters": p.filters}) +} + +fn preset_list(s: &mut Session, _: &Value) -> Result { + Ok(json!({"presets": s.filter_presets.presets().iter().map(preset_json).collect::>()})) +} + +fn preset_save(s: &mut Session, p: &Value) -> Result { + let name = str_req(p, "name")?; + let filters = match p.get("filters") { + None | Some(Value::Null) => selected_list(s)?, + list => parse_list(list)?, + }; + let (name, replaced) = s.filter_presets.save(name, &filters)?; + Ok(json!({"name": name, "replaced": replaced, "filters": filters.len(), "presets": s.filter_presets.presets().len()})) +} + +fn preset_apply(s: &mut Session, p: &Value) -> Result { + let name = str_req(p, "name")?; + let preset = s.filter_presets.find(name).cloned().ok_or_else(|| EngineError::Param(format!("you have no filter preset named '{}'", name.chars().take(64).collect::())))?; + let set = put(s, &preset.filters, true)?; + Ok(json!({"name": preset.name, "filters": preset.filters.len(), "set": set})) +} + +fn preset_rename(s: &mut Session, p: &Value) -> Result { + let to = s.filter_presets.rename(str_req(p, "name")?, str_req(p, "to")?)?; + Ok(json!({"name": to})) +} + +fn preset_delete(s: &mut Session, p: &Value) -> Result { + let gone = s.filter_presets.delete(str_req(p, "name")?)?; + Ok(json!({"deleted": gone.name, "presets": s.filter_presets.presets().len()})) +} + +fn preset_export(s: &mut Session, p: &Value) -> Result { + let path = std::path::PathBuf::from(str_req(p, "path")?); + let bad = || EngineError::Param("param 'names' must be a list of filter preset names".into()); + let chosen: Vec<_> = match p.get("names") { + None | Some(Value::Null) => s.filter_presets.presets().to_vec(), + Some(Value::Array(names)) => names + .iter() + .take(MAX_PRESETS * 2) + .map(|n| { + let n = n.as_str().ok_or_else(bad)?; + s.filter_presets.find(n).cloned().ok_or_else(|| EngineError::Param(format!("you have no filter preset named '{}'", n.chars().take(64).collect::()))) + }) + .collect::>()?, + Some(_) => return Err(bad()), + }; + if chosen.is_empty() { + return Err(EngineError::State("there are no filter presets to export yet (save one first)".into())); + } + let text = FilterLibrary::file_json(&chosen); + crate::vfs::write(&path, text.as_bytes())?; + Ok(json!({"written": path.display().to_string(), "presets": chosen.len(), "bytes": text.len()})) +} + +fn preset_import(s: &mut Session, p: &Value) -> Result { + let path = std::path::PathBuf::from(str_req(p, "path")?); + if crate::vfs::len(&path)? > MAX_FILE_BYTES { + return Err(EngineError::Param(format!("{} is too large to be a filter preset file", path.display()))); + } + let found = FilterLibrary::parse_file(&crate::vfs::read_to_string(&path)?)?; + if found.is_empty() { + return Err(EngineError::Param("the file has no filter presets in it".into())); + } + let mut names = Vec::with_capacity(found.len()); + for f in found { + match s.filter_presets.add_unique(f) { + Ok(n) => names.push(n), + Err(e) if names.is_empty() => return Err(e), + // The library filled up part way: say what came in. + Err(_) => break, + } + } + Ok(json!({"imported": names, "presets": s.filter_presets.presets().len()})) +} diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 57543aff..001634bd 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -47,6 +47,11 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { // user's own brushes are their preferences, and a brush set is a file. "brush" if id == "brush.preset_list" => Ok(()), "brush" => Err("plug-ins can't change your brushes or read and write brush sets"), + // Filter lists are the document's (ADR 0091); copied filters are the artist's + // clipboard, and the presets their preferences (listing and applying one is fine). + "filter" if matches!(id, "filter.copy" | "filter.paste") => Err("plug-ins don't use your clipboard"), + "filter" if matches!(id, "filter.preset_save" | "filter.preset_rename" | "filter.preset_delete" | "filter.preset_export" | "filter.preset_import") => Err("plug-ins can't change your filter presets or read and write preset files"), + "filter" => Ok(()), // The document's swatches are document data; swatch files are files. "swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"), "swatch" => Ok(()), diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index bdce9128..064a752b 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -157,6 +157,29 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { action: "Replace Swatches".into(), irreversible: false, }), + // Filter presets live in your preferences, outside undo (ADR 0091). + "filter.preset_delete" => { + let name = s.filter_presets.find(p.get("name").and_then(Value::as_str)?)?.name.clone(); + Some(Confirmation { + title: "Delete filter preset?".into(), + message: format!("The filter preset “{name}” will be deleted from your presets. Artwork that uses its filters keeps them. This cannot be undone."), + action: "Delete Preset".into(), + irreversible: true, + }) + } + "filter.preset_save" => { + let name = s.filter_presets.find(p.get("name").and_then(Value::as_str)?)?.name.clone(); + Some(Confirmation { + title: "Replace filter preset?".into(), + message: format!("You already have a filter preset named “{name}”. Saving replaces its filters. This cannot be undone."), + action: "Replace".into(), + irreversible: true, + }) + } + "filter.preset_export" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + crate::vfs::exists(path).then(|| overwrite(path, "Exporting the filter presets")) + } "brush.preset_export" => { let path = Path::new(p.get("path").and_then(Value::as_str)?); crate::vfs::exists(path).then(|| overwrite(path, "Exporting the brushes")) diff --git a/crates/engine/src/filter_library.rs b/crates/engine/src/filter_library.rs new file mode 100644 index 00000000..f3a0f4ad --- /dev/null +++ b/crates/engine/src/filter_library.rs @@ -0,0 +1,236 @@ +//! Filter presets (ADR 0091): named filter lists of the user's own, as Animate's Filters panel +//! keeps them (Save as Preset, apply, rename, delete). +//! +//! Like the user's brushes (ADR 0068) the presets belong to the session, not the document: they +//! survive New and Open, the desktop app keeps them in its preferences and puts them back at +//! start (so the engine never reads the settings folder), and they move between computers as a +//! small JSON file (`filter.preset_export`/`_import`). Applying one copies its list onto the +//! instances: a preset edited or deleted later never changes artwork behind the artist's back. + +use crate::{EngineError, Result}; +use anicraft_doc::FilterEntry; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Most presets. +pub const MAX_PRESETS: usize = 200; +/// Longest preset name, in characters. +pub const MAX_NAME: usize = 64; +/// Most filters on one instance (and so in one preset). +pub const MAX_FILTERS: usize = 16; +/// Largest preset file read. +pub const MAX_FILE_BYTES: u64 = 1 << 20; +/// What a preset file says it is. +pub const FILE_FORMAT: &str = "anicraft-filter-presets"; +pub const FILE_VERSION: u32 = 1; + +/// A named filter list. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct FilterPreset { + pub name: String, + #[serde(default)] + pub filters: Vec, +} + +impl FilterPreset { + /// The preset with a clean name and its filters in range (at most [`MAX_FILTERS`]); `None` + /// when the name is empty. + pub fn sanitized(self) -> Option { + let name = clean_name(&self.name)?; + Some(FilterPreset { name, filters: self.filters.iter().take(MAX_FILTERS).map(FilterEntry::sanitized).collect() }) + } +} + +/// A name as kept: one line, trimmed, at most [`MAX_NAME`] characters; `None` when empty. +pub fn clean_name(s: &str) -> Option { + let one: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + let t: String = one.trim().chars().take(MAX_NAME).collect(); + let t = t.trim().to_string(); + (!t.is_empty()).then_some(t) +} + +fn same_name(a: &str, b: &str) -> bool { + a.trim().to_lowercase() == b.trim().to_lowercase() +} + +/// The user's filter presets, in the order they were saved; names are unique, case aside. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct FilterLibrary { + presets: Vec, +} + +#[derive(Serialize, Deserialize)] +struct PresetFile { + format: String, + version: u32, + presets: Vec, +} + +impl FilterLibrary { + pub fn presets(&self) -> &[FilterPreset] { + &self.presets + } + + pub fn is_empty(&self) -> bool { + self.presets.is_empty() + } + + /// A library from untrusted entries (preferences, a file): bad entries skipped, values + /// clamped, names made unique, at most [`MAX_PRESETS`]. + pub fn from_values(values: impl IntoIterator) -> FilterLibrary { + let mut lib = FilterLibrary::default(); + for v in values.into_iter().take(MAX_PRESETS * 4) { + if let Ok(p) = serde_json::from_value::(v) { + let _ = lib.add_unique(p); + } + } + lib + } + + /// The same library with every entry sanitized (after deserializing preferences). + pub fn sanitized(self) -> FilterLibrary { + FilterLibrary::from_values(self.presets.into_iter().filter_map(|p| serde_json::to_value(p).ok())) + } + + pub fn position(&self, name: &str) -> Option { + self.presets.iter().position(|p| same_name(&p.name, name)) + } + + pub fn find(&self, name: &str) -> Option<&FilterPreset> { + self.position(name).and_then(|i| self.presets.get(i)) + } + + fn missing(name: &str) -> EngineError { + EngineError::Param(format!("you have no filter preset named '{}'", name.chars().take(MAX_NAME).collect::())) + } + + /// Saves `filters` under `name`, replacing the preset of that name. Returns the name kept + /// and whether it replaced one. + pub fn save(&mut self, name: &str, filters: &[FilterEntry]) -> Result<(String, bool)> { + let p = FilterPreset { name: name.to_string(), filters: filters.to_vec() }.sanitized().ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?; + if p.filters.is_empty() { + return Err(EngineError::State("there are no filters to save; add one first".into())); + } + let name = p.name.clone(); + if let Some(i) = self.position(&name) + && let Some(slot) = self.presets.get_mut(i) + { + // The name as written now (the case may differ). + *slot = p; + return Ok((name, true)); + } + if self.presets.len() >= MAX_PRESETS { + return Err(EngineError::State(format!("you have {MAX_PRESETS} filter presets already; delete some first"))); + } + self.presets.push(p); + Ok((name, false)) + } + + /// Adds `p`, renaming it ("Glow 2", "Glow 3", ..) if the name is taken. Returns its name. + pub fn add_unique(&mut self, p: FilterPreset) -> Result { + let p = p.sanitized().ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?; + if self.presets.len() >= MAX_PRESETS { + return Err(EngineError::State(format!("you have {MAX_PRESETS} filter presets already; delete some first"))); + } + let base = p.name.clone(); + let mut name = base.clone(); + let mut k = 2; + while self.position(&name).is_some() { + if k > MAX_PRESETS + 10 { + return Err(EngineError::State("too many filter presets of that name".into())); + } + let suffix = format!(" {k}"); + name = format!("{}{suffix}", base.chars().take(MAX_NAME.saturating_sub(suffix.chars().count())).collect::().trim_end()); + k += 1; + } + self.presets.push(FilterPreset { name: name.clone(), ..p }); + Ok(name) + } + + pub fn rename(&mut self, name: &str, to: &str) -> Result { + let i = self.position(name).ok_or_else(|| Self::missing(name))?; + let to = clean_name(to).ok_or_else(|| EngineError::Param("a filter preset needs a name".into()))?; + if self.position(&to).is_some_and(|j| j != i) { + return Err(EngineError::Param(format!("you already have a filter preset named '{to}'"))); + } + if let Some(p) = self.presets.get_mut(i) { + p.name = to.clone(); + } + Ok(to) + } + + pub fn delete(&mut self, name: &str) -> Result { + let i = self.position(name).ok_or_else(|| Self::missing(name))?; + Ok(self.presets.remove(i)) + } + + /// A preset file holding `presets`. + pub fn file_json(presets: &[FilterPreset]) -> String { + let f = PresetFile { format: FILE_FORMAT.into(), version: FILE_VERSION, presets: presets.iter().filter_map(|p| serde_json::to_value(p).ok()).collect() }; + serde_json::to_string_pretty(&f).unwrap_or_default() + } + + /// The presets in a preset file (bad entries skipped; values clamped). + pub fn parse_file(text: &str) -> Result> { + let f: PresetFile = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("not a filter preset file: {e}")))?; + if f.format != FILE_FORMAT { + return Err(EngineError::Param(format!("not a filter preset file (its format is '{}')", f.format.chars().take(40).collect::()))); + } + if f.version > FILE_VERSION { + return Err(EngineError::Param(format!("this filter preset file is version {}, newer than this AniCraft reads ({FILE_VERSION})", f.version))); + } + Ok(f.presets.into_iter().take(MAX_PRESETS * 4).filter_map(|v| serde_json::from_value::(v).ok()).filter_map(FilterPreset::sanitized).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anicraft_doc::Filter; + + fn blur(b: f32) -> FilterEntry { + Filter::Blur { blur_x: b, blur_y: b, quality: 1 }.into() + } + + #[test] + fn saving_renaming_and_deleting() { + let mut lib = FilterLibrary::default(); + assert_eq!(lib.save(" Soft \n glow ", &[blur(4.0)]).unwrap(), ("Soft glow".to_string(), false)); + assert!(lib.save("soft GLOW", &[blur(8.0), blur(1e9)]).unwrap().1, "same name, case aside, replaces"); + assert_eq!(lib.presets().len(), 1); + assert_eq!(lib.presets()[0].filters[1], blur(anicraft_doc::MAX_BLUR), "values clamped"); + assert!(lib.save(" ", &[blur(1.0)]).is_err()); + assert!(lib.save("Empty", &[]).is_err(), "nothing to save"); + assert_eq!(lib.add_unique(FilterPreset { name: "soft glow".into(), filters: vec![blur(1.0)] }).unwrap(), "soft glow 2"); + assert_eq!(lib.rename("SOFT GLOW 2", "Haze").unwrap(), "Haze"); + assert!(lib.rename("Haze", "Soft Glow").is_err() && lib.rename("nope", "x").is_err() && lib.rename("Haze", " ").is_err()); + assert_eq!(lib.rename("haze", "HAZE").unwrap(), "HAZE", "a new case of its own name"); + assert_eq!(lib.find("haze").map(|p| p.filters.len()), Some(1)); + assert_eq!(lib.delete("haze").unwrap().name, "HAZE"); + assert!(lib.delete("haze").is_err()); + let long = "x".repeat(200); + assert_eq!(lib.save(&long, &[blur(1.0)]).unwrap().0.chars().count(), MAX_NAME); + } + + #[test] + fn preset_files_round_trip_and_reject_junk() { + let off = FilterEntry { filter: Filter::new("glow").unwrap(), enabled: false }; + let mine = vec![FilterPreset { name: "A".into(), filters: vec![blur(3.0), off] }, FilterPreset { name: "B".into(), filters: vec![Filter::new("bevel").unwrap().into()] }]; + let text = FilterLibrary::file_json(&mine); + assert!(text.contains("\"enabled\": false"), "a switched-off filter keeps its switch: {text}"); + assert_eq!(FilterLibrary::parse_file(&text).unwrap(), mine); + assert!(FilterLibrary::parse_file("{}").is_err()); + assert!(FilterLibrary::parse_file(r#"{"format": "anicraft-brushes", "version": 1, "presets": []}"#).is_err()); + assert!(FilterLibrary::parse_file(r#"{"format": "anicraft-filter-presets", "version": 99, "presets": []}"#).is_err()); + // Bad entries are skipped, values clamped, bare filters take their defaults. + let got = FilterLibrary::parse_file(r#"{"format": "anicraft-filter-presets", "version": 1, "presets": [7, {"name": ""}, {"name": "x", "filters": [{"type": "sparkle"}]}, {"name": "Old", "filters": [{"type": "blur", "blur_x": -4}, {"type": "glow"}]}]}"#).unwrap(); + assert_eq!(got.len(), 1); + assert_eq!(got[0].filters[0], Filter::Blur { blur_x: 0.0, blur_y: 5.0, quality: 1 }.into()); + assert!(matches!(got[0].filters[1], FilterEntry { filter: Filter::Glow { blur_x: 5.0, .. }, enabled: true })); + // Preferences: the library as a list, names made unique. + let lib = FilterLibrary::from_values(serde_json::from_str::>(&serde_json::to_string(&[mine[0].clone(), mine[0].clone()]).unwrap()).unwrap()); + assert_eq!(lib.presets().iter().map(|p| p.name.as_str()).collect::>(), ["A", "A 2"]); + assert_eq!(lib.clone().sanitized(), lib); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 772f9b19..ef0592cb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ mod cmds_warp; pub mod cmds_brush; mod cmds_camera; mod cmds_draw; +pub mod cmds_filter; pub mod cmds_ease; pub mod cmds_envelope; pub mod cmds_drop; @@ -31,6 +32,7 @@ pub mod cmds_raw; pub mod cmds_rawsub; mod cmds_rawpoints; pub mod brush_library; +pub mod filter_library; pub mod cmds_recent; pub mod cmds_template; mod cmds_recovery; @@ -165,6 +167,7 @@ pub fn commands() -> Vec { v.extend(find::specs()); v.extend(explorer::specs()); v.extend(cmds_brush::specs()); + v.extend(cmds_filter::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); v.extend(cmds_swatch::specs()); @@ -368,6 +371,11 @@ pub struct Session { /// The user's own brush presets (ADR 0068). Like recent files they belong to the session /// and survive New and Open; the desktop app keeps them in its preferences. pub brushes: brush_library::BrushLibrary, + /// The user's filter presets (ADR 0091). Like brushes they belong to the session and + /// survive New and Open; the desktop app keeps them in its preferences. + pub filter_presets: filter_library::FilterLibrary, + /// Copied filters (Copy Filters, ADR 0091), for Paste Filters. + pub filter_clipboard: Option>, /// The open envelope (ADR 0080): view state over the shapes it bends, like a gesture. pub(crate) envelope: Option, } @@ -442,6 +450,8 @@ impl Session { published: std::collections::BTreeSet::new(), recent: cmds_recent::RecentFiles::default(), brushes: brush_library::BrushLibrary::default(), + filter_presets: filter_library::FilterLibrary::default(), + filter_clipboard: None, envelope: None, } } @@ -526,9 +536,14 @@ impl Session { let plugins = std::mem::take(&mut self.plugins); let recent = std::mem::take(&mut self.recent); let brushes = std::mem::take(&mut self.brushes); + let filter_presets = std::mem::take(&mut self.filter_presets); + let filter_clipboard = self.filter_clipboard.take(); *self = Session::new(doc); self.recent = recent; self.brushes = brushes; + self.filter_presets = filter_presets; + // Like copied artwork, copied filters carry across to the next document. + self.filter_clipboard = filter_clipboard; // The clipboard survives New/Open, so artwork can move between documents. self.clipboard = clipboard; self.plugins = plugins; @@ -1131,6 +1146,8 @@ mod tests_shape_bone; #[cfg(test)] mod tests_warp; #[cfg(test)] +mod tests_filter; +#[cfg(test)] mod merge_tests; #[cfg(test)] mod raw_tests; diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index 635f9859..fb620bfe 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -184,6 +184,9 @@ fn every_command_namespace_has_a_plugin_policy() { "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), // Brushes (ADR 0068): list yes; your own brushes and brush set files no. "brush" => assert_eq!(verdict.is_ok(), c.id == "brush.preset_list", "{}", c.id), + // Filters (ADR 0091): the document's lists yes (and listing and applying presets); + // the clipboard, your presets and preset files no. + "filter" => assert_eq!(verdict.is_ok(), matches!(c.id, "filter.move" | "filter.enable" | "filter.remove" | "filter.preset_list" | "filter.preset_apply"), "{}", c.id), // Swatches (ADR 0078): document data yes, swatch files no. "swatch" => assert_eq!(verdict.is_ok(), !matches!(c.id, "swatch.import" | "swatch.export"), "{}", c.id), // Rulers, grid and guides (ADR 0076): a scene's guides yes, how you see and snap no. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3ea04387..1932f486 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2429,7 +2429,7 @@ fn bevel_and_gradient_filters_render_save_and_export() { // A gradient glow whose ramp ends in blue; its start stays transparent whatever is sent. run(&mut s, "element.set_filters", json!({"filters": [{"type": "gradient_glow", "blur_x": 0, "blur_y": 0, "distance": 0, "stops": [{"offset": 0, "color": "#ff00ffff"}, {"offset": 1, "color": "#0000ff"}]}]})); let ElementKind::Symbol { filters, .. } = &s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind else { panic!() }; - let Some(Filter::GradientGlow { stops, side: FilterSide::Outer, .. }) = filters.first() else { panic!("{filters:?}") }; + let Some(Filter::GradientGlow { stops, side: FilterSide::Outer, .. }) = filters.first().map(|e| &e.filter) else { panic!("{filters:?}") }; assert_eq!(stops[0].color.a, 0.0, "pinned transparent"); assert_eq!(px(&s, 150, 150), [1.0, 0.0, 0.0, 1.0]); assert!(s.execute("element.set_filters", &json!({"filters": [{"type": "gradient_bevel", "stops": vec![json!({"offset": 0.5, "color": "#ffffff"}); 16]}]})).is_err(), "too many stops"); diff --git a/crates/engine/src/tests_filter.rs b/crates/engine/src/tests_filter.rs new file mode 100644 index 00000000..8e9a2e33 --- /dev/null +++ b/crates/engine/src/tests_filter.rs @@ -0,0 +1,247 @@ +//! Filter lists (ADR 0091): order, on/off, copy and paste, presets, and tweened values. + +use super::*; +use anicraft_doc::{ElementKind, Filter, FilterEntry}; +use serde_json::json; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A red 100 × 100 movie clip at (100, 100), selected. +fn clip() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); + s +} + +fn list(s: &Session) -> Vec { + match &s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind { + ElementKind::Symbol { filters, .. } => filters.clone(), + _ => Vec::new(), + } +} + +fn kinds(s: &Session) -> Vec<(&'static str, bool)> { + list(s).iter().map(|e| (e.filter.label(), e.enabled)).collect() +} + +fn px(s: &Session, x: u32, y: u32) -> [f32; 4] { + anicraft_render::render_frame(&s.doc, s.frame, 1.0).unwrap().pixel(x, y).unwrap() +} + +#[test] +fn the_order_changes_the_pixels() { + // A green glow outside the box, then Adjust Color taking all the saturation: the glow + // turns grey. The other way round the glow is added after the colour is gone: green. + let mut s = clip(); + let glow = json!({"type": "glow", "blur_x": 0, "blur_y": 0, "color": "#00ff00", "strength": 1}); + let grey = json!({"type": "adjust_color", "saturation": -100}); + // A glow with no blur is the artwork's own outline: widen it with a blur instead. + let glow = { + let mut g = glow; + g["blur_x"] = json!(20); + g["blur_y"] = json!(20); + g["strength"] = json!(10); + g + }; + run(&mut s, "element.set_filters", json!({"filters": [glow, grey]})); + let [r, g, b, a] = px(&s, 96, 150); + assert!(a > 0.5 && (r - g).abs() < 0.02 && (g - b).abs() < 0.02, "glow then grey: a grey glow {:?}", [r, g, b, a]); + let inside_grey = px(&s, 150, 150); + run(&mut s, "filter.move", json!({"from": 1, "to": 0})); + assert_eq!(kinds(&s), [("Adjust Color", true), ("Glow", true)]); + let [r, g, b, a] = px(&s, 96, 150); + assert!(a > 0.5 && g > 0.9 && r < 0.05 && b < 0.05, "grey then glow: a green glow {:?}", [r, g, b, a]); + assert_eq!(px(&s, 150, 150), inside_grey, "the box is grey either way"); + // One undo step puts the order back. + s.undo().unwrap(); + assert_eq!(kinds(&s), [("Glow", true), ("Adjust Color", true)]); + // `to` past the end is the end; an index the list doesn't have is refused. + run(&mut s, "filter.move", json!({"from": 0, "to": 99})); + assert_eq!(kinds(&s), [("Adjust Color", true), ("Glow", true)]); + assert!(s.execute("filter.move", &json!({"from": 5, "to": 0})).is_err()); + assert!(s.execute("filter.move", &json!({"from": 0})).is_err()); +} + +#[test] +fn a_filter_switched_off_is_as_if_absent_and_keeps_its_settings() { + let blur = json!({"type": "blur", "blur_x": 6, "blur_y": 6}); + let glow = json!({"type": "glow", "blur_x": 12, "blur_y": 12, "color": "#0000ff", "strength": 3}); + let mut only = clip(); + run(&mut only, "element.set_filters", json!({"filters": [blur.clone()]})); + let mut off = clip(); + run(&mut off, "element.set_filters", json!({"filters": [blur, glow]})); + let both = anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap(); + run(&mut off, "filter.enable", json!({"index": 1, "enabled": false})); + assert_eq!(kinds(&off), [("Blur", true), ("Glow", false)]); + // The oracle, the SVG and the HTML page all see the list without it. + let a = anicraft_render::render_frame(&only.doc, 0, 1.0).unwrap(); + let b = anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap(); + assert_eq!(a.data, b.data, "off draws exactly as absent"); + assert_ne!(both.data, b.data, "the glow did draw when on"); + let svg = |s: &Session| anicraft_render::svg::to_svg(&anicraft_doc::evaluate(&s.doc, 0), &s.doc.stage); + assert_eq!(svg(&only), svg(&off)); + let html = |s: &Session| anicraft_render::html::movie(&s.doc, &Default::default()).json; + assert_eq!(html(&only), html(&off)); + // Its settings stay, and the file keeps the switch. + let Some(FilterEntry { filter: Filter::Glow { strength, blur_x, .. }, enabled: false }) = list(&off).get(1).cloned() else { panic!("{:?}", list(&off)) }; + assert_eq!((strength, blur_x), (3.0, 12.0)); + let text = crate::format::to_json(&off.doc).unwrap(); + assert!(text.contains("\"enabled\":false") || text.contains("\"enabled\": false"), "saved switched off"); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, off.doc, "round trip"); + // Back on: as before. + run(&mut off, "filter.enable", json!({"enabled": true})); + assert_eq!(anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap().data, both.data); + // All off, then removing one and all. + run(&mut off, "filter.enable", json!({"enabled": false})); + assert_eq!(anicraft_render::render_frame(&off.doc, 0, 1.0).unwrap().data, anicraft_render::render_frame(&clip().doc, 0, 1.0).unwrap().data, "all off is no filters"); + run(&mut off, "filter.remove", json!({"index": 0})); + assert_eq!(kinds(&off), [("Glow", false)]); + assert!(off.execute("filter.enable", &json!({"index": 3, "enabled": true})).is_err()); + assert!(off.execute("filter.enable", &json!({"index": 0})).is_err(), "enabled is required"); + run(&mut off, "filter.remove", json!({})); + assert!(list(&off).is_empty()); + assert!(off.execute("filter.remove", &json!({})).is_err(), "nothing to remove"); + // `element.set_filters` takes the switch too. + run(&mut off, "element.set_filters", json!({"filters": [{"type": "blur", "enabled": false}]})); + assert_eq!(kinds(&off), [("Blur", false)]); +} + +#[test] +fn graphics_take_no_filters() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "G"})); + for (id, p) in [("filter.enable", json!({"enabled": false})), ("filter.remove", json!({})), ("filter.move", json!({"from": 0, "to": 1})), ("filter.copy", json!({}))] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("movie clip"), "{id}: {e}"); + } +} + +#[test] +fn copy_and_paste_filters_between_instances() { + let mut s = clip(); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}, {"type": "glow", "enabled": false}]})); + let first = s.selection.on(s.layer); + assert!(s.execute("filter.paste", &json!({})).is_err(), "nothing copied yet"); + run(&mut s, "filter.copy", json!({})); + // A second clip with a bevel of its own. + run(&mut s, "draw.rect", json!({"x": 300, "y": 100, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Other", "kind": "movie_clip"})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "bevel"}]})); + let second = s.selection.on(s.layer); + assert_ne!(first, second); + run(&mut s, "filter.paste", json!({})); + let of = |s: &Session, id: anicraft_doc::ElementId| match &s.doc.timeline(s.scene).layers[0].keyframes[0].elements.iter().find(|e| e.id == id).unwrap().kind { + ElementKind::Symbol { filters, .. } => filters.iter().map(|e| (e.filter.label(), e.enabled)).collect::>(), + _ => Vec::new(), + }; + assert_eq!(of(&s, second[0]), [("Bevel", true), ("Blur", true), ("Glow", false)], "added after its own, switches kept"); + run(&mut s, "filter.paste", json!({"replace": true})); + assert_eq!(of(&s, second[0]), [("Blur", true), ("Glow", false)]); + // One filter; past the limit is refused, whole. + run(&mut s, "filter.copy", json!({"index": 1})); + run(&mut s, "filter.paste", json!({})); + assert_eq!(of(&s, second[0]).len(), 3); + for _ in 0..13 { + run(&mut s, "filter.paste", json!({})); + } + assert_eq!(of(&s, second[0]).len(), 16); + assert!(s.execute("filter.paste", &json!({})).is_err()); + assert!(s.execute("filter.copy", &json!({"index": 40})).is_err()); + // Copied filters carry across to another document, as copied artwork does. + s.replace_document(anicraft_doc::Document::default(), None); + assert_eq!(s.filter_clipboard.as_ref().map(Vec::len), Some(1)); +} + +#[test] +fn filter_presets_save_apply_rename_delete_and_round_trip() { + let mut s = clip(); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "drop_shadow", "distance": 9}, {"type": "blur", "enabled": false}]})); + assert!(s.execute("filter.preset_apply", &json!({"name": "Shadowed"})).is_err()); + let rev = s.revision; + let v = run(&mut s, "filter.preset_save", json!({"name": " Shadowed "})); + assert_eq!((v["name"].as_str(), v["replaced"].as_bool()), (Some("Shadowed"), Some(false))); + // Saving over it asks (the old one can't come back), and replaces when confirmed. + assert!(matches!(s.execute("filter.preset_save", &json!({"name": "shadowed"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "filter.preset_save", json!({"name": "shadowed", "filters": [{"type": "glow", "color": "#ff00ff"}, {"type": "blur", "enabled": false}], "confirm": true})); + assert_eq!(s.filter_presets.presets().len(), 1); + // Saving and listing are outside the document and its undo. + assert_eq!(s.revision, rev); + let listed = run(&mut s, "filter.preset_list", json!({})); + assert_eq!(listed["presets"][0]["filters"][1]["enabled"], json!(false)); + // Applying replaces the instance's filters (as Animate does), one undo step. + run(&mut s, "filter.preset_apply", json!({"name": "SHADOWED"})); + assert_eq!(kinds(&s), [("Glow", true), ("Blur", false)]); + s.undo().unwrap(); + assert_eq!(kinds(&s), [("Drop Shadow", true), ("Blur", false)]); + run(&mut s, "filter.preset_rename", json!({"name": "shadowed", "to": "Neon"})); + assert!(s.execute("filter.preset_rename", &json!({"name": "nope", "to": "x"})).is_err()); + // A file round trip, into a session that has a preset of that name already. + let dir = std::env::temp_dir().join(format!("anicraft-filter-presets-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("presets.json"); + let _ = std::fs::remove_file(&path); + run(&mut s, "filter.preset_export", json!({"path": path.display().to_string()})); + assert!(matches!(s.execute("filter.preset_export", &json!({"path": path.display().to_string()})), Err(EngineError::NeedsConfirmation(_))), "replacing the file asks"); + let mut other = Session::default(); + run(&mut other, "filter.preset_save", json!({"name": "neon", "filters": [{"type": "blur"}]})); + let v = run(&mut other, "filter.preset_import", json!({"path": path.display().to_string()})); + assert_eq!(v["imported"], json!(["Neon 2"])); + assert_eq!(other.filter_presets.find("neon 2").map(|p| p.filters.clone()), s.filter_presets.find("neon").map(|p| p.filters.clone())); + std::fs::write(dir.join("junk.json"), "{\"format\": \"anicraft-brushes\"}").unwrap(); + assert!(other.execute("filter.preset_import", &json!({"path": dir.join("junk.json").display().to_string()})).is_err()); + // Deleting asks (it can't be undone); the artwork keeps the filters it got. + run(&mut s, "filter.preset_apply", json!({"name": "neon"})); + assert!(matches!(s.execute("filter.preset_delete", &json!({"name": "neon"})), Err(EngineError::NeedsConfirmation(_)))); + run(&mut s, "filter.preset_delete", json!({"name": "neon", "confirm": true})); + assert!(s.filter_presets.is_empty()); + assert_eq!(kinds(&s), [("Glow", true), ("Blur", false)]); + assert!(s.execute("filter.preset_export", &json!({"path": dir.join("none.json").display().to_string()})).is_err(), "nothing to export"); + // Presets survive New and Open, like brushes. + run(&mut s, "filter.preset_save", json!({"name": "Keep"})); + s.replace_document(anicraft_doc::Document::default(), None); + assert!(s.filter_presets.find("keep").is_some()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn classic_tweens_carry_blur_and_glow_to_their_midpoint() { + // Blur 0 → 20 and a glow's strength 0 → 200 %, over a linear tween of 10 frames. + let mut s = clip(); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 0, "blur_y": 0}, {"type": "glow", "strength": 0, "color": "#0000ff"}]})); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 20, "blur_y": 20}, {"type": "glow", "strength": 2, "color": "#0000ff"}]})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_tween", json!({"easing": "Linear"})); + let dl = anicraft_doc::evaluate(&s.doc, 5); + let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group"); + assert_eq!(g.filters.len(), 2); + assert!(matches!(g.filters[0], Filter::Blur { blur_x, blur_y, .. } if (blur_x - 10.0).abs() < 1e-4 && (blur_y - 10.0).abs() < 1e-4), "{:?}", g.filters[0]); + assert!(matches!(g.filters[1], Filter::Glow { strength, .. } if (strength - 1.0).abs() < 1e-4), "{:?}", g.filters[1]); + // The midpoint renders as a still instance with the midpoint's values. + let mut still = clip(); + run(&mut still, "element.set_filters", json!({"filters": [{"type": "blur", "blur_x": 10, "blur_y": 10}, {"type": "glow", "strength": 1, "color": "#0000ff"}]})); + assert_eq!(anicraft_render::render_frame(&s.doc, 5, 1.0).unwrap().data, anicraft_render::render_frame(&still.doc, 0, 1.0).unwrap().data); + // A filter switched off on the first keyframe stays off through the tween, values travelling. + s.set_frame(0); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "filter.enable", json!({"index": 1, "enabled": false})); + let dl = anicraft_doc::evaluate(&s.doc, 5); + let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group"); + assert_eq!(g.filters.len(), 1, "only the blur draws"); + // Reordered on one keyframe, the lists no longer pair up: the first keyframe's holds. + run(&mut s, "filter.move", json!({"from": 1, "to": 0})); + let dl = anicraft_doc::evaluate(&s.doc, 5); + let g = dl.groups.iter().find(|g| !g.filters.is_empty()).expect("a filtered group"); + assert!(matches!(g.filters[0], Filter::Blur { blur_x, .. } if blur_x == 0.0), "{:?}", g.filters); +} diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index 770e4d19..881ab0fa 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -115,13 +115,13 @@ fn filtered() -> Document { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { if let ElementKind::Symbol { filters, .. } = &mut Arc::make_mut(e).kind { - *filters = match i { + *filters = Vec::from_iter(match i { 0 => vec![ Filter::DropShadow { blur_x: 8.0, blur_y: 8.0, strength: 0.8, quality: 2, angle: 45.0, distance: 10.0, color: Rgba::BLACK, inner: false, knockout: false, hide_object: false }, Filter::Bevel { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 4.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side: FilterSide::Inner, knockout: false }, ], _ => vec![Filter::Glow { blur_x: 12.0, blur_y: 12.0, strength: 1.4, quality: 2, color: Rgba::new(1.0, 0.85, 0.2, 1.0), inner: false, knockout: false }], - }; + }.into_iter().map(anicraft_doc::FilterEntry::from)); } } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index ca847d49..e74a607e 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1103,10 +1103,10 @@ fn filtered_sample() -> anicraft_doc::Document { for k in &mut l.keyframes { for e in &mut Arc::make_mut(k).elements { if let ElementKind::Symbol { filters, .. } = &mut Arc::make_mut(e).kind { - *filters = match i { + *filters = Vec::from_iter(match i { 0 => vec![F::DropShadow { blur_x: 8.0, blur_y: 8.0, strength: 0.8, quality: 2, angle: 45.0, distance: 10.0, color: Rgba::BLACK, inner: false, knockout: false, hide_object: false }, F::Bevel { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 4.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side: anicraft_doc::FilterSide::Inner, knockout: false }], _ => vec![F::Glow { blur_x: 12.0, blur_y: 12.0, strength: 1.4, quality: 2, color: Rgba::new(1.0, 0.85, 0.2, 1.0), inner: false, knockout: false }], - }; + }.into_iter().map(anicraft_doc::FilterEntry::from)); } } } diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 961e35fc..639f8940 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -676,9 +676,11 @@ impl<'a> Bake<'a> { } // Filters run in the page as the renderer runs them (ADR 0072): `fx` the list, // `fm` how far they reach together (stage pixels). - if !filters.is_empty() { - o.insert("fx".into(), Value::Array(filters.iter().map(filter_json).collect())); - o.insert("fm".into(), exact(filters.iter().map(anicraft_doc::Filter::margin).sum::())); + // Filters switched off are left out, as the renderer leaves them (ADR 0091). + let on = anicraft_doc::active_filters(filters); + if !on.is_empty() { + o.insert("fx".into(), Value::Array(on.iter().map(filter_json).collect())); + o.insert("fm".into(), exact(on.iter().map(anicraft_doc::Filter::margin).sum::())); } if !events.is_empty() { o.insert("ev".into(), Value::Array(events.iter().map(|h| json!([h.event.key(), actions(&h.actions)])).collect())); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index f1246cbf..724e32f9 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -537,7 +537,7 @@ fn what_does_not_carry_across_is_reported() { let l = Arc::make_mut(&mut tl.layers[2]); let k = l.keyframe_mut(0).unwrap(); if let ElementKind::Symbol { filters, blend, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind { - filters.push(anicraft_doc::Filter::Blur { blur_x: 4.0, blur_y: 4.0, quality: 1 }); + filters.push(anicraft_doc::Filter::Blur { blur_x: 4.0, blur_y: 4.0, quality: 1 }.into()); *blend = BlendMode::Subtract; } Arc::make_mut(&mut tl.layers[0]).keyframe_mut(1).unwrap().script = Some(FrameScript::Plugin(PluginScript { id: "org.example.menu".into(), entry: "main".into() })); @@ -1102,7 +1102,7 @@ fn filtered_doc(filters: &[anicraft_doc::Filter]) -> Document { d.library.push(symbol(300, SymbolKind::MovieClip, vec![layer(301, vec![kf(0, 1, vec![el(302, a), el(303, b)], vec![], "")])])); let mut i = (*inst(310, 300, "art", Affine::translate(18.4, 15.2), vec![])).clone(); if let ElementKind::Symbol { filters: f, .. } = &mut i.kind { - *f = filters.to_vec(); + *f = filters.iter().cloned().map(Into::into).collect(); } Arc::make_mut(&mut d.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = vec![Arc::new(i)]; d diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 4b1a2a3f..bac5d908 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -24,7 +24,7 @@ use crate::edges::{self, Edge}; use crate::xml::{self, Element as X}; use anicraft_doc::{ - Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, ColorTransform, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, + Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, ColorTransform, Filter, FilterEntry, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, CustomEase, EaseGroup, FrameScript, FrameSound, Language, Linkage, ScaleGrid, SoundSync, SourceScript, Spread, MAX_FOCAL, }; use anicraft_doc::sound::{EnvelopePoint, SoundEffect, clean_points}; @@ -444,14 +444,13 @@ impl<'a> Builder<'a> { out.push(self.element(ElementKind::Shape(shape), parent.mul(&matrix(el)).mul(&fit), ColorEffect::default())); } - /// An instance's filters, by Animate's element names; switched-off filters are left out, - /// and unknown ones reported. - fn filters(&mut self, el: &X) -> Vec { + /// An instance's filters, by Animate's element names, in order; switched-off filters + /// (`enabled="false"`) come in switched off with their settings (ADR 0091), and unknown ones + /// are reported. + fn filters(&mut self, el: &X) -> Vec { let mut out = Vec::new(); for f in el.list("filters") { - if f.bool("enabled") == Some(false) { - continue; - } + let enabled = f.bool("enabled") != Some(false); let num = |k: &str, d: f32| f.f32(k).unwrap_or(d); let flag = |k: &str| f.bool(k).unwrap_or(false); let quality = f.u32("quality").unwrap_or(1).clamp(1, 3) as u8; @@ -498,7 +497,7 @@ impl<'a> Builder<'a> { continue; } }; - out.push(filter.sanitized()); + out.push(FilterEntry { filter: filter.sanitized(), enabled }); } out } diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 29a4f9ae..a0ea750d 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -151,8 +151,12 @@ fn symbols_instances_and_the_tween_between_them() { let sym = &doc.library[0]; assert_eq!((sym.name.as_str(), sym.kind), ("Ball", SymbolKind::MovieClip)); let inst = &doc.timeline(0).layers[0].keyframes[0].elements[0]; - let ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } = &inst.kind else { panic!("an instance") }; + let ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters: entries, .. } = &inst.kind else { panic!("an instance") }; assert_eq!(*blend, anicraft_doc::BlendMode::HardLight, "Animate's blend mode names"); + // In order; the switched-off glow comes in switched off, keeping its place (ADR 0091). + assert_eq!(entries.iter().map(|e| e.enabled).collect::>(), [true, true, false, true, true, true]); + assert!(matches!(entries[2].filter, anicraft_doc::Filter::Glow { .. })); + let filters: Vec = entries.iter().filter(|e| e.enabled).map(|e| e.filter.clone()).collect(); assert_eq!(filters.len(), 5, "{filters:?}"); assert!(matches!(filters[0], anicraft_doc::Filter::DropShadow { distance, inner: false, .. } if distance == 8.0)); assert!(matches!(filters[1], anicraft_doc::Filter::Blur { blur_x, quality: 2, .. } if blur_x == 10.0)); From 58d5498b98a2b28fe53474ff18f10d23e73d79d8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 19:18:58 -0700 Subject: [PATCH 3/5] feat(app): filter list with grips, on/off switches, presets and copy/paste in Properties (M5) --- src/app.rs | 10 +- src/panels.rs | 288 +++++++++++++++++++++++++++++++++++++++++++++--- src/platform.rs | 3 +- src/prefs.rs | 15 +++ 4 files changed, 298 insertions(+), 18 deletions(-) diff --git a/src/app.rs b/src/app.rs index 21fa6d6a..08982925 100644 --- a/src/app.rs +++ b/src/app.rs @@ -427,6 +427,8 @@ pub struct App { pub brush_clock: f64, /// Window › Brush Library and the brush pickers (ADR 0068). pub brush_lib: crate::brush_panel::BrushLibraryView, + /// A filter preset being named in Properties (ADR 0091). + pub filter_naming: crate::panels::FilterNaming, pub brush_samples: Vec<(anicraft_engine::geom::Vec2, Option)>, pub pen_pressure: Option, /// Eraser tool options (ADR 0034); its stroke's samples are `brush_samples`. @@ -633,6 +635,7 @@ impl App { // Open Recent is the session's list, kept in the preferences (ADR 0059). session.recent = prefs.recent.clone(); session.brushes = prefs.brushes.clone(); + session.filter_presets = prefs.filter_presets.clone(); // Whether rulers, grid and guides show and snap carries over between sessions (ADR 0076). session.aids = prefs.aids; // The editor draws as Animate does: merge drawing, until Object Drawing (J) is switched on. @@ -695,6 +698,7 @@ impl App { paint_brush: crate::brushtool::BrushOptions::paint_brush(), brush_clock: 0.0, brush_lib: crate::brush_panel::BrushLibraryView::default(), + filter_naming: Default::default(), brush_samples: Vec::new(), pen_pressure: None, eraser: crate::erasertool::EraserOptions::default(), @@ -2806,13 +2810,16 @@ impl App { // A brush set (ADR 0068): your brushes as a small JSON file. "brush.preset_export" => Some((tr_noop!("Export your brushes (a brush set file)"), "path", "brushes.json".to_string())), "brush.preset_import" => Some((tr_noop!("Import brushes (a brush set file)"), "path", "brushes.json".to_string())), + // Filter presets (ADR 0091): yours as a small JSON file. + "filter.preset_export" => Some((tr_noop!("Export your filter presets (a preset file)"), "path", "filter-presets.json".to_string())), + "filter.preset_import" => Some((tr_noop!("Import filter presets (a preset file)"), "path", "filter-presets.json".to_string())), // The document's swatches (ADR 0078): a swatch file, or a GIMP palette to import. "swatch.export" => Some((tr_noop!("Export swatches (a swatch file)"), "path", "swatches.json".to_string())), "swatch.import" => Some((tr_noop!("Import swatches (a swatch file or a GIMP palette)"), "path", "swatches.json".to_string())), _ => None, }; if let Some((title, key, text)) = prompt { - let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "plugin.install" | "brush.preset_export" | "brush.preset_import" | "swatch.export" | "swatch.import")); + let is_file = matches!(key, "path" | "dir") && (id.starts_with("file.") || matches!(id, "plugin.install" | "brush.preset_export" | "brush.preset_import" | "filter.preset_export" | "filter.preset_import" | "swatch.export" | "swatch.import")); if is_file && platform::WEB && platform::reads_file(id) { // The browser's file picker (ADR 0036). The file arrives on a later frame // (`open_picked`); a save or export asks for the download's name below. @@ -3595,6 +3602,7 @@ impl App { // Open Recent changed (an open, a save, a pin): into the preferences. crate::recent::sync(self); crate::brush_panel::sync(self); + crate::panels::sync_filter_presets(self); crate::rulers::sync(self); // A browser asks before leaving a page with unsaved work (its close guard). platform::set_unsaved(self.s.is_dirty()); diff --git a/src/panels.rs b/src/panels.rs index 368ead51..6de60760 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -1269,40 +1269,251 @@ fn instance_rows(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::Ele ui.add_space(4.0); } -/// The Filters rows of a movie clip or button instance: an Add menu, then each filter's values -/// with a remove button. Every change replaces the list (`element.set_filters`), one undo step -/// per gesture. -fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc::Filter], differs: bool) { - use anicraft_engine::doc::Filter; +/// Naming a filter preset in Properties (ADR 0091): saving the list under a new name, or +/// renaming one. +#[derive(Clone, Debug, Default)] +pub(crate) struct FilterNaming { + /// The name typed so far, and the preset being renamed (`None`: saving a new one). + pub name: Option<(String, Option)>, +} + +/// Copies the session's filter presets into the preferences when a command changed them, and +/// saves them (not in screenshot or test runs, which never write the user's preferences). +pub fn sync_filter_presets(app: &mut App) { + if app.s.filter_presets == app.prefs.filter_presets { + return; + } + app.prefs.filter_presets = app.s.filter_presets.clone(); + if app.shot.is_none() + && let Err(e) = app.prefs.save() + { + app.status_err(tr!("Could not save preferences: {e}", e = e)); + } +} + +/// What the filter list was asked to do this frame (done after drawing it), each one command. +enum FilterAct { + Move(usize, usize), + Enable(Option, bool), + Remove(Option), + Copy(Option), + Paste, + Apply(String), + Delete(String), +} + +/// A filter's grip: drag it up or down the list to reorder, or, focused, Alt+Up and Alt+Down +/// move it. +fn filter_grip(ui: &mut egui::Ui, fname: &str, i: usize, n: usize, act: &mut Option) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(vec2(14.0, crate::theme::TARGET), Sense::click_and_drag()); + let hot = resp.hovered() || resp.dragged() || resp.has_focus(); + let c = if hot { T.icon_hot } else { T.text_faint }; + for (dx, dy) in [(-2.5, -5.0), (2.5, -5.0), (-2.5, 0.0), (2.5, 0.0), (-2.5, 5.0), (2.5, 5.0)] { + ui.painter().circle_filled(rect.center() + vec2(dx, dy), 1.4, c); + } + if resp.has_focus() { + ui.painter().rect_stroke(rect.expand(1.0), 2.0, Stroke::new(1.0, T.text), StrokeKind::Outside); + let (up, down, alt) = ui.input(|inp| (inp.key_pressed(egui::Key::ArrowUp), inp.key_pressed(egui::Key::ArrowDown), inp.modifiers.alt)); + if alt { + ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, egui::EventFilter { vertical_arrows: true, ..Default::default() })); + if up && i > 0 { + *act = Some(FilterAct::Move(i, i - 1)); + } else if down && i + 1 < n { + *act = Some(FilterAct::Move(i, i + 1)); + } + } + } + let (up, down) = (crate::platform::shortcut_label("Alt+Up"), crate::platform::shortcut_label("Alt+Down")); + a11y::control(ui, &resp, WidgetType::Button, &tr!("Move {filter}: drag, or {up} and {down}", filter = fname, up = up.as_str(), down = down.as_str()), None); + resp.on_hover_text(tr!("Drag to change the order (filters apply from the top down)")) +} + +/// The Filters rows of a movie clip or button instance, as Animate's Filters section: Add, +/// Presets and an options menu (copy, paste, all on or off, remove all), then each filter with +/// its grip (drag, or Alt+arrows, to reorder), its on/off switch, its name and Remove, and its +/// values. A filter switched off keeps its values. Value changes replace the list +/// (`element.set_filters`, one undo step per gesture); the rest are `filter.*` commands. +fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc::FilterEntry], differs: bool) { + use anicraft_engine::doc::{Filter, FilterEntry}; // As the renderer sees them (a file may hold values or ramps a command would refuse). - let mut list: Vec = current.iter().map(Filter::sanitized).collect(); + let mut list: Vec = current.iter().map(FilterEntry::sanitized).collect(); + let n = list.len(); let mut changed: Option<&'static str> = None; + let mut act: Option = None; + let presets: Vec<(String, String)> = app.s.filter_presets.presets().iter().map(|p| (p.name.clone(), p.filters.iter().map(|f| crate::i18n::t(f.filter.label())).collect::>().join(", "))).collect(); + let copied = app.s.filter_clipboard.as_ref().map_or(0, Vec::len); + let mut naming = app.filter_naming.name.clone(); row_prose(ui, tr!("Filters"), |ui| { egui::ComboBox::from_id_salt("add_filter").selected_text(if list.is_empty() { tr!("None") } else { tr!("Add filter") }).show_ui(ui, |ui| { for (kind, label) in Filter::KINDS { if ui.selectable_label(false, crate::i18n::t(label)).clicked() && let Some(f) = Filter::new(kind) { - list.push(f); + list.push(f.into()); changed = Some(tr_noop!("Add filter")); } } }) .response .set_name(tr!("Add filter")); + let pr = crate::timeline::icon_button(ui, tr!("Filter presets: apply, save, rename, delete, import, export"), None, Icon::Folder); + egui::Popup::menu(&pr).id(egui::Id::new("anicraft.filters.presets")).show(|ui| { + if presets.is_empty() { + ui.label(text(Type::Caption, tr!("No presets yet. Set up filters, then Save as Preset."))); + } + for (name, what) in &presets { + if ui.button(name.as_str()).on_hover_text(tr!("Apply: {filters} (replaces the filters)", filters = what.as_str())).clicked() { + act = Some(FilterAct::Apply(name.clone())); + } + } + ui.separator(); + if ui.add_enabled(n > 0, egui::Button::new(tr!("Save as Preset…"))).on_hover_text(tr!("Keep these filters under a name, for any document")).clicked() { + naming = Some((String::new(), None)); + } + ui.add_enabled_ui(!presets.is_empty(), |ui| { + ui.menu_button(tr!("Rename Preset"), |ui| { + for (name, _) in &presets { + if ui.button(name.as_str()).clicked() { + naming = Some((name.clone(), Some(name.clone()))); + } + } + }); + ui.menu_button(tr!("Delete Preset"), |ui| { + for (name, _) in &presets { + if ui.button(name.as_str()).clicked() { + act = Some(FilterAct::Delete(name.clone())); + } + } + }); + }); + ui.separator(); + if ui.button(tr!("Import Presets…")).on_hover_text(tr!("Add the presets in a filter preset file (.json)")).clicked() { + app.invoke("filter.preset_import"); + } + if ui.add_enabled(!presets.is_empty(), egui::Button::new(tr!("Export Presets…"))).on_hover_text(tr!("Write your filter presets to a file, to use on another computer")).clicked() { + app.invoke("filter.preset_export"); + } + }); + let more = crate::timeline::icon_button(ui, tr!("Filter options: copy, paste, enable, disable, remove"), None, Icon::Ellipsis); + egui::Popup::menu(&more).id(egui::Id::new("anicraft.filters.menu")).show(|ui| { + if ui.add_enabled(n > 0, egui::Button::new(tr!("Copy All Filters"))).clicked() { + act = Some(FilterAct::Copy(None)); + } + let paste = if copied == 0 { tr!("Paste Filters").to_string() } else { trn!("Paste {n} Filter", "Paste {n} Filters", copied as u64, n = copied) }; + if ui.add_enabled(copied > 0, egui::Button::new(paste)).on_hover_text(tr!("Add the copied filters after these")).clicked() { + act = Some(FilterAct::Paste); + } + ui.separator(); + if ui.add_enabled(list.iter().any(|f| !f.enabled), egui::Button::new(tr!("Enable All"))).clicked() { + act = Some(FilterAct::Enable(None, true)); + } + if ui.add_enabled(list.iter().any(|f| f.enabled), egui::Button::new(tr!("Disable All"))).clicked() { + act = Some(FilterAct::Enable(None, false)); + } + if ui.add_enabled(n > 0, egui::Button::new(tr!("Remove All"))).clicked() { + act = Some(FilterAct::Remove(None)); + } + }); mixed(ui, differs); }); + // Naming a preset, inline: Enter saves, Escape cancels. + if let Some((buf, renaming)) = naming.as_mut() { + let mut done: Option = None; + let rename = renaming.is_some(); + row_prose(ui, if rename { tr!("Rename") } else { tr!("Preset") }, |ui| { + let r = ui.add(egui::TextEdit::singleline(buf).desired_width(120.0).hint_text(tr!("Name"))).named(tr!("Filter preset name")); + if !r.has_focus() && !r.lost_focus() && buf.is_empty() { + r.request_focus(); + } + let (enter, esc) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape))); + let ok = !buf.trim().is_empty(); + if ui.add_enabled(ok, egui::Button::new(if rename { tr!("Rename") } else { tr!("Save") })).clicked() || (enter && r.lost_focus() && ok) { + done = Some(true); + } else if ui.button(tr!("Cancel")).clicked() || esc { + done = Some(false); + } + }); + match done { + Some(true) => { + let to = buf.trim().to_string(); + let ok = match renaming.clone() { + Some(from) => app.run("filter.preset_rename", json!({"name": from, "to": to})).is_some(), + None => { + // Asks first when it would replace a preset of that name. + app.request("filter.preset_save", json!({"name": to})); + true + } + }; + if ok { + naming = None; + } + } + Some(false) => naming = None, + None => {} + } + } + app.filter_naming.name = naming; let quality_names = [tr!("Low"), tr!("Medium"), tr!("High")]; - let mut remove = None; - for (i, f) in list.iter_mut().enumerate() { + // Dragging a filter by its grip: which one, and where each header row starts (last frame's, + // for the drop: rows don't move while one is dragged). + let drag_id = egui::Id::new("anicraft.filters.drag"); + let mut dragging: Option = ui.data(|d| d.get_temp(drag_id)); + let last_tops: Vec = ui.data(|d| d.get_temp(drag_id.with("tops"))).unwrap_or_default(); + let drop_at = |y: f32| last_tops.iter().take(n).rposition(|t| y >= *t).unwrap_or(0); + let mut tops: Vec = Vec::with_capacity(n + 1); + let (list_left, list_w) = (ui.cursor().left(), ui.available_width()); + for (i, entry) in list.iter_mut().enumerate() { // Screen readers hear which filter a value belongs to: "Drop Shadow blur X". - let fname = crate::i18n::t(f.label()); + let fname = crate::i18n::t(entry.filter.label()); + let on = entry.enabled; ui.push_id(("filter", i), |ui| { - row_prose(ui, fname, |ui| { - if ui.small_button(tr!("Remove")).named(&tr!("Remove {filter}", filter = fname)).on_hover_text(tr!("Remove this filter")).clicked() { - remove = Some(i); + tops.push(ui.cursor().top()); + let header = ui.horizontal(|ui| { + let grip = filter_grip(ui, fname, i, n, &mut act); + let tip = if on { tr!("Turn {filter} off (it keeps its settings)", filter = fname) } else { tr!("Turn {filter} on", filter = fname) }; + if crate::timeline::icon_button(ui, &tip, Some(on), if on { Icon::Eye } else { Icon::EyeOff }).clicked() { + act = Some(FilterAct::Enable(Some(i), !on)); + } + let name = if on { text(Type::Label, fname) } else { text(Type::Label, tr!("{filter} (off)", filter = fname)).color(T.text_faint) }; + ui.label(name); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::timeline::icon_button(ui, &tr!("Remove {filter}", filter = fname), None, Icon::Trash).clicked() { + act = Some(FilterAct::Remove(Some(i))); + } + }); + grip + }); + let grip = header.inner; + if grip.drag_started() { + dragging = Some(i); + } + if grip.drag_stopped() && dragging == Some(i) { + dragging = None; + if let Some(p) = ui.ctx().pointer_interact_pos() + && drop_at(p.y) != i + { + act = Some(FilterAct::Move(i, drop_at(p.y))); + } + } + header.response.context_menu(|ui| { + if ui.add_enabled(i > 0, egui::Button::new(tr!("Move Up"))).clicked() { + act = Some(FilterAct::Move(i, i - 1)); + } + if ui.add_enabled(i + 1 < n, egui::Button::new(tr!("Move Down"))).clicked() { + act = Some(FilterAct::Move(i, i + 1)); + } + ui.separator(); + if ui.button(if on { tr!("Turn Off") } else { tr!("Turn On") }).clicked() { + act = Some(FilterAct::Enable(Some(i), !on)); + } + if ui.button(tr!("Copy Filter")).clicked() { + act = Some(FilterAct::Copy(Some(i))); + } + if ui.button(tr!("Remove Filter")).clicked() { + act = Some(FilterAct::Remove(Some(i))); } }); + let f = &mut entry.filter; let blur_rows = |ui: &mut egui::Ui, bx: &mut f32, by: &mut f32, quality: &mut u8, changed: &mut Option<&'static str>| { row(ui, tr!("Blur"), |ui| { let a = ui.add(egui::DragValue::new(bx).prefix("X ").suffix(" px").speed(0.25).range(0.0..=255.0).max_decimals(1)).named(&tr!("{filter} blur X", filter = fname)); @@ -1384,9 +1595,54 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc } }); } - if let Some(i) = remove { - list.remove(i); - changed = Some(tr_noop!("Remove filter")); + // Where the rows are, for the next frame's drop, and the drop mark while one is dragged: + // a bar where it would land. + tops.push(ui.cursor().top()); + ui.data_mut(|d| d.insert_temp(drag_id.with("tops"), tops.clone())); + if let (Some(from), Some(p)) = (dragging, ui.ctx().pointer_interact_pos()) + && ui.ctx().dragged_id().is_some() + { + let to = drop_at(p.y); + if to != from + && let Some(y) = tops.get(if to > from { to + 1 } else { to }).copied() + { + ui.painter().line_segment([pos2(list_left, y), pos2(list_left + list_w, y)], Stroke::new(2.0, T.accent)); + } + } else if ui.ctx().dragged_id().is_none() { + dragging = None; + } + ui.data_mut(|d| match dragging { + Some(v) => { + d.insert_temp(drag_id, v); + } + None => d.remove::(drag_id), + }); + if let Some(a) = act { + match a { + FilterAct::Move(from, to) => { + app.run("filter.move", json!({"from": from, "to": to})); + } + FilterAct::Enable(index, on) => { + app.run("filter.enable", json!({"index": index, "enabled": on})); + } + FilterAct::Remove(index) => { + app.run("filter.remove", json!({"index": index})); + } + FilterAct::Copy(index) => { + if let Some(v) = app.run("filter.copy", json!({"index": index})) { + let k = v["copied"].as_u64().unwrap_or(0); + app.status_ok(trn!("Copied {n} filter.", "Copied {n} filters.", k, n = k)); + } + } + FilterAct::Paste => { + app.run("filter.paste", json!({})); + } + FilterAct::Apply(name) => { + app.run("filter.preset_apply", json!({"name": name})); + } + FilterAct::Delete(name) => app.request("filter.preset_delete", json!({"name": name})), + } + return; } if let Some(label) = changed && let Ok(v) = serde_json::to_value(&list) diff --git a/src/platform.rs b/src/platform.rs index 10ccc051..6cbe15c2 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -692,6 +692,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { "file.open" => (tr_noop!("Documents"), &["anicraft", "fla", "xfl"]), "plugin.install" => (tr_noop!("WebAssembly plug-in"), &["wasm"]), "brush.preset_export" | "brush.preset_import" => (tr_noop!("Brush set"), &["json"]), + "filter.preset_export" | "filter.preset_import" => (tr_noop!("Filter preset file"), &["json"]), "swatch.export" => (tr_noop!("Swatch file"), &["json"]), "swatch.import" => (tr_noop!("Swatch file or GIMP palette"), &["json", "gpl"]), _ => (tr_noop!("AniCraft document"), &["anicraft"]), @@ -700,7 +701,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { /// Commands that read a file the user picks (the others write one, or a folder of them). pub fn reads_file(cmd: &str) -> bool { - matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library" | "brush.preset_import" | "swatch.import") + matches!(cmd, "file.open" | "plugin.install" | "file.import" | "file.import_to_library" | "brush.preset_import" | "filter.preset_import" | "swatch.import") } /// Shows the platform's own dialog (Windows common dialog, macOS panel, Linux XDG portal), with diff --git a/src/prefs.rs b/src/prefs.rs index 3d4ff57c..6971b23d 100644 --- a/src/prefs.rs +++ b/src/prefs.rs @@ -151,6 +151,9 @@ pub struct Prefs { /// Brushes of your own (ADR 0068), for the Brush and the Paint Brush. #[serde(deserialize_with = "lenient_brushes")] pub brushes: anicraft_engine::brush_library::BrushLibrary, + /// Filter presets of your own (ADR 0091), for movie clips and buttons in any document. + #[serde(deserialize_with = "lenient_filter_presets")] + pub filter_presets: anicraft_engine::filter_library::FilterLibrary, /// Test Movie plays in a window of its own (ADR 0062); off, or where a system can't open /// one, it floats inside the editor. pub test_movie_window: bool, @@ -225,6 +228,7 @@ impl Default for Prefs { recent: Default::default(), start_screen: true, brushes: Default::default(), + filter_presets: Default::default(), test_movie_window: true, test_movie_pos: None, workspaces: crate::dock::Workspaces::default(), @@ -256,6 +260,16 @@ fn lenient_brushes<'de, D: serde::Deserializer<'de>>(d: D) -> Result>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + let list: Vec = match v { + serde_json::Value::Array(a) => a, + _ => Vec::new(), + }; + Ok(anicraft_engine::filter_library::FilterLibrary::from_values(list)) +} + /// Autosave intervals offered in Preferences: `(seconds, label)`. pub const AUTOSAVE_INTERVALS: [(u32, &str); 5] = [(30, tr_noop!("30 seconds")), (60, tr_noop!("1 minute")), (120, tr_noop!("2 minutes")), (300, tr_noop!("5 minutes")), (600, tr_noop!("10 minutes"))]; pub const AUTOSAVE_SECS_RANGE: std::ops::RangeInclusive = 15..=600; @@ -324,6 +338,7 @@ impl Prefs { .collect(); self.recent = std::mem::take(&mut self.recent).sanitized(); self.brushes = std::mem::take(&mut self.brushes).sanitized(); + self.filter_presets = std::mem::take(&mut self.filter_presets).sanitized(); self.test_movie_pos = self.test_movie_pos.filter(|[x, y]| x.is_finite() && y.is_finite() && x.abs() < 1e5 && y.abs() < 1e5); self } From 2284f883ec0e612dbf91f89b5c648e04cab29b19 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 19:22:19 -0700 Subject: [PATCH 4/5] feat(app): the filters screenshot shows a switched-off filter and a preset of your own (M5) --- src/app.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/app.rs b/src/app.rs index 08982925..5deceff5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1474,18 +1474,25 @@ impl App { self.run("draw.rect", json!({"x": 640, "y": 500, "w": 300, "h": 180, "fill": "#f3d36b", "stroke": "#3d8bfd", "stroke_width": 6, "cap": "none", "join": "miter", "dash": [18, 8], "object": true})); } Some("filters") => { - // A movie clip with a bevel and a gradient glow, selected: Properties › Filters - // shows both (scrolled to the glow's ramp editor). + // A movie clip with a drop shadow switched off, a bevel and a gradient glow, + // selected, and a filter preset of your own: Properties › Filters shows the list + // with its grips and switches (ADR 0091), and the glow's ramp editor. self.run("draw.rect", json!({"x": 960, "y": 470, "w": 200, "h": 130, "fill": "#e8553b", "stroke": null})); self.run("modify.convert_to_symbol", json!({"name": "Badge"})); self.run("symbol.set_kind", json!({"kind": "movie_clip"})); self.run( "element.set_filters", json!({"filters": [ + {"type": "drop_shadow", "blur_x": 10, "blur_y": 10, "distance": 8, "enabled": false}, {"type": "bevel", "blur_x": 8, "blur_y": 8, "distance": 6, "strength": 1.2, "quality": 2}, {"type": "gradient_glow", "blur_x": 28, "blur_y": 28, "quality": 2, "distance": 0, "stops": [{"offset": 0, "color": "#ffffff00"}, {"offset": 0.55, "color": "#ffd36b"}, {"offset": 1, "color": "#ff4d3d"}]}, ]}), ); + self.run("filter.preset_save", json!({"name": "Warm badge"})); // i18n-exempt: a sample preset name + // Room for the whole list (this run only: screenshot runs never save the layout). + for p in [crate::dock::Panel::Align, crate::dock::Panel::Library, crate::dock::Panel::MovieExplorer, crate::dock::Panel::History] { + self.dock.close(p); + } } Some("testmovieinside") => { // Test Movie floating inside the editor (ADR 0062), as where there can't be a From 6db1dbc27731e4bd4d3c941454e169d5c7d9244e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 19:28:14 -0700 Subject: [PATCH 5/5] docs: ADR 0091 filter presets, order, on/off and tweens; guide, roadmap, changelog; XFL corpus keeps switched-off filters (M5) --- CHANGELOG.md | 18 ++++ crates/xfl/tests/corpus.rs | 6 +- ...-filter-presets-order-on-off-and-tweens.md | 83 +++++++++++++++++++ docs/adr/README.md | 1 - docs/guide/drawing.md | 31 ++++++- docs/guide/reference/commands.md | 28 ++++++- docs/roadmap.md | 4 +- 7 files changed, 162 insertions(+), 9 deletions(-) create mode 100644 docs/adr/0091-filter-presets-order-on-off-and-tweens.md diff --git a/CHANGELOG.md b/CHANGELOG.md index ad44a91d..23db6760 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## Unreleased +* **Filters, second slice: order, on/off, copy and paste, presets** (ADR 0091, M5). + * **Reorder filters** in Properties › Filters: drag a filter by its grip, or focus the grip + and press Alt+Up/Alt+Down, or right-click for Move Up/Down. The order changes the picture + (filters apply from the top down). + * **Switch a filter off** with its eye: it keeps its settings and draws nothing, on the + stage and in every export (SVG, HTML canvas, Lottie, video, images). Enable All and + Disable All in the **…** menu. Animate files' switched-off filters now come in switched + off instead of being dropped. + * **Copy and paste filters** between movie clips and buttons (Copy All Filters, Copy Filter, + Paste Filters). + * **Filter presets**: Save as Preset…, apply by name (replaces the filters, undoable), + rename, delete (asks), and export or import them as a small JSON file. Presets are kept in + your preferences, for any document. + * Classic tweens keep tweening filter values when a filter is switched off; tests cover a + blur and a glow at a tween's midpoint. + * Headless: `filter.move`, `filter.enable`, `filter.remove`, `filter.copy`, + `filter.paste`, `filter.preset_list/save/apply/rename/delete/export/import`, and + `enabled` in `element.set_filters`. * **Lottie export with real keyframes and eases** (ADR 0089, M4). * Tweens become **Lottie keyframes with Lottie's own Bézier eases** instead of a key at every frame: No Ease, Classic Ease, Bézier handles, Quad, Cubic, Back and Bounce, and custom diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index 36e91910..6c744987 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -425,8 +425,10 @@ fn a_screen_video_comes_across_as_its_first_frame() { #[test] fn filters_and_blend_modes_come_across() { let (doc, _) = import("filters"); - let filters: Vec = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| if let ElementKind::Symbol { filters, .. } = &e.kind { filters.len() } else { 99 }).collect(); - assert_eq!(filters, [1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 1], "switched-off and unknown filters are left out"); + let filters: Vec<(usize, usize)> = doc.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| if let ElementKind::Symbol { filters, .. } = &e.kind { (filters.len(), filters.iter().filter(|f| f.enabled).count()) } else { (99, 99) }).collect(); + // A switched-off filter comes in switched off, keeping its place (ADR 0091); unknown ones + // are left out. + assert_eq!(filters, [(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (2, 2), (1, 0), (0, 0), (1, 1)]); let blends: Vec<&str> = doc.timeline(0).layers[1].keyframes[0].elements.iter().filter_map(|e| if let ElementKind::Symbol { blend, .. } = &e.kind { Some(blend.key()) } else { None }).collect(); assert_eq!(blends, ["multiply", "screen", "difference", "add", "subtract", "overlay", "hardlight", "invert"]); } diff --git a/docs/adr/0091-filter-presets-order-on-off-and-tweens.md b/docs/adr/0091-filter-presets-order-on-off-and-tweens.md new file mode 100644 index 00000000..4dcb8f29 --- /dev/null +++ b/docs/adr/0091-filter-presets-order-on-off-and-tweens.md @@ -0,0 +1,83 @@ +# ADR 0091: Filter presets, order, on/off and tweened filter values + +* Status: accepted (2026-11-13) +* Relates to: roadmap M5 (filters on movie clips, second slice), ADR 0025 (bevel and gradient + filters), ADR 0032 (GPU filters), ADR 0068 (brush presets kept in the session and the + preferences), ADR 0072 (filters in the HTML canvas export), ADR 0081 (classic tweens ease + filters as a group), ADR 0004 (destructive actions), ADR 0009 (XFL import) + +## Context + +Movie clip and button instances carry a list of filters (ADR 0025), applied in order. Artists +coming from Animate expect more of the Filters section than adding and removing: to reorder +the list (the order changes the picture: a glow before a desaturating Adjust Color is grey, +after it is in colour), to switch a filter off and on without losing its settings, to copy +filters from one instance to another, and to keep favourite lists as **presets** that work in +any document. Classic tweens already interpolate matching lists (ADR 0081); switching a filter +off must not break that. Animate files mark switched-off filters with `enabled="false"`, which +the importer used to drop. + +Behaviour was learnt from Adobe's public help pages for the Filters panel (presets replace the +instance's filters when applied; filters tween when both keyframes have the same filters in the +same order) and by observation. No Adobe code or asset was used. + +## Decision + +1. **The switch is the list's, not the filter's.** `ElementKind::Symbol.filters` is a + `Vec`; `FilterEntry { filter: Filter, enabled: bool }` serializes as the filter's + own object with `"enabled": false` added (flattened; left out when on). Files from before + read unchanged, and an older build reads a newer file (it ignores the key; the filter then + draws). `Filter` itself, which every renderer and exporter consumes, is untouched. +2. **Off equals absent, decided once in `evaluate`.** The display list's group carries only + the filters that are on (`filter::active`), and an instance whose filters are all off gets + no group at all. So the CPU oracle, the GPU stage, SVG, Lottie, the plug-in exporters and + every raster export draw a switched-off filter exactly as if it were not there, with no + renderer change and so no GPU parity work. The HTML canvas page, which places instances + from the document itself, applies the same rule when it writes `fx`. Tests compare pixels, + SVG text and the page's data with and without the filter. +3. **Commands, one undo step each, on every selected movie clip and button.** `filter.move` + `{from, to}`, `filter.enable {enabled, index?}` (no index: all), `filter.remove {index?}`, + `filter.copy {index?}` and `filter.paste {replace?}` (added after the instance's own, as in + Animate; at most 16 filters, refused whole past that), and `element.set_filters` takes + `enabled` per filter. An index acts where an instance has one; the command fails only when + it acts nowhere. Graphics are refused with the reason, as before. +4. **Presets belong to the session and live in the preferences**, like brushes (ADR 0068): + `Session.filter_presets`, put there by the desktop app at start and written back when a + command changes them, so the engine never reads the settings folder and the CLI and MCP use + the same commands (`filter.preset_list`, `_save`, `_apply`, `_rename`, `_delete`, `_export`, + `_import`). A preset is a name (unique ignoring case, at most 64 characters) and a filter + list, switches included; at most 200. **Applying copies the list** onto the instances, + replacing theirs (Animate's behaviour): a preset changed or deleted later never changes + artwork, and documents need nothing extra to open elsewhere. The file is + `{"format": "anicraft-filter-presets", "version": 1, "presets": [...]}`, at most 1 MB; + importing skips bad entries, clamps values and numbers clashing names ("Glow 2"). +5. **Destructive tiers (ADR 0004).** Deleting a preset, saving over one, and exporting over a + file are irreversible, so the engine asks (`"confirm": true` headless). Everything that + touches the document is undoable and doesn't ask. +6. **Tweens.** A classic tween pairs two lists when they have the same kinds in the same + order, switched-off filters included, so switching one off never breaks a tween; numbers + and colours travel, and on/off (like Inner, Knockout and Quality) holds from the first + keyframe. Reordering one keyframe's list makes the lists no longer pair up, and the first + keyframe's filters hold, as in Animate. +7. **XFL.** `enabled="false"` filters now import switched off, in their place, instead of being + dropped; the corpus already holds one and its golden render is unchanged. +8. **Clipboard and plug-ins.** Copied filters live in `Session.filter_clipboard`, outside undo, + and survive New and Open like copied artwork. Plug-ins may move, switch, remove filters and + list and apply presets; they may not use the clipboard or change the user's presets or + preset files (`plugin_may_call`). +9. **Interface.** Properties › Filters keeps **Add filter**, and gains a presets button (apply + by name, Save as Preset… named inline, Rename and Delete submenus, Import… and Export…) and + a **…** menu (Copy All Filters, Paste Filters, Enable All, Disable All, Remove All). Each + filter's header has a grip (drag to reorder with a drop line; focused, Alt+Up/Alt+Down; + right-click for Move Up/Down, Turn Off/On, Copy Filter, Remove Filter), an eye toggle, the + name (faint and marked "(off)" when off) and a bin. All of it is named for screen readers + and translatable. + +## Consequences + +* One model of the list, its order and its switches across commands, files, XFL, the stage and + every export; renderers see only active filters. +* Not yet (later PRs): **motion-tween tracks per filter property in the Motion Editor** + (planned as filter properties addressed by slot and parameter beside the twenty transform + and colour properties, following moves and removals of filters), filters on text fields, + and built-in presets. diff --git a/docs/adr/README.md b/docs/adr/README.md index 3af10660..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0091 | m5/filters-2 (M5) | Filter presets, order, on/off and tweened filter values | diff --git a/docs/guide/drawing.md b/docs/guide/drawing.md index cd213d9e..49704ff3 100644 --- a/docs/guide/drawing.md +++ b/docs/guide/drawing.md @@ -419,8 +419,35 @@ Convert your artwork to a movie clip symbol first (see **Filters**: choose **Add filter** under Filters in Properties, and stack as many as you like: **Drop Shadow**, **Blur**, **Glow**, **Bevel**, **Gradient Glow**, **Gradient Bevel** and **Adjust Color**. Each has its own settings (blur, strength, quality, colour, angle, distance, -knockout and so on); the gradient ones have a colour ramp you click to add stops. **Remove** -takes a filter off. +knockout and so on); the gradient ones have a colour ramp you click to add stops. + +Each filter in the list has a row of its own: + +* **The order matters**: filters apply from the top down, so a Glow above Adjust Color is + greyed with the artwork, and one below it stays in colour. Drag a filter by its grip (the + dots on the left) to move it; or click the grip and press **Alt+Up** or **Alt+Down**; or + right-click the row for **Move Up** and **Move Down**. +* **The eye** switches a filter off without losing its settings, and back on. A filter that is + off draws nothing anywhere: on the stage, in Test Movie and in every export. +* **The bin** removes the filter. + +The **…** button next to **Add filter** has **Copy All Filters**, **Paste Filters** (adds the +copied filters after the instance's own; select another movie clip or button first), +**Enable All**, **Disable All** and **Remove All**. Right-click a filter's row for **Copy +Filter** to copy just that one. + +**Filter presets** keep a list of filters under a name, for any document. Click the folder +button next to **Add filter**: **Save as Preset…** names the current list; click a preset's +name to apply it (it replaces the instance's filters, as in Animate; **Edit › Undo** takes it +back). **Rename Preset** and **Delete Preset** manage them (deleting asks first; artwork keeps +the filters it got). **Export Presets…** writes them to a small JSON file and **Import +Presets…** adds a file's presets to yours, to move them to another computer. Presets are kept +in your preferences. + +**Tweening filters**: a classic tween changes filter values smoothly when both keyframes have +the same filters in the same order (switched-off ones count), as in Animate: a Blur from 0 to +20 is 10 halfway. On/off, Inner, Knockout and Quality stay as the first keyframe has them. +If the lists differ, the first keyframe's filters hold until the next keyframe. **Blending** sets how the instance mixes with what's below it: Normal, Layer, Darken, Multiply, Lighten, Screen, Overlay, Hard Light, Add, Subtract, Difference, Invert, Alpha and diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index f89217e9..b41c2a64 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -1,6 +1,6 @@ # Command reference -Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 335 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). +Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 347 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). This page is generated from the command registry, so it always matches the version of AniCraft it came with. @@ -496,7 +496,7 @@ These commands have no menu item: the panels, the stage and the timeline use the - **Blending** `element.set_blend` · changes the document Parameters: `{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances` - **Filters** `element.set_filters` · changes the document - Parameters: `{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color "#rrggbbaa"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)` + Parameters: `{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values, enabled?: bool (default true; false switches it off, keeping its settings)}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color "#rrggbbaa"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)` - **Looping** `element.set_loop` · changes the document Parameters: `{loop?: loop|play_once|single_frame, first_frame?}` - **Symbol Type** `symbol.set_kind` · changes the document @@ -601,6 +601,30 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: `{path, names? (default: all yours)} writes your brushes to a brush set file (JSON)` - **Import Brushes** `brush.preset_import` Parameters: `{path} adds the brushes in a brush set file to yours (a name you have already gets a number)` +- **Move Filter** `filter.move` · changes the document + Parameters: ``{from, to} moves the filter at index `from` (0 is the first, applied first) to index `to` in the selected movie clip and button instances' lists; the order changes how they draw`` +- **Enable Filter** `filter.enable` · changes the document + Parameters: `{enabled: bool, index? (default: every filter)} switches a filter on or off; a filter switched off keeps its settings and draws nothing` +- **Remove Filter** `filter.remove` · changes the document + Parameters: `{index? (default: every filter)} removes a filter from the selected movie clip and button instances` +- **Copy Filters** `filter.copy` + Parameters: `{index? (default: every filter)} copies the selected instance's filters (one, or all), for Paste Filters` +- **Paste Filters** `filter.paste` · changes the document + Parameters: `{replace? (default false: added after the instances' own)} pastes the copied filters onto the selected movie clip and button instances` +- **Filter Presets** `filter.preset_list` + Parameters: `{} your filter presets, each a name and its filters` +- **Save Filter Preset** `filter.preset_save` + Parameters: `{name, filters? (a list as element.set_filters takes; default: the selected instance's)} saves a filter preset of your own (kept in your preferences; a name you have already is replaced, after asking)` +- **Apply Filter Preset** `filter.preset_apply` · changes the document + Parameters: `{name} gives the selected movie clip and button instances the preset's filters, replacing theirs (as Animate does)` +- **Rename Filter Preset** `filter.preset_rename` + Parameters: `{name, to}` +- **Delete Filter Preset** `filter.preset_delete` + Parameters: `{name} deletes a filter preset (asks first: it can't be undone; artwork that used it keeps its filters)` +- **Export Filter Presets** `filter.preset_export` + Parameters: `{path, names? (default: all)} writes your filter presets to a small JSON file` +- **Import Filter Presets** `filter.preset_import` + Parameters: `{path} adds the presets in a filter preset file to yours (a name you have already gets a number)` - **Eraser** `draw.erase` · changes the document Parameters: `{points: [[x, y] or [x, y, pressure], ..] (one point erases a dab), size? (stage units, default 10), shape?: round|square, angle?, roundness?, mode?: normal|fills|lines|selected_fills|inside (Erase Normal takes fills and lines, Erase Fills leaves lines, Erase Lines leaves fills, Erase Selected Fills only the selected fills, Erase Inside only the fill the stroke starts on), unit? (stage units per screen point)} erases from the raw shapes on the active layer; drawing objects, symbols and text are kept` - **Faucet** `draw.faucet` · changes the document diff --git a/docs/roadmap.md b/docs/roadmap.md index 6e42781d..56ad142b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,7 +9,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Dimension | Status | |---|---| | 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 (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), 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. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | +| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), 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. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **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). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, 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, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); 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; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **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`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markers. Headless: `frames.transform`, `frames.align`, `frames.delete`, `frames.copy`, `frames.cut`, `frames.paste`, `frames.merge`, `merge` on `frames.edit_multiple`. Not yet: per-layer onion toggles, Duplicate/Distribute/Arrange and recolouring across keyframes, scaling a motion tween's object on several frames, a draggable pivot, onion frames of the timeline around an open symbol. **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, colour, filters, and instance filters tween; XFL custom and per-property eases import exactly; `ease.*` headless) + curve preview, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (any preset, saved ease or custom ease of several segments, ADR 0081; 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. **Retiming** (ADR 0083): keys drag sideways in time (snapped to frames, never past a neighbour), Shift-click picks keys across properties, an All lane picks a frame's keys, Left/Right move picked keys with the curve focused; dragging a span's end stretches a motion tween's keys in proportion (Shift keeps them); a click picks a whole motion span and dragging (or a selection of whole tween spans) moves it at its length, Alt-drag copies; **Split Motion** / **Join Motion** (split then join is exact). Headless: `motion.move_keys`, `timeline.resize_span`, `timeline.move_spans`, `motion.split`, `motion.join`. Not yet: joining two independent motion paths, retiming from a span's left edge. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start: a bone from a chained instance always starts at its joint; branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone (the grabbed point follows) or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. **Shape armatures** (ADR 0071): the Bone tool draws bones inside a shape (it moves to an armature layer as an object, outside merge drawing); its points are bound to the nearest bones automatically (weights by distance to each bone, up to four, summing to 1) and bend by linear blend skinning (handles with their anchors, strokes keep their width, the rest pose exact); the **Bind tool** (Shift+M) shows the points (squares, triangles where shared) and binds them by click, Shift/Ctrl-click or box; the same IK, poses and tweens; `bone.add_in_shape`, `bone.bind`, `bone.info {points}`. **Springs, joint translation and members in place** (ADR 0084): joints slide along X/Y of what they start on, freely or within pixel limits, as part of each pose (IK slides only where turning can't reach); per-bone Spring and Damping swing bones after the motion and settle, evaluated as a pure replay of up to six seconds of motion (seeking equals playing bit for bit; 0.33 ms a frame for 16 sprung bones), shown on the stage, in Test Movie and every export, switched off per armature for posing; a picked bone's instance takes colour effect, blending and filters in place on every pose; `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`. Not yet: runtime armatures, XFL import, mixing instances and shapes in one armature (proposed in ADR 0084), reshaping a bound shape, painted weights, gravity and wind. **Asset Warp** (ADR 0079): the **Asset Warp tool** (Shift+Q) pins a shape or a bitmap (the first pin covers it with a warp mesh: a grid over its bounds, 2–48 cells along the longer side, Properties › Asset Warp); dragging a pin bends the artwork around the other pins by rigid moving least squares (Schaefer et al. 2006) at the mesh's vertices, live, one undo step per drag; Delete removes a pin; pins are added to every keyframe holding the artwork and their poses tween with classic tweens and easing; shapes bend through the mesh (straight edges exactly, curves split), bitmaps are drawn through its triangles by the CPU oracle (bilinear) and the GPU stage takes the same prepared fill (parity exact); the rest pose is the drawing bit for bit; every raster export, SVG (a bent bitmap baked as an image), Lottie and HTML (a bent bitmap reported) go through `evaluate`; `warp.add`, `warp.pin_add`, `warp.pin_move`, `warp.pin_remove`, `warp.remove`, `warp.info`. Not yet: as-rigid-as-possible solving on a mesh that follows the outline, symbols and text, binding warp pins to bones, a GPU textured-triangle path, bent bitmaps in HTML and Lottie, XFL import of warped assets. eases saved in the document and offered everywhere; copy/paste of an ease; classic tweens eased per property group: position, **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. **Camera, second slice** (ADR 0082): layer depth in a pinhole perspective (deeper layers move and zoom less, draw behind nearer ones; depth 0 bit-exact), depth keyed over time (linear between keys), **Window › Layer Depth** (layers by depth, drag nearer or farther, key, attach), **Attach Layer to Camera** (timeline toggle; HUDs stay on screen), camera colour effects (Brightness, Tint, Advanced), and the Selection tool picking and moving artwork while previewing through the camera; headless `layer.set_depth {key, frame}`, `layer.remove_depth_key`, `layer.set_attached`, `layer.depths`, `element.pick {view: camera}`. Not yet: other tools while previewing, depth inside symbols, depth keys moving with inserted frames, XFL camera and layer-depth import (no public format description). **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. 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 selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. **Selection tool on raw shapes** (ADR 0041): drag an unselected segment or fill edge to bend it through the pointer (every shape sharing the edge bends with it), an unselected corner or end to move it with every raw shape that shares it, a fill to move only that fill; points and selections snap to points, strokes and fill edges within 10 screen px (snap ring), and arrow nudges join ends within 0.2 px at their midpoint or onto a line that stays put; a corner or curve mark by the pointer shows what a drag does; the marquee selects the parts of raw fills and strokes under it, cut at its edges (taken back if nothing uses them, no undo step), and objects wholly inside; each drag one undo step, merged on release. Headless: `path.bend_segment`, `raw.move_point`, `raw.select_rect`, `raw.merge`, `raw.hit`, `snap` on `element.translate`. **Subselection on raw shapes and merging everywhere** (ADR 0042): with Subselection (A), a click on a raw line or fill shows the anchors of everything connected to it (once per shared point; hollow, selected ones solid) and the handles of the selected anchors' curves and of the clicked edge; drag an anchor to move it with the other selected ones and every shape on them, a handle to change the curve in every shape that has the edge, a line or fill to move everything connected; Shift adds or removes anchors; the marquee takes whole shapes on the active layer and selects the anchors inside; arrows nudge 1 screen px (Shift 10); one undo step per gesture, merged on release. **Snap to Objects** (View › Snapping, a magnet under the tools, the selection tools' options) switches the Selection and Subselection tools' snapping. The Paint Bucket's raw fills are exact (up to the lines and fill edges, from the planar merge) and join fills of their colour; pasted raw shapes cut what they land on; raw shapes from Animate files open raw and merged; gradient and bitmap fills take part in the merge. Headless: `raw.subselect`, `raw.subselect_rect`, `raw.points`, `raw.move_handle`, `with` on `raw.move_point`, `draw.snap_to_objects`, `object` on `paint.bucket`. Not yet: width profiles in the merge. **Raw points and symbols in place** (ADR 0045): add a point on a raw edge (Pen Alt-click, Subselection double-click; every shape on the edge gets it, the curve unchanged), delete raw points (Delete; the shapes on each are joined across it so the drawing stays connected; points where three edges meet are kept), Make Smooth / Corner on raw points, smooth handle pairs (Alt breaks them; drawing objects too); the Line, Rectangle, Oval, PolyStar and Pen tools snap their points within 10 screen px (Snap to Objects, Ctrl+Shift+/); a double-click on an instance (or Ctrl+E, or a double-click in the Library) opens the symbol in place, the stage dimmed around it, the edit bar showing the path back, and every tool and command works on its timeline. Headless: `raw.add_point`, `raw.delete_points`, `raw.convert_points`, `draw.snap`, `smooth` on `raw.move_handle` and `path.move_points`, `symbol.edit`, `symbol.exit`. Not yet: rotated instances in place (they open upright). Onion skin and Edit Multiple Frames work inside a symbol since ADR 0051. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. **Paint Selection and Paint Inside** (ADR 0080): the paint is clipped to the selected fills' union, or to the fill (or closed-off empty area) the stroke starts in, exactly on the planar map, then merged under the lines; Paint Selection keeps the selection for the next stroke. Not yet: the live preview clipped as it paints. **Brush library, pressure curves and the Paint Brush (Y)** (ADR 0068, first slice): Window › Brush Library with seven built-in brushes made only of parameters (Pencil, Ink Pen, Flat Calligraphy, Round Taper, Marker, Chalk with a deterministic worn edge, Dotted stamps), each with a stroke preview drawn by the renderer; brushes of your own saved by name in your preferences, renamed, deleted (asks first) and moved between computers as a JSON brush set; a pressure curve editor (Linear, Soft, Firm, or your own points) driving size and, optionally, the stroke's opacity; tapers, dab spacing and a rough edge in Properties; Velocity (mouse speed as pressure, off by default); the Paint Brush draws a width-profiled stroke in the stroke colour that the Width tool edits. Headless: `brush.preset_list/save/rename/delete/export/import`, `preset`, `curve`, `as_stroke` and the shaping params on `draw.brush`. Not yet: pen tilt (egui doesn't report it), opacity varying along a stroke, textured or art brushes, Eraser presets and pressure. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. **Colour picker and drawing-tool fixes from user reports** (M1): every colour swatch (the Tools panel's fill and stroke squares too) opens one picker with Animate's web-safe swatches (216 colours, greys and primaries), the colours mixed or typed this session, a hex field and the full mixer; the Tools squares offer No Colour and recolour selected shapes; drawing tools leave nothing selected after a stroke and the Selection tool's box has no handles (they are Free Transform's); Break Apart turns drawing objects into merged drawing; Ctrl-drag on a raw edge adds a corner point; the Pencil and Line show no fill. **Swatches panel** (ADR 0078): Window › Swatches, the document's saved colours and gradients (in the `.anicraft` file; a default set for new documents and older files); click applies to the selection and the tool colour, to the stroke or fill that is active (Tools squares, Colour panel or the panel's toggle; gradients always to the fill); + adds the active colour or gradient, Duplicate, Delete, drag (or Alt+arrows) to reorder, names on hover, Clear (keeps black and white) and Load Default Swatches (ask first, undoable); import and export as a JSON swatch file, GIMP `.gpl` import; the colour picker shows the document's swatches and the fill picker its gradient swatches. Headless: `swatch.list/add/remove/move/duplicate/rename/apply/clear/reset/import/export`. Not yet: swatch folders, sorting by colour, bitmap swatches, Save as Default, XFL swatch import (no public description), Adobe `.aco`/`.ase`/`.clr` (proprietary). The layer footer is icon buttons (New Layer, Delete, New Folder, Up, Down) that fit at any size and language. **Groups and Combine Objects** (ADR 0073): Modify › Group (Ctrl+G) / Ungroup (Ctrl+Shift+G), a group element whose members are a one-layer, one-frame timeline, opened in place by a double-click like a symbol (every tool works inside; raw shapes merge only with each other); nested groups; exports, player, sounds and the Library see inside; XFL `DOMGroup` imports as groups. Combine Objects › Union, Intersect, Punch, Crop on the planar map (analytic area tests). Selection tool: Alt-drag copies, Shift constrains to 45° (Ctrl/⌘-drag corners: #257). **Drawing parity leftovers** (ADR 0080): PolyStar's Shape (Polygon or Star), sides 3–32 and star point size 0–1 in its options (`shape`, `sides`, `point_size` on `draw.star`); a double-click (or Ctrl+E) opens a drawing object in place, its raw shapes merging only with each other, and it closes as one object again (a group of the pieces when an edit leaves several); **Modify › Transform › Envelope**: a Bézier mesh of corner and tangent handles bends the selected shapes and drawing objects, one undo step per drag, baked like Animate's (no Delete Envelope needed), undo restoring the mesh; headless `modify.envelope`, `modify.envelope_move`, `modify.envelope_close`. *Not yet:* gradient and bitmap strokes (proposed in ADR 0080), envelope handles from the keyboard, an envelope on symbols, text or groups, drawing objects edited without opening them (#181), Combine across layers. **Rulers, grid and guides** (ADR 0076): View › Rulers (stage pixels, following zoom and pan, pointer marked); guides per scene saved in the document, dragged from a ruler, moved with the Selection tool, dragged back to delete, Show/Lock/Snap/Edit/Add/Clear (Edit Guides lists and adds them from the keyboard); a grid (spacing, | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format ` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, a binary document view. | @@ -38,7 +38,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **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; the ease presets, saved and custom eases of ADR 0081 per segment); ~~Motion Editor and timeline retiming, Split/Join Motion~~ ✅ (ADR 0083); ~~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), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~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~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~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: GPU binning inside masks and groups, 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); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters; motion-tween tracks per filter property in the Motion Editor, filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | | **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). | | **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groups in one dock, minimum sizes per panel, panel shortcut keys). |