diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 44271455..5f962455 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -123,6 +123,7 @@ OR Apache-2.0) is noted in the table. | Resampling by cubic Hermite (Catmull-Rom) interpolation | `crates/audio/src/mix.rs` | E. Catmull and R. Rom, *A class of local interpolating splines* (1974); R. Keys, *Cubic convolution interpolation for digital image processing* (1981) | Public mathematical results. | | Ogg Vorbis decoding | `crates/audio/src/vorbis.rs` | `lewton` (MIT OR Apache-2.0) with `ogg` (BSD-3-Clause); Xiph.Org's open, royalty-free Vorbis I specification | Used as a library, not copied. | | MP3 (MPEG-1/2 audio layers I–III) decoding | `crates/audio/src/mp3.rs` | `nanomp3` (MIT OR Apache-2.0), a port of minimp3 (CC0) | Used as a library. The MP3 patents have expired; decoding only, no encoder. | +| Animated PNG and animated WebP files: APNG chunks (`acTL`, `fcTL`, `fdAT`), frame regions, blend and dispose ops; the WebP RIFF container (`VP8X`, `ANIM`, `ANMF`) | `crates/engine/src/anim.rs` | The APNG specification (Mozilla; part of W3C *Portable Network Graphics (PNG) Specification*, Third Edition); Google's public *WebP Container Specification* and *WebP Lossless Bitstream Specification*; PNG frame data by the `png` crate (MIT OR Apache-2.0), lossless WebP frames by `image-webp` (MIT OR Apache-2.0) | Open, royalty-free specifications; the chunks are written by our own code (ADR 0063). | ## Rust dependencies diff --git a/CHANGELOG.md b/CHANGELOG.md index 000fc213..87ac11c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,22 @@ * Windows and Linux already open a double-clicked document from the command line; a test now covers it. +* **Animated PNG and animated WebP export** (ADR 0063, M4). + * **File › Export › Export Animated PNG…** and **Export Animated WebP…** make full-colour + animations with real transparency, for the web and chat apps, where a GIF has 256 colours + and hard edges. WebP is lossless. Both are transparent by default; turn on the stage colour + as background if you want it. Loop forever, play once, or play a set number of times. + * Every frame is exactly what AniCraft renders. Frames that repeat the one before are stored + once and shown longer, and each later frame stores only the rectangle that changed, so + holds and small motions cost little. + * Timing is exact: APNG delays are fractions of the frame rate (29.97 fps stays 29.97), and + WebP's milliseconds never drift. + * Both are in **Publish Settings** (Animated PNG, Animated WebP) with frames, scale, loop and + background; in a browser they download. Headless: `file.export_apng`, `file.export_webp` + and `anicraft-cli apng` / `webp`. + * On the sample (48 frames, 1280 × 720) the APNG is 2.0 MB and the WebP 1.8 MB, against the + GIF's 1.4 MB, which has only 256 colours; both take less time to make than the GIF. + * **Publish Settings and Publish** (ADR 0060, M8). * **File › Publish Settings** (Ctrl+Shift+F12) is a window that stays open while you work. It lists every format AniCraft exports (HTML canvas, animated GIF, video, Lottie, sprite diff --git a/Cargo.lock b/Cargo.lock index a8c54644..6c8a91ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -294,6 +294,7 @@ dependencies = [ "anicraft-text", "anicraft-xfl", "gif", + "image-webp", "miniz_oxide 0.8.9", "png 0.17.16", "rayon", @@ -2248,6 +2249,16 @@ dependencies = [ "tiff", ] +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "indexmap" version = "2.14.2" diff --git a/Cargo.toml b/Cargo.toml index 181af8e4..505b6d07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "MIT OR Apache-2.0" # An application, not a library: not published to crates.io. publish = false repository = "https://github.com/storytold/AniCraft" -rust-version = "1.90" +rust-version = "1.95" [workspace.dependencies] anicraft-geom = { path = "crates/geom" } @@ -42,6 +42,8 @@ png = "0.17" # JPEG decoding for imported images (already in the tree; MIT OR Apache-2.0 OR Zlib). zune-jpeg = { version = "0.5", default-features = false } gif = "0.14" +# Lossless WebP frames for animated WebP export (pure Rust, MIT OR Apache-2.0; ADR 0063). +image-webp = "0.2" # wgpu is the primary renderer; glow (OpenGL) is the fallback for GPUs/VMs where wgpu fails. # Default features off: we skip `links` (opening web links pulls in url/idna/ICU Unicode # tables we don't use) and the web-only screen-reader shim. Same set as PhotoCraft, plus glow. diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 42a4cc5b..a685d692 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -18,6 +18,9 @@ USAGE: anicraft-cli render --out [--frame N] [--scale S] anicraft-cli render-seq --out-dir [--from A] [--to B] [--scale S] anicraft-cli gif --out [--from A] [--to B] [--scale S] [--overwrite yes] + anicraft-cli apng|webp --out [--from A] [--to B] [--scale S] + [--loop forever|N] [--background yes] [--overwrite yes] + full colour with real transparency (WebP: lossless) anicraft-cli commands anicraft-cli run [--save ] anicraft-cli exec [] [--save ] @@ -148,9 +151,11 @@ pub fn run(argv: &[String]) -> Result { } exec(&mut s, "file.export_png_sequence", &p).map(|v| v.to_string()) } - "gif" => { - let mut s = session(&a, Some(src.ok_or("gif needs a file or --sample")?))?; - let out = a.flag("out").ok_or("gif needs --out ")?; + "gif" | "apng" | "webp" => { + let mut s = session(&a, Some(src.ok_or(format!("{cmd} needs a file or --sample"))?))?; + let cmd = cmd.as_str(); + let ext = if cmd == "apng" { "png" } else { cmd }; + let out = a.flag("out").ok_or(format!("{cmd} needs --out "))?; let mut p = json!({"path": out}); if let Some(f) = one_based(&a, "from")? { p["from"] = json!(f); @@ -164,7 +169,16 @@ pub fn run(argv: &[String]) -> Result { if a.flag("overwrite").is_some_and(|v| v == "yes" || v == "true") { p["confirm"] = json!(true); } - exec(&mut s, "file.export_gif", &p).map(|v| v.to_string()) + if cmd != "gif" { + match a.flag("loop") { + None | Some("forever") => {} + Some(n) => p["loop"] = json!(n.parse::().map_err(|_| format!("--loop is forever or how many times it plays, not '{n}'"))?), + } + if a.flag("background").is_some_and(|v| v == "yes" || v == "true") { + p["background"] = json!(true); + } + } + exec(&mut s, &format!("file.export_{cmd}"), &p).map(|v| v.to_string()) } "new" => { let mut s = Session::default(); diff --git a/crates/doc/src/publish.rs b/crates/doc/src/publish.rs index 86343d5c..701ee881 100644 --- a/crates/doc/src/publish.rs +++ b/crates/doc/src/publish.rs @@ -14,6 +14,8 @@ use serde::{Deserialize, Serialize}; pub enum PublishFormat { Html, Gif, + Apng, + Webp, Video, Lottie, SpriteSheet, @@ -25,9 +27,11 @@ pub enum PublishFormat { impl PublishFormat { /// Every format, in the order Publish runs them. - pub const ALL: [PublishFormat; 9] = [ + pub const ALL: [PublishFormat; 11] = [ PublishFormat::Html, PublishFormat::Gif, + PublishFormat::Apng, + PublishFormat::Webp, PublishFormat::Video, PublishFormat::Lottie, PublishFormat::SpriteSheet, @@ -42,6 +46,8 @@ impl PublishFormat { match self { PublishFormat::Html => "html", PublishFormat::Gif => "gif", + PublishFormat::Apng => "apng", + PublishFormat::Webp => "webp", PublishFormat::Video => "video", PublishFormat::Lottie => "lottie", PublishFormat::SpriteSheet => "sprite_sheet", @@ -61,6 +67,8 @@ impl PublishFormat { match self { PublishFormat::Html => "HTML canvas", PublishFormat::Gif => "Animated GIF", + PublishFormat::Apng => "Animated PNG", + PublishFormat::Webp => "Animated WebP", PublishFormat::Video => "Video", PublishFormat::Lottie => "Lottie", PublishFormat::SpriteSheet => "Sprite sheet", @@ -76,6 +84,9 @@ impl PublishFormat { match self { PublishFormat::Html => "{name}.html", PublishFormat::Gif => "{name}.gif", + // Not {name}.png: the PNG image has that. + PublishFormat::Apng => "{name}_animated.png", + PublishFormat::Webp => "{name}.webp", PublishFormat::Video => "{name}.webm", PublishFormat::Lottie => "{name}.json", PublishFormat::SpriteSheet => "{name}_sheet.png", @@ -91,6 +102,8 @@ impl PublishFormat { match self { PublishFormat::Html => &["html", "htm"], PublishFormat::Gif => &["gif"], + PublishFormat::Apng => &["png", "apng"], + PublishFormat::Webp => &["webp"], PublishFormat::Video => &["webm", "mp4"], PublishFormat::Lottie => &["json"], PublishFormat::SpriteSheet | PublishFormat::Png => &["png"], @@ -107,6 +120,8 @@ pub const MAX_OUTPUT_CHARS: usize = 512; pub const MAX_TITLE_CHARS: usize = 256; /// Largest export scale. pub const MAX_PUBLISH_SCALE: f32 = 8.0; +/// Most plays an animated PNG or WebP's loop count says (WebP stores it in 16 bits). +pub const MAX_PLAYS: u32 = 65_535; /// Movie frames to publish (every scene in order, 0-based): `None` ends are the movie's ends. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -156,6 +171,30 @@ format_settings!( looping: bool = true, } ); +format_settings!( + /// An animated PNG: full colour, real alpha (`file.export_apng`, ADR 0063). + ApngSettings, PublishFormat::Apng, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// How many times it plays; 0: forever. + #[serde(rename = "loop")] + plays: u32 = 0, + /// The stage colour behind it; off: transparent. + background: bool = false, + } +); +format_settings!( + /// An animated WebP, lossless (`file.export_webp`, ADR 0063). + WebpSettings, PublishFormat::Webp, false, { + range: FrameRange = FrameRange::default(), + scale: f32 = 1.0, + /// How many times it plays; 0: forever. + #[serde(rename = "loop")] + plays: u32 = 0, + /// The stage colour behind it; off: transparent. + background: bool = false, + } +); format_settings!( /// WebM or MP4 through the user's ffmpeg (`file.export_video`). VideoSettings, PublishFormat::Video, false, { @@ -220,6 +259,8 @@ format_settings!( pub struct PublishProfile { pub html: HtmlSettings, pub gif: GifSettings, + pub apng: ApngSettings, + pub webp: WebpSettings, pub video: VideoSettings, pub lottie: LottieSettings, pub sprite_sheet: SpriteSheetSettings, @@ -249,6 +290,8 @@ impl PublishProfile { match f { PublishFormat::Html => (self.html.enabled, &self.html.output), PublishFormat::Gif => (self.gif.enabled, &self.gif.output), + PublishFormat::Apng => (self.apng.enabled, &self.apng.output), + PublishFormat::Webp => (self.webp.enabled, &self.webp.output), PublishFormat::Video => (self.video.enabled, &self.video.output), PublishFormat::Lottie => (self.lottie.enabled, &self.lottie.output), PublishFormat::SpriteSheet => (self.sprite_sheet.enabled, &self.sprite_sheet.output), @@ -264,6 +307,8 @@ impl PublishProfile { match f { PublishFormat::Html => (&mut self.html.enabled, &mut self.html.output), PublishFormat::Gif => (&mut self.gif.enabled, &mut self.gif.output), + PublishFormat::Apng => (&mut self.apng.enabled, &mut self.apng.output), + PublishFormat::Webp => (&mut self.webp.enabled, &mut self.webp.output), PublishFormat::Video => (&mut self.video.enabled, &mut self.video.output), PublishFormat::Lottie => (&mut self.lottie.enabled, &mut self.lottie.output), PublishFormat::SpriteSheet => (&mut self.sprite_sheet.enabled, &mut self.sprite_sheet.output), @@ -290,16 +335,18 @@ impl PublishProfile { } } clip(&mut self.html.title, MAX_TITLE_CHARS); - for s in [&mut self.gif.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] { + for s in [&mut self.gif.scale, &mut self.apng.scale, &mut self.webp.scale, &mut self.video.scale, &mut self.sprite_sheet.scale, &mut self.png_sequence.scale, &mut self.png.scale] { *s = clean_scale(*s); } self.sprite_sheet.padding = self.sprite_sheet.padding.min(256); + self.apng.plays = self.apng.plays.min(MAX_PLAYS); + self.webp.plays = self.webp.plays.min(MAX_PLAYS); self.sprite_sheet.columns = self.sprite_sheet.columns.min(10_000); self.audio.rate = self.audio.rate.clamp(8_000, 192_000); if !matches!(self.audio.bits, 16 | 24 | 32) { self.audio.bits = 16; } - for r in [&mut self.gif.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] { + for r in [&mut self.gif.range, &mut self.apng.range, &mut self.webp.range, &mut self.video.range, &mut self.lottie.range, &mut self.sprite_sheet.range, &mut self.png_sequence.range, &mut self.audio.range] { if let (Some(a), Some(b)) = (r.from, r.to) && b < a { @@ -344,6 +391,13 @@ mod tests { assert!(partial.gif.enabled && partial.html.enabled); assert_eq!(partial.gif.output, "{name}.gif"); assert_eq!(partial.gif.scale, 1.0); + assert_eq!((partial.apng.plays, partial.webp.background, partial.webp.enabled), (0, false, false), "formats newer than the file get their defaults"); + let mut q = PublishProfile::default(); + q.apng.plays = 3; + q.webp.background = true; + let text = serde_json::to_string(&q).unwrap(); + assert!(text.contains("\"apng\"") && text.contains("\"loop\":3"), "{text}"); + assert_eq!(serde_json::from_str::(&text).unwrap(), q); } #[test] @@ -354,12 +408,14 @@ mod tests { p.audio.rate = 5; p.audio.bits = 7; p.sprite_sheet.padding = u32::MAX; + p.webp.plays = u32::MAX; p.video.output = " ".into(); p.html.title = "x".repeat(10_000); p.lottie.range = FrameRange { from: Some(9), to: Some(2) }; p.sanitize(); assert_eq!((p.gif.scale, p.png.scale, p.audio.rate, p.audio.bits, p.sprite_sheet.padding), (1.0, MAX_PUBLISH_SCALE, 8_000, 16, 256)); assert_eq!(p.video.output, "{name}.webm"); + assert_eq!(p.webp.plays, MAX_PLAYS); assert_eq!(p.html.title.chars().count(), MAX_TITLE_CHARS); assert_eq!(p.lottie.range, FrameRange { from: Some(2), to: Some(9) }); } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 333dea00..f6d9eda8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,11 +21,12 @@ thiserror.workspace = true rayon.workspace = true web-time.workspace = true gif.workspace = true +# Animated PNG frames (ADR 0063; already in the tree through the renderer). +png.workspace = true +image-webp.workspace = true regex.workspace = true [dev-dependencies] -# Decodes exported sheets in tests (already in the tree through the renderer). -png.workspace = true # Packs the XFL corpus into .fla archives in tests (ADR 0054; already in the tree through xfl). miniz_oxide = "0.8" # Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception). diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs new file mode 100644 index 00000000..b54c248e --- /dev/null +++ b/crates/engine/src/anim.rs @@ -0,0 +1,502 @@ +//! Animated PNG and animated WebP export (ADR 0063): full colour and real alpha, for the web +//! and chat apps, where an animated GIF has 256 colours and 1-bit transparency. +//! +//! Both formats share one pipeline. Frames render in parallel, a batch at a time (memory stays +//! bounded), as GIF export does. A frame identical to the one before it is merged into that +//! frame's delay. Every other frame is cut down to the rectangle that changed since the frame +//! before and compressed in parallel as an image of its own (a PNG, or a lossless WebP); the +//! compressed data is then put into one file in order, by hand, chunk by chunk: +//! +//! * **APNG** (the APNG specification): `IHDR`, `acTL`, then per frame an `fcTL` (its region, +//! delay, dispose op none, blend op) and its `IDAT` / `fdAT` data. Delays are exact fractions +//! of the document's frame rate (2 frames at 29.97 fps: 200/2997 s). A region whose changed +//! pixels are all opaque blends *over* the frame before, with its unchanged pixels left +//! transparent (they compress to almost nothing); otherwise it replaces (*source*). +//! * **WebP** (the WebP container specification): `VP8X`, `ANIM`, then an `ANMF` per frame +//! wrapping its `VP8L` (lossless) bitstream. Regions start on even pixels, as the format +//! needs, and replace what was there (no blending: the decoders' blend rounds opaque pixels). +//! Durations are whole milliseconds; each is rounded from the exact time the frame starts, so +//! the error never adds up and the running time is exact to the millisecond. +//! +//! A delay longer than one frame header can hold goes on, after the frame, as frames that +//! change nothing (one transparent pixel blended over), so timing is never cut short. + +use crate::params::*; +use crate::{EngineError, Result, Session}; +use anicraft_render::{View, render}; +use rayon::prelude::*; +use serde_json::{Value, json}; +use std::path::PathBuf; + +/// The two animated formats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Apng, + Webp, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Apng => "animated PNG", + Kind::Webp => "animated WebP", + } + } +} + +/// Largest animation made (frames × pixels), as for GIF: time stays bounded. +pub const MAX_ANIM_PIXELS: u64 = 600 * 1280 * 720; +/// WebP canvases and frames are at most 16384 px per side. +pub const MAX_WEBP_EDGE: u32 = 16_384; +/// Pixels rendered at once (a batch of frames), so memory stays bounded at any size. +const BATCH_PIXELS: u64 = 32 * 1024 * 1024; +/// Most plays a loop count says (both formats store it in 16 bits for WebP's sake). +pub const MAX_PLAYS: u32 = anicraft_doc::publish::MAX_PLAYS; +/// Longest WebP frame duration (24 bits of milliseconds). +const MAX_WEBP_MS: u64 = 0xFF_FFFF; + +/// A rectangle of the canvas, in pixels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub w: u32, + pub h: u32, +} + +/// One frame, compressed: the region it covers, whether it blends over what is there (else it +/// replaces it), and its image data (PNG `IDAT` data, or a whole `VP8L` chunk). +struct Encoded { + rect: Rect, + over: bool, + data: Vec, +} + +/// The frame rate as a fraction `p / q` frames per second: 24 → 24/1, 29.97 → 2997/100, +/// 23.976 → 2997/125. Rates no small fraction matches are taken to a thousandth. +pub fn fps_ratio(fps: f32) -> (u64, u64) { + let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 24.0 }; + for q in 1..=1001u64 { + let p = (fps * q as f64).round(); + if p >= 1.0 && (p / q as f64 - fps).abs() <= fps * 1e-6 { + return (p as u64, q); + } + } + let p = ((fps * 1000.0).round() as u64).max(1); + let g = gcd(p, 1000); + (p / g, 1000 / g) +} + +fn gcd(mut a: u64, mut b: u64) -> u64 { + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +/// When frame `t` (from the first exported) starts, in whole milliseconds, rounded from the +/// exact time at `p / q` fps. +pub fn start_ms(t: u64, (p, q): (u64, u64)) -> u64 { + let p = u128::from(p.max(1)); + ((2 * u128::from(t) * 1000 * u128::from(q) + p) / (2 * p)) as u64 +} + +/// The APNG delays (numerator, denominator in seconds) of a frame shown from frame `start` for +/// `count` frames: one exact fraction, or more when it is longer than one `fcTL` holds. +pub fn apng_delays(start: u64, count: u64, (p, q): (u64, u64)) -> Vec<(u16, u16)> { + let mut out = Vec::new(); + if let Ok(den) = u16::try_from(p) { + // `count` frames last count·q/p s; pieces of at most 65535/q frames always fit. + let most = (u64::from(u16::MAX) / q.max(1)).max(1); + let mut left = count; + while left > 0 { + let m = left.min(most); + let (num, g) = (m * q, gcd(m * q, p)); + out.push((u16::try_from(num / g).unwrap_or(u16::MAX), u16::try_from(u64::from(den) / g).unwrap_or(den))); + left -= m; + } + } else { + // A rate with a huge denominator: milliseconds, rounded from each frame's start. + let mut ms = start_ms(start + count, (p, q)) - start_ms(start, (p, q)); + while ms > 0 { + let m = ms.min(u64::from(u16::MAX)); + out.push((m as u16, 1000)); + ms -= m; + } + } + if out.is_empty() { + out.push((0, 1)); + } + out +} + +/// The WebP durations (milliseconds) of a frame shown from frame `start` for `count` frames: +/// one, or more when it is longer than one `ANMF` holds. +pub fn webp_durations(start: u64, count: u64, ratio: (u64, u64)) -> Vec { + let mut ms = start_ms(start + count, ratio).saturating_sub(start_ms(start, ratio)); + let mut out = Vec::new(); + loop { + let m = ms.min(MAX_WEBP_MS); + out.push(m as u32); + ms -= m; + if ms == 0 { + return out; + } + } +} + +/// The smallest rectangle holding every pixel where RGBA8 images `a` and `b` (`w` × `h`) differ, +/// or `None` when they are the same. +pub fn changed(a: &[u8], b: &[u8], w: u32, h: u32) -> Option { + let stride = w as usize * 4; + let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32); + for y in 0..h { + let at = y as usize * stride; + let (Some(ra), Some(rb)) = (a.get(at..at + stride), b.get(at..at + stride)) else { break }; + if ra == rb { + continue; + } + let (pa, pb) = (ra.as_chunks::<4>().0, rb.as_chunks::<4>().0); + let first = pa.iter().zip(pb).position(|(u, v)| u != v).unwrap_or(0) as u32; + let last = pa.iter().zip(pb).rposition(|(u, v)| u != v).unwrap_or(0) as u32; + x0 = x0.min(first); + x1 = x1.max(last); + y0 = y0.min(y); + y1 = y; + } + (y0 != u32::MAX).then(|| Rect { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 }) +} + +/// Rectangle `r` of RGBA8 image `px` (`w` wide). +fn crop(px: &[u8], w: u32, r: Rect) -> Vec { + let stride = w as usize * 4; + let mut out = Vec::with_capacity(r.w as usize * r.h as usize * 4); + for y in r.y..r.y + r.h { + let at = y as usize * stride + r.x as usize * 4; + if let Some(row) = px.get(at..at + r.w as usize * 4) { + out.extend_from_slice(row); + } + } + out +} + +/// What frame `cur` writes after frame `before` (none: it is the first, and covers the canvas): +/// the region, whether it blends over, and its pixels. +fn region(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> (Rect, bool, Vec) { + let full = Rect { x: 0, y: 0, w, h }; + let Some(before) = before else { return (full, false, cur.to_vec()) }; + let mut r = changed(before, cur, w, h).unwrap_or(full); + match kind { + Kind::Webp => { + // Frame offsets are stored halved: the region starts on an even pixel. + let (ex, ey) = (r.x & !1, r.y & !1); + r = Rect { x: ex, y: ey, w: r.w + (r.x - ex), h: r.h + (r.y - ey) }; + (r, false, crop(cur, w, r)) + } + Kind::Apng => { + let (old, new) = (crop(before, w, r), crop(cur, w, r)); + let (po, pn) = (old.as_chunks::<4>().0, new.as_chunks::<4>().0); + if po.iter().zip(pn).all(|(o, n)| o == n || n[3] == 255) { + // Every changed pixel is opaque: blend over, unchanged pixels transparent. + let mut px = Vec::with_capacity(new.len()); + for (o, n) in po.iter().zip(pn) { + px.extend_from_slice(if o == n { &[0, 0, 0, 0] } else { n }); + } + (r, true, px) + } else { + (r, false, new) + } + } + } +} + +/// A standalone PNG's image data: its `IDAT` chunks' contents, joined. +fn idat(png: &[u8]) -> Result> { + let mut out = Vec::new(); + let mut at = 8usize; + while let Some(head) = png.get(at..at + 8) { + let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize; + let data = png.get(at + 8..at + 8 + len).ok_or_else(|| EngineError::Format("the PNG encoder wrote a short chunk".into()))?; + if &head[4..8] == b"IDAT" { + out.extend_from_slice(data); + } + at += 12 + len; + } + Ok(out) +} + +/// A RIFF file's first chunk named `id`, whole (header, data and padding). +fn riff_chunk<'a>(riff: &'a [u8], id: &[u8; 4]) -> Option<&'a [u8]> { + let mut at = 12usize; + while let Some(head) = riff.get(at..at + 8) { + let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; + let whole = 8 + len + (len & 1); + if &head[0..4] == id { + return riff.get(at..at + whole).or_else(|| riff.get(at..at + 8 + len)); + } + at += whole; + } + None +} + +/// Compresses `px` (`w` × `h` RGBA8) as one frame's data. +fn compress(kind: Kind, px: &[u8], w: u32, h: u32) -> Result> { + let fail = |e: String| EngineError::Format(format!("{} frame: {e}", kind.name())); + match kind { + Kind::Apng => { + let mut buf = Vec::new(); + { + let mut enc = png::Encoder::new(&mut buf, w, h); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.set_adaptive_filter(png::AdaptiveFilterType::Adaptive); + enc.set_compression(png::Compression::Best); + let mut wr = enc.write_header().map_err(|e| fail(e.to_string()))?; + wr.write_image_data(px).map_err(|e| fail(e.to_string()))?; + } + idat(&buf) + } + Kind::Webp => { + if px.len() != w as usize * h as usize * 4 { + return Err(fail("the frame has the wrong size".into())); + } + let mut buf = Vec::new(); + image_webp::WebPEncoder::new(&mut buf).encode(px, w, h, image_webp::ColorType::Rgba8).map_err(|e| fail(e.to_string()))?; + riff_chunk(&buf, b"VP8L").map(<[u8]>::to_vec).ok_or_else(|| fail("the WebP encoder wrote no lossless image".into())) + } + } +} + +fn encode(kind: Kind, before: Option<&[u8]>, cur: &[u8], w: u32, h: u32) -> Result { + let (rect, over, px) = region(kind, before, cur, w, h); + Ok(Encoded { rect, over, data: compress(kind, &px, rect.w, rect.h)? }) +} + +/// A frame that changes nothing (one transparent pixel blended over the top-left corner): how +/// a delay too long for one frame header goes on. +fn still(kind: Kind) -> Result { + Ok(Encoded { rect: Rect { x: 0, y: 0, w: 1, h: 1 }, over: true, data: compress(kind, &[0, 0, 0, 0], 1, 1)? }) +} + +// ----- the files --------------------------------------------------------------------------- + +fn png_chunk(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { + let len = u32::try_from(data.len()).ok().filter(|l| *l < 1 << 31).ok_or_else(|| EngineError::Format("an animated PNG frame is too large".into()))?; + out.extend_from_slice(&len.to_be_bytes()); + let from = out.len(); + out.extend_from_slice(id); + out.extend_from_slice(data); + let crc = anicraft_xfl::zip::crc32(out.get(from..).unwrap_or(&[])); + out.extend_from_slice(&crc.to_be_bytes()); + Ok(()) +} + +/// The APNG file: frames with their delays (the first frame is the default image). +fn apng_file(w: u32, h: u32, plays: u32, frames: &[(&Encoded, (u16, u16))]) -> Result> { + let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = Vec::with_capacity(13); + ihdr.extend_from_slice(&w.to_be_bytes()); + ihdr.extend_from_slice(&h.to_be_bytes()); + ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA, deflate, adaptive filters, no interlace + png_chunk(&mut out, b"IHDR", &ihdr)?; + let count = u32::try_from(frames.len()).map_err(|_| EngineError::Format("too many frames".into()))?; + let mut actl = count.to_be_bytes().to_vec(); + actl.extend_from_slice(&plays.to_be_bytes()); + png_chunk(&mut out, b"acTL", &actl)?; + let mut seq = 0u32; + for (k, (f, (num, den))) in frames.iter().enumerate() { + let mut fctl = Vec::with_capacity(26); + for v in [seq, f.rect.w, f.rect.h, f.rect.x, f.rect.y] { + fctl.extend_from_slice(&v.to_be_bytes()); + } + fctl.extend_from_slice(&num.to_be_bytes()); + fctl.extend_from_slice(&den.to_be_bytes()); + fctl.extend_from_slice(&[0, u8::from(f.over)]); // dispose: none; blend: source or over + png_chunk(&mut out, b"fcTL", &fctl)?; + seq += 1; + if k == 0 { + png_chunk(&mut out, b"IDAT", &f.data)?; + } else { + let mut fdat = Vec::with_capacity(f.data.len() + 4); + fdat.extend_from_slice(&seq.to_be_bytes()); + fdat.extend_from_slice(&f.data); + png_chunk(&mut out, b"fdAT", &fdat)?; + seq += 1; + } + } + png_chunk(&mut out, b"IEND", &[])?; + Ok(out) +} + +fn le24(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()[..3]); +} + +fn riff_push(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<()> { + let len = u32::try_from(data.len()).map_err(|_| EngineError::Format("an animated WebP frame is too large".into()))?; + out.extend_from_slice(id); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(data); + if len & 1 == 1 { + out.push(0); + } + Ok(()) +} + +/// The animated WebP file: frames with their durations. `background` is the stage colour as +/// the `ANIM` background (RGBA), or transparent. +fn webp_file(w: u32, h: u32, plays: u32, alpha: bool, background: [u8; 4], frames: &[(&Encoded, u32)]) -> Result> { + let mut body = b"WEBP".to_vec(); + let mut vp8x = vec![if alpha { 0x10 | 0x02 } else { 0x02 }, 0, 0, 0]; + le24(&mut vp8x, w - 1); + le24(&mut vp8x, h - 1); + riff_push(&mut body, b"VP8X", &vp8x)?; + let [r, g, b, a] = background; + let mut anim = vec![b, g, r, a]; + anim.extend_from_slice(&u16::try_from(plays).unwrap_or(u16::MAX).to_le_bytes()); + riff_push(&mut body, b"ANIM", &anim)?; + for (f, ms) in frames { + let mut anmf = Vec::with_capacity(16 + f.data.len()); + le24(&mut anmf, f.rect.x / 2); + le24(&mut anmf, f.rect.y / 2); + le24(&mut anmf, f.rect.w - 1); + le24(&mut anmf, f.rect.h - 1); + le24(&mut anmf, *ms); + anmf.push(if f.over { 0 } else { 0x02 }); // blending: alpha-blend or replace; dispose: none + anmf.extend_from_slice(&f.data); + riff_push(&mut body, b"ANMF", &anmf)?; + } + let mut out = Vec::with_capacity(body.len() + 8); + riff_push(&mut out, b"RIFF", &body)?; + Ok(out) +} + +// ----- the command ------------------------------------------------------------------------- + +/// How many times it plays: `loop` true (or absent) forever (0), false once, or a count. +pub(crate) fn plays(p: &Value) -> Result { + match p.get("loop") { + None | Some(Value::Null) | Some(Value::Bool(true)) => Ok(0), + Some(Value::Bool(false)) => Ok(1), + Some(v) => v + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n <= MAX_PLAYS) + .ok_or_else(|| EngineError::Param(format!("param 'loop' must be true (forever), false (once) or how many times it plays (0 is forever, at most {MAX_PLAYS})"))), + } +} + +/// `file.export_apng` and `file.export_webp`. +pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + // The whole movie: every scene in order. + let last = s.doc.frame_count().saturating_sub(1); + let from = opt_u32(p, "from")?.unwrap_or(0).min(last); + let to = opt_u32(p, "to")?.unwrap_or(last).min(last); + if to < from { + return Err(EngineError::Param("'to' must not be before 'from'".into())); + } + let scale = crate::cmds_file::scale_param(p)?; + let plays = plays(p)?; + let background = opt_bool(p, "background")?.unwrap_or(false); + let mut view = View::stage(&s.doc, scale); + if !background { + view.background = None; + } + let (w, h) = (view.width.max(1), view.height.max(1)); + if kind == Kind::Webp && (w > MAX_WEBP_EDGE || h > MAX_WEBP_EDGE) { + return Err(EngineError::Param(format!("WebP frames are at most {MAX_WEBP_EDGE} px per side; lower 'scale'"))); + } + let n = u64::from(to - from) + 1; + if n * u64::from(w) * u64::from(h) > MAX_ANIM_PIXELS { + return Err(EngineError::Param(format!("that {} would be too large ({n} frames at {w}×{h}); lower 'scale' or the frame range", kind.name()))); + } + let doc = &s.doc; + let job = s.job.as_deref(); + let started = web_time::Instant::now(); + let batch = (BATCH_PIXELS / (u64::from(w) * u64::from(h))).clamp(2, 16) as usize; + // Each distinct frame: its first frame (from 0) and how many frames it shows for. + let mut shown: Vec<(u64, u64)> = Vec::new(); + let mut encoded: Vec = Vec::new(); + let mut prev: Option> = None; + let frames: Vec = (from..=to).collect(); + for (b, chunk) in frames.chunks(batch).enumerate() { + let images: Vec> = chunk + .par_iter() + .map(|&f| { + let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + crate::publish::tick(job, 1)?; + Ok(pm.to_rgba8()) + }) + .collect::>()?; + // A frame like the one before it only lengthens that frame's delay. + let mut fresh: Vec = Vec::new(); + let mut last_seen: Option<&[u8]> = prev.as_deref(); + for (i, img) in images.iter().enumerate() { + match shown.last_mut() { + Some((_, count)) if last_seen == Some(img.as_slice()) => *count += 1, + _ => { + shown.push(((b * batch + i) as u64, 1)); + fresh.push(i); + } + } + last_seen = Some(img.as_slice()); + } + let made = (0..fresh.len()) + .into_par_iter() + .map(|k| { + let cur = fresh.get(k).and_then(|&i| images.get(i)).ok_or_else(|| EngineError::Format("lost a frame".into()))?; + let before = match k.checked_sub(1) { + None => prev.as_deref(), + Some(j) => fresh.get(j).and_then(|&i| images.get(i)).map(Vec::as_slice), + }; + encode(kind, before, cur, w, h) + }) + .collect::>>()?; + encoded.extend(made); + if let Some(&i) = fresh.last() { + prev = images.into_iter().nth(i); + } + } + let ratio = fps_ratio(doc.stage.fps); + let pad = still(kind)?; + let bytes = match kind { + Kind::Apng => { + let mut list: Vec<(&Encoded, (u16, u16))> = Vec::new(); + for (e, &(start, count)) in encoded.iter().zip(&shown) { + for (k, d) in apng_delays(start, count, ratio).into_iter().enumerate() { + list.push((if k == 0 { e } else { &pad }, d)); + } + } + apng_file(w, h, plays, &list)? + } + Kind::Webp => { + let mut list: Vec<(&Encoded, u32)> = Vec::new(); + for (e, &(start, count)) in encoded.iter().zip(&shown) { + for (k, d) in webp_durations(start, count, ratio).into_iter().enumerate() { + list.push((if k == 0 { e } else { &pad }, d)); + } + } + let padded = list.len() > encoded.len(); + let c = s.doc.stage.background.sanitized(); + let q = |v: f32| (v * 255.0).round() as u8; + let bg = if background { [q(c.r), q(c.g), q(c.b), 255] } else { [0; 4] }; + webp_file(w, h, plays, !background || padded, bg, &list)? + } + }; + crate::vfs::write(&path, &bytes)?; + Ok(json!({ + "written": path.display().to_string(), + "frames": n, + "stored_frames": encoded.len(), + "bytes": bytes.len(), + "width": w, + "height": h, + "loop": plays, + "ms": started.elapsed().as_millis() as u64, + })) +} + +#[cfg(test)] +#[path = "anim_tests.rs"] +mod tests; diff --git a/crates/engine/src/anim_tests.rs b/crates/engine/src/anim_tests.rs new file mode 100644 index 00000000..fcce90cd --- /dev/null +++ b/crates/engine/src/anim_tests.rs @@ -0,0 +1,347 @@ +use super::*; +use crate::Session; +use anicraft_doc::sample; +use serde_json::json; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn tmp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("anicraft-anim-{}-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// What the CPU renderer draws for movie frames `from..=to`, as straight RGBA8. +fn renders(doc: &anicraft_doc::Document, from: u32, to: u32, scale: f32, background: bool) -> Vec> { + let mut view = View::stage(doc, scale); + if !background { + view.background = None; + } + (from..=to).map(|f| render(&anicraft_doc::evaluate(doc, f), &view).unwrap().0.to_rgba8()).collect() +} + +/// An APNG decoded as a player shows it (the APNG specification's compositing): each frame's +/// canvas, its delay (num, den), its region and blend op, and the play count. +struct ApngFrame { + canvas: Vec, + delay: (u16, u16), + rect: Rect, + over: bool, +} + +struct Apng { + frames: Vec, + plays: u32, + size: (u32, u32), +} + +fn decode_apng(bytes: &[u8]) -> Apng { + let dec = png::Decoder::new(std::io::Cursor::new(bytes)); + let mut reader = dec.read_info().unwrap(); + let info = reader.info(); + let (w, h) = (info.width, info.height); + let actl = info.animation_control.expect("an acTL chunk"); + assert_eq!((info.color_type, info.bit_depth), (png::ColorType::Rgba, png::BitDepth::Eight)); + let mut canvas = vec![0u8; (w * h * 4) as usize]; + let mut frames = Vec::new(); + let mut buf = vec![0u8; reader.output_buffer_size()]; + for _ in 0..actl.num_frames { + let out = reader.next_frame(&mut buf).unwrap(); + let fc = *reader.info().frame_control().expect("an fcTL per frame"); + assert_eq!(fc.dispose_op, png::DisposeOp::None); + let over = fc.blend_op == png::BlendOp::Over; + let r = Rect { x: fc.x_offset, y: fc.y_offset, w: fc.width, h: fc.height }; + assert_eq!((out.width, out.height), (r.w, r.h)); + assert!(r.x + r.w <= w && r.y + r.h <= h); + for y in 0..r.h { + for x in 0..r.w { + let s = ((y * r.w + x) * 4) as usize; + let d = (((r.y + y) * w + r.x + x) * 4) as usize; + let src = &buf[s..s + 4]; + if over { + // Exact for the pixels the exporter blends: transparent or opaque. + assert!(src[3] == 0 || src[3] == 255, "an over-blended pixel is neither transparent nor opaque"); + if src[3] == 255 { + canvas[d..d + 4].copy_from_slice(src); + } + } else { + canvas[d..d + 4].copy_from_slice(src); + } + } + } + frames.push(ApngFrame { canvas: canvas.clone(), delay: (fc.delay_num, fc.delay_den), rect: r, over }); + } + Apng { frames, plays: actl.num_plays, size: (w, h) } +} + +/// The frames an APNG shows, one per movie frame at `ratio` fps (each delay is a whole number +/// of movie frames, exactly). +fn apng_movie(a: &Apng, (p, q): (u64, u64)) -> Vec> { + let mut out = Vec::new(); + for f in &a.frames { + let (num, den) = (u64::from(f.delay.0), u64::from(f.delay.1)); + // num/den s = k·q/p s + assert_eq!((num * p) % (den * q), 0, "a delay of {num}/{den} s is not a whole number of frames at {p}/{q} fps"); + for _ in 0..num * p / (den * q) { + out.push(f.canvas.clone()); + } + } + out +} + +/// A WebP decoded as a player shows it: each frame's canvas and duration. +/// An animated WebP's frames (canvas, milliseconds), loop count, size and whether it has alpha. +struct Webp { + frames: Vec<(Vec, u32)>, + looping: image_webp::LoopCount, + size: (u32, u32), + alpha: bool, +} + +fn decode_webp(bytes: &[u8]) -> Webp { + let mut dec = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).unwrap(); + assert!(dec.is_animated()); + let (w, h) = dec.dimensions(); + let alpha = dec.has_alpha(); + let mut buf = vec![0u8; dec.output_buffer_size().unwrap()]; + let mut frames = Vec::new(); + for _ in 0..dec.num_frames() { + let ms = dec.read_frame(&mut buf).unwrap(); + let rgba = if alpha { buf.clone() } else { buf.chunks(3).flat_map(|c| [c[0], c[1], c[2], 255]).collect() }; + frames.push((rgba, ms)); + } + Webp { frames, looping: dec.loop_count(), size: (w, h), alpha } +} + +/// The frames a WebP shows, one per movie frame: the frame showing when each starts. +fn webp_movie(frames: &[(Vec, u32)], n: u64, ratio: (u64, u64)) -> Vec> { + let mut starts = Vec::new(); + let mut t = 0u64; + for (_, ms) in frames { + starts.push(t); + t += u64::from(*ms); + } + assert_eq!(t, start_ms(n, ratio), "the running time is exact to the millisecond"); + (0..n).map(|f| { + let at = start_ms(f, ratio); + let i = starts.iter().rposition(|s| *s <= at).unwrap(); + frames[i].0.clone() + }) + .collect() +} + +fn same(got: &[Vec], want: &[Vec], what: &str) { + assert_eq!(got.len(), want.len(), "{what}: frame count"); + for (k, (g, w)) in got.iter().zip(want).enumerate() { + assert!(g == w, "{what}: frame {} differs from the CPU renderer", k + 1); + } +} + +/// A ball that holds still for 10 frames, jumps, and holds 6 more: 16 frames, 2 pictures. +fn holds() -> Session { + let mut s = Session::default(); + run(&mut s, "draw.ellipse", json!({"x": 40, "y": 40, "w": 60, "h": 60})); + 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.translate", json!({"dx": 200, "dy": 30})); + run(&mut s, "timeline.goto", json!({"frame": 15})); + run(&mut s, "timeline.insert_frame", json!({})); + assert_eq!(s.frame_count(), 16); + s +} + +#[test] +fn frame_rates_are_exact_fractions() { + assert_eq!(fps_ratio(24.0), (24, 1)); + assert_eq!(fps_ratio(29.97), (2997, 100)); + assert_eq!(fps_ratio(23.976), (2997, 125)); + assert_eq!(fps_ratio(12.5), (25, 2)); + assert_eq!(fps_ratio(f32::NAN), (24, 1)); + assert_eq!(fps_ratio(-3.0), (24, 1)); + // Millisecond starts round from the exact time, so the error never adds up. + assert_eq!(start_ms(24, (24, 1)), 1000); + assert_eq!(start_ms(1, (30, 1)), 33); + assert_eq!(start_ms(2, (30, 1)), 67); + assert_eq!(start_ms(2997, (2997, 100)), 100_000); + assert_eq!(webp_durations(0, 3, (30, 1)), vec![100]); + let total: u32 = (0..30).flat_map(|i| webp_durations(i, 1, (30, 1))).sum(); + assert_eq!(total, 1000); + // APNG delays are fractions of the frame rate, reduced. + assert_eq!(apng_delays(0, 1, (24, 1)), vec![(1, 24)]); + assert_eq!(apng_delays(0, 6, (24, 1)), vec![(1, 4)]); + assert_eq!(apng_delays(5, 2, (2997, 100)), vec![(200, 2997)]); + // Longer than one fcTL holds: more pieces, adding up exactly. + let long = apng_delays(0, 200_000, (2997, 100)); + assert!(long.len() > 1); + let frames: u64 = long.iter().map(|&(n, d)| u64::from(n) * 2997 / (u64::from(d) * 100)).sum(); + assert_eq!(frames, 200_000); + // A rate with a huge denominator falls back to milliseconds, still adding up. + let odd = (100_003, 1000); + let ms: u64 = apng_delays(0, 1000, odd).iter().map(|&(n, d)| { + assert_eq!(d, 1000); + u64::from(n) + }).sum(); + assert_eq!(ms, start_ms(1000, odd)); + let hours = webp_durations(0, 100_000, (1, 1)); + assert_eq!(hours.iter().map(|&m| u64::from(m)).sum::(), 100_000_000); + assert!(hours.iter().all(|&m| u64::from(m) <= MAX_WEBP_MS) && hours.len() > 1); +} + +#[test] +fn the_changed_rectangle_is_tight() { + let (w, h) = (8u32, 6u32); + let a = vec![0u8; (w * h * 4) as usize]; + assert_eq!(changed(&a, &a, w, h), None); + let mut b = a.clone(); + b[((2 * w + 3) * 4 + 1) as usize] = 9; // (3, 2) + b[((4 * w + 6) * 4 + 3) as usize] = 9; // (6, 4) + assert_eq!(changed(&a, &b, w, h), Some(Rect { x: 3, y: 2, w: 4, h: 3 })); + // WebP regions start on even pixels; APNG's stay tight. + let (r, over, px) = region(Kind::Webp, Some(&a), &b, w, h); + assert_eq!((r, over, px.len()), (Rect { x: 2, y: 2, w: 5, h: 3 }, false, 5 * 3 * 4)); + let (r, over, _) = region(Kind::Apng, Some(&a), &b, w, h); + assert_eq!((r, over), (Rect { x: 3, y: 2, w: 4, h: 3 }, false), "semi-transparent changes replace"); + let mut c = a.clone(); + c[((2 * w + 3) * 4) as usize..((2 * w + 3) * 4 + 4) as usize].copy_from_slice(&[1, 2, 3, 255]); + let (r, over, px) = region(Kind::Apng, Some(&a), &c, w, h); + assert_eq!((r, over, px), (Rect { x: 3, y: 2, w: 1, h: 1 }, true, vec![1, 2, 3, 255]), "opaque changes blend over"); +} + +#[test] +fn apng_frames_match_the_renderer_exactly() { + let dir = tmp("apng"); + let mut s = Session::new(sample::demo()); + for background in [false, true] { + let path = dir.join(format!("walk-{background}.png")); + let v = run(&mut s, "file.export_apng", json!({"path": path.display().to_string(), "scale": 0.25, "to": 23, "background": background})); + assert_eq!(v["frames"], 24); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(v["bytes"], bytes.len()); + let a = decode_apng(&bytes); + assert_eq!(a.plays, 0, "loops forever by default"); + let want = renders(&s.doc, 0, 23, 0.25, background); + assert_eq!(a.size, (320, 180)); + same(&apng_movie(&a, fps_ratio(s.doc.stage.fps)), &want, "APNG"); + // Frames after the first cover only what changed. + assert!(a.frames.iter().skip(1).any(|f| f.rect.w * f.rect.h < 320 * 180), "dirty rectangles"); + if background { + assert!(a.frames.iter().skip(1).all(|f| f.over), "opaque frames blend over"); + } + // The default image is the first frame, and a plain PNG reader sees it. + let first = png::Decoder::new(std::io::Cursor::new(&bytes)).read_info().unwrap().info().frame_control.unwrap(); + assert_eq!((first.width, first.height, first.x_offset, first.y_offset), (320, 180, 0, 0)); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn webp_frames_match_the_renderer_exactly() { + let dir = tmp("webp"); + let mut s = Session::new(sample::demo()); + for background in [false, true] { + let path = dir.join(format!("walk-{background}.webp")); + let v = run(&mut s, "file.export_webp", json!({"path": path.display().to_string(), "scale": 0.25, "from": 4, "to": 27, "background": background})); + assert_eq!(v["frames"], 24); + let bytes = std::fs::read(&path).unwrap(); + assert!(bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP"); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len()); + let Webp { frames, looping, size, alpha } = decode_webp(&bytes); + assert_eq!((size, alpha), ((320, 180), !background)); + assert_eq!(looping, image_webp::LoopCount::Forever); + let want = renders(&s.doc, 4, 27, 0.25, background); + same(&webp_movie(&frames, 24, fps_ratio(s.doc.stage.fps)), &want, "WebP"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn identical_frames_merge_into_longer_delays() { + let dir = tmp("holds"); + let mut s = holds(); + let ratio = fps_ratio(s.doc.stage.fps); + let want = renders(&s.doc, 0, 15, 1.0, false); + let png = dir.join("holds.png"); + let v = run(&mut s, "file.export_apng", json!({"path": png.display().to_string(), "loop": 3})); + assert_eq!((v["frames"].as_u64(), v["stored_frames"].as_u64(), v["loop"].as_u64()), (Some(16), Some(2), Some(3))); + let a = decode_apng(&std::fs::read(&png).unwrap()); + assert_eq!(a.frames.len(), 2); + assert_eq!(a.plays, 3); + let fps = s.doc.stage.fps; + assert_eq!(a.frames[0].delay, apng_delays(0, 10, ratio)[0], "10 frames at {fps} fps"); + same(&apng_movie(&a, ratio), &want, "held APNG"); + let webp = dir.join("holds.webp"); + let v = run(&mut s, "file.export_webp", json!({"path": webp.display().to_string(), "loop": false})); + assert_eq!(v["stored_frames"], 2); + let Webp { frames, looping, .. } = decode_webp(&std::fs::read(&webp).unwrap()); + assert_eq!(frames.len(), 2); + assert_eq!(looping, image_webp::LoopCount::Times(std::num::NonZeroU16::new(1).unwrap())); + same(&webp_movie(&frames, 16, ratio), &want, "held WebP"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_params_are_refused_and_overwrites_confirm() { + let dir = tmp("params"); + let mut s = holds(); + let at = |n: &str| dir.join(n).display().to_string(); + for id in ["file.export_apng", "file.export_webp"] { + for bad in [json!({"loop": -1}), json!({"loop": 70_000}), json!({"loop": "yes"}), json!({"scale": 0}), json!({"from": 9, "to": 2}), json!({"background": 3})] { + let mut p = bad.clone(); + p["path"] = json!(at("x.out")); + assert!(s.execute(id, &p).is_err(), "{id} {bad}"); + } + assert!(s.execute(id, &json!({"path": at("big.out"), "scale": 8})).is_err(), "{id}: too large"); + assert!(!Path::new(&at("x.out")).exists() && !Path::new(&at("big.out")).exists()); + let path = at(&format!("once-{id}.out")); + run(&mut s, id, json!({"path": path, "to": 1})); + assert!(s.execute(id, &json!({"path": path})).is_err(), "{id}: replacing a file asks first"); + run(&mut s, id, json!({"path": path, "confirm": true})); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_cancelled_publish_stops_the_export() { + let mut s = Session::new(sample::demo()); + let job = std::sync::Arc::new(crate::publish::Control::default()); + job.cancel(); + s.job = Some(job); + let dir = tmp("cancel"); + let path = dir.join("walk.webp"); + let e = s.execute("file.export_webp", &json!({"path": path.display().to_string(), "scale": 0.1})).unwrap_err(); + assert!(matches!(e, EngineError::Cancelled), "{e}"); + assert!(!path.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +#[ignore = "a measurement: cargo test --release -p anicraft-engine anim::tests::sizes -- --ignored --nocapture"] +fn sizes() { + // docs/performance.md › Animated exports: the sample, every frame, at full size and half. + let dir = tmp("sizes"); + for scale in [1.0, 0.5] { + let mut s = Session::new(sample::demo()); + let mut row = format!("scale {scale}:"); + for (id, ext, extra) in [ + ("file.export_gif", "gif", json!({})), + ("file.export_apng", "png", json!({"background": true})), + ("file.export_apng", "png", json!({})), + ("file.export_webp", "webp", json!({"background": true})), + ("file.export_webp", "webp", json!({})), + ] { + let mut p = extra.clone(); + p["path"] = json!(dir.join(format!("walk-{scale}-{}.{ext}", extra.as_object().map_or(0, |o| o.len()))).display().to_string()); + p["scale"] = json!(scale); + p["confirm"] = json!(true); + let t = std::time::Instant::now(); + let v = run(&mut s, id, p); + row.push_str(&format!(" | {id} {extra}: {} KB, {} stored, {} ms", v["bytes"].as_u64().unwrap() / 1024, v["stored_frames"], t.elapsed().as_millis())); + } + println!("{row}"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index a3b900d1..7aa7fa93 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -74,6 +74,24 @@ pub fn specs() -> Vec { mutates: false, run: export_gif, }, + CommandSpec { + id: "file.export_apng", + label: "Export Animated PNG…", + menu: "File/Export", + shortcut: None, + params: "{path (.png or .apng), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Apng), + }, + CommandSpec { + id: "file.export_webp", + label: "Export Animated WebP…", + menu: "File/Export", + shortcut: None, + params: "{path (.webp; lossless), from?, to? (movie frames: every scene in order), scale?, loop? (true (default): forever; false: once; or how many times it plays), background? (default false: transparent), confirm?}", + mutates: false, + run: |s, p| crate::anim::export(s, p, crate::anim::Kind::Webp), + }, CommandSpec { id: "file.export_lottie", label: "Export Lottie Animation…", @@ -207,7 +225,7 @@ fn save(s: &mut Session, p: &Value) -> Result { Ok(json!({"saved": path.display().to_string()})) } -fn scale_param(p: &Value) -> Result { +pub(crate) fn scale_param(p: &Value) -> Result { match opt_f32(p, "scale")? { None => Ok(1.0), Some(v) if v > 0.0 && v <= 8.0 => Ok(v), diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index bf666f85..cee96054 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -109,7 +109,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { let same = s.path.as_deref() == Some(path); (!same && crate::vfs::exists(path)).then(|| overwrite(path, "Saving")) } - "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { + "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => { let path = Path::new(p.get("path").and_then(Value::as_str)?); crate::vfs::exists(path).then(|| overwrite(path, "Exporting")) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 83438b1a..0a5ca065 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! JSON params, so headless and interactive behaviour cannot drift apart. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod anim; mod cmds_actions; mod cmds_bone; pub mod cmds_brush; diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index d8ae7d26..90335a60 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -136,6 +136,8 @@ fn plugins_cannot_reach_files_history_the_clipboard_or_other_plugins() { let forbidden = [ save.as_str(), r#"{"op":"command","id":"file.export_png","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_apng","params":{"path":"x.png"}}"#, + r#"{"op":"command","id":"file.export_webp","params":{"path":"x.webp"}}"#, r#"{"op":"command","id":"plugin.run","params":{"id":"org.test.sneaky"}}"#, r#"{"op":"command","id":"plugin.remove","params":{"id":"org.test.sneaky","confirm":true}}"#, r#"{"op":"command","id":"edit.undo"}"#, diff --git a/crates/engine/src/publish.rs b/crates/engine/src/publish.rs index 857f232b..64d83afc 100644 --- a/crates/engine/src/publish.rs +++ b/crates/engine/src/publish.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { label: "Publish Settings", menu: "", shortcut: None, - params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", + params: "{profile? (a whole profile, as publish.settings_get returns it), format? (html | gif | apng | webp | video | lottie | sprite_sheet | png_sequence | png | svg | audio), enabled?, output? (relative to the document's folder; {name} is the document's name), and that format's options: title, sound, fit (html); from, to, scale, loop (gif); from, to, scale, loop (true, false or how many times it plays; 0: forever), background (apng, webp); from, to, scale, audio (video); from, to, background (lottie); from, to, scale, columns, padding, background (sprite_sheet); from, to, scale (png_sequence); frame, scale (png); frame (svg); from, to, rate, bits (audio). from/to/frame are movie frames, null for the movie's ends}", mutates: true, run: settings_set, }, @@ -205,6 +205,17 @@ pub fn plan(doc: &Document, path: Option<&Path>, only: Option<&[PublishFormat]>) p.insert("loop".into(), json!(g.looping)); ("file.export_gif", n, vec![out]) } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background, command) = match f { + PublishFormat::Apng => (prof.apng.range, prof.apng.scale, prof.apng.plays, prof.apng.background, "file.export_apng"), + _ => (prof.webp.range, prof.webp.scale, prof.webp.plays, prof.webp.background, "file.export_webp"), + }; + let n = range_params(&mut p, range, last); + p.insert("scale".into(), json!(scale)); + p.insert("loop".into(), json!(plays)); + p.insert("background".into(), json!(background)); + (command, n, vec![out]) + } PublishFormat::Video => { let v = &prof.video; let n = range_params(&mut p, v.range, last); @@ -310,7 +321,7 @@ pub fn formats_param(p: &Value) -> Result>> { Some(Value::Array(list)) => list .iter() .take(64) - .map(|v| v.as_str().and_then(PublishFormat::from_key).ok_or_else(|| EngineError::Param(format!("unknown format {v} (html, gif, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))) + .map(|v| v.as_str().and_then(PublishFormat::from_key).ok_or_else(|| EngineError::Param(format!("unknown format {v} (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))) .collect::>>() .map(Some), Some(_) => Err(EngineError::Param("param 'formats' must be a list of format names".into())), @@ -549,6 +560,7 @@ fn option_keys(f: PublishFormat) -> &'static [&'static str] { match f { PublishFormat::Html => &["title", "sound", "fit"], PublishFormat::Gif => &["from", "to", "scale", "loop"], + PublishFormat::Apng | PublishFormat::Webp => &["from", "to", "scale", "loop", "background"], PublishFormat::Video => &["from", "to", "scale", "audio"], PublishFormat::Lottie => &["from", "to", "background"], PublishFormat::SpriteSheet => &["from", "to", "scale", "columns", "padding", "background"], @@ -633,6 +645,18 @@ fn apply(prof: &mut PublishProfile, f: PublishFormat, p: &Value) -> Result<()> { set_scale(&mut g.scale, p)?; set_bool(&mut g.looping, p, "loop")?; } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background) = match f { + PublishFormat::Apng => (&mut prof.apng.range, &mut prof.apng.scale, &mut prof.apng.plays, &mut prof.apng.background), + _ => (&mut prof.webp.range, &mut prof.webp.scale, &mut prof.webp.plays, &mut prof.webp.background), + }; + set_range(range, p)?; + set_scale(scale, p)?; + if p.get("loop").is_some() { + *plays = crate::anim::plays(p)?; + } + set_bool(background, p, "background")?; + } PublishFormat::Video => { let v = &mut prof.video; set_range(&mut v.range, p)?; @@ -704,7 +728,7 @@ fn settings_set(s: &mut Session, p: &Value) -> Result { }; match opt_str(p, "format")? { Some(k) => { - let f = PublishFormat::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown format '{k}' (html, gif, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))?; + let f = PublishFormat::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown format '{k}' (html, gif, apng, webp, video, lottie, sprite_sheet, png_sequence, png, svg or audio)")))?; apply(&mut prof, f, p)?; } None if p.get("profile").is_none_or(Value::is_null) && p.as_object().is_some_and(|o| o.keys().any(|k| k != "confirm" && k != "profile")) => { diff --git a/crates/engine/src/web_tests.rs b/crates/engine/src/web_tests.rs index d496a0f5..2d04c05c 100644 --- a/crates/engine/src/web_tests.rs +++ b/crates/engine/src/web_tests.rs @@ -57,6 +57,8 @@ fn exports_come_back_as_files() { ("file.export_png", json!({"path": "frame.png"})), ("file.export_svg", json!({"path": "frame.svg"})), ("file.export_gif", json!({"path": "movie.gif", "to": 3})), + ("file.export_apng", json!({"path": "movie.png", "to": 3})), + ("file.export_webp", json!({"path": "movie.webp", "to": 3})), ("file.export_lottie", json!({"path": "movie.json"})), ("file.export_html", json!({"path": "movie.html"})), ("file.export_audio", json!({"path": "track.wav"})), @@ -67,12 +69,16 @@ fn exports_come_back_as_files() { s.execute("file.export_png_sequence", &json!({"dir": "frames", "to": 2})).unwrap(); let out = vfs::take_written(); let n = names(&out); - for want in ["frame.png", "frame.svg", "movie.gif", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { + for want in ["frame.png", "frame.svg", "movie.gif", "movie.png", "movie.webp", "movie.json", "movie.html", "track.wav", "sheet.png", "sheet.json", "frames/frame_00001.png", "frames/frame_00003.png"] { assert!(n.iter().any(|x| x == want), "{want} missing from {n:?}"); } assert!(out.iter().all(|(_, b)| !b.is_empty())); let png = &out.iter().find(|(p, _)| p == Path::new("frame.png")).unwrap().1; assert!(png.starts_with(b"\x89PNG")); + let apng = &out.iter().find(|(p, _)| p == Path::new("movie.png")).unwrap().1; + assert!(apng.starts_with(b"\x89PNG") && apng.windows(4).any(|w| w == b"acTL"), "an animated PNG"); + let webp = &out.iter().find(|(p, _)| p == Path::new("movie.webp")).unwrap().1; + assert!(webp.starts_with(b"RIFF") && webp.windows(4).any(|w| w == b"ANMF"), "an animated WebP"); let wav = &out.iter().find(|(p, _)| p == Path::new("track.wav")).unwrap().1; assert!(wav.starts_with(b"RIFF") && !n.iter().any(|x| x.ends_with(".tmp"))); let err = s.execute("file.export_video", &json!({"path": "movie.webm"})).unwrap_err().to_string(); diff --git a/docs/adr/0062-test-movie-window-and-macos-document-opening.md b/docs/adr/0062-test-movie-window-and-macos-document-opening.md index d1b7ab3f..e5e0c19a 100644 --- a/docs/adr/0062-test-movie-window-and-macos-document-opening.md +++ b/docs/adr/0062-test-movie-window-and-macos-document-opening.md @@ -121,9 +121,9 @@ association, `Exec=anicraft %f` in the desktop entry). Nothing had tested that. * The editor redraws while the movie plays (point 1). This is measured and recorded in the PR. * One small third-party crate holds `unsafe` macOS code on our behalf. It is a supply-chain risk, mitigated by an exact pin and a full read, and listed for the lead. -* The workspace's `rust-version` is 1.90, but `fmv-macos-events` declares 1.95. The macOS build - therefore needs Rust 1.95 or newer (CI and releases use the current stable). Windows and Linux - don't build the crate. +* `fmv-macos-events` declares `rust-version = 1.95`, so the workspace's declared minimum moved + from 1.90 to **1.95** (`Cargo.toml`, `docs/requirements.md`) on every platform, one MSRV for + all. CI and releases already build with the current stable. ## Only a Mac can verify diff --git a/docs/adr/0063-animated-png-and-webp-export.md b/docs/adr/0063-animated-png-and-webp-export.md new file mode 100644 index 00000000..a13330aa --- /dev/null +++ b/docs/adr/0063-animated-png-and-webp-export.md @@ -0,0 +1,96 @@ +# ADR 0063: Animated PNG and animated WebP export + +* Status: accepted (2026-11-11) +* Relates to: ADR 0002 (CPU renderer as the oracle), ADR 0004 (destructive actions), ADR 0017 + (plug-in policy), ADR 0036 (web build), ADR 0040 (interface languages), ADR 0060 (Publish + Settings) + +## Context + +AniCraft exports animated GIF, video through the user's ffmpeg, Lottie, an HTML canvas page and +sprite sheets. GIF has 256 colours per frame and 1-bit transparency: gradients band and soft +edges get a hard fringe over any background other than the one they were made on. Animators who +post to the web and chat apps want **full colour with real alpha** in one file that plays +everywhere without a player. Two formats do that and are supported by every current browser: +**APNG** (animated PNG) and **animated WebP**. + +The specifications are public: the APNG specification (Mozilla, now part of the W3C PNG +Third Edition) and Google's WebP container and lossless bitstream specifications. Both +formats are royalty-free. + +## Decision + +1. **Two commands, one pipeline.** `file.export_apng` and `file.export_webp` (File › Export › + Export Animated PNG… / Export Animated WebP…) take `path`, `from`, `to` (movie frames, every + scene in order, as GIF), `scale`, `loop` (`true` = forever, the default; `false` = once; or + how many times it plays, 0 = forever, at most 65535) and `background` (default **off: + transparent**, the reason to pick these formats; on: the stage colour). Both live in + `crates/engine/src/anim.rs`. +2. **Rendering is GIF's.** Frames render on the CPU renderer (the oracle) in parallel, a batch + at a time. The batch is sized so that at most 32 Mpx are held at once (2 to 16 frames), so + memory stays bounded at any size. Publish's `Control` counts frames and cancels between + them. The size limit is GIF's (600 frames of 1280 × 720 in pixels). WebP frames are also + limited to 16384 px per side. +3. **Repeated frames are stored once.** A frame byte-identical to the one before it lengthens + that frame's delay and adds nothing else. Holds, which animators use all the time, cost + nothing. +4. **Only what changed is stored.** Each later frame is cut down to the smallest rectangle + holding every pixel that differs from the frame before it. Neither format disposes frames + (dispose op *none*): each frame is drawn over the one before it. + * **APNG**: when every changed pixel in the rectangle is opaque, the frame **blends over** + the canvas and its unchanged pixels are written fully transparent. They compress to + almost nothing, and a transparent pixel blended over leaves the canvas exactly as it was. + Otherwise (semi-transparent edges in a transparent export) the rectangle **replaces** + what is there (blend op *source*). Both are exact. + * **WebP**: rectangles start on even pixels (the format halves offsets) and always replace + (no blending). The decoders' blend (libwebp's, and `image-webp`'s port of it) rounds an + opaque pixel's channels down by one, so blending would not be lossless. +5. **Timing is exact.** The frame rate is taken as a fraction p/q (24 → 24/1, 29.97 → + 2997/100, 23.976 → 2997/125). + * APNG delays are fractions: a frame shown for k frames has a delay of k·q/p s, reduced. + 2 frames at 29.97 fps is 200/2997 s, never a rounded 67 ms. + * WebP durations are whole milliseconds. Each one is the difference between the rounded + starts of this frame and the next, so the rounding never adds up and the running time + is exact to the millisecond. + * A delay longer than one frame header holds (65535/q frames in APNG, 4.6 hours in WebP) + continues as extra frames that change nothing: one transparent pixel blended over the + corner. Timing is never cut short. +6. **Frames compress in parallel; we write the container.** Each frame's rectangle is + compressed on the thread pool as an image of its own: a PNG from the `png` crate (already + in the tree; RGBA8, adaptive filters, its best compression), or a lossless WebP from + `image-webp` (MIT OR Apache-2.0, pure Rust, `#![forbid(unsafe_code)]`). The file is then + put together in order by hand from the published chunk layouts. For APNG that is `IHDR`, + `acTL`, `fcTL` with `IDAT` for the first frame (so a plain PNG viewer shows the first + frame), `fcTL` with `fdAT` for the rest, and `IEND`. For WebP it is `RIFF`/`WEBP`, `VP8X`, + `ANIM` and one `ANMF` per frame wrapping that frame's `VP8L` chunk. + * The `png` crate can write APNG itself, but only from raw pixels, one frame after another + on one thread. Compression is most of the cost, so we use the crate for each frame's + data and write the chunks (a length, a type, the data and a CRC-32) ourselves. + `image-webp` has no animation encoder at all. +7. **Lossless WebP only, for now.** There is no permissively licensed, pure-Rust lossy (VP8) + WebP encoder on crates.io: `image-webp` encodes lossless only, and the `webp` and + `libwebp-sys` crates bind the C library, which this project does not build. The + commands therefore have no `quality` parameter yet. When a permissive pure-Rust VP8 + encoder exists, `quality` (lossy, with an `ALPH` chunk for alpha) slots into step 6 + without changing anything else. +8. **Everywhere GIF is.** File › Export lists both. Publish Settings (ADR 0060) gains + *Animated PNG* (`{name}_animated.png`, since `{name}.png` belongs to the PNG image; `.png` + or `.apng`) and *Animated WebP* (`{name}.webp`), each with frames, scale, loop forever or a + play count, and stage colour as background. Older profiles open with both off. Replacing a + file confirms (ADR 0004). Plug-ins can't call either command, like every `file.*` + command (ADR 0017). The CLI has `apng` and `webp` beside `gif`. In the web build the file + becomes a download, as GIF's does (ADR 0036). + +## Consequences + +* Every frame of both formats decodes back to the CPU renderer's pixels exactly (tests decode + with the `png` crate's APNG reader, compositing by the APNG rules, and `image-webp`'s + animation decoder), along with the delays, play counts, repeated-frame merging and the + rectangles. +* On the sample (48 frames, 1280 × 720) APNG is 2019 KB and WebP 1829 KB, against GIF's + 1464 KB of 256-colour frames; at half size they are 741 KB, 666 KB and 660 KB. Both are + faster to make than GIF: 0.18 s and 0.13 s against 0.42 s (docs/performance.md). +* Some players clamp very short delays. 240 fps is about 4 ms a frame, and a few browsers + slow down frames shorter than 10–20 ms, as they do for GIF. This is not worked around. +* `image-webp` is a new dependency. Its licence (MIT OR Apache-2.0) and its dependencies + (`byteorder-lite`, `quick-error`) are already allowed by `deny.toml`. diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index ae2c0751..b48b98f6 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -62,7 +62,12 @@ pinned with `=`. It registers AppKit's open-documents and quit Apple Event handl AniCraft's own code stays free of `unsafe`. It was read in full before it was added: about 170 lines, no network or file access. Its `objc2` 0.6, `objc2-app-kit` 0.3 and `objc2-foundation` 0.3 (MIT, Zlib OR Apache-2.0 OR MIT) were already in the tree through wgpu. No new licence. It -declares `rust-version = 1.95`, so the macOS build needs that toolchain or newer. +declares `rust-version = 1.95`, so the workspace's minimum Rust is now 1.95. +**Audit note:** the crate is built only for `cfg(target_os = "macos")`, is pinned with `=0.1.0` +(the checksum is in `Cargo.lock`), and its licence is checked by `cargo deny`. It registers +two Apple Event handlers (open documents, quit) and an observer, and returns paths through a +main-thread inbox. It has no network, file or process access, and no build script. Read any +new version in full before it comes in. ### Find and Replace (2026-11-11, ADR 0058) @@ -104,6 +109,15 @@ page's player in it. Nothing of it is in the app or the CLI. No new licence. The JavaScript is our own code (`crates/render/src/html/`), MIT OR Apache-2.0 like the rest, and uses no npm packages. +### Animated PNG and WebP (2026-11-11, ADR 0063) + +New crate, from crates.io: `image-webp` 0.2 (lossless WebP encoding and decoding in pure Rust, +`#![forbid(unsafe_code)]`, MIT OR Apache-2.0). Its dependencies, `byteorder-lite` (Unlicense +OR MIT) and `quick-error` (MIT OR Apache-2.0), were already in the tree. No new licence. APNG frames use the `png` crate already in +the tree. There is no lossy WebP yet: the only lossy encoders on crates.io bind the C libwebp +library, which this project does not build. APNG and WebP are both royalty-free (see the +codec table). + ### Sound (2026-11-09, ADR 0020) The audio slice adds, all permissive and from crates.io: `lewton` (Ogg Vorbis decoding, MIT OR diff --git a/docs/performance.md b/docs/performance.md index 8063616f..0e2f6ab6 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -230,6 +230,24 @@ frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14. table in step. The GPU stage's are `BUDGETS` in `crates/gpu/examples/gpu_bench.rs` (`--check`; the CLI has no GPU). +## Animated PNG and WebP (2026-11-11, ADR 0063) + +The sample, all 48 frames, release build, Windows 10, 32 threads +(`cargo test --release -p anicraft-engine anim::tests::sizes -- --ignored --nocapture`). +Times include rendering every frame. + +| Export | 1280 × 720 | Time | 640 × 360 | Time | +|---|---|---|---|---| +| Animated GIF (256 colours, 1-bit alpha) | 1464 KB | 421 ms | 660 KB | 110 ms | +| Animated PNG | 2019 KB | 183 ms | 741 KB | 52 ms | +| Animated WebP, lossless | 1829 KB | 130 ms | 666 KB | 36 ms | + +The sample moves something in every frame, so all 48 frames are stored. Its sky is a full-stage +shape, so the transparent and stage-colour exports come out the same size. Compressing each +APNG frame at the `png` crate's best level instead of its default brought the file from 3387 KB +to 2019 KB for 25 % more time. The frames compress in parallel, which is why both formats are +faster than GIF, whose LZW coding runs on one thread. + ## Sound (2026-11-09, ADR 0020) Release build, Windows 10, one 120-second 48 kHz stereo sine, through `anicraft-cli run` diff --git a/docs/requirements.md b/docs/requirements.md index e94ae252..1ab07e9a 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -62,7 +62,7 @@ Priority: **P0** = M0–M2 skeleton must have, **P1** = parity core, **P2** = lo | Concern | Choice | Why | |---|---|---| -| Language | Rust 2024 edition, stable toolchain (MSRV 1.90) | Memory safety, fearless parallelism, one language for engine, UI, CLI and web. | +| Language | Rust 2024 edition, stable toolchain (MSRV 1.95, ADR 0062: the macOS Apple Event crate needs it; CI builds with current stable) | Memory safety, fearless parallelism, one language for engine, UI, CLI and web. | | UI | **egui / eframe 0.36** (wgpu backend) | Immediate mode keeps the UI a thin function of state, matches PhotoCraft, runs native and on the web. | | Rendering (oracle) | In-house CPU rasterizer: Bézier flattening + signed-area coverage accumulation, rayon row parallelism | Deterministic, testable, headless; the reference every other renderer is compared against. | | Rendering (interactive, M3) | wgpu compute/fragment renderer (sparse strips or tile binning in the style of public Vello/Pathfinder papers), compared per-pixel against the CPU oracle | Fast stage at high zoom and 4K; GPU and CPU must agree within a tolerance in tests. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 4ff66a27..7e40d68e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,9 +14,9 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click 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`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. | | Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `totalFrames`, `currentLabel`, `mouseX/Y`, `name`), `removeEventListener`, `Event.ENTER_FRAME`, `KeyboardEvent.KEY_DOWN/KEY_UP` on the stage with `e.keyCode`, `e.target`/`e.currentTarget`, seeded `Math.random()`; keyboard in Test Movie and the HTML page, `control.test_movie` key events and `seed`; `player.js` mirrors the evaluator, checked step by step in Boa. Not yet: ActionScript `switch`, `for in`, arrays and objects, string methods, closures, event bubbling, mouse listeners on the stage, ActionScript 1.0/2.0, scripts on instances, filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. **Buttons, complete** (ADR 0057): a button open in place names its frames Up, Over, Down and Hit on the timeline and shows its Hit area translucent over the other states; Test Movie has **Show hit areas**; sounds on its frames play as its state changes. | -| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | +| Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. Not yet: sounds kept only in Animate's own data format (undocumented; reported), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. Not yet: exact drop positions on the desktop (winit 0.30 gives none during a drag; a drop waits for the first pointer move, else lands mid-view), SVG into the Library, drops on the timeline, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). No per-character styles or motion tweens from XFL yet; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. Not yet: exact drop positions on the desktop (winit 0.30 gives none during a drag; a drop waits for the first pointer move, else lands mid-view), SVG into the Library, drops on the timeline, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | @@ -36,7 +36,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~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: camera colour effects beyond tint, 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); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | +| **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); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~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, text on a path and input fields 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. | | **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 kinds later); ~~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); 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: shape armatures, spring, joint translation, runtime armatures, XFL armature import, editing member instances' properties in place); ~~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; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, 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); ~~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; asset warp; graph-based easing presets library. | diff --git a/src/a11y.rs b/src/a11y.rs index 53c33459..b57c09fa 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -361,7 +361,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "start", "drop", "droplibrary", "testmovie", "testmovieinside"] { + for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062): its controls, named in that window. diff --git a/src/app.rs b/src/app.rs index b5901470..3240f079 100644 --- a/src/app.rs +++ b/src/app.rs @@ -865,6 +865,17 @@ impl App { crate::publish_panel::publish_now(self); } } + Some("publishanim") => { + // Publish Settings with the animated PNG on (ADR 0063): played three times, + // transparent, the WebP on beside it. + let dir = std::env::temp_dir().join("anicraft-publish-shot"); + let _ = std::fs::create_dir_all(&dir); + self.s.path = Some(dir.join("walk.anicraft")); + self.run("publish.settings_set", json!({"format": "apng", "enabled": true, "loop": 3})); + self.run("publish.settings_set", json!({"format": "webp", "enabled": true})); + self.publish.selected = anicraft_engine::doc::publish::PublishFormat::Apng; + crate::publish_panel::open(self); + } Some("explorer") => { // The Movie Explorer tab (ADR 0058), its first rows open: scene, layers, keyframes // and the instances on them, opening into their symbols. @@ -1718,6 +1729,16 @@ impl App { let done = trn!("Exported {path} ({n} frame, {kb} KB): open it in a web browser.", "Exported {path} ({n} frames, {kb} KB): open it in a web browser.", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), kb = kb); self.status_ok(format!("{done}{report}")); } + "file.export_apng" | "file.export_webp" => { + // Frames identical to the one before are kept once, with a longer delay. + let kb = v["bytes"].as_u64().unwrap_or(0).div_ceil(1024); + let n = v["frames"].as_u64().unwrap_or(0); + let stored = v["stored_frames"].as_u64().unwrap_or(n); + let path = v["written"].as_str().unwrap_or(""); + let done = trn!("Exported {path} ({n} frame, {kb} KB).", "Exported {path} ({n} frames, {kb} KB).", n, path = path, kb = kb); + let held = if stored < n { format!(" {}", tr!("Frames that repeat the one before are stored once, shown longer.")) } else { String::new() }; + self.status_ok(format!("{done}{held}")); + } "file.export_lottie" => { let report = v["report"].as_str().filter(|r| !r.is_empty()).map(|r| format!(" {r}")).unwrap_or_default(); let done = trn!("Exported {path} ({n} frame, {layers} layers).", "Exported {path} ({n} frames, {layers} layers).", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), layers = v["layers"]); @@ -1854,6 +1875,8 @@ impl App { "file.export_png" => Some((tr_noop!("Export frame as PNG"), "path", format!("frame_{:04}.png", self.s.frame + 1))), "file.export_png_sequence" => Some((tr_noop!("Export PNG sequence to folder"), "dir", "frames".to_string())), "file.export_gif" => Some((tr_noop!("Export animated GIF"), "path", "animation.gif".to_string())), + "file.export_apng" => Some((tr_noop!("Export animated PNG (full colour, transparent)"), "path", "animation.png".to_string())), + "file.export_webp" => Some((tr_noop!("Export animated WebP (lossless, transparent)"), "path", "animation.webp".to_string())), "file.export_svg" => Some((tr_noop!("Export frame as SVG"), "path", format!("frame_{:04}.svg", self.s.frame + 1))), "file.export_sprite_sheet" => Some((tr_noop!("Export sprite sheet (PNG + JSON frame map)"), "path", "sprites.png".to_string())), "file.export_video" => Some((tr_noop!("Export video (.webm or .mp4, made with your ffmpeg)"), "path", "animation.webm".to_string())), diff --git a/src/dialogs.rs b/src/dialogs.rs index 3599a32b..254c7d50 100644 --- a/src/dialogs.rs +++ b/src/dialogs.rs @@ -201,7 +201,7 @@ impl Entry { /// Commands the palette can run without extra input (everything optional, or prompted). fn runnable(c: &CommandSpec) -> bool { - if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") { + if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_apng" | "file.export_webp" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") { return true; } let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}'); diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index bae09541..46e51a72 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -587,7 +587,7 @@ fn every_control_can_be_used_in_the_pseudo_locale() { a.run("element.set_color_effect", serde_json::json!({"style": style})); })); } - for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "start", "testmovie", "testmovieinside"] { + for panel in ["sound", "camera", "motion", "motionpins", "actions", "script", "prefs", "envelope", "onionmenu", "editmultiple", "edittransform", "onionsymbol", "find", "explorer", "publish", "publishreport", "publishanim", "start", "testmovie", "testmovieinside"] { found.extend(click_everything(panel, |a, _| a.open_panel(Some(panel)))); } // Test Movie in a window of its own (ADR 0062; egui stands in for the window system here). @@ -612,12 +612,12 @@ fn status_lines_for_every_result_are_translated() { "kb": 12, "layers": 2, "masks": 1, "elements": 3, "report": "Imported walk.fla.", "copied": 2, "cut": 2, "pasted": 2, "removed": 2, "cleared": 2, "original_newer": true, "sounds": 1, "name": "beat", "sound": 1, "log": ["Did it."], "installed": [{"name": "Tint", "version": "1.0"}], "failed": ["bad.wasm: not a plug-in"], "replaced": "Tint 0.9", - "plugin": {"name": "Tint", "version": "1.0"}, "undone": "Move", "redone": "Move", + "plugin": {"name": "Tint", "version": "1.0"}, "undone": "Move", "redone": "Move", "bytes": 4096, "stored_frames": 2, }); let bare = json!({}); let ids = [ "file.new", "file.open", "file.recover", "file.discard_recovery", "file.save", "file.save_as", "file.import", "file.import_to_library", - "file.export_audio", "file.export_sprite_sheet", "file.export_html", "file.export_lottie", "file.export_png", "file.export_gif", + "file.export_audio", "file.export_sprite_sheet", "file.export_html", "file.export_lottie", "file.export_png", "file.export_gif", "file.export_apng", "file.export_webp", "sound.delete", "edit.undo", "edit.redo", "edit.delete", "layer.delete", "draw.erase_all", "scene.delete", "scene.new", "timeline.clear_keyframe", "timeline.copy_frames", "timeline.cut_frames", "timeline.paste_frames", "timeline.remove_frame", "plugin.run", "plugin.install", "plugin.remove", "plugin.reload", diff --git a/src/main.rs b/src/main.rs index f5e7b30f..3522b968 100644 --- a/src/main.rs +++ b/src/main.rs @@ -212,7 +212,7 @@ fn parse_args(args: impl IntoIterator) -> Result { /// `--help` (the console's text, in English). #[cfg(not(target_arch = "wasm32"))] // i18n-exempt: the --help console text -const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|button|testhits|exporthtml|publish|publishreport|sound|envelope|library|librarymenu|colour]\n\ +const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|nineslice|nineslicedit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\ diff --git a/src/platform.rs b/src/platform.rs index 55160935..4ea33149 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -445,6 +445,8 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) { match cmd { "file.export_png" => (tr_noop!("PNG image"), &["png"]), "file.export_gif" => (tr_noop!("Animated GIF"), &["gif"]), + "file.export_apng" => (tr_noop!("Animated PNG"), &["png", "apng"]), + "file.export_webp" => (tr_noop!("Animated WebP"), &["webp"]), "file.export_svg" => (tr_noop!("SVG image"), &["svg"]), "file.export_lottie" => (tr_noop!("Lottie animation"), &["json"]), "file.export_html" => (tr_noop!("Web page"), &["html", "htm"]), diff --git a/src/publish_panel.rs b/src/publish_panel.rs index ebb86db3..8be65d31 100644 --- a/src/publish_panel.rs +++ b/src/publish_panel.rs @@ -81,6 +81,8 @@ pub fn label(f: PublishFormat) -> &'static str { crate::i18n::t(match f { PublishFormat::Html => tr_noop!("HTML canvas"), PublishFormat::Gif => tr_noop!("Animated GIF"), + PublishFormat::Apng => tr_noop!("Animated PNG"), + PublishFormat::Webp => tr_noop!("Animated WebP"), PublishFormat::Video => tr_noop!("Video"), PublishFormat::Lottie => tr_noop!("Lottie"), PublishFormat::SpriteSheet => tr_noop!("Sprite sheet"), @@ -96,6 +98,8 @@ fn about(f: PublishFormat) -> &'static str { crate::i18n::t(match f { PublishFormat::Html => tr_noop!("One web page that plays the movie, buttons and actions included."), PublishFormat::Gif => tr_noop!("An animated GIF, with exact frame timing."), + PublishFormat::Apng => tr_noop!("An animated PNG: full colour and real transparency, for the web and chat apps."), + PublishFormat::Webp => tr_noop!("An animated WebP, lossless: full colour and real transparency, smaller than PNG."), PublishFormat::Video => tr_noop!("WebM or MP4 video, made with your ffmpeg (ffmpeg.org)."), PublishFormat::Lottie => tr_noop!("A Lottie animation (JSON) for web and apps."), PublishFormat::SpriteSheet => tr_noop!("Frames in a grid on one PNG, with a JSON frame map beside it."), @@ -402,6 +406,23 @@ fn scale_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, scale: f32) { }); } +/// How many times it plays: forever, or a count. +fn plays_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, plays: u32) { + let mut forever = plays == 0; + form_row(ui, FORM_LABEL_DIALOG, tr!("Playback"), |ui| { + if crate::theme::checkbox(ui, &mut forever, tr!("Loop forever")).on_hover_text(tr!("Off: it plays the number of times you set, then stops on the last frame")).changed() { + set(app, f, "loop", json!(if forever { 0 } else { 1 }), false); + } + if !forever { + let mut n = plays.max(1); + ui.label(text(Type::Label, tr!("Plays"))); + if ui.add(egui::DragValue::new(&mut n).range(1..=anicraft_engine::doc::publish::MAX_PLAYS).speed(0.1)).named(tr!("Plays")).changed() { + set(app, f, "loop", json!(n), true); + } + } + }); +} + /// Which movie frames: all of them, or from one to another (shown 1-based, as the timeline). fn range_row(app: &mut App, ui: &mut egui::Ui, f: PublishFormat, r: FrameRange) { let total = app.s.doc.frame_count(); @@ -467,6 +488,13 @@ fn options(app: &mut App, ui: &mut egui::Ui, f: PublishFormat) { scale_row(app, ui, f, p.gif.scale); check(app, ui, f, "loop", p.gif.looping, tr!("Loop"), tr!("Off: it plays once and stops on the last frame")); } + PublishFormat::Apng | PublishFormat::Webp => { + let (range, scale, plays, background) = if f == PublishFormat::Apng { (p.apng.range, p.apng.scale, p.apng.plays, p.apng.background) } else { (p.webp.range, p.webp.scale, p.webp.plays, p.webp.background) }; + range_row(app, ui, f, range); + scale_row(app, ui, f, scale); + plays_row(app, ui, f, plays); + check(app, ui, f, "background", background, tr!("Stage colour as background"), tr!("Off: transparent")); + } PublishFormat::Video => { range_row(app, ui, f, p.video.range); scale_row(app, ui, f, p.video.scale);